Skip to content
Python

fix(server): surface crashed WS turns as error events

Ali Abuhassan98717dd72ff7
diff --git a/coworker/server/app.py b/coworker/server/app.py
index bce87406..f1ed9348 100644
--- a/coworker/server/app.py
+++ b/coworker/server/app.py
@@ -11,6 +11,7 @@ import asyncio
import base64
import binascii
import json
+import logging
import os
import re
import secrets
@@ -24,6 +25,8 @@ from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
+logger = logging.getLogger("coworker.server.app")
+
# Origins allowed to talk to the local sidecar. It binds to 127.0.0.1, but a page in the
# user's own browser can still reach loopback — so without an origin gate, any website they
# visit could read `GET /v1/sessions` (CORS was `*`) and drive a session over the WS (which
@@ -3114,6 +3117,14 @@ def create_app(manager: SessionManager) -> FastAPI:
# Title on the user's words the moment they land — never behind
# a long agentic turn (owner catch 2026-08-24).
manager._maybe_autotitle(session_id)
+ except Exception as exc:
+ # An unexpected raise out of the turn must not vanish: the task would otherwise
+ # die silently ("Task exception was never retrieved") and the GUI would only see
+ # turn_done. Surface it as an error event like the background-turn path does.
+ logger.warning("ws turn crashed for %s: %s", session_id, exc)
+ await manager.broadcast_session(
+ session_id, {"type": "error", "data": {"error": str(exc)}}
+ )
finally:
manager.mark_idle(session_id)
manager.save(session_id, engine)
diff --git a/tests/test_server.py b/tests/test_server.py
index 6f07233b..75b50807 100644
--- a/tests/test_server.py
+++ b/tests/test_server.py
@@ -575,6 +575,40 @@ def test_ws_error_persists_notice_and_retry_reruns(tmp_path):
assert sum(1 for m in messages if m["role"] == "user") == 1
+def test_ws_turn_crash_broadcasts_error_event(tmp_path):
+ """An exception escaping engine.run() (not a provider error the engine converts into an
+ error event) must surface as an error event + turn_done — not die silently as an
+ unretrieved task exception with only a bare turn_done (#367)."""
+ import asyncio
+
+ from coworker.engine import Event
+
+ manager = SessionManager(workspace=tmp_path, provider=ScriptedProvider([]))
+ engine = manager.get_engine("boom", workspace=tmp_path)
+ assert engine is not None
+
+ async def exploding_run(*args, **kwargs):
+ raise RuntimeError("engine blew up")
+ yield # pragma: no cover - makes this an async generator
+
+ engine.run = exploding_run # type: ignore[method-assign]
+ client = TestClient(create_app(manager))
+ with client.websocket_connect("/ws/session/boom") as ws:
+ assert ws.receive_json()["type"] == "ready"
+ ws.send_json({"type": "user_message", "text": "hello"})
+ types, errors = [], []
+ while True:
+ event = ws.receive_json()
+ types.append(event["type"])
+ if event["type"] == "error":
+ errors.append(event["data"].get("error"))
+ if event["type"] == "turn_done":
+ break
+ assert len(errors) == 1 and "engine blew up" in errors[0]
+ assert "turn_done" in types
+ assert "assistant_message" not in types # the crashed turn produced no reply
+
+
# -- origin gate (local-API hardening): a browser page on a foreign origin must not be able to
# read the API cross-origin or open the driving WebSocket. -------------------------------------