Skip to content
Open
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
73 changes: 64 additions & 9 deletions pythonclaw/daemon.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down Expand Up @@ -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
Expand All @@ -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)

Expand Down Expand Up @@ -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
10 changes: 6 additions & 4 deletions pythonclaw/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand Down
25 changes: 22 additions & 3 deletions pythonclaw/web/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -52,22 +54,37 @@ 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
----------
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
_store = SessionStore()
_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")
Expand Down Expand Up @@ -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

Expand Down
Loading
Loading