diff --git a/craftbot.py b/craftbot.py index 964c6b6f..edb381a1 100644 --- a/craftbot.py +++ b/craftbot.py @@ -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 @@ -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 diff --git a/run.py b/run.py index 212f8df9..54452cc1 100644 --- a/run.py +++ b/run.py @@ -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 @@ -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. @@ -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) diff --git a/tests/test_craftbot_service.py b/tests/test_craftbot_service.py index 895eb010..052f3a07 100644 --- a/tests/test_craftbot_service.py +++ b/tests/test_craftbot_service.py @@ -7,6 +7,10 @@ from pathlib import Path from types import SimpleNamespace +import time +import urllib.error +import urllib.request + import pytest import craftbot @@ -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") @@ -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'
' + + +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"Directory listing")) + + 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 diff --git a/tests/test_run_browser_readiness.py b/tests/test_run_browser_readiness.py new file mode 100644 index 00000000..99dd2bb2 --- /dev/null +++ b/tests/test_run_browser_readiness.py @@ -0,0 +1,209 @@ +"""Exercise the real browser startup sequence without bootstrapping an agent.""" + +import ast +import sys +import urllib.error +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from app import instance + +SOURCE = Path(__file__).resolve().parents[1] / "run.py" +FRONTEND_URL = "http://localhost:8925" +BACKEND_URL = "http://localhost:8926" + + +class _FakeClock: + def __init__(self): + self.now = 1000.0 + + def time(self): + return self.now + + def sleep(self, seconds): + self.now += seconds + + +class _Response: + def __init__(self, body=b'', status=200): + self.body = body + self.status = status + + def read(self, size): + return self.body[:size] + + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + +def _run_py(monkeypatch, outcomes): + calls = [] + + def open_url(url, timeout): + outcome = outcomes[min(len(calls), len(outcomes) - 1)] + calls.append(url) + if isinstance(outcome, Exception): + raise outcome + return outcome + + monkeypatch.setattr( + instance, "loopback_opener", lambda: SimpleNamespace(open=open_url) + ) + tree = ast.parse(SOURCE.read_text(encoding="utf-8")) + functions = [ + node + for node in tree.body + if isinstance(node, ast.FunctionDef) + and node.name in ("wait_for_frontend_silent", "wait_for_backend_silent") + ] + namespace = { + "time": _FakeClock(), + "_instance": instance, + "_local_url": lambda port: f"http://localhost:{port}", + "FRONTEND_PORT": 8925, + "BACKEND_PORT": 8926, + } + exec( + compile(ast.Module(body=functions, type_ignores=[]), str(SOURCE), "exec"), + namespace, + ) + return SimpleNamespace(**namespace), calls + + +@pytest.mark.parametrize("code", [400, 403, 404, 500, 503]) +def test_frontend_http_error_is_not_ready(monkeypatch, code): + error = urllib.error.HTTPError(FRONTEND_URL, code, "error", None, None) + run, calls = _run_py(monkeypatch, [error]) + assert run.wait_for_frontend_silent(2) is False + assert set(calls) == {FRONTEND_URL} + + +@pytest.mark.parametrize( + "response", [_Response(b"Directory listing"), _Response(status=302)] +) +def test_frontend_requires_success_and_react_root(monkeypatch, response): + run, _ = _run_py(monkeypatch, [response]) + assert run.wait_for_frontend_silent(2) is False + + +def test_frontend_retries_until_ui_is_served(monkeypatch): + run, calls = _run_py(monkeypatch, [urllib.error.URLError("refused"), _Response()]) + assert run.wait_for_frontend_silent(2) is True + assert calls == [FRONTEND_URL, FRONTEND_URL] + + +@pytest.mark.parametrize("code, expected", [(404, True), (500, False)]) +def test_backend_response_semantics_are_preserved(monkeypatch, code, expected): + error = urllib.error.HTTPError(BACKEND_URL, code, "error", None, None) + run, calls = _run_py(monkeypatch, [error]) + assert run.wait_for_backend_silent(2) is expected + assert set(calls) == {BACKEND_URL} + + +def _startup_sequence(): + tree = ast.parse(SOURCE.read_text(encoding="utf-8")) + for node in ast.walk(tree): + if not isinstance(node, ast.Try) or not node.body: + continue + first = node.body[0] + if isinstance(first, ast.Assign) and any( + getattr(target, "id", None) == "frontend_ready" for target in first.targets + ): + return ast.Module(body=node.body, type_ignores=[]) + raise AssertionError("Browser startup sequence not found") + + +def _run_startup( + frontend_results, *, no_open_browser=False, frontend_alive=True, agent_state="ready" +): + events = [] + results = iter(frontend_results) + + def frontend_wait(timeout): + ready = next(results) + events.append(("frontend", ready)) + return ready + + def fail_agent(*args): + raise SystemExit(1) + + namespace = { + "wait_for_frontend_silent": frontend_wait, + "_wait_for_agent_ready": lambda proc: ( + events.append(("agent", agent_state)) or agent_state + ), + "_wait_for_backend_port": lambda proc: "ready", + "_fail_agent_exited": fail_agent, + "_adopt_port_listeners": lambda *ports: events.append(("adopt", ports)), + "frontend_process": SimpleNamespace(poll=lambda: None if frontend_alive else 1), + "agent_process": SimpleNamespace(wait=lambda: events.append(("wait", True))), + "_instance": SimpleNamespace( + write_ui=lambda *ports: events.append(("publish", ports)) + ), + "print_ready_banner": lambda url: events.append(("banner", url)), + "webbrowser": SimpleNamespace(open=lambda url: events.append(("open", url))), + "time": _FakeClock(), + "sys": sys, + "FRONTEND_PORT": 8925, + "BACKEND_PORT": 8926, + "FRONTEND_URL": FRONTEND_URL, + "BIND_HOST": "localhost", + "no_open_browser": no_open_browser, + "use_conda": False, + "env_name": None, + } + exec(compile(_startup_sequence(), str(SOURCE), "exec"), namespace) + return events + + +def test_frontend_not_ready_does_not_publish_announce_or_open(capsys): + events = _run_startup([False, False]) + assert not [event for event in events if event[0] in ("publish", "banner", "open")] + assert all(8925 not in ports for kind, ports in events if kind == "adopt") + assert "not responding" in capsys.readouterr().out + + +def test_ready_frontend_publishes_dynamic_ports_and_opens(): + events = _run_startup([True]) + assert ("publish", (8925, 8926)) in events + assert ("banner", FRONTEND_URL) in events + assert ("open", FRONTEND_URL) in events + assert [event for event in events if event[0] == "frontend"] == [("frontend", True)] + + +def test_no_open_browser_still_announces_ready_ui(): + events = _run_startup([True], no_open_browser=True) + assert ("banner", FRONTEND_URL) in events + assert not [event for event in events if event[0] == "open"] + + +def test_frontend_crash_does_not_announce_success(): + with pytest.raises(SystemExit): + _run_startup([True], frontend_alive=False) + + +def test_agent_crash_does_not_announce_success(): + with pytest.raises(SystemExit): + _run_startup([True], agent_state="exited") + + +def test_frontend_that_loads_during_agent_startup_is_rechecked(): + events = _run_startup([False, True]) + assert events.index(("frontend", False)) < events.index(("agent", "ready")) + assert events.index(("agent", "ready")) < events.index(("frontend", True)) + assert ("adopt", (8925, 8926)) in events + assert ("publish", (8925, 8926)) in events + assert ("open", FRONTEND_URL) in events + + +def test_frontend_still_down_after_agent_startup_is_rechecked_without_announcement(): + events = _run_startup([False, False]) + assert [event for event in events if event[0] == "frontend"] == [ + ("frontend", False) + ] * 2 + assert not [event for event in events if event[0] in ("publish", "banner", "open")]