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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(workbench): send-now + stop-keeps-queue, and Codex round-4 backend fixes (Step 5d)
cyh1e61fdc68652
diff --git a/core/internal_server.py b/core/internal_server.pyindex 99c49bf83..384fbb897 100644--- a/core/internal_server.py+++ b/core/internal_server.py@@ -83,6 +83,13 @@ def create_app(controller: "Controller") -> FastAPI:in_flight: dict[str, tuple[asyncio.Task, MessageContext]] = {}app.state.in_flight_dispatches = in_flight+ # Sessions whose current turn should flush its send-while-busy queue EVEN+ # though it's ending via cancellation. A plain Stop cancels without flushing+ # (the user asked to keep the queue — "不清空队列"); ``send-now`` cancels the+ # running turn but sets this so the queue runs immediately afterwards.+ flush_on_cancel: set[str] = set()+ app.state.flush_on_cancel = flush_on_cancel+async def _noop_chunk(_envelope: dict) -> None:# Chunks are discarded — the browser renders from ``message.new``.return None@@ -93,16 +100,21 @@ def create_app(controller: "Controller") -> FastAPI:A no-op chunk sink keeps ``dispatch_turn`` alive for the turn's lifetimeso ``in_flight`` stays populated (Stop works) and the session-level``turn.start`` / ``turn.end`` lifecycle is published for the browser's- working indicator. On completion the queue is flushed: messages the user- sent while this turn ran are merged + run as the next turn. The reply- itself reaches the browser over ``message.new``, not a response stream.+ working indicator. On NATURAL completion the queue is flushed: messages+ the user sent while this turn ran are merged + run as the next turn. A+ user Stop (cancellation) does NOT flush — the queue is kept per the+ user's "don't clear the queue on stop" rule — unless ``send-now`` opted+ this session into ``flush_on_cancel``. The reply reaches the browser over+ ``message.new``, not a response stream."""from core.inbox_events import busasync def _runner() -> None:+ cancelled = Falsetry:await dispatch_turn(controller, context, text, on_chunk=_noop_chunk)except asyncio.CancelledError:+ cancelled = Trueraiseexcept Exception:logger.exception("internal async dispatch failed for session=%s", session_id)@@ -110,7 +122,10 @@ 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})- await _flush_queue(session_id, context)+ should_flush = (not cancelled) or (session_id in flush_on_cancel)+ flush_on_cancel.discard(session_id)+ if should_flush:+ await _flush_queue(session_id, context)task = asyncio.create_task(_runner(), name="internal-dispatch-async")if isinstance(session_id, str) and session_id:@@ -347,6 +362,36 @@ def create_app(controller: "Controller") -> FastAPI:task.cancel()return {"ok": True, "session_id": session_id, "status": "cancel_requested"}+ @app.post("/internal/send-now/{session_id}")+ async def _send_now(session_id: str) -> Any:+ """Run the session's send-while-busy queue immediately ("立即发送").++ If a turn is running, interrupt it (the user explicitly chose to cut in)+ and opt into ``flush_on_cancel`` so the queue runs as soon as that turn+ unwinds. If nothing is running (e.g. after a Stop left the queue intact),+ flush directly as a fresh turn. No-op when the queue is empty.+ """+ entry = in_flight.get(session_id)+ if entry is not None and not entry[0].done():+ _task, turn_context = entry+ flush_on_cancel.add(session_id)+ try:+ await controller.command_handler.handle_stop(turn_context)+ except Exception:+ logger.exception("internal send-now: backend stop failed for session=%s", session_id)+ _task.cancel()+ return {"ok": True, "session_id": session_id, "status": "interrupted"}+ # No running turn — flush the queue directly as a new turn.+ try:+ context = _build_session_context(session_id)+ except Exception as err:+ return JSONResponse(+ status_code=404,+ content={"ok": False, "code": "session_not_found", "detail": str(err)},+ )+ await _flush_queue(session_id, context)+ return {"ok": True, "session_id": session_id, "status": "flushed"}+return appdiff --git a/core/message_mirror.py b/core/message_mirror.pyindex b3e5df635..afab0fc23 100644--- a/core/message_mirror.py+++ b/core/message_mirror.py@@ -235,7 +235,22 @@ def mirror_harness_inbound(context: MessageContext, text: str) -> None:scope_id = _scope_id_for_session(conn, session_id) if session_id else Nonerow_session_id = session_idelse:- scope_id = _resolve_scope_id(conn, context)+ # Attribute the prompt to the SAME scope the reply lands in. A+ # scheduled/watch run with a delivery override (post_to / a+ # different deliver-key) sends its result to the override channel+ # (see ``emit_agent_message``); resolve the prompt there too so+ # one turn isn't split across the source + delivery scopes (Codex+ # P2). Falls back to the source context when there's no override.+ deliver_ctx = context+ override = spec.get("delivery_override") or {}+ if override.get("channel_id"):+ deliver_ctx = MessageContext(+ user_id=override.get("user_id") or context.user_id,+ channel_id=override["channel_id"],+ platform=override.get("platform") or context.platform,+ thread_id=override.get("thread_id"),+ )+ scope_id = _resolve_scope_id(conn, deliver_ctx)row_session_id = Noneif scope_id is None:returndiff --git a/storage/messages_service.py b/storage/messages_service.pyindex 3da45137e..0ba8bd5c8 100644--- a/storage/messages_service.py+++ b/storage/messages_service.py@@ -376,6 +376,10 @@ def list_inbox_sessions(m = messages# Rank every message in a session by recency (any author) → latest = activity clock.+ # Exclude the ephemeral queue/draft rows: they live in this table (Step 5)+ # but aren't sent conversation, so a saved draft or a pending queued message+ # must NOT bump the session to the top of the inbox or flip its "replied"+ # badge (Codex P2).any_ranked = (select(m.c.session_id.label("session_id"),@@ -387,6 +391,7 @@ def list_inbox_sessions(.label("rn"),).where(m.c.session_id.is_not(None))+ .where(m.c.type.notin_((QUEUED_TYPE, DRAFT_TYPE))))if platform is not None:any_ranked = any_ranked.where(m.c.platform == platform)diff --git a/tests/test_internal_server.py b/tests/test_internal_server.pyindex 00e7e73db..b33cef92d 100644--- a/tests/test_internal_server.py+++ b/tests/test_internal_server.py@@ -546,6 +546,60 @@ def test_async_dispatch_flushes_queue_on_turn_end(monkeypatch, tmp_path):assert [m["text"] for m in transcript["messages"]] == ["q1\nq2"], "the flush persisted one merged user row"+def test_cancel_does_not_flush_queue(monkeypatch, tmp_path):+ """A user Stop interrupts the turn but must NOT flush the queue — the user+ asked to keep queued messages on stop ('不清空队列'). The queued rows survive+ the cancellation; only a natural turn end (or send-now) runs them."""+ from core.services import sessions as sessions_service+ from storage import messages_service+ from storage.db import create_sqlite_engine+ from storage.importer import ensure_sqlite_state+ from storage.settings_service import upsert_scope++ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ ensure_sqlite_state()+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = upsert_scope(+ conn, platform="avibe", scope_type="project", native_id="proj_noflush", now="2026-05-31T00:00:00Z"+ )+ session = sessions_service.create_session(+ conn, scope_id=scope_id, agent_backend="claude", agent_name="worker"+ )+ session_id = session["id"]++ started = asyncio.Event()++ async def long_handler(ctx, text):+ started.set()+ await asyncio.sleep(5) # held until the test cancels it+ return None++ controller = _build_controller_double(handler=long_handler)+ app = internal_server.create_app(controller)+ transport = httpx.ASGITransport(app=app)++ async def _go():+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:+ await client.post("/internal/dispatch_async", json={"session_id": session_id, "text": "first"})+ await asyncio.wait_for(started.wait(), timeout=3)+ # Queue a message while the turn runs, then Stop.+ with engine.begin() as conn:+ messages_service.enqueue_queued(conn, scope_id=scope_id, session_id=session_id, text="q1")+ await client.post(f"/internal/cancel/{session_id}")+ for _ in range(200):+ if session_id not in app.state.in_flight_dispatches:+ break+ await asyncio.sleep(0.02)++ asyncio.run(_go())+ with engine.connect() as conn:+ queued = messages_service.list_queued(conn, session_id)+ transcript = messages_service.list_session_messages(conn, session_id=session_id, types=("user",))+ assert [q["text"] for q in queued] == ["q1"], "Stop must keep the queue intact"+ assert transcript["messages"] == [], "Stop must not flush the queue into a turn"++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/tests/test_messages_service.py b/tests/test_messages_service.pyindex b51546c04..8ed4850ac 100644--- a/tests/test_messages_service.py+++ b/tests/test_messages_service.py@@ -556,3 +556,27 @@ def test_draft_upsert_get_and_clear(isolated_state):messages_service.clear_draft(conn, "ses_d")with engine.connect() as conn:assert messages_service.get_draft(conn, "ses_d") is None+++def test_inbox_ignores_draft_and_queued_activity(isolated_state):+ """A saved draft / pending queued message lives in the messages table but+ must NOT bump the session in the inbox or flip its 'replied' badge — only+ sent conversation counts as activity (Codex P2)."""+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_scope(conn)+ _seed_session(conn, scope_id, "ses_inbox")+ _insert_msg(conn, scope_id, "ses_inbox", "user", "hi", "2026-05-30T10:00:00Z")+ _insert_msg(conn, scope_id, "ses_inbox", "agent", "reply", "2026-05-30T10:00:01Z")+ # A LATER draft + queued (newer created_at) must not count as activity.+ _insert_msg(conn, scope_id, "ses_inbox", "user", "typing", "2026-05-30T10:05:00Z", msg_type="draft")+ _insert_msg(conn, scope_id, "ses_inbox", "user", "queued", "2026-05-30T10:06:00Z", msg_type="queued")++ with engine.connect() as conn:+ rows = messages_service.list_inbox_sessions(conn, platform="avibe")["sessions"]+ assert len(rows) == 1+ row = rows[0]+ # Activity clock = the agent reply, NOT the later draft/queued rows.+ assert row["last_activity_at"] == "2026-05-30T10:00:01Z"+ assert row["last_message_author"] == "agent"+ assert row["replied"] is Falsediff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex f5c6502f6..6b680237f 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -105,6 +105,12 @@ export type ApiContextType = {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 }>;+ // 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 }>;+ 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>;connectWorkbenchEvents: (handlers: WorkbenchEventHandlers) => () => void;listVibeAgents: (params?: { backend?: string; includeDisabled?: boolean }) => Promise<{ ok: boolean; agents: VibeAgentBrief[]; default_agent_name: string | null }>;@@ -353,6 +359,8 @@ export type WorkbenchEventHandlers = {// button without the browser having to infer turn end from message rows.onTurnStart?: (data: { session_id: string }) => void;onTurnEnd?: (data: { session_id: string }) => void;+ // The send-while-busy queue for a session changed (enqueue / flush / remove).+ onQueueUpdated?: (data: { session_id: string }) => void;onAny?: (event: WorkbenchEventEnvelope) => void;onError?: (err: Event) => void;};@@ -1134,6 +1142,26 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenconst body = await res.json().catch(() => ({}));return { ok: res.ok, ...body };},+ listSessionQueue: (sessionId) => getJson(`/api/sessions/${encodeURIComponent(sessionId)}/queue`),+ removeQueuedMessage: (sessionId, messageId) =>+ deleteJson(`/api/sessions/${encodeURIComponent(sessionId)}/queue/${encodeURIComponent(messageId)}`),+ sendQueuedNow: async (sessionId, messageId) => {+ const res = await apiFetch(+ `/api/sessions/${encodeURIComponent(sessionId)}/queue/${encodeURIComponent(messageId)}/send-now`,+ { method: 'POST' },+ );+ const body = await res.json().catch(() => ({}));+ return { ok: res.ok, ...body };+ },+ getSessionDraft: (sessionId) => getJson(`/api/sessions/${encodeURIComponent(sessionId)}/draft`),+ setSessionDraft: async (sessionId, text) => {+ const res = await apiFetch(`/api/sessions/${encodeURIComponent(sessionId)}/draft`, {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ text }),+ });+ return res.ok ? res.json() : { ok: false };+ },listInbox: (params) => {const search = new URLSearchParams();if (params?.platform) search.set('platform', params.platform);@@ -1333,6 +1361,19 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenhandlers.onTurnEnd?.(envelope.data);}});+ source.addEventListener('queue.updated', (e: MessageEvent) => {+ const envelope = (() => {+ try {+ return JSON.parse(e.data) as WorkbenchEventEnvelope<{ session_id: string }>;+ } catch {+ return null;+ }+ })();+ if (envelope) {+ handlers.onAny?.(envelope);+ handlers.onQueueUpdated?.(envelope.data);+ }+ });source.onerror = (err) => handlers.onError?.(err);return () => source.close();},diff --git a/vibe/internal_client.py b/vibe/internal_client.pyindex 0dd89311a..66f7cf21a 100644--- a/vibe/internal_client.py+++ b/vibe/internal_client.py@@ -227,6 +227,29 @@ async def cancel_dispatch(session_id: str, *, socket_path: Optional[Path] = Nonereturn {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}+async def send_now(session_id: str, *, socket_path: Optional[Path] = None) -> dict[str, Any]:+ """Ask the controller to run a session's send-while-busy queue immediately+ ("立即发送"): interrupt any running turn + flush the queue. Returns+ ``{status_code, body}``; raises ``InternalServerUnavailable`` on socket+ failure so the UI route can degrade.+ """++ 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(10.0, connect=1.0),+ ) as client:+ resp = await client.post(f"/internal/send-now/{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.pyindex 59caccd98..dc6574f9e 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -3125,6 +3125,12 @@ async def sessions_messages_create(session_id: str):}if request.args.get("stream") != "1":+ # Content-only message (an attachment with no text): there's nothing for+ # the agent to run and the dispatch endpoint requires non-empty text, so+ # just persist + publish the row (the pre-dispatch behavior) without+ # starting a turn (Codex P2).+ if not dispatch_text.strip():+ return jsonify(_persist_user_message()), 201# Session/page-scoped model (the default web Chat): fire-and-forget the# turn; the reply arrives over ``message.new``. Dispatch FIRST so the# controller's in_flight check is the single source of truth — 202 →@@ -3277,6 +3283,23 @@ def sessions_queue_remove(session_id: str, message_id: str):return jsonify({"removed": bool(removed)})[email protected]("/api/sessions/<session_id>/queue/<message_id>/send-now", methods=["POST"])+async def sessions_queue_send_now(session_id: str, message_id: str):+ """Run the queue now ("立即发送"): interrupt the running turn + flush. The+ queue flushes as one merged turn, so ``message_id`` identifies the button's+ item but the whole queue runs (the merge is the user's chosen behavior)."""+ from vibe import internal_client++ try:+ result = await internal_client.send_now(session_id)+ except internal_client.InternalServerUnavailable as exc:+ return jsonify({"ok": False, "code": "internal_unavailable", "detail": str(exc)}), 503+ status = result.get("status_code", 500)+ body = result.get("body") or {}+ body.setdefault("ok", status < 400)+ return jsonify(body), status++@app.route("/api/sessions/<session_id>/draft", methods=["GET"])def sessions_draft_get(session_id: str):"""The session's saved unsent compose text (restored on open / device switch)."""