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): authoritative turn lifecycle signal + suppress_delivery guard (Codex round 2)

cyh0f4ba09019c8
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index d7326cc10..52583c9b5 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -140,7 +140,11 @@ class MessageHandler(BaseHandler):
from core.message_mirror import mirror_inbound
mirror_inbound(context, control_message)
- else:
+ elif not (context.platform_specific or {}).get("suppress_delivery"):
+ # Harness turn (scheduled / watch / webhook). Skip the mirror when
+ # the run suppresses delivery (a ``no_delivery`` target): the
+ # dispatcher keeps that run's output private, so persisting its
+ # prompt would leak the input into the visible transcript.
from core.message_mirror import mirror_harness_inbound
mirror_harness_inbound(context, message)
diff --git a/core/internal_server.py b/core/internal_server.py
index eaf74011e..2fbbb4134 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -216,6 +216,16 @@ def create_app(controller: "Controller") -> FastAPI:
# Chunks are discarded — the browser renders from ``message.new``.
return None
+ # Session-level turn lifecycle for the browser's working indicator. The
+ # Chat page can't reliably infer turn end from message rows (a Codex
+ # ``system``/``thread.started`` row also persists as ``notify`` mid-turn),
+ # so the controller is the authority: publish ``turn.start`` when the turn
+ # is accepted and ``turn.end`` when it settles — normal result, agent
+ # error/terminal (mark_turn_complete), cancel, or the safety timeout all
+ # unblock the held ``dispatch_turn`` and reach the finally below. These
+ # ride the same bus→bridge→broker path as ``message.new``.
+ from core.inbox_events import bus
+
async def _runner() -> None:
try:
await dispatch_turn(controller, context, text, on_chunk=_noop_chunk)
@@ -226,10 +236,12 @@ def create_app(controller: "Controller") -> FastAPI:
finally:
if isinstance(session_id, str):
in_flight.pop(session_id, None)
+ bus.publish("turn.end", {"session_id": session_id})
task = asyncio.create_task(_runner(), name="internal-dispatch-async")
if isinstance(session_id, str) and session_id:
in_flight[session_id] = (task, context)
+ bus.publish("turn.start", {"session_id": session_id})
return JSONResponse(status_code=202, content={"ok": True, "session_id": session_id})
@app.get("/internal/events")
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index a7daeaa04..f4acdafac 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -413,7 +413,12 @@ def test_dispatch_async_starts_turn_and_returns_202():
"""The fire-and-forget path starts the turn and returns 202 immediately.
It still holds the turn open (via a no-op on_chunk) so ``in_flight`` is set
for the turn's lifetime, then released when the turn completes — the reply
- itself reaches the browser over ``message.new``, not this response."""
+ itself reaches the browser over ``message.new``, not this response.
+
+ It also publishes the session-level ``turn.start`` / ``turn.end`` lifecycle
+ on the inbox bus (the browser's working-indicator signal)."""
+ from core import inbox_events
+
started = asyncio.Event()
async def handler(ctx, text):
@@ -427,22 +432,33 @@ def test_dispatch_async_starts_turn_and_returns_202():
transport = httpx.ASGITransport(app=app)
async def _go():
- async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
- resp = await client.post("/internal/dispatch_async", json={"session_id": "ses_a", "text": "hi"})
- # The background runner finishes after the 202; wait for it + the
- # in_flight slot to clear.
- await asyncio.wait_for(started.wait(), timeout=3)
- for _ in range(100):
- if "ses_a" not in app.state.in_flight_dispatches:
- break
- await asyncio.sleep(0.02)
- return resp
+ sub_id, queue = inbox_events.bus.subscribe()
+ events: list[str] = []
+ try:
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ resp = await client.post("/internal/dispatch_async", json={"session_id": "ses_a", "text": "hi"})
+ await asyncio.wait_for(started.wait(), timeout=3)
+ for _ in range(100):
+ if "ses_a" not in app.state.in_flight_dispatches:
+ break
+ await asyncio.sleep(0.02)
+ # Drain the bus: turn.start (at accept) + turn.end (at settle).
+ for _ in range(2):
+ try:
+ evt, _data = await asyncio.wait_for(queue.get(), timeout=1.0)
+ events.append(evt)
+ except asyncio.TimeoutError:
+ break
+ finally:
+ inbox_events.bus.unsubscribe(sub_id)
+ return resp, events
- resp = asyncio.run(_go())
+ resp, events = asyncio.run(_go())
assert resp.status_code == 202
assert resp.json()["ok"] is True
controller.message_handler.handle_user_message.assert_awaited()
assert "ses_a" not in app.state.in_flight_dispatches, "slot released after the turn"
+ assert events == ["turn.start", "turn.end"], "publishes session turn lifecycle on the bus"
def test_dispatch_async_refuses_concurrent_turn_with_409():
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index 9b0df9b02..484beaf9c 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -17,11 +17,13 @@ import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
const EFFORT_OPTIONS = ['low', 'medium', 'high', 'max'];
-// Safety net: if a turn never emits a result (agent crash / auth failure / a
-// terminal that isn't a ``result``), clear the working indicator after this so
-// the thinking bubble + disabled compose don't linger forever. Real turns clear
-// it the instant their ``result`` arrives over the stream.
-const WORKING_FALLBACK_MS = 5 * 60 * 1000;
+// Last-resort failsafe for a LOST ``turn.end`` event. The controller is the
+// authority on turn end (``turn.start`` / ``turn.end`` over the bus) and its own
+// dispatch safety timeout is 600s, so a real turn always ends by then. This is
+// deliberately longer (11 min) so it only fires if the ``turn.end`` event itself
+// was dropped in transit — never while the backend could still be running, which
+// would hide Stop on a live turn (Codex P2).
+const WORKING_FALLBACK_MS = 11 * 60 * 1000;
// The transcript-visible message types — mirrors the server filter on
// ``GET /api/sessions/{id}/messages`` so the live ``message.new`` feed appends
@@ -109,7 +111,10 @@ export const ChatPage: React.FC = () => {
return add.length ? [...prev, ...add] : prev;
});
}
- if (res.messages.some((m) => m.author === 'agent' && (m.type === 'result' || m.type === 'notify'))) {
+ // Recover a lost ``turn.end``: a freshly-seen agent ``result`` is a
+ // definitive turn output, so the turn is over. Don't use ``notify`` here —
+ // it can be a mid-turn status row (Codex P2); turn.end is the real signal.
+ if (res.messages.some((m) => m.author === 'agent' && m.type === 'result')) {
setWorking(false);
}
} catch {
@@ -160,14 +165,18 @@ export const ChatPage: React.FC = () => {
if (msg.session_id !== sessionId) return;
if (!isTranscriptMessage(msg)) return;
appendMessage(msg);
- // A terminal agent row ends the turn. Both a ``result`` (the reply) and
- // a ``notify`` (a backend that failed after dispatch — e.g. startup /
- // auth error — and stopped without a result) are turn-terminal here, so
- // either clears the working state. Without this a notify-only failure
- // would pin the thinking bubble until the fallback timer.
- if (msg.author === 'agent' && (msg.type === 'result' || msg.type === 'notify')) {
- setWorking(false);
- }
+ // NB: don't infer turn end from message rows — a Codex ``system`` /
+ // ``thread.started`` row also persists as ``notify`` mid-turn, so
+ // clearing on notify would hide Stop while the backend is still running
+ // (Codex P2). The working state is driven by turn.start / turn.end below.
+ },
+ onTurnStart: (data) => {
+ if (data.session_id === sessionId) setWorking(true);
+ },
+ onTurnEnd: (data) => {
+ // The controller confirms the turn settled (result, agent error, cancel,
+ // or its own timeout) — the authoritative end of the working state.
+ if (data.session_id === sessionId) setWorking(false);
},
onConnected: () => {
// Every (re)connect reconciles durable storage, recovering any
@@ -242,16 +251,21 @@ export const ChatPage: React.FC = () => {
const stopMessage = useCallback(async () => {
if (!sessionId || !working) return;
try {
- await api.cancelSession(sessionId);
- // Reflect the stop immediately. A late straggler reply (if the backend
- // had already produced one) simply appends as the next message.
- setWorking(false);
+ const res = await api.cancelSession(sessionId);
+ // Don't clear the working state here. cancelSession returns a non-throwing
+ // payload for controller-side failures (503 socket-unavailable, 404
+ // not_in_flight); if the stop didn't reach the backend the turn may still
+ // be live, so keep Stop available and surface the failure (Codex P2). On
+ // success the backend is interrupted and the authoritative ``turn.end``
+ // clears the working state.
+ if (res && res.ok === false) {
+ setError(res.detail ? String(res.detail) : t('chat.stopFailed'));
+ }
} catch (err: any) {
- // The cancel request itself failed (socket down) — surface it so the user
- // knows the stop didn't reach the controller.
+ // The cancel request itself threw (network) — surface it; keep Stop.
setError(err?.message ?? String(err));
}
- }, [api, sessionId, working]);
+ }, [api, sessionId, working, t]);
useEffect(() => {
refresh();
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index c9d4bd477..f5c6502f6 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -348,6 +348,11 @@ export type WorkbenchEventHandlers = {
// Carries the recomputed per-session row so consumers upsert + re-sort in
// place without a refetch (the realtime "bump to top" signal).
onInboxSessionUpdated?: (data: InboxSession) => void;
+ // Session-level turn lifecycle (the controller is the authority): a turn for
+ // this session started / settled. Drives the Chat working indicator + Stop
+ // button without the browser having to infer turn end from message rows.
+ onTurnStart?: (data: { session_id: string }) => void;
+ onTurnEnd?: (data: { session_id: string }) => void;
onAny?: (event: WorkbenchEventEnvelope) => void;
onError?: (err: Event) => void;
};
@@ -1302,6 +1307,32 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
handlers.onInboxSessionUpdated?.(envelope.data);
}
});
+ source.addEventListener('turn.start', (e: MessageEvent) => {
+ const envelope = (() => {
+ try {
+ return JSON.parse(e.data) as WorkbenchEventEnvelope<{ session_id: string }>;
+ } catch {
+ return null;
+ }
+ })();
+ if (envelope) {
+ handlers.onAny?.(envelope);
+ handlers.onTurnStart?.(envelope.data);
+ }
+ });
+ source.addEventListener('turn.end', (e: MessageEvent) => {
+ const envelope = (() => {
+ try {
+ return JSON.parse(e.data) as WorkbenchEventEnvelope<{ session_id: string }>;
+ } catch {
+ return null;
+ }
+ })();
+ if (envelope) {
+ handlers.onAny?.(envelope);
+ handlers.onTurnEnd?.(envelope.data);
+ }
+ });
source.onerror = (err) => handlers.onError?.(err);
return () => source.close();
},
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index ec584d263..94998de6a 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -1485,6 +1485,7 @@
"thinking": "Thinking…",
"notifyLabel": "Notify",
"turnInProgress": "A turn is already running — wait for the reply.",
+ "stopFailed": "Couldn't reach the agent to stop it — it may still be running.",
"source": {
"scheduled": "Scheduled task",
"watch": "Watch",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 8ed1c89b0..dfde84225 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -1484,6 +1484,7 @@
"thinking": "思考中…",
"notifyLabel": "通知",
"turnInProgress": "当前回合还在进行中,请等待回复后再发送。",
+ "stopFailed": "没能联系到 Agent 来停止,它可能还在运行。",
"source": {
"scheduled": "定时任务",
"watch": "Watch 监听",