Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions craftbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -552,6 +552,43 @@ def _current_url(args: Optional[List[str]] = None) -> str:
return _frontend_url(args)


#: How long cmd_start probes the browser UI after run.py reports readiness.
#: The UI should already answer; this absorbs a slow first response.
FRONTEND_READY_TIMEOUT_S = 30

#: Present in the UI's index.html (dev and built). A 200 without it is not
#: the UI — e.g. the directory listing of a dist/ that has no index.html.
_FRONTEND_ROOT_MARKER = b'id="root"'


def _frontend_serving(url: str) -> bool:
"""True only when `url` answers with the CraftBot UI itself.

The agent readiness marker says nothing about the frontend, and a server
that answers is not necessarily one that can serve the page: a 404 is
exactly what the user saw when the URL was shown too early. The opener
raises on every 4xx/5xx, so any HTTP error counts as not ready.
"""
try:
with _instance.loopback_opener().open(url, timeout=2) as resp:
return 200 <= resp.status < 300 and _FRONTEND_ROOT_MARKER in resp.read(
65536
)
except Exception:
return False


def _wait_for_frontend(url: str, timeout: float) -> bool:
"""Poll `url` until it serves the UI. Returns False on timeout."""
deadline = time.time() + timeout
while True:
if _frontend_serving(url):
return True
if time.time() >= deadline:
return False
time.sleep(0.5)


def _is_running(pid: int) -> bool:
"""Return True if a process with the given PID is currently alive."""
return _helpers.process_start_time(pid) is not None
Expand Down Expand Up @@ -815,6 +852,14 @@ def cmd_start(extra_args: List[str]) -> bool:
# No web UI and no desktop icon: the client is `craftbot.py tui`.
print(f" {DIM}░░{RESET} {WHITE}Open it with: python craftbot.py tui{RESET}")
return True
print(f" {DIM}░░ Waiting for the browser interface...{RESET}", flush=True)
if not _wait_for_frontend(browser_url, FRONTEND_READY_TIMEOUT_S):
print(
f" {RED}✗{RESET} {WHITE}The browser interface is not responding"
f" at {browser_url}{RESET}"
)
print(f" {DIM}Check progress: {sys.executable} craftbot.py logs{RESET}")
return True
print(f" {DIM}░░{RESET} {ORANGE}{browser_url}{RESET}")

# Create a desktop shortcut so the user can reopen the browser anytime
Expand Down
53 changes: 37 additions & 16 deletions run.py
Original file line number Diff line number Diff line change
Expand Up @@ -1068,11 +1068,20 @@ def wait_for_backend_silent(timeout: int = 60) -> bool:


def wait_for_frontend_silent(timeout: int = 30) -> bool:
"""Wait for the frontend server to be ready (silent)."""
"""Wait for a successful response containing the frontend's React root."""
start = time.time()
while time.time() - start < timeout:
if _instance.http_answers(_local_url(FRONTEND_PORT)):
return True
try:
# Probe the local listener directly, bypassing corporate proxies.
with _instance.loopback_opener().open(
_local_url(FRONTEND_PORT), timeout=2
) as response:
if 200 <= response.status < 300 and b'id="root"' in response.read(
65536
):
return True
except Exception:
pass
time.sleep(0.5)
return False

Expand Down Expand Up @@ -2139,6 +2148,11 @@ def _patched_init(self, *args, **kwargs):
if _wait_for_backend_port(agent_process) == "exited":
_fail_agent_exited(agent_process, use_conda, env_name)

# The frontend may have finished loading during agent startup.
# Recheck before publishing readiness and adopting its listener.
if not frontend_ready:
frontend_ready = wait_for_frontend_silent(30)

# Record the listeners into the owned-process ledger: a port that
# answered is a process we spawned, and recording it is what lets
# the next run stop it if this one is killed.
Expand All @@ -2156,22 +2170,29 @@ def _patched_init(self, *args, **kwargs):
print(" Try running: cd app/ui_layer/browser/frontend && npm run dev")
sys.exit(1)

