Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(show): type annotation transcript rows (#1052)

Call Whitecbb390c6f0a1
diff --git a/core/internal_server.py b/core/internal_server.py
index d37af113b..01cd3324a 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -43,6 +43,7 @@ from config import paths
from core.services.dispatch import SOURCE_HUMAN, SOURCE_SCHEDULED
from modules.im.base import MessageContext
from storage.db import get_cached_sqlite_engine
+from vibe.message_identity import HARNESS_TYPE, is_input_turn
from vibe.message_types import types_with
if TYPE_CHECKING: # pragma: no cover - typing only
@@ -374,6 +375,7 @@ def create_app(controller: "Controller") -> FastAPI:
target_type = messages_service.pending_message_target_type(
row.get("author"),
row.get("source"),
+ row.get("author_name"),
)
promoted = messages_service.promote_pending(
conn,
@@ -396,7 +398,11 @@ def create_app(controller: "Controller") -> FastAPI:
"scope_id": row.get("scope_id"),
"event": (
"show_event"
- if row.get("type") == messages_service.HARNESS_TYPE
+ if row.get("author") == HARNESS_TYPE
+ and is_input_turn(
+ row.get("author"),
+ row.get("type"),
+ )
else "user_message"
),
},
diff --git a/core/services/session_fork.py b/core/services/session_fork.py
index 24787cb8c..f92b860de 100644
--- a/core/services/session_fork.py
+++ b/core/services/session_fork.py
@@ -566,7 +566,7 @@ def _forked_session_title(source_title: str, lang: str = "en") -> str:
def _latest_source_message_anchor(conn: Any, source_session_id: str) -> SourceMessageAnchor:
- from sqlalchemy import func, or_, select
+ from sqlalchemy import select
from storage.models import messages
@@ -574,14 +574,11 @@ def _latest_source_message_anchor(conn: Any, source_session_id: str) -> SourceMe
select(messages.c.id, messages.c.author, messages.c.type)
.where(
messages.c.session_id == source_session_id,
- or_(
- # Include the invisible ``silent`` completion marker so a turn that
- # finished silently is the anchor (a terminal, NOT a running input),
- # otherwise the anchor falls back to the input row and the fork treats
- # the completed turn as still running and trims/rolls it back.
- messages.c.type.in_(_FORK_ANCHOR_TYPES),
- func.json_extract(messages.c.metadata_json, "$.source") == "show_page",
- ),
+ # Include the invisible ``silent`` completion marker so a turn that
+ # finished silently is the anchor (a terminal, NOT a running input),
+ # otherwise the anchor falls back to the input row and the fork treats
+ # the completed turn as still running and trims/rolls it back.
+ messages.c.type.in_(_FORK_ANCHOR_TYPES),
)
.order_by(messages.c.created_at.desc(), messages.c.id.desc())
.limit(1)
diff --git a/core/session_turns.py b/core/session_turns.py
index c2d8af242..f80ad3628 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -75,7 +75,7 @@ def _as_backend_activity_item(item: dict[str, Any]) -> dict[str, Any]:
# a plain human turn (#84). Its PRESENCE also marks the row as a scheduled segment
# (vs a user send) for flush_queue.
SCHEDULED_PROVENANCE_KEY = "scheduled_provenance"
-QUEUED_DISPATCH_TEXT_KEY = "_queued_dispatch_text"
+QUEUED_DISPATCH_TEXT_KEY = messages_service.QUEUED_DISPATCH_TEXT_KEY
SCHEDULED_QUEUE_MERGE_WINDOW_SECONDS = 60
SCHEDULED_QUEUE_BURST_HINT_THRESHOLD = 3
SCHEDULED_QUEUE_FULL_DETAIL_LIMIT = 3
@@ -614,8 +614,12 @@ def _promote_merged_user_segment(
visible_type = messages_service.pending_message_target_type(
canonical.get("author"),
canonical.get("source"),
+ canonical.get("author_name"),
)
- is_harness = visible_type == messages_service.HARNESS_TYPE
+ is_harness = messages_service.HARNESS_TYPE in {
+ canonical.get("author"),
+ canonical.get("source"),
+ }
native_message_ids = [
str(row.get("native_message_id") or "").strip()
for row in segment
@@ -624,6 +628,9 @@ def _promote_merged_user_segment(
if native_message_ids and len(segment) != 1:
raise ValueError("independently identified user rows must flush as separate segments")
merged_content: dict[str, Any] = {"text": text}
+ annotation = (canonical.get("content") or {}).get("annotation")
+ if isinstance(annotation, dict):
+ merged_content["annotation"] = annotation
if attachments:
merged_content["attachments"] = attachments
visible = messages_service.append(
@@ -1298,14 +1305,15 @@ class SessionTurnManager:
]
# Carry attachments queued in this user segment so a file
# attached while the agent was busy still reaches the merged
- # turn. An attachment-ONLY segment has empty texts but must
- # still run (the agent reads the files), so guard on both.
+ # turn. An attachment-only input or annotation with an empty
+ # display body still has work to dispatch, so the guard uses
+ # agent-facing text rather than transcript text.
queued_attachments = [
att
for r in segment
for att in ((r.get("content") or {}).get("attachments") or [])
]
- if not texts and not queued_attachments:
+ if not dispatch_texts and not queued_attachments:
messages_service.delete_queued(conn, [r["id"] for r in segment])
return False
user_owners = list(
diff --git a/core/show_git.py b/core/show_git.py
index 374d4913e..b3b9c50bb 100644
--- a/core/show_git.py
+++ b/core/show_git.py
@@ -36,6 +36,20 @@ _SESSION_ID_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$")
_MAIN_ANCHOR_REF = "refs/avibe/checkpoint-main"
_TURN_STATE_KEY = "_avibe_show_git_checkpoint"
_CHECKPOINT_STATUS_VERSION = 1
+TURN_CHECKPOINT_INPUT_AUTHOR_TYPES = (
+ *input_author_type_pairs(),
+ ("user", "pending"),
+ ("harness", "pending"),
+)
+TURN_CHECKPOINT_INPUT_TYPES = tuple(
+ dict.fromkeys(
+ message_type
+ for _author, message_type in TURN_CHECKPOINT_INPUT_AUTHOR_TYPES
+ )
+)
+_TURN_CHECKPOINT_INPUT_AUTHOR_TYPE_SET = frozenset(
+ TURN_CHECKPOINT_INPUT_AUTHOR_TYPES
+)
_checkpoint_service_active: bool | None = None
_SCRUBBED_GIT_ENV = {
"GIT_DIR",
@@ -248,7 +262,7 @@ def load_turn_checkpoint_context(session_id: str, *, after: str | None = None) -
"""Read the driving message/run without changing the turn event payload."""
try:
- from sqlalchemy import select
+ from sqlalchemy import select, tuple_
from storage.db import get_cached_sqlite_engine
from storage.models import agent_runs, messages
@@ -269,6 +283,7 @@ def load_turn_checkpoint_context(session_id: str, *, after: str | None = None) -
message_query = select(
messages.c.id,
+ messages.c.author,
messages.c.type,
messages.c.content_text,
messages.c.content_json,
@@ -283,17 +298,20 @@ def load_turn_checkpoint_context(session_id: str, *, after: str | None = None) -
else:
message_query = (
message_query.where(
- messages.c.type.in_((*_INPUT_TURN_MESSAGE_TYPES, "pending"))
+ tuple_(messages.c.author, messages.c.type).in_(
+ TURN_CHECKPOINT_INPUT_AUTHOR_TYPES
+ )
)
.where(messages.c.created_at >= after)
.order_by(messages.c.created_at.asc(), messages.c.id.asc())
.limit(1)
)
message_row = conn.execute(message_query).first()
- if message_row is None or message_row.type not in {
- *_INPUT_TURN_MESSAGE_TYPES,
- "pending",
- }:
+ if (
+ message_row is None
+ or (message_row.author, message_row.type)
+ not in _TURN_CHECKPOINT_INPUT_AUTHOR_TYPE_SET
+ ):
return TurnCheckpointContext()
return TurnCheckpointContext(
message=_read_message_text(message_row.content_text, message_row.content_json),
diff --git a/core/show_session_events.py b/core/show_session_events.py
index 9c0a4b234..26eb3c989 100644
--- a/core/show_session_events.py
+++ b/core/show_session_events.py
@@ -67,15 +67,6 @@ 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
-# mark event fails a test instead of leaking a raw i18n key into a conversation.
-ASSISTANT_MARK_TRANSCRIPT_I18N_KEYS = {
- "assistant.mark.created": "show.mark.created",
- "assistant.mark.updated": "show.mark.updated",
- "assistant.mark.resolved": "show.mark.resolved",
-}
# The *only* fields the user-facing locator may come from, best first. Both hold
# copy the user can see on the page: ``vibe show mark --anchor-text`` writes
# ``text``, while ``vibe show reply`` copies the annotation's anchor verbatim and
@@ -158,9 +149,6 @@ class ShowSessionEventStore:
event_id = _event_id(payload, {})
request_fingerprint = _event_request_fingerprint(event_type, payload)
created_at = _utc_now_iso()
- # Resolved once per append, outside the transaction: transcript text is
- # rendered for the user at write time, so it needs their display language.
- lang = _configured_language()
with ExitStack() as cleanup:
with self.engine.begin() as conn:
@@ -212,7 +200,13 @@ class ShowSessionEventStore:
transcript_text = (
""
if event_type == "assistant.mark.resolved" and author is not None
- else _format_transcript_text(event_type, event_payload, anchor, lang=lang)
+ else _format_transcript_text(event_type, event_payload, anchor)
+ )
+ dispatch_text = _format_dispatch_text(
+ event_type,
+ event_payload,
+ anchor,
+ event_id=event_id,
)
if records_author:
event_payload["author"] = _normalize_human_author(author)
@@ -267,8 +261,33 @@ class ShowSessionEventStore:
return existing
message: dict[str, Any] | None = None
message_id: str | None = None
- if transcript_text:
+ writes_annotation = (
+ event_type == "human.annotation.created"
+ or (
+ event_type in ASSISTANT_MARK_EVENT_TYPES
+ and not (event_type == "assistant.mark.resolved" and author is not None)
+ )
+ )
+ if writes_annotation or (
+ transcript_text and event_type not in ANNOTATION_EVENT_TYPES
+ ):
harness_input = requests_dispatch
+ content: dict[str, Any] = {"text": transcript_text}
+ metadata: dict[str, Any] = {
+ "source": "show_page",
+ "show_event_id": event_id,
+ "show_event_type": event_type,
+ "show_event_scope": scope,
+ **({"author": event_payload["author"]} if "author" in event_payload else {}),
+ }
+ if writes_annotation:
+ content["annotation"] = _annotation_display(event_type, anchor)
+ attachments = _annotation_attachments(event_payload)
+ if attachments:
+ content["attachments"] = attachments
+ metadata.update(_annotation_metadata(event_payload, anchor))
+ if requests_dispatch:
+ metadata[messages_service.QUEUED_DISPATCH_TEXT_KEY] = dispatch_text
message = messages_service.append(
conn,
scope_id=session["scope_id"],
@@ -284,19 +303,15 @@ class ShowSessionEventStore:
message_type=(
messages_service.PENDING_TYPE
if requests_dispatch and reserve_dispatch
+ else messages_service.ANNOTATION_TYPE
+ if writes_annotation
else messages_service.HARNESS_TYPE
if harness_input
else None
),
text=transcript_text,
- content={"text": transcript_text, "show_event_type": event_type},
- metadata={
- "source": "show_page",
- "show_event_id": event_id,
- "show_event_type": event_type,
- "show_event_scope": scope,
- **({"author": event_payload["author"]} if "author" in event_payload else {}),
- },
+ content=content,
+ metadata=metadata,
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,
@@ -555,7 +570,7 @@ def _normalize_event_payload(event_type: str, payload: dict[str, Any]) -> dict[s
if event_type.startswith("assistant.mark."):
mark = _normalize_json_object(payload.get("mark") or payload.get("payload"))
target = _required_text(mark.get("target"), "mark.target")
- body = _required_text(mark.get("body") or mark.get("comment"), "mark.body")
+ body = str(mark.get("body") or mark.get("comment") or "").strip()
created_at = _text_or_none(mark.get("createdAt")) or _utc_now_iso()
normalized = {
"id": _text_or_none(mark.get("id")) or _new_id("mark"),
@@ -864,61 +879,194 @@ def _mark_locator(anchor: dict[str, Any]) -> str | None:
return None
-def _configured_language() -> str:
- """Display language for user-visible transcript text.
+def _annotation_display(
+ event_type: str,
+ anchor: dict[str, Any],
+) -> dict[str, str]:
+ display = {
+ "direction": "user" if event_type in ANNOTATION_EVENT_TYPES else "agent",
+ "action": event_type.rsplit(".", 1)[-1],
+ }
+ quote = _mark_locator(anchor)
+ if quote:
+ display["quote"] = quote
+ return display
+
+
+def _annotation_attachments(payload: dict[str, Any]) -> list[dict[str, Any]]:
+ screenshot = _normalize_json_object(payload.get("screenshot"))
+ attachment_id = _text_or_none(screenshot.get("attachmentId"))
+ path = _text_or_none(screenshot.get("path"))
+ mime = _text_or_none(screenshot.get("mimeType"))
+ width = screenshot.get("width")
+ height = screenshot.get("height")
+ if not attachment_id or not path or not mime or width is None or height is None:
+ return []
+ suffix = "webp" if mime.lower() == "image/webp" else "png"
+ return [
+ {
+ "url": f"/api/media/{attachment_id}",
+ "name": f"annotation-region.{suffix}",
+ "mime": mime,
+ "kind": "image",
+ "width": width,
+ "height": height,
+ }
+ ]
- The store has no controller to read config off, so it loads the persisted
- config directly; a headless run with no config file (tests, a fresh CLI) falls
- back to English, the documented default.
- """
- from config.v2_config import V2Config
- try:
- return str(getattr(V2Config.load(), "language", "en") or "en")
- except (OSError, ValueError):
- return "en"
+def _annotation_metadata(
+ payload: dict[str, Any],
+ anchor: dict[str, Any],
+) -> dict[str, Any]:
+ metadata: dict[str, Any] = {}
+ anchor_kind = _normalize_annotation_primary_anchor(payload.get("primaryAnchor"))
+ if anchor_kind:
+ metadata["anchor_kind"] = anchor_kind
+ selector = _text_or_none(anchor.get("selector"))
+ if selector:
+ metadata["anchor_selector"] = selector
+ user_region = _format_rect(payload.get("userRegion") or payload.get("region"))
+ if user_region:
+ metadata["user_region"] = user_region
+ screenshot = _normalize_json_object(payload.get("screenshot"))
+ screenshot_region = _format_rect(
+ screenshot.get("capturedRegion") or screenshot.get("region") or screenshot.get("rect")
+ )
+ if screenshot_region:
+ metadata["screenshot_region"] = screenshot_region
+ classification = _format_classification(payload.get("classification"))
+ if classification:
+ metadata["classification"] = classification
+ matched_elements = _json_object_list(payload.get("matchedElements"))
+ anchors = _json_object_list(payload.get("anchors"))
+ matched_count = len(matched_elements) or (
+ len(anchors) if anchor_kind == "element-group" else 0
+ )
+ if matched_count:
+ metadata["matched_element_count"] = matched_count
+ return metadata
-def _format_assistant_mark_text(
+def _format_annotation_prompt_text(
+ event_type: str,
+ payload: dict[str, Any],
+ anchor: dict[str, Any],
+) -> str:
+ action = event_type.split(".")[-1]
+ text = _text_or_none(payload.get("text") or payload.get("comment"))
+ label = _text_or_none(payload.get("intent")) or "comment"
+ header = _format_transcript_header(
+ "show-annotation",
+ scope=payload.get("scope"),
+ action=action,
+ default_action="created",
+ )
+ lines = [f"{header} {label}"]
+ if text:
+ lines.extend(["", text])
+ primary_anchor = _normalize_annotation_primary_anchor(payload.get("primaryAnchor"))
+ if primary_anchor:
+ lines.extend(["", f"Anchor kind: {primary_anchor}"])
+ screenshot = _normalize_json_object(payload.get("screenshot"))
+ if screenshot:
+ screenshot_ref = _text_or_none(
+ screenshot.get("path")
+ or screenshot.get("attachmentId")
+ or screenshot.get("assetId")
+ or screenshot.get("id")
+ or screenshot.get("url")
+ or screenshot.get("src")
+ )
+ screenshot_dimensions = _format_dimensions(
+ screenshot.get("width"),
+ screenshot.get("height"),
+ )
+ dimensions_suffix = f" ({screenshot_dimensions})" if screenshot_dimensions else ""
+ lines.append(
+ f"Screenshot: {screenshot_ref or 'captured region'}{dimensions_suffix}"
+ )
+ screenshot_region = _format_rect(
+ screenshot.get("capturedRegion")
+ or screenshot.get("region")
+ or screenshot.get("rect")
+ )
+ if screenshot_region:
+ lines.append(f"Screenshot region: {screenshot_region}")
+ screenshot_items = _json_object_list(screenshot.get("items"))
+ if screenshot_items:
+ lines.append("Screenshot comments:")
+ for index, item in enumerate(screenshot_items, start=1):
+ item_label = _text_or_none(item.get("label")) or str(index)
+ item_text = _text_or_none(
+ item.get("comment") or item.get("text") or item.get("body")
+ )
+ line = f"{item_label}. {item_text or 'comment'}"
+ item_region = _format_rect(item.get("region") or item.get("rect"))
+ item_point = _format_point(item.get("point"))
+ if item_region:
+ line += f" ({item_region})"
+ elif item_point:
+ line += f" ({item_point})"
+ lines.append(line)
+ region = _format_rect(payload.get("userRegion") or payload.get("region"))
+ if region:
+ lines.append(f"Region: {region}")
+ classification = _format_classification(payload.get("classification"))
+ if classification:
+ lines.append(f"Selection: {classification}")
+ matched_elements = _json_object_list(payload.get("matchedElements"))
+ anchor_list = _json_object_list(payload.get("anchors"))
+ matched_count = len(matched_elements) or (
+ len(anchor_list) if primary_anchor == "element-group" else 0
+ )
+ if matched_count:
+ lines.append(f"Matched elements: {matched_count}")
+ quote = _text_or_none(anchor.get("textQuote") or anchor.get("text"))
+ if quote:
+ lines.extend(["", f"Quote: {quote}"])
+ selector = _text_or_none(anchor.get("selector"))
+ if selector:
+ lines.append(f"Anchor: {selector}")
+ return "\n".join(lines)
+
+
+def _format_dispatch_text(
event_type: str,
payload: dict[str, Any],
anchor: dict[str, Any],
*,
- lang: str,
+ event_id: str,
) -> str:
- """Render an assistant mark as the chat message a user reads.
-
- The agent's own words are the message; the header is a short line saying what
- happened and, when it can be said in plain words, where.
-
- The header is assembled from exactly two sources, and that is the invariant:
- a closed label map keyed by event type, and anchor copy the user can see on
- the page. No free-form field of the mark reaches the user -- not ``target``
- (see :data:`ANCHOR_HUMAN_COPY_KEYS`), and not ``scope``, which namespaces the
- synthetic mark id in :func:`stable_assistant_mark_id`, never appears anywhere
- on the page, and so names nothing the reader could go and look at. ``body``,
- the agent's own ``--message``, is the one payload field that is human words by
- construction, and it is the message rather than the header.
- """
- header = i18n_t(ASSISTANT_MARK_TRANSCRIPT_I18N_KEYS[event_type], lang)
- locator = _mark_locator(anchor)
- if locator:
- header = i18n_t("show.mark.quoteSuffix", lang, header=header, quote=locator)
- body = str(payload.get("body") or "").strip()
- return f"{header}\n\n{body}" if body else header
+ if event_type not in ANNOTATION_EVENT_TYPES:
+ return _format_transcript_text(event_type, payload, anchor)
+
+ prompt = _format_annotation_prompt_text(event_type, payload, anchor)
+ if event_type != "human.annotation.created":
+ return prompt
+ lines = [prompt, "", f"Show event id: {event_id}"]
+ intent = _text_or_none(payload.get("intent")) or "comment"
+ if intent in {"question", "comment"}:
+ lines.extend(
+ [
+ "",
+ "如需在页面上原位回应,可执行:",
+ f" vibe show reply {event_id} --message '<你的回答>'",
+ "(也可以直接修改页面内容来响应,按场景选择。)",
+ ]
+ )
+ return "\n".join(lines)
def _format_transcript_text(
event_type: str,
payload: dict[str, Any],
anchor: dict[str, Any],
- *,
- lang: str = "en",
) -> str:
if event_type == "system.annotation.control":
return ""
- if event_type in ASSISTANT_MARK_TRANSCRIPT_I18N_KEYS:
- return _format_assistant_mark_text(event_type, payload, anchor, lang=lang)
+ if event_type in ASSISTANT_MARK_EVENT_TYPES:
+ return str(payload.get("body") or "").strip()
if event_type == "human.intent.submitted":
text = _text_or_none(payload.get("text") or payload.get("comment") or payload.get("value"))
@@ -927,71 +1075,7 @@ def _format_transcript_text(
return f"{header} {label}\n\n{text or _json_dumps(payload)}"
if event_type in ANNOTATION_EVENT_TYPES:
- action = event_type.split(".")[-1]
- text = _text_or_none(payload.get("text") or payload.get("comment"))
- label = _text_or_none(payload.get("intent")) or "comment"
- header = _format_transcript_header(
- "show-annotation",
- scope=payload.get("scope"),
- action=action,
- default_action="created",
- )
- lines = [f"{header} {label}"]
- if text:
- lines.extend(["", text])
- primary_anchor = _normalize_annotation_primary_anchor(payload.get("primaryAnchor"))
- if primary_anchor:
- lines.extend(["", f"Anchor kind: {primary_anchor}"])
- screenshot = _normalize_json_object(payload.get("screenshot"))
- if screenshot:
- screenshot_ref = _text_or_none(
- screenshot.get("path")
- or screenshot.get("attachmentId")
- or screenshot.get("assetId")
- or screenshot.get("id")
- or screenshot.get("url")
- or screenshot.get("src")
- )
- screenshot_dimensions = _format_dimensions(screenshot.get("width"), screenshot.get("height"))
- dimensions_suffix = f" ({screenshot_dimensions})" if screenshot_dimensions else ""
- lines.append(f"Screenshot: {screenshot_ref or 'captured region'}{dimensions_suffix}")
- screenshot_region = _format_rect(
- screenshot.get("capturedRegion") or screenshot.get("region") or screenshot.get("rect")
- )
- if screenshot_region:
- lines.append(f"Screenshot region: {screenshot_region}")
- screenshot_items = _json_object_list(screenshot.get("items"))
- if screenshot_items:
- lines.append("Screenshot comments:")
- for index, item in enumerate(screenshot_items, start=1):
- item_label = _text_or_none(item.get("label")) or str(index)
- item_text = _text_or_none(item.get("comment") or item.get("text") or item.get("body"))
- line = f"{item_label}. {item_text or 'comment'}"
- item_region = _format_rect(item.get("region") or item.get("rect"))
- item_point = _format_point(item.get("point"))
- if item_region:
- line += f" ({item_region})"
- elif item_point:
- line += f" ({item_point})"
- lines.append(line)
- region = _format_rect(payload.get("userRegion") or payload.get("region"))
- if region:
- lines.append(f"Region: {region}")
- classification = _format_classification(payload.get("classification"))
- if classification:
- lines.append(f"Selection: {classification}")
- matched_elements = _json_object_list(payload.get("matchedElements"))
- anchor_list = _json_object_list(payload.get("anchors"))
- matched_count = len(matched_elements) or (len(anchor_list) if primary_anchor == "element-group" else 0)
- if matched_count:
- lines.append(f"Matched elements: {matched_count}")
- quote = _text_or_none(anchor.get("textQuote") or anchor.get("text"))
- if quote:
- lines.extend(["", f"Quote: {quote}"])
- selector = _text_or_none(anchor.get("selector"))
- if selector:
- lines.append(f"Anchor: {selector}")
- return "\n".join(lines)
+ return str(payload.get("text") or payload.get("comment") or "").strip()
if event_type == "assistant.page.updated":
summary = _text_or_none(payload.get("summary") or payload.get("text") or payload.get("body"))
diff --git a/docs/plans/show-annotation-message-type.md b/docs/plans/show-annotation-message-type.md
new file mode 100644
index 000000000..329e54ccd
--- /dev/null
+++ b/docs/plans/show-annotation-message-type.md
@@ -0,0 +1,256 @@
+# Show Page annotations: one message type, visibility by type alone
+
+Frozen interface artifacts live in
+`docs/plans/show-annotation-message-type/contract.ts` and
+`docs/plans/show-annotation-message-type/examples.json`.
+
+## Reported defects
+
+1. Annotating a Show Page while the agent is busy shows the annotation twice:
+ once in the queue strip and once as an already-delivered chat bubble.
+2. An agent reverse mark arrives as an ordinary agent message with its label
+ embedded in the body.
+3. A reverse mark written while Chat is open does not stream live and appears
+ only after a history refetch.
+
+## Root cause
+
+Reverse marks had no transcript message type. `ShowSessionEventStore.append`
+wrote them as `author="agent"`, which became `type="assistant"`.
+`assistant` is intentionally absent from the transcript type set.
+
+History compensated with a metadata back door:
+`list_session_messages(..., include_metadata_sources=("show_page",))` retained
+every row whose `metadata.source` was `show_page`, regardless of type. Forward
+reservations carry that metadata while they are `pending` and `queued`, so the
+history fetch exposed an undelivered queue row as a chat message.
+
+The live message publisher had no equivalent override, which made live and
+refetched visibility disagree. Activity grouping and session-fork anchoring
+also grew `metadata.source == "show_page"` exceptions. All are consequences of
+the missing type.
+
+## Invariants
+
+| Question | Decide with | Never with |
+| --- | --- | --- |
+| Does the row appear in Chat? | `type` alone | `author`, `source`, `author_name`, or `metadata` |
+| Does the row drive or checkpoint a turn? | the catalog's `(author, type)` input pairs | `author_name`, metadata, or type alone |
+| Does the row group as activity? | catalog `activityRole` | Show-specific metadata |
+| Which side and title does the card draw? | `content.annotation.direction` | `author` or `source` |
+| Does it preview, settle, notify, or become unread? | the corresponding catalog property | the assumption that visible means terminal |
+
+An annotation is an input turn only for `(harness, annotation)`. It is never an
+activity-grouping event. These are independent axes.
+
+## Contract A: one annotation type
+
+The only new message type is `annotation`. `status` is not introduced. The
+catalog entry is:
+
+```json
+"annotation": {
+ "transcript": true,
+ "searchable": true,
+ "inputAuthors": ["harness"],
+ "acceptedReservation": true,
+ "render": "annotation"
+}
+```
+
+The inherited defaults are deliberate:
+
+- `inboxPreview: false`
+- `inboxSettlesReply: false`
+- `activityRole: "none"`
+- `terminalWhenEvents: []`
+- `unread: false`
+- `webPush: false`
+- `inboxActivity: true`
+
+`acceptedReservation: true` makes a settled Show replay idempotent.
+
+### Row identities
+
+| Flow | `author` | `source` | `author_name` | Written type |
+| --- | --- | --- | --- | --- |
+| dispatching forward annotation | `harness` | `harness` | `show_annotation` | `pending` -> `queued` -> `annotation` |
+| non-dispatching new forward annotation | `user` | null | null | `annotation` |
+| reverse mark | `agent` | null | null | `annotation` |
+| Show intent | `harness` | `harness` | `show_intent` | existing `harness` flow |
+
+`pending_message_target_type(author, source, author_name)` returns
+`annotation` only for the exact harness Show-annotation identity. Every caller
+supplies all three fields.
+
+### Lifecycle write rule
+
+A chat row is written only when someone wrote words that were not already
+delivered:
+
+| Event | Chat row | Reason |
+| --- | --- | --- |
+| `human.annotation.created` | yes | new user-authored words |
+| `human.annotation.updated` | no | lifecycle update to the existing page annotation |
+| `human.annotation.resolved` | no | lifecycle update to the existing page annotation |
+| `human.annotation.dismissed` | no | lifecycle update to the existing page annotation |
+| `assistant.mark.created` | yes | new agent-authored body |
+| `assistant.mark.updated` | yes | new agent-authored body |
+| `assistant.mark.resolved` | yes | new agent-authored body |
+
+A user resolving an existing agent mark does not create another agent-authored
+row.
+
+`assistant.page.updated` and `system.runtime.error` continue to resolve to
+`type="assistant"`. Removing the history back door intentionally hides them.
+They do not receive a replacement type or a data migration.
+
+## Contract B: display text and dispatch text
+
+One text field cannot serve both a human transcript and an agent prompt.
+`ShowSessionEventStore.append` therefore produces:
+
+- `transcript_text`: authored human words only. Forward annotations use the
+ user's comment; reverse marks use the agent's body. It may be empty.
+- `dispatch_text`: the full agent-facing prompt, including the existing
+ annotation family tag, anchor details, selector, screenshot path and region,
+ event id, and reply command guidance.
+
+The row layout is:
+
+| Field | Content |
+| --- | --- |
+| `content_text` / `content.text` | `transcript_text` |
+| `content.annotation` | frozen display record |
+| `content.attachments` | materialized screenshot in upload attachment shape |
+| `metadata._queued_dispatch_text` | `dispatch_text` from reservation time |
+| remaining `metadata` | machine facts only |
+
+`_queued_dispatch_text` is stored under the shared
+`QUEUED_DISPATCH_TEXT_KEY` before dispatch. Immediate dispatch, queued flush,
+and retry dispatch all read the stored value. Promotion to the delivered row
+strips the private queue metadata.
+
+Pre-upgrade reservations can reconstruct their former prompt from the stored
+Show event. A current annotation with a display record never falls back to its
+human-only transcript body.
+
+## Contract C: reservation recovery
+
+A stale `pending` reservation proves only that the row was persisted. It does
+not prove that an agent turn started.
+
+Startup recovery therefore:
+
+1. deletes pending rows whose session is missing or archived;
+2. makes ordinary user-authored Chat rows visible without redispatching;
+3. leaves harness-owned reservations `pending` with
+ `_queued_dispatch_text` intact;
+4. publishes neither `queue.updated` nor `message.new` for the unrun turn.
+
+Replaying the originating Show event reuses the same reservation and initiates
+the real dispatch. Only controller acceptance promotes it to its final catalog
+type. Recovery never creates an ownerless `queued` row and never fabricates a
+delivered transcript receipt.
+
+## Contract D: frontend consumption
+
+The frontend consumes the frozen row shape in `contract.ts` and
+`examples.json`. It admits transcript rows by catalog type and chooses the
+annotation card's side and title from `content.annotation.direction`.
+Because `annotation` is shared by harness, user, and agent authors, search
+results classify the row from the `(author, type)` pair rather than from
+`author` alone. Within `annotation`, `author='agent'` is an agent reverse
+mark and every other author — including `harness`, which carries the user's
+own submitted annotation — is the user. The type's `inputAuthors=["harness"]`
+capability identifies the harness input pair only, and is never a
+display-role shortcut.
+
+The backend and frontend implementations keep separate file ownership, then
+land together so no release contains the new type without its consumer.
+
+## Migration
+
+Revision `20260727_0038` performs two pinned changes.
+
+### Inbox input index
+
+SQLite cannot alter a partial index. The migration drops and recreates
+`ix_messages_inbox_user_send` with the literal predicate:
+
+```sql
+session_id is not null and (
+ (author = 'user' and type = 'user')
+ or (author = 'harness' and type = 'harness')
+ or (author = 'harness' and type = 'annotation')
+)
+```
+
+The migration does not call the live catalog. A drift test compares the pinned
+literal with today's `build_partial_index_predicate` output.
+
+The other predicates do not change. `ix_messages_inbox_activity` includes
+`annotation` automatically through its exclusion model, and
+`ix_messages_inbox_agent_reply` remains limited to `result`, `notify`, and
+`error`.
+
+### Legacy Show rows
+
+Revision `20260727_0038` performs no data migration. Rows written before it
+keep their original types and are not rendered as annotations. They are out of
+scope by owner decision: the feature never shipped, so no installation holds
+annotation history outside a developer machine.
+
+The downgrade likewise changes only the inbox input index and leaves every
+message row untouched.
+
+## Deleted back doors
+
+- Remove `include_metadata_sources` from `list_session_messages` and all
+ production calls.
+- Remove metadata-source exceptions from activity grouping and session-fork
+ anchoring.
+- Remove the obsolete `show.mark.*` backend translations.
+- Derive message-type behavior from `vibe/message_types.json`; do not add
+ hand-maintained vocabulary mirrors.
+
+## Acceptance criteria
+
+1. **Visibility is decided by type alone.** History and live streaming admit a
+ row exactly when its catalog type is transcript-visible.
+2. **One annotation is in one place.** While busy it is only queued; after
+ drain it is only in the transcript.
+3. **Chat bodies contain authored words only.** Selectors, event ids, file
+ paths, pixel rectangles, tags, and CLI hints remain machine-only.
+4. **The prompt is not degraded.** Immediate, queued, and retried dispatch
+ replay the stored full prompt.
+6. **Reservations converge honestly.** Startup leaves a stranded Show
+ reservation pending and retryable until a real dispatch is accepted; it
+ never creates an ownerless queue row or a receipt for an unrun turn.
+7. **Live equals refetch.** A reverse mark publishes live and a refetch returns
+ the same single row.
+
+## Evidence
+
+- **Unit:** catalog policy; target type by `(author, source, author_name)`;
+ pure transcript/dispatch builders against frozen examples.
+- **Contract:** production-argument transcript fetch; busy-session queue
+ exclusivity; all dispatch paths; recovery with prompt preservation; live
+ reverse-mark publication.
+- **Migration:** upgrade and downgrade a copied database; every supported
+ reverse-mark event and historical forward annotation converts, while
+ post-upgrade rows downgrade by author; the pinned index predicate matches the
+ catalog.
+- **Static invariant:** no backend query, filter, or branch uses Show metadata
+ to widen or narrow transcript visibility.
+- **Manual integration:** deferred to the combined backend/frontend regression
+ pass.
+
+## Non-goals
+
+- Deep-linking a card back to a Show Page anchor.
+- Rendering `human.intent.submitted` as an annotation.
+- Renaming `mark`, `unmark`, or Show Page URL parameters.
+- Changing the `show_session_events` schema.
+- Adding a `status` message type.
+- Modifying frontend source in this lane.
diff --git a/docs/plans/show-annotation-message-type/contract.ts b/docs/plans/show-annotation-message-type/contract.ts
new file mode 100644
index 000000000..529d02b37
--- /dev/null
+++ b/docs/plans/show-annotation-message-type/contract.ts
@@ -0,0 +1,78 @@
+/**
+ * FROZEN CONTRACT — Show Page annotation chat row.
+ *
+ * Both lanes build against this file, not against prose. Lane BE produces rows
+ * that satisfy it; Lane UI consumes rows that satisfy it. A deviation goes
+ * through the orchestrator, never lane-to-lane.
+ *
+ * Spec: docs/plans/show-annotation-message-type.md
+ * Examples: docs/plans/show-annotation-message-type/examples.json
+ */
+
+/** Who authored the annotation. Selects the card title, nothing else. */
+export type ShowAnnotationDirection = 'user' | 'agent'
+
+/**
+ * What happened to the annotation. `resolved` is the only value that renders a
+ * visible state element; the others render nothing beyond the body itself.
+ */
+export type ShowAnnotationAction = 'created' | 'updated' | 'resolved' | 'dismissed'
+
+/**
+ * `content.annotation` — the display record. Every field here is rendered.
+ * Anything the card does not draw belongs in `metadata`, not here.
+ */
+export interface ShowAnnotationDisplay {
+ direction: ShowAnnotationDirection
+ action: ShowAnnotationAction
+ /**
+ * Copy the reader can find on the page, condensed to at most 60 characters
+ * with a trailing ellipsis. Absent when the anchor carries no human-readable
+ * copy — a locator the user cannot read is noise, not a locator.
+ */
+ quote?: string
+}
+
+/**
+ * The chat row. Field names and nesting are exactly what
+ * `GET /api/sessions/<id>/messages` returns (see `WorkbenchMessage` in
+ * `ui/src/context/ApiContext.tsx`); only the annotation-relevant fields are
+ * narrowed here.
+ */
+export interface ShowAnnotationMessageRow {
+ id: string
+ /** The single gate on transcript visibility. */
+ type: 'annotation'
+ /** `harness` when the row is turn input, `user` for a non-dispatching human
+ * annotation event, `agent` for a reverse mark. Never consulted for
+ * visibility, and never consulted to pick the card. */
+ author: 'harness' | 'user' | 'agent'
+ source: 'harness' | null
+ author_name: 'show_annotation' | null
+ /** Human words only: the user's comment, or the agent's `--message`. May be
+ * empty, in which case the card renders title + quote + attachments alone. */
+ text: string
+ content: {
+ /** Mirrors `text`. */
+ text: string
+ annotation: ShowAnnotationDisplay
+ /** The materialized screenshot, in the same record shape a Web chat upload
+ * writes, so the existing attachment renderer shows a thumbnail. Absent
+ * when the annotation carried no screenshot. */
+ attachments?: Array<Record<string, unknown>>
+ }
+ /**
+ * Machine facts. None of these are rendered in chat. `_queued_dispatch_text`
+ * is present from the moment the row is reserved and holds the agent-facing
+ * prompt; it is stripped when the row flushes.
+ */
+ metadata: {
+ source: 'show_page'
+ show_event_id: string
+ show_event_type: string
+ show_event_scope: string
+ _queued_dispatch_text?: string
+ [key: string]: unknown
+ }
+ created_at: string
+}
diff --git a/docs/plans/show-annotation-message-type/examples.json b/docs/plans/show-annotation-message-type/examples.json
new file mode 100644
index 000000000..165a43ffc
--- /dev/null
+++ b/docs/plans/show-annotation-message-type/examples.json
@@ -0,0 +1,149 @@
+{
+ "_contract": "docs/plans/show-annotation-message-type/contract.ts",
+ "_spec": "docs/plans/show-annotation-message-type.md",
+ "_frozen_fields": [
+ "type",
+ "author",
+ "content.text",
+ "content.annotation",
+ "content.attachments",
+ "metadata._queued_dispatch_text"
+ ],
+ "_notes": [
+ "These are representative rows from `GET /api/sessions/<id>/messages`. `_frozen_fields` is the machine-readable cross-lane boundary; all other values are production-shaped illustrations.",
+ "`content.annotation` is frozen: exactly `direction`, `action`, and optional `quote`. Adding a field means the card draws something new, which needs a design change first.",
+ "`metadata` keys beyond `source`, `show_event_id`, `show_event_type`, `show_event_scope`, and `_queued_dispatch_text` are Lane BE's choice — nothing in the UI reads them. `_queued_dispatch_text` presence is frozen; its machine-only body and the other metadata values are illustrative.",
+ "`content.attachments[].url` must be `/api/media/<attachment_id>` so `isProxyMediaUrl` passes and the image renders inline instead of degrading to a click-through card."
+ ],
+ "examples": [
+ {
+ "_name": "forward / user annotation, comment only, dispatched immediately",
+ "row": {
+ "id": "msg_01J8XK2Q4W",
+ "type": "annotation",
+ "author": "harness",
+ "source": "harness",
+ "author_name": "show_annotation",
+ "author_id": "evt_7f3a91c2",
+ "native_message_id": "show:evt_7f3a91c2",
+ "text": "这里的标题太小了,正文和它几乎一样重",
+ "content": {
+ "text": "这里的标题太小了,正文和它几乎一样重",
+ "annotation": {
+ "direction": "user",
+ "action": "created",
+ "quote": "Model Hub"
+ }
+ },
+ "metadata": {
+ "source": "show_page",
+ "show_event_id": "evt_7f3a91c2",
+ "show_event_type": "human.annotation.created",
+ "show_event_scope": "default",
+ "anchor_kind": "element",
+ "anchor_selector": "main > section:nth-of-type(2) > h2",
+ "_queued_dispatch_text": "[show-annotation] comment\n\n这里的标题太小了,正文和它几乎一样重\n\nAnchor kind: element\n\nQuote: Model Hub\nAnchor: main > section:nth-of-type(2) > h2\n\nShow event id: evt_7f3a91c2\n\n如需在页面上原位回应,可执行:\n vibe show reply evt_7f3a91c2 --message '<你的回答>'\n(也可以直接修改页面内容来响应,按场景选择。)"
+ },
+ "created_at": "2026-07-27T10:14:02.417Z"
+ }
+ },
+ {
+ "_name": "forward / user annotation with a screenshot region, queued behind a running turn",
+ "row": {
+ "id": "msg_01J8XK5M8T",
+ "type": "queued",
+ "author": "harness",
+ "source": "harness",
+ "author_name": "show_annotation",
+ "author_id": "evt_b0c4d5e6",
+ "native_message_id": "show:evt_b0c4d5e6",
+ "text": "这两个卡片的间距不一致",
+ "content": {
+ "text": "这两个卡片的间距不一致",
+ "annotation": {
+ "direction": "user",
+ "action": "created"
+ },
+ "attachments": [
+ {
+ "url": "/api/media/med_9a71c33f8b2e",
+ "name": "annotation-region.png",
+ "mime": "image/png",
+ "kind": "image",
+ "width": 1240,
+ "height": 620
+ }
+ ]
+ },
+ "metadata": {
+ "source": "show_page",
+ "show_event_id": "evt_b0c4d5e6",
+ "show_event_type": "human.annotation.created",
+ "show_event_scope": "default",
+ "anchor_kind": "screenshot",
+ "screenshot_region": "x:120, y:340, 1240x620",
+ "_queued_dispatch_text": "[show-annotation] comment\n\n这两个卡片的间距不一致\n\nAnchor kind: screenshot\nScreenshot: state/media/med_9a71c33f8b2e.png (1240x620)\nScreenshot region: x:120, y:340, 1240x620\n\nShow event id: evt_b0c4d5e6\n\n如需在页面上原位回应,可执行:\n vibe show reply evt_b0c4d5e6 --message '<你的回答>'\n(也可以直接修改页面内容来响应,按场景选择。)"
+ },
+ "created_at": "2026-07-27T10:15:48.006Z"
+ },
+ "_invariant": "While `type` is `queued` this row appears in the queue strip ONLY. It is absent from the transcript fetch and from the live stream, because neither may look at `metadata.source`. When the turn drains, the flushed row is minted with `type: \"annotation\"` and `_queued_dispatch_text` is stripped."
+ },
+ {
+ "_name": "reverse / agent mark",
+ "row": {
+ "id": "msg_01J8XKB1Q9",
+ "type": "annotation",
+ "author": "agent",
+ "source": null,
+ "author_name": null,
+ "author_id": null,
+ "native_message_id": "show:evt_c8d9e0f1",
+ "text": "标题已经改成 20px/600,正文降到 14px,层级现在拉开了。",
+ "content": {
+ "text": "标题已经改成 20px/600,正文降到 14px,层级现在拉开了。",
+ "annotation": {
+ "direction": "agent",
+ "action": "created",
+ "quote": "Model Hub"
+ }
+ },
+ "metadata": {
+ "source": "show_page",
+ "show_event_id": "evt_c8d9e0f1",
+ "show_event_type": "assistant.mark.created",
+ "show_event_scope": "default"
+ },
+ "created_at": "2026-07-27T10:19:31.882Z"
+ },
+ "_invariant": "`type: \"annotation\"` is in `TRANSCRIPT_TYPES`, so this row streams live to an open Chat page and a refetch returns exactly the same single row."
+ },
+ {
+ "_name": "reverse / agent mark closing out a user annotation",
+ "row": {
+ "id": "msg_01J8XKF7R3",
+ "type": "annotation",
+ "author": "agent",
+ "source": null,
+ "author_name": null,
+ "author_id": null,
+ "native_message_id": "show:evt_d2e3f4a5",
+ "text": "间距统一到 16px 了。",
+ "content": {
+ "text": "间距统一到 16px 了。",
+ "annotation": {
+ "direction": "agent",
+ "action": "resolved"
+ }
+ },
+ "metadata": {
+ "source": "show_page",
+ "show_event_id": "evt_d2e3f4a5",
+ "show_event_type": "assistant.mark.resolved",
+ "show_event_scope": "default"
+ },
+ "created_at": "2026-07-27T10:21:07.140Z"
+ },
+ "_invariant": "`action: \"resolved\"` renders a distinct state element on the card. The title stays exactly `Agent 批注`."
+ }
+ ]
+}
diff --git a/storage/agent_activity_service.py b/storage/agent_activity_service.py
index f020e504d..bdbb16ecf 100644
--- a/storage/agent_activity_service.py
+++ b/storage/agent_activity_service.py
@@ -185,17 +185,12 @@ def _timeline(conn, session_id: str, *, include_text: bool) -> list[dict[str, An
mtype = msg.get("type")
author = msg.get("author")
metadata = msg.get("metadata") or {}
- # Show-Page annotations/intents persist as transcript rows (``user`` AND
- # ``assistant``) with metadata.source='show_page'; they are display-only and
- # must never act as a turn opener (would split an in-flight turn) nor as
- # activity — always ignore them in the grouping.
- show_page = metadata.get("source") == "show_page"
activity_role = spec_for(mtype if isinstance(mtype, str) else "")["activityRole"]
if _is_terminal(mtype, author, metadata):
kind = "terminal"
- elif activity_role == "turn_start" and not show_page:
+ elif activity_role == "turn_start":
kind = "turn_start"
- elif activity_role == "activity" and not show_page:
+ elif activity_role == "activity":
kind = "activity"
else:
kind = "ignore"
diff --git a/storage/alembic/versions/20260727_0038_show_annotation_type.py b/storage/alembic/versions/20260727_0038_show_annotation_type.py
new file mode 100644
index 000000000..7a40909b5
--- /dev/null
+++ b/storage/alembic/versions/20260727_0038_show_annotation_type.py
@@ -0,0 +1,50 @@
+"""add the Show annotation message type's inbox index support
+
+This revision changes schema only. Rows written before it keep their original
+types and are not supported by the annotation renderer. The feature never
+shipped, so no installation holds annotation history that requires migration.
+
+Revision ID: 20260727_0038
+Revises: 20260726_0037
+Create Date: 2026-07-27
+"""
+
+from __future__ import annotations
+
+from alembic import op
+
+revision = "20260727_0038"
+down_revision = "20260726_0037"
+branch_labels = None
+depends_on = None
+
+UPGRADE_USER_SEND_PREDICATE = (
+ "session_id is not null and ((author = 'user' and type = 'user') "
+ "or (author = 'harness' and type = 'harness') "
+ "or (author = 'harness' and type = 'annotation'))"
+)
+DOWNGRADE_USER_SEND_PREDICATE = (
+ "session_id is not null and ((author = 'user' and type = 'user') "
+ "or (author = 'harness' and type = 'harness'))"
+)
+
+_CREATE_USER_SEND_INDEX_PREFIX = (
+ "create index ix_messages_inbox_user_send "
+ "on messages (platform, session_id, created_at desc, id desc) where "
+)
+
+
+def upgrade() -> None:
+ bind = op.get_bind()
+ bind.exec_driver_sql("drop index if exists ix_messages_inbox_user_send")
+ bind.exec_driver_sql(
+ _CREATE_USER_SEND_INDEX_PREFIX + UPGRADE_USER_SEND_PREDICATE
+ )
+
+
+def downgrade() -> None:
+ bind = op.get_bind()
+ bind.exec_driver_sql("drop index if exists ix_messages_inbox_user_send")
+ bind.exec_driver_sql(
+ _CREATE_USER_SEND_INDEX_PREFIX + DOWNGRADE_USER_SEND_PREDICATE
+ )
diff --git a/storage/messages_service.py b/storage/messages_service.py
index 66728ee80..bea64c370 100644
--- a/storage/messages_service.py
+++ b/storage/messages_service.py
@@ -17,7 +17,7 @@ import uuid
from datetime import datetime, timezone
from typing import Any, Iterable, Optional
-from sqlalchemy import and_, delete, func, or_, select, update
+from sqlalchemy import and_, case, delete, func, or_, select, update
from sqlalchemy.engine import Connection
from storage.db import escape_sql_like
@@ -237,13 +237,15 @@ def search_messages(
Substring (case-insensitive) ``LIKE`` over ``messages.content_text``, scoped
to one ``platform`` (Workbench = ``avibe``) and a set of transcript-visible
``types`` (human prompts + harness prompts + the agent's rendered ``result``
- replies — all land on a message the chat actually renders, so a clicked result
- is always jumpable). Archived sessions are excluded, as are messages under an
- archived PROJECT — ``projects_service.archive_project`` disables a project by setting
- ``scope_settings.enabled = 0`` (its sessions stay ``active``), so the scope's
- disabled state is the authoritative "archived project" signal here. A scope
- with no ``scope_settings`` row is treated as enabled (legacy / folder-less
- projects never got one). ``limit`` caps the number of
+ replies + Show annotations — all land on a message the chat
+ actually renders, so a clicked result is always jumpable). Archived sessions
+ are excluded, as are messages under an archived PROJECT —
+ ``projects_service.archive_project``
+ disables a project by setting ``scope_settings.enabled = 0`` (its sessions
+ stay ``active``), so the scope's disabled state is the authoritative
+ "archived project" signal here. A scope with no ``scope_settings`` row is
+ treated as enabled (legacy / folder-less projects never got one). ``limit``
+ caps the number of
MATCHED messages scanned (newest first), so it bounds total work; the matches
are then grouped into sessions. The snippet is built in Python (see
:func:`build_snippet`) so the client renders ``match`` with a highlight and
@@ -494,20 +496,13 @@ def list_session_messages(
around_id: Optional[str] = None,
limit: int = 50,
types: Optional[Iterable[str]] = None,
- include_metadata_sources: Iterable[str] = (),
tail: bool = False,
) -> dict[str, Any]:
"""Return messages for one session in chronological order with cursor pagination.
``types`` optionally restricts the rows to a set of message types. The chat
- transcript passes ``('user', 'result')`` so the intermediate ``assistant`` /
- ``tool_call`` / ``notify`` rows — now persisted for avibe sessions too — stay
- out of the conversation view (they're the process log, not the dialogue).
-
- ``include_metadata_sources`` keeps rows whose ``metadata.source`` matches even
- when their type is filtered out — the chat transcript passes ``('show_page',)``
- so Show-Page transcript marks (written with ``author='agent'`` → ``type
- ='assistant'``) stay visible alongside the user/result dialogue.
+ transcript passes :data:`TRANSCRIPT_TYPES` so intermediate process-log rows
+ stay out of the conversation view.
``before_id`` returns the page immediately older than that row, still in
chronological order. This powers upward history loading from the chat page.
@@ -528,15 +523,8 @@ def list_session_messages(
"""
query = select(messages).where(messages.c.session_id == session_id)
- metadata_sources = list(include_metadata_sources)
if types is not None:
- type_filter = messages.c.type.in_(list(types))
- if metadata_sources:
- query = query.where(
- or_(type_filter, func.json_extract(messages.c.metadata_json, "$.source").in_(metadata_sources))
- )
- else:
- query = query.where(type_filter)
+ query = query.where(messages.c.type.in_(list(types)))
effective_limit = min(max(int(limit), 1), 500)
if around_id:
# Window centered on a specific message (deep-link / search jump). Resolve
@@ -686,6 +674,7 @@ def first_user_text(conn: Connection, session_id: str) -> str:
QUEUED_TYPE = "queued"
DRAFT_TYPE = "draft"
+QUEUED_DISPATCH_TEXT_KEY = "_queued_dispatch_text"
# 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
@@ -706,6 +695,7 @@ HARNESS_DEDUPE_TYPE = "harness_dedupe"
# in NON_CONVERSATION_TYPES below so it never bumps the inbox activity clock / last
# author. Never delivered to IM (avibe-persistence only).
SILENT_TYPE = "silent"
+ANNOTATION_TYPE = "annotation"
# Types that must never count as inbox conversation activity: the ephemeral user rows
# above plus the invisible agent silent-completion marker.
NON_CONVERSATION_TYPES = types_without("inboxActivity")
@@ -715,12 +705,11 @@ NON_CONVERSATION_TYPES = types_without("inboxActivity")
# gate, so what a page loads and what it receives over the stream are identical.
# Excludes the agent's process log (``assistant`` / ``tool_call``) and ``system``
# (which isn't persisted at all). Harness-triggered prompts have their own type
-# so they cannot be mistaken for human input. ``show_page`` transcript marks are
-# kept via a metadata-source
-# override in the fetch even though their row type is ``assistant``. ``error`` is a
-# terminal FAILED result (turned the dot red): shown in the conversation like any
-# terminal message, but the unread queries below stay ``result``-only so a failure
-# is not counted as an unread agent reply.
+# so they cannot be mistaken for human input. Show Page annotations in either
+# direction share one explicit transcript type. ``error`` is a terminal FAILED
+# result (turned the dot red): shown in the conversation like any terminal
+# message, but the unread queries below stay ``result``-only so a failure is not
+# counted as an unread agent reply.
TRANSCRIPT_TYPES = types_with("transcript")
_INBOX_PREVIEW_TYPES = types_with("inboxPreview")
_INBOX_SETTLES_REPLY_TYPES = types_with("inboxSettlesReply")
@@ -867,18 +856,41 @@ def delete_pending(conn: Connection, message_id: str) -> bool:
def promote_pending(conn: Connection, message_id: str, to_type: str) -> bool:
- """Change only the rendering state of one reserved transcript row."""
+ """Advance one reservation and discard its prompt only when delivered."""
+
+ values: dict[str, Any] = {"type": to_type}
+ if to_type != QUEUED_TYPE:
+ values["metadata_json"] = case(
+ (
+ func.json_valid(messages.c.metadata_json) == 1,
+ func.json_remove(
+ messages.c.metadata_json,
+ f"$.{QUEUED_DISPATCH_TEXT_KEY}",
+ ),
+ ),
+ else_=messages.c.metadata_json,
+ )
result = conn.execute(
update(messages)
.where(messages.c.id == message_id)
.where(messages.c.type == PENDING_TYPE)
- .values(type=to_type)
+ .values(**values)
)
return bool(result.rowcount)
-def pending_message_target_type(author: Optional[str], source: Optional[str]) -> str:
+def pending_message_target_type(
+ author: Optional[str],
+ source: Optional[str],
+ author_name: Optional[str],
+) -> str:
"""Resolve an accepted input reservation to its transcript-visible type."""
+ if (
+ author == HARNESS_TYPE
+ and source == HARNESS_TYPE
+ and author_name == "show_annotation"
+ ):
+ return ANNOTATION_TYPE
if HARNESS_TYPE in {author, source}:
return HARNESS_TYPE
return "user"
diff --git a/tests/test_agent_activity_service.py b/tests/test_agent_activity_service.py
index a52fe67a9..518a8e971 100644
--- a/tests/test_agent_activity_service.py
+++ b/tests/test_agent_activity_service.py
@@ -9,7 +9,7 @@ Covers the grouping contract in ``storage/agent_activity_service.py``:
* a turn whose activity is followed by a NEW turn (no terminal) → ``interrupted``
anchored at the next turn's opening message; a trailing one → anchor ``None``,
* a turn with no activity rows produces no group,
-* Show-Page ``assistant`` marks (metadata.source='show_page') are not activity,
+* agent-authored annotation rows are not activity,
* detail mode returns the ordered rows; an unknown group id returns ``None``.
"""
@@ -24,7 +24,7 @@ from sqlalchemy import select # noqa: F401 (kept parallel to sibling tests)
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
-from storage import agent_activity_service
+from storage import agent_activity_service, messages_service
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
from storage.models import agent_events, agent_sessions, messages
@@ -187,14 +187,15 @@ def test_rows_merge_across_tables_by_parsed_timestamp(isolated_state):
]
-def test_show_page_assistant_marks_are_not_activity(isolated_state):
+def test_agent_annotation_marks_are_not_activity(isolated_state):
engine = create_sqlite_engine()
sid = "ses_sp"
with engine.begin() as conn:
scope = _seed_session(conn, session_id=sid)
_msg(conn, scope, sid, mid="m_u", mtype="user", author="user", created_at="2026-06-01T10:00:00.000000+00:00", text="q", source="user")
_msg(
- conn, scope, sid, mid="m_sp", mtype="assistant", author="agent",
+ conn, scope, sid, mid="m_sp",
+ mtype=messages_service.ANNOTATION_TYPE, author="agent",
created_at="2026-06-01T10:00:01.000000+00:00", text="show page mark",
metadata={"source": "show_page"},
)
@@ -202,7 +203,7 @@ def test_show_page_assistant_marks_are_not_activity(isolated_state):
with engine.connect() as conn:
summary = agent_activity_service.list_turn_groups(conn, session_id=sid)
- # The only ``assistant`` row is a Show-Page mark → no activity → no group.
+ # The annotation is display-only, not an interim assistant activity row.
assert summary["groups"] == []
@@ -317,9 +318,8 @@ def test_duration_measured_from_turn_opener(isolated_state):
assert summary["groups"][0]["duration_ms"] == 10_000
-def test_show_page_user_marks_do_not_split_a_turn(isolated_state):
- """A Show-Page annotation persists as a user row mid-turn; it must NOT be treated
- as a turn opener (which would mark the turn interrupted and orphan its terminal)."""
+def test_non_dispatching_user_annotations_do_not_split_a_turn(isolated_state):
+ """A non-dispatching annotation is display-only, even though a user authored it."""
engine = create_sqlite_engine()
sid = "ses_spuser"
with engine.begin() as conn:
@@ -328,7 +328,8 @@ def test_show_page_user_marks_do_not_split_a_turn(isolated_state):
_evt(conn, scope, sid, eid="e_1", created_at="2026-06-01T10:00:01Z", text="🔧 `Bash`")
# A Show-Page user mark lands WHILE the turn is still producing activity.
_msg(
- conn, scope, sid, mid="m_sp", mtype="user", author="user",
+ conn, scope, sid, mid="m_sp",
+ mtype=messages_service.ANNOTATION_TYPE, author="user",
created_at="2026-06-01T10:00:02Z", text="pinned an element", source="user",
metadata={"source": "show_page"},
)
@@ -344,6 +345,47 @@ def test_show_page_user_marks_do_not_split_a_turn(isolated_state):
assert groups[0]["steps"] == 2
+def test_dispatching_annotations_do_not_group_as_activity_turns(isolated_state):
+ engine = create_sqlite_engine()
+ sid = "ses_annotation_turn"
+ with engine.begin() as conn:
+ scope = _seed_session(conn, session_id=sid)
+ _msg(
+ conn,
+ scope,
+ sid,
+ mid="m_annotation",
+ mtype=messages_service.ANNOTATION_TYPE,
+ author="harness",
+ created_at="2026-06-01T10:00:00Z",
+ text="review this heading",
+ source="harness",
+ )
+ _evt(
+ conn,
+ scope,
+ sid,
+ eid="e_annotation_tool",
+ created_at="2026-06-01T10:00:01Z",
+ text="🔧 `Read`",
+ )
+ _msg(
+ conn,
+ scope,
+ sid,
+ mid="m_result",
+ mtype="result",
+ author="agent",
+ created_at="2026-06-01T10:00:02Z",
+ text="done",
+ )
+
+ with engine.connect() as conn:
+ summary = agent_activity_service.list_turn_groups(conn, session_id=sid)
+
+ assert summary["groups"] == []
+
+
def test_interrupted_followed_by_running_turn_anchors_to_own_trigger(isolated_state):
"""(a) Interrupted turn followed by a still-RUNNING next turn — the P1 repro.
The interrupted chip must anchor AFTER its OWN trigger (above the newer turn),
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index 80330bf92..c64fedff7 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -723,15 +723,71 @@ def test_dispatch_async_enqueues_during_busy_turn(monkeypatch, tmp_path):
"stored_type",
"author",
"source",
+ "author_name",
+ "content",
"active_same_message",
"expect_queued",
"expected_type",
+ "expected_activity",
),
(
- ("pending", "user", "user", True, False, "user"),
- ("pending", "harness", "harness", True, False, "harness"),
- ("queued", "user", "user", False, True, "queued"),
- ("user", "user", "user", False, False, "user"),
+ (
+ "pending",
+ "user",
+ "user",
+ None,
+ {},
+ True,
+ False,
+ "user",
+ "user_message",
+ ),
+ (
+ "pending",
+ "user",
+ "user",
+ "show_annotation",
+ {},
+ True,
+ False,
+ "user",
+ "user_message",
+ ),
+ (
+ "pending",
+ "harness",
+ "harness",
+ None,
+ {},
+ True,
+ False,
+ "harness",
+ "show_event",
+ ),
+ (
+ "pending",
+ "harness",
+ "harness",
+ "show_annotation",
+ {"annotation": {"direction": "user", "action": "created"}},
+ True,
+ False,
+ "annotation",
+ "show_event",
+ ),
+ ("queued", "user", "user", None, {}, False, True, "queued", None),
+ ("user", "user", "user", None, {}, False, False, "user", None),
+ (
+ "annotation",
+ "harness",
+ "harness",
+ "show_annotation",
+ {"annotation": {"direction": "user", "action": "created"}},
+ False,
+ False,
+ "annotation",
+ None,
+ ),
),
)
def test_dispatch_async_deduplicates_replayed_reserved_message(
@@ -740,9 +796,12 @@ def test_dispatch_async_deduplicates_replayed_reserved_message(
stored_type,
author,
source,
+ author_name,
+ content,
active_same_message,
expect_queued,
expected_type,
+ expected_activity,
):
from core.inbox_events import bus
from core.services import sessions as sessions_service
@@ -776,8 +835,10 @@ def test_dispatch_async_deduplicates_replayed_reserved_message(
platform="avibe",
author=author,
source=source,
+ author_name=author_name,
message_type=stored_type,
text="same show event",
+ content=content,
)
controller = _build_controller_double()
@@ -842,6 +903,14 @@ def test_dispatch_async_deduplicates_replayed_reserved_message(
assert [item["id"] for item in visible_events] == [row["id"]]
else:
assert visible_events == []
+ activity_events = [
+ data["event"]
+ for event_type, data in published
+ if event_type == "session.activity"
+ ]
+ assert activity_events == (
+ [expected_activity] if expected_activity is not None else []
+ )
def test_dispatch_async_persists_acceptance_before_a_lost_response_replay(
@@ -1221,7 +1290,32 @@ def test_slow_live_show_post_cli_timeout_waits_without_duplicate_submit(
assert json.loads(capsys.readouterr().out)["event_id"] == event_input["id"]
-def test_dispatch_async_queues_show_annotation_and_runs_it_after_active_turn(monkeypatch, tmp_path):
+ ("comment", "anchor", "expected_display"),
+ [
+ (
+ "Deliver after the active turn.",
+ None,
+ {"direction": "user", "action": "created"},
+ ),
+ (
+ "",
+ {"text": "Busy annotation quote"},
+ {
+ "direction": "user",
+ "action": "created",
+ "quote": "Busy annotation quote",
+ },
+ ),
+ ],
+)
+def test_dispatch_async_queues_show_annotation_and_runs_it_after_active_turn(
+ monkeypatch,
+ tmp_path,
+ comment,
+ anchor,
+ expected_display,
+):
from core.services import sessions as sessions_service
from core.show_session_events import ShowSessionEventStore
from storage import messages_service
@@ -1281,8 +1375,9 @@ def test_dispatch_async_queues_show_annotation_and_runs_it_after_active_turn(mon
"type": "human.annotation.created",
"annotation": {
"intent": "comment",
- "comment": "Deliver after the active turn.",
+ "comment": comment,
"dispatch": True,
+ **({"anchor": anchor} if anchor else {}),
},
},
reserve_dispatch=True,
@@ -1290,11 +1385,10 @@ def test_dispatch_async_queues_show_annotation_and_runs_it_after_active_turn(mon
finally:
store.close()
assert annotation["message"]["type"] == messages_service.PENDING_TYPE
- enriched_dispatch_text = (
- f"{annotation['transcript_text']}\n\n"
- f"Show event ID: {annotation['id']}\n"
- "Reply on the Show Page with `vibe show reply`."
- )
+ enriched_dispatch_text = annotation["message"]["metadata"][
+ session_turns.QUEUED_DISPATCH_TEXT_KEY
+ ]
+ assert f"Show event id: {annotation['id']}" in enriched_dispatch_text
queued = await client.post(
"/internal/dispatch_async",
json={
@@ -1317,7 +1411,9 @@ def test_dispatch_async_queues_show_annotation_and_runs_it_after_active_turn(mon
visible = messages_service.list_session_messages(
conn,
session_id=session_id,
- types=("user",),
+ limit=50,
+ types=messages_service.TRANSCRIPT_TYPES,
+ tail=True,
)
assert visible["messages"] == []
assert seen_texts == ["active turn"]
@@ -1338,14 +1434,19 @@ def test_dispatch_async_queues_show_annotation_and_runs_it_after_active_turn(mon
visible = messages_service.list_session_messages(
conn,
session_id=session_id,
+ limit=50,
types=messages_service.TRANSCRIPT_TYPES,
+ tail=True,
)
linked_message_id = conn.execute(
select(show_session_events.c.message_id).where(show_session_events.c.id == annotation["id"])
).scalar_one()
assert [message["text"] for message in visible["messages"]] == [annotation["transcript_text"]]
- assert visible["messages"][0]["type"] == messages_service.HARNESS_TYPE
+ assert visible["messages"][0]["type"] == messages_service.ANNOTATION_TYPE
+ assert visible["messages"][0]["author"] == messages_service.HARNESS_TYPE
+ assert visible["messages"][0]["source"] == messages_service.HARNESS_TYPE
assert visible["messages"][0]["author_name"] == "show_annotation"
+ assert visible["messages"][0]["content"]["annotation"] == expected_display
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"]
@@ -1353,6 +1454,123 @@ def test_dispatch_async_queues_show_annotation_and_runs_it_after_active_turn(mon
assert linked_message_id == visible["messages"][0]["id"]
+def test_startup_recovered_annotation_retries_reserved_dispatch_text(
+ monkeypatch,
+ tmp_path,
+):
+ from core.services import sessions as sessions_service
+ from core.show_session_events import ShowSessionEventStore
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.settings_service import upsert_scope
+ from vibe import 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_sweep_flush",
+ now="2026-05-31T00:00:00Z",
+ )
+ _seed_project_workdir(conn, scope_id, tmp_path)
+ session = sessions_service.create_session(
+ conn,
+ scope_id=scope_id,
+ agent_backend="claude",
+ agent_name="worker",
+ )
+ store = ShowSessionEventStore()
+ try:
+ annotation = store.append(
+ session["id"],
+ {
+ "type": "human.annotation.created",
+ "annotation": {
+ "intent": "comment",
+ "comment": "Recover and deliver this.",
+ "dispatch": True,
+ "anchor": {
+ "kind": "element",
+ "selector": "#summary",
+ "text": "Quarterly summary",
+ },
+ },
+ },
+ reserve_dispatch=True,
+ )
+ finally:
+ store.close()
+ expected_dispatch = annotation["message"]["metadata"][
+ session_turns.QUEUED_DISPATCH_TEXT_KEY
+ ]
+
+ assert ui_server._recover_stale_pending_messages() == {
+ "promoted": 0,
+ "deleted": 0,
+ "skipped": 1,
+ }
+
+ controller = _build_controller_double()
+ internal_app = internal_server.create_app(controller)
+ transport = httpx.ASGITransport(app=internal_app)
+ manager = controller.session_turns
+ manager._build_context = lambda sid: MessageContext(
+ user_id="U",
+ channel_id="C",
+ platform="avibe",
+ platform_specific={"agent_session_id": sid},
+ )
+ dispatched = []
+
+ async def capture_run(sid, context, text, *, source=SOURCE_HUMAN):
+ dispatched.append((sid, context.message_id, text, source))
+
+ manager._run = capture_run
+
+ async def dispatch_through_controller(payload, **_kwargs):
+ 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(
+ "vibe.internal_client.dispatch_async",
+ dispatch_through_controller,
+ )
+ outcome = asyncio.run(ui_server._run_show_event_dispatch(annotation))
+ assert outcome == ui_server._ShowEventDispatchOutcome.ACCEPTED
+
+ with engine.connect() as conn:
+ queued = messages_service.list_queued(conn, session["id"])
+ transcript = messages_service.list_session_messages(
+ conn,
+ session_id=session["id"],
+ limit=50,
+ types=messages_service.TRANSCRIPT_TYPES,
+ tail=True,
+ )["messages"]
+ assert queued == []
+ assert dispatched[0][1] == annotation["message_id"]
+ assert dispatched[0][2] == expected_dispatch
+ assert "Anchor: #summary" in dispatched[0][2]
+ assert f"Show event id: {annotation['id']}" in dispatched[0][2]
+ assert transcript[0]["type"] == messages_service.ANNOTATION_TYPE
+ assert transcript[0]["text"] == "Recover and deliver this."
+ assert transcript[0]["content"]["annotation"]["quote"] == "Quarterly summary"
+ assert (
+ session_turns.QUEUED_DISPATCH_TEXT_KEY
+ not in transcript[0]["metadata"]
+ )
+
+
def test_dispatch_async_keeps_identified_show_row_after_idle_anonymous_queue(
monkeypatch,
tmp_path,
@@ -1436,7 +1654,9 @@ def test_dispatch_async_keeps_identified_show_row_after_idle_anonymous_queue(
"/internal/dispatch_async",
json={
"session_id": session["id"],
- "text": annotation["transcript_text"],
+ "text": annotation["message"]["metadata"][
+ session_turns.QUEUED_DISPATCH_TEXT_KEY
+ ],
"user_message_id": annotation["message_id"],
"show_event_id": annotation["id"],
},
@@ -1462,7 +1682,9 @@ def test_dispatch_async_keeps_identified_show_row_after_idle_anonymous_queue(
visible = messages_service.list_session_messages(
conn,
session_id=session["id"],
+ limit=50,
types=messages_service.TRANSCRIPT_TYPES,
+ tail=True,
)["messages"]
assert [row["id"] for row in queued] == [annotation["message_id"]]
assert original_exists == annotation["message_id"]
@@ -1482,15 +1704,19 @@ def test_dispatch_async_keeps_identified_show_row_after_idle_anonymous_queue(
visible = messages_service.list_session_messages(
conn,
session_id=session["id"],
+ limit=50,
types=messages_service.TRANSCRIPT_TYPES,
+ tail=True,
)["messages"]
assert [run[1] for run in runs] == [
"older stopped message",
- annotation["transcript_text"],
+ annotation["message"]["metadata"][
+ session_turns.QUEUED_DISPATCH_TEXT_KEY
+ ],
]
assert original_exists is None
assert linked_message_id == visible[1]["id"]
- assert visible[1]["type"] == messages_service.HARNESS_TYPE
+ assert visible[1]["type"] == messages_service.ANNOTATION_TYPE
assert visible[1]["author_name"] == "show_annotation"
assert visible[1]["native_message_id"] == f"show:{annotation['id']}"
diff --git a/tests/test_message_search.py b/tests/test_message_search.py
index 10dcbba2e..648b3a01c 100644
--- a/tests/test_message_search.py
+++ b/tests/test_message_search.py
@@ -178,6 +178,33 @@ def test_search_finds_harness_prompt_by_default(isolated_state):
)
+def test_search_finds_annotation_by_default(isolated_state):
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_session(conn, scope_id, "ses_annotation", "Show review")
+ _insert_msg(
+ conn,
+ scope_id,
+ "ses_annotation",
+ "harness",
+ "The heading needs more contrast",
+ "2026-06-01T10:00:00Z",
+ msg_type=messages_service.ANNOTATION_TYPE,
+ source="harness",
+ )
+
+ with engine.connect() as conn:
+ result = messages_service.search_messages(conn, query="contrast")
+
+ match = result["sessions"][0]["matches"][0]
+ assert (match["author"], match["source"], match["type"]) == (
+ "harness",
+ "harness",
+ messages_service.ANNOTATION_TYPE,
+ )
+
+
def test_search_excludes_im_platform_rows(isolated_state):
"""A ``result`` row on a non-avibe (IM) platform is excluded for the default
platform='avibe' search — search is Workbench-scoped."""
diff --git a/tests/test_message_type_catalog.py b/tests/test_message_type_catalog.py
index a03b8b76d..5d3094a74 100644
--- a/tests/test_message_type_catalog.py
+++ b/tests/test_message_type_catalog.py
@@ -67,7 +67,7 @@ def test_catalog_resource_and_defaults_are_cross_language_data() -> None:
def test_transcript_types_match_current_constant() -> None:
- expected = ("user", "harness", "result", "notify", "error")
+ expected = ("user", "harness", "annotation", "result", "notify", "error")
assert types_with("transcript") == expected
assert messages_service.TRANSCRIPT_TYPES == expected
@@ -76,7 +76,7 @@ def test_searchable_types_match_current_default_query() -> None:
connection = _CaptureConnection()
messages_service.search_messages(connection, query="catalog-probe")
- expected = ("user", "harness", "result")
+ expected = ("user", "harness", "annotation", "result")
assert types_with("searchable") == expected
assert _sequence_params(connection.statements[-1]) == {expected}
@@ -120,11 +120,33 @@ def test_unread_types_match_current_queries(query: Any) -> None:
def test_input_turn_pairs_match_current_constant() -> None:
- expected = (("user", "user"), ("harness", "harness"))
+ expected = (
+ ("user", "user"),
+ ("harness", "harness"),
+ ("harness", "annotation"),
+ )
assert input_author_type_pairs() == expected
assert INPUT_TURN_AUTHOR_TYPES == expected
+def test_annotation_catalog_contract_is_explicit() -> None:
+ assert dict(spec_for("annotation")) == {
+ "transcript": True,
+ "searchable": True,
+ "inputAuthors": ("harness",),
+ "inboxActivity": True,
+ "inboxPreview": False,
+ "inboxSettlesReply": False,
+ "activityRole": "none",
+ "terminalWhenEvents": (),
+ "unread": False,
+ "webPush": False,
+ "webPushWhenEvents": (),
+ "acceptedReservation": True,
+ "render": "annotation",
+ }
+
+
def test_activity_fetch_and_terminal_semantics_match_current_service() -> None:
derived_relevant = {
message_type
diff --git a/tests/test_message_type_python_consumers.py b/tests/test_message_type_python_consumers.py
index 603671e70..3233393a8 100644
--- a/tests/test_message_type_python_consumers.py
+++ b/tests/test_message_type_python_consumers.py
@@ -10,6 +10,7 @@ def test_backend_failure_predicate_matches_legacy_type_and_event_pair() -> None:
for message_type in (
"user",
"harness",
+ "annotation",
"result",
"notify",
"error",
@@ -41,7 +42,7 @@ def test_backend_failure_predicate_matches_legacy_type_and_event_pair() -> None:
def test_reservation_acceptance_matches_legacy_consumers() -> None:
- expected = {"user", "harness", "queued"}
+ expected = {"user", "harness", "annotation", "queued"}
assert set(types_with("acceptedReservation")) == expected
assert internal_server._ACCEPTED_RESERVATION_TYPES == expected
assert ui_server._ACCEPTED_RESERVATION_TYPES == expected
@@ -62,6 +63,7 @@ def test_fork_activity_sets_match_legacy_values() -> None:
assert set(session_fork._FORK_ANCHOR_TYPES) == {
"user",
"harness",
+ "annotation",
"result",
"notify",
"error",
@@ -70,7 +72,7 @@ def test_fork_activity_sets_match_legacy_values() -> None:
def test_show_git_input_message_types_match_legacy_values() -> None:
- assert show_git._INPUT_TURN_MESSAGE_TYPES == ("user", "harness")
+ assert show_git._INPUT_TURN_MESSAGE_TYPES == ("user", "harness", "annotation")
def test_mirror_catalog_roles_match_legacy_type_sets() -> None:
diff --git a/tests/test_messages_service.py b/tests/test_messages_service.py
index 6c47931c7..b0ee33ebe 100644
--- a/tests/test_messages_service.py
+++ b/tests/test_messages_service.py
@@ -52,6 +52,16 @@ def _seed_session(conn, scope_id: str, session_id: str) -> None:
)
+def _list_production_transcript(conn, session_id: str):
+ return messages_service.list_session_messages(
+ conn,
+ session_id=session_id,
+ limit=50,
+ types=messages_service.TRANSCRIPT_TYPES,
+ tail=True,
+ )
+
+
def _insert_harness_msg(conn, scope_id, session_id, *, author_name, native_message_id,
author_id=None, msg_id, created_at):
conn.execute(
@@ -415,17 +425,71 @@ def test_append_normalizes_legacy_harness_identity(isolated_state):
@pytest.mark.parametrize(
- ("author", "source", "expected"),
+ ("author", "source", "author_name", "expected"),
[
- ("user", "user", "user"),
- ("user", None, "user"),
- ("harness", "harness", "harness"),
- ("user", "harness", "harness"),
- ("harness", None, "harness"),
+ ("user", "user", None, "user"),
+ ("user", None, None, "user"),
+ ("harness", "harness", "show_intent", "harness"),
+ ("user", "harness", "show_intent", "harness"),
+ ("harness", None, None, "harness"),
+ ("harness", "harness", "show_annotation", "annotation"),
+ ("user", "user", "show_annotation", "user"),
+ ("user", "harness", "show_annotation", "harness"),
+ ("harness", None, "show_annotation", "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_pending_message_target_type_uses_row_origin(
+ author,
+ source,
+ author_name,
+ expected,
+):
+ assert (
+ messages_service.pending_message_target_type(
+ author,
+ source,
+ author_name,
+ )
+ == expected
+ )
+
+
+def test_show_annotation_reservation_flushes_as_annotation(isolated_state):
+ from core import session_turns
+
+ engine = create_sqlite_engine()
+ legacy_prompt = (
+ "[show-annotation] comment\n\nLegacy body\n\n"
+ "Anchor: #hero\n\nShow event id: evt_legacy"
+ )
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_session(conn, scope_id, "ses_legacy_annotation")
+ messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_legacy_annotation",
+ platform="avibe",
+ author="harness",
+ source="harness",
+ author_name="show_annotation",
+ message_type=messages_service.QUEUED_TYPE,
+ text=legacy_prompt,
+ content={"text": legacy_prompt},
+ )
+ segment = messages_service.list_queued(conn, "ses_legacy_annotation")
+ visible = session_turns._promote_merged_user_segment(
+ conn,
+ segment,
+ text=legacy_prompt,
+ attachments=[],
+ metadata={},
+ author_id=None,
+ )
+
+ assert visible["type"] == messages_service.ANNOTATION_TYPE
+ assert visible["text"] == legacy_prompt
+ assert "annotation" not in visible["content"]
def test_same_second_messages_order_by_insertion(isolated_state):
@@ -463,10 +527,7 @@ def test_same_second_messages_order_by_insertion(isolated_state):
assert [m["text"] for m in page["messages"]] == ["prompt", "answer"]
-def test_list_session_messages_keeps_show_page_marks(isolated_state):
- """Show-Page transcript marks (author='agent' → type='assistant', but
- metadata.source='show_page') stay visible in the chat transcript even though
- plain intermediate 'assistant' process rows are filtered out."""
+def test_transcript_visibility_depends_only_on_message_type(isolated_state):
engine = create_sqlite_engine()
with engine.begin() as conn:
scope_id = _seed_scope(conn)
@@ -474,15 +535,27 @@ def test_list_session_messages_keeps_show_page_marks(isolated_state):
messages_service.append(
conn, scope_id=scope_id, session_id="ses_mark", platform="avibe", author="user", text="q"
)
- # Avibe intermediate assistant (process log) — must be hidden.
messages_service.append(
conn, scope_id=scope_id, session_id="ses_mark", platform="avibe",
author="agent", message_type="assistant", text="thinking",
+ metadata={"source": "show_page"},
+ )
+ messages_service.append(
+ conn, scope_id=scope_id, session_id="ses_mark", platform="avibe",
+ author="harness", source="harness", author_name="show_annotation",
+ message_type=messages_service.PENDING_TYPE, text="pending",
+ metadata={"source": "show_page"},
+ )
+ messages_service.append(
+ conn, scope_id=scope_id, session_id="ses_mark", platform="avibe",
+ author="harness", source="harness", author_name="show_annotation",
+ message_type=messages_service.QUEUED_TYPE, text="queued",
+ metadata={"source": "show_page"},
)
- # Show-page assistant mark — must stay visible via metadata.source.
messages_service.append(
conn, scope_id=scope_id, session_id="ses_mark", platform="avibe",
- author="agent", text="annotation", metadata={"source": "show_page"},
+ author="agent", message_type=messages_service.ANNOTATION_TYPE,
+ text="annotation", metadata={"source": "anything"},
)
messages_service.append(
conn, scope_id=scope_id, session_id="ses_mark", platform="avibe",
@@ -490,11 +563,11 @@ def test_list_session_messages_keeps_show_page_marks(isolated_state):
)
with engine.connect() as conn:
- page = messages_service.list_session_messages(
- conn, session_id="ses_mark", types=("user", "result"), include_metadata_sources=("show_page",)
- )
+ page = _list_production_transcript(conn, "ses_mark")
texts = [m["text"] for m in page["messages"]]
- assert texts == ["q", "annotation", "final"] # 'thinking' (plain assistant) filtered out
+ assert texts == ["q", "annotation", "final"]
+ assert messages_service.ANNOTATION_TYPE in messages_service.TRANSCRIPT_TYPES
+ assert messages_service.ANNOTATION_TYPE not in messages_service.NON_CONVERSATION_TYPES
def test_transcript_keeps_notify_terminal_marker(isolated_state):
@@ -517,9 +590,7 @@ def test_transcript_keeps_notify_terminal_marker(isolated_state):
)
with engine.connect() as conn:
- page = messages_service.list_session_messages(
- conn, session_id="ses_n", types=("user", "result", "notify"), include_metadata_sources=("show_page",)
- )
+ page = _list_production_transcript(conn, "ses_n")
texts = [m["text"] for m in page["messages"]]
assert texts == ["go", "Agent run failed and stopped."] # notify kept; assistant/tool_call hidden
@@ -928,6 +999,41 @@ def test_list_inbox_sessions_counts_harness_prompt_as_pending_input(isolated_sta
assert completed["preview_text"] == "R2"
+def test_list_inbox_sessions_counts_dispatching_annotation_as_pending_input(
+ isolated_state,
+):
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_titled_session(conn, scope_id, "ses_annotation", "Show review")
+ _insert_msg(
+ conn,
+ scope_id,
+ "ses_annotation",
+ "agent",
+ "R1",
+ "2026-05-30T10:00:00Z",
+ )
+ _insert_msg(
+ conn,
+ scope_id,
+ "ses_annotation",
+ "harness",
+ "review this heading",
+ "2026-05-30T10:01:00Z",
+ msg_type=messages_service.ANNOTATION_TYPE,
+ )
+
+ with engine.connect() as conn:
+ pending = messages_service.list_inbox_sessions(
+ conn,
+ platform="avibe",
+ )["sessions"][0]
+
+ assert pending["replied"] is True
+ assert pending["last_message_author"] == "harness"
+
+
def test_list_inbox_sessions_same_second_followup_uses_id_tiebreaker(isolated_state):
"""``created_at`` is second-resolution, so a follow-up sent in the SAME second
as the prior agent reply ties on time; the time-sortable message id breaks the
diff --git a/tests/test_session_fork.py b/tests/test_session_fork.py
index ae3cf4e3f..9a11eb01d 100644
--- a/tests/test_session_fork.py
+++ b/tests/test_session_fork.py
@@ -1322,6 +1322,17 @@ def test_harness_message_is_an_input_turn() -> None:
).is_running_input_turn is True
+def test_dispatching_annotation_is_an_input_turn() -> None:
+ assert SourceMessageAnchor(
+ author="harness",
+ message_type=messages_service.ANNOTATION_TYPE,
+ ).is_running_input_turn is True
+ assert SourceMessageAnchor(
+ author="user",
+ message_type=messages_service.ANNOTATION_TYPE,
+ ).is_running_input_turn is False
+
+
def test_fork_source_state_tracks_harness_turn_after_anchor(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
diff --git a/tests/test_show_git.py b/tests/test_show_git.py
index 33290dc3f..36ee84739 100644
--- a/tests/test_show_git.py
+++ b/tests/test_show_git.py
@@ -896,3 +896,84 @@ def test_storage_lookup_includes_harness_driving_message():
assert show_git.load_turn_checkpoint_context(
session_id, after="2099-01-01T00:00:00+00:00"
) == expected
+
+ with get_cached_sqlite_engine().begin() as conn:
+ for index, author in enumerate(("user", "agent"), start=2):
+ display_only = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author=author,
+ message_type=messages_service.ANNOTATION_TYPE,
+ text=f"display-only annotation from {author}",
+ )
+ conn.execute(
+ messages.update()
+ .where(messages.c.id == display_only["id"])
+ .values(created_at=f"2099-01-01T00:00:0{index}+00:00")
+ )
+
+ assert show_git.load_turn_checkpoint_context(session_id) == TurnCheckpointContext()
+ assert show_git.load_turn_checkpoint_context(
+ session_id, after="2099-01-01T00:00:01.500000+00:00"
+ ) == TurnCheckpointContext()
+
+
+def test_storage_lookup_includes_annotation_driving_message():
+ from storage import messages_service
+ from storage.db import get_cached_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.models import agent_sessions, messages
+ from storage.settings_service import upsert_scope
+
+ ensure_sqlite_state(primary_platform="avibe")
+ session_id = "ses_annotation_checkpoint"
+ with get_cached_sqlite_engine().begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform="avibe",
+ scope_type="project",
+ native_id="proj_annotation_checkpoint",
+ now="2026-07-27T00:00:00+00:00",
+ )
+ conn.execute(
+ agent_sessions.insert().values(
+ id=session_id,
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_variant="default",
+ session_anchor=session_id,
+ native_session_id="",
+ status="active",
+ metadata_json="{}",
+ created_at="2026-07-27T00:00:00+00:00",
+ updated_at="2026-07-27T00:00:00+00:00",
+ last_active_at="2026-07-27T00:00:00+00:00",
+ )
+ )
+ prompt = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author="harness",
+ message_type=messages_service.ANNOTATION_TYPE,
+ source="harness",
+ text="tighten the heading hierarchy",
+ native_message_id="show:show_evt_checkpoint",
+ )
+ conn.execute(
+ messages.update()
+ .where(messages.c.id == prompt["id"])
+ .values(created_at="2099-01-01T00:00:01+00:00")
+ )
+
+ expected = TurnCheckpointContext(
+ message="tighten the heading hierarchy",
+ message_id=prompt["id"],
+ )
+ assert show_git.load_turn_checkpoint_context(session_id) == expected
+ assert show_git.load_turn_checkpoint_context(
+ session_id, after="2099-01-01T00:00:00+00:00"
+ ) == expected
diff --git a/tests/test_show_pages.py b/tests/test_show_pages.py
index 39556e3f8..855ea2d38 100644
--- a/tests/test_show_pages.py
+++ b/tests/test_show_pages.py
@@ -2206,9 +2206,12 @@ def test_show_mark_cli_records_event_and_message(monkeypatch, tmp_path, capsys):
assert payload["ok"] is True
assert payload["event"]["type"] == "assistant.mark.created"
assert payload["event"]["message_id"]
- # No anchor text and a synthetic target: the header stands alone rather than
- # falling back to printing the handle at the user.
- assert payload["event"]["transcript_text"] == "Page note\n\nReview this summary."
+ assert payload["event"]["transcript_text"] == "Review this summary."
+ assert payload["event"]["message"]["type"] == "annotation"
+ assert payload["event"]["message"]["content"]["annotation"] == {
+ "direction": "agent",
+ "action": "created",
+ }
with engine.connect() as conn:
assert conn.execute(select(show_session_events.c.id)).scalar_one() == payload["event"]["id"]
@@ -2282,13 +2285,13 @@ def test_show_mark_keeps_anchor_text_without_a_selector(monkeypatch, tmp_path, c
anchor = json.loads(conn.execute(select(show_session_events.c.anchor_json)).scalar_one())
assert anchor == expected_anchor
- # The user-facing echo locates the mark whenever anchor copy was supplied, and
- # never leaks the selector that may sit beside it.
transcript = payload["event"]["transcript_text"]
+ display = payload["event"]["message"]["content"]["annotation"]
+ assert transcript == "Aligned it."
if "text" in expected_anchor:
- assert transcript == "Page note · “Checkout”\n\nAligned it."
+ assert display["quote"] == "Checkout"
else:
- assert transcript == "Page note\n\nAligned it."
+ assert "quote" not in display
assert "#cta" not in transcript
@@ -2459,9 +2462,10 @@ def test_show_reply_copies_annotation_anchor_and_replaces_prior_reply(monkeypatc
assert first["mark_id"] == second["mark_id"]
assert first["event"]["anchor"] == annotation["anchor"]
assert first["event"]["payload"]["target"] == "#revenue-card"
- # A reply copies the annotation's anchor, so the chat message can quote the copy
- # the user highlighted; the reply target is the selector and stays out of sight.
- assert first["event"]["transcript_text"] == "Page note · “Revenue”\n\nFirst answer."
+ assert first["event"]["transcript_text"] == "First answer."
+ assert second["event"]["transcript_text"] == "Better answer."
+ assert first["event"]["message"]["content"]["annotation"]["quote"] == "Revenue"
+ assert second["event"]["message"]["content"]["annotation"]["quote"] == "Revenue"
assert "#revenue-card" not in first["event"]["transcript_text"]
assert first["event"]["payload"]["replyTo"] == annotation["id"]
assert second["replaced"] is True
diff --git a/tests/test_show_session_events.py b/tests/test_show_session_events.py
index 6c51f6302..4e8784114 100644
--- a/tests/test_show_session_events.py
+++ b/tests/test_show_session_events.py
@@ -12,12 +12,14 @@ from sqlalchemy import select
from core.show_session_events import (
ANCHOR_HUMAN_COPY_KEYS,
ASSISTANT_MARK_EVENT_TYPES,
- ASSISTANT_MARK_TRANSCRIPT_I18N_KEYS,
MARK_LOCATOR_MAX_LENGTH,
MARK_PAYLOAD_KEYS,
SHOW_TRIGGER_KIND,
ShowSessionEventError,
ShowSessionEventStore,
+ _annotation_attachments,
+ _annotation_display,
+ _format_dispatch_text,
_format_transcript_text,
localized_show_event_error,
show_event_requests_dispatch,
@@ -118,11 +120,15 @@ def test_show_event_store_records_assistant_mark_and_transcript_message(isolated
assert event["scope"] == "default"
assert event["message_id"]
assert event["message"]["id"] == event["message_id"]
- # The user reads this one, so it says what happened and quotes copy they can
- # see on the page — never the synthetic target or the selector behind it.
- assert event["transcript_text"] == 'Page note · “Quarterly summary”\n\nReview this summary again.'
+ assert event["transcript_text"] == "Review this summary again."
assert "mark-default-summary" not in event["transcript_text"]
assert "[mark-default='summary']" not in event["transcript_text"]
+ assert event["message"]["type"] == "annotation"
+ assert event["message"]["content"]["annotation"] == {
+ "direction": "agent",
+ "action": "created",
+ "quote": "Quarterly summary",
+ }
with engine.connect() as conn:
event_row = conn.execute(select(show_session_events)).mappings().one()
@@ -140,6 +146,49 @@ def test_show_event_store_records_assistant_mark_and_transcript_message(isolated
assert last_active_at != previous_active_at
+ ("event_type", "payload", "direction"),
+ [
+ (
+ "human.annotation.created",
+ {"annotation": {"comment": "", "anchor": {"text": "Summary"}}},
+ "user",
+ ),
+ (
+ "assistant.mark.created",
+ {"mark": {"target": "#summary", "body": ""}, "anchor": {"text": "Summary"}},
+ "agent",
+ ),
+ ],
+)
+def test_annotation_card_can_have_empty_authored_text(
+ isolated_state,
+ event_type,
+ payload,
+ direction,
+):
+ _seed_session()
+ store = ShowSessionEventStore()
+ try:
+ event = store.append(
+ "ses_mark",
+ {"type": event_type, **payload},
+ )
+ finally:
+ store.close()
+
+ assert event["transcript_text"] == ""
+ assert event["message"]["text"] == ""
+ assert event["message"]["content"] == {
+ "text": "",
+ "annotation": {
+ "direction": direction,
+ "action": "created",
+ "quote": "Summary",
+ },
+ }
+
+
def test_show_event_store_records_human_annotation_with_anchor_context(isolated_state):
_seed_session()
@@ -170,9 +219,13 @@ def test_show_event_store_records_human_annotation_with_anchor_context(isolated_
assert event["payload"]["status"] == "pending"
assert event["payload"]["author"] == {"kind": "local"}
assert event["message_id"]
- assert "[show-annotation] question" in event["transcript_text"]
- assert "Clarify this claim." in event["transcript_text"]
- assert "Quote: Quarterly summary" in event["transcript_text"]
+ assert event["transcript_text"] == "Clarify this claim."
+ assert event["message"]["type"] == "annotation"
+ assert event["message"]["content"]["annotation"] == {
+ "direction": "user",
+ "action": "created",
+ "quote": "Quarterly summary",
+ }
engine = create_sqlite_engine()
with engine.connect() as conn:
@@ -372,10 +425,11 @@ def test_show_event_store_records_element_group_annotation_context(isolated_stat
assert event["payload"]["userRegion"]["width"] == 300
assert len(event["payload"]["matchedElements"]) == 2
assert event["anchor"]["selector"] == "[data-card='summary']"
- assert "Anchor kind: element-group" in event["transcript_text"]
- assert "Region: x:10, y:20, 300x120" in event["transcript_text"]
- assert "Selection: element-group" in event["transcript_text"]
- assert "Matched elements: 2" in event["transcript_text"]
+ assert event["transcript_text"] == "Align these cards."
+ assert event["message"]["metadata"]["anchor_kind"] == "element-group"
+ assert event["message"]["metadata"]["user_region"] == "x:10, y:20, 300x120"
+ assert event["message"]["metadata"]["classification"] == "element-group"
+ assert event["message"]["metadata"]["matched_element_count"] == 2
def test_show_event_store_materializes_screenshot_attachment(isolated_state):
@@ -418,8 +472,20 @@ def test_show_event_store_materializes_screenshot_attachment(isolated_state):
assert local_path.is_absolute()
assert local_path.parent == isolated_state / "attachments" / "avibe" / "ses_mark"
assert local_path.read_bytes() == raw
- assert f"Screenshot: {local_path} (4x3)" in event["transcript_text"]
- assert "Screenshot region: x:24, y:32, 640x360" in event["transcript_text"]
+ assert event["transcript_text"] == "Review the captured area."
+ assert event["message"]["content"]["attachments"] == [
+ {
+ "url": f"/api/media/{screenshot['attachmentId']}",
+ "name": "annotation-region.png",
+ "mime": "image/png",
+ "kind": "image",
+ "width": 4,
+ "height": 3,
+ }
+ ]
+ assert event["message"]["metadata"]["screenshot_region"] == (
+ "x:24, y:32, 640x360"
+ )
engine = create_sqlite_engine()
with engine.connect() as conn:
@@ -595,11 +661,18 @@ def test_show_event_store_records_screenshot_annotation_batch(isolated_state):
assert event["payload"]["primaryAnchor"] == "screenshot"
assert event["payload"]["screenshot"]["attachmentId"] == "show_asset_screenshot_1"
assert len(event["payload"]["screenshot"]["items"]) == 2
- assert "Anchor kind: screenshot" in event["transcript_text"]
- assert "Screenshot: show_asset_screenshot_1" in event["transcript_text"]
- assert "Screenshot region: x:24, y:32, 640x360" in event["transcript_text"]
- assert "1. This counter looks stale. (x:120, y:80)" in event["transcript_text"]
- assert "2. Crop this empty area. (x:420, y:240, 160x72)" in event["transcript_text"]
+ assert event["transcript_text"] == "Review the captured area."
+ dispatch_text = _format_dispatch_text(
+ event["type"],
+ event["payload"],
+ event["anchor"],
+ event_id=event["id"],
+ )
+ assert "Anchor kind: screenshot" in dispatch_text
+ assert "Screenshot: show_asset_screenshot_1" in dispatch_text
+ assert "Screenshot region: x:24, y:32, 640x360" in dispatch_text
+ assert "1. This counter looks stale. (x:120, y:80)" in dispatch_text
+ assert "2. Crop this empty area. (x:420, y:240, 160x72)" in dispatch_text
def test_show_event_store_records_annotation_resolution(isolated_state):
@@ -623,6 +696,41 @@ def test_show_event_store_records_annotation_resolution(isolated_state):
assert event["payload"]["id"] == "annotation_1"
assert event["payload"]["status"] == "resolved"
assert "resolved" in event["transcript_text"]
+ assert event["message_id"] is None
+ assert event["message"] is None
+
+
+ "event_type",
+ [
+ "human.annotation.updated",
+ "human.annotation.dismissed",
+ ],
+)
+def test_show_event_store_does_not_duplicate_forward_annotation_lifecycle(
+ isolated_state,
+ event_type,
+):
+ _seed_session()
+
+ store = ShowSessionEventStore()
+ try:
+ event = store.append(
+ "ses_mark",
+ {
+ "type": event_type,
+ "annotation": {
+ "id": "annotation_1",
+ "comment": "Existing annotation words.",
+ },
+ },
+ )
+ finally:
+ store.close()
+
+ assert event["transcript_text"]
+ assert event["message_id"] is None
+ assert event["message"] is None
def test_show_event_store_keeps_object_ids_separate_from_event_ids(isolated_state):
@@ -838,33 +946,35 @@ def test_show_event_store_records_assistant_page_update(isolated_state):
assert event["actor"] == "assistant"
assert event["message_id"]
+ assert event["message"]["type"] == "assistant"
assert "[show-page-updated] Updated the Show Page" in event["transcript_text"]
+def test_show_event_store_records_runtime_error_as_hidden_activity(isolated_state):
+ _seed_session()
+
+ store = ShowSessionEventStore()
+ try:
+ event = store.append(
+ "ses_mark",
+ {
+ "type": "system.runtime.error",
+ "payload": {"error": "Show Runtime failed to render."},
+ },
+ )
+ finally:
+ store.close()
+
+ assert event["actor"] == "system"
+ assert event["message"]["type"] == "assistant"
+ assert event["transcript_text"] == (
+ "[show-runtime-error] Show Runtime failed to render."
+ )
+
+
@pytest.mark.parametrize(
("event_type", "payload", "expected_header"),
[
- # The three mark rows pin the action wording. They also carry a `scope` and
- # a `target` that no header renders, so the rows below double as the
- # contrast this table exists to show: the very same `scope: "review"` that
- # is invisible to the user in a mark stays visible to the Agent in the
- # `[show-intent ...]` / `[show-annotation ...]` rows further down, because
- # only there is it something the reader can act on.
- (
- "assistant.mark.created",
- {"scope": "default", "target": "summary", "body": "Created."},
- "Page note",
- ),
- (
- "assistant.mark.resolved",
- {"scope": "default", "target": "summary", "body": "Resolved."},
- "Page note (resolved)",
- ),
- (
- "assistant.mark.updated",
- {"scope": "review", "target": "summary", "body": "Updated."},
- "Page note (updated)",
- ),
(
"human.intent.submitted",
{"scope": "default", "intent": "question", "text": "Why?"},
@@ -875,29 +985,13 @@ def test_show_event_store_records_assistant_page_update(isolated_state):
{"scope": "review", "intent": "question", "text": "Why?"},
"[show-intent scope=review] question",
),
- (
- "human.annotation.created",
- {"scope": "default", "intent": "question", "comment": "Why?"},
- "[show-annotation] question",
- ),
- (
- "human.annotation.resolved",
- {"scope": "default", "intent": "comment", "comment": "Done."},
- "[show-annotation resolved] comment",
- ),
- (
- "human.annotation.created",
- {"scope": "review", "intent": "question", "comment": "Why?"},
- "[show-annotation scope=review] question",
- ),
- (
- "human.annotation.resolved",
- {"scope": "review", "intent": "comment", "comment": "Done."},
- "[show-annotation resolved scope=review] comment",
- ),
],
)
-def test_show_event_transcript_headers_only_render_deviations(event_type, payload, expected_header):
+def test_show_intent_transcript_headers_only_render_deviations(
+ event_type,
+ payload,
+ expected_header,
+):
transcript = _format_transcript_text(event_type, payload, {})
assert transcript.splitlines()[0] == expected_header
@@ -928,7 +1022,7 @@ def test_assistant_mark_transcript_never_shows_the_mark_target(target):
"""
transcript = _format_transcript_text("assistant.mark.created", {"target": target, "body": "Aligned it."}, {})
- assert transcript == "Page note\n\nAligned it."
+ assert transcript == "Aligned it."
@pytest.mark.parametrize(
@@ -956,7 +1050,7 @@ def test_assistant_mark_transcript_never_shows_the_mark_scope(scope):
transcript = _format_transcript_text("assistant.mark.created", payload, {})
- assert transcript == "Page note\n\nAligned it."
+ assert transcript == "Aligned it."
def test_no_machine_field_of_a_mark_ever_reaches_the_chat():
@@ -983,12 +1077,12 @@ def test_no_machine_field_of_a_mark_ever_reaches_the_chat():
"assistant.mark.created", {**machine_text, "body": "Aligned it."}, {}
)
- assert transcript == "Page note\n\nAligned it."
+ assert transcript == "Aligned it."
for key, value in machine_text.items():
assert value not in transcript, f"{key} leaked into the chat"
-def test_assistant_mark_transcript_quotes_page_copy_the_user_can_see():
+def test_assistant_mark_card_quotes_page_copy_the_user_can_see():
"""The anchor is the only human source, so it is the only thing that locates."""
transcript = _format_transcript_text(
"assistant.mark.created",
@@ -996,19 +1090,31 @@ def test_assistant_mark_transcript_quotes_page_copy_the_user_can_see():
{"selector": "#root .cta-button", "text": "Get started"},
)
- assert transcript == "Page note · “Get started”\n\nAligned it."
+ display = _annotation_display(
+ "assistant.mark.created",
+ {"selector": "#root .cta-button", "text": "Get started"},
+ )
+ assert transcript == "Aligned it."
+ assert display["quote"] == "Get started"
assert "#root .cta-button" not in transcript
-def test_assistant_mark_transcript_renders_in_the_configured_language():
+def test_assistant_mark_title_is_not_localized_at_write_time():
transcript = _format_transcript_text(
"assistant.mark.updated",
{"target": "cta", "body": "改了按钮的对齐方式,和设计稿一致了"},
{"text": "开始使用"},
- lang="zh",
)
- assert transcript == "页面批注(已更新) ·「开始使用」\n\n改了按钮的对齐方式,和设计稿一致了"
+ assert transcript == "改了按钮的对齐方式,和设计稿一致了"
+ assert _annotation_display(
+ "assistant.mark.updated",
+ {"text": "开始使用"},
+ ) == {
+ "direction": "agent",
+ "action": "updated",
+ "quote": "开始使用",
+ }
def test_assistant_mark_transcript_keeps_the_whole_body():
@@ -1022,7 +1128,7 @@ def test_assistant_mark_transcript_keeps_the_whole_body():
assert transcript.endswith(body.strip())
-def test_assistant_mark_transcript_quotes_a_text_range_anchor():
+def test_assistant_mark_card_quotes_a_text_range_anchor():
"""`vibe show reply` copies the annotation anchor, which carries ``textQuote``."""
transcript = _format_transcript_text(
"assistant.mark.created",
@@ -1030,30 +1136,33 @@ def test_assistant_mark_transcript_quotes_a_text_range_anchor():
{"kind": "text-range", "selector": "#revenue-card", "textQuote": "Revenue"},
)
- assert transcript == "Page note · “Revenue”\n\nQ3 restated the figure."
+ display = _annotation_display(
+ "assistant.mark.created",
+ {"kind": "text-range", "selector": "#revenue-card", "textQuote": "Revenue"},
+ )
+ assert transcript == "Q3 restated the figure."
+ assert display["quote"] == "Revenue"
assert "#revenue-card" not in transcript
@pytest.mark.parametrize("copy_key", ANCHOR_HUMAN_COPY_KEYS)
-def test_both_transcript_directions_read_the_same_anchor_copy_fields(copy_key):
- """The user-facing and agent-facing formatters must agree on where copy lives.
+def test_both_annotation_directions_read_the_same_anchor_copy_fields(copy_key):
+ """The user-facing and agent-facing cards must agree on where copy lives.
Adding a third anchor copy field to one side and not the other silently drops
- the user's own words from whichever transcript forgot it, so pin both here.
+ the locator from whichever card forgot it, so pin both here.
"""
- mark = _format_transcript_text(
+ anchor = {"selector": "#revenue-card", copy_key: "Revenue"}
+ mark = _annotation_display(
"assistant.mark.created",
- {"target": "#revenue-card", "body": "Answered."},
- {"selector": "#revenue-card", copy_key: "Revenue"},
+ anchor,
)
- annotation = _format_transcript_text(
+ annotation = _annotation_display(
"human.annotation.created",
- {"comment": "Why?"},
- {"selector": "#revenue-card", copy_key: "Revenue"},
+ anchor,
)
- assert mark == "Page note · “Revenue”\n\nAnswered."
- assert "Quote: Revenue" in annotation
+ assert mark["quote"] == annotation["quote"] == "Revenue"
@pytest.mark.parametrize("anchor", [{}, {"text": ""}, {"selector": "#cta"}], ids=["absent", "blank", "selector-only"])
@@ -1061,36 +1170,38 @@ def test_assistant_mark_without_page_copy_is_just_the_agents_words(anchor):
"""No human locator available: say what happened, then get out of the way."""
transcript = _format_transcript_text("assistant.mark.created", {"target": "cta", "body": "Aligned it."}, anchor)
- assert transcript == "Page note\n\nAligned it."
+ assert transcript == "Aligned it."
+ assert _annotation_display("assistant.mark.created", anchor) == {
+ "direction": "agent",
+ "action": "created",
+ }
@pytest.mark.parametrize("copy_key", ANCHOR_HUMAN_COPY_KEYS)
def test_assistant_mark_condenses_every_locator_source(copy_key):
- """Whichever copy field fills the locator, the header stays one bounded line."""
- transcript = _format_transcript_text(
+ """Whichever copy field fills the locator, the card stays bounded."""
+ display = _annotation_display(
"assistant.mark.created",
- {"target": "cta", "body": "Aligned it."},
{copy_key: "Get\n started " + "x" * MARK_LOCATOR_MAX_LENGTH},
)
- header = transcript.splitlines()[0]
-
- assert header.startswith("Page note · “Get started x")
- assert header.endswith("…”")
- assert len(transcript.splitlines()) == 3 # header, blank, body
-
-
-def test_every_assistant_mark_event_has_a_plain_language_label():
- """Adding a fourth mark event must fail here, not leak a raw key into chat."""
- from vibe.i18n import get_supported_languages, t as i18n_t
-
- assert set(ASSISTANT_MARK_TRANSCRIPT_I18N_KEYS) == ASSISTANT_MARK_EVENT_TYPES
- for lang in get_supported_languages():
- for key in ASSISTANT_MARK_TRANSCRIPT_I18N_KEYS.values():
- assert i18n_t(key, lang) != key
+ quote = display["quote"]
+ assert quote.startswith("Get started x")
+ assert quote.endswith("…")
+ assert len(quote) == MARK_LOCATOR_MAX_LENGTH
+
+
+def test_every_assistant_mark_event_has_annotation_display_data():
+ assert {
+ event_type: _annotation_display(event_type, {})
+ for event_type in ASSISTANT_MARK_EVENT_TYPES
+ } == {
+ "assistant.mark.created": {"direction": "agent", "action": "created"},
+ "assistant.mark.updated": {"direction": "agent", "action": "updated"},
+ "assistant.mark.resolved": {"direction": "agent", "action": "resolved"},
+ }
-def test_appended_mark_speaks_the_users_configured_language(isolated_state):
- """The store has no controller, so prove it still reaches the saved language."""
+def test_appended_mark_stores_direction_instead_of_localized_title(isolated_state):
from config.v2_config import (
AgentsConfig,
PlatformsConfig,
@@ -1126,7 +1237,12 @@ def test_appended_mark_speaks_the_users_configured_language(isolated_state):
finally:
store.close()
- assert event["transcript_text"] == "页面批注 ·「开始使用」\n\n按钮对齐改好了"
+ assert event["transcript_text"] == "按钮对齐改好了"
+ assert event["message"]["content"]["annotation"] == {
+ "direction": "agent",
+ "action": "created",
+ "quote": "开始使用",
+ }
def test_show_event_store_rejects_unknown_session(isolated_state):
@@ -1218,10 +1334,16 @@ def test_dispatching_show_event_reserves_pending_transcript_row(isolated_state):
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"
+ assert non_dispatching["message"]["type"] == messages_service.ANNOTATION_TYPE
engine = create_sqlite_engine()
with engine.connect() as conn:
- visible = messages_service.list_session_messages(conn, session_id="ses_show", types=("user",))
+ visible = messages_service.list_session_messages(
+ conn,
+ session_id="ses_show",
+ limit=50,
+ types=messages_service.TRANSCRIPT_TYPES,
+ tail=True,
+ )
queued = messages_service.list_queued(conn, "ses_show")
assert [message["text"] for message in visible["messages"]] == [non_dispatching["transcript_text"]]
assert queued == []
@@ -1350,7 +1472,7 @@ def test_localized_show_event_errors_follow_configured_language(
assert str(pending) == "Show 事件可能仍在处理中,未在本地重复提交。"
-def test_direct_dispatching_show_event_is_visible_harness_input(isolated_state):
+def test_direct_dispatching_show_event_is_visible_annotation_input(isolated_state):
from storage import messages_service
_seed_session("ses_show")
@@ -1371,7 +1493,7 @@ def test_direct_dispatching_show_event_is_visible_harness_input(isolated_state):
finally:
store.close()
- assert event["message"]["type"] == messages_service.HARNESS_TYPE
+ assert event["message"]["type"] == messages_service.ANNOTATION_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"]]
@@ -1413,8 +1535,8 @@ def test_startup_repairs_stranded_pending_rows_by_origin(isolated_state):
text="Recover my chat prompt after restart.",
)
- # One startup sweep handles cleanup for both origins, but only Chat can become
- # visible without proving dispatch acceptance. Show stays retryable.
+ # Ordinary Chat becomes visible. Harness-owned Show input stays retryable
+ # because startup has no queue drain that owns it.
summary = ui_server._recover_stale_pending_messages()
assert summary == {"promoted": 1, "deleted": 0, "skipped": 1}
@@ -1424,12 +1546,16 @@ def test_startup_repairs_stranded_pending_rows_by_origin(isolated_state):
for row in messages_service.list_session_messages(
conn,
session_id="ses_show_restart",
+ limit=50,
types=messages_service.TRANSCRIPT_TYPES,
+ tail=True,
)["messages"]
}
+ queued = messages_service.list_queued(conn, "ses_show_restart")
assert repaired[chat_message["id"]]["type"] == "user"
assert repaired[chat_message["id"]]["author"] == "user"
assert show_event["message_id"] not in repaired
+ assert queued == []
store = ShowSessionEventStore()
try:
@@ -1438,12 +1564,16 @@ def test_startup_repairs_stranded_pending_rows_by_origin(isolated_state):
store.close()
assert retryable is not None
assert retryable["message"]["type"] == messages_service.PENDING_TYPE
+ assert retryable["message"]["metadata"][
+ messages_service.QUEUED_DISPATCH_TEXT_KEY
+ ].startswith("[show-annotation] comment")
def test_record_local_show_event_uses_synchronous_unified_entry(
isolated_state,
monkeypatch,
):
+ from storage import messages_service
from vibe import internal_client, ui_server
from vibe.sse_broker import broker
@@ -1470,8 +1600,16 @@ def test_record_local_show_event_uses_synchronous_unified_entry(
)
assert dispatches[0]["user_message_id"] == event["message_id"]
+ assert dispatches[0]["text"].startswith(
+ "[show-annotation] comment\n\nDeliver this."
+ )
+ assert f"Show event id: {event['id']}" in dispatches[0]["text"]
+ assert (
+ messages_service.QUEUED_DISPATCH_TEXT_KEY
+ not in event["message"]["metadata"]
+ )
assert "dispatch_owner" not in dispatches[0]
- assert event["message"]["type"] == "harness"
+ assert event["message"]["type"] == "annotation"
assert [name for name, _data in published] == [
"show.event",
"message.new",
@@ -1515,19 +1653,23 @@ def test_failed_local_show_dispatch_keeps_row_pending_so_replay_retries(
stranded = messages_service.list_session_messages(
conn,
session_id="ses_show",
+ limit=50,
types=messages_service.TRANSCRIPT_TYPES,
+ tail=True,
)
assert stranded["messages"] == []
replay = ui_server.record_local_show_event("ses_show", payload)
assert attempts == 2
- assert replay["message"]["type"] == messages_service.HARNESS_TYPE
+ assert replay["message"]["type"] == messages_service.ANNOTATION_TYPE
with create_sqlite_engine().connect() as conn:
visible = messages_service.list_session_messages(
conn,
session_id="ses_show",
+ limit=50,
types=messages_service.TRANSCRIPT_TYPES,
+ tail=True,
)
assert [row["id"] for row in visible["messages"]] == [replay["message_id"]]
@@ -1567,7 +1709,7 @@ def test_ambiguous_local_show_dispatch_replays_under_the_same_reservation(
assert len(seen_message_ids) == 2
assert seen_message_ids[0] == seen_message_ids[1]
- assert replay["message"]["type"] == messages_service.HARNESS_TYPE
+ assert replay["message"]["type"] == messages_service.ANNOTATION_TYPE
@pytest.mark.parametrize(
@@ -1582,23 +1724,21 @@ def test_ambiguous_local_show_dispatch_replays_under_the_same_reservation(
],
)
def test_annotation_dispatch_text_adds_event_id_and_optional_reply_guidance(intent, expects_guidance):
- from vibe import ui_server
-
label = intent or "comment"
- event = {
- "id": "show_evt_1a2b3c4d",
- "type": "human.annotation.created",
- "session_id": "ses_show",
- "scope_id": "scope1",
- "payload": {"intent": intent} if intent is not None else {},
- "transcript_text": f"[show-annotation] {label}\n\nReview this.",
- "message_id": "m1",
- "message": {"id": "m1", "type": "pending"},
+ payload = {
+ "comment": "Review this.",
+ **({"intent": intent} if intent is not None else {}),
}
+ dispatch_text = _format_dispatch_text(
+ "human.annotation.created",
+ payload,
+ {},
+ event_id="show_evt_1a2b3c4d",
+ )
- dispatch_text = ui_server._show_event_dispatch_text(event)
-
- assert event["transcript_text"] == f"[show-annotation] {label}\n\nReview this."
+ assert dispatch_text.startswith(
+ f"[show-annotation] {label}\n\nReview this."
+ )
assert "Show event id: show_evt_1a2b3c4d" in dispatch_text
guidance = (
"如需在页面上原位回应,可执行:\n"
@@ -1608,3 +1748,179 @@ def test_annotation_dispatch_text_adds_event_id_and_optional_reply_guidance(inte
assert (guidance in dispatch_text) is expects_guidance
if expects_guidance:
assert dispatch_text.endswith(guidance)
+
+
+def test_annotation_builders_match_frozen_examples():
+ from storage import messages_service
+
+ # This docs fixture is the single authoritative row copy shared by both lanes.
+ fixture_path = (
+ Path(__file__).parents[1]
+ / "docs/plans/show-annotation-message-type/examples.json"
+ )
+ fixture = json.loads(fixture_path.read_text(encoding="utf-8"))
+ frozen_fields = fixture["_frozen_fields"]
+ frozen_rows = [
+ example["row"]
+ for example in fixture["examples"]
+ ]
+
+ forward = frozen_rows[0]
+ forward_anchor = {
+ "selector": forward["metadata"]["anchor_selector"],
+ "text": forward["content"]["annotation"]["quote"],
+ }
+ forward_payload = {
+ "scope": forward["metadata"]["show_event_scope"],
+ "intent": "comment",
+ "comment": forward["text"],
+ "primaryAnchor": forward["metadata"]["anchor_kind"],
+ }
+
+ queued = frozen_rows[1]
+ queued_attachment = queued["content"]["attachments"][0]
+ queued_dispatch = queued["metadata"][messages_service.QUEUED_DISPATCH_TEXT_KEY]
+ screenshot_line = next(
+ line for line in queued_dispatch.splitlines() if line.startswith("Screenshot: ")
+ )
+ assert screenshot_line == (
+ "Screenshot: state/media/med_9a71c33f8b2e.png (1240x620)"
+ )
+ origin_x, origin_y, dimensions = queued["metadata"]["screenshot_region"].split(
+ ", "
+ )
+ width, height = dimensions.split("x", 1)
+ screenshot_region = {
+ "x": int(origin_x.removeprefix("x:")),
+ "y": int(origin_y.removeprefix("y:")),
+ "width": int(width),
+ "height": int(height),
+ }
+ queued_payload = {
+ "scope": queued["metadata"]["show_event_scope"],
+ "intent": "comment",
+ "comment": queued["text"],
+ "primaryAnchor": queued["metadata"]["anchor_kind"],
+ "screenshot": {
+ "attachmentId": queued_attachment["url"].removeprefix("/api/media/"),
+ "path": "state/media/med_9a71c33f8b2e.png",
+ "mimeType": queued_attachment["mime"],
+ "width": queued_attachment["width"],
+ "height": queued_attachment["height"],
+ "region": screenshot_region,
+ },
+ }
+
+ produced_rows = [
+ {
+ "type": messages_service.ANNOTATION_TYPE,
+ "author": messages_service.HARNESS_TYPE,
+ "content": {
+ "text": _format_transcript_text(
+ forward["metadata"]["show_event_type"],
+ forward_payload,
+ forward_anchor,
+ ),
+ "annotation": _annotation_display(
+ forward["metadata"]["show_event_type"],
+ forward_anchor,
+ ),
+ },
+ "metadata": {
+ messages_service.QUEUED_DISPATCH_TEXT_KEY: _format_dispatch_text(
+ forward["metadata"]["show_event_type"],
+ forward_payload,
+ forward_anchor,
+ event_id=forward["metadata"]["show_event_id"],
+ )
+ },
+ },
+ {
+ "type": messages_service.QUEUED_TYPE,
+ "author": messages_service.HARNESS_TYPE,
+ "content": {
+ "text": _format_transcript_text(
+ queued["metadata"]["show_event_type"],
+ queued_payload,
+ {},
+ ),
+ "annotation": _annotation_display(
+ queued["metadata"]["show_event_type"],
+ {},
+ ),
+ "attachments": _annotation_attachments(queued_payload),
+ },
+ "metadata": {
+ messages_service.QUEUED_DISPATCH_TEXT_KEY: _format_dispatch_text(
+ queued["metadata"]["show_event_type"],
+ queued_payload,
+ {},
+ event_id=queued["metadata"]["show_event_id"],
+ )
+ },
+ },
+ ]
+
+ for frozen in frozen_rows[2:]:
+ event_type = frozen["metadata"]["show_event_type"]
+ quote = frozen["content"]["annotation"].get("quote")
+ anchor = {"text": quote} if quote else {}
+ produced_rows.append(
+ {
+ "type": messages_service.ANNOTATION_TYPE,
+ "author": "agent",
+ "content": {
+ "text": _format_transcript_text(
+ event_type,
+ {"body": frozen["text"]},
+ anchor,
+ ),
+ "annotation": _annotation_display(event_type, anchor),
+ },
+ "metadata": {},
+ }
+ )
+
+ def frozen_value(row, path):
+ current = row
+ for part in path.split("."):
+ if not isinstance(current, dict) or part not in current:
+ return False, None
+ current = current[part]
+ return True, current
+
+ assert frozen_fields == [
+ "type",
+ "author",
+ "content.text",
+ "content.annotation",
+ "content.attachments",
+ "metadata._queued_dispatch_text",
+ ]
+ for produced, frozen in zip(produced_rows, frozen_rows, strict=True):
+ for field in frozen_fields:
+ produced_present, produced_value = frozen_value(produced, field)
+ frozen_present, frozen_value_at_path = frozen_value(frozen, field)
+ assert produced_present is frozen_present, field
+ if field == "metadata._queued_dispatch_text":
+ # The prompt body is machine-only; its presence is the contract.
+ continue
+ assert produced_value == frozen_value_at_path, field
+
+ machine_markers = (
+ "[show-annotation]",
+ "Anchor kind:",
+ "Quote:",
+ "Anchor:",
+ "Screenshot:",
+ "Screenshot region:",
+ "Show event id:",
+ "vibe show reply",
+ )
+ for produced in produced_rows[:2]:
+ display_text = produced["content"]["text"]
+ dispatch_text = produced["metadata"][
+ messages_service.QUEUED_DISPATCH_TEXT_KEY
+ ]
+ assert display_text in dispatch_text
+ assert all(marker not in display_text for marker in machine_markers)
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index c494da48c..cfd0af363 100644
--- a/tests/test_sqlite_state_migration.py
+++ b/tests/test_sqlite_state_migration.py
@@ -1,6 +1,7 @@
from __future__ import annotations
from concurrent.futures import ThreadPoolExecutor
+from importlib import import_module
import json
import re
import sqlite3
@@ -24,7 +25,7 @@ from storage.settings_service import SQLiteSettingsService
from vibe.message_types import build_partial_index_predicate
-HEAD_REVISION = "20260726_0037"
+HEAD_REVISION = "20260727_0038"
MESSAGE_PARTIAL_INDEX_PREDICATES = {
"ix_messages_inbox_activity": (
"session_id is not null and type not in "
@@ -35,7 +36,8 @@ MESSAGE_PARTIAL_INDEX_PREDICATES = {
),
"ix_messages_inbox_user_send": (
"session_id is not null and ((author = 'user' and type = 'user') "
- "or (author = 'harness' and type = 'harness'))"
+ "or (author = 'harness' and type = 'harness') "
+ "or (author = 'harness' and type = 'annotation'))"
),
}
@@ -66,6 +68,16 @@ def test_message_partial_index_ddl_matches_catalog_contract(
)
+def test_show_annotation_migration_predicate_matches_catalog() -> None:
+ migration = import_module(
+ "storage.alembic.versions.20260727_0038_show_annotation_type"
+ )
+
+ assert migration.UPGRADE_USER_SEND_PREDICATE == build_partial_index_predicate(
+ "ix_messages_inbox_user_send"
+ )
+
+
class _Pre335Cursor(sqlite3.Cursor):
def execute(self, sql, parameters=()):
normalized = " ".join(str(sql).upper().split())
@@ -494,6 +506,102 @@ def test_retirement_marker_migration_is_forward_only(tmp_path: Path) -> None:
assert version == (HEAD_REVISION,)
+def test_show_annotation_migration_changes_only_the_user_send_index(
+ tmp_path: Path,
+) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path, revision="20260726_0037")
+ now = "2026-07-27T00:00:00Z"
+ legacy_payloads = [
+ ("agent", "assistant", "assistant.mark.created")
+ for _ in range(5)
+ ]
+ legacy_payloads.extend(
+ [
+ ("agent", "assistant", "assistant.mark.updated"),
+ ("agent", "assistant", "assistant.mark.resolved"),
+ ]
+ )
+ legacy_payloads.extend(
+ ("harness", "harness", "human.annotation.created")
+ for _ in range(10)
+ )
+ legacy_payloads.extend(
+ ("user", "user", "human.annotation.created")
+ for _ in range(10)
+ )
+ assert len(legacy_payloads) == 27
+
+ with sqlite3.connect(db_path) as conn:
+ for index, (author, message_type, show_event_type) in enumerate(
+ legacy_payloads
+ ):
+ conn.execute(
+ """
+ insert into messages (
+ id, platform, author, type, content_text, content_json,
+ metadata_json, created_at, updated_at
+ ) values (?, 'avibe', ?, ?, ?, ?, ?, ?, ?)
+ """,
+ (
+ f"legacy_message_{index:02d}",
+ author,
+ message_type,
+ f"legacy text {index}",
+ json.dumps({"ordinal": index}, separators=(",", ":")),
+ json.dumps(
+ {
+ "source": "show_page",
+ "show_event_type": show_event_type,
+ },
+ separators=(",", ":"),
+ ),
+ now,
+ now,
+ ),
+ )
+ conn.commit()
+ original_rows = conn.execute(
+ "select * from messages order by id"
+ ).fetchall()
+ original_index = _index_sql(conn, "ix_messages_inbox_user_send")
+
+ migration = import_module(
+ "storage.alembic.versions.20260727_0038_show_annotation_type"
+ )
+ assert original_index.endswith(migration.DOWNGRADE_USER_SEND_PREDICATE)
+
+ run_migrations(db_path)
+
+ with sqlite3.connect(db_path) as conn:
+ upgraded_rows = conn.execute(
+ "select * from messages order by id"
+ ).fetchall()
+ user_send_index = _index_sql(conn, "ix_messages_inbox_user_send")
+ version = conn.execute("select version_num from alembic_version").fetchone()
+
+ assert upgraded_rows == original_rows
+ assert user_send_index.endswith(
+ MESSAGE_PARTIAL_INDEX_PREDICATES["ix_messages_inbox_user_send"]
+ )
+ assert "(platform, session_id, created_at desc, id desc)" in user_send_index
+ assert version == (HEAD_REVISION,)
+
+ command.downgrade(migrations.alembic_config(db_path), "20260726_0037")
+
+ with sqlite3.connect(db_path) as conn:
+ downgraded_rows = conn.execute(
+ "select * from messages order by id"
+ ).fetchall()
+ user_send_index = _index_sql(conn, "ix_messages_inbox_user_send")
+ version = conn.execute("select version_num from alembic_version").fetchone()
+
+ assert downgraded_rows == original_rows
+ assert user_send_index.endswith(migration.DOWNGRADE_USER_SEND_PREDICATE)
+ assert "(platform, session_id, created_at desc, id desc)" in user_send_index
+ assert version == ("20260726_0037",)
+
+
def test_session_pinning_migration_preserves_existing_sessions_as_unpinned(tmp_path: Path) -> None:
db_path = tmp_path / "vibe.sqlite"
run_migrations(db_path, revision="20260723_0033")
diff --git a/tests/test_ui_session_stream.py b/tests/test_ui_session_stream.py
index 64a505616..7b48c738c 100644
--- a/tests/test_ui_session_stream.py
+++ b/tests/test_ui_session_stream.py
@@ -415,7 +415,7 @@ def test_recover_stale_pending_keeps_show_owned_rows_retryable(
isolated_state,
tmp_path,
):
- """Startup cannot make an unaccepted Show reservation look dispatched."""
+ """Startup must not claim an unaccepted Show reservation was queued."""
from core.show_session_events import ShowSessionEventStore
from vibe import ui_server
@@ -450,6 +450,9 @@ def test_recover_stale_pending_keeps_show_owned_rows_retryable(
store.close()
assert recovered is not None
assert recovered["message"]["type"] == messages_service.PENDING_TYPE
+ assert recovered["message"]["metadata"][
+ messages_service.QUEUED_DISPATCH_TEXT_KEY
+ ].startswith("[show-annotation] comment")
publish.assert_not_called()
diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.py
index f73823082..01810de70 100644
--- a/tests/test_ui_show_pages.py
+++ b/tests/test_ui_show_pages.py
@@ -2110,7 +2110,9 @@ def test_private_show_page_idle_dispatch_promotes_visible_harness_row(monkeypatc
transcript = messages_service.list_session_messages(
conn,
session_id="ses123",
+ limit=50,
types=messages_service.TRANSCRIPT_TYPES,
+ tail=True,
)
assert [message["id"] for message in transcript["messages"]] == [
response.get_json()["event"]["message_id"]
@@ -2166,7 +2168,7 @@ def test_private_show_page_waits_for_turn_acceptance_before_responding(monkeypat
assert not request_thread.is_alive()
assert result["response"].status_code == 201
- assert result["response"].get_json()["event"]["message"]["type"] == "harness"
+ assert result["response"].get_json()["event"]["message"]["type"] == "annotation"
assert dispatch_kwargs == {"timeout": None}
@@ -2265,6 +2267,136 @@ def test_private_show_page_concurrent_dispatch_replay_returns_pending(
assert body["event"]["message"]["type"] == messages_service.PENDING_TYPE
+def test_legacy_settled_show_dispatch_replay_does_not_require_reserved_prompt(
+ monkeypatch,
+):
+ from storage import messages_service
+
+ async def unexpected_dispatch(*_args, **_kwargs):
+ pytest.fail("a settled legacy Show input must not dispatch again")
+
+ monkeypatch.setattr("vibe.internal_client.dispatch_async", unexpected_dispatch)
+ outcome = asyncio.run(
+ ui_server._run_show_event_dispatch(
+ {
+ "id": "show_evt_legacy_settled",
+ "session_id": "ses123",
+ "message": {
+ "id": "msg_legacy_settled",
+ "type": messages_service.HARNESS_TYPE,
+ "metadata": {},
+ },
+ }
+ )
+ )
+
+ assert outcome is ui_server._ShowEventDispatchOutcome.ACCEPTED
+
+
+def test_legacy_pending_show_dispatch_replays_stored_prompt(monkeypatch):
+ from storage import messages_service
+
+ dispatched = {}
+
+ async def accept_dispatch(payload, **_kwargs):
+ dispatched.update(payload)
+ return {"status_code": 202, "body": {"ok": True}}
+
+ monkeypatch.setattr("vibe.internal_client.dispatch_async", accept_dispatch)
+ monkeypatch.setattr(
+ ui_server,
+ "_settle_show_event_message",
+ lambda _event: {"type": messages_service.HARNESS_TYPE},
+ )
+ outcome = asyncio.run(
+ ui_server._run_show_event_dispatch(
+ {
+ "id": "show_evt_legacy_pending",
+ "session_id": "ses123",
+ "type": "human.annotation.created",
+ "transcript_text": "[show-annotation] comment\n\nLegacy prompt",
+ "payload": {"intent": "comment"},
+ "message": {
+ "id": "msg_legacy_pending",
+ "type": messages_service.PENDING_TYPE,
+ "content": {
+ "text": "[show-annotation] comment\n\nLegacy prompt",
+ },
+ "metadata": {},
+ },
+ }
+ )
+ )
+
+ assert outcome is ui_server._ShowEventDispatchOutcome.ACCEPTED
+ assert dispatched["text"] == (
+ "[show-annotation] comment\n\nLegacy prompt\n\n"
+ "Show event id: show_evt_legacy_pending\n\n"
+ "如需在页面上原位回应,可执行:\n"
+ " vibe show reply show_evt_legacy_pending --message '<你的回答>'\n"
+ "(也可以直接修改页面内容来响应,按场景选择。)"
+ )
+
+
+def test_current_pending_annotation_never_dispatches_display_body(monkeypatch):
+ from storage import messages_service
+
+ async def unexpected_dispatch(*_args, **_kwargs):
+ pytest.fail("a current annotation without its reserved prompt must not dispatch")
+
+ monkeypatch.setattr("vibe.internal_client.dispatch_async", unexpected_dispatch)
+ outcome = asyncio.run(
+ ui_server._run_show_event_dispatch(
+ {
+ "id": "show_evt_missing_prompt",
+ "session_id": "ses123",
+ "type": "human.annotation.created",
+ "transcript_text": "Visible words only",
+ "message": {
+ "id": "msg_missing_prompt",
+ "type": messages_service.PENDING_TYPE,
+ "content": {
+ "text": "Visible words only",
+ "annotation": {
+ "direction": "user",
+ "action": "created",
+ },
+ },
+ "metadata": {},
+ },
+ }
+ )
+ )
+
+ assert outcome is ui_server._ShowEventDispatchOutcome.FAILED
+
+
+def test_pending_show_dispatch_rejects_whitespace_only_reserved_prompt(monkeypatch):
+ from storage import messages_service
+
+ async def unexpected_dispatch(*_args, **_kwargs):
+ pytest.fail("a blank Show prompt must not start a turn")
+
+ monkeypatch.setattr("vibe.internal_client.dispatch_async", unexpected_dispatch)
+ outcome = asyncio.run(
+ ui_server._run_show_event_dispatch(
+ {
+ "id": "show_evt_blank_prompt",
+ "session_id": "ses123",
+ "message": {
+ "id": "msg_blank_prompt",
+ "type": messages_service.PENDING_TYPE,
+ "metadata": {
+ messages_service.QUEUED_DISPATCH_TEXT_KEY: " \n\t ",
+ },
+ },
+ }
+ )
+ )
+
+ assert outcome is ui_server._ShowEventDispatchOutcome.FAILED
+
+
def test_private_show_page_returns_promoted_row_after_synchronous_queue_drain(
monkeypatch,
tmp_path,
@@ -2332,7 +2464,7 @@ 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"] == "harness"
+ assert event["message"]["type"] == "annotation"
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
@@ -2389,7 +2521,9 @@ def test_private_show_page_busy_dispatch_queues_without_message_new(monkeypatch,
transcript = messages_service.list_session_messages(
conn,
session_id="ses123",
+ limit=50,
types=messages_service.TRANSCRIPT_TYPES,
+ tail=True,
)
assert [(message["id"], message["text"]) for message in queued] == [
(message_id, response.get_json()["event"]["transcript_text"])
@@ -2427,7 +2561,7 @@ def test_private_show_page_non_dispatching_annotation_stays_immediately_visible(
)
assert response.status_code == 201
- assert response.get_json()["event"]["message"]["type"] == "user"
+ assert response.get_json()["event"]["message"]["type"] == "annotation"
assert [event_type for event_type, _data in published] == [
"show.event",
"message.new",
@@ -2435,6 +2569,104 @@ def test_private_show_page_non_dispatching_annotation_stays_immediately_visible(
]
+def test_private_show_page_reverse_mark_publishes_live_annotation(
+ monkeypatch,
+ tmp_path,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_agent_session("ses123")
+ _create_show_page("ses123", "private")
+ token = "session-write-token"
+ monkeypatch.setattr(
+ "vibe.ui_server.show_event_write_token",
+ lambda session_id: token,
+ )
+ published = []
+ monkeypatch.setattr(
+ "vibe.sse_broker.broker.publish",
+ lambda event_type, data: published.append((event_type, data)),
+ )
+
+ response = app.test_client().post(
+ "/show/ses123/__show/events",
+ base_url="http://127.0.0.1:5123",
+ headers={
+ "Origin": "http://127.0.0.1:5123",
+ "Content-Type": "application/json",
+ "X-Vibe-Show-Token": token,
+ },
+ json={
+ "type": "assistant.mark.created",
+ "mark": {
+ "target": "#summary",
+ "body": "Updated the summary.",
+ },
+ "anchor": {
+ "selector": "#summary",
+ "text": "Quarterly summary",
+ },
+ },
+ )
+
+ assert response.status_code == 201
+ message = response.get_json()["event"]["message"]
+ assert message["type"] == "annotation"
+ assert message["author"] == "agent"
+ assert message["source"] is None
+ assert message["text"] == "Updated the summary."
+ assert message["content"]["annotation"] == {
+ "direction": "agent",
+ "action": "created",
+ "quote": "Quarterly summary",
+ }
+ assert [
+ data["type"]
+ for event_type, data in published
+ if event_type == "message.new"
+ ] == ["annotation"]
+
+
+ ("message_type", "expects_message"),
+ [
+ ("annotation", True),
+ ("assistant", False),
+ ],
+)
+def test_show_event_live_publish_uses_catalog_transcript_gate(
+ monkeypatch,
+ message_type,
+ expects_message,
+):
+ published = []
+ monkeypatch.setattr(
+ "vibe.sse_broker.broker.publish",
+ lambda event_type, data: published.append((event_type, data)),
+ )
+
+ ui_server._publish_show_session_event(
+ {
+ "id": "show_evt_publish_gate",
+ "session_id": "ses123",
+ "scope_id": "scope1",
+ "type": "assistant.page.updated",
+ "actor": "assistant",
+ "payload": {},
+ "message": {
+ "id": "msg_publish_gate",
+ "type": message_type,
+ },
+ }
+ )
+
+ assert (
+ "message.new" in [event_type for event_type, _data in published]
+ ) is expects_message
+ assert [event_type for event_type, _data in published][0] == "show.event"
+ assert [event_type for event_type, _data in published][-1] == "session.activity"
+
+
def test_private_show_page_publishes_annotation_control_without_message_or_dispatch(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config(tmp_path)
@@ -2531,6 +2763,17 @@ def test_private_show_page_dispatches_screenshot_annotation_batch(monkeypatch, t
assert "dataUrl" not in screenshot
assert screenshot["attachmentId"] != "show_asset_screenshot_1"
assert Path(screenshot["path"]).read_bytes() == raw
+ assert event["message"]["text"] == "Review this screenshot batch."
+ assert event["message"]["content"]["attachments"] == [
+ {
+ "url": f"/api/media/{screenshot['attachmentId']}",
+ "name": "annotation-region.png",
+ "mime": "image/png",
+ "kind": "image",
+ "width": 4,
+ "height": 3,
+ }
+ ]
asyncio.run(asyncio.wait_for(dispatch_done.wait(), timeout=1))
assert dispatches
transcript = dispatches[0]["text"]
@@ -2994,7 +3237,7 @@ def test_cli_show_event_dispatch_waits_for_unambiguous_acceptance(monkeypatch, t
assert not request_thread.is_alive()
assert result["response"].status_code == 201
- assert result["response"].get_json()["event"]["message"]["type"] == "harness"
+ assert result["response"].get_json()["event"]["message"]["type"] == "annotation"
def test_cli_show_event_ingress_requires_cli_token(monkeypatch, tmp_path):
@@ -3354,14 +3597,25 @@ def test_public_show_page_redacts_materialized_screenshot_path(monkeypatch, tmp_
internal_event = published[0]
internal_screenshot = internal_event["payload"]["screenshot"]
assert Path(internal_screenshot["path"]).is_file()
- assert internal_screenshot["path"] in internal_event["transcript_text"]
+ assert internal_event["transcript_text"] == "Review this screenshot."
+ assert internal_screenshot["path"] not in internal_event["transcript_text"]
+ assert internal_event["message"]["content"]["attachments"] == [
+ {
+ "url": f"/api/media/{internal_screenshot['attachmentId']}",
+ "name": "annotation-region.png",
+ "mime": "image/png",
+ "kind": "image",
+ "width": 4,
+ "height": 3,
+ }
+ ]
public_event = response.get_json()["event"]
public_screenshot = public_event["payload"]["screenshot"]
assert "path" not in public_screenshot
assert public_screenshot["attachmentId"] == internal_screenshot["attachmentId"]
assert internal_screenshot["path"] not in public_event["transcript_text"]
- assert f"Screenshot: {internal_screenshot['attachmentId']} (4x3)" in public_event["transcript_text"]
+ assert public_event["transcript_text"] == "Review this screenshot."
assert public_screenshot["url"] == (
f"/p/{share_id}/__show/media/{internal_screenshot['attachmentId']}"
)
diff --git a/ui/src/components/workbench/AnnotationMessage.test.tsx b/ui/src/components/workbench/AnnotationMessage.test.tsx
new file mode 100644
index 000000000..3f8a9faea
--- /dev/null
+++ b/ui/src/components/workbench/AnnotationMessage.test.tsx
@@ -0,0 +1,113 @@
+import { createInstance } from 'i18next';
+import type { ReactNode } from 'react';
+import { renderToStaticMarkup } from 'react-dom/server';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { describe, expect, it } from 'vitest';
+
+import en from '../../i18n/en.json';
+import zh from '../../i18n/zh.json';
+import type { AnnotationView } from '../../lib/annotationView';
+import { AnnotationMessage } from './AnnotationMessage';
+import { AGENT_BUBBLE, USER_BUBBLE } from './chatBubble';
+
+const instance = (lng: 'en' | 'zh') => {
+ const i18n = createInstance();
+ void i18n.use(initReactI18next).init({
+ lng,
+ fallbackLng: 'en',
+ resources: { en: { translation: en }, zh: { translation: zh } },
+ interpolation: { escapeValue: false },
+ });
+ return i18n;
+};
+
+const render = (view: AnnotationView, lng: 'en' | 'zh' = 'en', body: ReactNode = <p>Body</p>) =>
+ renderToStaticMarkup(
+ <I18nextProvider i18n={instance(lng)}>
+ <AnnotationMessage
+ messageId="msg_01J8XK2Q4W"
+ view={view}
+ body={body}
+ attachments={<img alt="" src="/api/media/med_9a71c33f8b2e" />}
+ time={<span>12:04</span>}
+ rowClass={(extra) => `flex w-full ${extra}`}
+ />
+ </I18nextProvider>,
+ );
+
+const USER: AnnotationView = { direction: 'user', resolved: false };
+const AGENT: AnnotationView = { direction: 'agent', resolved: false };
+
+describe('AnnotationMessage', () => {
+ // Rule 01. The side is direction, full stop — the component is never told who
+ // authored the row, so there is nothing else it could side on.
+ it('sides the card by direction', () => {
+ expect(render(USER)).toContain('justify-end');
+ expect(render(AGENT)).toContain('justify-start');
+ });
+
+ // Rule 02: exactly two titles, and the action never enters them.
+ it('titles the card by direction only, in the UI language', () => {
+ expect(render(USER)).toContain('User annotation');
+ expect(render(AGENT)).toContain('Agent annotation');
+ expect(render(USER, 'zh')).toContain('用户批注');
+ expect(render(AGENT, 'zh')).toContain('Agent 批注');
+ });
+
+ it('keeps the title the same for a resolved mark', () => {
+ const html = render({ ...AGENT, resolved: true });
+ expect(html).toContain('Agent annotation');
+ expect(html).not.toContain('User annotation');
+ });
+
+ // Rule 03: the bubble IS the column's existing bubble. Asserting against the
+ // shared constants rather than a copied class string means a future restyle of
+ // the ordinary bubbles carries the card with it and cannot leave it behind.
+ it('reuses the transcript bubble the row would otherwise have drawn', () => {
+ // The Tailwind arbitrary-variant classes carry ``&``, which React escapes in
+ // the attribute; escape the constant the same way rather than loosening the
+ // match, so this stays an assertion about the WHOLE class string.
+ const asAttr = (cls: string) => cls.replaceAll('&', '&amp;');
+ expect(render(USER)).toContain(asAttr(USER_BUBBLE));
+ expect(render(AGENT)).toContain(asAttr(AGENT_BUBBLE));
+ });
+
+ // Rule 04: quoted only when the anchor carried copy the reader can find.
+ it('draws the anchor quote when there is one, and nothing when there is not', () => {
+ expect(render({ ...USER, quote: 'Model Hub' })).toContain('Model Hub');
+ expect(render(USER)).not.toContain('border-l-2');
+ });
+
+ // Rule 07: created / updated / dismissed draw no marker at all.
+ it('marks only a resolved annotation', () => {
+ expect(render({ ...AGENT, resolved: true })).toContain('Resolved');
+ expect(render({ ...AGENT, resolved: true }, 'zh')).toContain('已处理');
+ expect(render(AGENT)).not.toContain('Resolved');
+ });
+
+ // Rule 06: the screenshot is the transcript's own thumbnail, passed in. The card
+ // renders no image element of its own.
+ it('passes the transcript body, attachments and timestamp straight through', () => {
+ const html = render(USER);
+ expect(html).toContain('<p>Body</p>');
+ expect(html).toContain('/api/media/med_9a71c33f8b2e');
+ expect(html).toContain('12:04');
+ });
+
+ it('carries the deep-link row dressing so an annotation can be jumped to', () => {
+ expect(render(USER)).toContain('data-message-id="msg_01J8XK2Q4W"');
+ });
+
+ // The contract's empty case: authored text "may be empty, in which case the
+ // card renders title + quote + attachments alone". The transcript withholds its
+ // em-dash stand-in for exactly this row (drawsEmptyBodyPlaceholder), so what
+ // arrives here is a null body — and a pure highlight must still read as a
+ // complete annotation rather than as an empty bubble.
+ it('reads complete with no authored text at all', () => {
+ const html = render({ ...USER, quote: 'Model Hub' }, 'en', null);
+ expect(html).toContain('User annotation');
+ expect(html).toContain('Model Hub');
+ expect(html).toContain('/api/media/med_9a71c33f8b2e');
+ expect(html).not.toContain('—');
+ });
+});
diff --git a/ui/src/components/workbench/AnnotationMessage.tsx b/ui/src/components/workbench/AnnotationMessage.tsx
new file mode 100644
index 000000000..61f0eaa7b
--- /dev/null
+++ b/ui/src/components/workbench/AnnotationMessage.tsx
@@ -0,0 +1,118 @@
+import { Check, MapPin, MessageSquareQuote } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import clsx from 'clsx';
+
+import { annotationTitleKey, type AnnotationView } from '../../lib/annotationView';
+import { AGENT_BUBBLE, USER_BUBBLE } from './chatBubble';
+import { RoleAvatar } from './RoleAvatar';
+
+// A Show Page annotation, in chat. Both directions are the same message type —
+// the user annotating the page, and the agent marking it back — and the card's
+// title is what says which. Design: design.pen m31JWV (states) + TxFKk (anatomy
+// and rules); the rule numbers cited below are that frame's.
+//
+// The card is a row component, not a page fragment: it takes the body,
+// attachment and timestamp nodes the transcript already builds and only adds
+// what is specific to an annotation (title, anchor quote, resolved marker), so
+// it cannot drift from the surrounding bubbles.
+
+type AnnotationMessageProps = {
+ messageId: string;
+ view: AnnotationView;
+ /** The transcript's own Markdown body node. */
+ body: React.ReactNode;
+ /** The transcript's own attachment renderer — rule 06: the screenshot reuses
+ * the existing thumbnail, viewer modal and proxy-url guard, with no second
+ * image element anywhere in the codebase. */
+ attachments: React.ReactNode;
+ /** The transcript's own hover-revealed timestamp — rule 03. */
+ time: React.ReactNode;
+ bodyStyle?: React.CSSProperties;
+ /** The transcript's row dressing (deep-link highlight); the card supplies only
+ * the alignment, because the alignment is the part that depends on direction. */
+ rowClass: (extra: string) => string;
+};
+
+export const AnnotationMessage: React.FC<AnnotationMessageProps> = ({
+ messageId,
+ view,
+ body,
+ attachments,
+ time,
+ bodyStyle,
+ rowClass,
+}) => {
+ const { t } = useTranslation();
+ const fromUser = view.direction === 'user';
+
+ // Rule 02: two title values, and the action never enters the title. A resolved
+ // agent mark is still titled "Agent 批注" — the marker below says it is done.
+ const label = (
+ <span className={clsx('text-[11px] font-medium', fromUser ? 'text-cyan' : 'text-mint')}>
+ {t(annotationTitleKey(view.direction))}
+ </span>
+ );
+ const avatar = (
+ <RoleAvatar tone={fromUser ? 'cyan' : 'mint'}>
+ <MessageSquareQuote />
+ </RoleAvatar>
+ );
+
+ // Rule 04: drawn only when the anchor carries copy a reader can find on the
+ // page. When it does not, nothing is drawn — a selector, an anchor kind, an
+ // event id or a screenshot path is a locator the reader cannot use, so none of
+ // them stands in for the quote (rule 05).
+ const quoteNode = view.quote ? (
+ <div className="mb-[9px] flex w-full items-start gap-[7px] border-l-2 border-foreground/25 py-px pl-[9px]">
+ <span className="pt-[3px]">
+ <MapPin className="size-[11px] shrink-0 text-muted" />
+ </span>
+ <span className="min-w-0 break-words text-[12px] leading-[1.5] text-muted">{view.quote}</span>
+ </div>
+ ) : null;
+
+ // Rule 07.
+ const resolvedNode = view.resolved ? (
+ <div className="mt-[9px] flex w-full">
+ <span className="inline-flex items-center gap-1 rounded-full border border-mint/35 bg-mint-soft px-[9px] py-[3px] text-[10.5px] font-semibold text-mint">
+ <Check className="size-[11px] shrink-0" />
+ {t('chat.annotation.resolved')}
+ </span>
+ </div>
+ ) : null;
+
+ return (
+ <div data-message-id={messageId} className={rowClass(fromUser ? 'justify-end' : 'justify-start')}>
+ <div
+ className={clsx(
+ 'group/message flex max-w-[min(92%,860px)] flex-col gap-1',
+ fromUser ? 'items-end' : 'items-start',
+ )}
+ >
+ {/* Mirrored head: the avatar always sits on the outer edge, so the two
+ directions read as a matched pair across the column. */}
+ <div className="flex items-center gap-2 px-0.5">
+ {fromUser ? (
+ <>
+ {label}
+ {avatar}
+ </>
+ ) : (
+ <>
+ {avatar}
+ {label}
+ </>
+ )}
+ </div>
+ {/* Rule 03: the bubble is the column's existing bubble, not a new shape. */}
+ <div className={fromUser ? USER_BUBBLE : AGENT_BUBBLE} style={bodyStyle}>
+ {quoteNode}
+ {body}
+ {attachments}
+ {resolvedNode}
+ </div>
+ {time}
+ </div>
+ </div>
+ );
+};
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index eb1f5356d..c22f5d032 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -1,7 +1,7 @@
import { Fragment, memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Link, useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';
-import { Activity, ArrowLeft, ArrowRight, ArrowUpRight, Bell, Bot, ChevronDown, ChevronRight, Clock, Eye, GitFork, Info, Loader2, MessageSquare, Pencil, Presentation, Terminal, Undo2, UploadCloud, X } from 'lucide-react';
+import { Activity, ArrowLeft, ArrowRight, ArrowUpRight, Bell, Bot, ChevronDown, ChevronRight, Clock, Eye, GitFork, Image as ImageIcon, Info, Loader2, MapPin, MessageSquare, MessageSquareQuote, Pencil, Presentation, Terminal, Undo2, UploadCloud, X } from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import clsx from 'clsx';
@@ -12,8 +12,9 @@ import { useRegisterComposerTarget, type ComposerInsertTarget } from '../../cont
import type { SessionActivityItemKind, SessionActivityState, SessionRuntimeState, VaultRequest, VibeAgentBrief, WorkbenchMessage, WorkbenchSession } from '../../context/ApiContext';
import { apiFetch } from '../../lib/apiFetch';
import { normalizeChatMessageFontSize } from '../../lib/chatDisplay';
-import { isNotifyMessageType, isTerminalAgentMessage } from '../../lib/chatMessageTypes';
-import { specFor } from '../../lib/messageTypes';
+import { annotationStandIn, annotationTitleKey, readAnnotationView } from '../../lib/annotationView';
+import { isTerminalAgentMessage, isTranscriptMessage } from '../../lib/chatMessageTypes';
+import { chatRowKind, drawsEmptyBodyPlaceholder, isAgentAuthored } from '../../lib/chatRowKind';
import { useIosKeyboardInset } from '../../lib/useIosKeyboardInset';
import { isProxyMediaUrl } from '../../lib/mediaProxy';
import { localPath, type ShowPageLinkInfo } from '../../lib/showPageLinks';
@@ -27,6 +28,9 @@ import {
sortBackgroundActivities,
} from '../../lib/backgroundActivity';
import { chatTriggerLink, harnessChipLabelKey, isUnresolvedAgentCallback } from '../../lib/chatTrigger';
+import { AnnotationMessage } from './AnnotationMessage';
+import { AGENT_BUBBLE, SYSTEM_BUBBLE, USER_BUBBLE } from './chatBubble';
+import { RoleAvatar } from './RoleAvatar';
import { useFileDrop } from '../../lib/useFileDrop';
import { quoteText } from '../../lib/quoteText';
import { mergeById, insertMessageOrdered } from '../../lib/transcriptOrder';
@@ -103,17 +107,6 @@ const emptyRuntimeState = (): SessionRuntimeState => ({
connection: 'unknown',
});
-// The transcript-visible message types — the shared catalog's ``transcript``
-// property, the same declaration the server filter on
-// ``GET /api/sessions/{id}/messages`` reads, so the live ``message.new`` feed
-// appends the same rows the initial load shows (assistant / tool_call are process
-// log). The ``show_page`` clause is NOT a message type: it is a metadata side
-// channel standing in for a Show-Page message type the server does not emit yet,
-// and it stays until the annotation rollout gives those rows a real type.
-const isTranscriptMessage = (msg: WorkbenchMessage): boolean =>
- specFor(msg.type).transcript ||
- (msg.metadata as { source?: string } | null)?.source === 'show_page';
-
// Bounded retained transcript window: cap how many message rows stay mounted so a
// long streaming session (or a deep upward scroll) doesn't keep thousands of full
// react-markdown subtrees in the DOM. The trimmed rows stay in SQLite and page
@@ -881,7 +874,12 @@ export const ChatPage: React.FC = () => {
setShowToolCalls(bootstrap.config?.ui?.show_tool_calls !== false);
// Merge (not replace) so a row that arrived over the stream during the
// load isn't clobbered; the session-change reset keeps prior sessions out.
- setMessages((prev) => mergeById(bootstrap.messages, prev));
+ // Filtered like every other entry point: the transcript decides what it
+ // shows by type, whatever a payload happens to contain. First paint is a
+ // visibility decision too — unfiltered, a queued annotation opened the chat
+ // as a delivered bubble *and* sat in the queue strip, the exact double
+ // render the live path already rejects.
+ setMessages((prev) => mergeById(bootstrap.messages.filter(isTranscriptMessage), prev));
setOlderCursor(bootstrap.next_before_id ?? null);
setHistoricalWindow(false);
// Chat Activity chips for past turns: resync the per-turn summary (row text
@@ -986,11 +984,11 @@ export const ChatPage: React.FC = () => {
// Agent Activity rows (assistant / tool_call) only reach the browser when
// the toggle streams them (message_mirror). Route them to the running
// buffer — never the transcript. ``isTranscriptMessage`` already excludes
- // them, so the feature-off path is unchanged. Show-Page marks are ALSO
- // ``assistant`` rows but are transcript-visible (isTranscriptMessage keeps
- // them) — let them fall through so they render in the chat, not the panel.
- const isShowPage = (msg.metadata as { source?: string } | null)?.source === 'show_page';
- if (showAgentActivityRef.current && isActivityMessageType(msg.type) && !isShowPage) {
+ // them, so the feature-off path is unchanged. A reverse Show Page mark is
+ // no longer an ``assistant`` row — it arrives typed ``annotation`` — so it
+ // cannot match here and needs no metadata-keyed exemption to escape the
+ // activity buffer.
+ if (showAgentActivityRef.current && isActivityMessageType(msg.type)) {
if (!historicalWindowRef.current) ingestActivityRow(msg);
return;
}
@@ -1956,7 +1954,7 @@ export const ChatPage: React.FC = () => {
// One queued message. Its text is a single truncated line by default; clicking
// it expands to the full wrapped text (and clicking again collapses it) so a
// long queued prompt can be read without sending it.
-const QueueRow: React.FC<{
+export const QueueRow: React.FC<{
item: WorkbenchMessage;
onRemove: (id: string) => void;
onRecall: (item: WorkbenchMessage) => void;
@@ -1976,7 +1974,23 @@ const QueueRow: React.FC<{
// - recall can't carry uploaded files (content.attachments), so an attachment
// row would silently lose them. Both can still be deleted or left to send.
const att = (item.content as Record<string, unknown> | undefined)?.attachments;
- const canRecall = item.source === 'user' && !(Array.isArray(att) && att.length > 0);
+ const hasAttachments = Array.isArray(att) && att.length > 0;
+ const canRecall = item.source === 'user' && !hasAttachments;
+ // Rule 08: a queued annotation belongs to the strip and nowhere else, so the
+ // strip is where it has to be identifiable. Same title as the card it will
+ // become, so the row the user is looking at and the bubble that replaces it
+ // read as one thing rather than two.
+ //
+ // Read straight from the content rather than through ``chatRowKind``: this
+ // row's type is ``queued`` by definition — that is precisely why it is here
+ // and not in the transcript — so the transcript's mapper would (correctly)
+ // classify it as anything but an annotation. The display record is on the row
+ // from the moment it is queued; only its type changes when the flush lands.
+ const annotationView = readAnnotationView(item.content);
+ // ``item.text`` is the annotator's authored words and nothing else, by
+ // contract — so an annotation that is only a highlight or only a boxed region
+ // has none, and would sit here as a title, a separator, and empty space.
+ const standIn = annotationView && annotationStandIn(annotationView, item.text, hasAttachments);
return (
<div className="flex items-start gap-2 rounded-lg bg-surface-2 px-2.5 py-1.5">
<div
@@ -1995,7 +2009,30 @@ const QueueRow: React.FC<{
expanded ? 'whitespace-pre-wrap break-words' : 'truncate',
)}
>
+ {annotationView && (
+ <>
+ <span className="mr-2 inline-flex items-center gap-[5px] align-middle text-[10.5px] font-medium text-cyan">
+ <MessageSquareQuote className="size-[11px] shrink-0" />
+ {t(annotationTitleKey(annotationView.direction))}
+ </span>
+ {(item.text || standIn) && <span className="mr-2 text-[11px] text-muted">·</span>}
+ </>
+ )}
{item.text}
+ {standIn?.kind === 'quote' && (
+ // The card's own quote treatment (pin + muted), flattened to the one
+ // line the strip has room for.
+ <span className="inline-flex items-center gap-[5px] align-middle text-muted">
+ <MapPin className="size-[11px] shrink-0" />
+ {standIn.quote}
+ </span>
+ )}
+ {standIn?.kind === 'screenshot' && (
+ <span className="inline-flex items-center gap-[5px] align-middle text-muted">
+ <ImageIcon className="size-[11px] shrink-0" />
+ {t('chat.annotation.screenshot')}
+ </span>
+ )}
</div>
{canRecall && (
<Button
@@ -3014,22 +3051,6 @@ const ForkSourceBanner: React.FC<{ sourceSessionId: string; sourceTitle: string
);
};
-
-// Small role avatar — a tinted rounded square with a lucide glyph, shown on the
-// header line above a left-aligned message bubble (IM layout). Kept on its own
-// line with the name so it never eats into the bubble's usable width.
-const TONE_AVATAR: Record<'mint' | 'cyan' | 'gold' | 'muted', string> = {
- mint: 'border-mint/30 bg-mint/[0.13] text-mint',
- cyan: 'border-cyan/30 bg-cyan/[0.13] text-cyan',
- gold: 'border-gold/30 bg-gold/[0.13] text-gold',
- muted: 'border-border-strong bg-foreground/[0.06] text-muted',
-};
-const RoleAvatar: React.FC<{ tone: keyof typeof TONE_AVATAR; children: React.ReactNode }> = ({ tone, children }) => (
- <span className={clsx('flex size-6 shrink-0 items-center justify-center rounded-lg border [&_svg]:size-3.5', TONE_AVATAR[tone])}>
- {children}
- </span>
-);
-
// Shown while a turn is in flight but the reply hasn't landed yet — a left
// agent bubble with three dots that fade in sequence (``.vr-typing-dot``
// keyframes in index.css), so the user gets immediate feedback a reply is
@@ -3087,15 +3108,18 @@ const MessageRow = memo(function MessageRow({ message, session, messageFontSize,
// Each branch composes this onto its own ``justify-*`` so alignment is kept.
const rowClass = (extra: string) => clsx('flex w-full', extra, highlighted && 'msg-highlight');
- // Runtime notifications and legacy error rows are compact status pills,
- // not Agent-authored answers.
- const isNotify = isNotifyMessageType(message.type);
- const isAgent = !isNotify && message.author === 'agent';
- const isSystem = !isNotify && message.author === 'system';
- // A harness-origin row is turn input the human didn't type (scheduled task /
- // watch / webhook); collapsed by default so it doesn't dominate.
- const isHarness = !isNotify && !isAgent && !isSystem && message.source === 'harness';
- const isUser = !isNotify && !isAgent && !isSystem && !isHarness;
+ // Which card family draws this row — one decision, made once, in a pure mapper
+ // (``chatRowKind``) so the ordering between the families is testable without
+ // mounting the page. Everything below reads the answer; nothing re-derives it.
+ const row = chatRowKind(message);
+ const isNotify = row.kind === 'notify';
+ const isAgent = row.kind === 'agent';
+ // ...and, separately, who wrote it. Only the agent's own words may carry the
+ // agent-authored Markdown affordances, and its reverse annotation is still its
+ // own words even though a different card draws it.
+ const agentAuthored = isAgentAuthored(message);
+ const isHarness = row.kind === 'harness';
+ const isUser = row.kind === 'user';
// Trigger-message provenance click-through (contract A9a/A9b): agent-callback
// rows link to the source session's chat; task/watch rows to the Harness view.
const triggerLink = isHarness ? chatTriggerLink(message, t('chat.source.agentFallback')) : null;
@@ -3134,7 +3158,7 @@ const MessageRow = memo(function MessageRow({ message, session, messageFontSize,
// THIS message's ``content`` (parsed server-side; the chosen answer recorded on
// the same message is the single source of truth for the lock — no correlating
// a separate user reply). IM channels render native buttons from the same parse.
- const qr = isAgent
+ const qr = agentAuthored
? (message.content as { quick_replies?: unknown; quick_reply_chosen?: unknown } | null)
: null;
const quickReplyOptions = Array.isArray(qr?.quick_replies)
@@ -3161,14 +3185,18 @@ const MessageRow = memo(function MessageRow({ message, session, messageFontSize,
const bodyNode = message.text ? (
<Markdown
content={message.text}
- softBreaks={isUser || isHarness}
+ // An annotation the user typed is the user's own words (rule 05), so it
+ // keeps their line breaks exactly as the ordinary user bubble does.
+ softBreaks={isUser || isHarness || (row.kind === 'annotation' && row.annotation.direction === 'user')}
references={(message.content as { references?: MentionReference[] } | null)?.references}
- // Only the agent's own replies may render `$<NAME>` as an interactive secret-input card;
- // user/harness/system bubbles with the marker stay plain text (no false "agent asked" card).
- secretRequests={isAgent}
+ // Only the agent's own words may render `$<NAME>` as an interactive secret-input card;
+ // user/harness/system bubbles with the marker stay plain text (no false "agent asked"
+ // card). Keyed to authorship, not to the card family, so the agent's reverse annotation
+ // keeps the card it had before that row had its own type.
+ secretRequests={agentAuthored}
className="vr-markdown--inherit-size"
/>
- ) : messageAttachments.length === 0 ? (
+ ) : drawsEmptyBodyPlaceholder(row, messageAttachments.length > 0) ? (
<div className="text-[13px] text-muted">—</div>
) : null;
@@ -3184,6 +3212,21 @@ const MessageRow = memo(function MessageRow({ message, session, messageFontSize,
</span>
);
+ // ----- Annotation: the Show Page card, sided by direction (design.pen m31JWV)
+ if (row.kind === 'annotation') {
+ return (
+ <AnnotationMessage
+ messageId={message.id}
+ view={row.annotation}
+ body={bodyNode}
+ attachments={attachmentsNode}
+ time={time}
+ bodyStyle={messageFontStyle}
+ rowClass={rowClass}
+ />
+ );
+ }
+
// ----- Notify: compact gold pill, left-aligned (a status marker) -----
if (isNotify) {
return (
@@ -3207,10 +3250,7 @@ const MessageRow = memo(function MessageRow({ message, session, messageFontSize,
return (
<div data-message-id={message.id} className={rowClass('justify-end')}>
<div className="group/message flex max-w-[min(92%,860px)] flex-col items-end gap-1">
- <div
- className="w-fit min-w-0 max-w-full rounded-2xl rounded-tr-md border border-border-strong bg-foreground/[0.06] px-3.5 py-2.5 leading-relaxed [&_pre]:max-w-full [&_pre]:overflow-x-auto [&_table]:w-full"
- style={messageFontStyle}
- >
+ <div className={USER_BUBBLE} style={messageFontStyle}>
{bodyNode}
{attachmentsNode}
</div>
@@ -3295,13 +3335,7 @@ const MessageRow = memo(function MessageRow({ message, session, messageFontSize,
<RoleAvatar tone={isAgent ? 'mint' : 'muted'}>{isAgent ? <Bot /> : <Info />}</RoleAvatar>
{name && <span className="text-[11px] font-medium text-muted">{name}</span>}
</div>
- <div
- className={clsx(
- 'w-fit min-w-0 max-w-full rounded-2xl rounded-tl-md border px-3.5 py-2.5 leading-relaxed [&_pre]:max-w-full [&_pre]:overflow-x-auto [&_table]:w-full',
- isAgent ? 'border-mint/25 bg-mint/[0.09]' : 'border-border bg-foreground/[0.03]',
- )}
- style={messageFontStyle}
- >
+ <div className={isAgent ? AGENT_BUBBLE : SYSTEM_BUBBLE} style={messageFontStyle}>
{bodyNode}
{attachmentsNode}
</div>
diff --git a/ui/src/components/workbench/ChatQueueRow.test.tsx b/ui/src/components/workbench/ChatQueueRow.test.tsx
new file mode 100644
index 000000000..bbebdcd80
--- /dev/null
+++ b/ui/src/components/workbench/ChatQueueRow.test.tsx
@@ -0,0 +1,156 @@
+import { createInstance } from 'i18next';
+import { renderToStaticMarkup } from 'react-dom/server';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { describe, expect, it } from 'vitest';
+
+import en from '../../i18n/en.json';
+import type { WorkbenchMessage } from '../../context/ApiContext';
+import { AnnotationMessage } from './AnnotationMessage';
+import { QueueRow } from './ChatPage';
+
+const i18n = createInstance();
+void i18n.use(initReactI18next).init({
+ lng: 'en',
+ fallbackLng: 'en',
+ resources: { en: { translation: en } },
+ interpolation: { escapeValue: false },
+});
+
+const wrap = (ui: React.ReactElement) =>
+ renderToStaticMarkup(<I18nextProvider i18n={i18n}>{ui}</I18nextProvider>);
+
+// A queued forward annotation, exactly as the contract freezes it
+// (docs/plans/show-annotation-message-type/examples.json, msg_01J8XK5M8T): the
+// display record is already on the row; only ``type`` says it has not been sent.
+const queued = (over: Partial<WorkbenchMessage> = {}): WorkbenchMessage =>
+ ({
+ id: 'msg_01J8XK5M8T',
+ type: 'queued',
+ author: 'harness',
+ source: 'harness',
+ author_name: 'show_annotation',
+ text: 'This chart needs a legend',
+ content: { annotation: { direction: 'user', action: 'created' } },
+ metadata: { source: 'show_page' },
+ created_at: '2026-07-27T04:04:00Z',
+ ...over,
+ }) as WorkbenchMessage;
+
+const renderQueued = (item: WorkbenchMessage) =>
+ wrap(<QueueRow item={item} onRemove={() => undefined} onRecall={() => undefined} />);
+
+describe('QueueRow — a queued annotation in the strip (rule 08)', () => {
+ it('names a queued annotation, and leaves an ordinary queued prompt unlabelled', () => {
+ expect(renderQueued(queued())).toContain('User annotation');
+ expect(renderQueued(queued())).toContain('This chart needs a legend');
+
+ const plain = renderQueued(queued({ content: {} as WorkbenchMessage['content'] }));
+ expect(plain).not.toContain('User annotation');
+ expect(plain).not.toContain('Agent annotation');
+ });
+
+ // The point of the strip label. The row the user is looking at now and the
+ // bubble that replaces it when the queue flushes must name the same thing the
+ // same way — otherwise sending appears to turn one thing into another. Both
+ // sides are rendered here rather than compared by key, so a divergence in
+ // either renderer fails this.
+ it('uses the same title the card will use once the queue flushes', () => {
+ const strip = renderQueued(queued());
+ const card = wrap(
+ <AnnotationMessage
+ messageId="msg_01J8XK5M8T"
+ view={{ direction: 'user', resolved: false }}
+ body={null}
+ attachments={null}
+ time={null}
+ rowClass={(extra) => extra}
+ />,
+ );
+ const title = (html: string) => html.match(/(User|Agent) annotation/)?.[0];
+
+ expect(title(strip)).toBeDefined();
+ expect(title(strip)).toBe(title(card));
+ });
+
+ it('names a queued reverse mark with the agent title', () => {
+ const html = renderQueued(
+ queued({ content: { annotation: { direction: 'agent', action: 'created' } } as WorkbenchMessage['content'] }),
+ );
+ expect(html).toContain('Agent annotation');
+ });
+});
+
+// ``text`` is the annotator's own words and nothing else, so an annotation is
+// allowed to arrive with none: a pure highlight, or a boxed region submitted
+// without a comment. The strip is the ONLY place a queued row is visible, so
+// "no words" must not mean "no row".
+describe('QueueRow — a queued annotation nobody wrote words for', () => {
+ const wordless = (over: Partial<WorkbenchMessage> = {}) => queued({ text: '', ...over });
+ const withAnnotation = (annotation: Record<string, unknown>, attachments?: unknown[]) =>
+ ({ annotation, ...(attachments ? { attachments } : {}) }) as WorkbenchMessage['content'];
+ const screenshot = [{ url: '/api/media/med_9a71c33f8b2e', name: 'annotation-region.png', kind: 'image' }];
+
+ it('shows the boxed region a screenshot-only annotation is made of', () => {
+ const html = renderQueued(
+ wordless({ content: withAnnotation({ direction: 'user', action: 'created' }, screenshot) }),
+ );
+ expect(html).toContain('User annotation');
+ expect(html).toContain('Screenshot');
+ });
+
+ it('shows the highlight an anchor-only annotation is made of', () => {
+ const html = renderQueued(
+ wordless({ content: withAnnotation({ direction: 'user', action: 'created', quote: 'Model Hub' }) }),
+ );
+ expect(html).toContain('User annotation');
+ expect(html).toContain('Model Hub');
+ });
+
+ // Both present: the strip has one line and the card puts the quote above the
+ // screenshot, so the line takes the quote.
+ it('takes the quote over the screenshot, and the words over both', () => {
+ const both = withAnnotation({ direction: 'user', action: 'created', quote: 'Model Hub' }, screenshot);
+ const silent = renderQueued(wordless({ content: both }));
+ expect(silent).toContain('Model Hub');
+ expect(silent).not.toContain('Screenshot');
+
+ const spoken = renderQueued(queued({ text: 'The spacing is off', content: both }));
+ expect(spoken).toContain('The spacing is off');
+ expect(spoken).not.toContain('Model Hub');
+ expect(spoken).not.toContain('Screenshot');
+ });
+
+ // Neither a quote nor a region: nothing about the row can be shown that the
+ // reader could act on, so the title stands alone — without the separator that
+ // would promise something after it.
+ it('leaves no dangling separator when the title is all there is', () => {
+ const html = renderQueued(wordless({ content: withAnnotation({ direction: 'user', action: 'created' }) }));
+ expect(html).toContain('User annotation');
+ expect(html).not.toContain('·');
+ });
+
+ // Same requirement as the title, one level down: the strip entry and the card
+ // that replaces it on flush must show the reader the same quote, so sending
+ // does not appear to change what was annotated.
+ it('quotes what the card will quote', () => {
+ const view = { direction: 'user' as const, resolved: false, quote: 'Model Hub' };
+ const strip = renderQueued(
+ wordless({ content: withAnnotation({ direction: 'user', action: 'created', quote: view.quote }) }),
+ );
+ const card = wrap(
+ <AnnotationMessage
+ messageId="msg_01J8XK5M8T"
+ view={view}
+ body={null}
+ attachments={null}
+ time={null}
+ rowClass={(extra) => extra}
+ />,
+ );
+
+ for (const html of [strip, card]) {
+ expect(html).toContain('User annotation');
+ expect(html).toContain('Model Hub');
+ }
+ });
+});
diff --git a/ui/src/components/workbench/RoleAvatar.tsx b/ui/src/components/workbench/RoleAvatar.tsx
new file mode 100644
index 000000000..f2d9f13ad
--- /dev/null
+++ b/ui/src/components/workbench/RoleAvatar.tsx
@@ -0,0 +1,28 @@
+import clsx from 'clsx';
+
+// The tone-tinted 24px chip that leads every message head in Chat — agent,
+// system, harness and annotation all draw the same geometry, so a new row kind
+// inherits exactly the avatar its neighbours already have (design.pen m31JWV
+// draws the Claude head and the annotation head identically).
+//
+// Lives in its own module rather than inside ChatPage so a row component can
+// reuse it without importing the whole page back.
+const TONE_AVATAR: Record<'mint' | 'cyan' | 'gold' | 'muted', string> = {
+ mint: 'border-mint/30 bg-mint/[0.13] text-mint',
+ cyan: 'border-cyan/30 bg-cyan/[0.13] text-cyan',
+ gold: 'border-gold/30 bg-gold/[0.13] text-gold',
+ muted: 'border-border-strong bg-foreground/[0.06] text-muted',
+};
+
+export type RoleAvatarTone = keyof typeof TONE_AVATAR;
+
+export const RoleAvatar: React.FC<{ tone: RoleAvatarTone; children: React.ReactNode }> = ({ tone, children }) => (
+ <span
+ className={clsx(
+ 'flex size-6 shrink-0 items-center justify-center rounded-lg border [&_svg]:size-3.5',
+ TONE_AVATAR[tone],
+ )}
+ >
+ {children}
+ </span>
+);
diff --git a/ui/src/components/workbench/chatBubble.ts b/ui/src/components/workbench/chatBubble.ts
new file mode 100644
index 000000000..94d53ddc8
--- /dev/null
+++ b/ui/src/components/workbench/chatBubble.ts
@@ -0,0 +1,27 @@
+// The two message-bubble shapes the chat column draws, in one place.
+//
+// design.pen TxFKk rule 03 says the annotation card's bubble IS the existing
+// chat bubble — same width rule, same radius, same timestamp — because an
+// annotation is a message, not a widget, and a second bubble shape in the same
+// column reads as a different product. The frame backs that literally: its
+// annotation bubbles are byte-identical to the ordinary user / Claude bubbles
+// drawn beside them.
+//
+// Naming these makes that rule a fact instead of a comment: the card cannot
+// drift from the rows around it, because there is nothing to drift from.
+//
+// Shape is shared; only the corner notch (which points back at the head above
+// it) and the tint depend on which side the row takes.
+const BUBBLE_BASE =
+ 'w-fit min-w-0 max-w-full rounded-2xl border px-3.5 py-2.5 leading-relaxed [&_pre]:max-w-full [&_pre]:overflow-x-auto [&_table]:w-full';
+const BUBBLE_RIGHT = `${BUBBLE_BASE} rounded-tr-md`;
+const BUBBLE_LEFT = `${BUBBLE_BASE} rounded-tl-md`;
+
+/** Right-aligned neutral bubble — the user's own words. */
+export const USER_BUBBLE = `${BUBBLE_RIGHT} border-border-strong bg-foreground/[0.06]`;
+
+/** Left-aligned mint bubble — the agent's own words. */
+export const AGENT_BUBBLE = `${BUBBLE_LEFT} border-mint/25 bg-mint/[0.09]`;
+
+/** Left-aligned neutral bubble — a system row, quieter than the agent's. */
+export const SYSTEM_BUBBLE = `${BUBBLE_LEFT} border-border bg-foreground/[0.03]`;
diff --git a/ui/src/components/workbench/search/SearchResultRow.test.ts b/ui/src/components/workbench/search/SearchResultRow.test.ts
index cced029a1..18042694f 100644
--- a/ui/src/components/workbench/search/SearchResultRow.test.ts
+++ b/ui/src/components/workbench/search/SearchResultRow.test.ts
@@ -13,4 +13,34 @@ describe('messageSearchRole', () => {
expect(messageSearchRole({ author: 'user', source: 'user', type: 'user' })).toBe('you');
expect(messageSearchRole({ author: 'agent', source: 'agent', type: 'result' })).toBe('agent');
});
+
+ // ``annotation`` is the first type that carries both directions, and the rows
+ // below are the frozen contract shapes: a forward annotation — the user's own
+ // words — is harness-authored because it enters as turn input, and a reverse
+ // mark is agent-authored with no source. Neither is automated: nobody
+ // scheduled them, so the harness author must not be read as one here.
+ it('reads an annotation as its direction, not as a harness-authored row', () => {
+ expect(messageSearchRole({ author: 'harness', source: 'harness', type: 'annotation' })).toBe(
+ 'you',
+ );
+ expect(messageSearchRole({ author: 'agent', source: null, type: 'annotation' })).toBe('agent');
+ });
+
+ // The same author/source pair on any other type is still automated, so the
+ // annotation case is a property of that type and not a hole in the rule.
+ it('keeps a harness-authored row of any other type automated', () => {
+ expect(messageSearchRole({ author: 'harness', source: 'harness', type: 'harness' })).toBe(
+ 'automated',
+ );
+ expect(messageSearchRole({ author: 'harness', source: 'harness', type: 'result' })).toBe(
+ 'automated',
+ );
+ });
+
+ // The catalog still decides a row whose author names nobody the mapping knows,
+ // so a future harness-input type inherits the automated treatment for free.
+ it('falls back to the catalog input-turn identity for an unknown author', () => {
+ expect(messageSearchRole({ author: 'system', source: null, type: 'harness' })).toBe('automated');
+ expect(messageSearchRole({ author: 'system', source: null, type: 'result' })).toBe('agent');
+ });
});
diff --git a/ui/src/components/workbench/search/messageSearchRole.ts b/ui/src/components/workbench/search/messageSearchRole.ts
index 6a2a71670..87e434cc8 100644
--- a/ui/src/components/workbench/search/messageSearchRole.ts
+++ b/ui/src/components/workbench/search/messageSearchRole.ts
@@ -6,14 +6,21 @@ export type MessageSearchRole = 'you' | 'automated' | 'agent';
export const messageSearchRole = (
match: Pick<MessageSearchMatch, 'author' | 'source' | 'type'>,
): MessageSearchRole => {
- // The type test is the catalog's input-turn identity: a type accepted as harness
- // input (``inputAuthors`` contains ``harness``), not a bare name comparison.
- if (
- match.author === 'harness' ||
- match.source === 'harness' ||
- specFor(match.type).inputAuthors.includes('harness')
- ) {
- return 'automated';
- }
- return match.author === 'user' ? 'you' : 'agent';
+ // An annotation is one type in two directions, and ``direction`` — the field
+ // that separates them — lives in ``content``, which a search match does not
+ // carry. Inside this type the frozen contract makes ``author`` stand in for it
+ // exactly: a forward annotation is the user's own, submitted as turn input and
+ // therefore recorded as harness-authored; a reverse mark is written by the
+ // agent. So here a harness author does NOT mean automated, which is why the
+ // type is settled before the author rules below rather than inside them.
+ if (match.type === 'annotation') return match.author === 'agent' ? 'agent' : 'you';
+
+ if (match.author === 'harness' || match.source === 'harness') return 'automated';
+ if (match.author === 'user') return 'you';
+ if (match.author === 'agent') return 'agent';
+ // ``inputAuthors`` is a permission — which authors may submit this type as
+ // input — not a claim about who wrote this row, so it only decides rows whose
+ // author names nobody above. Keeping it means a future harness-input type
+ // inherits the automated treatment without another edit here.
+ return specFor(match.type).inputAuthors.includes('harness') ? 'automated' : 'agent';
};
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index e881824ed..36a0a8a33 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -2835,12 +2835,17 @@
"scheduled": "Scheduled task",
"watch": "Watch",
"webhook": "Webhook",
- "showAnnotation": "Page annotation",
"showIntent": "Page action",
"harness": "From agent",
"from": "From",
"agentFallback": "agent"
},
+ "annotation": {
+ "titleUser": "User annotation",
+ "titleAgent": "Agent annotation",
+ "resolved": "Resolved",
+ "screenshot": "Screenshot"
+ },
"picker": {
"agent": "Agent",
"model": "Model",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 662a1c4db..b0afcbaff 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -2835,12 +2835,17 @@
"scheduled": "定时任务",
"watch": "Watch 监听",
"webhook": "Webhook",
- "showAnnotation": "页面批注",
"showIntent": "页面操作",
"harness": "来自 Agent",
"from": "来自",
"agentFallback": "智能体"
},
+ "annotation": {
+ "titleUser": "用户批注",
+ "titleAgent": "Agent 批注",
+ "resolved": "已处理",
+ "screenshot": "截图"
+ },
"picker": {
"agent": "Agent",
"model": "模型",
diff --git a/ui/src/lib/annotationView.test.ts b/ui/src/lib/annotationView.test.ts
new file mode 100644
index 000000000..3eca4ac4c
--- /dev/null
+++ b/ui/src/lib/annotationView.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from 'vitest';
+
+import { annotationStandIn, type AnnotationView } from './annotationView';
+
+const view = (over: Partial<AnnotationView> = {}): AnnotationView => ({
+ direction: 'user',
+ resolved: false,
+ ...over,
+});
+
+describe('annotationStandIn', () => {
+ it('stays out of the way when the annotator wrote something', () => {
+ expect(annotationStandIn(view({ quote: 'Model Hub' }), 'The heading is too small', true)).toBeNull();
+ });
+
+ it('treats blank text as no text', () => {
+ expect(annotationStandIn(view({ quote: 'Model Hub' }), ' ', false)).toEqual({
+ kind: 'quote',
+ quote: 'Model Hub',
+ });
+ expect(annotationStandIn(view(), '', true)).toEqual({ kind: 'screenshot' });
+ expect(annotationStandIn(view(), null, true)).toEqual({ kind: 'screenshot' });
+ });
+
+ // The card stacks quote above attachments; one line can hold one of them, so
+ // it takes the upper. A highlight the reader can find on the page beats
+ // "there is a picture".
+ it('prefers the quote to the screenshot, as the card stacks them', () => {
+ expect(annotationStandIn(view({ quote: 'Model Hub' }), '', true)).toEqual({
+ kind: 'quote',
+ quote: 'Model Hub',
+ });
+ });
+
+ it('leaves the title to stand alone when there is nothing to say', () => {
+ expect(annotationStandIn(view(), '', false)).toBeNull();
+ });
+
+ it('reads the same for a reverse mark', () => {
+ expect(annotationStandIn(view({ direction: 'agent' }), '', true)).toEqual({ kind: 'screenshot' });
+ });
+});
diff --git a/ui/src/lib/annotationView.ts b/ui/src/lib/annotationView.ts
new file mode 100644
index 000000000..2db12efc3
--- /dev/null
+++ b/ui/src/lib/annotationView.ts
@@ -0,0 +1,73 @@
+// What a Show Page annotation draws in chat, distilled from ``content.annotation``.
+// Design: design.pen m31JWV (states) + TxFKk (anatomy and rules); the rule
+// numbers cited below are that frame's.
+//
+// Pure, and separate from the card component, so the transcript's branch mapper
+// can depend on it without a lib → component import.
+
+export type AnnotationView = {
+ // Rule 01: direction alone decides the side and the title. A forward
+ // annotation is authored by ``harness`` (it is turn input), so reading
+ // ``author`` here would put the user's own annotation on the left behind a
+ // harness chip. ``author`` is bookkeeping and never reaches the view.
+ direction: 'user' | 'agent';
+ // Rule 07: only ``resolved`` draws a marker; created / updated / dismissed
+ // draw nothing beyond the body. Collapsing the action to a boolean means no
+ // later edit can quietly start branching on the other three without going
+ // back to the design first.
+ resolved: boolean;
+ quote?: string;
+};
+
+// Reads ``content.annotation`` off a chat row; null when the row carries no
+// usable display record.
+export function readAnnotationView(content: unknown): AnnotationView | null {
+ const raw = (content as { annotation?: unknown } | null | undefined)?.annotation;
+ if (!raw || typeof raw !== 'object') return null;
+ const { direction, action, quote } = raw as Record<string, unknown>;
+ if (direction !== 'user' && direction !== 'agent') return null;
+ return {
+ direction,
+ resolved: action === 'resolved',
+ // Rule 04: the strip needs copy the reader can find on the page. An empty
+ // string is the same as no quote.
+ quote: typeof quote === 'string' && quote.trim().length > 0 ? quote : undefined,
+ };
+}
+
+// Rule 02: exactly two title values, and the action never enters the title — a
+// resolved agent mark is still titled "Agent 批注"; the marker below the body is
+// what says it is done. The direction is data on the row; the words are frontend
+// i18n, so switching UI language re-labels existing rows instead of rewriting them.
+export const annotationTitleKey = (direction: AnnotationView['direction']): string =>
+ direction === 'user' ? 'chat.annotation.titleUser' : 'chat.annotation.titleAgent';
+
+// What names a queued annotation on the strip's single line when its author
+// wrote no words.
+//
+// A queued annotation is visible in the strip and nowhere else — its type is
+// ``queued``, so the transcript cannot draw it — which makes that one line the
+// only account of what is waiting. Authored text is the whole line for an
+// ordinary queued prompt, but an annotation is allowed to carry none: a pure
+// highlight contributes its quote, a boxed region contributes its screenshot.
+// Left to the text alone, those two draw a title and then nothing.
+//
+// The card answers the same question by stacking quote and attachments under
+// the title. This picks whichever of them fits one line, in the order the card
+// stacks them, so the strip and the bubble that replaces it say the same thing.
+export type AnnotationStandIn = { kind: 'quote'; quote: string } | { kind: 'screenshot' } | null;
+
+export function annotationStandIn(
+ view: AnnotationView,
+ text: string | null | undefined,
+ hasAttachments: boolean,
+): AnnotationStandIn {
+ // The annotator's own words always speak for the row; a stand-in only ever
+ // fills a silence.
+ if (text && text.trim().length > 0) return null;
+ if (view.quote) return { kind: 'quote', quote: view.quote };
+ // Rule 05 in reverse: on the card a locator is never shown because the reader
+ // cannot use it, and the same holds here — an anchor with no quote and no
+ // region leaves the title to stand alone rather than printing a selector.
+ return hasAttachments ? { kind: 'screenshot' } : null;
+}
diff --git a/ui/src/lib/chatMessageTypes.test.ts b/ui/src/lib/chatMessageTypes.test.ts
index 9a3d0bc04..94d308d8e 100644
--- a/ui/src/lib/chatMessageTypes.test.ts
+++ b/ui/src/lib/chatMessageTypes.test.ts
@@ -1,6 +1,38 @@
import { describe, expect, it } from 'vitest';
-import { isNotifyMessageType, isTerminalAgentMessage } from './chatMessageTypes';
+import { isNotifyMessageType, isTerminalAgentMessage, isTranscriptMessage } from './chatMessageTypes';
+
+describe('isTranscriptMessage', () => {
+ it('shows the rows the transcript has always shown, and hides process log', () => {
+ for (const type of ['user', 'harness', 'result', 'notify', 'error']) {
+ expect(isTranscriptMessage({ type }), type).toBe(true);
+ }
+ for (const type of ['assistant', 'tool_call', 'draft', 'pending', 'silent', 'future_type']) {
+ expect(isTranscriptMessage({ type }), type).toBe(false);
+ }
+ });
+
+ it('shows an annotation, in either direction', () => {
+ expect(isTranscriptMessage({ type: 'annotation' })).toBe(true);
+ });
+
+ // The back door this replaced. A forward annotation carries
+ // ``metadata.source === 'show_page'`` from the moment it is queued, so the old
+ // predicate showed it as a delivered bubble while the very same row was still
+ // sitting in the queue strip waiting to be sent. Only the type changes when the
+ // flush lands, and the type is now the only thing consulted.
+ it('hides a queued annotation however it is dressed', () => {
+ const queued = {
+ type: 'queued',
+ author: 'harness',
+ source: 'harness',
+ author_name: 'show_annotation',
+ metadata: { source: 'show_page', show_event_type: 'human.annotation.created' },
+ content: { annotation: { direction: 'user', action: 'created' } },
+ };
+ expect(isTranscriptMessage(queued)).toBe(false);
+ });
+});
describe('isNotifyMessageType', () => {
it('renders current and legacy failure rows as notifications', () => {
diff --git a/ui/src/lib/chatMessageTypes.ts b/ui/src/lib/chatMessageTypes.ts
index 74655e779..310b127c7 100644
--- a/ui/src/lib/chatMessageTypes.ts
+++ b/ui/src/lib/chatMessageTypes.ts
@@ -3,6 +3,23 @@ import { specFor } from './messageTypes';
// Status pills rather than authored answers — the catalog's ``status`` render kind.
export const isNotifyMessageType = (type: string): boolean => specFor(type).render === 'status';
+// Whether a row belongs in the chat transcript — the catalog's ``transcript``
+// property, the same declaration the server filter on
+// ``GET /api/sessions/{id}/messages`` reads, so the live ``message.new`` feed
+// appends exactly the rows the initial load shows (assistant / tool_call are
+// process log).
+//
+// Visibility is a function of ``type`` ALONE, which is why the parameter is
+// narrowed to ``{ type }``: no caller and no future edit can reach ``author`` /
+// ``source`` / ``author_name`` / ``metadata`` from in here to widen the set,
+// even by accident. What that replaced was a ``metadata.source === 'show_page'``
+// clause standing in for a message type the server did not emit yet; it kept ANY
+// row of that origin whatever its type, and a forward annotation carries that
+// origin in EVERY state — so a still-``queued`` annotation rendered as a
+// delivered bubble while the same row sat in the queue strip. An annotation
+// becomes transcript-visible exactly once: when the flush mints it ``annotation``.
+export const isTranscriptMessage = (message: { type: string }): boolean => specFor(message.type).transcript;
+
type TerminalMessageCandidate = {
author: string;
type: string;
diff --git a/ui/src/lib/chatRowKind.test.ts b/ui/src/lib/chatRowKind.test.ts
new file mode 100644
index 000000000..8dac9bf4e
--- /dev/null
+++ b/ui/src/lib/chatRowKind.test.ts
@@ -0,0 +1,149 @@
+import { describe, expect, it } from 'vitest';
+
+import { chatRowKind, drawsEmptyBodyPlaceholder, isAgentAuthored } from './chatRowKind';
+
+const row = (over: Partial<Parameters<typeof chatRowKind>[0]>) =>
+ chatRowKind({ type: 'user', author: 'user', source: 'user', ...over });
+
+// The row shapes the contract freezes (docs/plans/show-annotation-message-type/
+// examples.json). A forward annotation is authored by ``harness``; a reverse mark
+// is authored by ``agent``. Both are ``type: 'annotation'``, and that is the only
+// thing either of them has in common.
+const FORWARD = {
+ type: 'annotation',
+ author: 'harness',
+ source: 'harness',
+ content: { annotation: { direction: 'user', action: 'created', quote: 'Model Hub' } },
+};
+const REVERSE = {
+ type: 'annotation',
+ author: 'agent',
+ source: null,
+ content: { annotation: { direction: 'agent', action: 'resolved' } },
+};
+
+describe('chatRowKind', () => {
+ it('keeps the pre-existing role families intact', () => {
+ expect(row({ author: 'user', source: 'user' })).toEqual({ kind: 'user' });
+ expect(row({ author: 'agent', type: 'result' })).toEqual({ kind: 'agent' });
+ expect(row({ author: 'system', type: 'user' })).toEqual({ kind: 'system' });
+ expect(row({ author: 'harness', source: 'harness', type: 'harness' })).toEqual({ kind: 'harness' });
+ expect(row({ author: 'agent', type: 'notify' })).toEqual({ kind: 'notify' });
+ expect(row({ author: 'agent', type: 'error' })).toEqual({ kind: 'notify' });
+ });
+
+ it('draws an annotation card for both directions', () => {
+ expect(chatRowKind(FORWARD)).toEqual({
+ kind: 'annotation',
+ annotation: { direction: 'user', resolved: false, quote: 'Model Hub' },
+ });
+ expect(chatRowKind(REVERSE)).toEqual({
+ kind: 'annotation',
+ annotation: { direction: 'agent', resolved: true, quote: undefined },
+ });
+ });
+
+ // The defect this lane exists to remove. A forward annotation is turn input, so
+ // it is authored by ``harness`` — under an author-first cascade it drew as a
+ // collapsed trigger row, and the user's own words sat behind a chip.
+ it('lets the type outvote the author, never the other way round', () => {
+ for (const author of ['harness', 'agent', 'system', 'user']) {
+ for (const source of ['harness', 'user', null]) {
+ expect(chatRowKind({ ...FORWARD, author, source }).kind, `${author}/${source}`).toBe('annotation');
+ }
+ }
+ });
+
+ // Rule 01: the side is direction, and direction is on the row. Two annotations
+ // with the SAME author land on opposite sides; two with the same direction land
+ // on the same side whoever authored them.
+ it('reads the side from direction, not from who authored the row', () => {
+ const asUser = chatRowKind({ ...FORWARD, author: 'agent' });
+ const asAgent = chatRowKind({ ...REVERSE, author: 'agent' });
+ expect(asUser).toMatchObject({ kind: 'annotation', annotation: { direction: 'user' } });
+ expect(asAgent).toMatchObject({ kind: 'annotation', annotation: { direction: 'agent' } });
+ });
+
+ // A queued annotation carries the identical content and metadata; only its type
+ // says it has not been sent. It belongs to the queue strip (rule 08), so the
+ // transcript mapper must not claim it — the old ``metadata.source`` back door
+ // did, which is how one row appeared twice.
+ it('does not claim a queued annotation for the transcript', () => {
+ expect(chatRowKind({ ...FORWARD, type: 'queued' }).kind).not.toBe('annotation');
+ });
+
+ // Contract D requires ``content.annotation`` on every row of the type, and the
+ // migration backfills it onto the historical reverse marks, so this is a
+ // backend defect. It must still degrade inside the family: falling back to the
+ // author cascade would draw a mark the AGENT wrote as the user's own bubble.
+ it('still draws a card when the display record is missing or malformed', () => {
+ for (const content of [undefined, null, {}, { annotation: null }, { annotation: { direction: 'sideways' } }]) {
+ expect(chatRowKind({ type: 'annotation', author: 'agent', source: null, content })).toEqual({
+ kind: 'annotation',
+ annotation: { direction: 'agent', resolved: false },
+ });
+ }
+ });
+});
+
+describe('isAgentAuthored', () => {
+ // The defect this exists to prevent, stated as the disagreement itself: on a
+ // reverse mark the two questions give different answers, and they are supposed
+ // to. Deriving authorship from the card family made ``$<NAME>`` in an agent's
+ // mark render as inert literal text where the same words in an ordinary reply
+ // render an interactive secret-input card.
+ it('keeps an agent mark agent-authored even though an annotation card draws it', () => {
+ expect(chatRowKind(REVERSE).kind).toBe('annotation');
+ expect(isAgentAuthored(REVERSE)).toBe(true);
+ });
+
+ // The other direction is the reason this is not simply ``type === 'annotation'``:
+ // a forward annotation is the USER's words on an agent-adjacent card, and must
+ // never be dressed as something the agent asked for.
+ it('never treats the user side of an annotation as agent-authored', () => {
+ expect(isAgentAuthored(FORWARD)).toBe(false);
+ });
+
+ // Everywhere else it must still agree with the flag it replaced
+ // (``!isNotify && author === 'agent'`` on master), so this is a fix confined to
+ // annotations rather than a widening of who gets the agent affordances.
+ it('matches the pre-annotation rule on every other row', () => {
+ expect(isAgentAuthored({ type: 'result', author: 'agent' })).toBe(true);
+ expect(isAgentAuthored({ type: 'user', author: 'user' })).toBe(false);
+ expect(isAgentAuthored({ type: 'harness', author: 'harness' })).toBe(false);
+ expect(isAgentAuthored({ type: 'result', author: 'system' })).toBe(false);
+ // A notify/error row draws a status pill with no Markdown body; it was
+ // excluded before and stays excluded.
+ expect(isAgentAuthored({ type: 'notify', author: 'agent' })).toBe(false);
+ expect(isAgentAuthored({ type: 'error', author: 'agent' })).toBe(false);
+ });
+});
+
+describe('drawsEmptyBodyPlaceholder', () => {
+ // An ordinary row really is broken-looking when it is empty, which is why the
+ // stand-in exists at all.
+ it('fills an ordinary empty bubble', () => {
+ expect(drawsEmptyBodyPlaceholder({ kind: 'user' }, false)).toBe(true);
+ expect(drawsEmptyBodyPlaceholder({ kind: 'agent' }, false)).toBe(true);
+ expect(drawsEmptyBodyPlaceholder({ kind: 'harness' }, false)).toBe(true);
+ });
+
+ // The empty annotation is a real, supported shape in BOTH directions — a pure
+ // highlight the annotator submitted with no comment (backend: an empty
+ // ``comment`` / empty mark ``body``). The frozen contract says the card then
+ // renders its title, quote and attachments ALONE, so an em dash here would be
+ // a body the annotator never wrote.
+ it('leaves an empty annotation to its title and quote', () => {
+ for (const direction of ['user', 'agent'] as const) {
+ const row = { kind: 'annotation' as const, annotation: { direction, resolved: false } };
+ expect(drawsEmptyBodyPlaceholder(row, false)).toBe(false);
+ }
+ });
+
+ // Unchanged from before the card existed: an attachment already fills the
+ // bubble, so nothing stands in for the missing words.
+ it('never draws it when an attachment already fills the bubble', () => {
+ expect(drawsEmptyBodyPlaceholder({ kind: 'user' }, true)).toBe(false);
+ expect(drawsEmptyBodyPlaceholder({ kind: 'agent' }, true)).toBe(false);
+ });
+});
diff --git a/ui/src/lib/chatRowKind.ts b/ui/src/lib/chatRowKind.ts
new file mode 100644
index 000000000..4fb1a5085
--- /dev/null
+++ b/ui/src/lib/chatRowKind.ts
@@ -0,0 +1,100 @@
+// Three adjacent questions about a transcript row, kept apart on purpose:
+// ``chatRowKind`` — which card family DRAWS it, ``isAgentAuthored`` — who WROTE
+// it, and ``drawsEmptyBodyPlaceholder`` — whether an empty one still needs a
+// stand-in body. All three agreed on every row until ``annotation`` arrived,
+// which is exactly why they are asked separately now (see the two below).
+//
+// A pure mapper so the branching is unit-tested without the component — the same
+// reason ``chatTrigger`` is one. It replaces a cascade of booleans read off the
+// row in ``MessageRow``, where the ordering between them was the load-bearing
+// part and nothing checked it.
+//
+// The ordering is the whole point. ``type`` is settled FIRST and returns, so a
+// message type can never be outvoted by who happens to be recorded as its
+// author. A forward annotation is authored by ``harness``: under the old
+// author/source-first cascade it drew as a collapsed trigger row behind a
+// "定时任务"-style chip, which is how an annotation looked before it had a type.
+//
+// ``author`` and ``source`` still decide among the ROLE families below, which is
+// what they legitimately describe. What they no longer do is decide whether a
+// typed row is that type.
+import { isNotifyMessageType } from './chatMessageTypes';
+import { readAnnotationView, type AnnotationView } from './annotationView';
+
+// A row typed ``annotation`` whose display record is unreadable. Every writer of
+// the type emits one, and the migration backfills ``direction: "agent"`` onto the
+// historical reverse marks, so reaching this is a backend defect — it is here so
+// the defect degrades INSIDE the annotation family (a card with the wrong title)
+// instead of escaping it (the user's own words, drawn as if the user typed them).
+const UNREADABLE_ANNOTATION: AnnotationView = { direction: 'agent', resolved: false };
+
+// The annotation case carries its view along, so a caller cannot narrow to the
+// family and then disagree with a second lookup about what is in it.
+export type ChatRowKind =
+ | { kind: 'annotation'; annotation: AnnotationView }
+ | { kind: 'notify' }
+ | { kind: 'agent' }
+ | { kind: 'system' }
+ | { kind: 'harness' }
+ | { kind: 'user' };
+
+type ChatRowFields = {
+ type: string;
+ author: string;
+ source?: string | null;
+ content?: unknown;
+};
+
+export function chatRowKind(message: ChatRowFields): ChatRowKind {
+ // Typed families first, and by ``type`` alone: not ``author``, not ``source``,
+ // not ``metadata.source`` (a forward annotation carries ``show_page`` in every
+ // state, including while it is still queued and belongs only to the strip).
+ if (message.type === 'annotation') {
+ return { kind: 'annotation', annotation: readAnnotationView(message.content) ?? UNREADABLE_ANNOTATION };
+ }
+ // Runtime notifications and legacy error rows are compact status pills, not
+ // Agent-authored answers.
+ if (isNotifyMessageType(message.type)) return { kind: 'notify' };
+
+ if (message.author === 'agent') return { kind: 'agent' };
+ if (message.author === 'system') return { kind: 'system' };
+ // A harness-origin row is turn input the human didn't type (scheduled task /
+ // watch / webhook); collapsed by default so it doesn't dominate.
+ if (message.source === 'harness') return { kind: 'harness' };
+ return { kind: 'user' };
+}
+
+// Did the AGENT write this row's text?
+//
+// Some Markdown affordances are earned by authorship, not by card family: a
+// ``$<NAME>`` marker becomes an interactive secret-input card only in the agent's
+// own words, because in anyone else's it would fake an "agent asked for this"
+// prompt. Before ``annotation`` existed, "drawn as the agent" and "written by the
+// agent" were the same rows, so one flag served both and the distinction cost
+// nothing to ignore.
+//
+// An agent's reverse mark broke that: it draws as an annotation and is still the
+// agent talking. Reading authorship off ``chatRowKind`` would silently strip the
+// card from it — re-creating, one field over, the same conflation this module
+// exists to delete. So this asks ``author`` directly, and equals
+// ``kind === 'agent'`` for every row EXCEPT an agent-authored annotation.
+export function isAgentAuthored(message: Pick<ChatRowFields, 'type' | 'author'>): boolean {
+ // Notify/error rows draw a status pill with no Markdown body at all; excluding
+ // them keeps this identical to the pre-annotation flag rather than widening it.
+ return !isNotifyMessageType(message.type) && message.author === 'agent';
+}
+
+// A row with no text: does it still need the ``—`` stand-in body?
+//
+// A bubble holding neither text nor attachment would draw as a bare rounded box
+// that reads as broken, so the transcript fills it with a muted em dash meaning
+// "this row really is empty".
+//
+// The annotation card is the one that is never bare — it always draws its title,
+// and usually the anchor quote — and an empty-text annotation is a SUPPORTED
+// shape rather than a defect: a pure highlight, where the quote is the whole of
+// what the annotator contributed. Both directions can be empty. So the stand-in
+// would not be filling a hole here, it would be adding a body nobody wrote.
+export function drawsEmptyBodyPlaceholder(row: ChatRowKind, hasAttachments: boolean): boolean {
+ return !hasAttachments && row.kind !== 'annotation';
+}
diff --git a/ui/src/lib/chatTrigger.test.ts b/ui/src/lib/chatTrigger.test.ts
index ca913bc99..86e7896c0 100644
--- a/ui/src/lib/chatTrigger.test.ts
+++ b/ui/src/lib/chatTrigger.test.ts
@@ -66,7 +66,6 @@ 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();
});
@@ -118,8 +117,15 @@ describe('harnessChipLabelKey (leading-label key by source presence)', () => {
}
});
- it('uses Show-specific labels for annotation and intent triggers', () => {
- expect(key({ author_name: 'show_annotation' })).toBe('chat.source.showAnnotation');
+ it('keeps the Show-specific label for a page-button intent', () => {
expect(key({ author_name: 'show_intent' })).toBe('chat.source.showIntent');
});
+
+ // An annotation is its own message type now and draws its own card, so it
+ // never reaches the harness chip. The branch that gave it a Show-specific
+ // label is gone along with the ``chat.source.showAnnotation`` string; this
+ // pins that it is not quietly re-added on the author_name side channel.
+ it('has no Show-specific label left for the retired show_annotation trigger', () => {
+ expect(key({ author_name: 'show_annotation' })).toBe('chat.source.harness');
+ });
});
diff --git a/ui/src/lib/chatTrigger.ts b/ui/src/lib/chatTrigger.ts
index 124a8e863..af8df6176 100644
--- a/ui/src/lib/chatTrigger.ts
+++ b/ui/src/lib/chatTrigger.ts
@@ -69,7 +69,10 @@ export function chatTriggerLink(message: TriggerFields, agentFallback: string):
}
const kind = message.author_name;
- if (kind === 'show_annotation' || kind === 'show_intent') return null;
+ // ``show_intent`` (a page button action) stays a non-navigating harness row.
+ // ``show_annotation`` no longer reaches here at all: an annotation is typed
+ // ``annotation`` and renders as its own card, never as a harness trigger row.
+ if (kind === 'show_intent') return null;
if (kind === 'watch' || TASK_KINDS.has(kind ?? '')) {
const itemKind = kind === 'watch' ? 'watch' : 'task';
return {
@@ -91,7 +94,6 @@ 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';
diff --git a/ui/src/lib/messageTypes.test.ts b/ui/src/lib/messageTypes.test.ts
index 9d0fdfa59..7cc844e1b 100644
--- a/ui/src/lib/messageTypes.test.ts
+++ b/ui/src/lib/messageTypes.test.ts
@@ -49,7 +49,15 @@ const PRE_REFACTOR_TYPES = [
'silent',
] as const;
-// Unknown / non-type strings the predicates must also agree on.
+// Unknown / non-type strings the predicates must also agree on. ``show_annotation``
+// is one of them on purpose: it is an ``author_name``, never a message type, and
+// keeping it here pins that it does not become one by the back door.
+//
+// ``annotation`` is deliberately absent. This block is an equivalence oracle
+// against pre-refactor behavior, and ``annotation`` is behavior that did not
+// exist then — it had no type, so the transcript reached it through
+// ``metadata.source``. Its behavior is pinned by the tests that own it
+// (chatMessageTypes / AnnotationMessage), not by an oracle it postdates.
const PROBE_TYPES: readonly string[] = [...PRE_REFACTOR_TYPES, 'show_annotation', 'future_type', ''];
const wasTranscript = (type: string): boolean =>
@@ -75,9 +83,9 @@ const wasTerminalAgentMessage = (message: TerminalCandidate): boolean =>
describe('catalog-derived predicates match pre-refactor behavior', () => {
it('transcript visibility (ChatPage isTranscriptMessage)', () => {
- // ``isTranscriptMessage`` is ``specFor(type).transcript`` OR the unchanged
- // ``metadata.source === 'show_page'`` side channel, so the catalog property is
- // the whole type-driven half of that predicate.
+ // ``isTranscriptMessage`` is now ``specFor(type).transcript`` and nothing
+ // else — the ``metadata.source`` side channel it used to be OR'd with is
+ // gone — so for these types the catalog property IS the predicate.
for (const type of PROBE_TYPES) {
expect(specFor(type).transcript, type).toBe(wasTranscript(type));
}
@@ -97,8 +105,11 @@ describe('catalog-derived predicates match pre-refactor behavior', () => {
it('harness input-turn identity (messageSearchRole type branch)', () => {
for (const type of PROBE_TYPES) {
- // Neutral author/source so the type test alone decides the role.
- const match = { author: 'agent', source: 'agent', type };
+ // A genuinely neutral author, so the type test alone decides the role.
+ // ``agent`` would not do: an agent-authored row is now attributed to the
+ // agent before the catalog is consulted, because a harness-input type can
+ // still carry agent-written rows (a reverse annotation is one).
+ const match = { author: 'system', source: 'system', type };
expect(messageSearchRole(match), type).toBe(wasHarnessInputType(type) ? 'automated' : 'agent');
expect(specFor(type).inputAuthors.includes('harness'), type).toBe(wasHarnessInputType(type));
}
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 4455965fe..ef2f38704 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -17,12 +17,6 @@
"acceptanceUnknown": "The Show event may still be processing. It was not replayed locally.",
"dispatchFailed": "The Show event was recorded, but its agent turn could not be delivered.",
"idConflict": "This Show event ID is already bound to different event contents."
- },
- "mark": {
- "created": "Page note",
- "updated": "Page note (updated)",
- "resolved": "Page note (resolved)",
- "quoteSuffix": "{header} · “{quote}”"
}
},
"harness": {
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index bbe7a31bf..3a580f7e8 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -17,12 +17,6 @@
"acceptanceUnknown": "Show 事件可能仍在处理中,未在本地重复提交。",
"dispatchFailed": "Show 事件已记录,但未能投递对应的 Agent turn。",
"idConflict": "此 Show 事件 ID 已绑定到不同的事件内容。"
- },
- "mark": {
- "created": "页面批注",
- "updated": "页面批注(已更新)",
- "resolved": "页面批注(已处理)",
- "quoteSuffix": "{header} ·「{quote}」"
}
},
"harness": {
diff --git a/vibe/message_types.json b/vibe/message_types.json
index 35ee03d3b..bddbd8023 100644
--- a/vibe/message_types.json
+++ b/vibe/message_types.json
@@ -35,6 +35,13 @@
"acceptedReservation": true,
"render": "harness"
},
+ "annotation": {
+ "transcript": true,
+ "searchable": true,
+ "inputAuthors": ["harness"],
+ "acceptedReservation": true,
+ "render": "annotation"
+ },
"result": {
"transcript": true,
"searchable": true,
diff --git a/vibe/message_types.py b/vibe/message_types.py
index b5d210b13..074c4bb9d 100644
--- a/vibe/message_types.py
+++ b/vibe/message_types.py
@@ -24,7 +24,15 @@ _LIST_PROPERTIES = {
}
_ENUM_PROPERTIES = {
"activityRole": {"none", "turn_start", "activity", "terminal"},
- "render": {"none", "user", "harness", "agent", "status", "activity"},
+ "render": {
+ "none",
+ "user",
+ "harness",
+ "annotation",
+ "agent",
+ "status",
+ "activity",
+ },
}
_PROPERTY_NAMES = _BOOL_PROPERTIES | _LIST_PROPERTIES | set(_ENUM_PROPERTIES)
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index da176728d..8f9e4a3a4 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -239,10 +239,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.
- 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.
+ Ordinary Chat rows are made visible without redispatching. Harness-owned rows
+ stay ``pending`` because no startup queue drain owns them; their originating
+ event can retry the same reservation and start the turn. Rows whose session is
+ missing or archived are deleted.
"""
from core.services import sessions as workbench_sessions_service
@@ -268,12 +268,21 @@ def _recover_stale_pending_messages() -> dict[str, int]:
summary["deleted"] += 1
continue
target_type = messages_service.pending_message_target_type(
- row.get("author"), row.get("source")
+ row.get("author"),
+ row.get("source"),
+ row.get("author_name"),
)
- if target_type == messages_service.HARNESS_TYPE:
+ if target_type in {
+ messages_service.HARNESS_TYPE,
+ messages_service.ANNOTATION_TYPE,
+ }:
summary["skipped"] += 1
continue
- promoted = messages_service.promote_pending(conn, str(row["id"]), target_type)
+ promoted = messages_service.promote_pending(
+ conn,
+ str(row["id"]),
+ target_type,
+ )
if not promoted:
summary["skipped"] += 1
continue
@@ -6392,7 +6401,6 @@ async def sessions_bootstrap(session_id: str):
session_id=session_id,
limit=50,
types=messages_service.TRANSCRIPT_TYPES,
- include_metadata_sources=("show_page",),
tail=True,
)
queued = messages_service.list_queued(conn, session_id)
@@ -6764,9 +6772,7 @@ def sessions_messages_list(session_id: str):
# persist intermediate assistant / tool_call rows (unified store) that we
# keep OUT of the conversation view, but ``notify`` rows are kept: a
# terminal notify (e.g. an agent run that failed and stopped without a
- # result) marks the end of that turn and must stay visible. Show-Page
- # transcript marks (metadata.source='show_page') are kept regardless of
- # type.
+ # result) marks the end of that turn and must stay visible.
result = messages_service.list_session_messages(
conn,
session_id=session_id,
@@ -6775,7 +6781,6 @@ def sessions_messages_list(session_id: str):
around_id=around_id,
limit=limit,
types=messages_service.TRANSCRIPT_TYPES,
- include_metadata_sources=("show_page",),
tail=tail,
)
return jsonify(result)
@@ -9269,13 +9274,17 @@ def record_local_show_event(
def _publish_show_session_event(event_payload: dict[str, Any]) -> None:
+ from storage import messages_service
from vibe.sse_broker import broker
broker.publish("show.event", event_payload)
message = event_payload.get("message")
if show_event_requests_dispatch(event_payload):
return
- if isinstance(message, dict):
+ if (
+ isinstance(message, dict)
+ and message.get("type") in messages_service.TRANSCRIPT_TYPES
+ ):
broker.publish("message.new", message)
broker.publish(
"session.activity",
@@ -9296,14 +9305,11 @@ async def _run_show_event_dispatch(
session_id = event_payload.get("session_id")
scope_id = event_payload.get("scope_id")
event_id = event_payload.get("id")
- transcript_text = event_payload.get("transcript_text")
if (
not isinstance(session_id, str)
or not session_id
or not isinstance(event_id, str)
or not event_id
- or not isinstance(transcript_text, str)
- or not transcript_text.strip()
):
return _ShowEventDispatchOutcome.FAILED
@@ -9316,9 +9322,13 @@ async def _run_show_event_dispatch(
if message_type != messages_service.PENDING_TYPE:
return _ShowEventDispatchOutcome.FAILED
+ dispatch_text = _show_event_dispatch_text(event_payload)
+ if not dispatch_text.strip():
+ return _ShowEventDispatchOutcome.FAILED
+
dispatch_payload = {
"session_id": session_id,
- "text": _show_event_dispatch_text(event_payload),
+ "text": dispatch_text,
"scope_id": scope_id,
"user_message_id": message["id"],
"show_event_id": event_id,
@@ -9382,12 +9392,8 @@ def _settle_show_event_message(
return None
with _projects_engine().begin() as conn:
- row = conn.execute(
- select(
- messages.c.id,
- messages.c.author,
- messages.c.source,
- )
+ message_id = conn.execute(
+ select(messages.c.id)
.select_from(
show_session_events.join(
messages,
@@ -9398,7 +9404,16 @@ def _settle_show_event_message(
show_session_events.c.id == event_id,
show_session_events.c.session_id == session_id,
)
- ).mappings().first()
+ ).scalar_one_or_none()
+ row = (
+ messages_service.get_message(
+ conn,
+ str(message_id),
+ session_id=session_id,
+ )
+ if message_id
+ else None
+ )
promoted = bool(
row
and messages_service.promote_pending(
@@ -9407,6 +9422,7 @@ def _settle_show_event_message(
messages_service.pending_message_target_type(
row.get("author"),
row.get("source"),
+ row.get("author_name"),
),
)
)
@@ -9424,7 +9440,10 @@ def _settle_show_event_message(
event_payload["message_id"] = message["id"]
event_payload["message"] = message
- if promoted and message.get("type") == messages_service.HARNESS_TYPE:
+ if promoted and message.get("type") in {
+ messages_service.HARNESS_TYPE,
+ messages_service.ANNOTATION_TYPE,
+ }:
_publish_visible_input_message(
message,
session_id=session_id,
@@ -9473,6 +9492,28 @@ def _load_session_message(session_id: str, message_id: str) -> dict[str, Any] |
def _show_event_dispatch_text(event_payload: dict[str, Any]) -> str:
+ from storage import messages_service
+
+ message = event_payload.get("message")
+ if not isinstance(message, dict):
+ return ""
+ metadata = message.get("metadata")
+ if not isinstance(metadata, dict):
+ return ""
+ if messages_service.QUEUED_DISPATCH_TEXT_KEY in metadata:
+ return str(
+ metadata.get(messages_service.QUEUED_DISPATCH_TEXT_KEY) or ""
+ ).strip()
+
+ # Pre-upgrade reservations stored the machine prompt on the Show event.
+ # Current annotation rows must never replay their stripped display body.
+ content = message.get("content")
+ if isinstance(content, dict) and isinstance(content.get("annotation"), dict):
+ return ""
+ return _legacy_show_event_dispatch_text(event_payload)
+
+
+def _legacy_show_event_dispatch_text(event_payload: dict[str, Any]) -> str:
transcript_text = str(event_payload.get("transcript_text") or "").strip()
if event_payload.get("type") != "human.annotation.created":
return transcript_text