Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(workbench): release stale stop turns (#549)

Call Whitea0876f27f773
diff --git a/core/handlers/command_handlers.py b/core/handlers/command_handlers.py
index 3cc0a1565..55a3a232d 100644
--- a/core/handlers/command_handlers.py
+++ b/core/handlers/command_handlers.py
@@ -971,7 +971,11 @@ class CommandHandlers(BaseHandler):
)
handled = await self.controller.agent_service.handle_stop(agent_name, request)
- if not handled:
+ if not handled and request.stop_failure_reason:
+ if context.platform_specific is None:
+ context.platform_specific = {}
+ context.platform_specific["stop_failure_reason"] = request.stop_failure_reason
+ if not handled and not payload.get("suppress_stop_no_active_notice"):
channel_context = self._get_channel_context(context)
await im_client.send_message(channel_context, f"ℹ️ {self._t('command.stop.noActiveSession')}")
# Return whether the backend actually interrupted a turn, so callers
diff --git a/core/session_turns.py b/core/session_turns.py
index 22a69fa94..f9b655685 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -294,7 +294,8 @@ class SessionTurnManager:
# NO turn-duration timeout: the slot is freed only by a real
# terminal signal here (Phase 1a — STUCK/sentinel removed).
turn = self.in_flight.pop(session_id, None)
- bus.publish("turn.end", {"session_id": session_id})
+ if turn is not None:
+ bus.publish("turn.end", {"session_id": session_id})
# Converge the no-terminal-result outcome onto the OUTBOUND status
# chokepoint. The normal path already emitted a terminal result;
# only ``failed`` reaches here without one: dispatch raised before
@@ -553,19 +554,44 @@ class SessionTurnManager:
# turn STARTED under so the right backend is interrupted even if the Chat
# header swapped the session's agent / model mid-turn.
turn.stop_no_flush = True
+ if turn.context.platform_specific is None:
+ turn.context.platform_specific = {}
+ turn.context.platform_specific["suppress_stop_no_active_notice"] = True
stopped = False
try:
stopped = bool(await self.controller.command_handler.handle_stop(turn.context))
except Exception:
logger.exception("internal cancel: backend stop failed for session=%s", session_id)
if not stopped:
- # Stop refused — the turn keeps running, so it isn't being stopped; drop
- # the no-flush marker so a later natural completion flushes normally.
- # Don't cancel the waiter — that would fire a false ``turn.end``, hide
- # Stop, and let follow-up work start while the turn still produces output
- # (Codex P2).
+ spec = getattr(turn.context, "platform_specific", None) or {}
+ reason = str(spec.get("stop_failure_reason") or "").strip()
+ stale_backend = reason in {"not_active", "runtime_unavailable"}
+ if stale_backend:
+ # The backend no longer has an active runtime handle, but Workbench
+ # still owns an in-flight waiter. Keeping it would leave Stop stuck
+ # and queue future sends behind a phantom turn. Release only after
+ # an explicit user Stop and keep ``stop_no_flush`` so queued
+ # messages are preserved.
+ turn.task.cancel()
+ await asyncio.gather(turn.task, return_exceptions=True)
+ released_turn = self.in_flight.pop(session_id, None)
+ from core.inbox_events import bus
+
+ if released_turn is not None:
+ bus.publish("turn.end", {"session_id": session_id})
+ if self.controller is not None:
+ self.controller.set_agent_status(session_id, "idle")
+ return {
+ "ok": True,
+ "session_id": session_id,
+ "status": "stale_released",
+ "reason": reason,
+ }
+ # Stop failed/refused while the backend may still be producing output;
+ # keep the Workbench turn registered so Stop remains available and
+ # later natural completion can flush normally.
turn.stop_no_flush = False
- return {"ok": False, "code": "stop_failed", "session_id": session_id}
+ return {"ok": False, "code": "stop_failed", "session_id": session_id, "reason": reason or None}
turn.task.cancel()
return {"ok": True, "session_id": session_id, "status": "cancel_requested"}
@@ -595,6 +621,9 @@ class SessionTurnManager:
# cancel, opposite intent: send-now WANTS the queue to run). Drop it on a
# refused stop and leave the turn + queue untouched (Codex P2).
turn.flush_on_cancel = True
+ if turn.context.platform_specific is None:
+ turn.context.platform_specific = {}
+ turn.context.platform_specific["suppress_stop_no_active_notice"] = True
stopped = False
try:
stopped = bool(await self.controller.command_handler.handle_stop(turn.context))
diff --git a/modules/agents/base.py b/modules/agents/base.py
index b843b4f2c..ddb7f0543 100644
--- a/modules/agents/base.py
+++ b/modules/agents/base.py
@@ -48,6 +48,10 @@ class AgentRequest:
typing_indicator_task: Optional[Any] = None
# File attachments (downloaded or with URLs for download)
files: Optional[List[FileAttachment]] = None
+ # Internal stop diagnostics. Backend adapters set this when ``handle_stop``
+ # returns False so Workbench can distinguish a stale missing runtime from an
+ # interrupt refusal/failure.
+ stop_failure_reason: Optional[str] = None
@dataclass
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
index 6c3367697..1a56eb1d1 100644
--- a/modules/agents/claude_agent.py
+++ b/modules/agents/claude_agent.py
@@ -332,6 +332,7 @@ class ClaudeAgent(BaseAgent):
async def handle_stop(self, request: AgentRequest) -> bool:
composite_key = request.composite_session_id
if composite_key not in self.claude_sessions:
+ request.stop_failure_reason = "not_active"
return False
client = self.claude_sessions[composite_key]
@@ -349,6 +350,7 @@ class ClaudeAgent(BaseAgent):
)
return True
else:
+ request.stop_failure_reason = "unsupported"
await self.controller.emit_agent_message(
request.context,
"notify",
@@ -356,6 +358,7 @@ class ClaudeAgent(BaseAgent):
)
return False
except Exception as err:
+ request.stop_failure_reason = "interrupt_failed"
logger.error(f"Failed to interrupt Claude session {composite_key}: {err}")
await self.controller.emit_agent_message(
request.context,
diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.py
index 0e10954b4..c09063e96 100644
--- a/modules/agents/codex/agent.py
+++ b/modules/agents/codex/agent.py
@@ -212,10 +212,12 @@ class CodexAgent(BaseAgent):
turn_id = self._turn_registry.get_active_turn(request.base_session_id)
if not thread_id or not turn_id:
+ request.stop_failure_reason = "not_active"
return False
transport = self._transports.get(request.working_path)
if not transport or not transport.is_alive:
+ request.stop_failure_reason = "runtime_unavailable"
return False
try:
@@ -238,6 +240,7 @@ class CodexAgent(BaseAgent):
logger.info("Codex turn %s interrupted via /stop", turn_id)
return True
except Exception as e:
+ request.stop_failure_reason = "interrupt_failed"
logger.error("Failed to interrupt Codex turn: %s", e)
return False
diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.py
index 66a601200..b87858731 100644
--- a/modules/agents/opencode/agent.py
+++ b/modules/agents/opencode/agent.py
@@ -437,6 +437,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
async def handle_stop(self, request: AgentRequest) -> bool:
task = self._active_requests.get(request.base_session_id)
if not task or task.done():
+ request.stop_failure_reason = "not_active"
return False
req_info = self._session_manager.get_request_session(request.base_session_id)
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index fd49aea4c..31e96be68 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -693,6 +693,145 @@ def test_cancel_returns_404_when_session_not_in_flight():
assert body["code"] == "not_in_flight"
+def test_cancel_releases_stale_turn_when_backend_not_active():
+ controller = _build_controller_double()
+ app = internal_server.create_app(controller)
+ transport = httpx.ASGITransport(app=app)
+ statuses = []
+ notices = []
+ controller.set_agent_status = lambda session_id, status: statuses.append((session_id, status))
+
+ async def _go():
+ task = asyncio.create_task(asyncio.sleep(60))
+ context = MessageContext(
+ user_id="U",
+ channel_id="C",
+ platform="avibe",
+ platform_specific={"agent_session_id": "ses_stale"},
+ )
+ app.state.in_flight_dispatches["ses_stale"] = session_turns.Turn(task=task, context=context)
+
+ async def _not_active(_context):
+ notices.append(_context.platform_specific.get("suppress_stop_no_active_notice"))
+ _context.platform_specific["stop_failure_reason"] = "not_active"
+ return False
+
+ controller.command_handler.handle_stop = AsyncMock(side_effect=_not_active)
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ resp = await client.post("/internal/cancel/ses_stale")
+ for _ in range(200):
+ if "ses_stale" not in app.state.in_flight_dispatches:
+ break
+ await asyncio.sleep(0.02)
+ return resp, task
+
+ resp, task = asyncio.run(_go())
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["status"] == "stale_released"
+ assert body["reason"] == "not_active"
+ assert task.cancelled()
+ assert "ses_stale" not in app.state.in_flight_dispatches
+ assert statuses == [("ses_stale", "idle")]
+ assert notices == [True]
+
+
+def test_cancel_waits_for_stale_dispatch_cleanup_before_releasing():
+ controller = _build_controller_double()
+ app = internal_server.create_app(controller)
+ transport = httpx.ASGITransport(app=app)
+ controller.set_agent_status = lambda session_id, status: None
+
+ async def _go():
+ done_event = asyncio.Event()
+ cleanup_started = asyncio.Event()
+ allow_cleanup = asyncio.Event()
+ context = MessageContext(
+ user_id="U",
+ channel_id="C",
+ platform="avibe",
+ platform_specific={"agent_session_id": "ses_stale_cleanup"},
+ )
+
+ async def _stale_dispatch():
+ controller.register_turn_sink(
+ controller._get_session_key(context),
+ on_chunk=AsyncMock(),
+ done_event=done_event,
+ turn_token="old-turn",
+ )
+ try:
+ await asyncio.sleep(60)
+ finally:
+ cleanup_started.set()
+ await allow_cleanup.wait()
+ controller.pop_turn_sink(controller._get_session_key(context), done_event)
+
+ task = asyncio.create_task(_stale_dispatch())
+ for _ in range(200):
+ if controller.get_turn_sink("avibe::C") is not None:
+ break
+ await asyncio.sleep(0.01)
+ assert controller.get_turn_sink("avibe::C") is not None
+ app.state.in_flight_dispatches["ses_stale_cleanup"] = session_turns.Turn(task=task, context=context)
+
+ async def _not_active(_context):
+ _context.platform_specific["stop_failure_reason"] = "not_active"
+ return False
+
+ controller.command_handler.handle_stop = AsyncMock(side_effect=_not_active)
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ cancel_task = asyncio.create_task(client.post("/internal/cancel/ses_stale_cleanup"))
+ await asyncio.wait_for(cleanup_started.wait(), timeout=1)
+ await asyncio.sleep(0.02)
+ assert not cancel_task.done()
+ assert "ses_stale_cleanup" in app.state.in_flight_dispatches
+ allow_cleanup.set()
+ resp = await cancel_task
+ return resp, task
+
+ resp, task = asyncio.run(_go())
+ assert resp.status_code == 200
+ assert resp.json()["status"] == "stale_released"
+ assert task.cancelled()
+ assert controller.get_turn_sink("avibe::C") is None
+
+
+def test_cancel_keeps_turn_when_backend_interrupt_failed():
+ controller = _build_controller_double()
+ app = internal_server.create_app(controller)
+ transport = httpx.ASGITransport(app=app)
+
+ async def _go():
+ task = asyncio.create_task(asyncio.sleep(60))
+ context = MessageContext(
+ user_id="U",
+ channel_id="C",
+ platform="avibe",
+ platform_specific={"agent_session_id": "ses_failed_stop"},
+ )
+ app.state.in_flight_dispatches["ses_failed_stop"] = session_turns.Turn(task=task, context=context)
+
+ async def _interrupt_failed(_context):
+ _context.platform_specific["stop_failure_reason"] = "interrupt_failed"
+ return False
+
+ controller.command_handler.handle_stop = AsyncMock(side_effect=_interrupt_failed)
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ resp = await client.post("/internal/cancel/ses_failed_stop")
+ held = "ses_failed_stop" in app.state.in_flight_dispatches and not task.done()
+ task.cancel()
+ return resp, held
+
+ resp, held = asyncio.run(_go())
+ assert resp.status_code == 409
+ body = resp.json()
+ assert body["ok"] is False
+ assert body["code"] == "stop_failed"
+ assert body["reason"] == "interrupt_failed"
+ assert held is True
+
+
def test_release_for_backend_refresh_cancels_matching_turn_and_sets_idle():
controller = _build_controller_double()
manager = session_turns.SessionTurnManager(controller)
diff --git a/tests/test_message_handler_typing.py b/tests/test_message_handler_typing.py
index 60666365b..c0e18bdba 100644
--- a/tests/test_message_handler_typing.py
+++ b/tests/test_message_handler_typing.py
@@ -779,6 +779,25 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(stop_request.base_session_id, "base-session:reviewer")
self.assertEqual(stop_request.composite_session_id, "base-session:reviewer:/tmp")
+ async def test_workbench_stop_suppresses_no_active_notice(self):
+ from core.handlers.command_handlers import CommandHandlers
+
+ controller = _StubController(platform="avibe", ack_mode="reaction", typing_result=True)
+ controller.agent_service.stop_result = False
+ controller.command_handler = CommandHandlers(controller)
+ controller.session_handler = _StubSessionHandler()
+ context = MessageContext(
+ user_id="workbench",
+ channel_id="ses_main",
+ platform="avibe",
+ platform_specific={"suppress_stop_no_active_notice": True},
+ )
+
+ handled = await controller.command_handler.handle_stop(context)
+
+ self.assertFalse(handled)
+ self.assertEqual(controller.im_client.sent_messages, [])
+
async def test_empty_fallback_uses_agent_message_not_control_text(self):
controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)
controller.command_handler.handle_start = AsyncMock()
diff --git a/tests/test_ui_session_stream.py b/tests/test_ui_session_stream.py
index 45fcfdb04..66499e110 100644
--- a/tests/test_ui_session_stream.py
+++ b/tests/test_ui_session_stream.py
@@ -317,6 +317,75 @@ def test_cancel_route_returns_503_when_socket_unavailable(isolated_state, tmp_pa
assert body["code"] == "internal_unavailable"
+def test_cancel_route_recovers_stale_running_status_on_not_in_flight(isolated_state, tmp_path):
+ from core.services import sessions as sessions_service
+ from storage.db import create_sqlite_engine
+ from vibe.ui_server import app
+
+ _, session_id = _make_session(tmp_path)
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ assert sessions_service.set_agent_status(conn, session_id, "running") is True
+
+ cancel_mock = AsyncMock(
+ return_value={"status_code": 404, "body": {"ok": False, "code": "not_in_flight"}}
+ )
+ with patch("vibe.internal_client.cancel_dispatch", cancel_mock):
+ client = app.test_client()
+ headers = csrf_headers(client)
+ response = client.post(f"/api/sessions/{session_id}/cancel", headers=headers)
+
+ assert response.status_code == 404
+ body = response.get_json()
+ assert body["code"] == "not_in_flight"
+ assert body["recovered_agent_status"] is True
+ with engine.connect() as conn:
+ assert sessions_service.get_session(conn, session_id)["agent_status"] == "idle"
+
+
+def test_cancel_route_does_not_recover_failed_status_on_not_in_flight(isolated_state, tmp_path):
+ from core.services import sessions as sessions_service
+ from storage.db import create_sqlite_engine
+ from vibe.ui_server import app
+
+ _, session_id = _make_session(tmp_path)
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ assert sessions_service.set_agent_status(conn, session_id, "failed") is True
+
+ cancel_mock = AsyncMock(
+ return_value={"status_code": 404, "body": {"ok": False, "code": "not_in_flight"}}
+ )
+ with patch("vibe.internal_client.cancel_dispatch", cancel_mock):
+ client = app.test_client()
+ headers = csrf_headers(client)
+ response = client.post(f"/api/sessions/{session_id}/cancel", headers=headers)
+
+ assert response.status_code == 404
+ body = response.get_json()
+ assert body["code"] == "not_in_flight"
+ assert body["recovered_agent_status"] is False
+ with engine.connect() as conn:
+ assert sessions_service.get_session(conn, session_id)["agent_status"] == "failed"
+
+
+def test_cancel_route_preserves_not_in_flight_for_missing_session(isolated_state):
+ from vibe.ui_server import app
+
+ cancel_mock = AsyncMock(
+ return_value={"status_code": 404, "body": {"ok": False, "code": "not_in_flight"}}
+ )
+ with patch("vibe.internal_client.cancel_dispatch", cancel_mock):
+ client = app.test_client()
+ headers = csrf_headers(client)
+ response = client.post("/api/sessions/ses_missing/cancel", headers=headers)
+
+ assert response.status_code == 404
+ body = response.get_json()
+ assert body["code"] == "not_in_flight"
+ assert body["recovered_agent_status"] is False
+
+
def test_turn_state_route_returns_504_on_probe_timeout(isolated_state, tmp_path):
from vibe import internal_client
from vibe.ui_server import app
@@ -332,3 +401,72 @@ def test_turn_state_route_returns_504_on_probe_timeout(isolated_state, tmp_path)
assert response.status_code == 504
assert response.get_json()["error"]["code"] == "turn_state_timeout"
+
+
+def test_turn_state_idle_recovers_stale_running_status(isolated_state, tmp_path):
+ from core.services import sessions as sessions_service
+ from storage.db import create_sqlite_engine
+ from vibe.ui_server import app
+
+ _, session_id = _make_session(tmp_path)
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ assert sessions_service.set_agent_status(conn, session_id, "running") is True
+
+ async def idle(session_id_inner):
+ assert session_id_inner == session_id
+ return {"status_code": 200, "body": {"in_flight": False}}
+
+ with patch("vibe.internal_client.turn_state", idle):
+ client = app.test_client()
+ response = client.get(f"/api/sessions/{session_id}/turn-state")
+
+ assert response.status_code == 200
+ body = response.get_json()
+ assert body["in_flight"] is False
+ assert body["recovered_agent_status"] is True
+ with engine.connect() as conn:
+ assert sessions_service.get_session(conn, session_id)["agent_status"] == "idle"
+
+
+def test_turn_state_idle_does_not_recover_failed_status(isolated_state, tmp_path):
+ from core.services import sessions as sessions_service
+ from storage.db import create_sqlite_engine
+ from vibe.ui_server import app
+
+ _, session_id = _make_session(tmp_path)
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ assert sessions_service.set_agent_status(conn, session_id, "failed") is True
+
+ async def idle(session_id_inner):
+ assert session_id_inner == session_id
+ return {"status_code": 200, "body": {"in_flight": False}}
+
+ with patch("vibe.internal_client.turn_state", idle):
+ client = app.test_client()
+ response = client.get(f"/api/sessions/{session_id}/turn-state")
+
+ assert response.status_code == 200
+ body = response.get_json()
+ assert body["in_flight"] is False
+ assert body["recovered_agent_status"] is False
+ with engine.connect() as conn:
+ assert sessions_service.get_session(conn, session_id)["agent_status"] == "failed"
+
+
+def test_turn_state_idle_preserves_response_for_missing_session(isolated_state):
+ from vibe.ui_server import app
+
+ async def idle(session_id_inner):
+ assert session_id_inner == "ses_missing"
+ return {"status_code": 200, "body": {"in_flight": False}}
+
+ with patch("vibe.internal_client.turn_state", idle):
+ client = app.test_client()
+ response = client.get("/api/sessions/ses_missing/turn-state")
+
+ assert response.status_code == 200
+ body = response.get_json()
+ assert body["in_flight"] is False
+ assert body["recovered_agent_status"] is False
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index a853929d7..b79457f47 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -693,7 +693,10 @@ export const ChatPage: React.FC = () => {
if (sessionId !== sessionIdRef.current) return;
// On success the backend is interrupted and the authoritative ``turn.end``
// clears the working state, so we don't clear it here.
- if (res && res.ok === false) {
+ if (res && res.status === 'stale_released') {
+ setWorking(false);
+ void syncTurnState();
+ } else if (res && res.ok === false) {
if (res.code === 'not_in_flight') {
// The controller has no running turn — our working state was stale
// (a missed turn.end). Clear it instead of leaving Stop stuck (Codex P2).
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index dcef75596..a0d8c9a9e 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -184,7 +184,15 @@ export type ApiContextType = {
listSessionMessages: (sessionId: string, params?: { afterId?: string; beforeId?: string; limit?: number; tail?: boolean; cache?: boolean }) => Promise<{ messages: WorkbenchMessage[]; next_after_id: string | null; next_before_id?: string | null }>;
sendSessionMessage: (sessionId: string, payload: { text?: string; content?: Record<string, unknown>; metadata?: Record<string, unknown>; author_id?: string; author_name?: string }) => Promise<WorkbenchMessage>;
markSessionRead: (sessionId: string, untilMessageId?: string) => Promise<{ updated: number; unread_counts: Record<string, number>; unread_by_session: Record<string, number> }>;
- cancelSession: (sessionId: string) => Promise<{ ok: boolean; status?: string; code?: string; detail?: string }>;
+ cancelSession: (
+ sessionId: string,
+ ) => Promise<{
+ ok: boolean;
+ status?: string;
+ code?: string;
+ detail?: string;
+ recovered_agent_status?: boolean;
+ }>;
// Send-while-busy queue (messages sent while a turn runs) + per-session draft.
listSessionQueue: (sessionId: string, options?: { cache?: boolean }) => Promise<{ queued: WorkbenchMessage[] }>;
removeQueuedMessage: (sessionId: string, messageId: string) => Promise<{ removed: boolean }>;
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index cefe4e7a6..71fda8202 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -123,6 +123,37 @@ LOG_SOURCES = (
)
+def _recover_stale_session_status(session_id: str) -> bool:
+ """Clear a persisted ``running`` dot after the controller proves idle.
+
+ The UI process owns the browser-facing API, while the controller owns the
+ in-memory turn registry. If the controller reports no in-flight turn (or the
+ user Stop reaches a stale turn), a ``running`` row in SQLite is only a stale
+ projection and must be repaired so reloads/sidebar state stop showing a
+ phantom run.
+ """
+
+ from core.services import sessions as workbench_sessions_service
+ from storage.db import create_sqlite_engine
+ from vibe.sse_broker import broker
+
+ engine = create_sqlite_engine()
+ try:
+ with engine.begin() as conn:
+ try:
+ session = workbench_sessions_service.get_session(conn, session_id)
+ except LookupError:
+ return False
+ if not session or session.get("agent_status") != "running":
+ return False
+ changed = workbench_sessions_service.set_agent_status(conn, session_id, "idle")
+ finally:
+ engine.dispose()
+ if changed:
+ broker.publish("session.status", {"session_id": session_id, "agent_status": "idle"})
+ return changed
+
+
def _is_continuation_line(line: str, previous_message: str | None = None) -> bool:
stripped = line.lstrip()
return (
@@ -4364,6 +4395,10 @@ async def sessions_cancel(session_id: str):
status = result.get("status_code", 500)
body = result.get("body") or {}
body.setdefault("ok", status == 200)
+ if status == 404 and body.get("code") == "not_in_flight":
+ body["recovered_agent_status"] = _recover_stale_session_status(session_id)
+ elif status == 200 and body.get("status") == "stale_released":
+ body["recovered_agent_status"] = _recover_stale_session_status(session_id)
return jsonify(body), status
@@ -4431,7 +4466,11 @@ async def sessions_turn_state(session_id: str):
504,
)
body = result.get("body") or {}
- return jsonify({"in_flight": bool(body.get("in_flight"))})
+ in_flight = bool(body.get("in_flight"))
+ recovered = False
+ if not in_flight:
+ recovered = _recover_stale_session_status(session_id)
+ return jsonify({"in_flight": in_flight, "recovered_agent_status": recovered})
@app.route("/api/sessions/<session_id>/queue", methods=["GET"])