# The UI answers: tell craftbot.py, the launcher and the desktop
# shortcut where it is (the ports may not be the defaults).
try:
_instance.write_ui(FRONTEND_PORT, BACKEND_PORT)
except OSError as e:
print(f"Warning: could not write {_instance.UI_FILE}: {e}")
print_ready_banner(FRONTEND_URL)
if BIND_HOST not in ("localhost", "127.0.0.1", "::1", "[::1]"):
if not frontend_ready:
print(
f" Listening on {BIND_HOST} (ports {FRONTEND_PORT} and "
f"{BACKEND_PORT}). Open {FRONTEND_URL} on this machine, or "
"the same ports where they are published.\n",
f"\nWarning: the browser interface is not responding at {FRONTEND_URL}",
flush=True,
)
if not no_open_browser:
webbrowser.open(FRONTEND_URL)
print(" Check the error messages above, then reload the page")
else:
# The UI answers: tell craftbot.py, the launcher and the desktop
# shortcut where it is (the ports may not be the defaults).
try:
_instance.write_ui(FRONTEND_PORT, BACKEND_PORT)
except OSError as e:
print(f"Warning: could not write {_instance.UI_FILE}: {e}")
print_ready_banner(FRONTEND_URL)
if BIND_HOST not in ("localhost", "127.0.0.1", "::1", "[::1]"):
print(
f" Listening on {BIND_HOST} (ports {FRONTEND_PORT} and "
f"{BACKEND_PORT}). Open {FRONTEND_URL} on this machine, or "
"the same ports where they are published.\n",
flush=True,
)
if not no_open_browser:
webbrowser.open(FRONTEND_URL)

# Wait for the agent to finish (keeps script running). Updates
# are handled by the external updater script (scripts/updater.bat)
Expand Down
200 changes: 200 additions & 0 deletions tests/test_craftbot_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@
from pathlib import Path
from types import SimpleNamespace

import time
import urllib.error
import urllib.request

import pytest

