Skip to content

Commit ea4362c

Browse files
fix(session): make PTY start + end routes async; pin uvicorn loop=asyncio
Three coordinated fixes that the per-agent Playwright matrix surfaced (the unit-test stubs were swallowing all three): 1. POST /api/session/start is now async def. The previous sync handler ran on the thread-pool worker, so ``asyncio.run(active.acquire(...))`` spun up a fresh event loop in a non-main thread. Python's signal module disallows installing signal handlers off the main thread — ``loop.add_signal_handler(SIGCHLD, ...)`` (from PTYTransport's SIGCHLD reaper) raised ``set_wakeup_fd only works in main thread``. Running on the FastAPI loop (main thread) fixes it. 2. POST /api/session/end is now async def and ``await active.release()`` before the legacy tmux cleanup. Without this, ending a PTY session cleared session_state.json but left active._active holding the transport, so the next start got 409 "already active" even though the UI had clearly ended. 3. ``studyloop web`` now runs uvicorn with ``loop="asyncio"`` (not the default uvloop). uvloop reserves SIGCHLD for its own subprocess watcher and refuses ``loop.add_signal_handler`` calls with ``cannot add a signal handler for SIGCHLD: it is used by the event loop``. The asyncio loop allows it; cost is a small perf delta irrelevant for a localhost single-user dashboard. These fixes were hidden from the §1.5b unit suite because those tests stub _build_pty_transport with a StubTransport, which never touches ``pty.fork()`` or SIGCHLD. The per-agent matrix hits the real path (with STUDYLOOP_TEST_AGENT_CMD='echo ready; exec cat' stubbing only the agent binary) and exposed all three. Main suite 2001 passed; per-agent matrix 15/15 green across claude, codex, gemini, kiro, opencode. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent 06ed6dd commit ea4362c

2 files changed

Lines changed: 37 additions & 9 deletions

File tree

‎packages/studyloop/src/studyloop/cli/_web.py‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,4 +79,16 @@ def web(port: int, lan: bool, password: str, ttyd_port: int) -> None:
7979
console.print(f"[bold]Study PWA at http://{host}:{port}[/bold]")
8080
if not lan:
8181
console.print("[dim]Use --lan to expose to network[/dim]")
82-
uvicorn.run(app, host=host, port=port, workers=1, log_level="warning")
82+
# loop="asyncio" is required for PTYTransport: uvloop reserves SIGCHLD
83+
# for its own subprocess tracking and refuses to install a user handler,
84+
# which our PTY child-exit detection depends on. The standard asyncio
85+
# loop allows add_signal_handler(SIGCHLD, ...) to coexist with subprocess
86+
# watching. See plan Blocker B6 + Amendment #7.
87+
uvicorn.run(
88+
app,
89+
host=host,
90+
port=port,
91+
workers=1,
92+
log_level="warning",
93+
loop="asyncio",
94+
)

‎packages/studyloop/src/studyloop/web/routes/session.py‎

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -427,7 +427,7 @@ class SessionOption(BaseModel):
427427

428428

429429
@router.post("/session/start")
430-
def start_session(body: StartSessionRequest) -> JSONResponse:
430+
async def start_session(body: StartSessionRequest) -> JSONResponse:
431431
"""Start a new study session from the web UI.
432432
433433
Two transports are supported:
@@ -439,23 +439,27 @@ def start_session(body: StartSessionRequest) -> JSONResponse:
439439
tmux+ttyd flow for one deprecation window. Enable explicitly via
440440
``{"transport": "ttyd"}`` in the body or by exporting
441441
``STUDYLOOP_TRANSPORT=ttyd``.
442+
443+
Declared ``async`` so the PTY path's ``active.acquire`` runs on the
444+
FastAPI event loop — installing the SIGCHLD signal handler requires
445+
a loop owned by the main thread, which ``asyncio.run`` in a worker
446+
thread cannot provide.
442447
"""
443448
transport = _resolve_transport(body.transport)
444449
if transport == "pty":
445-
return _start_pty_session(body)
450+
return await _start_pty_session(body)
446451
return _start_ttyd_session(body)
447452

448453

449-
def _start_pty_session(body: StartSessionRequest) -> JSONResponse:
454+
async def _start_pty_session(body: StartSessionRequest) -> JSONResponse:
450455
"""PTY-backed start path — no tmux, no ttyd.
451456
452457
1. Reject if a session is already active (``active.current()``).
453458
2. Resolve agent + check binary. 503 with ``install_hint`` on miss.
454459
3. Persona + DB + session_state writes (shared with legacy).
455-
4. ``active.acquire(config, factory)`` — atomic under asyncio.Lock.
460+
4. ``await active.acquire(config, factory)`` — atomic under asyncio.Lock.
456461
5. Return 201 with ``ws_url`` for the client to open.
457462
"""
458-
import asyncio as _asyncio
459463
import os
460464
import shutil
461465

@@ -578,7 +582,7 @@ def _start_pty_session(body: StartSessionRequest) -> JSONResponse:
578582
factory = _build_pty_transport(config)
579583

580584
try:
581-
_asyncio.run(session_active.acquire(config, factory))
585+
await session_active.acquire(config, factory)
582586
except SessionAlreadyActiveError:
583587
return JSONResponse(
584588
{"error": "A session is already active"},
@@ -1000,10 +1004,22 @@ async def ws_to_pty() -> None:
10001004

10011005

10021006
@router.post("/session/end")
1003-
def end_session() -> JSONResponse:
1004-
"""End the current study session from the web UI."""
1007+
async def end_session() -> JSONResponse:
1008+
"""End the current study session from the web UI.
1009+
1010+
Declared async so the PTY path can ``await active.release()`` to
1011+
tear down the active-session singleton + transport. Without this,
1012+
a follow-up ``/session/start`` would 409 even though the tmux/DB
1013+
side is cleaned up.
1014+
"""
1015+
from studyloop.session import active as session_active
1016+
10051017
state = read_session_state()
10061018

1019+
# Release the PTY singleton first — idempotent, safe when the session
1020+
# was a legacy ttyd flow that never touched active.py.
1021+
await session_active.release()
1022+
10071023
if not state.get("study_session_id"):
10081024
return JSONResponse(
10091025
{"error": "No active session"},

0 commit comments

Comments
 (0)