diff --git a/pythonclaw/daemon.py b/pythonclaw/daemon.py index a0aa332..81e200f 100644 --- a/pythonclaw/daemon.py +++ b/pythonclaw/daemon.py @@ -41,11 +41,14 @@ def start_daemon( and writes its PID to ``~/.pythonclaw/pythonclaw.pid``. """ pid = read_pid() - if pid and _is_alive(pid): - port = _read_meta().get("port", 7788) - print(f"[PythonClaw] Already running (PID {pid}).") - print(f"[PythonClaw] Dashboard: http://localhost:{port}") - return + if pid: + if _is_alive(pid): + port = _read_meta().get("port", 7788) + print(f"[PythonClaw] Already running (PID {pid}).") + print(f"[PythonClaw] Dashboard: http://localhost:{port}") + return + print(f"[PythonClaw] Stale PID file (process {pid} not running). Cleaning up.") + _cleanup_pid() _ensure_dir() @@ -113,7 +116,7 @@ def stop_daemon() -> None: print(f"[PythonClaw] Stopping daemon (PID {pid})...", end=" ", flush=True) try: os.kill(pid, signal.SIGTERM) - except ProcessLookupError: + except OSError: print("already stopped.") _cleanup_pid() return @@ -127,8 +130,9 @@ def stop_daemon() -> None: if _is_alive(pid): print("forcing...", end=" ", flush=True) try: - os.kill(pid, signal.SIGKILL) - except ProcessLookupError: + # Windows has no SIGKILL; os.kill() there terminates on any signal. + os.kill(pid, getattr(signal, "SIGKILL", signal.SIGTERM)) + except OSError: pass time.sleep(0.5) @@ -217,8 +221,59 @@ def _read_meta() -> dict: def _is_alive(pid: int) -> bool: + """Return True if a process with *pid* is currently running. + + Never raises: any failure to probe the process is reported as "not + alive" so a stale PID file can't crash ``start``/``status`` (issue #14). + """ + if pid <= 0: + return False + if sys.platform == "win32": + return _is_alive_windows(pid) try: os.kill(pid, 0) return True - except (ProcessLookupError, PermissionError): + except OSError: + # ProcessLookupError: gone. PermissionError: not ours. Anything + # else in the OSError family (EINVAL, ESRCH variants, ...): treat as + # not running rather than propagating. + return False + + +def _is_alive_windows(pid: int) -> bool: + """Non-destructive liveness probe for Windows. + + ``os.kill(pid, 0)`` is not a probe on Windows: any signal other than + CTRL_C_EVENT/CTRL_BREAK_EVENT is forwarded to ``TerminateProcess`` (so it + would kill a running daemon), and a missing/foreign PID surfaces as a + plain ``OSError`` with a WinError code rather than ProcessLookupError. + Open the process with query-only rights and ask for its exit code instead. + """ + import ctypes + + PROCESS_QUERY_LIMITED_INFORMATION = 0x1000 + STILL_ACTIVE = 259 + + try: + kernel32 = ctypes.WinDLL("kernel32") + kernel32.OpenProcess.restype = ctypes.c_void_p + kernel32.OpenProcess.argtypes = (ctypes.c_uint32, ctypes.c_int, ctypes.c_uint32) + kernel32.GetExitCodeProcess.restype = ctypes.c_int + kernel32.GetExitCodeProcess.argtypes = (ctypes.c_void_p, ctypes.POINTER(ctypes.c_uint32)) + kernel32.CloseHandle.restype = ctypes.c_int + kernel32.CloseHandle.argtypes = (ctypes.c_void_p,) + + handle = kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) + if not handle: + # ERROR_INVALID_PARAMETER (no such PID), ERROR_ACCESS_DENIED + # (someone else's process), or anything else: not our daemon. + return False + try: + exit_code = ctypes.c_uint32() + if not kernel32.GetExitCodeProcess(handle, ctypes.byref(exit_code)): + return False + return exit_code.value == STILL_ACTIVE + finally: + kernel32.CloseHandle(handle) + except (OSError, AttributeError): return False diff --git a/pythonclaw/main.py b/pythonclaw/main.py index b918c0d..30fac19 100644 --- a/pythonclaw/main.py +++ b/pythonclaw/main.py @@ -207,20 +207,22 @@ def _run_foreground(args) -> None: "Keep web.host on 127.0.0.1 unless you know what you're doing." ) - app = create_app(provider, build_provider_fn=_build_provider) - ch_to_start = channels or _detect_configured_channels() + on_startup = None if ch_to_start: from .server import start_channels from .web import app as web_app_module label = "explicit" if channels else "auto-detected" print(f"[PythonClaw] Channels ({label}): {', '.join(ch_to_start)}") - @app.on_event("startup") - async def _start_channels(): + async def _start_channels(app): bots = await start_channels(provider, ch_to_start, fastapi_app=app) web_app_module._active_bots.extend(bots) + on_startup = _start_channels + + app = create_app(provider, build_provider_fn=_build_provider, on_startup=on_startup) + print(f"[PythonClaw] Web dashboard: http://localhost:{port}") uvicorn.run(app, host=host, port=port, log_level="info") diff --git a/pythonclaw/web/app.py b/pythonclaw/web/app.py index df533b0..16c1344 100644 --- a/pythonclaw/web/app.py +++ b/pythonclaw/web/app.py @@ -14,6 +14,8 @@ import logging import os import time +from collections.abc import Awaitable, Callable +from contextlib import asynccontextmanager from pathlib import Path from typing import Any @@ -52,7 +54,12 @@ def _get_chat_lock() -> asyncio.Lock: return _chat_lock -def create_app(provider: LLMProvider | None, *, build_provider_fn=None) -> FastAPI: +def create_app( + provider: LLMProvider | None, + *, + build_provider_fn=None, + on_startup: Callable[[FastAPI], Awaitable[None]] | None = None, +) -> FastAPI: """Build and return the FastAPI app. Parameters @@ -60,6 +67,10 @@ def create_app(provider: LLMProvider | None, *, build_provider_fn=None) -> FastA provider : LLM provider (may be None if not yet configured) build_provider_fn : callable that rebuilds the provider from config (used after config save to hot-reload the provider) + on_startup : optional coroutine function awaited once the server + starts (receives the app). Registered through the + lifespan API because the ``on_event`` shortcut is + deprecated in FastAPI and gone from Starlette >= 1.0. """ global _provider, _store, _start_time, _build_provider_fn, _fastapi_app _provider = provider @@ -67,7 +78,13 @@ def create_app(provider: LLMProvider | None, *, build_provider_fn=None) -> FastA _start_time = time.time() _build_provider_fn = build_provider_fn - app = FastAPI(title="PythonClaw Dashboard", docs_url=None, redoc_url=None) + @asynccontextmanager + async def _lifespan(app: FastAPI): + if on_startup is not None: + await on_startup(app) + yield + + app = FastAPI(title="PythonClaw Dashboard", docs_url=None, redoc_url=None, lifespan=_lifespan) _fastapi_app = app app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static") @@ -98,7 +115,9 @@ def create_app(provider: LLMProvider | None, *, build_provider_fn=None) -> FastA app.add_api_route("/api/channels/restart", _api_channels_restart, methods=["POST"]) app.add_api_route("/api/files/clear", _api_clear_files, methods=["POST"]) app.add_api_route("/api/files", _api_list_files, methods=["GET"]) - app.add_websocket_route("/ws/chat", _ws_chat) + # FastAPI's own method; the Starlette ``add_websocket_route`` shortcut was + # removed in Starlette 1.0, which FastAPI >= 0.133 resolves to, see issue #13. + app.add_api_websocket_route("/ws/chat", _ws_chat) return app diff --git a/tests/test_daemon_and_web.py b/tests/test_daemon_and_web.py new file mode 100644 index 0000000..449fedd --- /dev/null +++ b/tests/test_daemon_and_web.py @@ -0,0 +1,300 @@ +""" +Regression tests for issues #13 and #14. + +#13: ``create_app`` used the Starlette ``add_websocket_route`` shortcut, which + Starlette 1.0 removed, so the daemon crashed on modern FastAPI. +#14: ``_is_alive`` only caught ProcessLookupError/PermissionError, but on + Windows ``os.kill(pid, 0)`` on a stale PID raises a plain ``OSError`` + (e.g. ``[WinError 11]``), so ``pythonclaw start`` crashed with a traceback. +""" +import ctypes +import os +import sys +import warnings + +import pytest + +from pythonclaw import daemon + +# ── Fixtures ───────────────────────────────────────────────────────────────── + +@pytest.fixture +def daemon_dir(tmp_path, monkeypatch): + """Point the daemon's PID/meta/log files at a temp directory.""" + monkeypatch.setattr(daemon, "PYTHONCLAW_DIR", tmp_path) + monkeypatch.setattr(daemon, "PID_FILE", tmp_path / "pythonclaw.pid") + monkeypatch.setattr(daemon, "META_FILE", tmp_path / "daemon.meta.json") + monkeypatch.setattr(daemon, "LOG_FILE", tmp_path / "daemon.log") + return tmp_path + + +def _posix_only_probe(monkeypatch): + """Force the os.kill() probe path even when the suite runs on Windows.""" + monkeypatch.setattr(daemon.sys, "platform", "linux") + + +# ── #14: _is_alive must never raise ────────────────────────────────────────── + +class TestIsAlive: + def test_current_process_is_alive(self): + assert daemon._is_alive(os.getpid()) is True + + def test_non_positive_pid_is_not_alive(self): + assert daemon._is_alive(0) is False + assert daemon._is_alive(-1) is False + + def test_process_lookup_error_is_not_alive(self, monkeypatch): + _posix_only_probe(monkeypatch) + + def _kill(pid, sig): + raise ProcessLookupError(3, "No such process") + + monkeypatch.setattr(daemon.os, "kill", _kill) + assert daemon._is_alive(12345) is False + + def test_permission_error_keeps_existing_behaviour(self, monkeypatch): + _posix_only_probe(monkeypatch) + + def _kill(pid, sig): + raise PermissionError(1, "Operation not permitted") + + monkeypatch.setattr(daemon.os, "kill", _kill) + assert daemon._is_alive(12345) is False + + def test_generic_oserror_is_not_alive(self, monkeypatch): + """The Windows failure mode from #14: a plain OSError with a WinError code.""" + _posix_only_probe(monkeypatch) + + def _kill(pid, sig): + exc = OSError(22, "An attempt was made to load a program with an incorrect format") + exc.winerror = 11 + raise exc + + monkeypatch.setattr(daemon.os, "kill", _kill) + assert daemon._is_alive(12345) is False + + def test_windows_path_never_calls_os_kill(self, monkeypatch): + """On Windows os.kill(pid, 0) would TerminateProcess; the probe must not use it.""" + monkeypatch.setattr(daemon.sys, "platform", "win32") + calls = [] + monkeypatch.setattr(daemon.os, "kill", lambda *a: calls.append(a)) + monkeypatch.setattr(daemon, "_is_alive_windows", lambda pid: True) + + assert daemon._is_alive(12345) is True + assert calls == [] + + +class _FakeKernel32: + """Minimal stand-in for ctypes.WinDLL('kernel32') used by _is_alive_windows.""" + + STILL_ACTIVE = 259 + + def __init__(self, *, open_ok: bool, exit_code: int | None): + self._open_ok = open_ok + self._exit_code = exit_code + self.closed = [] + + class _Fn: + def __init__(self, impl): + self._impl = impl + self.restype = None + self.argtypes = None + + def __call__(self, *args): + return self._impl(*args) + + @property + def OpenProcess(self): + return self._Fn(lambda access, inherit, pid: 0x1234 if self._open_ok else None) + + @property + def GetExitCodeProcess(self): + def impl(handle, out_ptr): + if self._exit_code is None: + return 0 + out_ptr._obj.value = self._exit_code + return 1 + return self._Fn(impl) + + @property + def CloseHandle(self): + return self._Fn(lambda handle: self.closed.append(handle) or 1) + + +class TestIsAliveWindows: + @pytest.fixture(autouse=True) + def _fake_ctypes(self, monkeypatch): + self._kernel32 = None + + def _windll(name, **kwargs): + assert name == "kernel32" + return self._kernel32 + + monkeypatch.setattr(ctypes, "WinDLL", _windll, raising=False) + + def test_running_process(self): + self._kernel32 = _FakeKernel32(open_ok=True, exit_code=_FakeKernel32.STILL_ACTIVE) + assert daemon._is_alive_windows(4242) is True + assert self._kernel32.closed == [0x1234] + + def test_exited_process(self): + self._kernel32 = _FakeKernel32(open_ok=True, exit_code=0) + assert daemon._is_alive_windows(4242) is False + assert self._kernel32.closed == [0x1234] + + def test_open_failure_means_not_alive(self): + self._kernel32 = _FakeKernel32(open_ok=False, exit_code=None) + assert daemon._is_alive_windows(4242) is False + + def test_exit_code_query_failure_means_not_alive(self): + self._kernel32 = _FakeKernel32(open_ok=True, exit_code=None) + assert daemon._is_alive_windows(4242) is False + assert self._kernel32.closed == [0x1234] + + def test_dll_load_error_means_not_alive(self, monkeypatch): + def _boom(name, **kwargs): + raise OSError("cannot load kernel32") + + monkeypatch.setattr(ctypes, "WinDLL", _boom, raising=False) + assert daemon._is_alive_windows(4242) is False + + +# ── #14: start/status with a stale PID file ────────────────────────────────── + +def _raise_winerror(pid, sig): + exc = OSError(22, "An attempt was made to load a program with an incorrect format") + exc.winerror = 11 + raise exc + + +class TestStalePidFile: + def test_status_cleans_up_stale_pid(self, daemon_dir, monkeypatch, capsys): + _posix_only_probe(monkeypatch) + monkeypatch.setattr(daemon.os, "kill", _raise_winerror) + daemon.PID_FILE.write_text("99999\n") + daemon.META_FILE.write_text('{"port": 7788}\n') + + assert daemon.daemon_status() is None + assert not daemon.PID_FILE.exists() + assert not daemon.META_FILE.exists() + + daemon.print_status() + assert "No daemon is running" in capsys.readouterr().out + + def test_stop_reports_stale_pid(self, daemon_dir, monkeypatch, capsys): + _posix_only_probe(monkeypatch) + monkeypatch.setattr(daemon.os, "kill", _raise_winerror) + daemon.PID_FILE.write_text("99999\n") + + daemon.stop_daemon() + assert "Stale PID file" in capsys.readouterr().out + assert not daemon.PID_FILE.exists() + + def test_start_with_stale_pid_does_not_crash(self, daemon_dir, monkeypatch, capsys): + _posix_only_probe(monkeypatch) + monkeypatch.setattr(daemon.os, "kill", _raise_winerror) + monkeypatch.setattr(daemon.time, "sleep", lambda s: None) + daemon.PID_FILE.write_text("99999\n") + + class _FakeProc: + pid = 54321 + returncode = None + + def poll(self): + return None + + popen_calls = [] + + def _popen(cmd, **kwargs): + popen_calls.append(cmd) + return _FakeProc() + + monkeypatch.setattr(daemon.subprocess, "Popen", _popen) + + daemon.start_daemon() + + out = capsys.readouterr().out + assert "Stale PID file (process 99999 not running)" in out + assert "Daemon started (PID 54321)" in out + assert len(popen_calls) == 1 + assert daemon.read_pid() == 54321 + + def test_start_when_already_running(self, daemon_dir, monkeypatch, capsys): + monkeypatch.setattr(daemon, "_is_alive", lambda pid: True) + daemon.PID_FILE.write_text("4242\n") + popen_calls = [] + monkeypatch.setattr(daemon.subprocess, "Popen", lambda *a, **k: popen_calls.append(a)) + + daemon.start_daemon() + + assert "Already running (PID 4242)" in capsys.readouterr().out + assert popen_calls == [] + + +# ── #13: the web app builds and serves on current FastAPI ──────────────────── + +@pytest.fixture +def web_home(tmp_path, monkeypatch): + from pythonclaw import config + + monkeypatch.setattr(config, "PYTHONCLAW_HOME", tmp_path) + return tmp_path + + +class TestWebApp: + def test_create_app_builds_without_deprecated_starlette_shortcuts(self, web_home): + from pythonclaw.web.app import create_app + + with warnings.catch_warnings(): + warnings.simplefilter("error", DeprecationWarning) + app = create_app(None) + + paths = {getattr(r, "path", None) for r in app.routes} + assert "/" in paths + assert "/ws/chat" in paths + + def test_index_and_websocket_respond(self, web_home): + pytest.importorskip("httpx") + from fastapi.testclient import TestClient + + from pythonclaw.web.app import create_app + + app = create_app(None) + with TestClient(app) as client: + resp = client.get("/") + assert resp.status_code == 200 + assert "text/html" in resp.headers["content-type"] + assert "