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(show): queue annotations through unified turn entry (#1015)

Call Whitee7515910856f
diff --git a/core/internal_server.py b/core/internal_server.py
index 97b5f9451..41cbe40d9 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -5,8 +5,7 @@ This is the C4 piece of Plan 2 from
exposes a minimal FastAPI app on
``~/.vibe_remote/state/dispatch.sock`` so cross-process callers (the
separate UI server subprocess, future ``vibe agent run --sync`` flows)
-can invoke ``core.services.dispatch.dispatch_turn`` and stream the
-agent's output back over SSE chunked response.
+can submit turns to the controller-owned session turn manager.
Three properties matter:
@@ -21,8 +20,8 @@ Three properties matter:
restrictive umask and chmod'd to ``0o600`` when the filesystem supports
it — defense in depth against shared hosts.
-The endpoint set is intentionally tiny for v1 (``dispatch`` + a stub
-``cancel``); follow-ups can grow it without changing the bind contract.
+The endpoint set is intentionally tiny; follow-ups can grow it without
+changing the bind contract.
"""
from __future__ import annotations
@@ -41,7 +40,7 @@ from fastapi.responses import JSONResponse, StreamingResponse
from sqlalchemy.exc import IntegrityError
from config import paths
-from core.services.dispatch import SOURCE_HUMAN, SOURCE_SCHEDULED, dispatch_turn
+from core.services.dispatch import SOURCE_HUMAN, SOURCE_SCHEDULED
from modules.im.base import MessageContext
from storage.db import get_cached_sqlite_engine
@@ -72,7 +71,7 @@ def create_app(controller: "Controller") -> FastAPI:
Factored out so tests can mount the same routes against a fake
controller without spinning up uvicorn.
"""
- from core.inbox_events import bus, mark_controller_process
+ from core.inbox_events import mark_controller_process
mark_controller_process()
@@ -89,14 +88,14 @@ def create_app(controller: "Controller") -> FastAPI:
# waiting for the agent to settle, and reuses the stored context so it
# interrupts the backend the turn actually started on — even if the Chat
# header changed the session's agent / model while the reply was streaming.
- # Tasks are registered when the SSE response starts and removed in its
- # ``finally`` so cancelled / completed sessions don't leak slots.
+ # Tasks are registered by ``SessionTurnManager`` before they run and removed
+ # in its ``finally`` so cancelled / completed sessions don't leak slots.
# The turn owner (FSM) is created in Controller.__init__ so it exists for boot
# stale-reset + OpenCode restore; reuse it here and bind the routing-context
# builder now that the gate (which owns _build_session_context) is built. A fake
# controller in tests may lack one — create it then. The registry bound below
# is the SAME object the closures + ``controller.session_turn_gate`` use.
- from core.session_turns import SessionTurnManager, Turn
+ from core.session_turns import SessionTurnManager, queue_pending_user_message
manager = getattr(controller, "session_turns", None)
if not isinstance(manager, SessionTurnManager):
@@ -106,19 +105,12 @@ def create_app(controller: "Controller") -> FastAPI:
controller.session_turns = manager
manager.bind_context(_build_session_context)
- # The turn registry (``session_id -> Turn``) is owned by the manager; the legacy
- # streaming ``/internal/dispatch`` (Show-page) endpoint below shares it directly,
- # and tests inspect it via ``app.state``. The flush intents live ON each ``Turn``
- # (set by ``manager.cancel`` / ``manager.send_now``), not in side sets here.
+ # The turn registry (``session_id -> Turn``) is owned by the manager and tests
+ # inspect it via ``app.state``. Flush intents live on each ``Turn`` (set by
+ # ``manager.cancel`` / ``manager.send_now``), not in side sets here.
in_flight = manager.in_flight
app.state.in_flight_dispatches = in_flight
- async def _flush_queue(session_id: str) -> bool:
- """Thin delegation to ``SessionTurnManager.flush_queue`` (FSM, Phase 1b):
- pop + merge the send-while-busy queue and run it as the next turn. Returns
- True if a turn was started, False on an empty queue / failure."""
- return await manager.flush_queue(session_id)
-
async def _submit_scheduled_turn(session_id: str, context: MessageContext, text: str) -> str:
"""Run a scheduled / watch turn through the SAME unified ``manager.submit``
the interactive Chat path uses, so a scheduled run can never preempt an
@@ -128,7 +120,8 @@ def create_app(controller: "Controller") -> FastAPI:
a fresh ``queued`` row attributed to the harness.
"""
if not session_id:
- return await manager.submit(None, context, text, source=SOURCE_SCHEDULED)
+ submission = await manager.submit(None, context, text, source=SOURCE_SCHEDULED)
+ return submission.route
native_message_id = str(getattr(context, "message_id", None) or "").strip()
if native_message_id:
@@ -147,7 +140,7 @@ def create_app(controller: "Controller") -> FastAPI:
):
return "duplicate"
- def _enqueue() -> None:
+ def _enqueue() -> bool:
from core.message_mirror import _scope_id_for_session
from core.session_turns import SCHEDULED_PROVENANCE_KEY, capture_scheduled_provenance
from storage import messages_service
@@ -161,22 +154,41 @@ def create_app(controller: "Controller") -> FastAPI:
with engine.begin() as conn:
scope_id = _scope_id_for_session(conn, session_id)
try:
- messages_service.append(
- conn,
- scope_id=scope_id,
- session_id=session_id,
- platform="avibe",
- author="harness",
- source="harness",
- message_type=messages_service.QUEUED_TYPE,
- text=text,
- metadata={SCHEDULED_PROVENANCE_KEY: capture_scheduled_provenance(context)},
- native_message_id=native_message_id or None,
- )
+ with conn.begin_nested():
+ messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author="harness",
+ source="harness",
+ message_type=messages_service.QUEUED_TYPE,
+ text=text,
+ metadata={SCHEDULED_PROVENANCE_KEY: capture_scheduled_provenance(context)},
+ native_message_id=native_message_id or None,
+ )
except IntegrityError:
logger.info("scheduled turn duplicate native id already queued: %s", native_message_id)
-
- return await manager.submit(session_id, context, text, source=SOURCE_SCHEDULED, enqueue=_enqueue)
+ return bool(
+ native_message_id
+ and messages_service.native_message_exists(
+ conn,
+ platform="avibe",
+ native_message_id=native_message_id,
+ )
+ )
+ return True
+
+ submission = await manager.submit(
+ session_id,
+ context,
+ text,
+ source=SOURCE_SCHEDULED,
+ enqueue=_enqueue,
+ )
+ if submission.route == "enqueued" and submission.queue_persisted is not True:
+ raise RuntimeError("scheduled turn queue row was not persisted")
+ return submission.route
@app.get("/internal/health")
async def _health() -> dict[str, Any]:
@@ -232,126 +244,6 @@ def create_app(controller: "Controller") -> FastAPI:
return JSONResponse(status_code=409, content=result)
return result
- @app.post("/internal/dispatch")
- async def _dispatch(request: Request) -> Any:
- """Streaming turn dispatch: runs a turn and proxies its notify/result
- chunks back over an SSE response. The web **Chat** page no longer uses
- this (it's fire-and-forget via ``/internal/dispatch_async`` +
- ``message.new``); this backs the **Show-page** dispatch flow, where
- ``ui_server._run_show_event_dispatch`` re-publishes each event as
- ``show.dispatch`` for the open Show page."""
- payload = await _safe_json(request)
- try:
- text, context = await _build_dispatch_payload(payload)
- except ValueError as err:
- return JSONResponse(status_code=400, content={"ok": False, "error": str(err)})
-
- session_id = payload.get("session_id")
-
- # One streaming turn per session. If a turn is already in flight for
- # this session (a second browser tab, or a resend before the first
- # finishes), refuse the new one HERE — before creating a task or
- # touching ``in_flight`` — so we never overwrite the real turn's task
- # handle. Overwriting it would orphan the running turn: its sink keeps
- # streaming but ``/internal/cancel`` could no longer find the task to
- # interrupt, so the Stop button would silently no-op.
- if isinstance(session_id, str) and session_id:
- existing = in_flight.get(session_id)
- if existing is not None and not existing.task.done():
- async def _busy_stream():
- yield _sse_event("turn.start", {"session_id": session_id})
- yield _sse_event(
- "turn.chunk",
- {
- "kind": "error",
- "text": controller._t("error.streamTurnInProgress"),
- "message_id": None,
- },
- )
- yield _sse_event("turn.end", {"session_id": session_id})
-
- return StreamingResponse(
- _busy_stream(),
- media_type="text/event-stream",
- headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"},
- )
-
- # SSE chunked stream — the response body is fed by ``on_chunk``
- # callbacks that the dispatcher fires for every successful
- # ``emit_agent_message`` notify / result during the turn. The
- # turn coroutine and the producer-consumer queue live on the
- # same loop, so ordering is preserved.
- chunk_queue: asyncio.Queue[Optional[dict]] = asyncio.Queue()
-
- async def on_chunk(envelope: dict) -> None:
- await chunk_queue.put(envelope)
-
- async def _runner() -> None:
- try:
- await dispatch_turn(controller, context, text, on_chunk=on_chunk)
- except asyncio.CancelledError:
- # Surface a cancel envelope so the SSE consumer can
- # distinguish "user stopped me" from "agent finished".
- await chunk_queue.put({"kind": "cancelled", "text": ""})
- raise
- except Exception as err:
- logger.exception("internal dispatch failed for session=%s", session_id)
- await chunk_queue.put({"kind": "error", "text": str(err)})
- finally:
- # This legacy streaming route invokes dispatch_turn directly, so it
- # bypasses SessionTurnManager._run_turn, which owns lifecycle bus
- # events for Chat/scheduled turns. The two paths are exclusive:
- # streaming lifecycle is owned here; manager lifecycle stays in
- # core/session_turns.py. Publishing before the sentinel also makes
- # post-turn subscribers finish before queued work can be flushed.
- if isinstance(session_id, str) and session_id:
- bus.publish("turn.end", {"session_id": session_id})
- # Sentinel signals end-of-stream to the consumer below.
- await chunk_queue.put(None)
-
- task = asyncio.create_task(_runner(), name="internal-dispatch")
- if isinstance(session_id, str) and session_id:
- in_flight[session_id] = Turn(task=task, context=context)
- # create_task cannot run until this coroutine yields, so synchronous
- # pre-turn subscribers complete before the backend can touch files.
- bus.publish("turn.start", {"session_id": session_id})
-
- async def _stream():
- saw_cancel = False
- reached_end = False
- try:
- yield _sse_event("turn.start", {"session_id": session_id})
- while True:
- envelope = await chunk_queue.get()
- if envelope is None:
- reached_end = True
- break
- if envelope.get("kind") == "cancelled":
- saw_cancel = True
- yield _sse_event("turn.chunk", envelope)
- yield _sse_event("turn.end", {"session_id": session_id})
- finally:
- if not task.done():
- task.cancel()
- # Release the slot whether the task completed normally,
- # was cancelled by the UI, or the SSE consumer
- # disconnected mid-stream. ``pop`` is idempotent.
- if isinstance(session_id, str):
- in_flight.pop(session_id, None)
- # This endpoint shares ``in_flight`` with the session, so a Chat
- # send during a Show-page dispatch enqueues behind it. Drain that
- # queue on NATURAL completion (not a Stop / consumer disconnect,
- # mirroring _run_turn's no-flush-on-cancel rule) so the queued
- # Chat message isn't stranded until manual intervention (Codex P2).
- if reached_end and not saw_cancel:
- await _flush_queue(session_id)
-
- return StreamingResponse(
- _stream(),
- media_type="text/event-stream",
- headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"},
- )
-
@app.post("/internal/dispatch_async")
async def _dispatch_async(request: Request) -> Any:
"""Fire-and-forget turn dispatch for the session/page-scoped stream.
@@ -364,6 +256,8 @@ def create_app(controller: "Controller") -> FastAPI:
Stop works), publishes the turn lifecycle, and flushes the
send-while-busy queue when it settles.
"""
+ from storage import messages_service
+
payload = await _safe_json(request)
try:
text, context = await _build_dispatch_payload(payload)
@@ -373,24 +267,309 @@ def create_app(controller: "Controller") -> FastAPI:
session_id = payload.get("session_id")
sid = session_id if isinstance(session_id, str) and session_id else None
user_message_id = payload.get("user_message_id")
-
- def _enqueue() -> None:
+ show_event_id = payload.get("show_event_id")
+ show_event_id = (
+ show_event_id.strip()
+ if isinstance(show_event_id, str) and show_event_id.strip()
+ else None
+ )
+ dispatch_owner = payload.get("dispatch_owner")
+ dispatch_owner = (
+ dispatch_owner.strip()
+ if isinstance(dispatch_owner, str) and dispatch_owner.strip()
+ else None
+ )
+ reserved_type: str | None = None
+ def _enqueue() -> bool:
# Chat already persisted the user's message as a ``pending`` row; promote
- # it to ``queued`` so it drains via the queue after the active turn.
+ # it to ``queued`` so it drains via the queue after the active turn. Keep
+ # the exact agent-facing text separately from its transcript display text.
if isinstance(user_message_id, str) and user_message_id:
- from storage import messages_service
-
engine = get_cached_sqlite_engine()
with engine.begin() as conn:
- messages_service.promote_pending(conn, user_message_id, messages_service.QUEUED_TYPE)
+ return queue_pending_user_message(
+ conn,
+ user_message_id,
+ text,
+ )
+ return False
+
+ def _active_message_id() -> str:
+ active = manager.in_flight.get(sid) if sid else None
+ return str(
+ getattr(getattr(active, "context", None), "message_id", None) or ""
+ ).strip()
+
+ if show_event_id:
+ from core.show_session_events import (
+ DISPATCH_ACCEPTED,
+ DISPATCH_ARCHIVED,
+ DISPATCH_IN_FLIGHT,
+ get_show_dispatch_status,
+ observe_and_settle_show_dispatch,
+ )
+ from sqlalchemy import select
+ from storage.models import messages
- outcome = await manager.submit(sid, context, text, enqueue=_enqueue)
- if outcome == "enqueued":
+ if not sid or not dispatch_owner:
+ return JSONResponse(
+ status_code=400,
+ content={"ok": False, "error": "Show dispatch identity is incomplete."},
+ )
+ with get_cached_sqlite_engine().connect() as conn:
+ show_status = get_show_dispatch_status(
+ conn,
+ show_event_id,
+ session_id=sid,
+ )
+ if show_status is None:
+ return JSONResponse(
+ status_code=409,
+ content={"ok": False, "code": "show_event_not_found"},
+ )
+ if show_status.session_status == "archived":
+ with get_cached_sqlite_engine().begin() as conn:
+ observe_and_settle_show_dispatch(
+ conn,
+ show_event_id,
+ session_id=sid,
+ owner=dispatch_owner,
+ active_message_id=_active_message_id(),
+ queue_persisted=None,
+ )
+ return JSONResponse(
+ status_code=409,
+ content={"ok": False, "code": "session_archived"},
+ )
+ if (
+ not isinstance(user_message_id, str)
+ or not user_message_id
+ or show_status.message_id != user_message_id
+ ):
+ return JSONResponse(
+ status_code=409,
+ content={"ok": False, "code": "show_event_message_mismatch"},
+ )
+
+ active_message_id = _active_message_id()
+ if (
+ active_message_id == user_message_id
+ and show_status.state == DISPATCH_IN_FLIGHT
+ and show_status.owner == dispatch_owner
+ ):
+ with get_cached_sqlite_engine().begin() as conn:
+ show_status, _message_type = observe_and_settle_show_dispatch(
+ conn,
+ show_event_id,
+ session_id=sid,
+ owner=dispatch_owner,
+ active_message_id=active_message_id,
+ queue_persisted=None,
+ )
+
+ if show_status is not None and show_status.state == DISPATCH_ACCEPTED:
+ current_message_id = show_status.message_id
+ current_message_type = None
+ if current_message_id:
+ with get_cached_sqlite_engine().connect() as conn:
+ current_message_type = conn.execute(
+ select(messages.c.type).where(
+ messages.c.id == current_message_id,
+ messages.c.session_id == sid,
+ )
+ ).scalar_one_or_none()
+ return JSONResponse(
+ status_code=202,
+ content={
+ "ok": True,
+ "duplicate": True,
+ "session_id": session_id,
+ **(
+ {"message_id": current_message_id}
+ if current_message_id
+ else {}
+ ),
+ **(
+ {"message_type": current_message_type}
+ if current_message_type
+ else {}
+ ),
+ **(
+ {"queued": True}
+ if current_message_type == messages_service.QUEUED_TYPE
+ else {}
+ ),
+ },
+ )
+ if show_status is not None and show_status.state == DISPATCH_ARCHIVED:
+ return JSONResponse(
+ status_code=409,
+ content={"ok": False, "code": "session_archived"},
+ )
+ if (
+ show_status is None
+ or show_status.state != DISPATCH_IN_FLIGHT
+ or show_status.owner != dispatch_owner
+ ):
+ if show_status is None or show_status.state != DISPATCH_IN_FLIGHT:
+ return JSONResponse(
+ status_code=409,
+ content={"ok": False, "code": "show_dispatch_not_claimed"},
+ )
+ return JSONResponse(
+ status_code=202,
+ content={
+ "ok": True,
+ "duplicate": True,
+ "dispatch_pending": True,
+ "session_id": session_id,
+ },
+ )
+
+ if not show_event_id and isinstance(user_message_id, str) and user_message_id and sid:
+ from sqlalchemy import select
+ from storage.models import messages
+
+ active = manager.in_flight.get(sid)
+ active_message_id = str(
+ getattr(getattr(active, "context", None), "message_id", None) or ""
+ ).strip()
+ with get_cached_sqlite_engine().connect() as conn:
+ reserved_type = conn.execute(
+ select(messages.c.type).where(
+ messages.c.id == user_message_id,
+ messages.c.session_id == sid,
+ )
+ ).scalar_one_or_none()
+ if (
+ active_message_id == user_message_id
+ and reserved_type == messages_service.PENDING_TYPE
+ ):
+ with get_cached_sqlite_engine().begin() as conn:
+ messages_service.promote_pending(conn, user_message_id, "user")
+ reserved_type = "user"
+ if active_message_id == user_message_id or reserved_type == "user":
+ return JSONResponse(
+ status_code=202,
+ content={
+ "ok": True,
+ "duplicate": True,
+ "session_id": session_id,
+ "message_id": user_message_id,
+ **({"message_type": reserved_type} if reserved_type else {}),
+ },
+ )
+ if reserved_type == messages_service.QUEUED_TYPE:
+ return JSONResponse(
+ status_code=202,
+ content={
+ "ok": True,
+ "queued": True,
+ "duplicate": True,
+ "session_id": session_id,
+ "message_id": user_message_id,
+ "message_type": messages_service.QUEUED_TYPE,
+ },
+ )
+
+ submission = await manager.submit(sid, context, text, enqueue=_enqueue)
+ settled_message_id = user_message_id
+ settled_type = None
+ if show_event_id and sid and dispatch_owner:
+ from core.show_session_events import (
+ DISPATCH_ACCEPTED,
+ DISPATCH_ARCHIVED,
+ DISPATCH_FAILED,
+ observe_and_settle_show_dispatch,
+ )
+
+ with get_cached_sqlite_engine().begin() as conn:
+ show_status, settled_type = observe_and_settle_show_dispatch(
+ conn,
+ show_event_id,
+ session_id=sid,
+ owner=dispatch_owner,
+ active_message_id=_active_message_id(),
+ queue_persisted=submission.queue_persisted,
+ )
+ if show_status is None:
+ return JSONResponse(
+ status_code=409,
+ content={"ok": False, "code": "show_event_not_found"},
+ )
+ if show_status.state == DISPATCH_ARCHIVED:
+ return JSONResponse(
+ status_code=409,
+ content={"ok": False, "code": "session_archived"},
+ )
+ if show_status.state == DISPATCH_FAILED:
+ return JSONResponse(
+ status_code=409,
+ content={"ok": False, "code": "show_dispatch_reservation_lost"},
+ )
+ if show_status.state != DISPATCH_ACCEPTED:
+ return JSONResponse(
+ status_code=409,
+ content={"ok": False, "code": "show_dispatch_claim_lost"},
+ )
+ settled_message_id = show_status.message_id
+
+ if (
+ not show_event_id
+ and isinstance(settled_message_id, str)
+ and settled_message_id
+ and sid
+ ):
+ from sqlalchemy import select
+ from storage.models import messages
+
+ with get_cached_sqlite_engine().connect() as conn:
+ settled_type = conn.execute(
+ select(messages.c.type).where(
+ messages.c.id == settled_message_id,
+ messages.c.session_id == sid,
+ )
+ ).scalar_one_or_none()
+
+ if submission.route == "enqueued":
+ # An idle session can already have queue rows left by Stop. ``submit``
+ # may drain synchronously before returning. The Show path uses the same
+ # observed settlement that decided acceptance; ordinary Chat reads its
+ # message once above. Neither response infers durability from the route.
+ if settled_type != messages_service.QUEUED_TYPE:
+ return JSONResponse(
+ status_code=202,
+ content={
+ "ok": True,
+ "drained": True,
+ "session_id": session_id,
+ **(
+ {"message_id": settled_message_id}
+ if settled_type
+ else {}
+ ),
+ **({"message_type": settled_type} if settled_type else {}),
+ },
+ )
return JSONResponse(
status_code=202,
- content={"ok": True, "queued": True, "session_id": session_id, "message_id": user_message_id},
+ content={
+ "ok": True,
+ "queued": True,
+ "session_id": session_id,
+ "message_id": settled_message_id,
+ "message_type": messages_service.QUEUED_TYPE,
+ },
)
- return JSONResponse(status_code=202, content={"ok": True, "session_id": session_id})
+ return JSONResponse(
+ status_code=202,
+ content={
+ "ok": True,
+ "session_id": session_id,
+ **({"message_id": settled_message_id} if settled_type else {}),
+ **({"message_type": settled_type} if settled_type else {}),
+ },
+ )
@app.post("/internal/reconcile-platforms")
async def _reconcile_platforms() -> Any:
@@ -730,7 +909,7 @@ async def _build_dispatch_payload(payload: dict[str, Any]) -> tuple[str, Message
channel_id=payload.get("channel_id"),
platform=payload.get("platform"),
thread_id=payload.get("thread_id"),
- message_id=payload.get("message_id"),
+ message_id=payload.get("message_id") or payload.get("user_message_id"),
files=files,
)
return text, context
diff --git a/core/session_turns.py b/core/session_turns.py
index bd63207ce..9663842c1 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -21,10 +21,10 @@ import json
import logging
from dataclasses import dataclass
from datetime import datetime, timezone
-from typing import TYPE_CHECKING, Any, Callable, Optional
+from typing import TYPE_CHECKING, Any, Callable, Literal, Optional
-from sqlalchemy import select
-from sqlalchemy.engine import Engine
+from sqlalchemy import select, update
+from sqlalchemy.engine import Connection, Engine
from sqlalchemy.exc import IntegrityError
from core.web_push_notifications import WEB_PUSH_USER_KEY_METADATA, WEB_PUSH_USER_KEYS_METADATA
@@ -75,6 +75,7 @@ def _as_backend_activity_item(item: dict[str, Any]) -> dict[str, Any]:
# a plain human turn (#84). Its PRESENCE also marks the row as a scheduled segment
# (vs a user send) for flush_queue.
SCHEDULED_PROVENANCE_KEY = "scheduled_provenance"
+QUEUED_DISPATCH_TEXT_KEY = "_queued_dispatch_text"
SCHEDULED_QUEUE_MERGE_WINDOW_SECONDS = 60
SCHEDULED_QUEUE_BURST_HINT_THRESHOLD = 3
SCHEDULED_QUEUE_FULL_DETAIL_LIMIT = 3
@@ -93,6 +94,45 @@ _FLUSH_REBUILT_KEYS = frozenset(
SCHEDULED_TARGET_AGENT_KEY = "scheduled_target_agent_name"
+def queue_pending_user_message(conn: Connection, message_id: str, dispatch_text: str) -> bool:
+ """Move a reserved user row into the queue.
+
+ Queue rows keep user-visible transcript text in ``content_text``. The prompt
+ submitted by an entry point may be richer (attachment paths, Show event IDs,
+ reply guidance), so store that separately for ``flush_queue`` to replay.
+ This runs only from ``SessionTurnManager.submit``'s enqueue callback.
+ """
+ queueable_types = (messages_service.PENDING_TYPE,)
+ raw_metadata = conn.execute(
+ select(messages.c.metadata_json).where(
+ messages.c.id == message_id,
+ messages.c.type.in_(queueable_types),
+ )
+ ).scalar_one_or_none()
+ if raw_metadata is None:
+ return False
+ try:
+ metadata = json.loads(raw_metadata or "{}")
+ except (TypeError, json.JSONDecodeError):
+ metadata = {}
+ if not isinstance(metadata, dict):
+ metadata = {}
+ metadata[QUEUED_DISPATCH_TEXT_KEY] = dispatch_text
+ result = conn.execute(
+ update(messages)
+ .where(
+ messages.c.id == message_id,
+ messages.c.type.in_(queueable_types),
+ )
+ .values(
+ type=messages_service.QUEUED_TYPE,
+ metadata_json=json.dumps(metadata),
+ updated_at=_utc_now_iso(),
+ )
+ )
+ return bool(result.rowcount)
+
+
def capture_scheduled_provenance(context: "MessageContext") -> dict:
"""Capture the scheduled run's provenance to persist on its queued row so
flush_queue can restore it (#84):
@@ -256,6 +296,21 @@ def _collect_scheduled_segment(rows: list[dict]) -> list[dict]:
return segment
+def _collect_user_segment(rows: list[dict]) -> list[dict]:
+ """Collect one user turn without coalescing durable message identities."""
+ segment: list[dict] = []
+ for row in rows:
+ if _scheduled_provenance(row) is not None:
+ break
+ native_message_id = str(row.get("native_message_id") or "").strip()
+ if native_message_id:
+ if not segment:
+ segment.append(row)
+ break
+ segment.append(row)
+ return segment
+
+
def _build_scheduled_segment_text(segment: list[dict]) -> str:
texts = [str(row.get("text") or "") for row in segment if str(row.get("text") or "")]
if not texts:
@@ -540,6 +595,84 @@ def _scheduled_claimed_queue_row_ids(conn: Any, segment: list[dict]) -> set[str]
return claimed_row_ids
+def _promote_merged_user_segment(
+ conn: Connection,
+ segment: list[dict[str, Any]],
+ *,
+ text: str,
+ attachments: list[dict[str, Any]],
+ metadata: Optional[dict[str, Any]],
+ author_id: Optional[str],
+) -> dict[str, Any]:
+ """Replace a queued segment with one freshly ordered visible user message.
+
+ ``messages`` sort by ``(created_at, id)`` and ids encode creation time. Reusing
+ an old queued id with a new timestamp makes that pair contradictory, so mint
+ both together and atomically repoint every dependent record.
+ """
+ canonical = segment[0]
+ native_message_ids = [
+ str(row.get("native_message_id") or "").strip()
+ for row in segment
+ if str(row.get("native_message_id") or "").strip()
+ ]
+ if native_message_ids and len(segment) != 1:
+ raise ValueError("independently identified user rows must flush as separate segments")
+ merged_content: dict[str, Any] = {"text": text}
+ if attachments:
+ merged_content["attachments"] = attachments
+ visible = messages_service.append(
+ conn,
+ scope_id=canonical.get("scope_id"),
+ session_id=str(canonical["session_id"]),
+ platform=str(canonical.get("platform") or "avibe"),
+ author="user",
+ message_type="user",
+ text=text,
+ content=merged_content,
+ metadata=metadata,
+ author_id=author_id,
+ source="user",
+ parent_native_message_id=canonical.get("parent_native_message_id"),
+ delivered_at=canonical.get("delivered_at"),
+ read_at=canonical.get("read_at"),
+ )
+ source_ids = [str(row["id"]) for row in segment]
+ visible_id = str(visible["id"])
+ _repoint_message_dependents(conn, source_ids, visible_id)
+ messages_service.delete_queued(conn, source_ids)
+
+ native_message_id = native_message_ids[0] if native_message_ids else None
+ if native_message_id:
+ conn.execute(
+ update(messages)
+ .where(messages.c.id == visible_id)
+ .values(native_message_id=native_message_id)
+ )
+ visible["native_message_id"] = native_message_id
+ return visible
+
+
+def _repoint_message_dependents(
+ conn: Connection,
+ source_ids: list[str],
+ target_id: str,
+) -> None:
+ """Retarget every foreign key to messages merged into one canonical row."""
+ for table in messages.metadata.tables.values():
+ if table is messages:
+ continue
+ for foreign_key in table.foreign_keys:
+ if foreign_key.column.table is not messages or foreign_key.column.name != messages.c.id.name:
+ continue
+ column = foreign_key.parent
+ conn.execute(
+ update(table)
+ .where(column.in_(source_ids))
+ .values({column.name: target_id})
+ )
+
+
@dataclass
class Turn:
"""The one active turn for an avibe session — the EXECUTION half of the FSM
@@ -582,6 +715,14 @@ class Turn:
cancel_settled_by: Optional[str] = None
+@dataclass(frozen=True)
+class TurnSubmissionResult:
+ """Routing decision plus the enqueue callback's durable-write result."""
+
+ route: Literal["ran", "enqueued"]
+ queue_persisted: bool | None = None
+
+
class SessionTurnManager:
"""Owns the live per-session turn state + lifecycle for avibe sessions.
@@ -815,23 +956,27 @@ class SessionTurnManager:
text: str,
*,
source: str = SOURCE_HUMAN,
- enqueue: Optional[Callable[[], None]] = None,
- ) -> str:
+ enqueue: Optional[Callable[[], bool]] = None,
+ ) -> TurnSubmissionResult:
"""Unified turn entry for BOTH Chat and the scheduler: idle → run now; busy
(or a pre-existing send-while-busy queue) → enqueue and run later.
- Returns ``"ran"`` or ``"enqueued"``. The busy / pre-existing-queue decision,
- the idle-with-queue drain, and the run are unified here; the caller supplies
- ``enqueue`` — a 0-arg callable that persists the SOURCE-specific queued row
- (Chat promotes its pre-saved pending row; the scheduler appends a harness
- row) — because that row's shape depends on the request. The in_flight check
- and the enqueue have no ``await`` between them (single-threaded loop), so a
- running turn cannot end + flush in the gap — the enqueue stays atomic.
+ The result separates the routing decision (``route``) from whether the
+ SOURCE-specific enqueue callback actually persisted its row
+ (``queue_persisted``). Chat promotes its pre-saved pending row; the
+ scheduler appends a harness row. Their shapes differ, so the caller owns the
+ write and reports its durable result through the callback.
+
+ The in_flight check and callback have no ``await`` between them, which only
+ prevents this event loop from finishing + flushing the active turn in that
+ gap. It does NOT make the callback atomic with external transactions such as
+ session archival; callers must use ``queue_persisted`` (and any domain-owned
+ post-submit observation) rather than infer durability from ``route``.
"""
if not (isinstance(session_id, str) and session_id):
# No session key (CLI-style) — just run; nothing to queue against.
await self._run(None, context, text, source=source)
- return "ran"
+ return TurnSubmissionResult(route="ran")
backend = self._context_backend(context)
entry = self.in_flight.get(session_id)
@@ -847,9 +992,8 @@ class SessionTurnManager:
with self._sqlite_engine().connect() as conn:
should_enqueue = bool(messages_service.list_queued(conn, session_id))
if should_enqueue:
- if enqueue is not None:
- enqueue()
- if busy or backend in self._draining_backends:
+ queue_persisted = bool(enqueue()) if enqueue is not None else False
+ if queue_persisted and (busy or backend in self._draining_backends):
# The row joins the active turn's queue and stays until it drains —
# surface the queue growth NOW so the UI reflects it immediately
# (the later flush emits its own queue.updated when it pops). This
@@ -857,14 +1001,18 @@ class SessionTurnManager:
from core.inbox_events import bus
bus.publish("queue.updated", {"session_id": session_id})
- else:
+ elif not busy and backend not in self._draining_backends:
# Idle + pre-existing queue → no running turn to flush behind, so
- # drain the whole queue (this row included) now, in order. flush_queue
- # publishes queue.updated itself.
+ # drain the durable queue now, in order. If this callback lost an
+ # archival race, only pre-existing rows remain. flush_queue publishes
+ # queue.updated itself.
await self.flush_queue(session_id)
- return "enqueued"
+ return TurnSubmissionResult(
+ route="enqueued",
+ queue_persisted=queue_persisted,
+ )
await self._run(session_id, context, text, source=source)
- return "ran"
+ return TurnSubmissionResult(route="ran")
async def _run(
self,
@@ -1009,13 +1157,15 @@ class SessionTurnManager:
"""Drain the send-while-busy queue ONE segment per call — the turn's
completion re-flushes the next, so segments run in order, one at a time.
- A leading run of consecutive USER rows is merged into a single user turn (the
- user's choice — one dispatch, not N). A SCHEDULED row (it carries stored
- provenance) is NOT merged: it runs as its OWN ``SOURCE_SCHEDULED`` turn with
- its delivery / attribution provenance restored, so a scheduled run that was
- enqueued behind an active turn keeps its suppress-delivery / delivery-target /
- source when it finally runs (#84). Returns True if a turn was started, False
- on an empty queue / failure."""
+ A leading run of anonymous USER rows is merged into one user turn (the
+ user's choice — one dispatch, not N). A row with ``native_message_id`` is
+ already an independently addressable event and therefore runs as its own
+ segment. A SCHEDULED row (it carries stored provenance) is NOT merged: it
+ runs as its OWN ``SOURCE_SCHEDULED`` turn with its delivery / attribution
+ provenance restored, so a scheduled run that was enqueued behind an active
+ turn keeps its suppress-delivery / delivery-target / source when it finally
+ runs (#84). Returns True if a turn was started, False on an empty queue /
+ failure."""
from core.inbox_events import bus
from core.workbench_media import file_attachments_from_specs, resolve_attachment_specs
from storage.background import run_update_event_transaction
@@ -1047,6 +1197,7 @@ class SessionTurnManager:
pending_agent_run_ids: list[str] = []
pending_scheduled_segment: list[dict] = []
claimed_agent_run_ids: list[str] = []
+ dispatch_text = ""
engine = self._sqlite_engine()
try:
with run_update_event_transaction(engine) as conn:
@@ -1125,17 +1276,20 @@ class SessionTurnManager:
scheduled_text = coalesced_prompt
pending_scheduled_segment = segment
else:
- # User segment: the leading run of consecutive non-scheduled rows
- # (stop at the first scheduled row so it stays its own turn).
- segment = []
- for r in rows:
- if _scheduled_provenance(r) is not None:
- break
- segment.append(r)
- if segment and not pending_agent_run_ids:
+ segment = _collect_user_segment(rows)
+ if is_scheduled and segment and not pending_agent_run_ids:
messages_service.delete_queued(conn, [r["id"] for r in segment])
if not is_scheduled:
- texts = [r.get("text") for r in segment if (r.get("text") or "").strip()]
+ texts = [str(r.get("text") or "") for r in segment if str(r.get("text") or "").strip()]
+ dispatch_texts = [
+ str((r.get("metadata") or {}).get(QUEUED_DISPATCH_TEXT_KEY) or r.get("text") or "")
+ for r in segment
+ if str(
+ (r.get("metadata") or {}).get(QUEUED_DISPATCH_TEXT_KEY)
+ or r.get("text")
+ or ""
+ ).strip()
+ ]
# Carry attachments queued in this user segment so a file
# attached while the agent was busy still reaches the merged
# turn. An attachment-ONLY segment has empty texts but must
@@ -1146,6 +1300,7 @@ class SessionTurnManager:
for att in ((r.get("content") or {}).get("attachments") or [])
]
if not texts and not queued_attachments:
+ messages_service.delete_queued(conn, [r["id"] for r in segment])
return False
user_owners = list(
dict.fromkeys(
@@ -1156,24 +1311,24 @@ class SessionTurnManager:
)
)
user_owner = user_owners[0] if len(user_owners) == 1 else None
- user_metadata = None
+ user_metadata = dict(segment[0].get("metadata") or {})
+ user_metadata.pop(QUEUED_DISPATCH_TEXT_KEY, None)
+ user_metadata.pop(WEB_PUSH_USER_KEY_METADATA, None)
+ user_metadata.pop(WEB_PUSH_USER_KEYS_METADATA, None)
if user_owner:
- user_metadata = {WEB_PUSH_USER_KEY_METADATA: user_owner}
+ user_metadata[WEB_PUSH_USER_KEY_METADATA] = user_owner
elif user_owners:
- user_metadata = {WEB_PUSH_USER_KEYS_METADATA: user_owners}
+ user_metadata[WEB_PUSH_USER_KEYS_METADATA] = user_owners
attachment_specs = resolve_attachment_specs(
conn, session_id=session_id, attachments=queued_attachments
)
- user_row = messages_service.append(
+ visible_text = "\n".join(texts)
+ dispatch_text = "\n".join(dispatch_texts)
+ user_row = _promote_merged_user_segment(
conn,
- scope_id=segment[0]["scope_id"],
- session_id=session_id,
- platform="avibe",
- author="user",
- source="user",
- message_type="user",
- text="\n".join(texts),
- content={"attachments": queued_attachments} if queued_attachments else None,
+ segment,
+ text=visible_text,
+ attachments=queued_attachments,
metadata=user_metadata,
author_id=user_owner,
)
@@ -1199,7 +1354,8 @@ class SessionTurnManager:
if not is_scheduled:
# Carry the queued segment's uploaded files into the merged turn.
context.files = file_attachments_from_specs(attachment_specs)
- await self._run(session_id, context, user_row.get("text") or "")
+ context.message_id = user_row["id"]
+ await self._run(session_id, context, dispatch_text)
else:
# Restore the scheduled run's delivery / source provenance onto the rebuilt
# (fresh-routing) context, then run as SOURCE_SCHEDULED — not a plain user
diff --git a/core/show_session_events.py b/core/show_session_events.py
index b38cf081c..a63110484 100644
--- a/core/show_session_events.py
+++ b/core/show_session_events.py
@@ -2,21 +2,25 @@ from __future__ import annotations
import hashlib
import json
+import os
+import threading
import uuid
-from contextlib import ExitStack
+from contextlib import ExitStack, contextmanager
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
-from typing import Any
+from typing import Any, Iterator
-from sqlalchemy import select, update
+from sqlalchemy import delete, select, update
from config import paths
+from config.v2_config import V2Config
from core.services import sessions as workbench_sessions_service
from storage import messages_service
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state, resolve_primary_platform_from_config
-from storage.models import agent_sessions, show_session_events
+from storage.models import agent_sessions, media_objects, messages, show_session_events
+from vibe.i18n import t as i18n_t
DEFAULT_MARK_SCOPE = "default"
HUMAN_EVENT_TYPES = {
@@ -55,6 +59,32 @@ ASSISTANT_MARK_EVENT_TYPES = {
"assistant.mark.updated",
"assistant.mark.resolved",
}
+_EVENT_REQUEST_FINGERPRINT_KEY = "__avibe_request_fingerprint"
+DISPATCH_NONE = "none"
+DISPATCH_IN_FLIGHT = "in_flight"
+DISPATCH_ACCEPTED = "accepted"
+DISPATCH_FAILED = "failed"
+DISPATCH_ARCHIVED = "archived"
+SHOW_DISPATCH_CLAIM_TTL_SECONDS = 60
+_DISPATCH_STATES = {
+ DISPATCH_NONE,
+ DISPATCH_IN_FLIGHT,
+ DISPATCH_ACCEPTED,
+ DISPATCH_FAILED,
+ DISPATCH_ARCHIVED,
+}
+_TERMINAL_DISPATCH_STATES = {
+ DISPATCH_ACCEPTED,
+ DISPATCH_FAILED,
+ DISPATCH_ARCHIVED,
+}
+SHOW_EVENT_ERROR_I18N_KEYS = {
+ "event_id_conflict": "show.event.idConflict",
+ "show_event_dispatch_failed": "show.event.dispatchFailed",
+ "show_event_dispatch_pending": "show.event.acceptanceUnknown",
+}
+_ACTIVE_SHOW_DISPATCH_ATTEMPTS: set[str] = set()
+_ACTIVE_SHOW_DISPATCH_ATTEMPTS_LOCK = threading.Lock()
class ShowSessionEventError(ValueError):
@@ -63,6 +93,533 @@ class ShowSessionEventError(ValueError):
self.code = code
+def localized_show_event_error(code: str) -> ShowSessionEventError:
+ """Build a localized user-facing Show event error for a stable code."""
+ translation_key = SHOW_EVENT_ERROR_I18N_KEYS.get(code)
+ if translation_key is None:
+ raise ValueError(f"unsupported localized Show event error code: {code}")
+ try:
+ language = V2Config.load().language
+ except Exception:
+ language = "en"
+ return ShowSessionEventError(i18n_t(translation_key, language), code=code)
+
+
+def show_event_requests_dispatch(event: dict[str, Any]) -> bool:
+ """Whether a normalized Show event should start an agent turn."""
+ if event.get("actor") != "human":
+ return False
+ if event.get("type") not in {"human.intent.submitted", "human.annotation.created"}:
+ return False
+ payload = event.get("payload")
+ return isinstance(payload, dict) and bool(payload.get("dispatch"))
+
+
+@dataclass(frozen=True)
+class ShowDispatchStatus:
+ state: str
+ owner: str | None = None
+ claimed_at: str | None = None
+ message_id: str | None = None
+ session_status: str | None = None
+ claimed: bool = False
+
+
+@dataclass(frozen=True)
+class ShowDispatchSettlement:
+ """Observed dispatch lifecycle plus the current transcript presentation."""
+
+ status: ShowDispatchStatus
+ message: dict[str, Any] | None
+ message_promoted: bool = False
+
+ @property
+ def can_publish_message_new(self) -> bool:
+ return bool(
+ self.message_promoted
+ and self.message
+ and self.message.get("type") == "user"
+ and self.status.state in {DISPATCH_ACCEPTED, DISPATCH_FAILED}
+ )
+
+ @property
+ def can_publish_queue_updated(self) -> bool:
+ return bool(
+ self.status.state == DISPATCH_ACCEPTED
+ and self.message
+ and self.message.get("type") == messages_service.QUEUED_TYPE
+ )
+
+ @property
+ def can_report_success(self) -> bool:
+ return bool(
+ self.status.state == DISPATCH_ACCEPTED
+ and self.message
+ and self.message.get("type")
+ in {"user", messages_service.QUEUED_TYPE}
+ )
+
+
+@dataclass(frozen=True)
+class _ShowDispatchOwnerIdentity:
+ pid: int
+ started_at: str
+ attempt_id: str | None
+
+
+def _dispatch_state_payload(raw: Any) -> dict[str, Any]:
+ parsed = _json_loads(raw, {})
+ if not isinstance(parsed, dict):
+ return {"state": DISPATCH_NONE}
+ state = parsed.get("state")
+ if state not in _DISPATCH_STATES:
+ return {"state": DISPATCH_NONE}
+ return parsed
+
+
+def _dispatch_state_json(
+ state: str,
+ *,
+ owner: str | None = None,
+ claimed_at: str | None = None,
+) -> str:
+ if state not in _DISPATCH_STATES:
+ raise ValueError(f"unsupported Show dispatch state: {state}")
+ payload: dict[str, Any] = {"state": state}
+ if state == DISPATCH_IN_FLIGHT:
+ if not owner or not claimed_at:
+ raise ValueError("in-flight Show dispatch state requires owner and claimed_at")
+ payload.update({"owner": owner, "claimed_at": claimed_at})
+ return _json_dumps(payload)
+
+
+def _current_show_dispatch_process_identity() -> tuple[int, str]:
+ from vibe.runtime import process_create_time
+
+ pid = os.getpid()
+ started_at = process_create_time(pid)
+ suffix = f"{started_at:.6f}" if isinstance(started_at, (int, float)) else "unknown"
+ return pid, suffix
+
+
+def _parse_show_dispatch_owner(owner: str | None) -> _ShowDispatchOwnerIdentity | None:
+ if not isinstance(owner, str):
+ return None
+ parts = owner.split(":", 2)
+ if len(parts) < 2:
+ return None
+ try:
+ pid = int(parts[0])
+ except ValueError:
+ return None
+ return _ShowDispatchOwnerIdentity(
+ pid=pid,
+ started_at=parts[1],
+ attempt_id=parts[2] if len(parts) == 3 and parts[2] else None,
+ )
+
+
+@contextmanager
+def show_dispatch_attempt() -> Iterator[str]:
+ """Register one live dispatch attempt and yield its durable claim owner."""
+ pid, started_at = _current_show_dispatch_process_identity()
+ attempt_id = uuid.uuid4().hex
+ with _ACTIVE_SHOW_DISPATCH_ATTEMPTS_LOCK:
+ _ACTIVE_SHOW_DISPATCH_ATTEMPTS.add(attempt_id)
+ try:
+ yield f"{pid}:{started_at}:{attempt_id}"
+ finally:
+ with _ACTIVE_SHOW_DISPATCH_ATTEMPTS_LOCK:
+ _ACTIVE_SHOW_DISPATCH_ATTEMPTS.discard(attempt_id)
+
+
+def _show_dispatch_owner_is_alive(owner: str | None) -> bool:
+ identity = _parse_show_dispatch_owner(owner)
+ if identity is None:
+ return False
+
+ from vibe.runtime import pid_alive, process_create_time
+
+ if not pid_alive(identity.pid):
+ return False
+ if identity.started_at == "unknown":
+ return True
+ try:
+ expected_started_at = float(identity.started_at)
+ except ValueError:
+ return False
+ actual_started_at = process_create_time(identity.pid)
+ return isinstance(actual_started_at, (int, float)) and abs(
+ actual_started_at - expected_started_at
+ ) < 0.001
+
+
+def _show_dispatch_claim_is_stale(claimed_at: str | None) -> bool:
+ try:
+ claimed = datetime.fromisoformat(str(claimed_at).replace("Z", "+00:00"))
+ except ValueError:
+ return True
+ if claimed.tzinfo is None:
+ claimed = claimed.replace(tzinfo=timezone.utc)
+ return (
+ datetime.now(timezone.utc) - claimed.astimezone(timezone.utc)
+ ).total_seconds() >= SHOW_DISPATCH_CLAIM_TTL_SECONDS
+
+
+def _show_dispatch_claim_is_active(
+ owner: str | None,
+ claimed_at: str | None,
+) -> bool:
+ identity = _parse_show_dispatch_owner(owner)
+ if identity is not None and identity.attempt_id is not None:
+ current_pid, current_started_at = _current_show_dispatch_process_identity()
+ if (
+ identity.pid == current_pid
+ and identity.started_at == current_started_at
+ ):
+ with _ACTIVE_SHOW_DISPATCH_ATTEMPTS_LOCK:
+ return identity.attempt_id in _ACTIVE_SHOW_DISPATCH_ATTEMPTS
+ return _show_dispatch_owner_is_alive(owner) or not _show_dispatch_claim_is_stale(
+ claimed_at
+ )
+
+
+def get_show_dispatch_status(
+ conn: Any,
+ event_id: str,
+ *,
+ session_id: str | None = None,
+) -> ShowDispatchStatus | None:
+ query = (
+ select(
+ show_session_events.c.dispatch_state,
+ show_session_events.c.message_id,
+ agent_sessions.c.status.label("session_status"),
+ )
+ .select_from(
+ show_session_events.join(
+ agent_sessions,
+ agent_sessions.c.id == show_session_events.c.session_id,
+ )
+ )
+ .where(show_session_events.c.id == event_id)
+ )
+ if session_id is not None:
+ query = query.where(show_session_events.c.session_id == session_id)
+ row = conn.execute(query.limit(1)).mappings().first()
+ if row is None:
+ return None
+ payload = _dispatch_state_payload(row["dispatch_state"])
+ return ShowDispatchStatus(
+ state=str(payload["state"]),
+ owner=_text_or_none(payload.get("owner")),
+ claimed_at=_text_or_none(payload.get("claimed_at")),
+ message_id=_text_or_none(row.get("message_id")),
+ session_status=_text_or_none(row.get("session_status")),
+ )
+
+
+def claim_show_dispatch(
+ conn: Any,
+ event_id: str,
+ *,
+ session_id: str,
+ owner: str,
+) -> ShowDispatchStatus | None:
+ """Atomically claim a retryable or provably abandoned Show dispatch."""
+ for _attempt in range(3):
+ row = conn.execute(
+ select(
+ show_session_events.c.dispatch_state,
+ show_session_events.c.message_id,
+ agent_sessions.c.status.label("session_status"),
+ )
+ .select_from(
+ show_session_events.join(
+ agent_sessions,
+ agent_sessions.c.id == show_session_events.c.session_id,
+ )
+ )
+ .where(
+ show_session_events.c.id == event_id,
+ show_session_events.c.session_id == session_id,
+ )
+ .limit(1)
+ ).mappings().first()
+ if row is None:
+ return None
+ payload = _dispatch_state_payload(row["dispatch_state"])
+ state = str(payload["state"])
+ status = ShowDispatchStatus(
+ state=state,
+ owner=_text_or_none(payload.get("owner")),
+ claimed_at=_text_or_none(payload.get("claimed_at")),
+ message_id=_text_or_none(row.get("message_id")),
+ session_status=_text_or_none(row.get("session_status")),
+ )
+ if status.session_status == "archived":
+ if state not in {DISPATCH_ACCEPTED, DISPATCH_ARCHIVED}:
+ if settle_show_dispatch(
+ conn,
+ event_id,
+ session_id=session_id,
+ owner=None,
+ state=DISPATCH_ARCHIVED,
+ ):
+ return ShowDispatchStatus(
+ state=DISPATCH_ARCHIVED,
+ message_id=status.message_id,
+ session_status=status.session_status,
+ )
+ continue
+ return status
+ if state in {DISPATCH_ACCEPTED, DISPATCH_ARCHIVED}:
+ return status
+ if (
+ state == DISPATCH_IN_FLIGHT
+ and _show_dispatch_claim_is_active(status.owner, status.claimed_at)
+ ):
+ return status
+
+ claimed_at = _utc_now_iso()
+ raw_state = row["dispatch_state"]
+ result = conn.execute(
+ update(show_session_events)
+ .where(
+ show_session_events.c.id == event_id,
+ show_session_events.c.session_id == session_id,
+ show_session_events.c.dispatch_state == raw_state,
+ )
+ .values(
+ dispatch_state=_dispatch_state_json(
+ DISPATCH_IN_FLIGHT,
+ owner=owner,
+ claimed_at=claimed_at,
+ )
+ )
+ )
+ if result.rowcount:
+ return ShowDispatchStatus(
+ state=DISPATCH_IN_FLIGHT,
+ owner=owner,
+ claimed_at=claimed_at,
+ message_id=status.message_id,
+ session_status=status.session_status,
+ claimed=True,
+ )
+ return get_show_dispatch_status(conn, event_id, session_id=session_id)
+
+
+def settle_show_dispatch(
+ conn: Any,
+ event_id: str,
+ *,
+ session_id: str,
+ owner: str | None,
+ state: str,
+) -> bool:
+ """Persist one observed terminal outcome for the matching claim owner."""
+ if state not in _TERMINAL_DISPATCH_STATES:
+ raise ValueError(f"unsupported terminal Show dispatch state: {state}")
+ row = conn.execute(
+ select(show_session_events.c.dispatch_state).where(
+ show_session_events.c.id == event_id,
+ show_session_events.c.session_id == session_id,
+ )
+ ).scalar_one_or_none()
+ if row is None:
+ return False
+ payload = _dispatch_state_payload(row)
+ if payload["state"] == state:
+ return True
+ if owner is None:
+ if state != DISPATCH_ARCHIVED:
+ raise ValueError("ownerless Show dispatch settlement must be archived")
+ if payload["state"] in {DISPATCH_ACCEPTED, DISPATCH_ARCHIVED}:
+ return False
+ elif payload["state"] in _TERMINAL_DISPATCH_STATES:
+ return False
+ elif payload["state"] != DISPATCH_IN_FLIGHT or payload.get("owner") != owner:
+ return False
+ result = conn.execute(
+ update(show_session_events)
+ .where(
+ show_session_events.c.id == event_id,
+ show_session_events.c.session_id == session_id,
+ show_session_events.c.dispatch_state == row,
+ )
+ .values(dispatch_state=_dispatch_state_json(state))
+ )
+ return bool(result.rowcount)
+
+
+def observe_and_settle_show_dispatch(
+ conn: Any,
+ event_id: str,
+ *,
+ session_id: str,
+ owner: str,
+ active_message_id: str | None,
+ queue_persisted: bool | None,
+) -> tuple[ShowDispatchStatus | None, str | None]:
+ """Settle from the durable reservation observed after unified submission."""
+ row = (
+ conn.execute(
+ select(
+ show_session_events.c.dispatch_state,
+ show_session_events.c.message_id,
+ agent_sessions.c.status.label("session_status"),
+ messages.c.id.label("stored_message_id"),
+ messages.c.type.label("message_type"),
+ )
+ .select_from(
+ show_session_events.join(
+ agent_sessions,
+ agent_sessions.c.id == show_session_events.c.session_id,
+ ).outerjoin(
+ messages,
+ (messages.c.id == show_session_events.c.message_id)
+ & (messages.c.session_id == show_session_events.c.session_id),
+ )
+ )
+ .where(
+ show_session_events.c.id == event_id,
+ show_session_events.c.session_id == session_id,
+ )
+ .limit(1)
+ )
+ .mappings()
+ .first()
+ )
+ if row is None:
+ return None, None
+
+ payload = _dispatch_state_payload(row["dispatch_state"])
+ status = ShowDispatchStatus(
+ state=str(payload["state"]),
+ owner=_text_or_none(payload.get("owner")),
+ claimed_at=_text_or_none(payload.get("claimed_at")),
+ message_id=_text_or_none(row.get("message_id")),
+ session_status=_text_or_none(row.get("session_status")),
+ )
+ message_type = _text_or_none(row.get("message_type"))
+ if status.state in _TERMINAL_DISPATCH_STATES:
+ return status, message_type
+ if status.state != DISPATCH_IN_FLIGHT or status.owner != owner:
+ return status, message_type
+
+ stored_message_id = _text_or_none(row.get("stored_message_id"))
+ started = bool(stored_message_id and stored_message_id == active_message_id)
+ queued = bool(
+ stored_message_id
+ and message_type == messages_service.QUEUED_TYPE
+ )
+ reservation_observed = started or queued
+ if queue_persisted is False and not reservation_observed:
+ terminal_state = (
+ DISPATCH_ARCHIVED
+ if status.session_status == "archived"
+ else DISPATCH_FAILED
+ )
+ elif reservation_observed:
+ terminal_state = DISPATCH_ACCEPTED
+ elif status.session_status == "archived":
+ terminal_state = DISPATCH_ARCHIVED
+ else:
+ terminal_state = DISPATCH_FAILED
+
+ if not settle_show_dispatch(
+ conn,
+ event_id,
+ session_id=session_id,
+ owner=owner,
+ state=terminal_state,
+ ):
+ return get_show_dispatch_status(conn, event_id, session_id=session_id), message_type
+ return (
+ ShowDispatchStatus(
+ state=terminal_state,
+ message_id=status.message_id,
+ session_status=status.session_status,
+ ),
+ message_type,
+ )
+
+
+def reconcile_show_dispatch_settlement(
+ conn: Any,
+ event_id: str,
+ *,
+ session_id: str,
+) -> ShowDispatchSettlement | None:
+ """Read back one dispatch settlement and repair its transcript presentation."""
+
+ row = (
+ conn.execute(
+ select(
+ show_session_events.c.dispatch_state,
+ show_session_events.c.message_id,
+ agent_sessions.c.scope_id,
+ agent_sessions.c.status.label("session_status"),
+ messages.c.type.label("message_type"),
+ )
+ .select_from(
+ show_session_events.join(
+ agent_sessions,
+ agent_sessions.c.id == show_session_events.c.session_id,
+ ).outerjoin(
+ messages,
+ (messages.c.id == show_session_events.c.message_id)
+ & (messages.c.session_id == show_session_events.c.session_id),
+ )
+ )
+ .where(
+ show_session_events.c.id == event_id,
+ show_session_events.c.session_id == session_id,
+ )
+ .limit(1)
+ )
+ .mappings()
+ .first()
+ )
+ if row is None:
+ return None
+
+ payload = _dispatch_state_payload(row["dispatch_state"])
+ status = ShowDispatchStatus(
+ state=str(payload["state"]),
+ owner=_text_or_none(payload.get("owner")),
+ claimed_at=_text_or_none(payload.get("claimed_at")),
+ message_id=_text_or_none(row.get("message_id")),
+ session_status=_text_or_none(row.get("session_status")),
+ )
+ message_id = status.message_id
+ message_promoted = False
+ if (
+ message_id
+ and row.get("message_type") == messages_service.PENDING_TYPE
+ and status.state in {DISPATCH_ACCEPTED, DISPATCH_FAILED}
+ ):
+ message_promoted = messages_service.promote_pending(
+ conn,
+ message_id,
+ "user",
+ )
+
+ event = _existing_event_payload(
+ conn,
+ event_id=event_id,
+ session_id=session_id,
+ scope_id=_text_or_none(row.get("scope_id")),
+ )
+ message = event.get("message") if event is not None else None
+ return ShowDispatchSettlement(
+ status=status,
+ message=message if isinstance(message, dict) else None,
+ message_promoted=message_promoted,
+ )
+
+
@dataclass(frozen=True)
class ShowSessionEventStore:
db_path: Path | None = None
@@ -79,18 +636,68 @@ class ShowSessionEventStore:
def close(self) -> None:
self.engine.dispose()
+ def get_dispatch_status(
+ self,
+ session_id: str,
+ event_id: str,
+ ) -> ShowDispatchStatus | None:
+ with self.engine.connect() as conn:
+ return get_show_dispatch_status(conn, event_id, session_id=session_id)
+
+ def reconcile_dispatch_settlement(
+ self,
+ session_id: str,
+ event_id: str,
+ ) -> ShowDispatchSettlement | None:
+ with self.engine.begin() as conn:
+ return reconcile_show_dispatch_settlement(
+ conn,
+ event_id,
+ session_id=session_id,
+ )
+
+ def reconcile_dispatch_messages(self) -> int:
+ """Repair terminal Show events whose transcript row stayed pending."""
+
+ with self.engine.begin() as conn:
+ rows = conn.execute(
+ select(
+ show_session_events.c.id,
+ show_session_events.c.session_id,
+ )
+ .select_from(
+ show_session_events.join(
+ messages,
+ messages.c.id == show_session_events.c.message_id,
+ )
+ )
+ .where(messages.c.type == messages_service.PENDING_TYPE)
+ ).all()
+ reconciled = 0
+ for event_id, session_id in rows:
+ settlement = reconcile_show_dispatch_settlement(
+ conn,
+ str(event_id),
+ session_id=str(session_id),
+ )
+ if settlement is not None and settlement.message_promoted:
+ reconciled += 1
+ return reconciled
+
def append(
self,
session_id: str,
payload: dict[str, Any],
*,
author: dict[str, str] | None = None,
+ reserve_dispatch: bool = False,
) -> dict[str, Any]:
validate_show_event_payload_session(session_id, payload)
event_type = _validate_event_type(payload.get("type"))
actor = _actor_for_event(event_type)
records_author = actor == "human" or (event_type == "assistant.mark.resolved" and author is not None)
event_id = _event_id(payload, {})
+ request_fingerprint = _event_request_fingerprint(event_type, payload)
created_at = _utc_now_iso()
with ExitStack() as cleanup:
@@ -106,6 +713,22 @@ class ShowSessionEventStore:
# events (which dispatch as new agent work) into an archived session.
if session["status"] == "archived":
raise ShowSessionEventError("Agent session is archived.", code="session_archived")
+ existing = _existing_event_payload(
+ conn,
+ event_id=event_id,
+ session_id=session_id,
+ scope_id=session["scope_id"],
+ )
+ if existing is not None:
+ _assert_matching_event_replay(
+ conn,
+ event_id=event_id,
+ session_id=session_id,
+ event_type=event_type,
+ payload=payload,
+ request_fingerprint=request_fingerprint,
+ )
+ return existing
stored_payload = payload
if event_type == "assistant.mark.resolved":
@@ -131,21 +754,56 @@ class ShowSessionEventStore:
)
if records_author:
event_payload["author"] = _normalize_human_author(author)
-
- conn.execute(
- show_session_events.insert().values(
+ requests_dispatch = show_event_requests_dispatch(
+ {"type": event_type, "actor": actor, "payload": event_payload}
+ )
+ inserted = conn.execute(
+ show_session_events.insert().prefix_with("OR IGNORE").values(
id=event_id,
session_id=session_id,
event_type=event_type,
actor=actor,
scope=scope,
anchor_json=_json_dumps(anchor),
- payload_json=_json_dumps(event_payload),
+ payload_json=_json_dumps(
+ {
+ **event_payload,
+ _EVENT_REQUEST_FINGERPRINT_KEY: request_fingerprint,
+ }
+ ),
transcript_text=transcript_text,
message_id=None,
+ dispatch_state=_dispatch_state_json(DISPATCH_NONE),
created_at=created_at,
)
)
+ if inserted.rowcount == 0:
+ _assert_matching_event_replay(
+ conn,
+ event_id=event_id,
+ session_id=session_id,
+ event_type=event_type,
+ payload=payload,
+ request_fingerprint=request_fingerprint,
+ )
+ screenshot = _normalize_json_object(event_payload.get("screenshot"))
+ attachment_id = _text_or_none(screenshot.get("attachmentId"))
+ if attachment_id and screenshot_path:
+ conn.execute(
+ delete(media_objects).where(
+ media_objects.c.token == attachment_id,
+ media_objects.c.local_path == screenshot_path,
+ )
+ )
+ existing = _existing_event_payload(
+ conn,
+ event_id=event_id,
+ session_id=session_id,
+ scope_id=session["scope_id"],
+ )
+ if existing is None:
+ raise RuntimeError(f"show event id conflict without stored row: {event_id}")
+ return existing
message: dict[str, Any] | None = None
message_id: str | None = None
if transcript_text:
@@ -155,6 +813,11 @@ class ShowSessionEventStore:
session_id=session_id,
platform="avibe",
author="agent" if actor in {"assistant", "system"} else "user",
+ message_type=(
+ messages_service.PENDING_TYPE
+ if requests_dispatch and reserve_dispatch
+ else None
+ ),
text=transcript_text,
content={"text": transcript_text, "show_event_type": event_type},
metadata={
@@ -229,6 +892,23 @@ class ShowSessionEventStore:
).mappings().first()
return _row_to_payload(dict(row)) if row is not None else None
+ def get_event(self, session_id: str, event_id: str) -> dict[str, Any] | None:
+ """Return one event with its current transcript reservation state."""
+ with self.engine.connect() as conn:
+ session = conn.execute(
+ select(agent_sessions.c.scope_id)
+ .where(agent_sessions.c.id == session_id)
+ .limit(1)
+ ).first()
+ if session is None:
+ return None
+ return _existing_event_payload(
+ conn,
+ event_id=event_id,
+ session_id=session_id,
+ scope_id=session.scope_id,
+ )
+
def recent_annotation_event_ids(self, session_id: str, *, limit: int = 10) -> list[str]:
effective_limit = min(max(int(limit), 1), 50)
with self.engine.connect() as conn:
@@ -569,6 +1249,110 @@ def _event_id(original_payload: dict[str, Any], event_payload: dict[str, Any]) -
return _text_or_none(original_payload.get("id")) or _new_id("show_evt")
+def _canonical_request_value(raw: Any) -> Any:
+ if isinstance(raw, dict):
+ return {
+ key: _canonical_request_value(value)
+ for key, value in raw.items()
+ if value is not None
+ }
+ if isinstance(raw, list):
+ return [_canonical_request_value(value) for value in raw]
+ return raw
+
+
+def _event_request_content(payload: dict[str, Any]) -> dict[str, Any]:
+ return _canonical_request_value(
+ {
+ key: value
+ for key, value in payload.items()
+ if key not in {"id", "type", "sessionId", "session_id"}
+ }
+ )
+
+
+def _legacy_event_request_content(
+ event_type: str,
+ payload: dict[str, Any],
+) -> dict[str, Any]:
+ if event_type.startswith("assistant.mark."):
+ raw = payload.get("mark") or payload.get("payload")
+ elif event_type == "human.intent.submitted":
+ raw = payload.get("payload")
+ elif event_type in ANNOTATION_EVENT_TYPES:
+ raw = payload.get("annotation") or payload.get("payload")
+ else:
+ raw = payload.get("payload")
+ if isinstance(raw, dict):
+ return raw
+ return _event_request_content(payload)
+
+
+def _event_request_fingerprint(event_type: str, payload: dict[str, Any]) -> str:
+ canonical = json.dumps(
+ {
+ "type": event_type,
+ "payload": _event_request_content(payload),
+ },
+ ensure_ascii=False,
+ separators=(",", ":"),
+ sort_keys=True,
+ )
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
+
+
+def _legacy_request_matches_stored(requested: Any, stored: Any) -> bool:
+ if isinstance(requested, dict):
+ if not isinstance(stored, dict):
+ return False
+ return all(
+ key == "dataUrl" or (key in stored and _legacy_request_matches_stored(value, stored[key]))
+ for key, value in requested.items()
+ )
+ if isinstance(requested, list):
+ return isinstance(stored, list) and len(requested) == len(stored) and all(
+ _legacy_request_matches_stored(requested_item, stored_item)
+ for requested_item, stored_item in zip(requested, stored, strict=True)
+ )
+ return requested == stored
+
+
+def _assert_matching_event_replay(
+ conn: Any,
+ *,
+ event_id: str,
+ session_id: str,
+ event_type: str,
+ payload: dict[str, Any],
+ request_fingerprint: str,
+) -> None:
+ row = conn.execute(
+ select(
+ show_session_events.c.session_id,
+ show_session_events.c.event_type,
+ show_session_events.c.payload_json,
+ ).where(show_session_events.c.id == event_id)
+ ).mappings().first()
+ if row is None:
+ return
+ stored_payload = _json_loads(row.get("payload_json"), {})
+ stored_fingerprint = (
+ stored_payload.get(_EVENT_REQUEST_FINGERPRINT_KEY)
+ if isinstance(stored_payload, dict)
+ else None
+ )
+ matches = row["session_id"] == session_id and row["event_type"] == event_type and (
+ stored_fingerprint == request_fingerprint
+ if isinstance(stored_fingerprint, str)
+ else _legacy_request_matches_stored(
+ _legacy_event_request_content(event_type, payload),
+ stored_payload,
+ )
+ )
+ if not matches:
+ raise localized_show_event_error("event_id_conflict")
+
+
def _format_transcript_header(
family: str,
*,
@@ -697,6 +1481,9 @@ def _format_transcript_text(event_type: str, payload: dict[str, Any], anchor: di
def _row_to_payload(row: dict[str, Any]) -> dict[str, Any]:
+ payload = _json_loads(row.get("payload_json"), {})
+ if isinstance(payload, dict):
+ payload.pop(_EVENT_REQUEST_FINGERPRINT_KEY, None)
return {
"id": row["id"],
"session_id": row["session_id"],
@@ -704,13 +1491,47 @@ def _row_to_payload(row: dict[str, Any]) -> dict[str, Any]:
"actor": row["actor"],
"scope": row["scope"],
"anchor": _json_loads(row.get("anchor_json"), {}),
- "payload": _json_loads(row.get("payload_json"), {}),
+ "payload": payload,
"transcript_text": row.get("transcript_text"),
"message_id": row.get("message_id"),
"created_at": row.get("created_at"),
}
+def _existing_event_payload(
+ conn: Any,
+ *,
+ event_id: str,
+ session_id: str,
+ scope_id: str | None,
+) -> dict[str, Any] | None:
+ row = conn.execute(
+ select(show_session_events).where(
+ show_session_events.c.id == event_id,
+ show_session_events.c.session_id == session_id,
+ )
+ ).mappings().first()
+ if row is None:
+ return None
+ event = _row_to_payload(dict(row))
+ event["scope_id"] = scope_id
+ message_id = event.get("message_id")
+ message = None
+ if isinstance(message_id, str) and message_id:
+ window = messages_service.list_session_messages(
+ conn,
+ session_id=session_id,
+ around_id=message_id,
+ limit=1,
+ )
+ message = next(
+ (item for item in window["messages"] if item.get("id") == message_id),
+ None,
+ )
+ event["message"] = message
+ return event
+
+
def _required_text(raw: Any, field: str) -> str:
value = _text_or_none(raw)
if not value:
diff --git a/docs/plans/show-session-event-pipeline.md b/docs/plans/show-session-event-pipeline.md
index 45c955a30..c4db91d18 100644
--- a/docs/plans/show-session-event-pipeline.md
+++ b/docs/plans/show-session-event-pipeline.md
@@ -16,8 +16,16 @@ endpoint, stream endpoint, or write token.
- `show_session_events` persists typed events and links transcript messages.
- Private `/show/<session-id>/__show/events` accepts authenticated event POSTs.
- Private and public Show Pages can list and stream events.
-- `dispatch: true` human intent and annotation events stream an agent turn back
- through `show.dispatch` events.
+- `dispatch: true` human intent and annotation events reserve a transcript row
+ keyed by `show:<event-id>`, then enter the same `/internal/dispatch_async`
+ turn path as Chat. The transcript row stays hidden as `pending` until that
+ unified entry starts the turn or promotes it to the shared `queued` state.
+ Dispatch lifecycle belongs to the stable event row, not the transcript row:
+ `none` becomes an `in_flight` claim with owner and claim time, and only the unified
+ controller may write `accepted`; definitive rejection writes retryable
+ `failed`. CLI timeouts query that event state instead of blindly resubmitting.
+ Visible prompts and replies surface through the session-scoped `message.new`
+ stream, while queued prompts surface through `queue.updated`.
- The static Vibe Remote template reads the write token cookie, but managed
runtime pages currently depend on their own generated config and can miss the
token.
diff --git a/docs/plans/workbench-dispatch-architecture.md b/docs/plans/workbench-dispatch-architecture.md
index cbde2c1d2..a26761669 100644
--- a/docs/plans/workbench-dispatch-architecture.md
+++ b/docs/plans/workbench-dispatch-architecture.md
@@ -27,18 +27,17 @@ sections below.
**fire-and-forget**: `POST .../messages` → `/internal/dispatch_async` (202),
reply arrives over the stream. A closed tab can't cancel an in-flight turn.
-2. **Legacy per-turn Chat stream retired (Step 6).** The Chat page's
+2. **Legacy per-turn dispatch stream retired (Step 6, completed for Show in
+ 2026-07).** The Chat page's
`?stream=1` proxy was removed: the ui_server `?stream=1` route branch (the
Chat page is now fire-and-forget). The turn-sink / `on_chunk` machinery stays
— `dispatch_async` drives it with a no-op `on_chunk` to keep `in_flight`
populated (Stop) and to flush the send-while-busy queue on settle.
- **Correction:** `internal_client.stream_dispatch` + the streaming
- `POST /internal/dispatch` endpoint were initially removed too, but the merged
- show-annotation feature (#360) streams a turn back to the Show page via
- `ui_server._run_show_event_dispatch` → `stream_dispatch`, so both were
- restored. The streaming dispatch is NOT dead — it backs the Show-page flow;
- only the Chat `?stream=1` route is gone. (Guarded by
- `test_show_event_dispatch_streams_via_stream_dispatch`.)
+ Show annotations now use the same `POST /internal/dispatch_async` entry with
+ their reserved transcript `message_id`. `SessionTurnManager.submit` decides
+ start versus enqueue; replies arrive on the session-scoped `message.new`
+ stream. `internal_client.stream_dispatch`, `POST /internal/dispatch`, and
+ the unconsumed `show.dispatch` republishing path are removed.
3. **`turn_token` is load-bearing — NOT rolled back.** The plan treated the
per-turn token as scaffolding. It is now the completion guard: `_stream_chunk`
@@ -67,8 +66,13 @@ sections below.
distinct from author role, plus `author_name` / `author_id`. Harness turns
render a Scheduled-task / Watch badge.
- Send-while-busy **queue** + cross-device **draft** reuse the `messages` table
- via `queued` / `draft` / `pending` types (no new table). Stop keeps the queue;
- "立即发送" interrupts + flushes.
+ (no new queue table). A transcript reservation is hidden as `pending`; the
+ unified entry either starts the turn so its caller renders the row as `user`,
+ or moves it to `queued` for the shared drain. For Show events, dispatch
+ lifecycle is stored independently on the stable `show_session_events` row as
+ `none` / `in_flight` / `accepted` / `failed`, so rendering changes and queue
+ replacement cannot erase acceptance or make a retry ambiguous. Stop keeps the
+ queue; "立即发送" interrupts + flushes.
## 1. Why This Document Exists
diff --git a/storage/alembic/versions/20260726_0035_show_event_dispatch_state.py b/storage/alembic/versions/20260726_0035_show_event_dispatch_state.py
new file mode 100644
index 000000000..aff0beaae
--- /dev/null
+++ b/storage/alembic/versions/20260726_0035_show_event_dispatch_state.py
@@ -0,0 +1,52 @@
+"""move Show dispatch lifecycle onto Show events
+
+Revision ID: 20260726_0035
+Revises: 20260724_0034
+Create Date: 2026-07-26
+"""
+
+from __future__ import annotations
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "20260726_0035"
+down_revision = "20260724_0034"
+branch_labels = None
+depends_on = None
+
+_NONE_STATE = '{"state":"none"}'
+_ACCEPTED_STATE = '{"state":"accepted"}'
+
+
+def _columns(bind, table: str) -> set[str]:
+ return {
+ str(row[1])
+ for row in bind.exec_driver_sql(f'pragma table_info("{table}")').fetchall()
+ }
+
+
+def upgrade() -> None:
+ bind = op.get_bind()
+ if "dispatch_state" not in _columns(bind, "show_session_events"):
+ op.add_column(
+ "show_session_events",
+ sa.Column(
+ "dispatch_state",
+ sa.Text(),
+ nullable=False,
+ server_default=_NONE_STATE,
+ ),
+ )
+ op.execute(
+ sa.text(
+ "update show_session_events "
+ "set dispatch_state = :accepted_state"
+ ).bindparams(accepted_state=_ACCEPTED_STATE)
+ )
+
+
+def downgrade() -> None:
+ bind = op.get_bind()
+ if "dispatch_state" in _columns(bind, "show_session_events"):
+ op.drop_column("show_session_events", "dispatch_state")
diff --git a/storage/messages_service.py b/storage/messages_service.py
index a4cab394b..e64b544b2 100644
--- a/storage/messages_service.py
+++ b/storage/messages_service.py
@@ -686,7 +686,13 @@ HARNESS_DEDUPE_TYPE = "harness_dedupe"
SILENT_TYPE = "silent"
# Types that must never count as inbox conversation activity: the ephemeral user rows
# above plus the invisible agent silent-completion marker.
-NON_CONVERSATION_TYPES = (QUEUED_TYPE, DRAFT_TYPE, PENDING_TYPE, HARNESS_DEDUPE_TYPE, SILENT_TYPE)
+NON_CONVERSATION_TYPES = (
+ QUEUED_TYPE,
+ DRAFT_TYPE,
+ PENDING_TYPE,
+ HARNESS_DEDUPE_TYPE,
+ SILENT_TYPE,
+)
# The transcript-visible types — the SINGLE source of truth shared by the
# history fetch (``list_session_messages``) AND the live ``message.new`` publish
@@ -806,11 +812,11 @@ def clear_queued(conn: Connection, session_id: str) -> int:
def clear_pending(conn: Connection, session_id: str) -> int:
- """Drop ALL ``pending`` send reservations for a session. Used by archive: a
- send that reserved its row just before the archive committed must not later
- be promoted into a visible message / accepted turn for a now-terminal session
- — once the row is gone, ``promote_pending`` no-ops on the in-flight send.
- Returns the number removed."""
+ """Drop unsettled transcript reservations for a session.
+
+ Show dispatch lifecycle is stored on ``show_session_events``; message type
+ only controls whether the reserved transcript row is rendered.
+ """
result = conn.execute(
delete(messages)
.where(messages.c.session_id == session_id)
@@ -820,13 +826,7 @@ def clear_pending(conn: Connection, session_id: str) -> int:
def promote_pending(conn: Connection, message_id: str, to_type: str) -> bool:
- """Promote a reserved ``pending`` row to its decided type — ``user`` once the
- turn is accepted, or ``queued`` when a turn is already running. The row is
- persisted as ``pending`` BEFORE dispatch (reserving its (created_at, id) for
- correct ordering) and stays hidden until this promotes it, so no other tab
- can briefly see it as a sent prompt during the dispatch window. Returns True
- if a pending row was promoted.
- """
+ """Change only the rendering state of one reserved transcript row."""
result = conn.execute(
update(messages)
.where(messages.c.id == message_id)
diff --git a/storage/models.py b/storage/models.py
index 8d7d936d2..8f7a4335f 100644
--- a/storage/models.py
+++ b/storage/models.py
@@ -298,6 +298,7 @@ show_session_events = Table(
Column("payload_json", Text, nullable=False),
Column("transcript_text", Text, nullable=True),
Column("message_id", String, ForeignKey("messages.id", ondelete="SET NULL"), nullable=True),
+ Column("dispatch_state", Text, nullable=False, server_default='{"state":"none"}'),
Column("created_at", String, nullable=False),
Index("ix_show_session_events_session_created", "session_id", "created_at"),
Index("ix_show_session_events_type_created", "event_type", "created_at"),
diff --git a/tests/test_i18n_backend_keys.py b/tests/test_i18n_backend_keys.py
index eee859172..3e60f3821 100644
--- a/tests/test_i18n_backend_keys.py
+++ b/tests/test_i18n_backend_keys.py
@@ -17,6 +17,7 @@ import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from core.run_settlement import SETTLEMENT_I18N_KEYS, SWEEP_I18N_KEYS
+from core.show_session_events import SHOW_EVENT_ERROR_I18N_KEYS
from storage.background import (
SWEEP_REASON_ORPHANED,
SWEEP_REASON_QUEUE_HOLD_EXPIRED,
@@ -80,3 +81,14 @@ def test_sweep_reason_i18n_map_covers_every_store_sweep_reason() -> None:
SWEEP_REASON_TRANSPORT_UNAVAILABLE,
SWEEP_REASON_QUEUE_HOLD_EXPIRED,
}
+
+
+ "code,key",
+ sorted(SHOW_EVENT_ERROR_I18N_KEYS.items()),
+)
+def test_every_show_event_error_resolves(code: str, key: str) -> None:
+ for lang in get_supported_languages():
+ resolved = t(key, lang)
+ assert resolved != key, f"{key} is not translated in {lang} (code={code})"
+ assert resolved.strip()
diff --git a/tests/test_internal_client.py b/tests/test_internal_client.py
index d4f6b926a..888ff99c8 100644
--- a/tests/test_internal_client.py
+++ b/tests/test_internal_client.py
@@ -100,6 +100,30 @@ def test_dispatch_async_missing_socket_raises_unavailable(tmp_path):
asyncio.run(internal_client.dispatch_async({"session_id": "s", "text": "x"}, socket_path=sock))
+def test_dispatch_async_read_timeout_reports_acceptance_unknown(tmp_path):
+ sock = tmp_path / "dispatch.sock"
+ sock.touch()
+
+ class TimingOutClient:
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *_args):
+ return None
+
+ async def post(self, _path, json):
+ raise httpx.ReadTimeout("response deadline elapsed")
+
+ with patch("vibe.internal_client.httpx.AsyncClient", return_value=TimingOutClient()):
+ with pytest.raises(internal_client.InternalServerTimeout):
+ asyncio.run(
+ internal_client.dispatch_async(
+ {"session_id": "s", "text": "x"},
+ socket_path=sock,
+ )
+ )
+
+
def test_reconcile_platforms_round_trip(tmp_path):
app = FastAPI()
calls: list[bool] = []
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index 8b9f898c8..f5799fbf6 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -24,6 +24,7 @@ from pathlib import Path
from unittest.mock import AsyncMock, MagicMock, Mock
import httpx
+import pytest
from sqlalchemy import select
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
@@ -157,65 +158,18 @@ def test_bind_socket_prebinds_unix_listener():
def test_create_app_exposes_minimal_endpoints():
app = internal_server.create_app(_build_controller_double())
routes = {(r.path, tuple(sorted(r.methods))) for r in app.routes if hasattr(r, "methods")}
- # Endpoints locked by the design doc §7.4 v1 row + the health probe. Both
- # dispatch shapes exist: ``/internal/dispatch_async`` (fire-and-forget, the
- # Chat page) and the streaming ``/internal/dispatch`` (the Show-page dispatch
- # flow re-publishes its SSE chunks as ``show.dispatch``).
+ # All interactive sources use the fire-and-forget turn entry.
assert ("/internal/health", ("GET",)) in routes
assert ("/internal/dispatch_async", ("POST",)) in routes
assert ("/internal/reconcile-platforms", ("POST",)) in routes
assert ("/internal/reconcile-agent-backends", ("POST",)) in routes
assert ("/internal/model-hub", ("POST",)) in routes
assert ("/internal/cancel/{session_id}", ("POST",)) in routes
- assert ("/internal/dispatch", ("POST",)) in routes
+ assert ("/internal/dispatch", ("POST",)) not in routes
assert ("/internal/events", ("GET",)) in routes
assert ("/internal/events", ("POST",)) in routes
-def test_streaming_dispatch_publishes_single_bus_lifecycle(monkeypatch):
- """The Show-page stream owns one bus lifecycle because it bypasses the FSM."""
- from core import inbox_events
-
- context = MessageContext(user_id="workbench", channel_id="ses_show", platform="avibe")
-
- async def _build_payload(_payload):
- return "edit the show page", context
-
- async def _dispatch_turn(_controller, _context, _text, *, on_chunk=None):
- assert on_chunk is not None
- await on_chunk({"kind": "result", "text": "done"})
-
- monkeypatch.setattr(internal_server, "_build_dispatch_payload", _build_payload)
- monkeypatch.setattr(internal_server, "dispatch_turn", _dispatch_turn)
- controller = _build_controller_double()
- app = internal_server.create_app(controller)
- transport = httpx.ASGITransport(app=app)
- lifecycle = []
-
- async def _go():
- subscription_id = inbox_events.bus.subscribe_callback(
- lambda event_type, data: lifecycle.append((event_type, data))
- if event_type in {"turn.start", "turn.end"}
- else None
- )
- try:
- async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
- return await client.post(
- "/internal/dispatch",
- json={"session_id": "ses_show", "text": "edit the show page"},
- )
- finally:
- inbox_events.bus.unsubscribe(subscription_id)
-
- response = asyncio.run(_go())
-
- assert response.status_code == 200
- assert lifecycle == [
- ("turn.start", {"session_id": "ses_show"}),
- ("turn.end", {"session_id": "ses_show"}),
- ]
-
-
# ---------------------------------------------------------------------
# ASGI round-trips
# ---------------------------------------------------------------------
@@ -764,10 +718,22 @@ def test_dispatch_async_enqueues_during_busy_turn(monkeypatch, tmp_path):
assert transcript["messages"] == []
-def test_async_dispatch_flushes_queue_on_turn_end(monkeypatch, tmp_path):
- """When a turn ends, messages queued (send-while-busy) during it are popped,
- merged (newline-joined) into ONE user row, and run as the next turn —
- draining the queue. Exercises the controller-side flush wiring end to end."""
+ ("stored_type", "active_same_message", "expect_queued", "expected_type"),
+ (
+ ("pending", True, False, "user"),
+ ("queued", False, True, "queued"),
+ ("user", False, False, "user"),
+ ),
+)
+def test_dispatch_async_deduplicates_replayed_reserved_message(
+ monkeypatch,
+ tmp_path,
+ stored_type,
+ active_same_message,
+ expect_queued,
+ expected_type,
+):
from core.services import sessions as sessions_service
from storage import messages_service
from storage.db import create_sqlite_engine
@@ -779,79 +745,103 @@ def test_async_dispatch_flushes_queue_on_turn_end(monkeypatch, tmp_path):
engine = create_sqlite_engine()
with engine.begin() as conn:
scope_id = upsert_scope(
- conn, platform="avibe", scope_type="project", native_id="proj_flush", now="2026-05-31T00:00:00Z"
+ conn,
+ platform="avibe",
+ scope_type="project",
+ native_id=f"proj_replay_{stored_type}",
+ now="2026-05-31T00:00:00Z",
)
_seed_project_workdir(conn, scope_id, tmp_path)
session = sessions_service.create_session(
- conn, scope_id=scope_id, agent_backend="claude", agent_name="worker"
+ conn,
+ scope_id=scope_id,
+ agent_backend="claude",
+ agent_name="worker",
+ )
+ row = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=session["id"],
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type=stored_type,
+ text="same show event",
)
- session_id = session["id"]
-
- 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.append(
- conn,
- scope_id=scope_id,
- session_id=session_id,
- platform="avibe",
- author="user",
- source="user",
- message_type=messages_service.QUEUED_TYPE,
- text="q1",
- author_id="remote:user-a",
- metadata={"_web_push_user_key": "remote:user-a"},
- )
- messages_service.append(
- conn,
- scope_id=scope_id,
- session_id=session_id,
- platform="avibe",
- author="user",
- source="user",
- message_type=messages_service.QUEUED_TYPE,
- text="q2",
- )
- controller.mark_turn_complete(ctx) # release each turn immediately
- return None
- controller = _build_controller_double(handler=handler)
+ controller = _build_controller_double()
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 turn"})
- # Wait for the first turn AND the flush turn to both drain the queue.
- for _ in range(200):
- if len(seen_texts) >= 2 and session_id not in app.state.in_flight_dispatches:
- break
- await asyncio.sleep(0.02)
+ active_task = None
+ if active_same_message:
+ active_task = asyncio.create_task(asyncio.sleep(60))
+ app.state.in_flight_dispatches[session["id"]] = session_turns.Turn(
+ task=active_task,
+ context=MessageContext(
+ user_id="U",
+ channel_id="C",
+ platform="avibe",
+ message_id=row["id"],
+ ),
+ )
+ try:
+ async with httpx.AsyncClient(
+ transport=transport,
+ base_url="http://testserver",
+ ) as client:
+ return await client.post(
+ "/internal/dispatch_async",
+ json={
+ "session_id": session["id"],
+ "text": "same show event",
+ "user_message_id": row["id"],
+ },
+ )
+ finally:
+ if active_task is not None:
+ active_task.cancel()
- asyncio.run(_go())
- # First the user's turn, then ONE merged flush turn for the two queued msgs.
- assert seen_texts == ["first turn", "q1\nq2"]
- with engine.connect() as conn:
- assert messages_service.list_queued(conn, session_id) == []
- transcript = messages_service.list_session_messages(conn, session_id=session_id, types=("user",))
- assert [m["text"] for m in transcript["messages"]] == ["q1\nq2"], "the flush persisted one merged user row"
- assert transcript["messages"][0]["author_id"] == "remote:user-a"
- assert transcript["messages"][0]["metadata"]["_web_push_user_key"] == "remote:user-a"
+ response = asyncio.run(_go())
+ assert response.status_code == 202
+ assert response.json()["duplicate"] is True
+ assert bool(response.json().get("queued")) is expect_queued
+ controller.message_handler.handle_user_message.assert_not_awaited()
+ with engine.connect() as conn:
+ rows = messages_service.list_session_messages(
+ conn,
+ session_id=session["id"],
+ )["messages"]
+ assert [item["id"] for item in rows] == [row["id"]]
+ assert rows[0]["type"] == expected_type
+
+
+ ("case", "expected_code"),
+ [
+ ("missing_event", "show_event_not_found"),
+ ("missing_message", "show_event_message_mismatch"),
+ ("archived", "session_archived"),
+ ],
+)
+def test_dispatch_async_rejects_missing_or_archived_show_reservation(
+ monkeypatch,
+ tmp_path,
+ case,
+ expected_code,
+):
+ from sqlalchemy import delete, update
-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 core.show_session_events import (
+ ShowSessionEventStore,
+ claim_show_dispatch,
+ )
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
+ from storage.models import agent_sessions, messages
from storage.settings_service import upsert_scope
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
@@ -859,120 +849,1322 @@ def test_cancel_does_not_flush_queue(monkeypatch, tmp_path):
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"
+ conn,
+ platform="avibe",
+ scope_type="project",
+ native_id=f"proj_show_reject_{case}",
+ now="2026-05-31T00:00:00Z",
)
_seed_project_workdir(conn, scope_id, tmp_path)
session = sessions_service.create_session(
- conn, scope_id=scope_id, agent_backend="claude", agent_name="worker"
+ 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 TurnDispatchOutcome(error=None, settled_by=SETTLED_BY_TERMINAL_RESULT)
- 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"
+ event_id = "show_evt_missing"
+ message_id = "msg_missing"
+ owner = "101:1.0"
+ if case != "missing_event":
+ store = ShowSessionEventStore()
+ try:
+ event = store.append(
+ session["id"],
+ {
+ "id": f"show_evt_{case}",
+ "type": "human.annotation.created",
+ "annotation": {
+ "intent": "comment",
+ "comment": "Do not submit this turn.",
+ "dispatch": True,
+ },
+ },
+ reserve_dispatch=True,
+ )
+ finally:
+ store.close()
+ event_id = event["id"]
+ message_id = event["message_id"]
+ with engine.begin() as conn:
+ claimed = claim_show_dispatch(
+ conn,
+ event_id,
+ session_id=session["id"],
+ owner=owner,
+ )
+ assert claimed is not None and claimed.claimed
+ if case == "missing_message":
+ conn.execute(delete(messages).where(messages.c.id == message_id))
+ if case == "archived":
+ conn.execute(
+ update(agent_sessions)
+ .where(agent_sessions.c.id == session["id"])
+ .values(status="archived")
+ )
-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."""
controller = _build_controller_double()
- controller.agent_service.runtime_turn_started.return_value = True
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:
- 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"] = session_turns.Turn(
- task=task,
- context=MessageContext(
- user_id="U",
- channel_id="C",
- platform="avibe",
- platform_specific={"agent_session_target": {"agent_backend": "opencode"}},
- ),
+ async with httpx.AsyncClient(
+ transport=transport,
+ base_url="http://testserver",
+ ) as client:
+ return await client.post(
+ "/internal/dispatch_async",
+ json={
+ "session_id": session["id"],
+ "text": "Do not submit this turn.",
+ "user_message_id": message_id,
+ "show_event_id": event_id,
+ "dispatch_owner": owner,
+ },
)
- 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
- assert busy["native_turn_started"] is True
- assert busy["backend"] == "opencode"
+ response = asyncio.run(_go())
+ assert response.status_code == 409
+ assert response.json()["code"] == expected_code
+ controller.message_handler.handle_user_message.assert_not_awaited()
-def test_cancel_returns_404_when_session_not_in_flight():
- 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:
- return await client.post("/internal/cancel/ses_unknown")
+def test_dispatch_async_archive_race_never_marks_lost_show_reservation_accepted(
+ monkeypatch,
+ tmp_path,
+):
+ from core.services import sessions as sessions_service
+ from core.show_session_events import (
+ DISPATCH_ARCHIVED,
+ DISPATCH_IN_FLIGHT,
+ ShowSessionEventStore,
+ claim_show_dispatch,
+ )
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.models import messages
+ from storage.settings_service import upsert_scope
- resp = asyncio.run(_go())
- assert resp.status_code == 404
- body = resp.json()
- assert body["ok"] is False
- assert body["code"] == "not_in_flight"
+ monkeypatch.setenv("AVIBE_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_show_archive_race",
+ now="2026-05-31T00:00:00Z",
+ )
+ _seed_project_workdir(conn, scope_id, tmp_path)
+ session = sessions_service.create_session(
+ conn,
+ scope_id=scope_id,
+ agent_backend="claude",
+ agent_name="worker",
+ )
+ store = ShowSessionEventStore()
+ try:
+ event = store.append(
+ session["id"],
+ {
+ "id": "show_evt_archive_during_submit",
+ "type": "human.annotation.created",
+ "annotation": {
+ "intent": "comment",
+ "comment": "Do not lose this annotation as a false success.",
+ "dispatch": True,
+ },
+ },
+ reserve_dispatch=True,
+ )
+ finally:
+ store.close()
+ owner = "101:1.0:attempt"
+ with engine.begin() as conn:
+ claimed = claim_show_dispatch(
+ conn,
+ event["id"],
+ session_id=session["id"],
+ owner=owner,
+ )
+ assert claimed is not None
+ assert claimed.state == DISPATCH_IN_FLIGHT
+ assert claimed.claimed is True
-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"},
+ submissions = 0
+
+ async def archive_during_submit(session_id, _context, _text, *, enqueue, **_kwargs):
+ nonlocal submissions
+ submissions += 1
+ with engine.begin() as conn:
+ sessions_service.archive_session(conn, session_id)
+ queue_persisted = enqueue()
+ return session_turns.TurnSubmissionResult(
+ route="enqueued",
+ queue_persisted=queue_persisted,
)
- 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
+ monkeypatch.setattr(controller.session_turns, "submit", archive_during_submit)
+
+ async def _post():
+ async with httpx.AsyncClient(
+ transport=transport,
+ base_url="http://testserver",
+ ) as client:
+ payload = {
+ "session_id": session["id"],
+ "text": event["transcript_text"],
+ "user_message_id": event["message_id"],
+ "show_event_id": event["id"],
+ "dispatch_owner": owner,
+ }
+ return (
+ await client.post("/internal/dispatch_async", json=payload),
+ await client.post("/internal/dispatch_async", json=payload),
+ )
- controller.command_handler.handle_stop = AsyncMock(side_effect=_not_active)
- async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ first, replay = asyncio.run(_post())
+
+ assert first.status_code == 409
+ assert first.json()["code"] == "session_archived"
+ assert replay.status_code == 409
+ assert replay.json()["code"] == "session_archived"
+ assert submissions == 1
+ controller.message_handler.handle_user_message.assert_not_awaited()
+ store = ShowSessionEventStore()
+ try:
+ dispatch_status = store.get_dispatch_status(session["id"], event["id"])
+ finally:
+ store.close()
+ assert dispatch_status is not None
+ assert dispatch_status.state == DISPATCH_ARCHIVED
+ with engine.connect() as conn:
+ assert (
+ conn.execute(
+ select(messages.c.id).where(messages.c.id == event["message_id"])
+ ).scalar_one_or_none()
+ is None
+ )
+
+
+def test_failed_show_dispatch_retries_same_event_through_manager_once(monkeypatch, tmp_path):
+ from core.services import sessions as sessions_service
+ from core.show_session_events import (
+ DISPATCH_FAILED,
+ ShowSessionEventError,
+ ShowSessionEventStore,
+ )
+ 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
+ from vibe import internal_client, ui_server
+ from vibe.sse_broker import broker
+
+ monkeypatch.setenv("AVIBE_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_show_retry",
+ now="2026-05-31T00:00:00Z",
+ )
+ _seed_project_workdir(conn, scope_id, tmp_path)
+ session = sessions_service.create_session(
+ conn,
+ scope_id=scope_id,
+ agent_backend="claude",
+ agent_name="worker",
+ )
+
+ turn_started = asyncio.Event()
+
+ async def handler(_context, _text):
+ turn_started.set()
+
+ controller = _build_controller_double(handler)
+ app = internal_server.create_app(controller)
+ transport = httpx.ASGITransport(app=app)
+ manager = controller.session_turns
+ real_submit = manager.submit
+ submissions = []
+
+ async def tracked_submit(*args, **kwargs):
+ submissions.append((args, kwargs))
+ return await real_submit(*args, **kwargs)
+
+ monkeypatch.setattr(manager, "submit", tracked_submit)
+ attempts = 0
+
+ async def retrying_dispatch(payload, **_kwargs):
+ nonlocal attempts
+ attempts += 1
+ if attempts == 1:
+ raise internal_client.InternalServerUnavailable("controller unavailable")
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ response = await client.post("/internal/dispatch_async", json=payload)
+ await asyncio.sleep(0)
+ return {
+ "status_code": response.status_code,
+ "body": response.json(),
+ }
+
+ monkeypatch.setattr(internal_client, "dispatch_async", retrying_dispatch)
+ published = []
+ monkeypatch.setattr(broker, "publish", lambda event, data: published.append((event, data)))
+ event_input = {
+ "id": "show_evt_retry_acceptance",
+ "type": "human.annotation.created",
+ "annotation": {
+ "intent": "comment",
+ "comment": "Retry this exact annotation.",
+ "dispatch": True,
+ },
+ }
+
+ with pytest.raises(ShowSessionEventError):
+ ui_server.record_local_show_event(
+ session["id"],
+ event_input,
+ dispatch_sync=True,
+ )
+
+ store = ShowSessionEventStore()
+ try:
+ dispatch_status = store.get_dispatch_status(session["id"], event_input["id"])
+ finally:
+ store.close()
+ with engine.connect() as conn:
+ visible = messages_service.list_session_messages(
+ conn,
+ session_id=session["id"],
+ types=("user",),
+ )["messages"]
+ assert dispatch_status is not None
+ assert dispatch_status.state == DISPATCH_FAILED
+ assert len(visible) == 1
+ assert [event_type for event_type, _data in published] == [
+ "show.event",
+ "message.new",
+ "session.activity",
+ ]
+ assert submissions == []
+
+ retried = ui_server.record_local_show_event(
+ session["id"],
+ event_input,
+ dispatch_sync=True,
+ )
+
+ assert retried["id"] == event_input["id"]
+ assert retried["message"]["type"] == "user"
+ assert len(submissions) == 1
+ assert turn_started.is_set()
+ controller.message_handler.handle_user_message.assert_awaited_once()
+
+
+def test_ambiguous_show_dispatch_timeout_reconciles_accepted_turn_once(
+ monkeypatch,
+ tmp_path,
+):
+ from core.services import sessions as sessions_service
+ from core.show_session_events import ShowSessionEventStore
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.settings_service import upsert_scope
+ from vibe import internal_client, ui_server
+
+ monkeypatch.setenv("AVIBE_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_show_timeout",
+ now="2026-05-31T00:00:00Z",
+ )
+ _seed_project_workdir(conn, scope_id, tmp_path)
+ session = sessions_service.create_session(
+ conn,
+ scope_id=scope_id,
+ agent_backend="claude",
+ agent_name="worker",
+ )
+
+ turn_started = asyncio.Event()
+
+ async def handler(_context, _text):
+ turn_started.set()
+
+ controller = _build_controller_double(handler)
+ internal_app = internal_server.create_app(controller)
+ transport = httpx.ASGITransport(app=internal_app)
+ manager = controller.session_turns
+ real_submit = manager.submit
+ submissions = []
+
+ async def tracked_submit(*args, **kwargs):
+ submissions.append((args, kwargs))
+ return await real_submit(*args, **kwargs)
+
+ monkeypatch.setattr(manager, "submit", tracked_submit)
+
+ async def accepted_without_response(payload, **_kwargs):
+ async with httpx.AsyncClient(
+ transport=transport,
+ base_url="http://testserver",
+ ) as client:
+ response = await client.post("/internal/dispatch_async", json=payload)
+ assert response.status_code == 202
+ raise internal_client.InternalServerTimeout("response was lost")
+
+ monkeypatch.setattr(internal_client, "dispatch_async", accepted_without_response)
+ store = ShowSessionEventStore()
+ try:
+ event = store.append(
+ session["id"],
+ {
+ "id": "show_evt_timeout_acceptance",
+ "type": "human.annotation.created",
+ "annotation": {
+ "intent": "comment",
+ "comment": "Accept this despite the lost response.",
+ "dispatch": True,
+ },
+ },
+ reserve_dispatch=True,
+ )
+ finally:
+ store.close()
+
+ async def _go():
+ first = await ui_server._run_show_event_dispatch(event)
+ replay = await ui_server._run_show_event_dispatch(event)
+ await asyncio.wait_for(turn_started.wait(), timeout=1)
+ return first, replay
+
+ assert asyncio.run(_go()) == (
+ ui_server._ShowEventDispatchOutcome.ACCEPTED,
+ ui_server._ShowEventDispatchOutcome.ACCEPTED,
+ )
+ assert len(submissions) == 1
+ controller.message_handler.handle_user_message.assert_awaited_once()
+ assert event["message"]["type"] == "user"
+
+
+def test_slow_live_show_post_cli_timeout_waits_without_duplicate_submit(
+ monkeypatch,
+ tmp_path,
+ capsys,
+):
+ import json
+ import threading
+
+ from core.services import sessions as sessions_service
+ from core.show_session_events import ShowSessionEventStore
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.settings_service import upsert_scope
+ from vibe import cli, internal_client, ui_server
+
+ monkeypatch.setenv("AVIBE_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_show_cli_timeout",
+ now="2026-05-31T00:00:00Z",
+ )
+ _seed_project_workdir(conn, scope_id, tmp_path)
+ session = sessions_service.create_session(
+ conn,
+ scope_id=scope_id,
+ agent_backend="claude",
+ agent_name="worker",
+ )
+
+ turn_started = threading.Event()
+
+ async def handler(_context, _text):
+ turn_started.set()
+
+ controller = _build_controller_double(handler)
+ internal_app = internal_server.create_app(controller)
+ transport = httpx.ASGITransport(app=internal_app)
+ manager = controller.session_turns
+ real_submit = manager.submit
+ submissions = []
+
+ async def tracked_submit(*args, **kwargs):
+ submissions.append((args, kwargs))
+ return await real_submit(*args, **kwargs)
+
+ monkeypatch.setattr(manager, "submit", tracked_submit)
+ dispatch_entered = threading.Event()
+ release_dispatch = threading.Event()
+ request_thread: threading.Thread | None = None
+ request_errors: list[BaseException] = []
+
+ async def slow_dispatch(payload, **_kwargs):
+ dispatch_entered.set()
+ assert await asyncio.to_thread(release_dispatch.wait, 2)
+ async with httpx.AsyncClient(
+ transport=transport,
+ base_url="http://testserver",
+ ) as client:
+ response = await client.post("/internal/dispatch_async", json=payload)
+ return {"status_code": response.status_code, "body": response.json()}
+
+ monkeypatch.setattr(internal_client, "dispatch_async", slow_dispatch)
+
+ def timeout_after_live_request(request, **_kwargs):
+ nonlocal request_thread
+ posted = json.loads(request.data.decode("utf-8"))
+
+ def run_live_request():
+ try:
+ store = ShowSessionEventStore()
+ try:
+ event = store.append(
+ session["id"],
+ posted,
+ reserve_dispatch=True,
+ )
+ finally:
+ store.close()
+ asyncio.run(ui_server._run_show_event_dispatch(event))
+ except BaseException as exc: # pragma: no cover - thread relay
+ request_errors.append(exc)
+
+ request_thread = threading.Thread(target=run_live_request)
+ request_thread.start()
+ assert dispatch_entered.wait(1)
+ threading.Timer(0.1, release_dispatch.set).start()
+ raise TimeoutError("CLI deadline elapsed")
+
+ monkeypatch.setattr(cli.urllib.request, "urlopen", timeout_after_live_request)
+ monkeypatch.setattr(
+ cli,
+ "_local_show_events_url",
+ lambda session_id: f"http://127.0.0.1:5123/api/show/sessions/{session_id}/events",
+ )
+ monkeypatch.setattr(
+ ui_server,
+ "record_local_show_event",
+ lambda *args, **kwargs: pytest.fail("ambiguous timeout must not use local fallback"),
+ )
+ event_input = {
+ "id": "show_evt_slow_live_cli",
+ "type": "human.annotation.created",
+ "annotation": {
+ "intent": "comment",
+ "comment": "Wait for the original live request.",
+ "dispatch": True,
+ },
+ }
+ args = cli.build_parser().parse_args(
+ [
+ "show",
+ "event",
+ "--session-id",
+ session["id"],
+ "--event-json",
+ json.dumps(event_input),
+ "--json",
+ ]
+ )
+
+ assert cli.cmd_show(args) == 0
+ assert request_thread is not None
+ request_thread.join(2)
+ assert not request_thread.is_alive()
+ assert request_errors == []
+ assert len(submissions) == 1
+ assert turn_started.wait(1)
+ controller.message_handler.handle_user_message.assert_awaited_once()
+ assert json.loads(capsys.readouterr().out)["event_id"] == event_input["id"]
+
+
+def test_dispatch_async_queues_show_annotation_and_runs_it_after_active_turn(monkeypatch, tmp_path):
+ from core.services import sessions as sessions_service
+ from core.show_session_events import (
+ DISPATCH_ACCEPTED,
+ ShowSessionEventStore,
+ claim_show_dispatch,
+ )
+ 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("AVIBE_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_show_queue",
+ now="2026-05-31T00:00:00Z",
+ )
+ _seed_project_workdir(conn, scope_id, tmp_path)
+ session = sessions_service.create_session(
+ conn,
+ scope_id=scope_id,
+ agent_backend="claude",
+ agent_name="worker",
+ )
+ session_id = session["id"]
+
+ first_started = asyncio.Event()
+ release_first = asyncio.Event()
+ seen_texts: list[str] = []
+
+ async def handler(ctx, text):
+ seen_texts.append(text)
+ if text == "active turn":
+ first_started.set()
+ await release_first.wait()
+ controller.mark_turn_complete(ctx)
+
+ controller = _build_controller_double(handler=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:
+ first = await client.post(
+ "/internal/dispatch_async",
+ json={"session_id": session_id, "text": "active turn"},
+ )
+ assert first.status_code == 202
+ await asyncio.wait_for(first_started.wait(), timeout=3)
+
+ store = ShowSessionEventStore()
+ try:
+ annotation = store.append(
+ session_id,
+ {
+ "type": "human.annotation.created",
+ "annotation": {
+ "intent": "comment",
+ "comment": "Deliver after the active turn.",
+ "dispatch": True,
+ },
+ },
+ reserve_dispatch=True,
+ )
+ finally:
+ store.close()
+ assert annotation["message"]["type"] == messages_service.PENDING_TYPE
+ enriched_dispatch_text = (
+ f"{annotation['transcript_text']}\n\n"
+ f"Show event ID: {annotation['id']}\n"
+ "Reply on the Show Page with `vibe show reply`."
+ )
+ dispatch_owner = "101:1.0"
+ with engine.begin() as conn:
+ claimed = claim_show_dispatch(
+ conn,
+ annotation["id"],
+ session_id=session_id,
+ owner=dispatch_owner,
+ )
+ assert claimed is not None and claimed.claimed
+
+ queued = await client.post(
+ "/internal/dispatch_async",
+ json={
+ "session_id": session_id,
+ "text": enriched_dispatch_text,
+ "user_message_id": annotation["message_id"],
+ "show_event_id": annotation["id"],
+ "dispatch_owner": dispatch_owner,
+ },
+ )
+ assert queued.status_code == 202
+ assert queued.json()["queued"] is True
+ with engine.connect() as conn:
+ queued_rows = messages_service.list_queued(conn, session_id)
+ assert [row["id"] for row in queued_rows] == [annotation["message_id"]]
+ assert queued_rows[0]["text"] == annotation["transcript_text"]
+ assert (
+ queued_rows[0]["metadata"][session_turns.QUEUED_DISPATCH_TEXT_KEY]
+ == enriched_dispatch_text
+ )
+ visible = messages_service.list_session_messages(
+ conn,
+ session_id=session_id,
+ types=("user",),
+ )
+ assert visible["messages"] == []
+ assert seen_texts == ["active turn"]
+
+ release_first.set()
+ for _ in range(200):
+ if len(seen_texts) == 2 and session_id not in app.state.in_flight_dispatches:
+ break
+ await asyncio.sleep(0.02)
+ return annotation, enriched_dispatch_text
+
+ annotation, enriched_dispatch_text = asyncio.run(_go())
+ assert seen_texts == ["active turn", enriched_dispatch_text]
+ with engine.connect() as conn:
+ from storage.models import show_session_events
+
+ assert messages_service.list_queued(conn, session_id) == []
+ visible = messages_service.list_session_messages(conn, session_id=session_id, types=("user",))
+ linked_message_id = conn.execute(
+ select(show_session_events.c.message_id).where(show_session_events.c.id == annotation["id"])
+ ).scalar_one()
+ store = ShowSessionEventStore()
+ try:
+ dispatch_status = store.get_dispatch_status(session_id, annotation["id"])
+ finally:
+ store.close()
+ assert [message["text"] for message in visible["messages"]] == [annotation["transcript_text"]]
+ assert visible["messages"][0]["id"] != annotation["message_id"]
+ assert visible["messages"][0]["metadata"]["source"] == "show_page"
+ assert visible["messages"][0]["metadata"]["show_event_id"] == annotation["id"]
+ assert session_turns.QUEUED_DISPATCH_TEXT_KEY not in visible["messages"][0]["metadata"]
+ assert linked_message_id == visible["messages"][0]["id"]
+ assert dispatch_status is not None
+ assert dispatch_status.state == DISPATCH_ACCEPTED
+
+
+def test_dispatch_async_keeps_identified_show_row_after_idle_anonymous_queue(
+ monkeypatch,
+ tmp_path,
+):
+ from core.services import sessions as sessions_service
+ from core.show_session_events import ShowSessionEventStore, claim_show_dispatch
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.models import messages, show_session_events
+ from storage.settings_service import upsert_scope
+
+ monkeypatch.setenv("AVIBE_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_show_idle_queue",
+ now="2026-05-31T00:00:00Z",
+ )
+ _seed_project_workdir(conn, scope_id, tmp_path)
+ session = sessions_service.create_session(
+ conn,
+ scope_id=scope_id,
+ agent_backend="claude",
+ agent_name="worker",
+ )
+ messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=session["id"],
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type=messages_service.QUEUED_TYPE,
+ text="older stopped message",
+ )
+ store = ShowSessionEventStore()
+ try:
+ annotation = store.append(
+ session["id"],
+ {
+ "type": "human.annotation.created",
+ "annotation": {
+ "intent": "comment",
+ "comment": "Join and drain.",
+ "dispatch": True,
+ },
+ },
+ reserve_dispatch=True,
+ )
+ finally:
+ store.close()
+
+ controller = _build_controller_double()
+ app = internal_server.create_app(controller)
+ manager = controller.session_turns
+ manager._build_context = lambda sid: MessageContext(
+ user_id="U",
+ channel_id="C",
+ platform="avibe",
+ platform_specific={"agent_session_id": sid},
+ )
+ runs = []
+
+ async def capture_run(sid, context, text, *, source=SOURCE_HUMAN):
+ runs.append((sid, text, source))
+
+ manager._run = capture_run
+ transport = httpx.ASGITransport(app=app)
+ dispatch_owner = "101:1.0"
+ with engine.begin() as conn:
+ claimed = claim_show_dispatch(
+ conn,
+ annotation["id"],
+ session_id=session["id"],
+ owner=dispatch_owner,
+ )
+ assert claimed is not None and claimed.claimed
+
+ async def _go():
+ async with httpx.AsyncClient(
+ transport=transport,
+ base_url="http://testserver",
+ ) as client:
+ return await client.post(
+ "/internal/dispatch_async",
+ json={
+ "session_id": session["id"],
+ "text": annotation["transcript_text"],
+ "user_message_id": annotation["message_id"],
+ "show_event_id": annotation["id"],
+ "dispatch_owner": dispatch_owner,
+ },
+ )
+
+ response = asyncio.run(_go())
+
+ assert response.status_code == 202
+ assert response.json()["queued"] is True
+ assert response.json().get("drained") is None
+ assert len(runs) == 1
+ assert runs[0][1] == "older stopped message"
+ with engine.connect() as conn:
+ queued = messages_service.list_queued(conn, session["id"])
+ linked_message_id = conn.execute(
+ select(show_session_events.c.message_id).where(
+ show_session_events.c.id == annotation["id"]
+ )
+ ).scalar_one()
+ original_exists = conn.execute(
+ select(messages.c.id).where(messages.c.id == annotation["message_id"])
+ ).scalar_one_or_none()
+ visible = messages_service.list_session_messages(
+ conn,
+ session_id=session["id"],
+ types=("user",),
+ )["messages"]
+ assert [row["id"] for row in queued] == [annotation["message_id"]]
+ assert original_exists == annotation["message_id"]
+ assert linked_message_id == annotation["message_id"]
+ assert [row["text"] for row in visible] == ["older stopped message"]
+
+ assert asyncio.run(manager.flush_queue(session["id"])) is True
+ with engine.connect() as conn:
+ linked_message_id = conn.execute(
+ select(show_session_events.c.message_id).where(
+ show_session_events.c.id == annotation["id"]
+ )
+ ).scalar_one()
+ original_exists = conn.execute(
+ select(messages.c.id).where(messages.c.id == annotation["message_id"])
+ ).scalar_one_or_none()
+ visible = messages_service.list_session_messages(
+ conn,
+ session_id=session["id"],
+ types=("user",),
+ )["messages"]
+ assert [run[1] for run in runs] == [
+ "older stopped message",
+ annotation["transcript_text"],
+ ]
+ assert original_exists is None
+ assert linked_message_id == visible[1]["id"]
+ assert visible[1]["native_message_id"] == f"show:{annotation['id']}"
+
+
+def test_flush_promoted_user_row_uses_fresh_id_for_same_second_order(
+ tmp_path,
+ monkeypatch,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ session_id = _seed_avibe_session_with_queue([("queued follow-up", None)])
+
+ from sqlalchemy import update
+
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+ from storage.models import messages
+
+ with create_sqlite_engine().begin() as conn:
+ queued = messages_service.list_queued(conn, session_id)[0]
+ queued_id = queued["id"]
+ conn.execute(
+ update(messages)
+ .where(messages.c.id == queued["id"])
+ .values(created_at="2026-06-22T00:00:36Z")
+ )
+ generated_ids = iter(
+ (
+ "msg_000000000000100aaaaaaaa",
+ "msg_000000000000200aaaaaaaa",
+ "msg_000000000000300aaaaaaaa",
+ )
+ )
+ monkeypatch.setattr(messages_service, "_new_message_id", lambda: next(generated_ids))
+ monkeypatch.setattr(messages_service, "_utc_now_iso", lambda: "2026-06-22T00:00:37Z")
+ result = messages_service.append(
+ conn,
+ scope_id=queued["scope_id"],
+ session_id=session_id,
+ platform="avibe",
+ author="agent",
+ message_type="result",
+ text="preceding result",
+ )
+ conn.execute(
+ update(messages)
+ .where(messages.c.id == result["id"])
+ .values(
+ created_at="2026-06-22T00:00:37Z",
+ updated_at="2026-06-22T00:00:37Z",
+ )
+ )
+
+ manager, _runs = _manager_capturing_runs()
+ from core.inbox_events import bus
+
+ published = []
+ monkeypatch.setattr(
+ bus,
+ "publish",
+ lambda event_type, data: published.append((event_type, data)),
+ )
+
+ async def append_fast_result(sid, context, text, *, source=SOURCE_HUMAN):
+ with create_sqlite_engine().begin() as conn:
+ messages_service.append(
+ conn,
+ scope_id=context.platform_specific.get("scope_id"),
+ session_id=sid,
+ platform="avibe",
+ author="agent",
+ message_type="result",
+ text="fast queued result",
+ )
+
+ async def fail_if_sleeping(_delay):
+ pytest.fail("queue promotion must not wait for wall-clock time")
+
+ monkeypatch.setattr(session_turns.asyncio, "sleep", fail_if_sleeping)
+ manager._run = append_fast_result
+ assert asyncio.run(manager.flush_queue(session_id)) is True
+
+ with create_sqlite_engine().connect() as conn:
+ transcript = messages_service.list_session_messages(
+ conn,
+ session_id=session_id,
+ types=("user", "result"),
+ )
+ assert [(row["type"], row["text"]) for row in transcript["messages"]] == [
+ ("result", "preceding result"),
+ ("user", "queued follow-up"),
+ ("result", "fast queued result"),
+ ]
+ assert [row["created_at"] for row in transcript["messages"]] == [
+ "2026-06-22T00:00:37Z",
+ "2026-06-22T00:00:37Z",
+ "2026-06-22T00:00:37Z",
+ ]
+ assert [row["id"] for row in transcript["messages"]] == [
+ "msg_000000000000100aaaaaaaa",
+ "msg_000000000000200aaaaaaaa",
+ "msg_000000000000300aaaaaaaa",
+ ]
+ assert queued_id not in {row["id"] for row in transcript["messages"]}
+ assert [
+ (event_type, data.get("id"))
+ for event_type, data in published
+ if event_type == "message.new"
+ ] == [("message.new", "msg_000000000000200aaaaaaaa")]
+ assert not hasattr(session_turns, "_timestamp_after_latest_session_message")
+ assert not hasattr(session_turns, "_wait_until_message_timestamp")
+
+
+def test_flush_promoted_user_row_repoints_canonical_and_merged_dependencies(
+ tmp_path,
+ monkeypatch,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ session_id = _seed_avibe_session_with_queue(
+ [
+ ("canonical queued message", None),
+ ("merged queued message", None),
+ ]
+ )
+
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+ from storage.models import media_objects, messages, show_session_events
+
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ queued = messages_service.list_queued(conn, session_id)
+ canonical_id = queued[0]["id"]
+ merged_id = queued[1]["id"]
+ for index, message_id in enumerate((canonical_id, merged_id), start=1):
+ conn.execute(
+ show_session_events.insert().values(
+ id=f"show_evt_repoint_{index}",
+ session_id=session_id,
+ event_type="human.annotation.created",
+ actor="human",
+ scope="page",
+ anchor_json="{}",
+ payload_json="{}",
+ transcript_text=f"annotation {index}",
+ message_id=message_id,
+ created_at=f"2026-06-22T00:00:0{index}Z",
+ )
+ )
+ conn.execute(
+ media_objects.insert().values(
+ token=f"media_repoint_{index}",
+ scope_id=queued[index - 1]["scope_id"],
+ session_id=session_id,
+ message_id=message_id,
+ kind="file",
+ source="user_upload",
+ local_path=f"/tmp/repoint-{index}.txt",
+ created_at=f"2026-06-22T00:00:0{index}Z",
+ )
+ )
+
+ manager, _runs = _manager_capturing_runs()
+ assert asyncio.run(manager.flush_queue(session_id)) is True
+
+ with engine.connect() as conn:
+ visible = messages_service.list_session_messages(
+ conn,
+ session_id=session_id,
+ types=("user",),
+ )["messages"]
+ event_message_ids = conn.execute(
+ select(show_session_events.c.message_id).order_by(
+ show_session_events.c.id
+ )
+ ).scalars().all()
+ media_message_ids = conn.execute(
+ select(media_objects.c.message_id).order_by(media_objects.c.token)
+ ).scalars().all()
+ old_ids = conn.execute(
+ select(messages.c.id).where(messages.c.id.in_((canonical_id, merged_id)))
+ ).scalars().all()
+
+ assert len(visible) == 1
+ visible_id = visible[0]["id"]
+ assert visible_id not in {canonical_id, merged_id}
+ assert event_message_ids == [visible_id, visible_id]
+ assert media_message_ids == [visible_id, visible_id]
+ assert old_ids == []
+
+
+def test_flush_keeps_independently_identified_user_rows_as_separate_turns(
+ tmp_path,
+ monkeypatch,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ session_id = _seed_avibe_session_with_queue(
+ [
+ ("first show annotation", None),
+ ("second show annotation", None),
+ ]
+ )
+
+ from sqlalchemy import update
+
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+ from storage.models import messages, show_session_events
+
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ queued = messages_service.list_queued(conn, session_id)
+ for index, row in enumerate(queued, start=1):
+ event_id = f"show_evt_identity_{index}"
+ conn.execute(
+ update(messages)
+ .where(messages.c.id == row["id"])
+ .values(native_message_id=f"show:{event_id}")
+ )
+ conn.execute(
+ show_session_events.insert().values(
+ id=event_id,
+ session_id=session_id,
+ event_type="human.annotation.created",
+ actor="human",
+ scope="default",
+ anchor_json="{}",
+ payload_json="{}",
+ transcript_text=row["text"],
+ message_id=row["id"],
+ created_at=f"2026-06-22T00:00:0{index}Z",
+ )
+ )
+
+ manager, runs = _manager_capturing_runs()
+ assert asyncio.run(manager.flush_queue(session_id)) is True
+ assert asyncio.run(manager.flush_queue(session_id)) is True
+
+ with engine.connect() as conn:
+ visible = messages_service.list_session_messages(
+ conn,
+ session_id=session_id,
+ types=("user",),
+ )["messages"]
+ event_links = conn.execute(
+ select(show_session_events.c.id, show_session_events.c.message_id).order_by(
+ show_session_events.c.id
+ )
+ ).all()
+
+ assert [text for text, _source, _context in runs] == [
+ "first show annotation",
+ "second show annotation",
+ ]
+ assert [row["native_message_id"] for row in visible] == [
+ "show:show_evt_identity_1",
+ "show:show_evt_identity_2",
+ ]
+ assert event_links == [
+ ("show_evt_identity_1", visible[0]["id"]),
+ ("show_evt_identity_2", visible[1]["id"]),
+ ]
+
+
+def test_async_dispatch_flushes_queue_on_turn_end(monkeypatch, tmp_path):
+ """When a turn ends, messages queued (send-while-busy) during it are popped,
+ merged (newline-joined) into ONE user row, and run as the next turn —
+ draining the queue. Exercises the controller-side flush wiring end to end."""
+ 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("AVIBE_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_flush", now="2026-05-31T00:00:00Z"
+ )
+ _seed_project_workdir(conn, scope_id, tmp_path)
+ session = sessions_service.create_session(
+ conn, scope_id=scope_id, agent_backend="claude", agent_name="worker"
+ )
+ session_id = session["id"]
+
+ 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.append(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type=messages_service.QUEUED_TYPE,
+ text="q1",
+ author_id="remote:user-a",
+ metadata={"_web_push_user_key": "remote:user-a"},
+ )
+ messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type=messages_service.QUEUED_TYPE,
+ text="q2",
+ )
+ controller.mark_turn_complete(ctx) # release each turn immediately
+ return None
+
+ controller = _build_controller_double(handler=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 turn"})
+ # Wait for the first turn AND the flush turn to both drain the queue.
+ for _ in range(200):
+ if len(seen_texts) >= 2 and session_id not in app.state.in_flight_dispatches:
+ break
+ await asyncio.sleep(0.02)
+
+ asyncio.run(_go())
+ # First the user's turn, then ONE merged flush turn for the two queued msgs.
+ assert seen_texts == ["first turn", "q1\nq2"]
+ with engine.connect() as conn:
+ assert messages_service.list_queued(conn, session_id) == []
+ transcript = messages_service.list_session_messages(conn, session_id=session_id, types=("user",))
+ assert [m["text"] for m in transcript["messages"]] == ["q1\nq2"], "the flush persisted one merged user row"
+ assert transcript["messages"][0]["author_id"] == "remote:user-a"
+ assert transcript["messages"][0]["metadata"]["_web_push_user_key"] == "remote:user-a"
+
+
+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("AVIBE_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"
+ )
+ _seed_project_workdir(conn, scope_id, tmp_path)
+ 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 TurnDispatchOutcome(error=None, settled_by=SETTLED_BY_TERMINAL_RESULT)
+ 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_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."""
+ controller = _build_controller_double()
+ controller.agent_service.runtime_turn_started.return_value = True
+ 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:
+ 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"] = session_turns.Turn(
+ task=task,
+ context=MessageContext(
+ user_id="U",
+ channel_id="C",
+ platform="avibe",
+ platform_specific={"agent_session_target": {"agent_backend": "opencode"}},
+ ),
+ )
+ 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
+ assert busy["native_turn_started"] is True
+ assert busy["backend"] == "opencode"
+
+
+def test_cancel_returns_404_when_session_not_in_flight():
+ 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:
+ return await client.post("/internal/cancel/ses_unknown")
+
+ resp = asyncio.run(_go())
+ assert resp.status_code == 404
+ body = resp.json()
+ assert body["ok"] is False
+ 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:
@@ -1164,7 +2356,7 @@ def test_release_for_backend_refresh_leaves_other_backend_turn_running():
def test_backend_drain_queues_idle_session_without_dispatching():
controller = _build_controller_double()
manager = session_turns.SessionTurnManager(controller)
- enqueue = Mock()
+ enqueue = Mock(return_value=True)
context = MessageContext(user_id="U", channel_id="ses_codex", platform="avibe")
context.platform_specific = {
"agent_session_id": "ses_codex",
@@ -1177,17 +2369,44 @@ def test_backend_drain_queues_idle_session_without_dispatching():
result = asyncio.run(_go())
- assert result == "enqueued"
+ assert result == session_turns.TurnSubmissionResult(
+ route="enqueued",
+ queue_persisted=True,
+ )
enqueue.assert_called_once_with()
assert manager.is_in_flight("ses_codex") is False
assert manager._deferred_restart_sessions == {"codex": {"ses_codex"}}
+def test_backend_drain_exposes_failed_queue_persistence():
+ controller = _build_controller_double()
+ manager = session_turns.SessionTurnManager(controller)
+ enqueue = Mock(return_value=False)
+ context = MessageContext(user_id="U", channel_id="ses_codex", platform="avibe")
+ context.platform_specific = {
+ "agent_session_id": "ses_codex",
+ "agent_session_target": {"agent_backend": "codex"},
+ }
+
+ async def _go():
+ manager.begin_backend_drain("codex")
+ return await manager.submit("ses_codex", context, "next", enqueue=enqueue)
+
+ result = asyncio.run(_go())
+
+ assert result == session_turns.TurnSubmissionResult(
+ route="enqueued",
+ queue_persisted=False,
+ )
+ enqueue.assert_called_once_with()
+ assert manager.is_in_flight("ses_codex") is False
+
+
def test_backend_drain_resolves_inherited_default_agent_backend():
controller = _build_controller_double()
controller.resolve_agent_for_context = Mock(return_value="codex")
manager = session_turns.SessionTurnManager(controller)
- enqueue = Mock()
+ enqueue = Mock(return_value=True)
context = MessageContext(user_id="U", channel_id="ses_default", platform="avibe")
context.platform_specific = {
"agent_session_id": "ses_default",
@@ -1198,7 +2417,10 @@ def test_backend_drain_resolves_inherited_default_agent_backend():
manager.begin_backend_drain("codex")
return await manager.submit("ses_default", context, "next", enqueue=enqueue)
- assert asyncio.run(_go()) == "enqueued"
+ assert asyncio.run(_go()) == session_turns.TurnSubmissionResult(
+ route="enqueued",
+ queue_persisted=True,
+ )
enqueue.assert_called_once_with()
controller.resolve_agent_for_context.assert_called_once_with(context)
assert manager._deferred_restart_sessions == {"codex": {"ses_default"}}
@@ -2912,6 +4134,8 @@ def test_flush_continues_after_dropping_duplicate_scheduled_segment(tmp_path, mo
assert [(text, source) for text, source, _ in runs] == [("queued user follow-up", SOURCE_HUMAN)]
with create_sqlite_engine().begin() as conn:
assert messages_service.list_queued(conn, session_id) == []
+ visible = messages_service.list_session_messages(conn, session_id=session_id, types=("user",))
+ assert runs[0][2].message_id == visible["messages"][0]["id"]
def test_flush_does_not_coalesce_scheduled_callbacks_outside_window(tmp_path, monkeypatch):
diff --git a/tests/test_queued_message_writer_policy.py b/tests/test_queued_message_writer_policy.py
new file mode 100644
index 000000000..d55abe8bb
--- /dev/null
+++ b/tests/test_queued_message_writer_policy.py
@@ -0,0 +1,60 @@
+"""Keep the durable send-while-busy queue owned by controller/storage code."""
+
+from __future__ import annotations
+
+import ast
+from pathlib import Path
+
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+QUEUED_TYPE_WRITER_ALLOWLIST = {
+ "core/internal_server.py",
+ "core/session_turns.py",
+ "storage/messages_service.py",
+ "storage/workbench_sessions_service.py",
+}
+
+
+def _is_queued_type(node: ast.expr) -> bool:
+ return (
+ isinstance(node, ast.Constant)
+ and node.value == "queued"
+ or isinstance(node, ast.Name)
+ and node.id == "QUEUED_TYPE"
+ or isinstance(node, ast.Attribute)
+ and node.attr == "QUEUED_TYPE"
+ )
+
+
+def _writes_queued_message_type(tree: ast.AST) -> bool:
+ for node in ast.walk(tree):
+ if (
+ isinstance(node, ast.keyword)
+ and node.arg in {"type", "message_type"}
+ and _is_queued_type(node.value)
+ ):
+ return True
+ if isinstance(node, ast.Dict):
+ for key, value in zip(node.keys, node.values, strict=True):
+ if (
+ isinstance(key, ast.Constant)
+ and key.value in {"type", "message_type"}
+ and _is_queued_type(value)
+ ):
+ return True
+ return False
+
+
+def test_only_controller_and_storage_modules_write_queued_message_type():
+ # ``queued`` is executable queue state, not a Web presentation state. Keep
+ # its writers confined to the controller and storage ownership boundary.
+ writer_modules = {
+ path.relative_to(REPO_ROOT).as_posix()
+ for root in ("core", "storage", "vibe")
+ for path in (REPO_ROOT / root).rglob("*.py")
+ if _writes_queued_message_type(
+ ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
+ )
+ }
+
+ assert writer_modules <= QUEUED_TYPE_WRITER_ALLOWLIST
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index 24c9dfb34..01ff269bc 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -3359,7 +3359,9 @@ def test_workbench_turn_settles_its_agent_run_when_no_result_arrives(
)
async def _exercise() -> None:
- assert await manager.submit(session_id, context, "stop me", source=SOURCE_SCHEDULED) == "ran"
+ assert (
+ await manager.submit(session_id, context, "stop me", source=SOURCE_SCHEDULED)
+ ).route == "ran"
for _ in range(400):
if request_store.get_run(primary)["status"] != "running":
break
@@ -3429,8 +3431,7 @@ def test_backend_refresh_settles_its_run_as_a_refresh_not_a_user_stop(
async def _exercise() -> None:
assert (
await manager.submit(session_id, context, "interrupted by a config save", source=SOURCE_SCHEDULED)
- == "ran"
- )
+ ).route == "ran"
await asyncio.wait_for(dispatch_started.wait(), timeout=5)
released = await manager.release_for_backend_refresh(
backend="codex", base_session_ids={session_id}
@@ -3501,8 +3502,7 @@ def test_turn_only_result_leaves_an_activity_owned_run_alone(
await manager.submit(
session_id, context, "delivery failed, activity requeued", source=SOURCE_SCHEDULED
)
- == "ran"
- )
+ ).route == "ran"
for _ in range(400):
if session_id not in manager.in_flight:
break
@@ -3614,8 +3614,7 @@ def test_sweep_spares_a_hold_parked_behind_a_live_session_turn(
await manager.submit(
session_id, context, "the long legitimate turn", source=SOURCE_SCHEDULED
)
- == "ran"
- )
+ ).route == "ran"
await asyncio.wait_for(dispatch_started.wait(), timeout=5)
assert manager.busy_session_ids() == {session_id}
diff --git a/tests/test_show_git_turn_entrypoints.py b/tests/test_show_git_turn_entrypoints.py
index 470b8e236..84f81c4b3 100644
--- a/tests/test_show_git_turn_entrypoints.py
+++ b/tests/test_show_git_turn_entrypoints.py
@@ -205,7 +205,7 @@ def test_all_turn_entrypoints_reach_checkpoint_subscriber(monkeypatch, tmp_path)
contexts = {
"im_message": _context("im_message", platform="slack"),
"workbench_chat": _context("workbench_chat", platform="avibe"),
- "internal_dispatch": _context("internal_dispatch", platform="avibe"),
+ "show_page": _context("show_page", platform="avibe"),
"agent_run_sync": _context("agent_run_sync", platform="slack", trigger_kind="agent_run"),
"agent_run_async": _context("agent_run_async", platform="slack", trigger_kind="agent_run"),
"scheduled_task": _context("scheduled_task", platform="slack", trigger_kind="scheduled"),
@@ -278,10 +278,14 @@ def test_all_turn_entrypoints_reach_checkpoint_subscriber(monkeypatch, tmp_path)
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
response = await client.post(
- "/internal/dispatch",
- json={"session_id": "ses_internal_dispatch", "entrypoint": "internal_dispatch"},
+ "/internal/dispatch_async",
+ json={"session_id": "ses_show_page", "entrypoint": "show_page"},
)
- assert response.status_code == 200
+ assert response.status_code == 202
+ for _ in range(100):
+ if checkpoint_calls["ses_show_page"] == [PRE_TURN, POST_TURN]:
+ break
+ await asyncio.sleep(0.01)
# Sync and async CLI modes enqueue the same Agent Run execution; only
# the CLI caller's wait behavior differs. Exercise that executor twice.
diff --git a/tests/test_show_pages.py b/tests/test_show_pages.py
index 1b68a7d36..0b3267ab9 100644
--- a/tests/test_show_pages.py
+++ b/tests/test_show_pages.py
@@ -3021,7 +3021,10 @@ def test_show_event_cli_dispatch_fallback_records_and_dispatches(monkeypatch, tm
dispatched = []
async def _fake_run_dispatch(event):
+ from vibe import ui_server
+
dispatched.append(event)
+ return ui_server._ShowEventDispatchOutcome.ACCEPTED
monkeypatch.setattr("vibe.ui_server._run_show_event_dispatch", _fake_run_dispatch)
@@ -3049,6 +3052,286 @@ def test_show_event_cli_dispatch_fallback_records_and_dispatches(monkeypatch, tm
assert conn.execute(select(show_session_events.c.id)).scalar_one() == payload["event"]["id"]
+def test_show_event_cli_embedded_dispatch_fallback_uses_sync_bridge(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ _save_config()
+ monkeypatch.setattr(cli.runtime, "read_status", lambda: {"ui_pid": None})
+ captured = {}
+
+ def fake_record(session_id, payload, *, dispatch_sync):
+ captured.update(
+ session_id=session_id,
+ payload=payload,
+ dispatch_sync=dispatch_sync,
+ )
+ return {"id": "show_evt_local", "type": payload["type"], "message_id": "msg_local"}
+
+ monkeypatch.setattr("vibe.ui_server.record_local_show_event", fake_record)
+ args = cli.build_parser().parse_args(
+ [
+ "show",
+ "event",
+ "--session-id",
+ "ses123",
+ "--event-json",
+ json.dumps(
+ {
+ "type": "human.annotation.created",
+ "annotation": {"comment": "Deliver me.", "dispatch": True},
+ }
+ ),
+ "--json",
+ ]
+ )
+
+ assert cli.cmd_show(args) == 0
+ assert captured["dispatch_sync"] is True
+ assert captured["payload"]["annotation"]["dispatch"] is True
+
+
[email protected]("blank_event_id", [None, "", " "])
+def test_show_event_cli_timeout_replaces_blank_id_before_local_retry(
+ monkeypatch,
+ tmp_path,
+ blank_event_id,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ _save_config()
+ monkeypatch.setattr(cli.runtime, "read_status", lambda: {"ui_pid": 123})
+ posted = {}
+
+ def timeout_after_receiving(request, **_kwargs):
+ posted.update(json.loads(request.data.decode("utf-8")))
+ raise TimeoutError()
+
+ monkeypatch.setattr(cli.urllib.request, "urlopen", timeout_after_receiving)
+ replayed = []
+
+ def record_local(session_id, payload, *, dispatch_sync):
+ replayed.append((session_id, payload, dispatch_sync))
+ return {
+ "id": payload["id"],
+ "type": payload["type"],
+ "message_id": "msg_local",
+ }
+
+ monkeypatch.setattr(
+ "vibe.ui_server.record_local_show_event",
+ record_local,
+ )
+ args = cli.build_parser().parse_args(
+ [
+ "show",
+ "event",
+ "--session-id",
+ "ses123",
+ "--event-json",
+ json.dumps(
+ {
+ "id": blank_event_id,
+ "type": "human.annotation.created",
+ "annotation": {"comment": "Maybe accepted.", "dispatch": True},
+ }
+ ),
+ "--json",
+ ]
+ )
+
+ assert cli.cmd_show(args) == 0
+ assert len(replayed) == 1
+ replay_session_id, replay_payload, dispatch_sync = replayed[0]
+ assert replay_session_id == "ses123"
+ assert dispatch_sync is True
+ assert posted["id"].startswith("show_evt_")
+ assert replay_payload["id"] == posted["id"]
+
+
+def test_show_event_cli_timeout_poll_reuses_one_event_store(monkeypatch):
+ from core.show_session_events import (
+ DISPATCH_ACCEPTED,
+ DISPATCH_IN_FLIGHT,
+ ShowDispatchSettlement,
+ ShowDispatchStatus,
+ )
+
+ instances = []
+
+ class FakeStore:
+ def __init__(self):
+ self.states = iter((DISPATCH_IN_FLIGHT, DISPATCH_ACCEPTED))
+ self.closed = False
+ instances.append(self)
+
+ def get_dispatch_status(self, session_id, event_id):
+ return ShowDispatchStatus(state=next(self.states))
+
+ def get_event(self, session_id, event_id):
+ return {"id": event_id, "session_id": session_id}
+
+ def reconcile_dispatch_settlement(self, session_id, event_id):
+ return ShowDispatchSettlement(
+ status=ShowDispatchStatus(state=DISPATCH_ACCEPTED),
+ message={
+ "id": "msg_poll_once",
+ "session_id": session_id,
+ "type": "user",
+ },
+ )
+
+ def close(self):
+ self.closed = True
+
+ monkeypatch.setattr("core.show_session_events.ShowSessionEventStore", FakeStore)
+ monkeypatch.setattr(cli.time, "sleep", lambda _delay: None)
+
+ resolved = cli._resolve_show_event_after_ambiguous_live_timeout(
+ "ses123",
+ {"id": "show_evt_poll_once"},
+ wait_seconds=1,
+ )
+
+ assert resolved == {"id": "show_evt_poll_once", "session_id": "ses123"}
+ assert len(instances) == 1
+ assert instances[0].closed
+
+
+def test_show_event_cli_pending_response_polls_instead_of_falling_back(
+ monkeypatch,
+):
+ payload = {
+ "id": "show_evt_pending_response",
+ "type": "human.annotation.created",
+ }
+ resolved = {"id": payload["id"], "session_id": "ses123"}
+ polls = []
+
+ class PendingResponse:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_args):
+ return False
+
+ def read(self):
+ return json.dumps(
+ {
+ "ok": True,
+ "dispatch_pending": True,
+ "event": payload,
+ }
+ ).encode()
+
+ monkeypatch.setattr(
+ cli,
+ "_local_show_events_url",
+ lambda _session_id: "http://127.0.0.1:5123/api/show/sessions/ses123/events",
+ )
+ monkeypatch.setattr(
+ cli.urllib.request,
+ "urlopen",
+ lambda _request, **_kwargs: PendingResponse(),
+ )
+ monkeypatch.setattr(
+ cli,
+ "_resolve_show_event_after_ambiguous_live_timeout",
+ lambda session_id, event: polls.append((session_id, event)) or resolved,
+ )
+
+ result = cli._post_show_event_to_live_ui("ses123", payload)
+
+ assert result == resolved
+ assert polls == [("ses123", payload)]
+
+
+def test_show_event_cli_pending_timeout_is_localized(monkeypatch):
+ from core.show_session_events import (
+ DISPATCH_IN_FLIGHT,
+ ShowDispatchStatus,
+ ShowSessionEventError,
+ )
+
+ class FakeStore:
+ def get_dispatch_status(self, _session_id, _event_id):
+ return ShowDispatchStatus(state=DISPATCH_IN_FLIGHT)
+
+ def close(self):
+ return None
+
+ class _Config:
+ language = "zh"
+
+ monkeypatch.setattr("core.show_session_events.ShowSessionEventStore", FakeStore)
+ monkeypatch.setattr("core.show_session_events.V2Config.load", lambda: _Config())
+ monkeypatch.setattr(cli.time, "monotonic", iter((0.0, 2.0)).__next__)
+
+ with pytest.raises(ShowSessionEventError) as exc_info:
+ cli._resolve_show_event_after_ambiguous_live_timeout(
+ "ses123",
+ {"id": "show_evt_pending_i18n"},
+ wait_seconds=1,
+ )
+
+ assert exc_info.value.code == "show_event_dispatch_pending"
+ assert str(exc_info.value) == "Show 事件可能仍在处理中,未在本地重复提交。"
+
+
+def test_show_event_cli_http_502_replays_same_event_identity_locally(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ _save_config()
+ monkeypatch.setattr(cli.runtime, "read_status", lambda: {"ui_pid": 123})
+ posted = {}
+
+ def bad_gateway_after_receiving(request, **_kwargs):
+ posted.update(json.loads(request.data.decode("utf-8")))
+ raise cli.urllib.error.HTTPError(
+ request.full_url,
+ 502,
+ "Bad Gateway",
+ {},
+ None,
+ )
+
+ monkeypatch.setattr(cli.urllib.request, "urlopen", bad_gateway_after_receiving)
+ replayed = []
+
+ def record_local(session_id, payload, *, dispatch_sync):
+ replayed.append((session_id, payload, dispatch_sync))
+ return {
+ "id": payload["id"],
+ "type": payload["type"],
+ "message_id": "msg_local",
+ }
+
+ monkeypatch.setattr("vibe.ui_server.record_local_show_event", record_local)
+ args = cli.build_parser().parse_args(
+ [
+ "show",
+ "event",
+ "--session-id",
+ "ses123",
+ "--event-json",
+ json.dumps(
+ {
+ "type": "human.annotation.created",
+ "annotation": {"comment": "Retry after 502.", "dispatch": True},
+ }
+ ),
+ "--json",
+ ]
+ )
+
+ assert cli.cmd_show(args) == 0
+ assert len(replayed) == 1
+ replay_session_id, replay_payload, dispatch_sync = replayed[0]
+ assert replay_session_id == "ses123"
+ assert dispatch_sync is True
+ assert posted["id"].startswith("show_evt_")
+ assert replay_payload["id"] == posted["id"]
+
+
def test_show_event_cli_fallback_rejects_mismatched_session_id(monkeypatch, tmp_path, capsys):
from sqlalchemy import select
diff --git a/tests/test_show_session_events.py b/tests/test_show_session_events.py
index 35a6f1942..bd61779ac 100644
--- a/tests/test_show_session_events.py
+++ b/tests/test_show_session_events.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import asyncio
import base64
import json
import struct
@@ -9,7 +10,23 @@ from pathlib import Path
import pytest
from sqlalchemy import select
-from core.show_session_events import ShowSessionEventError, ShowSessionEventStore, _format_transcript_text
+from core.show_session_events import (
+ DISPATCH_ACCEPTED,
+ DISPATCH_ARCHIVED,
+ DISPATCH_FAILED,
+ DISPATCH_IN_FLIGHT,
+ DISPATCH_NONE,
+ ShowDispatchSettlement,
+ ShowDispatchStatus,
+ ShowSessionEventError,
+ ShowSessionEventStore,
+ _format_transcript_text,
+ claim_show_dispatch,
+ localized_show_event_error,
+ settle_show_dispatch,
+ show_dispatch_attempt,
+ show_event_requests_dispatch,
+)
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
from storage.models import agent_sessions, media_objects, messages, show_session_events
@@ -216,8 +233,6 @@ def test_show_event_store_keeps_remote_author_out_of_intent_fallback_text(isolat
def test_annotation_control_event_has_no_transcript_or_dispatch(isolated_state):
- from vibe.ui_server import _show_event_requests_dispatch
-
_seed_session()
store = ShowSessionEventStore()
try:
@@ -236,7 +251,7 @@ def test_annotation_control_event_has_no_transcript_or_dispatch(isolated_state):
assert event["transcript_text"] == ""
assert event["message_id"] is None
assert event["message"] is None
- assert _show_event_requests_dispatch(event) is False
+ assert show_event_requests_dispatch(event) is False
engine = create_sqlite_engine()
with engine.connect() as conn:
@@ -420,6 +435,52 @@ def test_show_event_store_materializes_screenshot_attachment(isolated_state):
assert "dataUrl" not in stored_payload["screenshot"]
+def test_show_event_store_rolls_back_media_from_losing_idempotent_insert(
+ isolated_state,
+ monkeypatch,
+):
+ import core.show_session_events as show_events
+
+ _seed_session()
+ payload = {
+ "id": "show_evt_screenshot_race",
+ "type": "human.annotation.created",
+ "annotation": {
+ "intent": "comment",
+ "comment": "Keep only the winning screenshot.",
+ "screenshot": {
+ "dataUrl": _image_data_url("image/png", _png_bytes(4, 3)),
+ },
+ },
+ }
+ store = ShowSessionEventStore()
+ try:
+ winner = store.append("ses_mark", payload)
+ real_existing = show_events._existing_event_payload
+ calls = 0
+
+ def miss_preflight_once(*args, **kwargs):
+ nonlocal calls
+ calls += 1
+ if calls == 1:
+ return None
+ return real_existing(*args, **kwargs)
+
+ monkeypatch.setattr(show_events, "_existing_event_payload", miss_preflight_once)
+ replay = store.append("ses_mark", payload)
+ finally:
+ store.close()
+
+ with create_sqlite_engine().connect() as conn:
+ media_rows = conn.execute(select(media_objects)).mappings().all()
+ attachment_dir = Path(winner["payload"]["screenshot"]["path"]).parent
+ assert replay["id"] == winner["id"]
+ assert len(media_rows) == 1
+ assert [path.resolve() for path in attachment_dir.iterdir()] == [
+ Path(winner["payload"]["screenshot"]["path"]).resolve()
+ ]
+
+
def test_show_event_store_materializes_webp_without_conversion(isolated_state):
_seed_session()
raw = base64.b64decode("UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA")
@@ -731,6 +792,7 @@ def test_show_event_store_records_intent_dispatch_payload(isolated_state):
"dispatch": True,
},
},
+ reserve_dispatch=True,
)
finally:
store.close()
@@ -878,47 +940,818 @@ def test_show_event_store_lists_after_cursor(isolated_state):
assert [event["id"] for event in page["events"]] == [second["id"]]
-def test_show_event_dispatch_streams_via_stream_dispatch(isolated_state, monkeypatch):
- """Regression guard: the Show-page dispatch flow MUST call
- ``internal_client.stream_dispatch`` and re-publish each turn event as
- ``show.dispatch``. Step 6 removed ``stream_dispatch`` as dead, but the merged
- show-annotation feature still depends on it — without this test that removal
- passed CI yet broke the Show page at runtime (Codex P2)."""
- import asyncio
+def test_dispatching_show_event_reserves_pending_transcript_row(isolated_state):
+ from storage import messages_service
+
+ _seed_session("ses_show")
+ store = ShowSessionEventStore()
+ try:
+ dispatching = store.append(
+ "ses_show",
+ {
+ "type": "human.annotation.created",
+ "annotation": {"intent": "comment", "comment": "Queue this.", "dispatch": True},
+ },
+ reserve_dispatch=True,
+ )
+ non_dispatching = store.append(
+ "ses_show",
+ {
+ "type": "human.annotation.created",
+ "annotation": {"intent": "comment", "comment": "Record only.", "dispatch": False},
+ },
+ )
+ finally:
+ store.close()
+
+ assert dispatching["message"]["type"] == messages_service.PENDING_TYPE
+ assert non_dispatching["message"]["type"] == "user"
+ engine = create_sqlite_engine()
+ with engine.connect() as conn:
+ visible = messages_service.list_session_messages(conn, session_id="ses_show", types=("user",))
+ queued = messages_service.list_queued(conn, "ses_show")
+ assert [message["text"] for message in visible["messages"]] == [non_dispatching["transcript_text"]]
+ assert queued == []
+
+
+def test_dispatching_show_event_retry_reuses_event_and_transcript_row(isolated_state):
+ from storage import messages_service
+
+ _seed_session("ses_show_retry")
+ payload = {
+ "id": "show_evt_retry_identity",
+ "type": "human.annotation.created",
+ "annotation": {
+ "intent": "comment",
+ "comment": "Deliver exactly once.",
+ "dispatch": True,
+ },
+ }
+ store = ShowSessionEventStore()
+ try:
+ first = store.append("ses_show_retry", payload, reserve_dispatch=True)
+ replay = store.append("ses_show_retry", payload, reserve_dispatch=True)
+ finally:
+ store.close()
+
+ assert replay["id"] == first["id"]
+ assert replay["message_id"] == first["message_id"]
+ assert replay["message"]["type"] == messages_service.PENDING_TYPE
+ engine = create_sqlite_engine()
+ with engine.connect() as conn:
+ event_rows = conn.execute(
+ select(show_session_events).where(
+ show_session_events.c.id == "show_evt_retry_identity"
+ )
+ ).mappings().all()
+ message_rows = conn.execute(
+ select(messages).where(
+ messages.c.native_message_id == "show:show_evt_retry_identity"
+ )
+ ).mappings().all()
+ assert len(event_rows) == 1
+ assert len(message_rows) == 1
+
+
+def test_show_event_store_rejects_reused_id_with_different_contents(isolated_state):
+ _seed_session("ses_show_conflict")
+ first_payload = {
+ "id": "show_evt_bound_identity",
+ "type": "human.annotation.created",
+ "annotation": {
+ "intent": "comment",
+ "comment": "Deliver the original annotation.",
+ "dispatch": True,
+ },
+ }
+ conflicting_payload = {
+ **first_payload,
+ "annotation": {
+ **first_payload["annotation"],
+ "comment": "Silently replace it with different work.",
+ },
+ }
+
+ store = ShowSessionEventStore()
+ try:
+ first = store.append("ses_show_conflict", first_payload, reserve_dispatch=True)
+ with pytest.raises(ShowSessionEventError) as exc_info:
+ store.append(
+ "ses_show_conflict",
+ conflicting_payload,
+ reserve_dispatch=True,
+ )
+ stored = store.get_event("ses_show_conflict", first["id"])
+ finally:
+ store.close()
+
+ assert exc_info.value.code == "event_id_conflict"
+ assert stored is not None
+ assert stored["payload"]["comment"] == "Deliver the original annotation."
+
+
+def test_show_event_store_fingerprint_includes_sibling_anchor(isolated_state):
+ _seed_session("ses_show_anchor_conflict")
+ original = {
+ "id": "show_evt_anchor_identity",
+ "type": "human.annotation.created",
+ "anchor": {"selector": "#summary"},
+ "annotation": {
+ "intent": "comment",
+ "comment": "Review this target.",
+ "dispatch": True,
+ },
+ }
+ store = ShowSessionEventStore()
+ try:
+ store.append("ses_show_anchor_conflict", original, reserve_dispatch=True)
+ with pytest.raises(ShowSessionEventError) as exc_info:
+ store.append(
+ "ses_show_anchor_conflict",
+ {**original, "anchor": {"selector": "#other"}},
+ reserve_dispatch=True,
+ )
+ finally:
+ store.close()
+
+ assert exc_info.value.code == "event_id_conflict"
+
+
+def test_show_dispatch_state_owns_claim_recovery_and_acceptance(
+ isolated_state,
+ monkeypatch,
+):
+ import core.show_session_events as show_events
+
+ _seed_session("ses_show_state")
+ store = ShowSessionEventStore()
+ try:
+ event = store.append(
+ "ses_show_state",
+ {
+ "id": "show_evt_state_machine",
+ "type": "human.annotation.created",
+ "annotation": {
+ "intent": "comment",
+ "comment": "Dispatch exactly once.",
+ "dispatch": True,
+ },
+ },
+ reserve_dispatch=True,
+ )
+ finally:
+ store.close()
+
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ initial = show_events.get_show_dispatch_status(
+ conn,
+ event["id"],
+ session_id="ses_show_state",
+ )
+ first = claim_show_dispatch(
+ conn,
+ event["id"],
+ session_id="ses_show_state",
+ owner="101:1.0",
+ )
+ assert initial is not None and initial.state == DISPATCH_NONE
+ assert first is not None and first.claimed
+ assert first.state == DISPATCH_IN_FLIGHT
+ assert first.claimed_at
+
+ monkeypatch.setattr(show_events, "_show_dispatch_owner_is_alive", lambda owner: True)
+ with engine.begin() as conn:
+ live = claim_show_dispatch(
+ conn,
+ event["id"],
+ session_id="ses_show_state",
+ owner="202:2.0",
+ )
+ assert live is not None and not live.claimed
+ assert live.owner == "101:1.0"
+
+ monkeypatch.setattr(show_events, "_show_dispatch_owner_is_alive", lambda owner: False)
+ monkeypatch.setattr(show_events, "_show_dispatch_claim_is_stale", lambda claimed_at: True)
+ with engine.begin() as conn:
+ recovered = claim_show_dispatch(
+ conn,
+ event["id"],
+ session_id="ses_show_state",
+ owner="202:2.0",
+ )
+ assert recovered is not None and recovered.claimed
+ assert settle_show_dispatch(
+ conn,
+ event["id"],
+ session_id="ses_show_state",
+ owner="202:2.0",
+ state=DISPATCH_ACCEPTED,
+ )
+ assert not settle_show_dispatch(
+ conn,
+ event["id"],
+ session_id="ses_show_state",
+ owner="202:2.0",
+ state=DISPATCH_FAILED,
+ )
+ accepted = show_events.get_show_dispatch_status(
+ conn,
+ event["id"],
+ session_id="ses_show_state",
+ )
+ assert accepted is not None and accepted.state == DISPATCH_ACCEPTED
+
+
[email protected]("initial_state", (DISPATCH_NONE, DISPATCH_FAILED))
+def test_claim_persists_archived_when_session_was_archived_before_claim(
+ isolated_state,
+ initial_state,
+):
+ from core.services import sessions as sessions_service
+
+ _seed_session("ses_show_preclaim_archive")
+ store = ShowSessionEventStore()
+ try:
+ event = store.append(
+ "ses_show_preclaim_archive",
+ {
+ "id": f"show_evt_preclaim_archive_{initial_state}",
+ "type": "human.annotation.created",
+ "annotation": {
+ "comment": "This session was archived before dispatch.",
+ "dispatch": True,
+ },
+ },
+ reserve_dispatch=True,
+ )
+ finally:
+ store.close()
+
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ if initial_state == DISPATCH_FAILED:
+ first = claim_show_dispatch(
+ conn,
+ event["id"],
+ session_id="ses_show_preclaim_archive",
+ owner="1:old-process:failed-attempt",
+ )
+ assert first is not None and first.claimed
+ assert settle_show_dispatch(
+ conn,
+ event["id"],
+ session_id="ses_show_preclaim_archive",
+ owner="1:old-process:failed-attempt",
+ state=DISPATCH_FAILED,
+ )
+ sessions_service.archive_session(
+ conn,
+ "ses_show_preclaim_archive",
+ )
+
+ with engine.begin() as conn:
+ archived = claim_show_dispatch(
+ conn,
+ event["id"],
+ session_id="ses_show_preclaim_archive",
+ owner="1:new-process:retry-attempt",
+ )
+
+ assert archived is not None
+ assert archived.state == DISPATCH_ARCHIVED
+ assert archived.claimed is False
+ store = ShowSessionEventStore()
+ try:
+ persisted = store.get_dispatch_status(
+ "ses_show_preclaim_archive",
+ event["id"],
+ )
+ finally:
+ store.close()
+ assert persisted is not None
+ assert persisted.state == DISPATCH_ARCHIVED
+
+
+def test_same_process_show_dispatch_claim_uses_live_attempt_not_age(
+ isolated_state,
+ monkeypatch,
+):
+ from core import show_session_events as show_events
+
+ _seed_session("ses_show_attempt")
+ store = ShowSessionEventStore()
+ try:
+ event = store.append(
+ "ses_show_attempt",
+ {
+ "id": "show_evt_attempt_identity",
+ "type": "human.annotation.created",
+ "annotation": {
+ "comment": "Keep a slow live attempt exclusive.",
+ "dispatch": True,
+ },
+ },
+ reserve_dispatch=True,
+ )
+ finally:
+ store.close()
+
+ engine = create_sqlite_engine()
+ monkeypatch.setattr(
+ show_events,
+ "_show_dispatch_claim_is_stale",
+ lambda _claimed_at: True,
+ )
+ with show_dispatch_attempt() as live_owner:
+ with engine.begin() as conn:
+ first = claim_show_dispatch(
+ conn,
+ event["id"],
+ session_id="ses_show_attempt",
+ owner=live_owner,
+ )
+ assert first is not None and first.claimed
+
+ with show_dispatch_attempt() as competing_owner:
+ with engine.begin() as conn:
+ blocked = claim_show_dispatch(
+ conn,
+ event["id"],
+ session_id="ses_show_attempt",
+ owner=competing_owner,
+ )
+ assert blocked is not None and not blocked.claimed
+ assert blocked.owner == live_owner
+
+ monkeypatch.setattr(
+ show_events,
+ "_show_dispatch_claim_is_stale",
+ lambda _claimed_at: False,
+ )
+ monkeypatch.setattr(
+ show_events,
+ "_show_dispatch_owner_is_alive",
+ lambda _owner: True,
+ )
+ with show_dispatch_attempt() as retry_owner:
+ with engine.begin() as conn:
+ recovered = claim_show_dispatch(
+ conn,
+ event["id"],
+ session_id="ses_show_attempt",
+ owner=retry_owner,
+ )
+ assert recovered is not None and recovered.claimed
+ assert recovered.owner == retry_owner
+
+
+def test_localized_show_event_errors_follow_configured_language(
+ monkeypatch,
+):
+ class _Config:
+ language = "zh"
+
+ monkeypatch.setattr(
+ "core.show_session_events.V2Config.load",
+ lambda: _Config(),
+ )
+
+ conflict = localized_show_event_error("event_id_conflict")
+ pending = localized_show_event_error("show_event_dispatch_pending")
+
+ assert conflict.code == "event_id_conflict"
+ assert str(conflict) == "此 Show 事件 ID 已绑定到不同的事件内容。"
+ assert pending.code == "show_event_dispatch_pending"
+ assert str(pending) == "Show 事件可能仍在处理中,未在本地重复提交。"
+
+
+ (
+ "state",
+ "message_type",
+ "promoted",
+ "publish_message",
+ "publish_queue",
+ "report_success",
+ ),
+ [
+ (DISPATCH_NONE, "pending", False, False, False, False),
+ (DISPATCH_IN_FLIGHT, "pending", False, False, False, False),
+ (DISPATCH_ACCEPTED, "pending", False, False, False, False),
+ (DISPATCH_ACCEPTED, "user", True, True, False, True),
+ (DISPATCH_ACCEPTED, "user", False, False, False, True),
+ (DISPATCH_ACCEPTED, "queued", False, False, True, True),
+ (DISPATCH_FAILED, "user", True, True, False, False),
+ (DISPATCH_ARCHIVED, "user", False, False, False, False),
+ ],
+)
+def test_show_dispatch_outward_promises_derive_from_observed_settlement(
+ state,
+ message_type,
+ promoted,
+ publish_message,
+ publish_queue,
+ report_success,
+):
+ settlement = ShowDispatchSettlement(
+ status=ShowDispatchStatus(state=state),
+ message={"id": "msg_settlement", "type": message_type},
+ message_promoted=promoted,
+ )
+
+ assert settlement.can_publish_message_new is publish_message
+ assert settlement.can_publish_queue_updated is publish_queue
+ assert settlement.can_report_success is report_success
+
+
+def test_startup_reconciles_accepted_dispatch_with_pending_transcript(
+ isolated_state,
+):
+ from storage import messages_service
+ from vibe import ui_server
+
+ _seed_session("ses_show_restart")
+ store = ShowSessionEventStore()
+ try:
+ event = store.append(
+ "ses_show_restart",
+ {
+ "id": "show_evt_restart_reconcile",
+ "type": "human.annotation.created",
+ "annotation": {
+ "comment": "Recover my accepted prompt after restart.",
+ "dispatch": True,
+ },
+ },
+ reserve_dispatch=True,
+ )
+ finally:
+ store.close()
+
+ with create_sqlite_engine().begin() as conn:
+ claimed = claim_show_dispatch(
+ conn,
+ event["id"],
+ session_id="ses_show_restart",
+ owner="1:old-process:attempt",
+ )
+ assert claimed is not None and claimed.claimed
+ assert settle_show_dispatch(
+ conn,
+ event["id"],
+ session_id="ses_show_restart",
+ owner="1:old-process:attempt",
+ state=DISPATCH_ACCEPTED,
+ )
+ assert event["message"]["type"] == messages_service.PENDING_TYPE
+
+ ui_server.reconcile_show_dispatch_messages_on_startup()
+
+ restarted_store = ShowSessionEventStore()
+ try:
+ recovered = restarted_store.get_event(
+ "ses_show_restart",
+ event["id"],
+ )
+ finally:
+ restarted_store.close()
+ assert recovered is not None
+ assert recovered["message"]["type"] == "user"
+
+
+def test_cli_reports_accepted_dispatch_only_after_linked_message_reconciles(
+ isolated_state,
+):
+ from vibe import cli
+
+ _seed_session("ses_show_cli_settlement")
+ store = ShowSessionEventStore()
+ try:
+ event = store.append(
+ "ses_show_cli_settlement",
+ {
+ "id": "show_evt_cli_settlement",
+ "type": "human.annotation.created",
+ "annotation": {
+ "comment": "Do not report success while I am hidden.",
+ "dispatch": True,
+ },
+ },
+ reserve_dispatch=True,
+ )
+ finally:
+ store.close()
+
+ with create_sqlite_engine().begin() as conn:
+ claimed = claim_show_dispatch(
+ conn,
+ event["id"],
+ session_id="ses_show_cli_settlement",
+ owner="1:cli-process:attempt",
+ )
+ assert claimed is not None and claimed.claimed
+ assert settle_show_dispatch(
+ conn,
+ event["id"],
+ session_id="ses_show_cli_settlement",
+ owner="1:cli-process:attempt",
+ state=DISPATCH_ACCEPTED,
+ )
+
+ recovered = cli._resolve_show_event_after_ambiguous_live_timeout(
+ "ses_show_cli_settlement",
+ {"id": event["id"]},
+ wait_seconds=0,
+ )
+ assert recovered is not None
+ assert recovered["message"]["type"] == "user"
+
+
+def test_concurrent_show_dispatch_replay_reports_in_flight_without_resubmit(
+ isolated_state,
+ monkeypatch,
+):
+ from vibe import internal_client, ui_server
+
+ _seed_session("ses_show_concurrent")
+ store = ShowSessionEventStore()
+ try:
+ event = store.append(
+ "ses_show_concurrent",
+ {
+ "id": "show_evt_concurrent_attempt",
+ "type": "human.annotation.created",
+ "annotation": {
+ "comment": "Submit this once while the first call is active.",
+ "dispatch": True,
+ },
+ },
+ reserve_dispatch=True,
+ )
+ finally:
+ store.close()
+ engine = create_sqlite_engine()
+
+ async def _go():
+ dispatch_entered = asyncio.Event()
+ release_dispatch = asyncio.Event()
+ dispatches = []
+
+ async def slow_dispatch(payload, **_kwargs):
+ dispatches.append(payload)
+ dispatch_entered.set()
+ await release_dispatch.wait()
+ with engine.begin() as conn:
+ assert settle_show_dispatch(
+ conn,
+ payload["show_event_id"],
+ session_id=payload["session_id"],
+ owner=payload["dispatch_owner"],
+ state=DISPATCH_ACCEPTED,
+ )
+ return {"status_code": 202, "body": {"ok": True}}
+
+ monkeypatch.setattr(internal_client, "dispatch_async", slow_dispatch)
+ first_task = asyncio.create_task(
+ ui_server._run_show_event_dispatch(event),
+ )
+ await asyncio.wait_for(dispatch_entered.wait(), timeout=1)
+ replay = await ui_server._run_show_event_dispatch(event)
+ assert replay is ui_server._ShowEventDispatchOutcome.IN_FLIGHT
+ assert len(dispatches) == 1
+ release_dispatch.set()
+ first = await asyncio.wait_for(first_task, timeout=1)
+ return first, replay, dispatches
+
+ first, replay, dispatches = asyncio.run(_go())
+
+ assert first is ui_server._ShowEventDispatchOutcome.ACCEPTED
+ assert replay is ui_server._ShowEventDispatchOutcome.IN_FLIGHT
+ assert len(dispatches) == 1
+
+
+def test_cancelled_show_dispatch_attempt_is_immediately_reclaimable(
+ isolated_state,
+ monkeypatch,
+):
+ from vibe import internal_client, ui_server
+
+ _seed_session("ses_show_cancelled")
+ store = ShowSessionEventStore()
+ try:
+ event = store.append(
+ "ses_show_cancelled",
+ {
+ "id": "show_evt_cancelled_attempt",
+ "type": "human.annotation.created",
+ "annotation": {
+ "comment": "Retry after the first caller is cancelled.",
+ "dispatch": True,
+ },
+ },
+ reserve_dispatch=True,
+ )
+ finally:
+ store.close()
+
+ engine = create_sqlite_engine()
+
+ async def _go():
+ dispatch_entered = asyncio.Event()
+
+ async def cancelled_dispatch(_payload, **_kwargs):
+ dispatch_entered.set()
+ await asyncio.Future()
+
+ monkeypatch.setattr(internal_client, "dispatch_async", cancelled_dispatch)
+ abandoned = asyncio.create_task(
+ ui_server._run_show_event_dispatch(event),
+ )
+ await asyncio.wait_for(dispatch_entered.wait(), timeout=1)
+ abandoned.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await abandoned
+
+ async def accepted_dispatch(payload, **_kwargs):
+ with engine.begin() as conn:
+ assert settle_show_dispatch(
+ conn,
+ payload["show_event_id"],
+ session_id=payload["session_id"],
+ owner=payload["dispatch_owner"],
+ state=DISPATCH_ACCEPTED,
+ )
+ return {"status_code": 202, "body": {"ok": True}}
+
+ monkeypatch.setattr(internal_client, "dispatch_async", accepted_dispatch)
+ return await ui_server._run_show_event_dispatch(event)
+
+ assert asyncio.run(_go()) is ui_server._ShowEventDispatchOutcome.ACCEPTED
+
+
+def test_direct_dispatching_show_event_stays_visible_without_reservation(isolated_state):
+ from storage import messages_service
+
+ _seed_session("ses_show")
+ store = ShowSessionEventStore()
+ try:
+ event = store.append(
+ "ses_show",
+ {
+ "type": "human.annotation.created",
+ "annotation": {
+ "intent": "comment",
+ "comment": "Record this visibly.",
+ "dispatch": True,
+ },
+ },
+ )
+ events = store.list("ses_show")
+ finally:
+ store.close()
+
+ assert event["message"]["type"] == "user"
+ assert [item["id"] for item in events["events"]] == [event["id"]]
+ with create_sqlite_engine().connect() as conn:
+ assert messages_service.list_queued(conn, "ses_show") == []
+
+
+def test_record_local_show_event_dispatch_sync_uses_unified_entry(isolated_state, monkeypatch):
from vibe import internal_client, ui_server
from vibe.sse_broker import broker
+ _seed_session("ses_show")
+ dispatches = []
published: list[tuple[str, dict]] = []
monkeypatch.setattr(broker, "publish", lambda event, data: published.append((event, data)))
- async def fake_stream_dispatch(payload, **kwargs):
- assert payload["session_id"] == "ses_show" and payload["text"] == "do the thing"
- yield ("turn.start", {"session_id": "ses_show"})
- yield ("turn.chunk", {"text": "working", "kind": "notify"})
- yield ("turn.end", {"session_id": "ses_show"})
+ async def fake_dispatch_async(payload, **kwargs):
+ dispatches.append(payload)
+ with create_sqlite_engine().begin() as conn:
+ assert settle_show_dispatch(
+ conn,
+ payload["show_event_id"],
+ session_id=payload["session_id"],
+ owner=payload["dispatch_owner"],
+ state=DISPATCH_ACCEPTED,
+ )
+ return {"status_code": 202, "body": {"ok": True}}
- # setattr requires the attribute to exist — so this also asserts stream_dispatch
- # wasn't removed again.
- monkeypatch.setattr(internal_client, "stream_dispatch", fake_stream_dispatch)
+ monkeypatch.setattr(internal_client, "dispatch_async", fake_dispatch_async)
+ event = ui_server.record_local_show_event(
+ "ses_show",
+ {
+ "type": "human.annotation.created",
+ "annotation": {"intent": "comment", "comment": "Deliver this.", "dispatch": True},
+ },
+ dispatch_sync=True,
+ )
+
+ assert dispatches[0]["user_message_id"] == event["message_id"]
+ assert event["message"]["type"] == "user"
+ assert [name for name, _data in published] == [
+ "show.event",
+ "message.new",
+ "session.activity",
+ ]
+ assert published[1][1]["id"] == event["message_id"]
+
+
+def test_record_local_show_event_reports_failed_sync_dispatch_with_retryable_record(
+ isolated_state,
+ monkeypatch,
+):
+ from storage import messages_service
+ from vibe import internal_client, ui_server
+
+ _seed_session("ses_show")
- asyncio.run(
- ui_server._run_show_event_dispatch(
+ async def fake_dispatch_async(payload, **kwargs):
+ raise internal_client.InternalServerUnavailable("controller unavailable")
+
+ monkeypatch.setattr(internal_client, "dispatch_async", fake_dispatch_async)
+ stored_event = None
+ with pytest.raises(ShowSessionEventError) as exc_info:
+ ui_server.record_local_show_event(
+ "ses_show",
{
- "id": "evt1",
- "session_id": "ses_show",
- "scope_id": "scope1",
- "transcript_text": "do the thing",
- "message_id": "m1",
- }
+ "type": "human.annotation.created",
+ "annotation": {"intent": "comment", "comment": "Record this.", "dispatch": True},
+ },
+ dispatch_sync=True,
)
- )
- assert [d["event"] for (e, d) in published if e == "show.dispatch"] == [
- "turn.start",
- "turn.chunk",
- "turn.end",
- ]
+ assert exc_info.value.code == "show_event_dispatch_failed"
+ store = ShowSessionEventStore()
+ try:
+ stored_event = store.list("ses_show")["events"][0]
+ dispatch_status = store.get_dispatch_status("ses_show", stored_event["id"])
+ finally:
+ store.close()
+ with create_sqlite_engine().connect() as conn:
+ visible = messages_service.list_session_messages(conn, session_id="ses_show", types=("user",))
+ queued = messages_service.list_queued(conn, "ses_show")
+ assert dispatch_status is not None
+ assert dispatch_status.state == DISPATCH_FAILED
+ assert [row["text"] for row in visible["messages"]] == [stored_event["transcript_text"]]
+ assert queued == []
+
+
+def test_ended_ambiguous_show_dispatch_attempt_is_immediately_retryable(
+ isolated_state,
+ monkeypatch,
+):
+ from storage import messages_service
+ from vibe import internal_client, ui_server
+
+ _seed_session("ses_show")
+ attempts = 0
+
+ async def fake_dispatch_async(payload, **kwargs):
+ nonlocal attempts
+ attempts += 1
+ raise internal_client.InternalServerTimeout("acceptance unknown")
+
+ monkeypatch.setattr(internal_client, "dispatch_async", fake_dispatch_async)
+ payload = {
+ "id": "show_evt_ambiguous_timeout",
+ "type": "human.annotation.created",
+ "annotation": {
+ "intent": "comment",
+ "comment": "Do not submit this twice.",
+ "dispatch": True,
+ },
+ }
+
+ for _attempt in range(2):
+ with pytest.raises(ShowSessionEventError) as exc_info:
+ ui_server.record_local_show_event(
+ "ses_show",
+ payload,
+ dispatch_sync=True,
+ )
+ assert exc_info.value.code == "show_event_dispatch_pending"
+
+ store = ShowSessionEventStore()
+ try:
+ event = store.get_event("ses_show", payload["id"])
+ dispatch_status = store.get_dispatch_status("ses_show", payload["id"])
+ finally:
+ store.close()
+ assert attempts == 2
+ assert event is not None
+ assert event["message"]["type"] == messages_service.PENDING_TYPE
+ assert dispatch_status is not None
+ assert dispatch_status.state == DISPATCH_IN_FLIGHT
+ with create_sqlite_engine().connect() as conn:
+ visible = messages_service.list_session_messages(
+ conn,
+ session_id="ses_show",
+ types=("user",),
+ )
+ assert visible["messages"] == []
@pytest.mark.parametrize(
@@ -932,19 +1765,9 @@ def test_show_event_dispatch_streams_via_stream_dispatch(isolated_state, monkeyp
("approve", False),
],
)
-def test_annotation_dispatch_text_adds_event_id_and_optional_reply_guidance(monkeypatch, intent, expects_guidance):
- import asyncio
-
- from vibe import internal_client, ui_server
-
- captured = []
-
- async def fake_stream_dispatch(payload, **kwargs):
- captured.append(payload)
- if False:
- yield None
+def test_annotation_dispatch_text_adds_event_id_and_optional_reply_guidance(intent, expects_guidance):
+ from vibe import ui_server
- monkeypatch.setattr(internal_client, "stream_dispatch", fake_stream_dispatch)
label = intent or "comment"
event = {
"id": "show_evt_1a2b3c4d",
@@ -954,17 +1777,18 @@ def test_annotation_dispatch_text_adds_event_id_and_optional_reply_guidance(monk
"payload": {"intent": intent} if intent is not None else {},
"transcript_text": f"[show-annotation] {label}\n\nReview this.",
"message_id": "m1",
+ "message": {"id": "m1", "type": "pending"},
}
- asyncio.run(ui_server._run_show_event_dispatch(event))
+ dispatch_text = ui_server._show_event_dispatch_text(event)
assert event["transcript_text"] == f"[show-annotation] {label}\n\nReview this."
- assert "Show event id: show_evt_1a2b3c4d" in captured[0]["text"]
+ assert "Show event id: show_evt_1a2b3c4d" in dispatch_text
guidance = (
"如需在页面上原位回应,可执行:\n"
" vibe show reply show_evt_1a2b3c4d --message '<你的回答>'\n"
"(也可以直接修改页面内容来响应,按场景选择。)"
)
- assert (guidance in captured[0]["text"]) is expects_guidance
+ assert (guidance in dispatch_text) is expects_guidance
if expects_guidance:
- assert captured[0]["text"].endswith(guidance)
+ assert dispatch_text.endswith(guidance)
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index e021cc304..308b21004 100644
--- a/tests/test_sqlite_state_migration.py
+++ b/tests/test_sqlite_state_migration.py
@@ -19,7 +19,7 @@ from storage.models import metadata
from storage.settings_service import SQLiteSettingsService
-HEAD_REVISION = "20260724_0034"
+HEAD_REVISION = "20260726_0035"
def _index_sql(conn: sqlite3.Connection, name: str) -> str:
@@ -134,6 +134,14 @@ def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:
assert "width_px" in media_columns # 20260604_0015: zero-shift image box
assert "height_px" in media_columns
assert media_scope_not_null == 0 # standalone sessions can own uploads
+ show_event_columns = {
+ row[1]: row for row in conn.execute("pragma table_info(show_session_events)")
+ }
+ assert show_event_columns["dispatch_state"][3] == 1
+ assert (
+ str(show_event_columns["dispatch_state"][4]).strip("'")
+ == '{"state":"none"}'
+ )
background_columns = {
row[1]
for row in conn.execute(
@@ -145,6 +153,54 @@ def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:
assert version == (HEAD_REVISION,)
+def test_show_dispatch_state_migration_accepts_legacy_rows_and_defaults_new_rows(
+ tmp_path: Path,
+) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path, revision="20260724_0034")
+ now = "2026-07-26T00:00:00Z"
+
+ with sqlite3.connect(db_path) as conn:
+ conn.execute(
+ """
+ insert into show_session_events (
+ id, session_id, event_type, actor, scope, anchor_json,
+ payload_json, transcript_text, message_id, created_at
+ ) values (
+ 'show_evt_legacy', 'ses_legacy', 'human.annotation.created',
+ 'human', 'default', '{}', '{}', 'Legacy annotation', null, ?
+ )
+ """,
+ (now,),
+ )
+ conn.commit()
+
+ run_migrations(db_path)
+
+ with sqlite3.connect(db_path) as conn:
+ legacy_state = conn.execute(
+ "select dispatch_state from show_session_events where id = 'show_evt_legacy'"
+ ).fetchone()
+ conn.execute(
+ """
+ insert into show_session_events (
+ id, session_id, event_type, actor, scope, anchor_json,
+ payload_json, transcript_text, message_id, created_at
+ ) values (
+ 'show_evt_new', 'ses_new', 'human.annotation.created',
+ 'human', 'default', '{}', '{}', 'New annotation', null, ?
+ )
+ """,
+ (now,),
+ )
+ new_state = conn.execute(
+ "select dispatch_state from show_session_events where id = 'show_evt_new'"
+ ).fetchone()
+
+ assert legacy_state == ('{"state":"accepted"}',)
+ assert new_state == ('{"state":"none"}',)
+
+
def test_session_pinning_migration_preserves_existing_sessions_as_unpinned(tmp_path: Path) -> None:
db_path = tmp_path / "vibe.sqlite"
run_migrations(db_path, revision="20260723_0033")
diff --git a/tests/test_ui_session_stream.py b/tests/test_ui_session_stream.py
index 9f8ed545d..8b5c71034 100644
--- a/tests/test_ui_session_stream.py
+++ b/tests/test_ui_session_stream.py
@@ -145,7 +145,19 @@ def test_route_enqueues_when_turn_in_progress(isolated_state, tmp_path):
_, session_id = _make_session(tmp_path)
- dispatch_mock = AsyncMock(return_value={"status_code": 202, "body": {"ok": True, "queued": True}})
+ async def dispatch(payload):
+ from core.session_turns import queue_pending_user_message
+ from storage.db import create_sqlite_engine
+
+ with create_sqlite_engine().begin() as conn:
+ assert queue_pending_user_message(
+ conn,
+ payload["user_message_id"],
+ payload["text"],
+ )
+ return {"status_code": 202, "body": {"ok": True, "queued": True}}
+
+ dispatch_mock = AsyncMock(side_effect=dispatch)
with patch("vibe.internal_client.dispatch_async", dispatch_mock):
client = app.test_client()
headers = csrf_headers(client)
@@ -166,6 +178,112 @@ def test_route_enqueues_when_turn_in_progress(isolated_state, tmp_path):
assert sent["user_message_id"] == body["id"]
+ ("error_kind", "expected_status"),
+ (("timeout", 504), ("ambiguous", 502)),
+)
+def test_route_ambiguous_failure_settles_unowned_pending_visible_without_queueing(
+ isolated_state,
+ tmp_path,
+ monkeypatch,
+ error_kind,
+ expected_status,
+):
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+ from vibe import internal_client
+ from vibe.ui_server import app
+
+ _, session_id = _make_session(tmp_path)
+ published = []
+
+ async def fail_after_connect(_payload):
+ if error_kind == "timeout":
+ raise internal_client.InternalServerTimeout("acceptance unknown")
+ raise RuntimeError("ambiguous response")
+
+ monkeypatch.setattr(
+ "vibe.sse_broker.broker.publish",
+ lambda event_type, data: published.append((event_type, data)),
+ )
+ dispatch_mock = AsyncMock(side_effect=fail_after_connect)
+ with patch("vibe.internal_client.dispatch_async", dispatch_mock):
+ client = app.test_client()
+ response = client.post(
+ f"/api/sessions/{session_id}/messages",
+ json={"text": "settle this after the timeout"},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == expected_status
+ body = response.get_json()
+ assert body["dispatch_error"] == "dispatch_pending"
+ assert body["type"] == "user"
+ dispatch_mock.assert_awaited_once()
+
+ with create_sqlite_engine().connect() as conn:
+ queued = messages_service.list_queued(conn, session_id)
+ visible = messages_service.list_session_messages(
+ conn,
+ session_id=session_id,
+ around_id=body["id"],
+ limit=1,
+ types=messages_service.TRANSCRIPT_TYPES,
+ )
+ assert queued == []
+ assert [row["id"] for row in visible["messages"]] == [body["id"]]
+ assert [event_type for event_type, _data in published].count("message.new") == 1
+
+
+def test_route_timeout_observes_controller_queue_without_republishing(
+ isolated_state,
+ tmp_path,
+ monkeypatch,
+):
+ from core.session_turns import queue_pending_user_message
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+ from vibe import internal_client
+ from vibe.ui_server import app
+
+ _, session_id = _make_session(tmp_path)
+ published = []
+
+ async def timeout_after_controller_queues(payload):
+ with create_sqlite_engine().begin() as conn:
+ assert queue_pending_user_message(
+ conn,
+ payload["user_message_id"],
+ payload["text"],
+ )
+ raise internal_client.InternalServerTimeout("response lost after enqueue")
+
+ monkeypatch.setattr(
+ "vibe.sse_broker.broker.publish",
+ lambda event_type, data: published.append((event_type, data)),
+ )
+ dispatch_mock = AsyncMock(side_effect=timeout_after_controller_queues)
+ with patch("vibe.internal_client.dispatch_async", dispatch_mock):
+ client = app.test_client()
+ response = client.post(
+ f"/api/sessions/{session_id}/messages",
+ json={"text": "already queued by the controller"},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 504
+ body = response.get_json()
+ assert body["dispatch_error"] == "dispatch_pending"
+ assert body["type"] == messages_service.QUEUED_TYPE
+ dispatch_mock.assert_awaited_once()
+
+ with create_sqlite_engine().connect() as conn:
+ queued = messages_service.list_queued(conn, session_id)
+ assert [row["id"] for row in queued] == [body["id"]]
+ assert "message.new" not in [event_type for event_type, _data in published]
+ assert [event_type for event_type, _data in published].count("queue.updated") == 1
+
+
def test_create_session_without_backend_defers_to_default_agent(isolated_state, tmp_path):
"""POST /api/sessions with no ``agent_backend`` must NOT stamp a concrete
backend onto the session. A stamped backend is treated by message_handler
diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.py
index 77f6b946c..329a9a51e 100644
--- a/tests/test_ui_show_pages.py
+++ b/tests/test_ui_show_pages.py
@@ -8,6 +8,7 @@ import socket
import ssl
import struct
import tarfile
+import threading
import urllib.error
import zlib
from pathlib import Path
@@ -176,6 +177,28 @@ def _create_agent_session(session_id: str, *, status: str = "active") -> None:
)
+def _accept_dispatch(payload: dict, message_type: str = "user") -> None:
+ from core.session_turns import queue_pending_user_message
+ from core.show_session_events import DISPATCH_ACCEPTED, settle_show_dispatch
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+
+ with create_sqlite_engine().begin() as conn:
+ if message_type == messages_service.QUEUED_TYPE:
+ assert queue_pending_user_message(
+ conn,
+ payload["user_message_id"],
+ payload["text"],
+ )
+ assert settle_show_dispatch(
+ conn,
+ payload["show_event_id"],
+ session_id=payload["session_id"],
+ owner=payload["dispatch_owner"],
+ state=DISPATCH_ACCEPTED,
+ )
+
+
def _write_runtime_archive(tmp_path: Path, *, text: str = "#!/usr/bin/env node\n") -> Path:
archive_root = tmp_path / f"archive-root-{hashlib.sha256(text.encode()).hexdigest()[:8]}"
cli_path = archive_root / "node_modules" / "@avibe" / "show-runtime" / "dist" / "cli.js"
@@ -1981,7 +2004,59 @@ def test_private_show_page_rejects_mismatched_event_session_id(monkeypatch, tmp_
assert response.get_json()["code"] == "session_mismatch"
-def test_private_show_page_dispatches_human_show_event(monkeypatch, tmp_path):
+def test_private_show_page_rejects_reused_event_id_with_different_contents(
+ monkeypatch,
+ tmp_path,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ config.language = "zh"
+ config.save()
+ _create_agent_session("ses123")
+ _create_show_page("ses123", "private")
+ token = "session-write-token"
+ monkeypatch.setattr("vibe.ui_server.show_event_write_token", lambda session_id: token)
+ headers = {
+ "Origin": "http://127.0.0.1:5123",
+ "Content-Type": "application/json",
+ "X-Vibe-Show-Token": token,
+ }
+ original = {
+ "id": "show_evt_payload_conflict",
+ "type": "human.annotation.created",
+ "annotation": {
+ "intent": "comment",
+ "comment": "Original annotation.",
+ "dispatch": False,
+ },
+ }
+
+ first = app.test_client().post(
+ "/show/ses123/__show/events",
+ base_url="http://127.0.0.1:5123",
+ headers=headers,
+ json=original,
+ )
+ conflict = app.test_client().post(
+ "/show/ses123/__show/events",
+ base_url="http://127.0.0.1:5123",
+ headers=headers,
+ json={
+ **original,
+ "annotation": {
+ **original["annotation"],
+ "comment": "Different annotation.",
+ },
+ },
+ )
+
+ assert first.status_code == 201
+ assert conflict.status_code == 409
+ assert conflict.get_json()["code"] == "event_id_conflict"
+ assert conflict.get_json()["error"] == "此 Show 事件 ID 已绑定到不同的事件内容。"
+
+
+def test_private_show_page_idle_dispatch_promotes_visible_user_row(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config(tmp_path)
_create_agent_session("ses123")
@@ -1993,13 +2068,13 @@ def test_private_show_page_dispatches_human_show_event(monkeypatch, tmp_path):
dispatches = []
dispatch_done = asyncio.Event()
- async def fake_stream_dispatch(payload, **kwargs):
+ async def fake_dispatch_async(payload, **kwargs):
dispatches.append(payload)
+ _accept_dispatch(payload)
dispatch_done.set()
- yield "turn.start", {"session_id": payload["session_id"]}
- yield "turn.end", {"session_id": payload["session_id"]}
+ return {"status_code": 202, "body": {"ok": True}}
- with patch("vibe.internal_client.stream_dispatch", fake_stream_dispatch):
+ with patch("vibe.internal_client.dispatch_async", fake_dispatch_async):
response = app.test_client().post(
"/show/ses123/__show/events",
base_url="http://127.0.0.1:5123",
@@ -2026,7 +2101,337 @@ def test_private_show_page_dispatches_human_show_event(monkeypatch, tmp_path):
assert dispatches[0]["session_id"] == "ses123"
assert "Pick B." in dispatches[0]["text"]
assert dispatches[0]["user_message_id"] == response.get_json()["event"]["message_id"]
- assert "show.dispatch" in [event_type for event_type, _data in published]
+ assert dispatches[0]["files"] == []
+ assert [event_type for event_type, _data in published] == [
+ "show.event",
+ "message.new",
+ "session.activity",
+ ]
+ assert published[1][1]["type"] == "user"
+
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+
+ with create_sqlite_engine().connect() as conn:
+ transcript = messages_service.list_session_messages(conn, session_id="ses123", types=("user",))
+ assert [message["id"] for message in transcript["messages"]] == [
+ response.get_json()["event"]["message_id"]
+ ]
+
+
+def test_private_show_page_waits_for_turn_acceptance_before_responding(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_agent_session("ses123")
+ _create_show_page("ses123", "private")
+ token = "session-write-token"
+ monkeypatch.setattr("vibe.ui_server.show_event_write_token", lambda session_id: token)
+ dispatch_entered = threading.Event()
+ release_dispatch = threading.Event()
+ result = {}
+ dispatch_kwargs = {}
+
+ async def fake_dispatch_async(payload, **kwargs):
+ dispatch_kwargs.update(kwargs)
+ dispatch_entered.set()
+ released = await asyncio.to_thread(release_dispatch.wait, 2)
+ assert released
+ _accept_dispatch(payload)
+ return {"status_code": 202, "body": {"ok": True}}
+
+ def post_event():
+ result["response"] = app.test_client().post(
+ "/show/ses123/__show/events",
+ base_url="http://127.0.0.1:5123",
+ headers={
+ "Origin": "http://127.0.0.1:5123",
+ "Content-Type": "application/json",
+ "X-Vibe-Show-Token": token,
+ },
+ json={
+ "type": "human.annotation.created",
+ "annotation": {
+ "intent": "comment",
+ "comment": "Wait for queue acceptance.",
+ "dispatch": True,
+ },
+ },
+ )
+
+ with patch("vibe.internal_client.dispatch_async", fake_dispatch_async):
+ request_thread = threading.Thread(target=post_event)
+ request_thread.start()
+ assert dispatch_entered.wait(1)
+ assert request_thread.is_alive()
+ release_dispatch.set()
+ request_thread.join(2)
+
+ assert not request_thread.is_alive()
+ assert result["response"].status_code == 201
+ assert result["response"].get_json()["event"]["message"]["type"] == "user"
+ assert dispatch_kwargs == {"timeout": None}
+
+
+def test_private_show_page_unavailable_dispatch_is_retryable_and_not_reported_as_delivered(
+ monkeypatch,
+ tmp_path,
+):
+ from vibe import internal_client
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_agent_session("ses123")
+ _create_show_page("ses123", "private")
+ token = "session-write-token"
+ monkeypatch.setattr("vibe.ui_server.show_event_write_token", lambda session_id: token)
+ published = []
+ monkeypatch.setattr(
+ "vibe.sse_broker.broker.publish",
+ lambda event_type, data: published.append((event_type, data)),
+ )
+
+ async def fake_dispatch_async(payload, **kwargs):
+ raise internal_client.InternalServerUnavailable("controller unavailable")
+
+ with patch("vibe.internal_client.dispatch_async", fake_dispatch_async):
+ response = app.test_client().post(
+ "/show/ses123/__show/events",
+ base_url="http://127.0.0.1:5123",
+ headers={
+ "Origin": "http://127.0.0.1:5123",
+ "Content-Type": "application/json",
+ "X-Vibe-Show-Token": token,
+ },
+ json={
+ "type": "human.annotation.created",
+ "annotation": {
+ "intent": "comment",
+ "comment": "Record but report failed delivery.",
+ "dispatch": True,
+ },
+ },
+ )
+
+ assert response.status_code == 502
+ body = response.get_json()
+ assert body["ok"] is False
+ assert body["code"] == "show_event_dispatch_failed"
+ assert body["event"]["message"]["type"] == "user"
+ assert [event_type for event_type, _data in published] == [
+ "show.event",
+ "message.new",
+ "session.activity",
+ ]
+
+
+def test_private_show_page_concurrent_dispatch_replay_returns_pending(
+ monkeypatch,
+ tmp_path,
+):
+ from storage import messages_service
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_agent_session("ses123")
+ _create_show_page("ses123", "private")
+ token = "session-write-token"
+ monkeypatch.setattr("vibe.ui_server.show_event_write_token", lambda session_id: token)
+
+ async def already_in_flight(_event):
+ return ui_server._ShowEventDispatchOutcome.IN_FLIGHT
+
+ monkeypatch.setattr(
+ "vibe.ui_server._run_show_event_dispatch",
+ already_in_flight,
+ )
+ response = app.test_client().post(
+ "/show/ses123/__show/events",
+ base_url="http://127.0.0.1:5123",
+ headers={
+ "Origin": "http://127.0.0.1:5123",
+ "Content-Type": "application/json",
+ "X-Vibe-Show-Token": token,
+ },
+ json={
+ "id": "show_evt_concurrent_http",
+ "type": "human.annotation.created",
+ "annotation": {
+ "comment": "The first request still owns this dispatch.",
+ "dispatch": True,
+ },
+ },
+ )
+
+ assert response.status_code == 202
+ body = response.get_json()
+ assert body["ok"] is True
+ assert body["dispatch_pending"] is True
+ assert body["event"]["message"]["type"] == messages_service.PENDING_TYPE
+
+
+def test_private_show_page_returns_promoted_row_after_synchronous_queue_drain(
+ monkeypatch,
+ tmp_path,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_agent_session("ses123")
+ _create_show_page("ses123", "private")
+ token = "session-write-token"
+ monkeypatch.setattr("vibe.ui_server.show_event_write_token", lambda session_id: token)
+ published = []
+ monkeypatch.setattr(
+ "vibe.sse_broker.broker.publish",
+ lambda event_type, data: published.append((event_type, data)),
+ )
+ settled = {}
+
+ async def fake_dispatch_async(payload, **kwargs):
+ from core import session_turns
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+
+ with create_sqlite_engine().begin() as conn:
+ assert session_turns.queue_pending_user_message(
+ conn,
+ payload["user_message_id"],
+ payload["text"],
+ )
+ segment = messages_service.list_queued(conn, "ses123")
+ metadata = dict(segment[0]["metadata"])
+ metadata.pop(session_turns.QUEUED_DISPATCH_TEXT_KEY)
+ visible = session_turns._promote_merged_user_segment(
+ conn,
+ segment,
+ text=segment[0]["text"],
+ attachments=[],
+ metadata=metadata,
+ author_id=None,
+ )
+ _accept_dispatch(payload)
+ settled.update(original_id=payload["user_message_id"], visible=visible)
+ return {"status_code": 202, "body": {"ok": True, "drained": True}}
+
+ with patch("vibe.internal_client.dispatch_async", fake_dispatch_async):
+ response = app.test_client().post(
+ "/show/ses123/__show/events",
+ base_url="http://127.0.0.1:5123",
+ headers={
+ "Origin": "http://127.0.0.1:5123",
+ "Content-Type": "application/json",
+ "X-Vibe-Show-Token": token,
+ },
+ json={
+ "type": "human.annotation.created",
+ "annotation": {
+ "intent": "comment",
+ "comment": "Drain before the 202 returns.",
+ "dispatch": True,
+ },
+ },
+ )
+
+ assert response.status_code == 201
+ event = response.get_json()["event"]
+ assert settled["visible"]["id"] != settled["original_id"]
+ assert event["message_id"] == settled["visible"]["id"]
+ assert event["message"]["id"] == settled["visible"]["id"]
+ assert event["message"]["type"] == "user"
+ # The real manager already publishes the promoted row. The route only
+ # published the event before entering our fake adapter and must not emit a
+ # stale pending/queued message afterwards.
+ assert [event_type for event_type, _data in published] == ["show.event"]
+
+
+def test_private_show_page_busy_dispatch_queues_without_message_new(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_agent_session("ses123")
+ _create_show_page("ses123", "private")
+ token = "session-write-token"
+ monkeypatch.setattr("vibe.ui_server.show_event_write_token", lambda session_id: token)
+ published = []
+ monkeypatch.setattr("vibe.sse_broker.broker.publish", lambda event_type, data: published.append((event_type, data)))
+ dispatch_done = asyncio.Event()
+
+ async def fake_dispatch_async(payload, **kwargs):
+ from storage import messages_service
+
+ _accept_dispatch(payload, messages_service.QUEUED_TYPE)
+ dispatch_done.set()
+ return {"status_code": 202, "body": {"ok": True, "queued": True}}
+
+ with patch("vibe.internal_client.dispatch_async", fake_dispatch_async):
+ response = app.test_client().post(
+ "/show/ses123/__show/events",
+ base_url="http://127.0.0.1:5123",
+ headers={
+ "Origin": "http://127.0.0.1:5123",
+ "Content-Type": "application/json",
+ "X-Vibe-Show-Token": token,
+ },
+ json={
+ "type": "human.annotation.created",
+ "annotation": {
+ "intent": "comment",
+ "comment": "Queue this annotation.",
+ "dispatch": True,
+ },
+ },
+ )
+
+ assert response.status_code == 201
+ asyncio.run(asyncio.wait_for(dispatch_done.wait(), timeout=1))
+ message_id = response.get_json()["event"]["message_id"]
+
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+
+ with create_sqlite_engine().connect() as conn:
+ queued = messages_service.list_queued(conn, "ses123")
+ transcript = messages_service.list_session_messages(conn, session_id="ses123", types=("user",))
+ assert [(message["id"], message["text"]) for message in queued] == [
+ (message_id, response.get_json()["event"]["transcript_text"])
+ ]
+ assert transcript["messages"] == []
+ assert [event_type for event_type, _data in published] == ["show.event", "queue.updated"]
+
+
+def test_private_show_page_non_dispatching_annotation_stays_immediately_visible(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_agent_session("ses123")
+ _create_show_page("ses123", "private")
+ token = "session-write-token"
+ monkeypatch.setattr("vibe.ui_server.show_event_write_token", lambda session_id: token)
+ published = []
+ monkeypatch.setattr("vibe.sse_broker.broker.publish", lambda event_type, data: published.append((event_type, data)))
+
+ response = app.test_client().post(
+ "/show/ses123/__show/events",
+ base_url="http://127.0.0.1:5123",
+ headers={
+ "Origin": "http://127.0.0.1:5123",
+ "Content-Type": "application/json",
+ "X-Vibe-Show-Token": token,
+ },
+ json={
+ "type": "human.annotation.created",
+ "annotation": {
+ "intent": "comment",
+ "comment": "Record this without dispatch.",
+ "dispatch": False,
+ },
+ },
+ )
+
+ assert response.status_code == 201
+ assert response.get_json()["event"]["message"]["type"] == "user"
+ assert [event_type for event_type, _data in published] == [
+ "show.event",
+ "message.new",
+ "session.activity",
+ ]
def test_private_show_page_publishes_annotation_control_without_message_or_dispatch(monkeypatch, tmp_path):
@@ -2072,13 +2477,13 @@ def test_private_show_page_dispatches_screenshot_annotation_batch(monkeypatch, t
dispatches = []
dispatch_done = asyncio.Event()
- async def fake_stream_dispatch(payload, **kwargs):
+ async def fake_dispatch_async(payload, **kwargs):
dispatches.append(payload)
+ _accept_dispatch(payload)
dispatch_done.set()
- yield "turn.start", {"session_id": payload["session_id"]}
- yield "turn.end", {"session_id": payload["session_id"]}
+ return {"status_code": 202, "body": {"ok": True}}
- with patch("vibe.internal_client.stream_dispatch", fake_stream_dispatch):
+ with patch("vibe.internal_client.dispatch_async", fake_dispatch_async):
response = app.test_client().post(
"/show/ses123/__show/events",
base_url="http://127.0.0.1:5123",
@@ -2381,92 +2786,6 @@ def test_show_events_stream_replays_all_persisted_pages_before_live(monkeypatch,
assert '"id": "show_evt_500"' in body
-def test_show_events_stream_forwards_live_dispatch_events(monkeypatch, tmp_path):
- from vibe.sse_broker import broker
- from vibe.ui_server import _show_events_stream
-
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- _save_config(tmp_path)
- _create_agent_session("ses123")
- _create_show_page("ses123", "private")
-
- async def _collect_live_dispatch() -> str:
- response = await _show_events_stream("ses123")
- iterator = response.body_iterator.__aiter__()
- chunks = []
- try:
- chunks.append(await iterator.__anext__())
- broker.publish(
- "show.dispatch",
- {
- "session_id": "ses123",
- "scope_id": "scope123",
- "show_event_id": "show_evt_1",
- "event": "turn.chunk",
- "data": {"text": "hello"},
- },
- )
- chunks.append(await asyncio.wait_for(iterator.__anext__(), timeout=1))
- finally:
- await iterator.aclose()
- return "".join(chunk.decode("utf-8") if isinstance(chunk, bytes) else chunk for chunk in chunks)
-
- body = asyncio.run(_collect_live_dispatch())
-
- assert "event: show.dispatch" in body
- assert '"show_event_id": "show_evt_1"' in body
-
-
-def test_public_show_events_stream_redacts_nested_dispatch_ids(monkeypatch, tmp_path):
- from vibe.sse_broker import broker
- from vibe.ui_server import _show_events_stream
-
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- _save_config(tmp_path)
- _create_agent_session("ses123")
- share_id = _create_show_page("ses123", "public")
-
- async def _collect_live_dispatch() -> str:
- response = await _show_events_stream(
- "ses123",
- public=True,
- public_share_id=share_id,
- )
- iterator = response.body_iterator.__aiter__()
- chunks = []
- try:
- chunks.append(await iterator.__anext__())
- broker.publish(
- "show.dispatch",
- {
- "session_id": "ses123",
- "scope_id": "scope123",
- "show_event_id": "show_evt_1",
- "event": "turn.chunk",
- "data": {
- "text": "hello",
- "session_id": "ses123",
- "message_id": "msg123",
- "nested": {"scope_id": "scope123", "user_message_id": "msg123"},
- },
- },
- )
- chunks.append(await asyncio.wait_for(iterator.__anext__(), timeout=1))
- finally:
- await iterator.aclose()
- return "".join(chunk.decode("utf-8") if isinstance(chunk, bytes) else chunk for chunk in chunks)
-
- body = asyncio.run(_collect_live_dispatch())
-
- assert "event: show.dispatch" in body
- assert '"show_event_id": "show_evt_1"' in body
- assert '"text": "hello"' in body
- assert '"session_id"' not in body
- assert '"scope_id"' not in body
- assert '"message_id"' not in body
- assert '"user_message_id"' not in body
-
-
def test_public_show_page_events_redact_internal_ids(monkeypatch, tmp_path):
from core.show_session_events import ShowSessionEventStore
@@ -2630,6 +2949,53 @@ def test_cli_show_event_ingress_records_and_publishes(monkeypatch, tmp_path):
assert [event_type for event_type, _data in published] == ["show.event", "message.new", "session.activity"]
+def test_cli_show_event_dispatch_waits_for_unambiguous_acceptance(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_agent_session("ses123")
+ dispatch_entered = threading.Event()
+ release_dispatch = threading.Event()
+ result = {}
+
+ async def stalled_dispatch(payload, **kwargs):
+ dispatch_entered.set()
+ released = await asyncio.to_thread(release_dispatch.wait, 2)
+ assert released
+ _accept_dispatch(payload)
+ return {"status_code": 202, "body": {"ok": True}}
+
+ def post_event():
+ result["response"] = app.test_client().post(
+ "/api/show/sessions/ses123/events",
+ base_url="http://127.0.0.1:5123",
+ headers={
+ "Content-Type": "application/json",
+ "X-Vibe-Show-Client": "cli",
+ "X-Vibe-Show-Cli-Token": show_cli_event_token(),
+ },
+ json={
+ "type": "human.annotation.created",
+ "annotation": {
+ "intent": "comment",
+ "comment": "Do not duplicate this.",
+ "dispatch": True,
+ },
+ },
+ )
+
+ with patch("vibe.internal_client.dispatch_async", stalled_dispatch):
+ request_thread = threading.Thread(target=post_event)
+ request_thread.start()
+ assert dispatch_entered.wait(1)
+ assert request_thread.is_alive()
+ release_dispatch.set()
+ request_thread.join(2)
+
+ assert not request_thread.is_alive()
+ assert result["response"].status_code == 201
+ assert result["response"].get_json()["event"]["message"]["type"] == "user"
+
+
def test_cli_show_event_ingress_requires_cli_token(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config(tmp_path)
diff --git a/vibe/cli.py b/vibe/cli.py
index c04de3470..837e9719d 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -10686,9 +10686,69 @@ def _post_show_event_to_live_ui(session_id: str, payload: dict) -> dict | None:
try:
with urllib.request.urlopen(request, timeout=3) as response:
parsed = json.loads(response.read().decode("utf-8"))
- except (OSError, TimeoutError, urllib.error.URLError, urllib.error.HTTPError, json.JSONDecodeError, ValueError):
+ except TimeoutError:
+ return _resolve_show_event_after_ambiguous_live_timeout(session_id, payload)
+ except urllib.error.HTTPError:
return None
- return parsed.get("event") if isinstance(parsed, dict) and parsed.get("ok") is True else None
+ except urllib.error.URLError as exc:
+ if isinstance(exc.reason, TimeoutError):
+ return _resolve_show_event_after_ambiguous_live_timeout(session_id, payload)
+ return None
+ except (OSError, json.JSONDecodeError, ValueError):
+ return None
+ if not isinstance(parsed, dict):
+ return None
+ if parsed.get("dispatch_pending") is True:
+ return _resolve_show_event_after_ambiguous_live_timeout(session_id, payload)
+ return parsed.get("event") if parsed.get("ok") is True else None
+
+
+def _resolve_show_event_after_ambiguous_live_timeout(
+ session_id: str,
+ payload: dict,
+ *,
+ wait_seconds: float = 15.0,
+) -> dict | None:
+ """Query the event-owned dispatch lifecycle after a live POST times out."""
+ from core.show_session_events import (
+ DISPATCH_ACCEPTED,
+ DISPATCH_ARCHIVED,
+ DISPATCH_FAILED,
+ DISPATCH_IN_FLIGHT,
+ DISPATCH_NONE,
+ ShowSessionEventStore,
+ localized_show_event_error,
+ )
+
+ event_id = payload.get("id")
+ if not isinstance(event_id, str) or not event_id:
+ return None
+ deadline = time.monotonic() + wait_seconds
+ store = ShowSessionEventStore()
+ try:
+ while True:
+ status = store.get_dispatch_status(session_id, event_id)
+ if status is None:
+ return None
+ if status.state == DISPATCH_ACCEPTED:
+ settlement = store.reconcile_dispatch_settlement(
+ session_id,
+ event_id,
+ )
+ if settlement is not None and settlement.can_report_success:
+ return store.get_event(session_id, event_id)
+ raise localized_show_event_error("show_event_dispatch_failed")
+ if status.state == DISPATCH_ARCHIVED:
+ raise localized_show_event_error("show_event_dispatch_failed")
+ if status.state in {DISPATCH_NONE, DISPATCH_FAILED}:
+ return None
+ if status.state != DISPATCH_IN_FLIGHT:
+ return store.get_event(session_id, event_id)
+ if time.monotonic() >= deadline:
+ raise localized_show_event_error("show_event_dispatch_pending")
+ time.sleep(0.05)
+ finally:
+ store.close()
def _post_show_mark_to_live_ui(session_id: str, payload: dict) -> dict | None:
@@ -11116,10 +11176,8 @@ def cmd_show_unmark(args):
def cmd_show_event(args):
from core.show_pages import ShowPageStore
- from core.show_session_events import ShowSessionEventStore
page_store = ShowPageStore()
- event_store = None
try:
session_id, session_default_notice = _resolve_show_session_id(args, help_command="vibe show event --help")
page = page_store.ensure(session_id)
@@ -11128,15 +11186,20 @@ def cmd_show_event(args):
payload = {**payload, "type": args.type}
if args.dispatch:
payload = _with_show_event_dispatch(payload)
+ event_id = payload.get("id")
+ payload["id"] = (
+ event_id.strip()
+ if isinstance(event_id, str) and event_id.strip()
+ else f"show_evt_{uuid4().hex[:16]}"
+ )
event = _post_show_event_to_live_ui(session_id, payload)
if event is None:
- if args.dispatch:
- from vibe.ui_server import record_local_show_event
+ # The local bridge handles both shapes: non-dispatch events are
+ # immediately visible, while any normalized dispatch:true event
+ # reserves and synchronously settles through the unified entry.
+ from vibe.ui_server import record_local_show_event
- event = record_local_show_event(session_id, payload, dispatch_sync=True)
- else:
- event_store = ShowSessionEventStore()
- event = event_store.append(session_id, payload)
+ event = record_local_show_event(session_id, payload, dispatch_sync=True)
result = _show_page_result(
page,
message="Show event recorded.",
@@ -11162,8 +11225,6 @@ def cmd_show_event(args):
return 1
finally:
page_store.close()
- if event_store is not None:
- event_store.close()
def cmd_show_annotate(args):
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 631e563de..ef2f38704 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -12,6 +12,13 @@
"title": "Fork {title}",
"titleUntitled": "Fork"
},
+ "show": {
+ "event": {
+ "acceptanceUnknown": "The Show event may still be processing. It was not replayed locally.",
+ "dispatchFailed": "The Show event was recorded, but its agent turn could not be delivered.",
+ "idConflict": "This Show event ID is already bound to different event contents."
+ }
+ },
"harness": {
"watch": {
"supervisorFailed": "Watch worker supervisor failed: {detail}",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index fc253e1b8..3a580f7e8 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -12,6 +12,13 @@
"title": "复刻 {title}",
"titleUntitled": "复刻"
},
+ "show": {
+ "event": {
+ "acceptanceUnknown": "Show 事件可能仍在处理中,未在本地重复提交。",
+ "dispatchFailed": "Show 事件已记录,但未能投递对应的 Agent turn。",
+ "idConflict": "此 Show 事件 ID 已绑定到不同的事件内容。"
+ }
+ },
"harness": {
"watch": {
"supervisorFailed": "Watch 监控进程失败:{detail}",
diff --git a/vibe/internal_client.py b/vibe/internal_client.py
index 9ffc36cb0..8e7b6a338 100644
--- a/vibe/internal_client.py
+++ b/vibe/internal_client.py
@@ -6,13 +6,12 @@ The UI server runs as its own subprocess; this module is how it reaches
Single responsibility: keep all the socket-path / httpx-transport /
SSE-parsing boilerplate out of the UI route bodies. Routes call
-``dispatch_async(...)`` to start a fire-and-forget turn (the Chat page — the
-reply arrives over the persistent ``message.new`` session stream, not the
-response), ``stream_dispatch(...)`` to run a turn and stream its chunks back
-(the Show-page dispatch flow), ``stream_events(...)`` to subscribe to the
-controller's event feed, and ``cancel_dispatch`` / ``send_now`` /
-``turn_state`` / ``health`` for the turn-control surface — each raising
-``InternalServerUnavailable`` so the route can degrade gracefully.
+``dispatch_async(...)`` to start a fire-and-forget turn (the reply arrives over
+the persistent ``message.new`` session stream, not the response),
+``stream_events(...)`` to subscribe to the controller's event feed, and
+``cancel_dispatch`` / ``send_now`` / ``turn_state`` / ``health`` for the
+turn-control surface — each raising ``InternalServerUnavailable`` so the route
+can degrade gracefully.
"""
from __future__ import annotations
@@ -34,12 +33,7 @@ _SOCKET_CONNECT_ERRORS = (httpx.ConnectError, httpx.ConnectTimeout, OSError)
class InternalServerUnavailable(Exception):
- """Raised when the dispatch socket cannot be reached.
-
- Routes should catch this and degrade to the queue-based fallback so
- a controller crash or socket-bind race doesn't take down the
- user-facing send-compose flow.
- """
+ """Raised when the dispatch socket cannot be reached before acceptance."""
class InternalServerTimeout(Exception):
@@ -62,71 +56,6 @@ def default_socket_path() -> Path:
return paths.get_state_dir() / "dispatch.sock"
-async def stream_dispatch(
- payload: dict[str, Any],
- *,
- socket_path: Optional[Path] = None,
- timeout: float = 1800.0,
-) -> AsyncIterator[tuple[str, dict[str, Any]]]:
- """Send a dispatch request and yield the turn's SSE events as they arrive.
-
- Each yielded tuple is ``(event_name, parsed_data)`` — e.g. ``("turn.start",
- {...})``, ``("turn.chunk", {...})``, ``("turn.end", {...})``. The caller
- re-encodes them for the browser. Raises ``InternalServerUnavailable`` for
- connect-time failures so the caller can degrade.
-
- NB: the web **Chat** page no longer uses this (it's fire-and-forget +
- ``message.new``); this streaming round-trip backs the **Show-page** dispatch
- flow (``_run_show_event_dispatch`` re-publishes each event as ``show.dispatch``).
- """
-
- 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(timeout, connect=5.0),
- ) as client:
- try:
- stream = client.stream("POST", "/internal/dispatch", json=payload)
- except _SOCKET_ERRORS as exc:
- raise InternalServerUnavailable(str(exc)) from exc
-
- async with stream as resp:
- if resp.status_code >= 400:
- detail = await resp.aread()
- raise InternalServerUnavailable(
- f"dispatch endpoint returned {resp.status_code}: {detail!r}"
- )
-
- current_event: Optional[str] = None
- async for line in resp.aiter_lines():
- if not line:
- # Blank line ends an SSE event block; reset the
- # event-name buffer so a missing ``event:`` field
- # on the next block defaults to ``message``.
- current_event = None
- continue
- if line.startswith("event:"):
- current_event = line.split(":", 1)[1].strip()
- elif line.startswith("data:"):
- raw = line[5:].lstrip()
- try:
- parsed = json.loads(raw)
- except json.JSONDecodeError:
- logger.warning("internal_client: invalid SSE data line %r", raw)
- continue
- yield (current_event or "message", parsed)
- except InternalServerUnavailable:
- raise
- except _SOCKET_ERRORS as exc:
- raise InternalServerUnavailable(str(exc)) from exc
-
-
async def stream_events(
*,
socket_path: Optional[Path] = None,
@@ -251,7 +180,7 @@ async def dispatch_async(
payload: dict[str, Any],
*,
socket_path: Optional[Path] = None,
- timeout: float = 10.0,
+ timeout: float | None = 10.0,
) -> dict[str, Any]:
"""Start a fire-and-forget turn on the controller and return immediately.
@@ -259,8 +188,9 @@ async def dispatch_async(
responds ``202`` right away (the reply arrives over the persistent
``message.new`` session stream, not this response). Returns
``{"status_code", "body"}`` so the caller can distinguish a started turn
- (202) from a concurrent-turn refusal (409). Raises
- ``InternalServerUnavailable`` on socket failure so the route can degrade.
+ from one accepted into the shared queue. A pre-connect failure raises
+ ``InternalServerUnavailable``; a post-connect timeout raises
+ ``InternalServerTimeout`` because acceptance is unknown.
"""
target = (socket_path or default_socket_path()).expanduser().resolve()
@@ -274,8 +204,12 @@ async def dispatch_async(
timeout=httpx.Timeout(timeout, connect=5.0),
) as client:
resp = await client.post("/internal/dispatch_async", json=payload)
- except _SOCKET_ERRORS as exc:
+ except _SOCKET_CONNECT_ERRORS as exc:
raise InternalServerUnavailable(str(exc)) from exc
+ except httpx.TimeoutException as exc:
+ # Once the socket connected, a timeout is acceptance-unknown: the
+ # controller request may still settle the durable reservation.
+ raise InternalServerTimeout(str(exc)) from exc
return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index aae369946..6d28a3359 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -20,6 +20,7 @@ import time
from collections import OrderedDict, deque
from contextlib import contextmanager
from datetime import datetime, timezone
+from enum import Enum
from pathlib import Path
from types import SimpleNamespace
from typing import Any, Callable
@@ -46,7 +47,13 @@ from core.show_pages import (
show_event_write_token,
show_public_event_write_token,
)
-from core.show_session_events import HUMAN_EVENT_TYPES, show_event_payload_session_mismatch
+from core.show_session_events import (
+ HUMAN_EVENT_TYPES,
+ ShowSessionEventError,
+ localized_show_event_error,
+ show_event_payload_session_mismatch,
+ show_event_requests_dispatch,
+)
from core.terminal_service import TERMINAL_SUPPORTED, TerminalService, TerminalServiceError, sanitize_session_id
from modules.agents.catalog import AGENT_BACKENDS, supports_runtime_refresh
from vibe.i18n import get_supported_languages, t
@@ -56,6 +63,13 @@ from vibe.sentry_integration import init_sentry
logger = logging.getLogger(__name__)
+
+class _ShowEventDispatchOutcome(str, Enum):
+ ACCEPTED = "accepted"
+ IN_FLIGHT = "in_flight"
+ FAILED = "failed"
+
+
# Python's mimetypes map omits .webmanifest; register it so the PWA manifest is
# served as a type browsers accept (an octet-stream manifest is rejected).
mimetypes.add_type("application/manifest+json", ".webmanifest")
@@ -7542,6 +7556,61 @@ def asr_status():
return jsonify({"available": False})
+def _publish_visible_user_message(
+ row: dict[str, Any],
+ *,
+ session_id: str,
+ scope_id: str | None,
+ activity_event: str = "user_message",
+) -> dict[str, Any]:
+ """Publish one already-visible user row through the shared fan-out."""
+ from storage import messages_service
+ from vibe.sse_broker import broker
+
+ broker.publish("message.new", row)
+ broker.publish(
+ "session.activity",
+ {"session_id": session_id, "scope_id": scope_id, "event": activity_event},
+ )
+ try:
+ with _projects_engine().connect() as conn:
+ inbox_row = messages_service.get_inbox_session(conn, session_id, platform="avibe")
+ if inbox_row is not None:
+ broker.publish("inbox.session.updated", inbox_row)
+ except Exception:
+ logger.debug("inbox.session.updated publish (user message) failed", exc_info=True)
+ return row
+
+
+def _promote_and_publish_pending_user_message(
+ row: dict[str, Any],
+ *,
+ session_id: str,
+ scope_id: str | None,
+ activity_event: str = "user_message",
+) -> dict[str, Any] | None:
+ """Settle one reserved row without publishing a stale or pending snapshot."""
+ from storage import messages_service
+ from vibe.sse_broker import broker
+
+ with _projects_engine().begin() as conn:
+ promoted = messages_service.promote_pending(conn, row["id"], "user")
+ settled = _load_session_message(session_id, row["id"])
+ if settled is None:
+ return None
+ if settled.get("type") == messages_service.QUEUED_TYPE:
+ broker.publish("queue.updated", {"session_id": session_id, "scope_id": scope_id})
+ return settled
+ if promoted and settled.get("type") == "user":
+ return _publish_visible_user_message(
+ settled,
+ session_id=session_id,
+ scope_id=scope_id,
+ activity_event=activity_event,
+ )
+ return settled
+
+
@app.route("/api/sessions/<session_id>/messages", methods=["POST"])
async def sessions_messages_create(session_id: str):
"""Persist a user message and fire-and-forget the agent turn.
@@ -7560,7 +7629,6 @@ async def sessions_messages_create(session_id: str):
from core.services import sessions as workbench_sessions_service
from storage import messages_service
from vibe import internal_client
- from vibe.sse_broker import broker
payload = request.json or {}
text = payload.get("text")
@@ -7648,37 +7716,6 @@ async def sessions_messages_create(session_id: str):
workbench_sessions_service.touch_session(conn, session_id)
return row
- def _promote_and_publish(row: dict) -> dict:
- """Promote the reserved pending row to a transcript-visible ``user`` row
- and fan it out (message.new + activity + inbox bump). Returns the row
- with its type corrected. The agent-reply side rides the controller→
- browser bridge, but the user row is persisted in this UI process so the
- controller bus never sees it."""
- with engine.begin() as conn:
- promoted = messages_service.promote_pending(conn, row["id"], "user")
- if not promoted:
- # The row wasn't pending anymore: the controller already promoted it
- # (e.g. enqueued as 'queued' via the busy-session path) before our
- # dispatch call failed/returned. Don't publish a phantom 'user'
- # transcript row alongside the still-queued item — nudge the queue view
- # and report it as queued instead (Codex P2).
- broker.publish("queue.updated", {"session_id": session_id, "scope_id": session["scope_id"]})
- return {**row, "type": "queued"}
- row = {**row, "type": "user"}
- broker.publish("message.new", row)
- broker.publish(
- "session.activity",
- {"session_id": session_id, "scope_id": session["scope_id"], "event": "user_message"},
- )
- try:
- with engine.connect() as conn:
- inbox_row = messages_service.get_inbox_session(conn, session_id, platform="avibe")
- if inbox_row is not None:
- broker.publish("inbox.session.updated", inbox_row)
- except Exception:
- logger.debug("inbox.session.updated publish (user message) failed", exc_info=True)
- return row
-
# Reserve the row FIRST (pending), then decide by the dispatch outcome.
message = _persist_user_row()
if message is None:
@@ -7688,7 +7725,13 @@ async def sessions_messages_create(session_id: str):
# promote + publish the row, no turn. Attachments WITHOUT text still run a
# turn (the agent reads the files), so they aren't caught here.
if not dispatch_text.strip() and not attachment_specs:
- return jsonify(_promote_and_publish(message)), 201
+ return jsonify(
+ _promote_and_publish_pending_user_message(
+ message,
+ session_id=session_id,
+ scope_id=session["scope_id"],
+ )
+ ), 201
# Session/page-scoped model (the web Chat): fire-and-forget the turn; the
# reply arrives over ``message.new``. The controller atomically either lets
# the turn start (we then promote the row to user) or — if a turn is already
@@ -7703,20 +7746,51 @@ async def sessions_messages_create(session_id: str):
}
try:
result = await internal_client.dispatch_async(dispatch_payload)
+ except internal_client.InternalServerTimeout as exc:
+ observed = _promote_and_publish_pending_user_message(
+ message,
+ session_id=session_id,
+ scope_id=session["scope_id"],
+ ) or message
+ return jsonify(
+ {
+ **observed,
+ "dispatch_error": "dispatch_pending",
+ "detail": str(exc),
+ }
+ ), 504
except internal_client.InternalServerUnavailable as exc:
- # Couldn't reach the controller — promote + surface the row so the
- # user still sees their message, plus the failure.
- published = _promote_and_publish(message)
- return jsonify({**published, "dispatch_error": "internal_unavailable", "detail": str(exc)}), 502
+ published = _promote_and_publish_pending_user_message(
+ message,
+ session_id=session_id,
+ scope_id=session["scope_id"],
+ ) or message
+ return jsonify(
+ {
+ **published,
+ "dispatch_error": "internal_unavailable",
+ "detail": str(exc),
+ }
+ ), 502
except Exception as exc:
- # The socket existed but the call failed another way (ReadTimeout, a
- # non-JSON / 500 response, etc.). The row is still reserved as hidden
- # ``pending`` and the draft was cleared, so WITHOUT this the user's text
- # would vanish from both transcript and queue behind an error. Promote +
- # publish it with the error, same as the unavailable branch (Codex P2).
- logger.warning("dispatch_async call failed for session %s: %s", session_id, exc, exc_info=True)
- published = _promote_and_publish(message)
- return jsonify({**published, "dispatch_error": "dispatch_failed", "detail": str(exc)}), 502
+ logger.warning(
+ "dispatch_async acceptance is unknown for session %s: %s",
+ session_id,
+ exc,
+ exc_info=True,
+ )
+ observed = _promote_and_publish_pending_user_message(
+ message,
+ session_id=session_id,
+ scope_id=session["scope_id"],
+ ) or message
+ return jsonify(
+ {
+ **observed,
+ "dispatch_error": "dispatch_pending",
+ "detail": str(exc),
+ }
+ ), 502
status = result.get("status_code", 500)
body = result.get("body") or {}
# Quick-reply accepted (turn started OR queued) → record the choice on the
@@ -7726,18 +7800,44 @@ async def sessions_messages_create(session_id: str):
if status == 202 and quick_reply_for:
with engine.begin() as conn:
messages_service.set_quick_reply_chosen(conn, session_id, quick_reply_for, dispatch_text)
+ if status == 202 and body.get("drained"):
+ # The row joined an idle pre-existing queue and was synchronously merged
+ # before acceptance returned. ``flush_queue`` already published the
+ # freshly ordered replacement; do not append the retired reservation.
+ return jsonify({"drained": True}), 202
if status == 202 and body.get("queued"):
# Enqueued behind a running turn: the controller already promoted the
# row pending→queued, so it stays OUT of the transcript (no
# message.new); show it above the composer via queue.updated.
- broker.publish("queue.updated", {"session_id": session_id, "scope_id": session["scope_id"]})
- return jsonify({**message, "type": "queued", "queued": True}), 202
+ queued = _promote_and_publish_pending_user_message(
+ message,
+ session_id=session_id,
+ scope_id=session["scope_id"],
+ ) or message
+ return jsonify({**queued, "queued": True}), 202
if status == 202:
- # Turn started — promote + publish the prompt.
- return jsonify(_promote_and_publish(message)), 201
- # Dispatch failed: still promote + show the row + the error.
- published = _promote_and_publish(message)
- return jsonify({**published, "dispatch_error": "dispatch_failed", "detail": body}), 502
+ # Turn started: the caller owns the rendering transition, while the
+ # unified manager owns only the turn/queue decision.
+ settled = _promote_and_publish_pending_user_message(
+ message,
+ session_id=session_id,
+ scope_id=session["scope_id"],
+ ) or message
+ return jsonify(
+ settled
+ ), 201
+ published = _promote_and_publish_pending_user_message(
+ message,
+ session_id=session_id,
+ scope_id=session["scope_id"],
+ ) or message
+ return jsonify(
+ {
+ **published,
+ "dispatch_error": "dispatch_failed",
+ "detail": body,
+ }
+ ), 502
@app.route("/api/sessions/<session_id>/cancel", methods=["POST"])
@@ -8908,7 +9008,7 @@ def _show_page_runtime_failure_response(
def _show_session_event_error_response(exc: Exception):
code = getattr(exc, "code", "show_session_event_failed")
- status = 404 if code == "session_not_found" else 400
+ status = 404 if code == "session_not_found" else 409 if code == "event_id_conflict" else 400
return jsonify({"ok": False, "code": code, "error": str(exc)}), status
@@ -9006,7 +9106,7 @@ def _show_me_response(author: dict[str, str] | None, *, write_token: str | None
return response
-def _show_event_response_from_payload(
+async def _show_event_response_from_payload(
session_id: str,
payload: dict[str, Any],
*,
@@ -9028,15 +9128,55 @@ def _show_event_response_from_payload(
)
store = _show_session_event_store()
try:
- event_payload = store.append(session_id, payload, author=author)
+ event_payload = store.append(
+ session_id,
+ payload,
+ author=author,
+ reserve_dispatch=allow_dispatch,
+ )
except Exception as exc:
return _show_session_event_error_response(exc)
finally:
store.close()
_publish_show_session_event(event_payload)
- if allow_dispatch:
- _dispatch_show_event_if_requested(event_payload)
+ if allow_dispatch and show_event_requests_dispatch(event_payload):
+ # The internal endpoint returns after SessionTurnManager has either
+ # started or queued the turn. Settle the pending transcript row before
+ # acknowledging the Show event so a successful POST cannot strand it.
+ dispatch_outcome = await _run_show_event_dispatch(event_payload)
+ if dispatch_outcome is _ShowEventDispatchOutcome.IN_FLIGHT:
+ return (
+ jsonify(
+ {
+ "ok": True,
+ "dispatch_pending": True,
+ "event": _show_event_response_payload(
+ event_payload,
+ public=public,
+ public_share_id=public_share_id,
+ ),
+ }
+ ),
+ 202,
+ )
+ if dispatch_outcome is _ShowEventDispatchOutcome.FAILED:
+ exc = _show_event_dispatch_error()
+ return (
+ jsonify(
+ {
+ "ok": False,
+ "code": exc.code,
+ "error": str(exc),
+ "event": _show_event_response_payload(
+ event_payload,
+ public=public,
+ public_share_id=public_share_id,
+ ),
+ }
+ ),
+ 502,
+ )
return (
jsonify(
{
@@ -9055,17 +9195,24 @@ def _show_event_response_from_payload(
def record_local_show_event(session_id: str, payload: dict[str, Any], *, dispatch_sync: bool = False) -> dict[str, Any]:
store = _show_session_event_store()
try:
- event_payload = store.append(session_id, payload)
+ event_payload = store.append(session_id, payload, reserve_dispatch=True)
finally:
store.close()
_publish_show_session_event(event_payload)
- if dispatch_sync and _show_event_requests_dispatch(event_payload):
+ if dispatch_sync and show_event_requests_dispatch(event_payload):
try:
- asyncio.run(_run_show_event_dispatch(event_payload))
+ asyncio.get_running_loop()
except RuntimeError:
- _dispatch_show_event_if_requested(event_payload)
- else:
- _dispatch_show_event_if_requested(event_payload)
+ # The 202 endpoint returns after the manager accepts or queues the
+ # turn, so CLI callers can synchronously settle the pending row
+ # without waiting for the agent turn itself.
+ dispatch_outcome = asyncio.run(_run_show_event_dispatch(event_payload))
+ if dispatch_outcome is _ShowEventDispatchOutcome.IN_FLIGHT:
+ raise _show_event_dispatch_pending_error()
+ if dispatch_outcome is _ShowEventDispatchOutcome.FAILED:
+ raise _show_event_dispatch_error()
+ return event_payload
+ _dispatch_show_event_if_requested(event_payload)
return event_payload
@@ -9074,6 +9221,8 @@ def _publish_show_session_event(event_payload: dict[str, Any]) -> None:
broker.publish("show.event", event_payload)
message = event_payload.get("message")
+ if show_event_requests_dispatch(event_payload):
+ return
if isinstance(message, dict):
broker.publish("message.new", message)
broker.publish(
@@ -9087,7 +9236,7 @@ def _publish_show_session_event(event_payload: dict[str, Any]) -> None:
def _dispatch_show_event_if_requested(event_payload: dict[str, Any]) -> None:
- if not _show_event_requests_dispatch(event_payload):
+ if not show_event_requests_dispatch(event_payload):
return
try:
loop = asyncio.get_running_loop()
@@ -9102,46 +9251,228 @@ def _dispatch_show_event_if_requested(event_payload: dict[str, Any]) -> None:
loop.create_task(_run_show_event_dispatch(event_payload))
-def _show_event_requests_dispatch(event_payload: dict[str, Any]) -> bool:
- if event_payload.get("actor") != "human":
- return False
- if event_payload.get("type") not in {"human.intent.submitted", "human.annotation.created"}:
- return False
- payload = event_payload.get("payload")
- if not isinstance(payload, dict):
- return False
- return bool(payload.get("dispatch"))
-
-
-async def _run_show_event_dispatch(event_payload: dict[str, Any]) -> None:
+async def _run_show_event_dispatch(
+ event_payload: dict[str, Any],
+) -> _ShowEventDispatchOutcome:
+ from core.show_session_events import (
+ DISPATCH_ACCEPTED,
+ DISPATCH_ARCHIVED,
+ DISPATCH_FAILED,
+ DISPATCH_IN_FLIGHT,
+ claim_show_dispatch,
+ settle_show_dispatch,
+ show_dispatch_attempt,
+ )
from vibe import internal_client
session_id = event_payload.get("session_id")
scope_id = event_payload.get("scope_id")
+ event_id = event_payload.get("id")
transcript_text = event_payload.get("transcript_text")
- if not isinstance(session_id, str) or not session_id or not isinstance(transcript_text, str) or not transcript_text.strip():
- return
- dispatch_payload = {
- "session_id": session_id,
- "text": _show_event_dispatch_text(event_payload),
- "scope_id": scope_id,
- "user_message_id": event_payload.get("message_id"),
- "message_id": event_payload.get("message_id"),
- "platform": "avibe",
- "channel_id": session_id,
- }
+ if (
+ not isinstance(session_id, str)
+ or not session_id
+ or not isinstance(event_id, str)
+ or not event_id
+ or not isinstance(transcript_text, str)
+ or not transcript_text.strip()
+ ):
+ return _ShowEventDispatchOutcome.FAILED
+
+ with show_dispatch_attempt() as owner:
+ with _projects_engine().begin() as conn:
+ dispatch_status = claim_show_dispatch(
+ conn,
+ event_id,
+ session_id=session_id,
+ owner=owner,
+ )
+ if (
+ dispatch_status is None
+ or dispatch_status.session_status == "archived"
+ or dispatch_status.state == DISPATCH_ARCHIVED
+ ):
+ return _ShowEventDispatchOutcome.FAILED
+ if dispatch_status.state == DISPATCH_ACCEPTED:
+ return _show_event_dispatch_outcome(
+ _reconcile_show_event_dispatch(event_payload)
+ )
+ if dispatch_status.state == DISPATCH_IN_FLIGHT and not dispatch_status.claimed:
+ return _ShowEventDispatchOutcome.IN_FLIGHT
+ if dispatch_status.state != DISPATCH_IN_FLIGHT:
+ return _ShowEventDispatchOutcome.FAILED
+
+ settlement = _reconcile_show_event_dispatch(event_payload)
+ message = settlement.message if settlement is not None else None
+ if not isinstance(message, dict):
+ with _projects_engine().begin() as conn:
+ settle_show_dispatch(
+ conn,
+ event_id,
+ session_id=session_id,
+ owner=owner,
+ state=DISPATCH_FAILED,
+ )
+ return _show_event_dispatch_outcome(
+ _reconcile_show_event_dispatch(event_payload)
+ )
+ dispatch_payload = {
+ "session_id": session_id,
+ "text": _show_event_dispatch_text(event_payload),
+ "scope_id": scope_id,
+ "user_message_id": message["id"],
+ "show_event_id": event_id,
+ "dispatch_owner": owner,
+ "files": [],
+ }
+
+ try:
+ result = await internal_client.dispatch_async(
+ dispatch_payload,
+ timeout=None,
+ )
+ except internal_client.InternalServerTimeout as exc:
+ logger.warning(
+ "show event dispatch still pending for session %s: %s",
+ session_id,
+ exc,
+ )
+ return _show_event_dispatch_outcome(
+ _reconcile_show_event_dispatch(event_payload)
+ )
+ except internal_client.InternalServerUnavailable as exc:
+ logger.warning(
+ "show event dispatch unavailable for session %s: %s",
+ session_id,
+ exc,
+ )
+ with _projects_engine().begin() as conn:
+ settle_show_dispatch(
+ conn,
+ event_id,
+ session_id=session_id,
+ owner=owner,
+ state=DISPATCH_FAILED,
+ )
+ return _show_event_dispatch_outcome(
+ _reconcile_show_event_dispatch(event_payload)
+ )
+ except Exception: # pragma: no cover - defensive
+ logger.exception("show event dispatch acceptance is unknown")
+ return _show_event_dispatch_outcome(
+ _reconcile_show_event_dispatch(event_payload)
+ )
+
+ status = result.get("status_code", 500)
+ body = result.get("body") or {}
+ if status != 202:
+ logger.warning(
+ "show event dispatch failed for session %s: status=%s body=%s",
+ session_id,
+ status,
+ body,
+ )
+ with _projects_engine().begin() as conn:
+ settle_show_dispatch(
+ conn,
+ event_id,
+ session_id=session_id,
+ owner=owner,
+ state=DISPATCH_FAILED,
+ )
+ return _show_event_dispatch_outcome(
+ _reconcile_show_event_dispatch(event_payload)
+ )
+ return _show_event_dispatch_outcome(
+ _reconcile_show_event_dispatch(event_payload)
+ )
+
+
+def _reconcile_show_event_dispatch(
+ event_payload: dict[str, Any],
+) -> Any | None:
+ from core.show_session_events import ShowSessionEventStore
+
+ session_id = event_payload.get("session_id")
+ event_id = event_payload.get("id")
+ if not isinstance(session_id, str) or not session_id:
+ return None
+ if not isinstance(event_id, str) or not event_id:
+ return None
+ store = ShowSessionEventStore()
try:
- async for event_name, data in internal_client.stream_dispatch(dispatch_payload):
- _publish_show_dispatch_event(event_payload, event_name, data)
- except internal_client.InternalServerUnavailable as exc:
- _publish_show_dispatch_event(
- event_payload,
- "stream.error",
- {"reason": "internal_server_unavailable", "detail": str(exc)},
+ settlement = store.reconcile_dispatch_settlement(session_id, event_id)
+ finally:
+ store.close()
+ if settlement is None or settlement.message is None:
+ return settlement
+
+ message = settlement.message
+ event_payload["message_id"] = message["id"]
+ event_payload["message"] = message
+ if settlement.can_publish_message_new:
+ _publish_visible_user_message(
+ message,
+ session_id=session_id,
+ scope_id=(
+ str(event_payload["scope_id"])
+ if isinstance(event_payload.get("scope_id"), str)
+ else None
+ ),
+ activity_event="show_event",
+ )
+ elif settlement.can_publish_queue_updated:
+ from vibe.sse_broker import broker
+
+ broker.publish(
+ "queue.updated",
+ {
+ "session_id": session_id,
+ "scope_id": event_payload.get("scope_id"),
+ },
+ )
+ return settlement
+
+
+def _show_event_dispatch_outcome(
+ settlement: Any | None,
+) -> _ShowEventDispatchOutcome:
+ from core.show_session_events import (
+ DISPATCH_IN_FLIGHT,
+ DISPATCH_NONE,
+ )
+
+ if settlement is None:
+ return _ShowEventDispatchOutcome.FAILED
+ if settlement.can_report_success:
+ return _ShowEventDispatchOutcome.ACCEPTED
+ if settlement.status.state in {DISPATCH_NONE, DISPATCH_IN_FLIGHT}:
+ return _ShowEventDispatchOutcome.IN_FLIGHT
+ return _ShowEventDispatchOutcome.FAILED
+
+
+def _show_event_dispatch_error() -> ShowSessionEventError:
+ return localized_show_event_error("show_event_dispatch_failed")
+
+
+def _show_event_dispatch_pending_error() -> ShowSessionEventError:
+ return localized_show_event_error("show_event_dispatch_pending")
+
+
+def _load_session_message(session_id: str, message_id: str) -> dict[str, Any] | None:
+ from storage import messages_service
+
+ with _projects_engine().connect() as conn:
+ window = messages_service.list_session_messages(
+ conn,
+ session_id=session_id,
+ around_id=message_id,
+ limit=1,
)
- except Exception as exc: # pragma: no cover - defensive
- logger.exception("show event dispatch failed")
- _publish_show_dispatch_event(event_payload, "stream.error", {"reason": "dispatch_failed", "detail": str(exc)})
+ return next(
+ (item for item in window["messages"] if item.get("id") == message_id),
+ None,
+ )
def _show_event_dispatch_text(event_payload: dict[str, Any]) -> str:
@@ -9169,21 +9500,6 @@ def _show_event_dispatch_text(event_payload: dict[str, Any]) -> str:
return "\n".join(lines)
-def _publish_show_dispatch_event(event_payload: dict[str, Any], event_name: str, data: Any) -> None:
- from vibe.sse_broker import broker
-
- broker.publish(
- "show.dispatch",
- {
- "show_event_id": event_payload.get("id"),
- "session_id": event_payload.get("session_id"),
- "scope_id": event_payload.get("scope_id"),
- "event": event_name,
- "data": data,
- },
- )
-
-
def _show_event_response_payload(
event_payload: dict[str, Any],
*,
@@ -9227,28 +9543,6 @@ def _show_event_response_payload(
return public_event
-def _show_dispatch_response_payload(event_payload: dict[str, Any], *, public: bool = False) -> dict[str, Any]:
- if not public:
- return event_payload
- return {
- key: _redact_public_dispatch_value(value)
- for key, value in event_payload.items()
- if key not in {"session_id", "scope_id", "message_id", "message", "user_message_id"}
- }
-
-
-def _redact_public_dispatch_value(value: Any) -> Any:
- if isinstance(value, dict):
- return {
- key: _redact_public_dispatch_value(nested)
- for key, nested in value.items()
- if key not in {"session_id", "scope_id", "message_id", "message", "user_message_id"}
- }
- if isinstance(value, list):
- return [_redact_public_dispatch_value(item) for item in value]
- return value
-
-
def _show_events_list_payload(
payload: dict[str, Any],
*,
@@ -9336,8 +9630,6 @@ async def _show_events_stream(
public_share_id=public_share_id,
),
)
- elif event_type == "show.dispatch" and isinstance(event_payload, dict) and _event_visible(event_payload):
- yield _sse_frame("show.dispatch", _show_dispatch_response_payload(event_payload, public=public))
except asyncio.TimeoutError:
yield ": ping\n\n"
except asyncio.CancelledError:
@@ -9393,7 +9685,7 @@ async def _show_events_response(
if not _show_event_write_authorized(session_id):
return jsonify({"ok": False, "code": "show_event_write_forbidden"}), 403
- return _show_event_response_from_payload(
+ return await _show_event_response_from_payload(
session_id,
_show_events_payload_from_request(),
author=_show_request_author(),
@@ -9401,10 +9693,10 @@ async def _show_events_response(
@app.route("/api/show/sessions/<session_id>/events", methods=["POST"])
-def show_session_events_create(session_id: str):
+async def show_session_events_create(session_id: str):
if not _is_cli_show_event_request():
return jsonify({"ok": False, "code": "forbidden"}), 403
- return _show_event_response_from_payload(session_id, _show_events_payload_from_request())
+ return await _show_event_response_from_payload(session_id, _show_events_payload_from_request())
@app.route("/api/show/sessions/<session_id>/prewarm", methods=["POST"])
@@ -10265,7 +10557,7 @@ async def serve_public_show_page(share_id, asset_path):
),
400,
)
- return _show_event_response_from_payload(
+ return await _show_event_response_from_payload(
page.session_id,
payload,
author=author,
@@ -10526,6 +10818,19 @@ async def _start_startup_dependency_reconcile() -> None:
)
+def reconcile_show_dispatch_messages_on_startup() -> None:
+ store = _show_session_event_store()
+ try:
+ reconciled = store.reconcile_dispatch_messages()
+ finally:
+ store.close()
+ if reconciled:
+ logger.info(
+ "Reconciled %s terminal Show dispatch transcript reservation(s)",
+ reconciled,
+ )
+
+
async def _stop_startup_dependency_reconcile() -> None:
global _startup_dependency_reconcile_task
task, _startup_dependency_reconcile_task = _startup_dependency_reconcile_task, None
@@ -10540,6 +10845,7 @@ async def _stop_startup_dependency_reconcile() -> None:
app.add_event_handler("startup", sweep_orphan_show_runtime_servers_on_startup)
+app.add_event_handler("startup", reconcile_show_dispatch_messages_on_startup)
app.add_event_handler("startup", _start_startup_dependency_reconcile)
app.add_event_handler("shutdown", _stop_startup_dependency_reconcile)
app.add_event_handler("shutdown", stop_show_runtime_on_shutdown)