Skip to content

Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)

Python
24.6 KB
Raw Blame
"""Launchers start one shared platform owner when the local proxy is down."""

import os
import socket
import subprocess
import sys
import threading
from collections.abc import Mapping
from concurrent.futures import ThreadPoolExecutor
from http.client import RemoteDisconnected
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import MagicMock
from urllib.error import URLError

import pytest

from free_claude_code.cli.launchers import common
from free_claude_code.config.paths import (
    server_owner_lock_path,
    server_startup_lock_path,
)
from free_claude_code.core.interprocess_lock import InterprocessFileLock
from tests.cli.conftest import LaunchCapture
from tests.cli.test_launcher_workflow import launch

URL = "http://127.0.0.1:8182"


def _status(code: int) -> MagicMock:
    response = MagicMock()
    response.__enter__.return_value.status = code
    return response


def _healthy() -> MagicMock:
    return _status(200)


def _refused() -> URLError:
    return URLError(ConnectionRefusedError("refused"))


class FakeServer:
    def __init__(self, exit_code: int | None = None) -> None:
        self.exit_code = exit_code
        self.terminated = False

    def poll(self) -> int | None:
        return self.exit_code

    def terminate(self) -> None:
        self.terminated = True
        self.exit_code = 0

    def wait(self, timeout: float | None = None) -> int:
        assert self.exit_code is not None
        return self.exit_code


