linnet/app/api/sessions.py
pyr0ball 1bc47b8e0f fix: mobile tab timeout — idle session reaper + wake lock + visibility reconnect
Backend:
- Session.last_subscriber_left_at: monotonic timestamp set when last SSE subscriber
  leaves, cleared when a new one arrives
- Session.subscriber_count(): replaces len(_subscribers) access from outside the model
- session_store._reaper_loop(): kills sessions with no subscribers for >SESSION_IDLE_TTL_S
  (default 90s); runs every TTL/2 seconds via asyncio.create_task at startup
- session_store._reaper_loop_once(): single-cycle variant for deterministic tests
- app/main.py lifespan: starts reaper on startup, cancels it cleanly on shutdown
- config.py: SESSION_IDLE_TTL_S setting (90s default, overridable per-env)

Frontend:
- useWakeLock.ts: Screen Wake Lock API wrapper; acquires on connect, releases on
  disconnect; degrades silently when unsupported (battery saver, iOS Safari)
- useToneStream.ts: visibilitychange handler — on hidden: closes EventSource without
  ending backend session (grace window stays open); on visible: GET /session/{id}
  liveness check, reconnects SSE + re-acquires wake lock if alive, sets expired=true
  and calls store.reset() if reaped
- ComposeBar.vue: surfaces expired state with calm 'Session timed out' notice
  (not an error — expected behaviour on long screen-off)

Tests:
- test_reaper.py: 7 tests covering subscriber idle tracking, reaper eligibility
  (kills idle, spares active subscriber, spares within-TTL)
2026-04-11 09:42:42 -07:00

51 lines
1.6 KiB
Python

# app/api/sessions.py — session lifecycle endpoints
from __future__ import annotations
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from app.services import session_store
router = APIRouter(prefix="/session", tags=["sessions"])
class StartRequest(BaseModel):
elcor: bool = False # enable Elcor subtext format (easter egg)
class SessionResponse(BaseModel):
session_id: str
state: str
elcor: bool
@router.post("/start", response_model=SessionResponse)
async def start_session(req: StartRequest = StartRequest()) -> SessionResponse:
"""Start a new annotation session and begin streaming VoiceFrames."""
session = await session_store.create_session(elcor=req.elcor)
return SessionResponse(
session_id=session.session_id,
state=session.state,
elcor=session.elcor,
)
@router.delete("/{session_id}/end")
async def end_session(session_id: str) -> dict:
"""Stop a session and release its classifier."""
removed = await session_store.end_session(session_id)
if not removed:
raise HTTPException(status_code=404, detail=f"Session {session_id} not found")
return {"session_id": session_id, "state": "stopped"}
@router.get("/{session_id}")
def get_session(session_id: str) -> SessionResponse:
session = session_store.get_session(session_id)
if session is None:
raise HTTPException(status_code=404, detail=f"Session {session_id} not found")
return SessionResponse(
session_id=session.session_id,
state=session.state,
elcor=session.elcor,
)