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): turn-state reconcile, idle send-now status, no-flush after timeout (Codex round 10)

cyhb32ce664d7d7
diff --git a/core/internal_server.py b/core/internal_server.py
index 42fde8a8f..c63c6fda5 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -122,7 +122,12 @@ def create_app(controller: "Controller") -> FastAPI:
if isinstance(session_id, str):
in_flight.pop(session_id, None)
bus.publish("turn.end", {"session_id": session_id})
- should_flush = (not cancelled) or (session_id in flush_on_cancel)
+ # Don't flush after a Stop (keep the queue) OR after a stream
+ # timeout (the backend may still be running, so flushing would
+ # overlap a second turn on top of it). send-now still forces a
+ # flush via flush_on_cancel.
+ timed_out = bool((context.platform_specific or {}).get("turn_timed_out"))
+ should_flush = (not cancelled and not timed_out) or (session_id in flush_on_cancel)
flush_on_cancel.discard(session_id)
if should_flush:
await _flush_queue(session_id)
@@ -132,18 +137,20 @@ def create_app(controller: "Controller") -> FastAPI:
in_flight[session_id] = (task, context)
bus.publish("turn.start", {"session_id": session_id})
- async def _flush_queue(session_id: str) -> None:
+ async def _flush_queue(session_id: str) -> bool:
"""Pop the messages queued while a turn ran, merge them into one
(newline-joined) user message, and run it as the next turn — recursively
- draining the queue. Empty queue → no-op. The merge is the user's choice
- (one dispatch, not N); the individual queued rows are deleted by
- ``pop_queued`` and replaced by the single merged user row."""
+ draining the queue. Returns True if a turn was started, False on an empty
+ queue / failure (so ``send-now`` can report idle instead of leaving the
+ client stuck waiting). The merge is the user's choice (one dispatch, not
+ N); the individual queued rows are deleted by ``pop_queued`` and replaced
+ by the single merged user row."""
from core.inbox_events import bus
from storage import messages_service
from storage.db import create_sqlite_engine
if not session_id:
- return
+ return False
user_row = None
inbox_row = None
try:
@@ -152,7 +159,7 @@ def create_app(controller: "Controller") -> FastAPI:
rows = messages_service.pop_queued(conn, session_id)
texts = [r.get("text") for r in rows if (r.get("text") or "").strip()]
if not texts:
- return
+ return False
user_row = messages_service.append(
conn,
scope_id=rows[0]["scope_id"],
@@ -166,9 +173,9 @@ def create_app(controller: "Controller") -> FastAPI:
inbox_row = messages_service.get_inbox_session(conn, session_id)
except Exception:
logger.exception("queue flush: failed to pop/merge for session=%s", session_id)
- return
+ return False
if user_row is None:
- return
+ return False
# Surface the flushed (merged) user message, bump the inbox card (so other
# workbench views re-rank + flip 'replied' without waiting for the next
# result — Codex P2), and mark the queue empty.
@@ -183,13 +190,24 @@ def create_app(controller: "Controller") -> FastAPI:
context = _build_session_context(session_id)
except Exception:
logger.exception("queue flush: failed to build context for session=%s", session_id)
- return
+ return False
await _run_turn(session_id, context, user_row.get("text") or "")
+ return True
@app.get("/internal/health")
async def _health() -> dict[str, Any]:
return {"ok": True, "service": "vibe-remote-internal", "version": 1}
+ @app.get("/internal/turn-state/{session_id}")
+ async def _turn_state(session_id: str) -> Any:
+ """Whether a turn is currently running for the session. The fire-and-
+ forget dispatch survives browser disconnects, so a freshly loaded /
+ reconnected Chat page asks this to restore its working/Stop state for a
+ turn that is still in flight (Codex P2)."""
+ entry = in_flight.get(session_id)
+ active = entry is not None and not entry[0].done()
+ return {"ok": True, "session_id": session_id, "in_flight": active}
+
@app.post("/internal/dispatch")
async def _dispatch(request: Request) -> Any:
payload = await _safe_json(request)
@@ -439,9 +457,12 @@ def create_app(controller: "Controller") -> FastAPI:
_task.cancel()
return {"ok": True, "session_id": session_id, "status": "interrupted"}
# No running turn — flush the queue directly as a new turn (it rebuilds
- # the routing context from the current session row internally).
- await _flush_queue(session_id)
- return {"ok": True, "session_id": session_id, "status": "flushed"}
+ # the routing context from the current session row internally). Report
+ # ``empty`` when there was nothing to flush (a stale queue item already
+ # gone) so the client clears its optimistic working state instead of
+ # waiting for a turn that never starts (Codex P2).
+ flushed = await _flush_queue(session_id)
+ return {"ok": True, "session_id": session_id, "status": "flushed" if flushed else "empty"}
return app
diff --git a/core/services/dispatch.py b/core/services/dispatch.py
index 46d99f731..5ff00730b 100644
--- a/core/services/dispatch.py
+++ b/core/services/dispatch.py
@@ -118,6 +118,13 @@ async def dispatch_turn(
session_key,
TURN_STREAM_TIMEOUT,
)
+ # The backend may STILL be running (a long command that hasn't
+ # produced a result yet). Mark the turn as unresolved so the async
+ # wrapper does NOT flush the queue / start a new turn on top of it —
+ # otherwise two turns overlap. The late result (if any) just appends.
+ if context.platform_specific is None:
+ context.platform_specific = {}
+ context.platform_specific["turn_timed_out"] = True
return result
finally:
# Pass our own done event so a turn that was superseded by a newer
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index c893c6b32..13595f46d 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -641,6 +641,30 @@ def test_cancel_does_not_flush_queue(monkeypatch, tmp_path):
assert transcript["messages"] == [], "Stop must not flush the queue into a turn"
+def test_turn_state_reflects_in_flight():
+ """``/internal/turn-state`` reports whether a turn is running, so a freshly
+ loaded / reconnected Chat page can restore its Stop state."""
+ app = internal_server.create_app(_build_controller_double())
+ transport = httpx.ASGITransport(app=app)
+
+ async def _go():
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ idle = (await client.get("/internal/turn-state/ses_ts")).json()
+ # Simulate an in-flight turn.
+ task = asyncio.create_task(asyncio.sleep(60))
+ app.state.in_flight_dispatches["ses_ts"] = (
+ task,
+ MessageContext(user_id="U", channel_id="C", platform="avibe"),
+ )
+ busy = (await client.get("/internal/turn-state/ses_ts")).json()
+ task.cancel()
+ return idle, busy
+
+ idle, busy = asyncio.run(_go())
+ assert idle["in_flight"] is False
+ assert busy["in_flight"] is True
+
+
def test_cancel_returns_404_when_session_not_in_flight():
app = internal_server.create_app(_build_controller_double())
transport = httpx.ASGITransport(app=app)
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index 0616e5a0d..8b901104f 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -193,17 +193,33 @@ export const ChatPage: React.FC = () => {
};
}, [sessionId, api]);
+ // The fire-and-forget turn survives browser disconnects, so a freshly loaded /
+ // reconnected page asks the controller whether a turn is still in flight and
+ // restores the working/Stop state to match (Codex P2). Authoritative: clears a
+ // stale working when idle, sets it when a turn is live.
+ const syncTurnState = useCallback(async () => {
+ if (!sessionId) return;
+ try {
+ const res = await api.getTurnState(sessionId);
+ if (sessionId !== sessionIdRef.current) return;
+ setWorking(res.in_flight);
+ } catch {
+ /* controller unreachable — leave the indicator as-is */
+ }
+ }, [api, sessionId]);
+
const refresh = useCallback(async () => {
if (!sessionId) return;
setLoading(true);
setError(null);
try {
- const [fetched, agentList, msgs, queued, draft] = await Promise.all([
+ const [fetched, agentList, msgs, queued, draft, turnState] = await Promise.all([
api.getSession(sessionId),
api.listVibeAgents({ includeDisabled: false }),
api.listSessionMessages(sessionId, { limit: 50 }),
api.listSessionQueue(sessionId),
api.getSessionDraft(sessionId),
+ api.getTurnState(sessionId).catch(() => ({ in_flight: false })),
]);
// Dropped if the user switched chats while this load was in flight.
if (sessionId !== sessionIdRef.current) return;
@@ -214,6 +230,9 @@ export const ChatPage: React.FC = () => {
setMessages((prev) => mergeById(msgs.messages, prev));
setQueue(queued.queued ?? []);
setInitialDraft(draft.text ?? '');
+ // Restore Stop for a turn that is still running (e.g. opened in another tab
+ // or reloaded mid-turn).
+ setWorking(turnState.in_flight);
} catch (err: any) {
// Only surface the error if we're still on the session that failed — a
// stale failure must not stamp an error onto the chat the user moved to.
@@ -277,17 +296,18 @@ export const ChatPage: React.FC = () => {
if (data.session_id === sessionId) void refreshQueue();
},
onConnected: () => {
- // Every (re)connect reconciles durable storage, recovering any
- // ``message.new`` dropped while the socket was down.
+ // Every (re)connect recovers any state missed while the socket was down:
+ // dropped message rows, the queue, and whether a turn is still running.
void reconcile();
void refreshQueue();
+ void syncTurnState();
},
onError: () => {
// Browser EventSource auto-reconnects; keep the page usable.
},
});
return disconnect;
- }, [api, sessionId, appendMessage, reconcile, refreshQueue]);
+ }, [api, sessionId, appendMessage, reconcile, refreshQueue, syncTurnState]);
// Mobile tabs (the common case for IM users) get backgrounded mid-turn; the
// SSE feed can be suspended without a clean reconnect, dropping the reply.
@@ -395,12 +415,17 @@ export const ChatPage: React.FC = () => {
if (res && res.ok === false) {
setWorking(false);
setError(res.detail ? String(res.detail) : t('chat.stopFailed'));
+ } else if (res && (res as { status?: string }).status === 'empty') {
+ // Nothing was actually flushed (a stale queue item already gone) — no
+ // turn is starting, so drop the optimistic working state + resync.
+ setWorking(false);
+ void refreshQueue();
}
} catch (err: any) {
setWorking(false);
setError(err?.message ?? String(err));
}
- }, [api, sessionId, queue, t]);
+ }, [api, sessionId, queue, t, refreshQueue]);
useEffect(() => {
refresh();
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 6b680237f..8f19eb7d0 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -108,7 +108,8 @@ export type ApiContextType = {
// Send-while-busy queue (messages sent while a turn runs) + per-session draft.
listSessionQueue: (sessionId: string) => Promise<{ queued: WorkbenchMessage[] }>;
removeQueuedMessage: (sessionId: string, messageId: string) => Promise<{ removed: boolean }>;
- sendQueuedNow: (sessionId: string, messageId: string) => Promise<{ ok: boolean; code?: string; detail?: string }>;
+ sendQueuedNow: (sessionId: string, messageId: string) => Promise<{ ok: boolean; status?: string; code?: string; detail?: string }>;
+ getTurnState: (sessionId: string) => Promise<{ in_flight: boolean }>;
getSessionDraft: (sessionId: string) => Promise<{ text: string }>;
setSessionDraft: (sessionId: string, text: string) => Promise<{ ok: boolean }>;
listInbox: (params?: { platform?: string; unreadOnly?: boolean; limit?: number; before?: string }) => Promise<InboxFeedResult>;
@@ -1153,6 +1154,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
const body = await res.json().catch(() => ({}));
return { ok: res.ok, ...body };
},
+ getTurnState: (sessionId) => getJson(`/api/sessions/${encodeURIComponent(sessionId)}/turn-state`),
getSessionDraft: (sessionId) => getJson(`/api/sessions/${encodeURIComponent(sessionId)}/draft`),
setSessionDraft: async (sessionId, text) => {
const res = await apiFetch(`/api/sessions/${encodeURIComponent(sessionId)}/draft`, {
diff --git a/vibe/internal_client.py b/vibe/internal_client.py
index 66f7cf21a..f8d106c11 100644
--- a/vibe/internal_client.py
+++ b/vibe/internal_client.py
@@ -250,6 +250,28 @@ async def send_now(session_id: str, *, socket_path: Optional[Path] = None) -> di
return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}
+async def turn_state(session_id: str, *, socket_path: Optional[Path] = None) -> dict[str, Any]:
+ """Query whether a turn is in flight for ``session_id`` so a freshly loaded /
+ reconnected Chat page can restore its Stop/working state. Returns
+ ``{status_code, body}``; raises ``InternalServerUnavailable`` on socket
+ failure so the route can degrade (assume idle)."""
+
+ target = (socket_path or default_socket_path()).expanduser().resolve()
+ if not target.exists():
+ raise InternalServerUnavailable(f"dispatch socket missing at {target}")
+ transport = httpx.AsyncHTTPTransport(uds=str(target))
+ try:
+ async with httpx.AsyncClient(
+ transport=transport,
+ base_url="http://localhost",
+ timeout=httpx.Timeout(5.0, connect=1.0),
+ ) as client:
+ resp = await client.get(f"/internal/turn-state/{session_id}")
+ except (httpx.ConnectError, FileNotFoundError, PermissionError) as exc:
+ raise InternalServerUnavailable(str(exc)) from exc
+ return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}
+
+
async def health(socket_path: Optional[Path] = None) -> bool:
"""Probe ``GET /internal/health``. Returns False on any failure.
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 432f2d819..7d86e6b72 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -3272,6 +3272,21 @@ def sessions_mark_read(session_id: str):
)
[email protected]("/api/sessions/<session_id>/turn-state", methods=["GET"])
+async def sessions_turn_state(session_id: str):
+ """Whether a turn is currently in flight (so a freshly loaded / reconnected
+ Chat page can restore its Stop/working state). Degrades to idle if the
+ controller socket is unreachable."""
+ from vibe import internal_client
+
+ try:
+ result = await internal_client.turn_state(session_id)
+ except internal_client.InternalServerUnavailable:
+ return jsonify({"in_flight": False})
+ body = result.get("body") or {}
+ return jsonify({"in_flight": bool(body.get("in_flight"))})
+
+
@app.route("/api/sessions/<session_id>/queue", methods=["GET"])
def sessions_queue_list(session_id: str):
"""Pending send-while-busy messages for a session (shown above the composer)."""