Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
refactor(show): classify annotations as harness messages (#1039)
Call White9fdd4d3de5e9
diff --git a/core/internal_server.py b/core/internal_server.pyindex 41cbe40d9..a0a45a285 100644--- a/core/internal_server.py+++ b/core/internal_server.py@@ -267,23 +267,76 @@ def create_app(controller: "Controller") -> FastAPI:session_id = payload.get("session_id")sid = session_id if isinstance(session_id, str) and session_id else Noneuser_message_id = payload.get("user_message_id")- 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 _reservation_state() -> tuple[dict[str, Any] | None, bool]:+ if not (+ isinstance(user_message_id, str)+ and user_message_id+ and sid+ ):+ return None, False++ from sqlalchemy import select+ from storage import workbench_sessions_service+ from storage.models import messages++ with get_cached_sqlite_engine().connect() as conn:+ reserved = conn.execute(+ select(+ messages.c.type,+ messages.c.author,+ messages.c.source,+ ).where(+ messages.c.id == user_message_id,+ messages.c.session_id == sid,+ )+ ).mappings().first()+ archived = workbench_sessions_service.is_session_archived(conn, sid)+ return reserved, archived++ async def _cancel_matching_turn() -> None:+ if not (+ isinstance(user_message_id, str)+ and user_message_id+ and sid+ ):+ return+ active = manager.in_flight.get(sid)+ active_message_id = str(+ getattr(getattr(active, "context", None), "message_id", None) or ""+ ).strip()+ if active_message_id == user_message_id:+ result = await manager.cancel(sid)+ if not result.get("ok") and not active.task.done():+ active.task.cancel()+ await asyncio.gather(active.task, return_exceptions=True)+ if manager.in_flight.get(sid) is active:+ manager.in_flight.pop(sid, None)+ from core.inbox_events import bus++ bus.publish("turn.end", {"session_id": sid})+ controller.set_agent_status(sid, "idle")++ def _reservation_conflict(*, archived: bool) -> JSONResponse:+ return JSONResponse(+ status_code=409,+ content={+ "ok": False,+ "code": (+ "session_archived"+ if archived+ else "message_reservation_lost"+ ),+ "session_id": session_id,+ "message_id": user_message_id,+ },+ )+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. Keep- # the exact agent-facing text separately from its transcript display text.+ # The caller already persisted an input as ``pending``; promote it to+ # ``queued`` so it drains 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:engine = get_cached_sqlite_engine()with engine.begin() as conn:@@ -294,161 +347,102 @@ def create_app(controller: "Controller") -> FastAPI:)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()+ def _accept_reserved_input() -> dict[str, Any] | None:+ """Persist controller acceptance before the HTTP response can be lost."""- 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+ if not (+ isinstance(user_message_id, str)+ and user_message_id+ and sid+ ):+ return None- 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(+ from core.inbox_events import bus+ from storage import messages_service++ promoted = False+ with get_cached_sqlite_engine().begin() as conn:+ row = messages_service.get_message(conn,- show_event_id,+ user_message_id,session_id=sid,)- if show_status is None:- return JSONResponse(- status_code=409,- content={"ok": False, "code": "show_event_not_found"},+ if row is None:+ return None+ target_type = messages_service.pending_message_target_type(+ row.get("author"),+ row.get("source"),)- 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"},+ promoted = messages_service.promote_pending(+ conn,+ user_message_id,+ target_type,)-- 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(+ if promoted:+ row = messages_service.get_message(conn,- show_event_id,+ user_message_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 promoted and row is not None:+ bus.publish("message.new", row)+ bus.publish(+ "session.activity",+ {+ "session_id": sid,+ "scope_id": row.get("scope_id"),+ "event": (+ "show_event"+ if row.get("type") == messages_service.HARNESS_TYPE+ else "user_message"),},)- 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"},+ try:+ with get_cached_sqlite_engine().connect() as conn:+ inbox_row = messages_service.get_inbox_session(+ conn,+ sid,+ platform="avibe",+ )+ if inbox_row is not None:+ bus.publish("inbox.session.updated", inbox_row)+ except Exception:+ logger.debug(+ "inbox.session.updated publish (accepted input) failed",+ exc_info=True,)- 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+ return row+ if isinstance(user_message_id, str) and user_message_id and sid: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()+ reserved, archived = _reservation_state()+ if archived or reserved is None:+ return _reservation_conflict(archived=archived)+ reserved_type = str(reserved["type"])if (active_message_id == user_message_idand 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":+ accepted = _accept_reserved_input()+ if accepted is None:+ reserved, archived = _reservation_state()+ if archived or reserved is None:+ await _cancel_matching_turn()+ return _reservation_conflict(archived=archived)+ reserved_type = (+ str(accepted["type"])+ if accepted is not None+ else messages_service.PENDING_TYPE+ )+ if active_message_id == user_message_id or reserved_type in {+ "user",+ messages_service.HARNESS_TYPE,+ }:return JSONResponse(status_code=202,content={@@ -475,67 +469,26 @@ def create_app(controller: "Controller") -> FastAPI:submission = await manager.submit(sid, context, text, enqueue=_enqueue)settled_message_id = user_message_idsettled_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 submission.route == "ran":+ settled = _accept_reserved_input()+ settled_type = settled.get("type") if settled is not None else Noneif (- not show_event_id+ settled_type is Noneand isinstance(settled_message_id, str)and settled_message_idand 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()+ settled, archived = _reservation_state()+ settled_type = str(settled["type"]) if settled is not None else None+ if archived or settled is None:+ if submission.route == "ran":+ await _cancel_matching_turn()+ return _reservation_conflict(archived=archived)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.+ # may drain synchronously before returning. Read the stored row rather+ # than inferring durability from the route.if settled_type != messages_service.QUEUED_TYPE:return JSONResponse(status_code=202,diff --git a/core/session_turns.py b/core/session_turns.pyindex 9663842c1..c2d8af242 100644--- a/core/session_turns.py+++ b/core/session_turns.py@@ -95,7 +95,7 @@ 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.+ """Move a reserved input row into the queue.Queue rows keep user-visible transcript text in ``content_text``. The promptsubmitted by an entry point may be richer (attachment paths, Show event IDs,@@ -604,13 +604,18 @@ def _promote_merged_user_segment(metadata: Optional[dict[str, Any]],author_id: Optional[str],) -> dict[str, Any]:- """Replace a queued segment with one freshly ordered visible user message.+ """Replace a queued input segment with one freshly ordered visible message.``messages`` sort by ``(created_at, id)`` and ids encode creation time. Reusingan old queued id with a new timestamp makes that pair contradictory, so mintboth together and atomically repoint every dependent record."""canonical = segment[0]+ visible_type = messages_service.pending_message_target_type(+ canonical.get("author"),+ canonical.get("source"),+ )+ is_harness = visible_type == messages_service.HARNESS_TYPEnative_message_ids = [str(row.get("native_message_id") or "").strip()for row in segment@@ -626,13 +631,14 @@ def _promote_merged_user_segment(scope_id=canonical.get("scope_id"),session_id=str(canonical["session_id"]),platform=str(canonical.get("platform") or "avibe"),- author="user",- message_type="user",+ author=messages_service.HARNESS_TYPE if is_harness else "user",+ message_type=visible_type,text=text,content=merged_content,metadata=metadata,- author_id=author_id,- source="user",+ author_id=canonical.get("author_id") if is_harness else author_id,+ author_name=canonical.get("author_name") if is_harness else None,+ source=messages_service.HARNESS_TYPE if is_harness else "user",parent_native_message_id=canonical.get("parent_native_message_id"),delivered_at=canonical.get("delivered_at"),read_at=canonical.get("read_at"),diff --git a/core/show_session_events.py b/core/show_session_events.pyindex 16e7e0fce..9c0a4b234 100644--- a/core/show_session_events.py+++ b/core/show_session_events.py@@ -2,14 +2,12 @@ from __future__ import annotationsimport hashlibimport json-import os-import threadingimport uuid-from contextlib import ExitStack, contextmanager+from contextlib import ExitStackfrom dataclasses import dataclassfrom datetime import datetime, timezonefrom pathlib import Path-from typing import Any, Iterator+from typing import Anyfrom sqlalchemy import delete, select, update@@ -19,7 +17,7 @@ from core.services import sessions as workbench_sessions_servicefrom storage import messages_servicefrom storage.db import create_sqlite_enginefrom storage.importer import ensure_sqlite_state, resolve_primary_platform_from_config-from storage.models import agent_sessions, media_objects, messages, show_session_events+from storage.models import agent_sessions, media_objects, show_session_eventsfrom vibe.i18n import t as i18n_tDEFAULT_MARK_SCOPE = "default"@@ -60,31 +58,15 @@ ASSISTANT_MARK_EVENT_TYPES = {"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()+SHOW_TRIGGER_KIND = {+ "human.annotation.created": "show_annotation",+ "human.intent.submitted": "show_intent",+}# Assistant marks are projected into the chat as a message the *user* reads, so# every member needs its own plain-language label. Keeping the mapping next to# the event set (and asserting they enumerate each other in tests) means a fourth@@ -139,517 +121,12 @@ 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"}:+ if event.get("type") not in SHOW_TRIGGER_KIND:return Falsepayload = 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@@ -666,54 +143,6 @@ 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,@@ -806,7 +235,6 @@ class ShowSessionEventStore:),transcript_text=transcript_text,message_id=None,- dispatch_state=_dispatch_state_json(DISPATCH_NONE),created_at=created_at,))@@ -840,15 +268,24 @@ class ShowSessionEventStore:message: dict[str, Any] | None = Nonemessage_id: str | None = Noneif transcript_text:+ harness_input = requests_dispatchmessage = messages_service.append(conn,scope_id=session["scope_id"],session_id=session_id,platform="avibe",- author="agent" if actor in {"assistant", "system"} else "user",+ author=(+ "agent"+ if actor in {"assistant", "system"}+ else messages_service.HARNESS_TYPE+ if harness_input+ else "user"+ ),message_type=(messages_service.PENDING_TYPEif requests_dispatch and reserve_dispatch+ else messages_service.HARNESS_TYPE+ if harness_inputelse None),text=transcript_text,@@ -860,6 +297,9 @@ class ShowSessionEventStore:"show_event_scope": scope,**({"author": event_payload["author"]} if "author" in event_payload else {}),},+ source=messages_service.HARNESS_TYPE if harness_input else None,+ author_name=SHOW_TRIGGER_KIND[event_type] if harness_input else None,+ author_id=event_id if harness_input else None,native_message_id=f"show:{event_id}",)message_id = message["id"]diff --git a/docs/plans/show-annotation-harness-message.md b/docs/plans/show-annotation-harness-message.mdnew file mode 100644index 000000000..6ce0506bf--- /dev/null+++ b/docs/plans/show-annotation-harness-message.md@@ -0,0 +1,173 @@+# Show Page annotations: a harness message, settled like a chat send++## Background++A Show Page annotation currently reaches chat through machinery no other+turn-input uses.++Two distinct oddities, one origin.++### 1. It renders as if the user typed it++`ShowSessionEventStore.append` writes the transcript row with+`author="user"` and no `source`, so `messages_service.append` resolves it to+`type="user"` (`storage/messages_service.py:362`). Chat renders it as the+right-aligned user bubble — indistinguishable from something the user typed+into the composer.++It is not that. It is turn input the user did not type, produced by another+surface — exactly what a scheduled task, a watch, a webhook, and an agent+callback are. Those already have a home: `source="harness"`, a trigger kind in+`author_name`, and a collapsed row with a labelled chip+(`ui/src/lib/chatTrigger.ts`, `ChatPage.tsx:3223`).++### 2. It carries a private dispatch state machine++`show_session_events.dispatch_state` holds a five-state lifecycle+(`none | in_flight | accepted | failed | archived`) plus an owner identity+(pid + process start + attempt id), a 60 s claim TTL, liveness probing of the+claiming process, and a startup sweep. Around it:++| File | refs |+| --- | --- |+| `core/show_session_events.py` | 63 |+| `tests/test_show_session_events.py` | 33 |+| `core/internal_server.py` | 21 |+| `vibe/ui_server.py` | 15 |+| `vibe/cli.py` | 9 |+| `tests/test_internal_server.py` | 8 |+| `tests/test_show_pages.py` | 6 |+| `tests/test_sqlite_state_migration.py` | 5 |+| `storage/alembic/versions/20260726_0035_show_event_dispatch_state.py` | 5 |+| `tests/test_ui_show_pages.py` | 2 |+| `storage/models.py` | 1 |++168 references. A chat send does the same job with none of them.++## Why the machine exists, and why it no longer needs to++A persisted lifecycle is how you answer "did the dispatch land?" **when the+answer cannot be returned in the response**. That was true when the annotation+POST fired the dispatch into a background task. It is no longer true:++- HTTP: `_show_event_response_from_payload` **awaits** the dispatch+ (`vibe/ui_server.py:9143`) and returns 202 `dispatch_pending` or 502 from the+ outcome.+- CLI: `record_local_show_event(..., dispatch_sync=True)`+ (`vibe/cli.py:11209`) runs it through `asyncio.run` and raises on failure.+- The fire-and-forget branch — `_dispatch_show_event_if_requested`+ (`vibe/ui_server.py:9211`) — has **no production caller left**. The CLI is the+ only caller of `record_local_show_event`, it passes `dispatch_sync=True`, and+ it runs with no event loop, so it returns from the sync branch above. Only+ tests reach the async branch, and they reach it by monkeypatching.++Two further jobs people assume the machine does, which it does not:++- **Replay safety.** That comes from `insert().prefix_with("OR IGNORE")` plus+ the `rowcount == 0` early return (`core/show_session_events.py:813-839`),+ inside one transaction. A replayed event id returns the stored row and never+ reaches dispatch — with or without a claim.+- **Archive safety.** `workbench_sessions_service` already clears pending rows+ on archive (`storage/workbench_sessions_service.py:989`), and the dispatch+ path re-checks archive state.++What the machine genuinely covers, and what must survive the deletion:++- **A crash between reserving the transcript row and settling it** leaves an+ invisible `pending` row. The startup sweep repairs it today — for Show events+ only. Chat sends have the identical exposure and no repair at all+ (`ui_server.py:7702` reserves; only the success/failure paths promote).++## Target++**One rule: a reserved transcript row is repaired by type, not by a per-event+lifecycle.** Replace the whole machine with a startup sweep that promotes every+stranded `pending` row to its visible type, whatever wrote it. That is strictly+more coverage than today (chat gains a repair it never had) in an order of+magnitude less code.++### Contract A — the annotation is a harness message++In `ShowSessionEventStore.append`, a human Show event that requests dispatch+writes its transcript row as harness input:++```python+source="harness"+author_name=SHOW_TRIGGER_KIND[event_type] # closed map, see below+author_id=event_id+```++`SHOW_TRIGGER_KIND` is a closed map over the two event types that+`show_event_requests_dispatch` accepts:++| event type | trigger kind | zh label | en label |+| --- | --- | --- | --- |+| `human.annotation.created` | `show_annotation` | 页面批注 | Page annotation |+| `human.intent.submitted` | `show_intent` | 页面操作 | Page action |++Both are the same mechanism and must not be split: classifying one and leaving+the other as a fake user bubble is the defect, restated.++Reserved rows keep `message_type=PENDING_TYPE`; the promote target becomes+`HARNESS_TYPE` instead of `"user"`. `HARNESS_TYPE` is already in+`TRANSCRIPT_TYPES`, so transcript visibility is unchanged.++Assistant/system marks (`actor in {"assistant", "system"}`) are **not** touched+— they stay agent-authored rows.++Frontend:++- `ui/src/lib/chatTrigger.ts` — `harnessChipLabelKey` returns+ `chat.source.showAnnotation` / `chat.source.showIntent` for the two kinds.+ `chatTriggerLink` returns `null` for both (non-navigating), matching+ `webhook`. Deep-linking a chip back to the Show Page is a separate change and+ is **out of scope**.+- `ui/src/i18n/{zh,en}.json` — the four strings above under `chat.source`.++### Contract B — dispatch settles in the response, and the row is repaired by type++1. Delete `show_session_events.dispatch_state` (column + migration) and every+ symbol built on it: the five state constants, `SHOW_DISPATCH_CLAIM_TTL_SECONDS`,+ `_ACTIVE_SHOW_DISPATCH_ATTEMPTS`, `ShowDispatchStatus`,+ `ShowDispatchSettlement`, `_ShowDispatchOwnerIdentity`,+ `show_dispatch_attempt`, `claim_show_dispatch`, `settle_show_dispatch`,+ `observe_and_settle_show_dispatch`, `reconcile_show_dispatch_settlement`,+ `get_show_dispatch_status`, `ShowSessionEventStore.get_dispatch_status`,+ `reconcile_dispatch_settlement`, `reconcile_dispatch_messages`.+2. Delete `_dispatch_show_event_if_requested` and the `dispatch_sync=False`+ branch of `record_local_show_event`. Local recording dispatches+ synchronously, full stop.+3. `_run_show_event_dispatch` keeps its shape — reserve, dispatch, promote,+ return an outcome — and drops `dispatch_owner` from the dispatch payload and+ from the internal endpoint's contract.+4. `core/internal_server.py` drops the `show_event_id` state re-derivation+ branch. It keeps the `PENDING → QUEUED_TYPE` promotion when the session is+ busy (`core/session_turns.py:105`), which is orthogonal.+5. New startup sweep, origin-agnostic: promote every `pending` message row to+ its visible type. Show/harness rows → `HARNESS_TYPE`; chat rows →+ `"user"`. Derive the target from the row's own `author`/`source`, so the+ sweep needs no join to `show_session_events`.++The 202 `dispatch_pending` / 502 responses stay exactly as they are — they are+the reporting surface that replaces the state machine, and the SDK already+throws on `!response.ok` (`packages/sdk/src/index.ts:468,586`).++## Non-goals++- Renaming `mark` / `unmark` or any Show Page URL parameter.+- Touching host-page routing, parameters, or behaviour.+- Deep-linking the new chip back to the Show Page.+- Any release tag.++## Evidence layers++- **unit** — trigger-kind map is a closed pure map; the pending-sweep target+ resolver is pure and tested per origin.+- **contract** — `tests/test_show_session_events.py` and+ `tests/test_internal_server.py` rewritten against the new shape: a replayed+ event id does not re-dispatch; a failed dispatch promotes the row and answers+ 502; an archived session rejects; a stranded `pending` row from **either**+ origin is repaired by the sweep.+- **frontend** — `chatTrigger` label-key branch per kind; `npm run build`.+- **manual** — Incus regression: annotate a page, confirm the chat row is the+ collapsed harness row titled 页面批注, and that the agent still answers it.diff --git a/storage/alembic/versions/20260726_0037_remove_show_event_dispatch_state.py b/storage/alembic/versions/20260726_0037_remove_show_event_dispatch_state.pynew file mode 100644index 000000000..f1688acc3--- /dev/null+++ b/storage/alembic/versions/20260726_0037_remove_show_event_dispatch_state.py@@ -0,0 +1,155 @@+"""remove the Show event dispatch state machine++Revision ID: 20260726_0037+Revises: 20260726_0036+Create Date: 2026-07-26+"""++from __future__ import annotations++import json++import sqlalchemy as sa+from alembic import op++revision = "20260726_0037"+down_revision = "20260726_0036"+branch_labels = None+depends_on = None++_NONE_STATE = '{"state":"none"}'+_ACCEPTED_STATE = '{"state":"accepted"}'+_PENDING_TYPE = "pending"+_HARNESS_TYPE = "harness"+_SHOW_TRIGGER_KINDS = {+ "human.annotation.created": "show_annotation",+ "human.intent.submitted": "show_intent",+}+++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 _reconcile_show_messages() -> None:+ bind = op.get_bind()+ events = list(+ bind.execute(+ sa.text(+ "select id, event_type, message_id, payload_json, dispatch_state "+ "from show_session_events "+ "where message_id is not null"+ )+ ).mappings()+ )+ for event in events:+ trigger_kind = _SHOW_TRIGGER_KINDS.get(str(event["event_type"]))+ payload = json.loads(str(event["payload_json"]))+ if trigger_kind is None or not bool(payload.get("dispatch")):+ continue+ accepted = (+ json.loads(str(event["dispatch_state"])).get("state") == "accepted"+ )+ op.execute(+ sa.text(+ "update messages "+ "set author = :harness_type, "+ "source = :harness_type, "+ "author_name = :trigger_kind, "+ "author_id = :event_id, "+ "type = case "+ "when type != :pending_type or :accepted then :harness_type "+ "else type end "+ "where id = :message_id"+ ).bindparams(+ accepted=accepted,+ event_id=event["id"],+ trigger_kind=trigger_kind,+ harness_type=_HARNESS_TYPE,+ message_id=event["message_id"],+ pending_type=_PENDING_TYPE,+ )+ )+++def _restore_legacy_show_message_identity() -> None:+ bind = op.get_bind()+ events = list(+ bind.execute(+ sa.text(+ "select event_type, message_id, payload_json "+ "from show_session_events "+ "where message_id is not null"+ )+ ).mappings()+ )+ for event in events:+ if str(event["event_type"]) not in _SHOW_TRIGGER_KINDS:+ continue+ payload = json.loads(str(event["payload_json"]))+ if not bool(payload.get("dispatch")):+ continue+ op.execute(+ sa.text(+ "update messages "+ "set author = :user_type, "+ "source = null, "+ "author_name = null, "+ "author_id = null, "+ "type = case "+ "when type = :harness_type then :user_type "+ "else type end "+ "where id = :message_id"+ ).bindparams(+ harness_type=_HARNESS_TYPE,+ message_id=event["message_id"],+ user_type="user",+ )+ )+++def upgrade() -> None:+ bind = op.get_bind()+ if "dispatch_state" in _columns(bind, "show_session_events"):+ _reconcile_show_messages()+ # SQLite before 3.35 needs the table-rebuild form of DROP COLUMN.+ with op.batch_alter_table("show_session_events") as batch_op:+ batch_op.drop_column("dispatch_state")+++def downgrade() -> 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)+ )+ op.execute(+ sa.text(+ "update show_session_events "+ "set dispatch_state = :none_state "+ "where exists ("+ "select 1 from messages "+ "where messages.id = show_session_events.message_id "+ "and messages.type = :pending_type"+ ")"+ ).bindparams(+ none_state=_NONE_STATE,+ pending_type=_PENDING_TYPE,+ )+ )+ _restore_legacy_show_message_identity()diff --git a/storage/messages_service.py b/storage/messages_service.pyindex 4046930f8..4f70032db 100644--- a/storage/messages_service.py+++ b/storage/messages_service.py@@ -17,7 +17,7 @@ import uuidfrom datetime import datetime, timezonefrom typing import Any, Iterable, Optional-from sqlalchemy import and_, delete, exists, func, or_, select, update+from sqlalchemy import and_, delete, func, or_, select, updatefrom sqlalchemy.engine import Connectionfrom storage.db import escape_sql_like@@ -27,7 +27,6 @@ from storage.models import (messages,scope_settings,scopes,- show_session_events,)from vibe.message_identity import HARNESS_TYPE, INPUT_TURN_AUTHOR_TYPES@@ -398,6 +397,21 @@ def append(return _row_to_payload(payload)+def get_message(+ conn: Connection,+ message_id: str,+ *,+ session_id: Optional[str] = None,+) -> Optional[dict[str, Any]]:+ """Load one message by id, optionally requiring its owning session."""++ query = select(messages).where(messages.c.id == message_id)+ if session_id is not None:+ query = query.where(messages.c.session_id == session_id)+ row = conn.execute(query).mappings().first()+ return _row_to_payload(dict(row)) if row else None++def native_message_exists(conn: Connection, *, platform: str, native_message_id: str) -> bool:"""True when a platform/native message id has already been recorded."""platform = str(platform or "").strip()@@ -662,19 +676,19 @@ def first_user_text(conn: Connection, session_id: str) -> str:# --- Send-while-busy queue + per-session draft -----------------------------# Both reuse the ``messages`` table via dedicated ``type`` values so no extra# table is needed (the queue is ephemeral operational state, not conversation):-# type='queued' — a message the user sent while a turn was in flight; flushed-# (merged, in order) into one dispatch when the turn ends.+# type='queued' — input sent while a turn was in flight; flushed (merged, in+# order) into one dispatch when the turn ends.# type='draft' — the user's unsent compose text for a session; one row per# session, persisted so switching sessions/devices keeps it.-# Both carry author='user'; the transcript (user/result/notify), inbox and-# unread queries are all type-filtered, so neither leaks into the conversation.+# The transcript, inbox, and unread queries are type-filtered, so neither leaks+# into the conversation.QUEUED_TYPE = "queued"DRAFT_TYPE = "draft"-# A reserved-but-not-yet-accepted user row: persisted BEFORE dispatch (so it+# A reserved-but-not-yet-accepted input row: persisted BEFORE dispatch (so it# reserves its (created_at, id) for correct ordering) but hidden from the# transcript, the queue AND the inbox until the controller decides whether the-# turn started (→ promote to 'user') or must be queued (→ promote to 'queued').+# turn started (→ promote by origin) or must be queued (→ promote to 'queued').# This stops another tab from briefly seeing the row as a sent prompt during the# dispatch window (Codex P2).PENDING_TYPE = "pending"@@ -751,15 +765,15 @@ def list_queued(conn: Connection, session_id: str) -> list[dict[str, Any]]:def list_recoverable_pending(conn: Connection) -> list[dict[str, Any]]:- """Pending reservations not owned by the Show dispatch state machine."""+ """Every pending input reservation considered by startup cleanup.++ The caller deletes rows whose sessions are gone and decides which live-session+ origins are safe to make visible without replaying their work.+ """- show_owner = select(show_session_events.c.id).where(- show_session_events.c.message_id == messages.c.id- )query = (select(messages).where(messages.c.type == PENDING_TYPE)- .where(~exists(show_owner)).order_by(messages.c.created_at.asc(), messages.c.id.asc()))return [_row_to_payload(dict(row)) for row in conn.execute(query).mappings().all()]@@ -834,11 +848,7 @@ def clear_queued(conn: Connection, session_id: str) -> int:def clear_pending(conn: Connection, session_id: str) -> int:- """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.- """+ """Drop unsettled transcript reservations for a session."""result = conn.execute(delete(messages).where(messages.c.session_id == session_id)@@ -869,6 +879,13 @@ def promote_pending(conn: Connection, message_id: str, to_type: str) -> bool:return bool(result.rowcount)+def pending_message_target_type(author: Optional[str], source: Optional[str]) -> str:+ """Resolve an accepted input reservation to its transcript-visible type."""+ if HARNESS_TYPE in {author, source}:+ return HARNESS_TYPE+ return "user"++def remove_queued(conn: Connection, session_id: str, message_id: str) -> bool:"""Delete one queued message, scoped to its session so a stale / cross-sessionid can't drop another chat's queued row. Returns True if a row was removed."""diff --git a/storage/models.py b/storage/models.pyindex 01cb782ef..0513a6877 100644--- a/storage/models.py+++ b/storage/models.py@@ -299,7 +299,6 @@ 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_internal_server.py b/tests/test_internal_server.pyindex f5799fbf6..80330bf92 100644--- a/tests/test_internal_server.py+++ b/tests/test_internal_server.py@@ -719,21 +719,32 @@ def test_dispatch_async_enqueues_during_busy_turn(monkeypatch, tmp_path):@pytest.mark.parametrize(- ("stored_type", "active_same_message", "expect_queued", "expected_type"),(- ("pending", True, False, "user"),- ("queued", False, True, "queued"),- ("user", False, False, "user"),+ "stored_type",+ "author",+ "source",+ "active_same_message",+ "expect_queued",+ "expected_type",+ ),+ (+ ("pending", "user", "user", True, False, "user"),+ ("pending", "harness", "harness", True, False, "harness"),+ ("queued", "user", "user", False, True, "queued"),+ ("user", "user", "user", False, False, "user"),),)def test_dispatch_async_deduplicates_replayed_reserved_message(monkeypatch,tmp_path,stored_type,+ author,+ source,active_same_message,expect_queued,expected_type,):+ from core.inbox_events import busfrom core.services import sessions as sessions_servicefrom storage import messages_servicefrom storage.db import create_sqlite_engine@@ -763,13 +774,19 @@ def test_dispatch_async_deduplicates_replayed_reserved_message(scope_id=scope_id,session_id=session["id"],platform="avibe",- author="user",- source="user",+ author=author,+ source=source,message_type=stored_type,text="same show event",)controller = _build_controller_double()+ published: list[tuple[str, dict]] = []+ monkeypatch.setattr(+ bus,+ "publish",+ lambda event_type, data: published.append((event_type, data)),+ )app = internal_server.create_app(controller)transport = httpx.ASGITransport(app=app)@@ -816,32 +833,26 @@ def test_dispatch_async_deduplicates_replayed_reserved_message()["messages"]assert [item["id"] for item in rows] == [row["id"]]assert rows[0]["type"] == expected_type+ visible_events = [+ data+ for event_type, data in published+ if event_type == "message.new"+ ]+ if stored_type == messages_service.PENDING_TYPE:+ assert [item["id"] for item in visible_events] == [row["id"]]+ else:+ assert visible_events == []- ("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(+def test_dispatch_async_persists_acceptance_before_a_lost_response_replay(monkeypatch,tmp_path,- case,- expected_code,):- from sqlalchemy import delete, update-+ from core.inbox_events import busfrom core.services import sessions as sessions_service- from core.show_session_events import (- ShowSessionEventStore,- claim_show_dispatch,- )+ from storage import messages_servicefrom storage.db import create_sqlite_enginefrom storage.importer import ensure_sqlite_state- from storage.models import agent_sessions, messagesfrom storage.settings_service import upsert_scopemonkeypatch.setenv("AVIBE_HOME", str(tmp_path))@@ -852,7 +863,7 @@ def test_dispatch_async_rejects_missing_or_archived_show_reservation(conn,platform="avibe",scope_type="project",- native_id=f"proj_show_reject_{case}",+ native_id="proj_lost_acceptance_response",now="2026-05-31T00:00:00Z",)_seed_project_workdir(conn, scope_id, tmp_path)@@ -862,88 +873,80 @@ def test_dispatch_async_rejects_missing_or_archived_show_reservation(agent_backend="claude",agent_name="worker",)+ row = messages_service.append(+ conn,+ scope_id=scope_id,+ session_id=session["id"],+ platform="avibe",+ author="harness",+ source="harness",+ message_type=messages_service.PENDING_TYPE,+ text="Dispatch exactly once.",+ )- 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")- )+ controller = None- controller = _build_controller_double()+ async def handler(context, _text):+ controller.mark_turn_complete(context)++ controller = _build_controller_double(handler)+ published: list[tuple[str, dict]] = []+ monkeypatch.setattr(+ bus,+ "publish",+ lambda event_type, data: published.append((event_type, data)),+ )app = internal_server.create_app(controller)transport = httpx.ASGITransport(app=app)+ payload = {+ "session_id": session["id"],+ "text": "Dispatch exactly once.",+ "user_message_id": row["id"],+ }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": "Do not submit this turn.",- "user_message_id": message_id,- "show_event_id": event_id,- "dispatch_owner": owner,- },- )+ first = await client.post("/internal/dispatch_async", json=payload)+ for _ in range(200):+ if session["id"] not in app.state.in_flight_dispatches:+ break+ await asyncio.sleep(0.01)+ replay = await client.post("/internal/dispatch_async", json=payload)+ return first, replay- response = asyncio.run(_go())+ first, replay = asyncio.run(_go())- assert response.status_code == 409- assert response.json()["code"] == expected_code- controller.message_handler.handle_user_message.assert_not_awaited()+ assert first.status_code == 202+ assert first.json()["message_type"] == messages_service.HARNESS_TYPE+ assert replay.status_code == 202+ assert replay.json()["duplicate"] is True+ controller.message_handler.handle_user_message.assert_awaited_once()+ with engine.connect() as conn:+ settled = messages_service.get_message(+ conn,+ row["id"],+ session_id=session["id"],+ )+ assert settled is not None+ assert settled["type"] == messages_service.HARNESS_TYPE+ assert [+ data["id"]+ for event_type, data in published+ if event_type == "message.new"+ ] == [row["id"]]-def test_dispatch_async_archive_race_never_marks_lost_show_reservation_accepted(+def test_dispatch_async_rejects_archived_session_after_reservation_reclaimed(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 import messages_service, workbench_sessions_servicefrom storage.db import create_sqlite_enginefrom storage.importer import ensure_sqlite_state- from storage.models import messagesfrom storage.settings_service import upsert_scopemonkeypatch.setenv("AVIBE_HOME", str(tmp_path))@@ -954,7 +957,7 @@ def test_dispatch_async_archive_race_never_marks_lost_show_reservation_accepted(conn,platform="avibe",scope_type="project",- native_id="proj_show_archive_race",+ native_id="proj_archived_dispatch",now="2026-05-31T00:00:00Z",)_seed_project_workdir(conn, scope_id, tmp_path)@@ -964,108 +967,53 @@ def test_dispatch_async_archive_race_never_marks_lost_show_reservation_accepted(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(+ row = messages_service.append(conn,- event["id"],+ scope_id=scope_id,session_id=session["id"],- owner=owner,+ platform="avibe",+ author="harness",+ source="harness",+ message_type=messages_service.PENDING_TYPE,+ text="Do not dispatch after archive.",)- assert claimed is not None- assert claimed.state == DISPATCH_IN_FLIGHT- assert claimed.claimed is True+ with engine.begin() as conn:+ workbench_sessions_service.archive_session(conn, session["id"])controller = _build_controller_double()app = internal_server.create_app(controller)transport = httpx.ASGITransport(app=app)- 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,- )-- monkeypatch.setattr(controller.session_turns, "submit", archive_during_submit)-- async def _post():+ async def _go():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),+ return await client.post(+ "/internal/dispatch_async",+ json={+ "session_id": session["id"],+ "text": "Do not dispatch after archive.",+ "user_message_id": row["id"],+ },)- first, replay = asyncio.run(_post())+ response = asyncio.run(_go())- 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+ assert response.status_code == 409+ assert response.json()["code"] == "session_archived"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):+def test_dispatch_async_cancels_turn_when_archive_reclaims_reservation_during_submit(+ 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 import messages_service, workbench_sessions_servicefrom storage.db import create_sqlite_enginefrom storage.importer import ensure_sqlite_statefrom storage.settings_service import upsert_scope- from vibe import internal_client, ui_server- from vibe.sse_broker import brokermonkeypatch.setenv("AVIBE_HOME", str(tmp_path))ensure_sqlite_state()@@ -1075,7 +1023,7 @@ def test_failed_show_dispatch_retries_same_event_through_manager_once(monkeypatcconn,platform="avibe",scope_type="project",- native_id="proj_show_retry",+ native_id="proj_archive_during_submit",now="2026-05-31T00:00:00Z",)_seed_project_workdir(conn, scope_id, tmp_path)@@ -1085,182 +1033,56 @@ def test_failed_show_dispatch_retries_same_event_through_manager_once(monkeypatcagent_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(+ row = messages_service.append(conn,+ scope_id=scope_id,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",+ author="harness",+ source="harness",+ message_type=messages_service.PENDING_TYPE,+ text="Archive before acceptance.",)- 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 = []+ controller = _build_controller_double()+ app = internal_server.create_app(controller)+ real_submit = controller.session_turns.submit- async def tracked_submit(*args, **kwargs):- submissions.append((args, kwargs))- return await real_submit(*args, **kwargs)+ async def submit_then_archive(*args, **kwargs):+ submission = await real_submit(*args, **kwargs)+ with engine.begin() as conn:+ workbench_sessions_service.archive_session(conn, session["id"])+ return submission- monkeypatch.setattr(manager, "submit", tracked_submit)+ monkeypatch.setattr(controller.session_turns, "submit", submit_then_archive)+ transport = httpx.ASGITransport(app=app)- async def accepted_without_response(payload, **_kwargs):+ async def _go():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,+ response = await client.post(+ "/internal/dispatch_async",+ json={+ "session_id": session["id"],+ "text": "Archive before acceptance.",+ "user_message_id": row["id"],},- },- reserve_dispatch=True,- )- finally:- store.close()+ )+ for _ in range(100):+ if session["id"] not in app.state.in_flight_dispatches:+ break+ await asyncio.sleep(0.01)+ return response- 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+ response = asyncio.run(_go())- 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"+ assert response.status_code == 409+ assert response.json()["code"] == "session_archived"+ assert session["id"] not in app.state.in_flight_dispatches+ controller.command_handler.handle_stop.assert_awaited_once()+ controller.message_handler.handle_user_message.assert_not_awaited()def test_slow_live_show_post_cli_timeout_waits_without_duplicate_submit(@@ -1401,11 +1223,7 @@ def test_slow_live_show_post_cli_timeout_waits_without_duplicate_submit(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 core.show_session_events import ShowSessionEventStorefrom storage import messages_servicefrom storage.db import create_sqlite_enginefrom storage.importer import ensure_sqlite_state@@ -1477,16 +1295,6 @@ def test_dispatch_async_queues_show_annotation_and_runs_it_after_active_turn(monf"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={@@ -1494,7 +1302,6 @@ def test_dispatch_async_queues_show_annotation_and_runs_it_after_active_turn(mon"text": enriched_dispatch_text,"user_message_id": annotation["message_id"],"show_event_id": annotation["id"],- "dispatch_owner": dispatch_owner,},)assert queued.status_code == 202@@ -1528,23 +1335,22 @@ def test_dispatch_async_queues_show_annotation_and_runs_it_after_active_turn(monfrom storage.models import show_session_eventsassert messages_service.list_queued(conn, session_id) == []- visible = messages_service.list_session_messages(conn, session_id=session_id, types=("user",))+ visible = messages_service.list_session_messages(+ conn,+ session_id=session_id,+ types=messages_service.TRANSCRIPT_TYPES,+ )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]["type"] == messages_service.HARNESS_TYPE+ assert visible["messages"][0]["author_name"] == "show_annotation"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_ACCEPTEDdef test_dispatch_async_keeps_identified_show_row_after_idle_anonymous_queue(@@ -1552,7 +1358,7 @@ def test_dispatch_async_keeps_identified_show_row_after_idle_anonymous_queue(tmp_path,):from core.services import sessions as sessions_service- from core.show_session_events import ShowSessionEventStore, claim_show_dispatch+ from core.show_session_events import ShowSessionEventStorefrom storage import messages_servicefrom storage.db import create_sqlite_enginefrom storage.importer import ensure_sqlite_state@@ -1620,15 +1426,6 @@ def test_dispatch_async_keeps_identified_show_row_after_idle_anonymous_queue(manager._run = capture_runtransport = 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.claimedasync def _go():async with httpx.AsyncClient(@@ -1642,7 +1439,6 @@ def test_dispatch_async_keeps_identified_show_row_after_idle_anonymous_queue("text": annotation["transcript_text"],"user_message_id": annotation["message_id"],"show_event_id": annotation["id"],- "dispatch_owner": dispatch_owner,},)@@ -1666,7 +1462,7 @@ def test_dispatch_async_keeps_identified_show_row_after_idle_anonymous_queue(visible = messages_service.list_session_messages(conn,session_id=session["id"],- types=("user",),+ types=messages_service.TRANSCRIPT_TYPES,)["messages"]assert [row["id"] for row in queued] == [annotation["message_id"]]assert original_exists == annotation["message_id"]@@ -1686,7 +1482,7 @@ def test_dispatch_async_keeps_identified_show_row_after_idle_anonymous_queue(visible = messages_service.list_session_messages(conn,session_id=session["id"],- types=("user",),+ types=messages_service.TRANSCRIPT_TYPES,)["messages"]assert [run[1] for run in runs] == ["older stopped message",@@ -1694,6 +1490,8 @@ def test_dispatch_async_keeps_identified_show_row_after_idle_anonymous_queue(]assert original_exists is Noneassert linked_message_id == visible[1]["id"]+ assert visible[1]["type"] == messages_service.HARNESS_TYPE+ assert visible[1]["author_name"] == "show_annotation"assert visible[1]["native_message_id"] == f"show:{annotation['id']}"diff --git a/tests/test_messages_service.py b/tests/test_messages_service.pyindex 05f7b58f9..6c47931c7 100644--- a/tests/test_messages_service.py+++ b/tests/test_messages_service.py@@ -414,6 +414,20 @@ def test_append_normalizes_legacy_harness_identity(isolated_state):assert row["source"] == messages_service.HARNESS_TYPE+ ("author", "source", "expected"),+ [+ ("user", "user", "user"),+ ("user", None, "user"),+ ("harness", "harness", "harness"),+ ("user", "harness", "harness"),+ ("harness", None, "harness"),+ ],+)+def test_pending_message_target_type_uses_row_origin(author, source, expected):+ assert messages_service.pending_message_target_type(author, source) == expected++def test_same_second_messages_order_by_insertion(isolated_state):"""Rows sharing a (second-resolution) created_at still order by insertion inthe transcript: the monotonic message id breaks the ``(created_at, id)`` tie,diff --git a/tests/test_show_pages.py b/tests/test_show_pages.pyindex f51a23c58..39556e3f8 100644--- a/tests/test_show_pages.py+++ b/tests/test_show_pages.py@@ -3135,18 +3135,17 @@ def test_show_event_cli_dispatch_fallback_records_and_dispatches(monkeypatch, tmassert 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):+def test_show_event_cli_embedded_dispatch_fallback_uses_synchronous_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):+ def fake_record(session_id, payload):captured.update(session_id=session_id,payload=payload,- dispatch_sync=dispatch_sync,)return {"id": "show_evt_local", "type": payload["type"], "message_id": "msg_local"}@@ -3169,10 +3168,59 @@ def test_show_event_cli_embedded_dispatch_fallback_uses_sync_bridge(monkeypatch,)assert cli.cmd_show(args) == 0- assert captured["dispatch_sync"] is Trueassert captured["payload"]["annotation"]["dispatch"] is True+def test_show_event_cli_failed_delivery_reports_generated_event_id(+ monkeypatch,+ tmp_path,+ capsys,+):+ from core.show_session_events import ShowSessionEventError++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ paths.ensure_data_dirs()+ _save_config()+ monkeypatch.setattr(cli, "_post_show_event_to_live_ui", lambda *_args: None)+ attempted = {}++ def fail_local_delivery(_session_id, payload):+ attempted["event_id"] = payload["id"]+ raise ShowSessionEventError(+ "Show event delivery failed.",+ code="show_event_dispatch_failed",+ )++ monkeypatch.setattr(+ "vibe.ui_server.record_local_show_event",+ fail_local_delivery,+ )+ args = cli.build_parser().parse_args(+ [+ "show",+ "event",+ "--session-id",+ "ses123",+ "--event-json",+ json.dumps(+ {+ "type": "human.annotation.created",+ "annotation": {+ "comment": "Keep the retry identity.",+ "dispatch": True,+ },+ }+ ),+ "--json",+ ]+ )++ assert cli.cmd_show(args) == 1+ error = json.loads(capsys.readouterr().err)+ assert attempted["event_id"].startswith("show_evt_")+ assert error["details"]["event_id"] == attempted["event_id"]++@pytest.mark.parametrize("blank_event_id", [None, "", " "])def test_show_event_cli_timeout_replaces_blank_id_before_local_retry(monkeypatch,@@ -3192,8 +3240,8 @@ def test_show_event_cli_timeout_replaces_blank_id_before_local_retry(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))+ def record_local(session_id, payload):+ replayed.append((session_id, payload))return {"id": payload["id"],"type": payload["type"],@@ -3224,44 +3272,31 @@ def test_show_event_cli_timeout_replaces_blank_id_before_local_retry(assert cli.cmd_show(args) == 0assert len(replayed) == 1- replay_session_id, replay_payload, dispatch_sync = replayed[0]+ replay_session_id, replay_payload = replayed[0]assert replay_session_id == "ses123"- assert dispatch_sync is Trueassert 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.message_types = iter(("pending", "harness"))self.closed = Falseinstances.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={+ return {+ "id": event_id,+ "session_id": session_id,+ "message": {"id": "msg_poll_once","session_id": session_id,- "type": "user",+ "type": next(self.message_types),},- )+ }def close(self):self.closed = True@@ -3275,7 +3310,15 @@ def test_show_event_cli_timeout_poll_reuses_one_event_store(monkeypatch):wait_seconds=1,)- assert resolved == {"id": "show_evt_poll_once", "session_id": "ses123"}+ assert resolved == {+ "id": "show_evt_poll_once",+ "session_id": "ses123",+ "message": {+ "id": "msg_poll_once",+ "session_id": "ses123",+ "type": "harness",+ },+ }assert len(instances) == 1assert instances[0].closed@@ -3328,36 +3371,28 @@ def test_show_event_cli_pending_response_polls_instead_of_falling_back(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,- )-+def test_show_event_cli_pending_timeout_allows_same_reservation_retry(monkeypatch):class FakeStore:- def get_dispatch_status(self, _session_id, _event_id):- return ShowDispatchStatus(state=DISPATCH_IN_FLIGHT)+ def get_event(self, session_id, event_id):+ return {+ "id": event_id,+ "session_id": session_id,+ "message": {"id": "msg_pending", "type": "pending"},+ }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,- )+ resolved = cli._resolve_show_event_after_ambiguous_live_timeout(+ "ses123",+ {"id": "show_evt_pending_retry"},+ wait_seconds=1,+ )- assert exc_info.value.code == "show_event_dispatch_pending"- assert str(exc_info.value) == "Show 事件可能仍在处理中,未在本地重复提交。"+ assert resolved is Nonedef test_show_event_cli_http_502_replays_same_event_identity_locally(monkeypatch, tmp_path):@@ -3380,8 +3415,8 @@ def test_show_event_cli_http_502_replays_same_event_identity_locally(monkeypatchmonkeypatch.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))+ def record_local(session_id, payload):+ replayed.append((session_id, payload))return {"id": payload["id"],"type": payload["type"],@@ -3408,9 +3443,8 @@ def test_show_event_cli_http_502_replays_same_event_identity_locally(monkeypatchassert cli.cmd_show(args) == 0assert len(replayed) == 1- replay_session_id, replay_payload, dispatch_sync = replayed[0]+ replay_session_id, replay_payload = replayed[0]assert replay_session_id == "ses123"- assert dispatch_sync is Trueassert posted["id"].startswith("show_evt_")assert replay_payload["id"] == posted["id"]diff --git a/tests/test_show_session_events.py b/tests/test_show_session_events.pyindex 819edff16..6c51f6302 100644--- a/tests/test_show_session_events.py+++ b/tests/test_show_session_events.py@@ -1,6 +1,5 @@from __future__ import annotations-import asyncioimport base64import jsonimport struct@@ -14,22 +13,13 @@ from core.show_session_events import (ANCHOR_HUMAN_COPY_KEYS,ASSISTANT_MARK_EVENT_TYPES,ASSISTANT_MARK_TRANSCRIPT_I18N_KEYS,- DISPATCH_ACCEPTED,- DISPATCH_ARCHIVED,- DISPATCH_FAILED,- DISPATCH_IN_FLIGHT,- DISPATCH_NONE,MARK_LOCATOR_MAX_LENGTH,MARK_PAYLOAD_KEYS,- ShowDispatchSettlement,- ShowDispatchStatus,+ SHOW_TRIGGER_KIND,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@@ -808,6 +798,25 @@ def test_show_event_store_records_intent_dispatch_payload(isolated_state):assert event["payload"]["dispatch"] is Trueassert "[show-intent] choose" in event["transcript_text"]assert "Pick B." in event["transcript_text"]+ assert event["message"]["author"] == "harness"+ assert event["message"]["source"] == "harness"+ assert event["message"]["author_name"] == "show_intent"+ assert event["message"]["author_id"] == event["id"]+++def test_show_trigger_kind_is_closed_over_dispatching_event_types():+ assert SHOW_TRIGGER_KIND == {+ "human.annotation.created": "show_annotation",+ "human.intent.submitted": "show_intent",+ }+ for event_type in SHOW_TRIGGER_KIND:+ assert show_event_requests_dispatch(+ {+ "type": event_type,+ "actor": "human",+ "payload": {"dispatch": True},+ }+ )def test_show_event_store_records_assistant_page_update(isolated_state):@@ -1205,6 +1214,10 @@ def test_dispatching_show_event_reserves_pending_transcript_row(isolated_state):store.close()assert dispatching["message"]["type"] == messages_service.PENDING_TYPE+ assert dispatching["message"]["author"] == messages_service.HARNESS_TYPE+ assert dispatching["message"]["source"] == messages_service.HARNESS_TYPE+ assert dispatching["message"]["author_name"] == "show_annotation"+ assert dispatching["message"]["author_id"] == dispatching["id"]assert non_dispatching["message"]["type"] == "user"engine = create_sqlite_engine()with engine.connect() as conn:@@ -1317,235 +1330,6 @@ def test_show_event_store_fingerprint_includes_sibling_anchor(isolated_state):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,):@@ -1566,115 +1350,49 @@ def test_localized_show_event_errors_follow_configured_language(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,-):+def test_direct_dispatching_show_event_is_visible_harness_input(isolated_state):from storage import messages_service- from vibe import ui_server- _seed_session("ses_show_restart")+ _seed_session("ses_show")store = ShowSessionEventStore()try:event = store.append(- "ses_show_restart",+ "ses_show",{- "id": "show_evt_restart_reconcile","type": "human.annotation.created","annotation": {- "comment": "Recover my accepted prompt after restart.",+ "intent": "comment",+ "comment": "Record this visibly.","dispatch": True,},},- reserve_dispatch=True,)+ events = store.list("ses_show")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"+ assert event["message"]["type"] == messages_service.HARNESS_TYPE+ assert event["message"]["author"] == messages_service.HARNESS_TYPE+ assert event["message"]["source"] == messages_service.HARNESS_TYPE+ 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_cli_reports_accepted_dispatch_only_after_linked_message_reconciles(- isolated_state,-):- from vibe import cli+def test_startup_repairs_stranded_pending_rows_by_origin(isolated_state):+ from storage import messages_service+ from vibe import ui_server- _seed_session("ses_show_cli_settlement")+ scope_id = _seed_session("ses_show_restart")store = ShowSessionEventStore()try:- event = store.append(- "ses_show_cli_settlement",+ show_event = store.append(+ "ses_show_restart",{- "id": "show_evt_cli_settlement",+ "id": "show_evt_restart_reconcile","type": "human.annotation.created","annotation": {- "comment": "Do not report success while I am hidden.",+ "comment": "Recover my harness prompt after restart.","dispatch": True,},},@@ -1684,182 +1402,49 @@ def test_cli_reports_accepted_dispatch_only_after_linked_message_reconciles(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(+ chat_message = messages_service.append(conn,- event["id"],- session_id="ses_show_cli_settlement",- owner="1:cli-process:attempt",- state=DISPATCH_ACCEPTED,+ scope_id=scope_id,+ session_id="ses_show_restart",+ platform="avibe",+ author="user",+ source="user",+ message_type=messages_service.PENDING_TYPE,+ text="Recover my chat prompt after restart.",)- 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"-+ # One startup sweep handles cleanup for both origins, but only Chat can become+ # visible without proving dispatch acceptance. Show stays retryable.+ summary = ui_server._recover_stale_pending_messages()+ assert summary == {"promoted": 1, "deleted": 0, "skipped": 1}-def test_concurrent_show_dispatch_replay_reports_in_flight_without_resubmit(- isolated_state,- monkeypatch,-):- from vibe import internal_client, ui_server+ with create_sqlite_engine().connect() as conn:+ repaired = {+ row["id"]: row+ for row in messages_service.list_session_messages(+ conn,+ session_id="ses_show_restart",+ types=messages_service.TRANSCRIPT_TYPES,+ )["messages"]+ }+ assert repaired[chat_message["id"]]["type"] == "user"+ assert repaired[chat_message["id"]]["author"] == "user"+ assert show_event["message_id"] not in repaired- _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,- )+ retryable = store.get_event("ses_show_restart", show_event["id"])finally:store.close()+ assert retryable is not None+ assert retryable["message"]["type"] == messages_service.PENDING_TYPE- 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(+def test_record_local_show_event_uses_synchronous_unified_entry(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_serverfrom vibe.sse_broker import broker_seed_session("ses_show")@@ -1867,16 +1452,8 @@ def test_record_local_show_event_dispatch_sync_uses_unified_entry(isolated_statepublished: list[tuple[str, dict]] = []monkeypatch.setattr(broker, "publish", lambda event, data: published.append((event, data)))- async def fake_dispatch_async(payload, **kwargs):+ 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}}monkeypatch.setattr(internal_client, "dispatch_async", fake_dispatch_async)@@ -1884,13 +1461,17 @@ def test_record_local_show_event_dispatch_sync_uses_unified_entry(isolated_state"ses_show",{"type": "human.annotation.created",- "annotation": {"intent": "comment", "comment": "Deliver this.", "dispatch": True},+ "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 "dispatch_owner" not in dispatches[0]+ assert event["message"]["type"] == "harness"assert [name for name, _data in published] == ["show.event","message.new",@@ -1899,7 +1480,7 @@ def test_record_local_show_event_dispatch_sync_uses_unified_entry(isolated_stateassert published[1][1]["id"] == event["message_id"]-def test_record_local_show_event_reports_failed_sync_dispatch_with_retryable_record(+def test_failed_local_show_dispatch_keeps_row_pending_so_replay_retries(isolated_state,monkeypatch,):@@ -1907,39 +1488,51 @@ def test_record_local_show_event_reports_failed_sync_dispatch_with_retryable_recfrom vibe import internal_client, ui_server_seed_session("ses_show")+ attempts = 0- async def fake_dispatch_async(payload, **kwargs):- raise internal_client.InternalServerUnavailable("controller unavailable")+ async def fake_dispatch_async(_payload, **_kwargs):+ nonlocal attempts+ attempts += 1+ if attempts == 1:+ raise internal_client.InternalServerUnavailable("controller unavailable")+ return {"status_code": 202, "body": {"ok": True}}monkeypatch.setattr(internal_client, "dispatch_async", fake_dispatch_async)- stored_event = None+ payload = {+ "id": "show_evt_failed_once",+ "type": "human.annotation.created",+ "annotation": {+ "intent": "comment",+ "comment": "Record this failure once.",+ "dispatch": True,+ },+ }with pytest.raises(ShowSessionEventError) as exc_info:- ui_server.record_local_show_event(- "ses_show",- {- "type": "human.annotation.created",- "annotation": {"intent": "comment", "comment": "Record this.", "dispatch": True},- },- dispatch_sync=True,+ ui_server.record_local_show_event("ses_show", payload)+ assert exc_info.value.code == "show_event_dispatch_failed"++ with create_sqlite_engine().connect() as conn:+ stranded = messages_service.list_session_messages(+ conn,+ session_id="ses_show",+ types=messages_service.TRANSCRIPT_TYPES,)+ assert stranded["messages"] == []- 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()+ replay = ui_server.record_local_show_event("ses_show", payload)++ assert attempts == 2+ assert replay["message"]["type"] == messages_service.HARNESS_TYPEwith 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 == []+ visible = messages_service.list_session_messages(+ conn,+ session_id="ses_show",+ types=messages_service.TRANSCRIPT_TYPES,+ )+ assert [row["id"] for row in visible["messages"]] == [replay["message_id"]]-def test_ended_ambiguous_show_dispatch_attempt_is_immediately_retryable(+def test_ambiguous_local_show_dispatch_replays_under_the_same_reservation(isolated_state,monkeypatch,):@@ -1947,12 +1540,13 @@ def test_ended_ambiguous_show_dispatch_attempt_is_immediately_retryable(from vibe import internal_client, ui_server_seed_session("ses_show")- attempts = 0+ seen_message_ids: list[str] = []- async def fake_dispatch_async(payload, **kwargs):- nonlocal attempts- attempts += 1- raise internal_client.InternalServerTimeout("acceptance unknown")+ async def fake_dispatch_async(dispatch_payload, **_kwargs):+ seen_message_ids.append(dispatch_payload["user_message_id"])+ if len(seen_message_ids) == 1:+ raise internal_client.InternalServerTimeout("acceptance unknown")+ return {"status_code": 202, "body": {"ok": True, "duplicate": True}}monkeypatch.setattr(internal_client, "dispatch_async", fake_dispatch_async)payload = {@@ -1965,33 +1559,15 @@ def test_ended_ambiguous_show_dispatch_attempt_is_immediately_retryable(},}- 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"+ with pytest.raises(ShowSessionEventError) as exc_info:+ ui_server.record_local_show_event("ses_show", payload)+ 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"] == []+ replay = ui_server.record_local_show_event("ses_show", payload)++ assert len(seen_message_ids) == 2+ assert seen_message_ids[0] == seen_message_ids[1]+ assert replay["message"]["type"] == messages_service.HARNESS_TYPE@pytest.mark.parametrize(diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.pyindex 6b71e36a8..b5b2f79eb 100644--- a/tests/test_sqlite_state_migration.py+++ b/tests/test_sqlite_state_migration.py@@ -8,6 +8,7 @@ import threadingfrom pathlib import Pathimport pytest+from alembic import commandfrom alembic.script import ScriptDirectoryfrom config import paths@@ -20,7 +21,7 @@ from storage.models import metadatafrom storage.settings_service import SQLiteSettingsService-HEAD_REVISION = "20260726_0036"+HEAD_REVISION = "20260726_0037"def _index_sql(conn: sqlite3.Connection, name: str) -> str:@@ -29,6 +30,19 @@ def _index_sql(conn: sqlite3.Connection, name: str) -> str:return str(row[0] or "")+class _Pre335Cursor(sqlite3.Cursor):+ def execute(self, sql, parameters=()):+ normalized = " ".join(str(sql).upper().split())+ if " DROP COLUMN " in f" {normalized} ":+ raise sqlite3.OperationalError("near \"DROP\": syntax error")+ return super().execute(sql, parameters)+++class _Pre335Connection(sqlite3.Connection):+ def cursor(self, factory=None):+ return super().cursor(factory or _Pre335Cursor)++def test_alembic_script_directory_has_exactly_one_head() -> None:heads = ScriptDirectory.from_config(migrations.alembic_config()).get_heads()@@ -145,11 +159,7 @@ def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None: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"}'- )+ assert "dispatch_state" not in show_event_columnsbackground_columns = {row[1]for row in conn.execute(@@ -161,52 +171,251 @@ 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(+def test_show_dispatch_state_removal_migration_preserves_existing_events(tmp_path: Path,+ monkeypatch,) -> None:db_path = tmp_path / "vibe.sqlite"- run_migrations(db_path, revision="20260724_0034")+ run_migrations(db_path, revision="20260726_0036")now = "2026-07-26T00:00:00Z"with sqlite3.connect(db_path) as conn:+ for message_id, author, message_type in (+ ("msg_upgrade_accepted", "user", "pending"),+ ("msg_upgrade_retryable", "user", "pending"),+ ("msg_upgrade_visible", "user", "user"),+ ("msg_upgrade_observed", "user", "user"),+ ("msg_upgrade_chat", "user", "pending"),+ ):+ conn.execute(+ """+ insert into messages (+ id, platform, author, type, content_json,+ metadata_json, created_at, updated_at+ ) values (?, 'avibe', ?, ?, '{}', '{}', ?, ?)+ """,+ (message_id, author, message_type, now, now),+ )conn.execute("""insert into show_session_events (id, session_id, event_type, actor, scope, anchor_json,- payload_json, transcript_text, message_id, created_at+ payload_json, transcript_text, message_id, dispatch_state,+ created_at) values ('show_evt_legacy', 'ses_legacy', 'human.annotation.created',- 'human', 'default', '{}', '{}', 'Legacy annotation', null, ?+ 'human', 'default', '{}', '{}', 'Legacy annotation', null,+ '{"state":"in_flight","owner":"1:old"}', ?)""",(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+ payload_json, transcript_text, message_id, dispatch_state,+ created_at) values (- 'show_evt_new', 'ses_new', 'human.annotation.created',- 'human', 'default', '{}', '{}', 'New annotation', null, ?+ 'show_evt_upgrade_accepted', 'ses_upgrade',+ 'human.annotation.created', 'human', 'default', '{}',+ '{"dispatch":true}',+ 'Accepted annotation', 'msg_upgrade_accepted',+ '{"state":"accepted"}', ?)""",(now,),)- new_state = conn.execute(- "select dispatch_state from show_session_events where id = 'show_evt_new'"+ conn.execute(+ """+ insert into show_session_events (+ id, session_id, event_type, actor, scope, anchor_json,+ payload_json, transcript_text, message_id, dispatch_state,+ created_at+ ) values (+ 'show_evt_upgrade_retryable', 'ses_upgrade',+ 'human.intent.submitted', 'human', 'default', '{}',+ '{"dispatch":true}',+ 'Retryable intent', 'msg_upgrade_retryable',+ '{"state":"failed"}', ?+ )+ """,+ (now,),+ )+ conn.execute(+ """+ insert into show_session_events (+ id, session_id, event_type, actor, scope, anchor_json,+ payload_json, transcript_text, message_id, dispatch_state,+ created_at+ ) values (+ 'show_evt_upgrade_visible', 'ses_upgrade',+ 'human.annotation.created', 'human', 'default', '{}',+ '{"dispatch":true}',+ 'Visible annotation', 'msg_upgrade_visible',+ '{"state":"failed"}', ?+ )+ """,+ (now,),+ )+ conn.execute(+ """+ insert into show_session_events (+ id, session_id, event_type, actor, scope, anchor_json,+ payload_json, transcript_text, message_id, dispatch_state,+ created_at+ ) values (+ 'show_evt_upgrade_observed', 'ses_upgrade',+ 'human.annotation.created', 'human', 'default', '{}', '{}',+ 'Observed annotation', 'msg_upgrade_observed',+ '{"state":"accepted"}', ?+ )+ """,+ (now,),+ )+ conn.commit()++ real_connect = sqlite3.connect++ def legacy_connect(*args, **kwargs):+ kwargs["factory"] = _Pre335Connection+ return real_connect(*args, **kwargs)++ monkeypatch.setattr(sqlite3, "connect", legacy_connect)+ monkeypatch.setattr(sqlite3.dbapi2, "connect", legacy_connect)+ run_migrations(db_path)++ with sqlite3.connect(db_path) as conn:+ columns = {+ row[1] for row in conn.execute("pragma table_info(show_session_events)")+ }+ legacy = conn.execute(+ "select id, transcript_text from show_session_events "+ "where id = 'show_evt_legacy'").fetchone()+ upgraded_messages = {+ row[0]: row[1:]+ for row in conn.execute(+ "select id, author, type, source, author_name, author_id "+ "from messages "+ "where id in ("+ "'msg_upgrade_accepted', "+ "'msg_upgrade_retryable', "+ "'msg_upgrade_visible', "+ "'msg_upgrade_observed', "+ "'msg_upgrade_chat'"+ ")"+ ).fetchall()+ }+ for message_id, message_type, event_id in (+ ("msg_pending_show", "pending", "show_evt_pending"),+ ("msg_accepted_show", "harness", "show_evt_accepted"),+ ):+ conn.execute(+ """+ insert into messages (+ id, platform, author, type, source, author_name, author_id,+ content_json,+ metadata_json, created_at, updated_at+ ) values (+ ?, 'avibe', 'harness', ?, 'harness', 'show_annotation',+ ?, '{}', '{}', ?, ?+ )+ """,+ (message_id, message_type, event_id, now, now),+ )+ for event_id, message_id in (+ ("show_evt_pending", "msg_pending_show"),+ ("show_evt_accepted", "msg_accepted_show"),+ ):+ 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 (+ ?, 'ses_downgrade', 'human.annotation.created',+ 'human', 'default', '{}', '{"dispatch":true}',+ 'Downgrade annotation', ?, ?+ )+ """,+ (event_id, message_id, now),+ )+ conn.commit()- assert legacy_state == ('{"state":"accepted"}',)- assert new_state == ('{"state":"none"}',)+ assert "dispatch_state" not in columns+ assert legacy == ("show_evt_legacy", "Legacy annotation")+ assert upgraded_messages["msg_upgrade_accepted"] == (+ "harness",+ "harness",+ "harness",+ "show_annotation",+ "show_evt_upgrade_accepted",+ )+ assert upgraded_messages["msg_upgrade_retryable"] == (+ "harness",+ "pending",+ "harness",+ "show_intent",+ "show_evt_upgrade_retryable",+ )+ assert upgraded_messages["msg_upgrade_visible"] == (+ "harness",+ "harness",+ "harness",+ "show_annotation",+ "show_evt_upgrade_visible",+ )+ assert upgraded_messages["msg_upgrade_observed"] == (+ "user",+ "user",+ None,+ None,+ None,+ )+ assert upgraded_messages["msg_upgrade_chat"] == (+ "user",+ "pending",+ None,+ None,+ None,+ )++ command.downgrade(migrations.alembic_config(db_path), "20260726_0036")++ with sqlite3.connect(db_path) as conn:+ downgraded = dict(+ conn.execute(+ "select id, dispatch_state from show_session_events "+ "where id in ('show_evt_legacy', 'show_evt_pending', 'show_evt_accepted')"+ ).fetchall()+ )+ downgraded_messages = {+ row[0]: row[1:]+ for row in conn.execute(+ "select id, author, type, source, author_name, author_id "+ "from messages "+ "where id in ('msg_pending_show', 'msg_accepted_show')"+ ).fetchall()+ }++ assert json.loads(downgraded["show_evt_legacy"]) == {"state": "accepted"}+ assert json.loads(downgraded["show_evt_accepted"]) == {"state": "accepted"}+ assert json.loads(downgraded["show_evt_pending"]) == {"state": "none"}+ assert downgraded_messages["msg_pending_show"] == (+ "user",+ "pending",+ None,+ None,+ None,+ )+ assert downgraded_messages["msg_accepted_show"] == (+ "user",+ "user",+ None,+ None,+ None,+ )def test_retirement_marker_migration_is_forward_only(tmp_path: Path) -> None:diff --git a/tests/test_ui_session_stream.py b/tests/test_ui_session_stream.pyindex b0d9b6b6e..64a505616 100644--- a/tests/test_ui_session_stream.py+++ b/tests/test_ui_session_stream.py@@ -411,10 +411,12 @@ def test_recover_stale_pending_skips_rows_already_retyped(isolated_state, tmp_papublish.assert_not_called()-def test_recover_stale_pending_leaves_show_owned_rows_to_show_reconciler(+def test_recover_stale_pending_keeps_show_owned_rows_retryable(isolated_state,tmp_path,):+ """Startup cannot make an unaccepted Show reservation look dispatched."""+from core.show_session_events import ShowSessionEventStorefrom vibe import ui_server@@ -439,9 +441,8 @@ def test_recover_stale_pending_leaves_show_owned_rows_to_show_reconciler(with patch("vibe.sse_broker.broker.publish") as publish:summary = ui_server._recover_stale_pending_messages()- ui_server.reconcile_show_dispatch_messages_on_startup()- assert summary == {"promoted": 0, "deleted": 0, "skipped": 0}+ assert summary == {"promoted": 0, "deleted": 0, "skipped": 1}store = ShowSessionEventStore()try:recovered = store.get_event(session_id, event["id"])diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.pyindex 329a9a51e..f73823082 100644--- a/tests/test_ui_show_pages.py+++ b/tests/test_ui_show_pages.py@@ -177,26 +177,18 @@ def _create_agent_session(session_id: str, *, status: str = "active") -> None:)-def _accept_dispatch(payload: dict, message_type: str = "user") -> None:+def _accept_dispatch(payload: dict, message_type: str = "harness") -> None:from core.session_turns import queue_pending_user_message- from core.show_session_events import DISPATCH_ACCEPTED, settle_show_dispatchfrom storage import messages_servicefrom storage.db import create_sqlite_engine- with create_sqlite_engine().begin() as conn:- if message_type == messages_service.QUEUED_TYPE:+ if message_type == messages_service.QUEUED_TYPE:+ with create_sqlite_engine().begin() as conn: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:@@ -2056,7 +2048,7 @@ def test_private_show_page_rejects_reused_event_id_with_different_contents(assert conflict.get_json()["error"] == "此 Show 事件 ID 已绑定到不同的事件内容。"-def test_private_show_page_idle_dispatch_promotes_visible_user_row(monkeypatch, tmp_path):+def test_private_show_page_idle_dispatch_promotes_visible_harness_row(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))_save_config(tmp_path)_create_agent_session("ses123")@@ -2102,18 +2094,24 @@ def test_private_show_page_idle_dispatch_promotes_visible_user_row(monkeypatch,assert "Pick B." in dispatches[0]["text"]assert dispatches[0]["user_message_id"] == response.get_json()["event"]["message_id"]assert dispatches[0]["files"] == []+ assert "dispatch_owner" not in dispatches[0]assert [event_type for event_type, _data in published] == ["show.event","message.new","session.activity",]- assert published[1][1]["type"] == "user"+ assert published[1][1]["type"] == "harness"+ assert published[1][1]["author_name"] == "show_intent"from storage import messages_servicefrom storage.db import create_sqlite_enginewith create_sqlite_engine().connect() as conn:- transcript = messages_service.list_session_messages(conn, session_id="ses123", types=("user",))+ transcript = messages_service.list_session_messages(+ conn,+ session_id="ses123",+ types=messages_service.TRANSCRIPT_TYPES,+ )assert [message["id"] for message in transcript["messages"]] == [response.get_json()["event"]["message_id"]]@@ -2168,11 +2166,11 @@ def test_private_show_page_waits_for_turn_acceptance_before_responding(monkeypatassert not request_thread.is_alive()assert result["response"].status_code == 201- assert result["response"].get_json()["event"]["message"]["type"] == "user"+ assert result["response"].get_json()["event"]["message"]["type"] == "harness"assert dispatch_kwargs == {"timeout": None}-def test_private_show_page_unavailable_dispatch_is_retryable_and_not_reported_as_delivered(+def test_private_show_page_unavailable_dispatch_keeps_row_pending_and_returns_502(monkeypatch,tmp_path,):@@ -2216,12 +2214,10 @@ def test_private_show_page_unavailable_dispatch_is_retryable_and_not_reported_asbody = response.get_json()assert body["ok"] is Falseassert 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",- ]+ # No turn started, so the reservation remains outside the transcript.+ assert body["event"]["message"]["type"] == "pending"+ assert body["event"]["message"]["author_name"] == "show_annotation"+ assert [event_type for event_type, _data in published] == ["show.event"]def test_private_show_page_concurrent_dispatch_replay_returns_pending(@@ -2336,7 +2332,8 @@ def test_private_show_page_returns_promoted_row_after_synchronous_queue_drain(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"+ assert event["message"]["type"] == "harness"+ assert event["message"]["author_name"] == "show_annotation"# 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.@@ -2389,7 +2386,11 @@ def test_private_show_page_busy_dispatch_queues_without_message_new(monkeypatch,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",))+ transcript = messages_service.list_session_messages(+ conn,+ session_id="ses123",+ types=messages_service.TRANSCRIPT_TYPES,+ )assert [(message["id"], message["text"]) for message in queued] == [(message_id, response.get_json()["event"]["transcript_text"])]@@ -2993,7 +2994,7 @@ def test_cli_show_event_dispatch_waits_for_unambiguous_acceptance(monkeypatch, tassert not request_thread.is_alive()assert result["response"].status_code == 201- assert result["response"].get_json()["event"]["message"]["type"] == "user"+ assert result["response"].get_json()["event"]["message"]["type"] == "harness"def test_cli_show_event_ingress_requires_cli_token(monkeypatch, tmp_path):@@ -3553,9 +3554,7 @@ def test_public_show_page_events_ignore_client_event_id_and_dispatch(monkeypatch_create_agent_session("ses123")share_id = _create_show_page("ses123", "public")published = []- dispatch_calls = []monkeypatch.setattr("vibe.ui_server._publish_show_session_event", published.append)- monkeypatch.setattr("vibe.ui_server._dispatch_show_event_if_requested", dispatch_calls.append)client = app.test_client()client.set_cookie(remote_access.SESSION_COOKIE_NAME,@@ -3581,7 +3580,6 @@ def test_public_show_page_events_ignore_client_event_id_and_dispatch(monkeypatchassert "\n" not in event["id"]assert "dispatch" not in event["payload"]assert "dispatch" not in published[0]["payload"]- assert dispatch_calls == []@pytest.mark.parametrize("event_type", ["assistant.mark.created", "system.annotation.control"])diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 4986281c3..e881824ed 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -2835,6 +2835,8 @@"scheduled": "Scheduled task","watch": "Watch","webhook": "Webhook",+ "showAnnotation": "Page annotation",+ "showIntent": "Page action","harness": "From agent","from": "From","agentFallback": "agent"diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 17d543f78..662a1c4db 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -2835,6 +2835,8 @@"scheduled": "定时任务","watch": "Watch 监听","webhook": "Webhook",+ "showAnnotation": "页面批注",+ "showIntent": "页面操作","harness": "来自 Agent","from": "来自","agentFallback": "智能体"diff --git a/ui/src/lib/chatTrigger.test.ts b/ui/src/lib/chatTrigger.test.tsindex 7aed91616..ca913bc99 100644--- a/ui/src/lib/chatTrigger.test.ts+++ b/ui/src/lib/chatTrigger.test.ts@@ -66,6 +66,8 @@ describe('chatTriggerLink', () => {it('does not navigate for webhook or unknown harness kinds without a source', () => {expect(link({ author_name: 'webhook' })).toBeNull();+ expect(link({ author_name: 'show_annotation' })).toBeNull();+ expect(link({ author_name: 'show_intent' })).toBeNull();expect(link({ author_name: 'agent_run', source_session_id: null })).toBeNull();});@@ -115,4 +117,9 @@ describe('harnessChipLabelKey (leading-label key by source presence)', () => {expect(key({ author_name })).toBe('chat.source.scheduled');}});++ it('uses Show-specific labels for annotation and intent triggers', () => {+ expect(key({ author_name: 'show_annotation' })).toBe('chat.source.showAnnotation');+ expect(key({ author_name: 'show_intent' })).toBe('chat.source.showIntent');+ });});diff --git a/ui/src/lib/chatTrigger.ts b/ui/src/lib/chatTrigger.tsindex 95c80b8fa..124a8e863 100644--- a/ui/src/lib/chatTrigger.ts+++ b/ui/src/lib/chatTrigger.ts@@ -69,6 +69,7 @@ export function chatTriggerLink(message: TriggerFields, agentFallback: string):}const kind = message.author_name;+ if (kind === 'show_annotation' || kind === 'show_intent') return null;if (kind === 'watch' || TASK_KINDS.has(kind ?? '')) {const itemKind = kind === 'watch' ? 'watch' : 'task';return {@@ -90,6 +91,8 @@ export function chatTriggerLink(message: TriggerFields, agentFallback: string):export function harnessChipLabelKey(message: TriggerFields): string {if (message.source === 'harness' && message.source_session_id) return 'chat.source.from';const kind = message.author_name;+ if (kind === 'show_annotation') return 'chat.source.showAnnotation';+ if (kind === 'show_intent') return 'chat.source.showIntent';if (kind === 'watch') return 'chat.source.watch';if (kind === 'webhook') return 'chat.source.webhook';if (TASK_KINDS.has(kind ?? '')) return 'chat.source.scheduled';diff --git a/vibe/cli.py b/vibe/cli.pyindex 51df127b6..78befc04d 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -10709,16 +10709,9 @@ def _resolve_show_event_after_ambiguous_live_timeout(*,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,- )+ """Wait for acceptance, then let the caller replay the same reservation."""+ from core.show_session_events import ShowSessionEventStore+ from storage import messages_serviceevent_id = payload.get("id")if not isinstance(event_id, str) or not event_id:@@ -10727,25 +10720,17 @@ def _resolve_show_event_after_ambiguous_live_timeout(store = ShowSessionEventStore()try:while True:- status = store.get_dispatch_status(session_id, event_id)- if status is None:+ event = store.get_event(session_id, event_id)+ if event 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)+ message = event.get("message")+ if (+ isinstance(message, dict)+ and message.get("type") != messages_service.PENDING_TYPE+ ):+ return eventif time.monotonic() >= deadline:- raise localized_show_event_error("show_event_dispatch_pending")+ return Nonetime.sleep(0.05)finally:store.close()@@ -11185,6 +11170,7 @@ def cmd_show_event(args):from core.show_pages import ShowPageStorepage_store = ShowPageStore()+ event_id_for_retry = Nonetry:session_id, session_default_notice = _resolve_show_session_id(args, help_command="vibe show event --help")page = page_store.ensure(session_id)@@ -11199,6 +11185,7 @@ def cmd_show_event(args):if isinstance(event_id, str) and event_id.strip()else f"show_evt_{uuid4().hex[:16]}")+ event_id_for_retry = payload["id"]event = _post_show_event_to_live_ui(session_id, payload)if event is None:# The local bridge handles both shapes: non-dispatch events are@@ -11206,7 +11193,7 @@ def cmd_show_event(args):# 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)+ event = record_local_show_event(session_id, payload)result = _show_page_result(page,message="Show event recorded.",@@ -11228,6 +11215,11 @@ def cmd_show_event(args):print(f" Message: {event.get('message_id') or 'none'}")return 0except Exception as exc:+ if event_id_for_retry:+ details = getattr(exc, "details", None)+ retry_details = dict(details) if isinstance(details, dict) else {}+ retry_details["event_id"] = event_id_for_retry+ exc.details = retry_details_print_show_page_error(exc)return 1finally:diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 36b397fde..8a244362d 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -237,9 +237,10 @@ def _recover_stale_session_status(session_id: str) -> bool:def _recover_stale_pending_messages() -> dict[str, int]:"""Repair hidden ``pending`` send reservations left behind by UI interruption.- Recovery restores ordinary transcript visibility only; it never re-dispatches- the text. Show-owned reservations remain under Show's event-aware reconciler.- Rows whose session is missing or archived are deleted.+ Ordinary Chat rows are made visible without redispatching. Show rows remain+ pending because their type is also the durable acceptance signal: a replay must+ still submit an annotation that the controller never accepted. Rows whose+ session is missing or archived are deleted regardless of origin."""from core.services import sessions as workbench_sessions_service@@ -264,16 +265,22 @@ def _recover_stale_pending_messages() -> dict[str, int]:if messages_service.delete_pending(conn, str(row["id"])):summary["deleted"] += 1continue- promoted = messages_service.promote_pending(conn, str(row["id"]), "user")+ target_type = messages_service.pending_message_target_type(+ row.get("author"), row.get("source")+ )+ if target_type == messages_service.HARNESS_TYPE:+ summary["skipped"] += 1+ continue+ promoted = messages_service.promote_pending(conn, str(row["id"]), target_type)if not promoted:summary["skipped"] += 1continuesettled = _load_session_message(session_id, str(row["id"]))- if settled is None or settled.get("type") != "user":+ if settled is None or settled.get("type") != target_type:summary["skipped"] += 1continuesummary["promoted"] += 1- _publish_visible_user_message(+ _publish_visible_input_message(settled,session_id=session_id,scope_id=session.get("scope_id"),@@ -7605,14 +7612,14 @@ def asr_status():return jsonify({"available": False})-def _publish_visible_user_message(+def _publish_visible_input_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."""+ """Publish one already-visible input row through the shared fan-out."""from storage import messages_servicefrom vibe.sse_broker import broker@@ -7651,7 +7658,7 @@ def _promote_and_publish_pending_user_message(broker.publish("queue.updated", {"session_id": session_id, "scope_id": scope_id})return settledif promoted and settled.get("type") == "user":- return _publish_visible_user_message(+ return _publish_visible_input_message(settled,session_id=session_id,scope_id=scope_id,@@ -9237,27 +9244,25 @@ async 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]:+def record_local_show_event(+ session_id: str,+ payload: dict[str, Any],+) -> dict[str, Any]:store = _show_session_event_store()try: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):- try:- asyncio.get_running_loop()- except RuntimeError:- # 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)+ if show_event_requests_dispatch(event_payload):+ # The internal endpoint returns after the manager accepts or queues the+ # turn, so local CLI callers can settle the reservation synchronously+ # 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@@ -9280,34 +9285,10 @@ 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):- return- try:- loop = asyncio.get_running_loop()- except RuntimeError:- thread = threading.Thread(- target=lambda: asyncio.run(_run_show_event_dispatch(event_payload)),- name="show-event-dispatch",- daemon=True,- )- thread.start()- return- loop.create_task(_run_show_event_dispatch(event_payload))--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 storage import messages_servicefrom vibe import internal_clientsession_id = event_payload.get("session_id")@@ -9324,119 +9305,80 @@ async def _run_show_event_dispatch():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": [],- }+ message = event_payload.get("message")+ if not isinstance(message, dict):+ return _ShowEventDispatchOutcome.FAILED+ message_type = message.get("type")+ if message_type in {+ messages_service.HARNESS_TYPE,+ messages_service.QUEUED_TYPE,+ "user",+ }:+ return _ShowEventDispatchOutcome.ACCEPTED+ if message_type != messages_service.PENDING_TYPE:+ return _ShowEventDispatchOutcome.FAILED- 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)- )+ 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,+ "files": [],+ }- 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)+ try:+ result = await internal_client.dispatch_async(+ dispatch_payload,+ timeout=None,)+ # Only acceptance makes the reservation transcript-visible. A timed-out CLI+ # uses that transition as its retry/dedupe signal.+ except internal_client.InternalServerTimeout as exc:+ logger.warning(+ "show event dispatch still pending for session %s: %s",+ session_id,+ exc,+ )+ return _ShowEventDispatchOutcome.IN_FLIGHT+ except internal_client.InternalServerUnavailable as exc:+ logger.warning(+ "show event dispatch unavailable for session %s: %s",+ session_id,+ exc,+ )+ return _ShowEventDispatchOutcome.FAILED+ except Exception: # pragma: no cover - defensive+ logger.exception("show event dispatch acceptance is unknown")+ return _ShowEventDispatchOutcome.IN_FLIGHT+ 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,+ )+ return _ShowEventDispatchOutcome.FAILED+ settled = _settle_show_event_message(event_payload)+ if settled and settled.get("type") in {+ messages_service.HARNESS_TYPE,+ messages_service.QUEUED_TYPE,+ "user",+ }:+ return _ShowEventDispatchOutcome.ACCEPTED+ return _ShowEventDispatchOutcome.FAILED-def _reconcile_show_event_dispatch(++def _settle_show_event_message(event_payload: dict[str, Any],-) -> Any | None:+) -> dict[str, Any] | None:from core.show_session_events import ShowSessionEventStore+ from sqlalchemy import select+ from storage import messages_service+ from storage.models import messages, show_session_eventssession_id = event_payload.get("session_id")event_id = event_payload.get("id")@@ -9444,19 +9386,52 @@ def _reconcile_show_event_dispatch(return Noneif not isinstance(event_id, str) or not event_id:return None++ with _projects_engine().begin() as conn:+ row = conn.execute(+ select(+ messages.c.id,+ messages.c.author,+ messages.c.source,+ )+ .select_from(+ show_session_events.join(+ messages,+ messages.c.id == show_session_events.c.message_id,+ )+ )+ .where(+ show_session_events.c.id == event_id,+ show_session_events.c.session_id == session_id,+ )+ ).mappings().first()+ promoted = bool(+ row+ and messages_service.promote_pending(+ conn,+ str(row["id"]),+ messages_service.pending_message_target_type(+ row.get("author"),+ row.get("source"),+ ),+ )+ )+store = ShowSessionEventStore()try:- settlement = store.reconcile_dispatch_settlement(session_id, event_id)+ settled_event = store.get_event(session_id, event_id)finally:store.close()- if settlement is None or settlement.message is None:- return settlement+ if settled_event is None:+ return None+ message = settled_event.get("message")+ if not isinstance(message, dict):+ return None- message = settlement.messageevent_payload["message_id"] = message["id"]event_payload["message"] = message- if settlement.can_publish_message_new:- _publish_visible_user_message(+ if promoted and message.get("type") == messages_service.HARNESS_TYPE:+ _publish_visible_input_message(message,session_id=session_id,scope_id=(@@ -9466,7 +9441,7 @@ def _reconcile_show_event_dispatch(),activity_event="show_event",)- elif settlement.can_publish_queue_updated:+ elif message.get("type") == messages_service.QUEUED_TYPE:from vibe.sse_broker import brokerbroker.publish(@@ -9476,24 +9451,7 @@ def _reconcile_show_event_dispatch("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+ return messagedef _show_event_dispatch_error() -> ShowSessionEventError:@@ -10863,19 +10821,6 @@ 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 _recover_stale_pending_messages_on_startup() -> None:start = time.monotonic()try:@@ -10911,7 +10856,6 @@ 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", _recover_stale_pending_messages_on_startup)app.add_event_handler("startup", _start_startup_dependency_reconcile)app.add_event_handler("shutdown", _stop_startup_dependency_reconcile)