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): per-session drafts, scoped queue delete, stop-confirm cancel, queue order (Codex round 6)

cyh27621a016417
diff --git a/core/internal_server.py b/core/internal_server.py
index 29f0fb80e..d3aecaad1 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -303,23 +303,32 @@ def create_app(controller: "Controller") -> FastAPI:
session_id = payload.get("session_id")
if isinstance(session_id, str) and session_id:
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+
existing = in_flight.get(session_id)
- if existing is not None and not existing[0].done():
- # A turn is already running → enqueue (send-while-busy). This is
- # the ATOMIC decision point: the in_flight check and the
- # mark-queued below have no ``await`` between them, so on the
- # single-threaded loop the running turn can't end + flush in the
- # gap (which would orphan the row). The UI persisted the user row
- # before dispatching, so we just re-type it as queued; it flushes
- # when the current turn ends.
+ busy = existing is not None and not existing[0].done()
+ # Enqueue (rather than start a turn) when EITHER a turn is already
+ # running OR a prior Stop left queued rows behind — in the latter case
+ # the new message must run AFTER them, so it joins the queue instead of
+ # jumping ahead (Codex P2). The in_flight check + the mark below have no
+ # ``await`` between them, so the running turn can't end + flush in the
+ # gap (single-threaded loop) — the atomic enqueue.
+ engine = create_sqlite_engine()
+ if busy:
+ should_enqueue = True
+ else:
+ with engine.connect() as conn:
+ should_enqueue = bool(messages_service.list_queued(conn, session_id))
+ if should_enqueue:
user_message_id = payload.get("user_message_id")
if isinstance(user_message_id, str) and user_message_id:
- from storage import messages_service
- from storage.db import create_sqlite_engine
-
- engine = create_sqlite_engine()
with engine.begin() as conn:
messages_service.mark_queued(conn, user_message_id)
+ # Idle + pre-existing queue → no running turn to flush behind, so
+ # drain the whole queue (this row included) now, in order.
+ if not busy:
+ await _flush_queue(session_id)
return JSONResponse(
status_code=202,
content={"ok": True, "queued": True, "session_id": session_id, "message_id": user_message_id},
@@ -380,10 +389,21 @@ def create_app(controller: "Controller") -> FastAPI:
# the turn STARTED under (captured at dispatch time), not one rebuilt
# from the current session row, so the right backend is interrupted
# even if the Chat header swapped the session's agent / model mid-turn.
+ stopped = False
try:
- await controller.command_handler.handle_stop(turn_context)
+ stopped = bool(await controller.command_handler.handle_stop(turn_context))
except Exception:
logger.exception("internal cancel: backend stop failed for session=%s", session_id)
+ if not stopped:
+ # The backend couldn't interrupt this turn (no interruptible active
+ # session). Don't cancel the waiter — that would fire a false
+ # ``turn.end``, hide Stop, and let follow-up work start while the turn
+ # is still producing output. Keep it cancellable; it ends naturally
+ # when the backend finishes (Codex P2).
+ return JSONResponse(
+ status_code=409,
+ content={"ok": False, "code": "stop_failed", "session_id": session_id},
+ )
task.cancel()
return {"ok": True, "session_id": session_id, "status": "cancel_requested"}
diff --git a/storage/messages_service.py b/storage/messages_service.py
index ee1c58f58..5c9a3454e 100644
--- a/storage/messages_service.py
+++ b/storage/messages_service.py
@@ -274,10 +274,14 @@ def mark_queued(conn: Connection, message_id: str) -> bool:
return bool(result.rowcount)
-def remove_queued(conn: Connection, message_id: str) -> bool:
- """Delete one queued message by id. Returns True if a row was removed."""
+def remove_queued(conn: Connection, session_id: str, message_id: str) -> bool:
+ """Delete one queued message, scoped to its session so a stale / cross-session
+ id can't drop another chat's queued row. Returns True if a row was removed."""
result = conn.execute(
- delete(messages).where(messages.c.id == message_id).where(messages.c.type == QUEUED_TYPE)
+ delete(messages)
+ .where(messages.c.id == message_id)
+ .where(messages.c.session_id == session_id)
+ .where(messages.c.type == QUEUED_TYPE)
)
return bool(result.rowcount)
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index e4830c472..2086f18b9 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -409,7 +409,7 @@ def test_dispatch_forwards_session_routing_into_platform_specific(monkeypatch, t
assert target.get("reasoning_effort") == "high"
-def test_dispatch_async_starts_turn_and_returns_202():
+def test_dispatch_async_starts_turn_and_returns_202(monkeypatch, tmp_path):
"""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
@@ -418,6 +418,12 @@ def test_dispatch_async_starts_turn_and_returns_202():
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
+ from storage.importer import ensure_sqlite_state
+
+ # dispatch_async reads the queue (to preserve order after a Stop), so it needs
+ # an initialized state DB even on the empty-queue happy path.
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ ensure_sqlite_state()
started = asyncio.Event()
@@ -544,15 +550,17 @@ def test_async_dispatch_flushes_queue_on_turn_end(monkeypatch, tmp_path):
conn, scope_id=scope_id, agent_backend="claude", agent_name="worker"
)
session_id = session["id"]
- # Two messages queued while the (about-to-start) turn runs.
- with engine.begin() as conn:
- messages_service.enqueue_queued(conn, scope_id=scope_id, session_id=session_id, text="q1")
- messages_service.enqueue_queued(conn, scope_id=scope_id, session_id=session_id, text="q2")
seen_texts: list[str] = []
async def handler(ctx, text):
seen_texts.append(text)
+ # Simulate the user queueing two messages WHILE the first turn runs (the
+ # real flow — queued rows only exist during an active turn).
+ if text == "first turn":
+ with engine.begin() as conn:
+ messages_service.enqueue_queued(conn, scope_id=scope_id, session_id=session_id, text="q1")
+ messages_service.enqueue_queued(conn, scope_id=scope_id, session_id=session_id, text="q2")
controller.mark_turn_complete(ctx) # release each turn immediately
return None
diff --git a/tests/test_messages_service.py b/tests/test_messages_service.py
index 8ed4850ac..14e1e964a 100644
--- a/tests/test_messages_service.py
+++ b/tests/test_messages_service.py
@@ -514,8 +514,11 @@ def test_remove_queued_targets_only_queued(isolated_state):
)
with engine.begin() as conn:
- assert messages_service.remove_queued(conn, a["id"]) is True
- assert messages_service.remove_queued(conn, user_row["id"]) is False
+ assert messages_service.remove_queued(conn, "ses_rm", a["id"]) is True
+ # Wrong session id must NOT delete the row (scoped delete).
+ assert messages_service.remove_queued(conn, "ses_other", a["id"]) is False
+ # A real user message is not removable through remove_queued.
+ assert messages_service.remove_queued(conn, "ses_rm", user_row["id"]) is False
with engine.connect() as conn:
assert [q["text"] for q in messages_service.list_queued(conn, "ses_rm")] == ["b"]
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index 4b4a6dd7d..c678ee516 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -87,6 +87,9 @@ export const ChatPage: React.FC = () => {
const [queue, setQueue] = useState<WorkbenchMessage[]>([]);
const [initialDraft, setInitialDraft] = useState<string | null>(null);
const draftTimerRef = useRef<number | null>(null);
+ // The debounced draft save still owed to the server, tagged with the session
+ // it belongs to — so a fast session switch flushes it instead of dropping it.
+ const draftPendingRef = useRef<{ sessionId: string; text: string } | null>(null);
// Tracks which session's handed-off initial message we've already replayed
// (see the initial-message effect below). Keyed by session id, not a global
// boolean, so a second create-via-chat flow that reuses this ChatPage
@@ -154,14 +157,36 @@ export const ChatPage: React.FC = () => {
const onDraftChange = useCallback(
(text: string) => {
if (!sessionId) return;
+ // Tag the pending save with THIS session so the timer (and the
+ // session-change flush) save to the right session even if the user has
+ // since navigated away.
+ draftPendingRef.current = { sessionId, text };
if (draftTimerRef.current) window.clearTimeout(draftTimerRef.current);
draftTimerRef.current = window.setTimeout(() => {
- void api.setSessionDraft(sessionId, text);
+ const pending = draftPendingRef.current;
+ draftPendingRef.current = null;
+ draftTimerRef.current = null;
+ if (pending) void api.setSessionDraft(pending.sessionId, pending.text);
}, 600);
},
[api, sessionId],
);
+ // Flush a still-pending draft for the session we're leaving, so switching
+ // chats within the debounce window doesn't drop it (Codex P2). Runs on
+ // sessionId change + unmount.
+ useEffect(() => {
+ return () => {
+ if (draftTimerRef.current) {
+ window.clearTimeout(draftTimerRef.current);
+ draftTimerRef.current = null;
+ }
+ const pending = draftPendingRef.current;
+ draftPendingRef.current = null;
+ if (pending) void api.setSessionDraft(pending.sessionId, pending.text);
+ };
+ }, [sessionId, api]);
+
const refresh = useCallback(async () => {
if (!sessionId) return;
setLoading(true);
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 3219281b2..2ed454119 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -3287,7 +3287,7 @@ def sessions_queue_remove(session_id: str, message_id: str):
engine = _projects_engine()
with engine.begin() as conn:
- removed = messages_service.remove_queued(conn, message_id)
+ removed = messages_service.remove_queued(conn, session_id, message_id)
if removed:
broker.publish("queue.updated", {"session_id": session_id})
return jsonify({"removed": bool(removed)})