@pytest.fixture(autouse=True)
def _fast_polling(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr(common, "SERVER_STARTUP_POLL_SECONDS", 0)
    monkeypatch.setattr(common, "_desktop_owner_running", lambda: False)


@pytest.fixture
def clock(monkeypatch):
    clock = SimpleNamespace(now=0.0)

    def sleep(seconds):
        clock.now += seconds

    monkeypatch.setattr(
        common, "time", SimpleNamespace(monotonic=lambda: clock.now, sleep=sleep)
    )
    monkeypatch.setattr(common, "SERVER_STARTUP_POLL_SECONDS", 0.25)
    monkeypatch.setattr(common, "SERVER_STARTUP_TIMEOUT_SECONDS", 1.0)
    return clock


@pytest.fixture
def spawned(monkeypatch: pytest.MonkeyPatch) -> list[tuple[list[str], dict]]:
    calls: list[tuple[list[str], dict]] = []

    def popen(command: list[str], **kwargs: object) -> FakeServer:
        calls.append((command, kwargs))
        return FakeServer()

    monkeypatch.setattr(common.subprocess, "Popen", popen)
    return calls


def _responses(monkeypatch: pytest.MonkeyPatch, *responses: object) -> MagicMock:
    request = MagicMock(side_effect=list(responses))
    monkeypatch.setattr(common, "open_local_request", request)
    return request


def test_healthy_proxy_needs_no_server(monkeypatch, spawned) -> None:
    request = _responses(monkeypatch, _healthy())
    assert common.ensure_proxy_available(URL, env={}) is None
    assert request.call_count == 1
    assert spawned == []


def test_answering_but_unhealthy_proxy_is_not_restarted(monkeypatch, spawned) -> None:
    _responses(monkeypatch, _status(503))
    message = common.ensure_proxy_available(URL, env={})
    assert message is not None
    assert "returned HTTP 503" in message
    assert "Start it manually with:" in message
    assert spawned == []


def test_missing_server_is_started_once_and_awaited(
    monkeypatch, spawned, capsys: pytest.CaptureFixture[str]
) -> None:
    request = _responses(monkeypatch, _refused(), _refused(), _refused(), _healthy())
    env = {"PATH": "/usr/bin", "MODEL": "nvidia_nim/test"}

    assert common.ensure_proxy_available(URL, env=env) is None

    assert request.call_count == 4
    assert len(spawned) == 1
    command, kwargs = spawned[0]
    assert command == common.server_command()
    assert kwargs["env"] == env
    assert kwargs["env"] is not env
    assert kwargs["stdin"] is subprocess.DEVNULL
    assert kwargs["stdout"] not in (None, subprocess.DEVNULL)
    assert kwargs["stderr"] is subprocess.STDOUT
    if sys.platform == "win32":
        assert kwargs["creationflags"]
    else:
        assert kwargs["start_new_session"] is True
    assert "Starting Free Claude Code" in capsys.readouterr().err
    # The startup lock is released for the next launcher.
    lock = InterprocessFileLock(server_startup_lock_path())
    assert lock.acquire()
    lock.release()


def test_server_exit_before_ready_is_reported(monkeypatch) -> None:
    _responses(monkeypatch, _refused(), _refused(), _refused())
    monkeypatch.setattr(
        common.subprocess, "Popen", lambda *_a, **_k: FakeServer(exit_code=3)
    )
    message = common.ensure_proxy_available(URL, env={})
    assert message is not None
    assert "exited with code 3" in message
    assert "Start it manually with:" in message


def test_startup_wait_is_bounded(monkeypatch, spawned, clock) -> None:
    monkeypatch.setattr(common, "open_local_request", MagicMock(side_effect=_refused()))
    message = common.ensure_proxy_available(URL, env={})
    assert message is not None
    assert "did not become ready" in message
    assert len(spawned) == 1
    assert clock.now == 1.0


def test_timed_out_start_preserves_running_desktop(monkeypatch, clock) -> None:
    monkeypatch.setattr(common, "open_local_request", MagicMock(side_effect=_refused()))
    child = FakeServer()
    monkeypatch.setattr(common, "server_command", lambda: ["fcc-test"])
    monkeypatch.setattr(common.subprocess, "Popen", lambda *_a, **_k: child)

    message = common.ensure_proxy_available(URL, env={})

    assert message is not None and "did not become ready" in message
    assert not child.terminated


def test_unhealthy_started_server_remains_available_for_inspection(monkeypatch) -> None:
    _responses(monkeypatch, _refused(), _refused(), _status(503))
    child = FakeServer()
    monkeypatch.setattr(common, "server_command", lambda: ["fcc-test"])
    monkeypatch.setattr(common.subprocess, "Popen", lambda *_a, **_k: child)

    message = common.ensure_proxy_available(URL, env={})

    assert message is not None and "returned HTTP 503" in message
    assert not child.terminated


def test_ready_server_outlives_harness(monkeypatch) -> None:
    _responses(monkeypatch, _refused(), _refused(), _healthy())
    child = FakeServer()
    monkeypatch.setattr(common, "server_command", lambda: ["fcc-test"])
    monkeypatch.setattr(common.subprocess, "Popen", lambda *_a, **_k: child)

    assert common.ensure_proxy_available(URL, env={}) is None
    assert not child.terminated


def test_manual_desktop_startup_is_awaited_without_another_spawn(
    monkeypatch, spawned
) -> None:
    monkeypatch.setattr(common, "_desktop_owner_running", lambda: True)
    _responses(monkeypatch, _refused(), _refused(), _healthy())

    assert common.ensure_proxy_available(URL, env={}) is None
    assert spawned == []


def test_short_lived_duplicate_desktop_yields_to_manual_owner(monkeypatch) -> None:
    _responses(monkeypatch, _refused(), _refused(), _refused(), _healthy())
    ownership = iter((False, True))
    monkeypatch.setattr(common, "_desktop_owner_running", lambda: next(ownership))
    child = FakeServer(exit_code=0)
    monkeypatch.setattr(common, "server_command", lambda: ["fcc-test"])
    monkeypatch.setattr(common.subprocess, "Popen", lambda *_a, **_k: child)

    assert common.ensure_proxy_available(URL, env={}) is None
    assert not child.terminated


def test_other_port_desktop_owner_waits_without_spawning(
    monkeypatch, spawned, clock
) -> None:
    monkeypatch.setattr(common, "_desktop_owner_running", lambda: True)
    monkeypatch.setattr(common, "open_local_request", MagicMock(side_effect=_refused()))

    message = common.ensure_proxy_available(URL, env={})

    assert message is not None and "did not become ready" in message
    assert URL in message
    assert clock.now == 1.0
    assert spawned == []


def test_terminal_owner_at_other_port_waits_without_spawning(
    monkeypatch, spawned, clock
) -> None:
    owner = InterprocessFileLock(server_owner_lock_path())
    assert owner.acquire()
    try:
        monkeypatch.setattr(
            common, "open_local_request", MagicMock(side_effect=_refused())
        )
        message = common.ensure_proxy_available(URL, env={})
    finally:
        owner.release()

    assert message is not None and "did not become ready" in message
    assert "check its configured port" in message
    assert spawned == []


@pytest.mark.parametrize(
    "closed_connection",
    [
        ConnectionResetError("reset during restart"),
        ConnectionAbortedError("aborted during restart"),
        RemoteDisconnected("closed during restart"),
    ],
)
@pytest.mark.parametrize("phase", ["first_probe", "readiness_wait"])
def test_harness_waits_through_owner_connection_close(
    monkeypatch, spawned, closed_connection, phase
) -> None:
    owner = InterprocessFileLock(server_owner_lock_path())
    assert owner.acquire()
    try:
        if phase == "first_probe":
            _responses(monkeypatch, closed_connection, closed_connection, _healthy())
        else:
            _responses(
                monkeypatch, _refused(), _refused(), closed_connection, _healthy()
            )
        assert common.ensure_proxy_available(URL, env={}) is None
    finally:
        owner.release()
    assert spawned == []


def test_unowned_connection_reset_does_not_start_fcc(monkeypatch, spawned) -> None:
    _responses(monkeypatch, ConnectionResetError("foreign listener reset"))
    message = common.ensure_proxy_available(URL, env={})
    assert message is not None and "foreign listener reset" in message
    assert spawned == []


def test_cancelled_start_stops_only_new_child(monkeypatch) -> None:
    _responses(monkeypatch, _refused(), _refused())
    child = FakeServer()
    monkeypatch.setattr(common, "_spawn_server", lambda _env: (child, None))
    monkeypatch.setattr(
        common,
        "_wait_for_server",
        lambda *_a, **_k: (_ for _ in ()).throw(KeyboardInterrupt),
    )

    with pytest.raises(KeyboardInterrupt):
        common.ensure_proxy_available(URL, env={})

    assert child.terminated
    lock = InterprocessFileLock(server_startup_lock_path())
    assert lock.acquire()
    lock.release()


def test_cancelled_wait_preserves_existing_owner(monkeypatch, spawned) -> None:
    monkeypatch.setattr(common, "_desktop_owner_running", lambda: True)
    _responses(monkeypatch, _refused(), _refused(), KeyboardInterrupt())
    with pytest.raises(KeyboardInterrupt):
        common.ensure_proxy_available(URL, env={})
    assert spawned == []
    lock = InterprocessFileLock(server_startup_lock_path())
    assert lock.acquire()
    lock.release()


def test_manual_listener_wins_the_bind_race(monkeypatch) -> None:
    owner = InterprocessFileLock(server_owner_lock_path())
    try:
        with socket.socket() as listener:
            listener.bind(("127.0.0.1", 0))
            listener.listen()
            url = f"http://127.0.0.1:{listener.getsockname()[1]}"
            _responses(
                monkeypatch,
                _refused(),
                _refused(),
                TimeoutError("starting"),
                _healthy(),
            )
            child = FakeServer(exit_code=1)

            def spawn(_env):
                assert owner.acquire()
                return child, None

            monkeypatch.setattr(common, "_spawn_server", spawn)
            assert common.ensure_proxy_available(url, env={}) is None
            assert not child.terminated
    finally:
        owner.release()


def test_unowned_listener_winning_bind_race_does_not_hide_child_failure(
    monkeypatch,
) -> None:
    with socket.socket() as listener:
        listener.bind(("127.0.0.1", 0))
        listener.listen()
        url = f"http://127.0.0.1:{listener.getsockname()[1]}"
        _responses(
            monkeypatch, _refused(), _refused(), TimeoutError("starting"), _healthy()
        )
        child = FakeServer(exit_code=1)
        monkeypatch.setattr(common, "_spawn_server", lambda _env: (child, None))
        message = common.ensure_proxy_available(url, env={})
        assert message is not None and "exited with code 1" in message
        assert not child.terminated


def test_probe_caps_both_connections_to_remaining_time(monkeypatch, clock) -> None:
    def http(_request, *, timeout):
        assert timeout == 1.0
        clock.now = 0.8
        raise TimeoutError("loading")

    def tcp(_address, *, timeout):
        assert timeout == pytest.approx(0.2)
        return MagicMock()

    monkeypatch.setattr(common, "open_local_request", http)
    monkeypatch.setattr(common.socket, "create_connection", tcp)
    assert common._probe_proxy(URL, deadline=1.0).state is common.ProxyState.STARTING


def test_expired_probe_does_not_start_any_connection(monkeypatch, clock) -> None:
    http = MagicMock()
    tcp = MagicMock()
    monkeypatch.setattr(common, "open_local_request", http)
    monkeypatch.setattr(common.socket, "create_connection", tcp)
    common._probe_proxy(URL, deadline=0.0)
    http.assert_not_called()
    tcp.assert_not_called()


def test_http_timeout_at_deadline_does_not_start_tcp_probe(monkeypatch, clock) -> None:
    def http(_request, *, timeout):
        clock.now = 1.0
        raise TimeoutError("loading")

    tcp = MagicMock()
    monkeypatch.setattr(common, "open_local_request", http)
    monkeypatch.setattr(common.socket, "create_connection", tcp)
    assert common._probe_proxy(URL, deadline=1.0).state is common.ProxyState.STARTING
    tcp.assert_not_called()


def test_exhausted_recheck_budget_does_not_spawn(monkeypatch, spawned, clock) -> None:
    calls = 0

    def request(_request, *, timeout):
        nonlocal calls
        calls += 1
        if calls == 2:
            clock.now = 1.0
        raise _refused()

    monkeypatch.setattr(common, "open_local_request", request)
    message = common.ensure_proxy_available(URL, env={})
    assert message is not None and "did not become ready" in message
    assert spawned == []


def test_detached_streams_and_browser_preference_are_independent(monkeypatch) -> None:
    monkeypatch.setattr(common, "server_command", lambda: ["fcc-test"])
    observed = {}

    def popen(_command, **kwargs):
        observed.update(kwargs)
        return FakeServer()

    monkeypatch.setattr(common.subprocess, "Popen", popen)
    common._spawn_server({"FCC_OPEN_BROWSER": "0"})

    assert observed["env"]["FCC_OPEN_BROWSER"] == "0"
    assert observed["stdin"] is subprocess.DEVNULL
    assert observed["stdout"] not in (None, subprocess.DEVNULL)
    assert observed["stderr"] is subprocess.STDOUT


def test_early_startup_error_is_retained_and_reported(monkeypatch) -> None:
    monkeypatch.setattr(common, "open_local_request", MagicMock(side_effect=_refused()))
    monkeypatch.setattr(
        common,
        "server_command",
        lambda: [
            sys.executable,
            "-c",
            "import sys; print('FCC startup: invalid test setting', "
            "file=sys.stderr); raise SystemExit(7)",
        ],
    )

    message = common.ensure_proxy_available(URL, env=dict(os.environ))

    assert message is not None
    assert "exited with code 7" in message
    assert "FCC startup: invalid test setting" in message
    log_path = common.paths.server_log_path().with_name("startup.log")
    assert str(log_path) in message
    assert "FCC startup: invalid test setting" in log_path.read_text()


@pytest.mark.parametrize("failure", ["directory", "file"])
@pytest.mark.parametrize("outcome", ["ready", "exited", "timeout", "spawn_failure"])
def test_startup_log_failure_does_not_block_or_reuse_stale_output(
    monkeypatch, capsys, clock, failure, outcome
) -> None:
    log_path = common.paths.server_startup_log_path()
    log_path.parent.mkdir(parents=True, exist_ok=True)
    log_path.write_text("Previous attempt: stale startup error", encoding="utf-8")
    operation = Path.mkdir if failure == "directory" else Path.open

    def denied(path, *args, **kwargs):
        if (failure == "directory" and path == log_path.parent) or (
            failure == "file" and path == log_path and args == ("wb",)
        ):
            raise PermissionError("startup log access denied")
        return operation(path, *args, **kwargs)

    monkeypatch.setattr(Path, "mkdir" if failure == "directory" else "open", denied)
    if outcome == "timeout":
        monkeypatch.setattr(
            common, "open_local_request", MagicMock(side_effect=_refused())
        )
    else:
        _responses(
            monkeypatch,
            _refused(),
            _refused(),
            _healthy() if outcome == "ready" else _refused(),
        )
    child = FakeServer(exit_code=3 if outcome == "exited" else None)
    popen = MagicMock(return_value=child)
    if outcome == "spawn_failure":
        popen.side_effect = OSError("test executable failed")
    monkeypatch.setattr(common.subprocess, "Popen", popen)

    message = common.ensure_proxy_available(URL, env={"FCC_OPEN_BROWSER": "0"})

    popen.assert_called_once()
    assert popen.call_args.kwargs["stdout"] is subprocess.DEVNULL
    assert popen.call_args.kwargs["stderr"] is subprocess.STDOUT
    assert popen.call_args.kwargs["env"]["FCC_OPEN_BROWSER"] == "0"
    warning = capsys.readouterr().err
    assert str(log_path) in warning
    assert "startup log access denied" in warning
    if outcome == "ready":
        assert message is None
    else:
        detail = {
            "exited": "exited with code 3",
            "timeout": "did not become ready",
            "spawn_failure": "test executable failed",
        }[outcome]
        assert message is not None and detail in message
        assert "stale startup error" not in message
    assert not child.terminated
    lock = InterprocessFileLock(server_startup_lock_path())
    assert lock.acquire()
    lock.release()


def test_existing_unresponsive_listener_is_not_replaced(
    monkeypatch, spawned, clock
) -> None:
    with socket.socket() as listener:
        listener.bind(("127.0.0.1", 0))
        listener.listen()
        url = f"http://127.0.0.1:{listener.getsockname()[1]}"
        monkeypatch.setattr(
            common,
            "open_local_request",
            MagicMock(side_effect=URLError(TimeoutError("starting"))),
        )
        assert common.ensure_proxy_available(url, env={}) is not None
        assert spawned == []


def test_timed_out_tcp_connect_is_not_mistaken_for_starting_server(
    monkeypatch, spawned
) -> None:
    with socket.socket() as unused:
        unused.bind(("127.0.0.1", 0))
        url = f"http://127.0.0.1:{unused.getsockname()[1]}"
        _responses(
            monkeypatch,
            URLError(TimeoutError("timed out")),
            URLError(TimeoutError("timed out")),
            _healthy(),
        )
        assert common.ensure_proxy_available(url, env={}) is None
        assert len(spawned) == 1


def test_other_network_error_is_not_treated_as_absent(monkeypatch, spawned) -> None:
    _responses(monkeypatch, URLError(PermissionError("blocked")))
    assert common.ensure_proxy_available(URL, env={}) is not None
    assert spawned == []


def test_spawn_failure_is_reported(monkeypatch) -> None:
    _responses(monkeypatch, _refused(), _refused())

    def fail(*_args: object, **_kwargs: object) -> FakeServer:
        raise OSError("no such executable")

    monkeypatch.setattr(common.subprocess, "Popen", fail)
    message = common.ensure_proxy_available(URL, env={})
    assert message is not None
    assert "Could not start" in message
    assert "no such executable" in message


@pytest.mark.parametrize("winner_succeeds", [True, False])
def test_concurrent_launchers_wait_for_the_lock_holder(
    monkeypatch, spawned, winner_succeeds: bool
) -> None:
    monkeypatch.setattr(common, "SERVER_STARTUP_TIMEOUT_SECONDS", 0.05)
    monkeypatch.setattr(common, "SERVER_STARTUP_LOCK_TIMEOUT_SECONDS", 0.05)
    holder = InterprocessFileLock(server_startup_lock_path())
    assert holder.acquire()
    try:
        _responses(
            monkeypatch, _refused(), _healthy() if winner_succeeds else _refused()
        )
        message = common.ensure_proxy_available(URL, env={})
    finally:
        holder.release()
    if winner_succeeds:
        assert message is None
    else:
        assert message is not None
        assert "Another launcher is still starting" in message
    assert spawned == []


def test_two_launchers_share_one_start_attempt(monkeypatch) -> None:
    spawning, other_probed, release, healthy = (threading.Event() for _ in range(4))
    starts = []
    child = FakeServer()

    def probe(_url, *, deadline):
        if healthy.is_set():
            return common.ProxyProbe(common.ProxyState.HEALTHY)
        if starts and starts[0] != threading.get_ident():
            other_probed.set()
        return common.ProxyProbe(common.ProxyState.UNREACHABLE, "refused")

    def spawn(_env):
        starts.append(threading.get_ident())
        spawning.set()
        assert release.wait(5)
        healthy.set()
        return child, None

    monkeypatch.setattr(common, "_probe_proxy", probe)
    monkeypatch.setattr(common, "_spawn_server", spawn)
    with ThreadPoolExecutor(max_workers=2) as workers:
        first = workers.submit(common.ensure_proxy_available, URL, env={})
        try:
            assert spawning.wait(5)
            second = workers.submit(common.ensure_proxy_available, URL, env={})
            assert other_probed.wait(5)
        finally:
            release.set()
        assert first.result(timeout=5) is None
        assert second.result(timeout=5) is None
    assert len(starts) == 1
    assert not child.terminated


def test_startup_budget_starts_after_the_lock_is_acquired(monkeypatch, spawned) -> None:
    monkeypatch.setattr(common, "SERVER_STARTUP_TIMEOUT_SECONDS", 0.05)
    monkeypatch.setattr(common, "SERVER_STARTUP_LOCK_TIMEOUT_SECONDS", 5.0)
    holder = InterprocessFileLock(server_startup_lock_path())
    assert holder.acquire()
    # The previous launcher gave up without a server, well after this
    # launcher's own startup budget would have expired.
    releaser = threading.Timer(0.2, holder.release)
    releaser.start()
    try:
        _responses(monkeypatch, _refused(), _refused(), _refused(), _healthy())
        assert common.ensure_proxy_available(URL, env={}) is None
    finally:
        releaser.cancel()
        holder.release()
    assert len(spawned) == 1


@pytest.mark.parametrize(
    "platform,command_name",
    [("win32", "fcc-desktop.exe"), ("darwin", "fcc-desktop"), ("linux", "fcc-server")],
)
def test_server_command_selects_platform_owner(
    monkeypatch, tmp_path, platform, command_name
) -> None:
    executable = tmp_path / "bin" / "python"
    executable.parent.mkdir()
    monkeypatch.setattr(
        common, "sys", SimpleNamespace(executable=str(executable), platform=platform)
    )
    sibling = executable.parent / command_name
    sibling.write_text("")
    if sys.platform != "win32":
        sibling.chmod(0o755)
    assert common.server_command() == [str(sibling), "--auto-started"]


def test_missing_installed_owner_does_not_fallback_to_python(
    monkeypatch, tmp_path
) -> None:
    executable = tmp_path / "bin" / "python"
    executable.parent.mkdir()
    monkeypatch.setattr(
        common,
        "sys",
        SimpleNamespace(executable=str(executable), platform=sys.platform),
    )
    with pytest.raises(OSError, match="fcc-"):
        common.server_command()


@pytest.mark.parametrize("name", ["claude", "aider"])
def test_launcher_starts_the_server_then_runs_the_client(
    name: str,
    launch_capture: LaunchCapture,
    monkeypatch: pytest.MonkeyPatch,
    capsys: pytest.CaptureFixture[str],
) -> None:
    launch_capture.health_error = _refused()
    client_start = subprocess.Popen
    server_command = common.server_command()

    def popen(command: list[str], **kwargs: object) -> object:
        if command == server_command:
            assert kwargs["stdout"] not in (None, subprocess.DEVNULL)
            launch_capture.health_error = None
            return FakeServer()
        env = kwargs["env"]
        assert isinstance(env, Mapping)
        return client_start(command, env=env)

    monkeypatch.setattr(subprocess, "Popen", popen)
    launch(name, ["--help"])

    assert [command[-1] for command in launch_capture.commands] == ["--help"]
    health = [r for r in launch_capture.requests if r.full_url.endswith("/health")]
    assert len(health) >= 3
    assert "Starting Free Claude Code" in capsys.readouterr().err
    assert server_startup_lock_path().exists()


def test_launcher_keeps_the_manual_hint_when_the_server_cannot_start(
    launch_capture: LaunchCapture,
    monkeypatch: pytest.MonkeyPatch,
    capsys: pytest.CaptureFixture[str],
) -> None:
    launch_capture.health_error = _refused()
    monkeypatch.setattr(subprocess, "Popen", lambda *_a, **_k: FakeServer(exit_code=1))
    launch("claude", [], exit_code=1)
    assert not launch_capture.commands
    err = capsys.readouterr().err
    assert "exited with code 1" in err
    assert "Start it manually with:" in err