import craftbot
Expand Down Expand Up @@ -71,6 +75,7 @@ def service(tmp_path, monkeypatch):
ready marker, no real port sweep (it must never reach a CraftBot that is
running on this machine), and recorders for the shortcut and browser."""
events = []
monkeypatch.setattr(craftbot, "_frontend_serving", lambda url: True)
pid_file = tmp_path / "craftbot.pid"
log_file = tmp_path / "craftbot.log"
log_file.write_text("", encoding="utf-8")
Expand Down Expand Up @@ -449,3 +454,198 @@ def fake_run(cmd, **kwargs):
saved = json.loads((tmp_path / "service-env.json").read_text(encoding="utf-8"))
assert saved["HTTPS_PROXY"] == "http://proxy.corp:3128"
assert saved["PIP_INDEX_URL"] == "https://mirror.corp/simple"


# ─── Browser interface readiness (#488) ───────────────────────────────────────

_UI_HTML = b'<!DOCTYPE html><html><body><div id="root"></div></body></html>'


class _FakeResponse:
def __init__(self, body, status=200):
self.body = body
self.status = status

def read(self, n=-1):
return self.body

def __enter__(self):
return self

def __exit__(self, *exc):
return False


def _http_error(code):
return urllib.error.HTTPError("http://localhost:7925", code, "err", None, None)


def _fake_urlopen(monkeypatch, *outcomes):
"""Patch urlopen to play `outcomes` in order (the last one repeats)."""
calls = []

def fake(url, timeout=None):
outcome = outcomes[min(len(calls), len(outcomes) - 1)]
calls.append(url)
if isinstance(outcome, Exception):
raise outcome
return outcome

monkeypatch.setattr(
craftbot._instance, "loopback_opener", lambda: SimpleNamespace(open=fake)
)
return calls


class _FakeClock:
"""Stands in for craftbot.time: sleeping advances time instantly."""

def __init__(self):
self.now = 1000.0
self.sleeps = []

def time(self):
return self.now

def sleep(self, seconds):
self.sleeps.append(seconds)
self.now += seconds

def __getattr__(self, name):
return getattr(time, name) # strftime etc. stay real


@pytest.mark.parametrize("code", [404, 403, 500, 503])
def test_frontend_error_response_is_not_ready(monkeypatch, code):
_fake_urlopen(monkeypatch, _http_error(code))

assert craftbot._frontend_serving("http://localhost:7925") is False


def test_frontend_200_without_ui_is_not_ready(monkeypatch):
# e.g. the directory listing of a dist/ with no index.html
_fake_urlopen(monkeypatch, _FakeResponse(b"<html>Directory listing</html>"))

assert craftbot._frontend_serving("http://localhost:7925") is False


def test_frontend_serving_ui_is_ready(monkeypatch):
_fake_urlopen(monkeypatch, _FakeResponse(_UI_HTML))

assert craftbot._frontend_serving("http://localhost:7925") is True


def test_wait_for_frontend_retries_through_startup_failures(monkeypatch):
clock = _FakeClock()
monkeypatch.setattr(craftbot, "time", clock)
calls = _fake_urlopen(
monkeypatch,
urllib.error.URLError("connection refused"),
_http_error(404),
_FakeResponse(_UI_HTML),
)

assert craftbot._wait_for_frontend("http://localhost:7925", timeout=30) is True
assert len(calls) == 3


def test_wait_for_frontend_gives_up_at_the_deadline(monkeypatch):
clock = _FakeClock()
monkeypatch.setattr(craftbot, "time", clock)
calls = _fake_urlopen(monkeypatch, _http_error(404))

assert craftbot._wait_for_frontend("http://localhost:7925", timeout=5) is False
assert sum(clock.sleeps) <= 5
assert len(calls) == len(clock.sleeps) + 1


def _start_with_running_child(tmp_path, monkeypatch, agent_ready=True):
"""cmd_start against a child that boots; returns the browser-open log."""
opened = []
monkeypatch.setattr(craftbot, "PID_FILE", str(tmp_path / "craftbot.pid"))
monkeypatch.setattr(craftbot, "LOG_FILE", str(tmp_path / "craftbot.log"))
monkeypatch.setattr(craftbot, "RUN_SCRIPT", str(tmp_path / "run.py"))
monkeypatch.setattr(craftbot, "cmd_stop", lambda quiet=False, args=None: False)
monkeypatch.setattr(craftbot, "_clear_agent_ready", lambda: None)
monkeypatch.setattr(
craftbot, "_create_desktop_shortcut_windows", lambda args=None: None
)
monkeypatch.setattr(craftbot, "_create_desktop_shortcut_unix", lambda args: None)
monkeypatch.setattr(
craftbot,
"_wait_until_ready",
lambda proc, offset, timeout: "ready" if agent_ready else "timeout",
)
monkeypatch.setattr(craftbot, "_owned_pid", lambda: None)
monkeypatch.setattr(craftbot, "_open_browser_detached", opened.append)

def fake_popen(cmd, **kwargs):
# The child announces itself, so the early-exit check returns at once.
kwargs["stdout"].write(f"{craftbot.CRAFTBOT_READY_MARKER}\n")
kwargs["stdout"].flush()
return _FakeProcess(alive_polls=10**6)

monkeypatch.setattr(craftbot.subprocess, "Popen", fake_popen)
return opened


def test_start_does_not_show_url_while_frontend_returns_404(
tmp_path, monkeypatch, capsys
):
opened = _start_with_running_child(tmp_path, monkeypatch)
monkeypatch.setattr(craftbot, "time", _FakeClock())
_fake_urlopen(monkeypatch, _http_error(404))

# Still a successful start: the agent is running, only the UI is not.
assert craftbot.cmd_start([]) is True

output = capsys.readouterr().out
assert opened == []
assert "not responding at http://localhost:7925" in output
url_lines = [line for line in output.splitlines() if "localhost:7925" in line]
assert all("not responding" in line for line in url_lines)


def test_start_shows_url_only_after_frontend_serves_ui(tmp_path, monkeypatch, capsys):
opened = _start_with_running_child(tmp_path, monkeypatch)
probed = _fake_urlopen(monkeypatch, _FakeResponse(_UI_HTML))

assert craftbot.cmd_start(["--frontend-port", "8925"]) is True

output = capsys.readouterr().out
assert probed == ["http://localhost:8925"]
assert opened == ["http://localhost:8925"]
assert output.index("Waiting for the browser interface") < output.index(
"http://localhost:8925"
)


def test_start_agent_timeout_skips_frontend_probe_and_explains(
tmp_path, monkeypatch, capsys
):
opened = _start_with_running_child(tmp_path, monkeypatch, agent_ready=False)
probed = _fake_urlopen(monkeypatch, _FakeResponse(_UI_HTML))

assert craftbot.cmd_start([]) is True

output = capsys.readouterr().out
assert probed == []
assert opened == []
# The URL only appears as "open it once it finishes", never as ready.
url_lines = [line for line in output.splitlines() if "localhost:7925" in line]
assert url_lines and all("when it finishes" in line for line in url_lines)
assert "craftbot.py logs" in output


def test_start_without_browser_still_checks_the_announced_url(
tmp_path, monkeypatch, capsys
):
opened = _start_with_running_child(tmp_path, monkeypatch)
probed = _fake_urlopen(monkeypatch, _FakeResponse(_UI_HTML))

assert craftbot.cmd_start(["--no-open-browser"]) is True

output = capsys.readouterr().out
assert probed == ["http://localhost:7925"]
assert opened == []
assert "Waiting for the browser interface" in output
Loading
Loading