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.

feat(show): add agent reply marks and read receipts (#955)

Call Whitee71890a78209
diff --git a/core/show_session_events.py b/core/show_session_events.py
index eb8c52441..f264cd61d 100644
--- a/core/show_session_events.py
+++ b/core/show_session_events.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import hashlib
import json
import uuid
from dataclasses import dataclass
@@ -48,6 +49,11 @@ ANNOTATION_PRIMARY_ANCHORS = {
"area",
"screenshot",
}
+ASSISTANT_MARK_EVENT_TYPES = {
+ "assistant.mark.created",
+ "assistant.mark.updated",
+ "assistant.mark.resolved",
+}
class ShowSessionEventError(ValueError):
@@ -82,15 +88,8 @@ class ShowSessionEventStore:
validate_show_event_payload_session(session_id, payload)
event_type = _validate_event_type(payload.get("type"))
actor = _actor_for_event(event_type)
- event_payload = _normalize_event_payload(event_type, payload)
- if actor == "human":
- event_payload.pop("author", None)
- anchor = _event_anchor(event_type, payload, event_payload)
- scope = _event_scope(event_type, event_payload)
- transcript_text = _format_transcript_text(event_type, event_payload, anchor)
- if actor == "human":
- event_payload["author"] = _normalize_human_author(author)
- event_id = _event_id(payload, event_payload)
+ records_author = actor == "human" or (event_type == "assistant.mark.resolved" and author is not None)
+ event_id = _event_id(payload, {})
created_at = _utc_now_iso()
with self.engine.begin() as conn:
@@ -106,6 +105,22 @@ class ShowSessionEventStore:
if session["status"] == "archived":
raise ShowSessionEventError("Agent session is archived.", code="session_archived")
+ stored_payload = payload
+ if event_type == "assistant.mark.resolved":
+ stored_payload = _prepare_mark_resolution(conn, session_id, payload)
+ event_payload = _normalize_event_payload(event_type, stored_payload)
+ if records_author:
+ event_payload.pop("author", None)
+ anchor = _event_anchor(event_type, stored_payload, event_payload)
+ scope = _event_scope(event_type, event_payload)
+ transcript_text = (
+ ""
+ if event_type == "assistant.mark.resolved" and author is not None
+ else _format_transcript_text(event_type, event_payload, anchor)
+ )
+ if records_author:
+ event_payload["author"] = _normalize_human_author(author)
+
conn.execute(
show_session_events.insert().values(
id=event_id,
@@ -136,7 +151,7 @@ class ShowSessionEventStore:
"show_event_id": event_id,
"show_event_type": event_type,
"show_event_scope": scope,
- **({"author": event_payload["author"]} if actor == "human" else {}),
+ **({"author": event_payload["author"]} if "author" in event_payload else {}),
},
native_message_id=f"show:{event_id}",
)
@@ -187,6 +202,137 @@ class ShowSessionEventStore:
"next_after_id": rows[-1]["id"] if len(rows) == effective_limit else None,
}
+ def get_annotation_event(self, session_id: str, event_id: str) -> dict[str, Any] | None:
+ with self.engine.connect() as conn:
+ row = conn.execute(
+ select(show_session_events)
+ .where(
+ show_session_events.c.session_id == session_id,
+ show_session_events.c.id == event_id,
+ show_session_events.c.event_type == "human.annotation.created",
+ )
+ .limit(1)
+ ).mappings().first()
+ return _row_to_payload(dict(row)) if row is not None else None
+
+ def recent_annotation_event_ids(self, session_id: str, *, limit: int = 10) -> list[str]:
+ effective_limit = min(max(int(limit), 1), 50)
+ with self.engine.connect() as conn:
+ rows = conn.execute(
+ select(show_session_events.c.id)
+ .where(
+ show_session_events.c.session_id == session_id,
+ show_session_events.c.event_type == "human.annotation.created",
+ )
+ .order_by(show_session_events.c.created_at.desc(), show_session_events.c.id.desc())
+ .limit(effective_limit)
+ ).all()
+ return [str(row[0]) for row in rows]
+
+ def active_marks(self, session_id: str) -> list[dict[str, Any]]:
+ with self.engine.connect() as conn:
+ return _active_marks_from_connection(conn, session_id)
+
+
+def stable_assistant_mark_id(*, scope: str, target: str | None = None, reply_to: str | None = None) -> str:
+ normalized_scope = _text_or_none(scope) or DEFAULT_MARK_SCOPE
+ if reply_to:
+ identity = f"reply:{reply_to.strip()}"
+ elif target:
+ identity = f"note:{target.strip()}"
+ else:
+ raise ValueError("target or reply_to is required")
+ digest = hashlib.sha256(f"{normalized_scope}\0{identity}".encode()).hexdigest()[:16]
+ return f"mark_{digest}"
+
+
+def project_active_assistant_marks(events: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ active_by_key: dict[tuple[str, str, str], dict[str, Any]] = {}
+ key_by_mark_id: dict[str, tuple[str, str, str]] = {}
+
+ for event in events:
+ event_type = str(event.get("type") or "")
+ if event_type not in ASSISTANT_MARK_EVENT_TYPES:
+ continue
+ payload = event.get("payload") or event.get("mark")
+ if not isinstance(payload, dict):
+ continue
+ mark_id = _text_or_none(payload.get("id"))
+ if not mark_id:
+ continue
+
+ if event_type == "assistant.mark.resolved" or payload.get("status") == "resolved":
+ key = key_by_mark_id.pop(mark_id, None)
+ if key is not None:
+ active_by_key.pop(key, None)
+ continue
+
+ key = _assistant_mark_replacement_key(payload)
+ previous = active_by_key.pop(key, None)
+ if previous is not None:
+ key_by_mark_id.pop(str(previous["id"]), None)
+ mark = {
+ **payload,
+ "id": mark_id,
+ "kind": "reply" if _text_or_none(payload.get("replyTo")) else "note",
+ "anchor": dict(event.get("anchor") or {}),
+ "event_id": event.get("id"),
+ "read_state": "unread",
+ }
+ mark.pop("author", None)
+ active_by_key[key] = mark
+ key_by_mark_id[mark_id] = key
+
+ return list(active_by_key.values())
+
+
+def _active_marks_from_connection(conn: Any, session_id: str) -> list[dict[str, Any]]:
+ rows = conn.execute(
+ select(show_session_events)
+ .where(
+ show_session_events.c.session_id == session_id,
+ show_session_events.c.event_type.in_(ASSISTANT_MARK_EVENT_TYPES),
+ )
+ .order_by(show_session_events.c.created_at.asc(), show_session_events.c.id.asc())
+ ).mappings().all()
+ return project_active_assistant_marks([_row_to_payload(dict(row)) for row in rows])
+
+
+def _prepare_mark_resolution(conn: Any, session_id: str, payload: dict[str, Any]) -> dict[str, Any]:
+ requested_mark = _normalize_json_object(payload.get("mark") or payload.get("payload"))
+ mark_id = _required_text(requested_mark.get("id"), "mark.id")
+ active_mark = next(
+ (mark for mark in _active_marks_from_connection(conn, session_id) if mark.get("id") == mark_id),
+ None,
+ )
+ if active_mark is None:
+ raise ShowSessionEventError("Assistant mark is not active.", code="mark_not_active")
+
+ requested_version = _text_or_none(requested_mark.get("updatedAt"))
+ if requested_version is None:
+ raise ShowSessionEventError("mark.updatedAt is required.", code="mark_version_required")
+ if requested_version != _text_or_none(active_mark.get("updatedAt")):
+ raise ShowSessionEventError("Assistant mark has changed.", code="mark_version_conflict")
+
+ mark = {
+ key: active_mark[key]
+ for key in ("id", "scope", "target", "body", "createdAt", "updatedAt", "replyTo")
+ if active_mark.get(key) is not None
+ }
+ return {
+ "type": "assistant.mark.resolved",
+ "mark": mark,
+ "anchor": dict(active_mark.get("anchor") or {}),
+ }
+
+
+def _assistant_mark_replacement_key(payload: dict[str, Any]) -> tuple[str, str, str]:
+ scope = _text_or_none(payload.get("scope")) or DEFAULT_MARK_SCOPE
+ reply_to = _text_or_none(payload.get("replyTo"))
+ if reply_to:
+ return (scope, "reply", reply_to)
+ return (scope, "note", _text_or_none(payload.get("target")) or "")
+
def show_event_payload_session_mismatch(session_id: str, payload: dict[str, Any]) -> str | None:
for candidate in _show_event_session_id_containers(payload):
@@ -244,7 +390,7 @@ def _normalize_event_payload(event_type: str, payload: dict[str, Any]) -> dict[s
target = _required_text(mark.get("target"), "mark.target")
body = _required_text(mark.get("body") or mark.get("comment"), "mark.body")
created_at = _text_or_none(mark.get("createdAt")) or _utc_now_iso()
- return {
+ normalized = {
"id": _text_or_none(mark.get("id")) or _new_id("mark"),
"role": "assistant",
"scope": _text_or_none(mark.get("scope")) or DEFAULT_MARK_SCOPE,
@@ -255,6 +401,10 @@ def _normalize_event_payload(event_type: str, payload: dict[str, Any]) -> dict[s
"updatedAt": _text_or_none(mark.get("updatedAt")) or created_at,
"resolvedAt": _text_or_none(mark.get("resolvedAt")) if event_type != "assistant.mark.resolved" else _text_or_none(mark.get("resolvedAt")) or _utc_now_iso(),
}
+ reply_to = _text_or_none(mark.get("replyTo"))
+ if reply_to:
+ normalized["replyTo"] = reply_to
+ return normalized
if event_type == "human.intent.submitted":
intent_payload = _normalize_json_object(payload.get("payload") or payload)
created_at = _text_or_none(intent_payload.get("createdAt")) or _utc_now_iso()
diff --git a/docs/plans/show-page-annotation-phase2-agent-marks.md b/docs/plans/show-page-annotation-phase2-agent-marks.md
new file mode 100644
index 000000000..144c6200d
--- /dev/null
+++ b/docs/plans/show-page-annotation-phase2-agent-marks.md
@@ -0,0 +1,141 @@
+# Show Page Annotation — Phase 2: Agent Reverse Marks (full loop)
+
+Status: draft for owner review (CLI surface is the owner-review focal point).
+Positioning ruled by owner 2026-07-22: reverse marks are **conversation
+bubbles, not document comments** — every lifecycle rule below derives from
+that.
+
+## Goal
+
+Close the second half of the annotate loop: the user points at the page and
+asks; the agent answers **on the page**, anchored to what the user pointed at.
+Chat keeps the transcript; the page carries the conversation.
+
+Two complementary mark kinds:
+
+| Kind | Authored via | Nature | Lifecycle owner |
+| --- | --- | --- | --- |
+| **Reply mark** (回应型) | `vibe show reply` (CLI, event-backed) | Answers a specific user annotation | Read-to-retire pairing |
+| **Note mark** (说明型) | `vibe show mark` (CLI) or `mark-note` attribute (declarative, in page source) | Agent's own callout on an element | CLI: replace-on-same-target + read-to-fade; attribute: lives/dies with the source |
+
+## Agent-facing API (owner review section)
+
+### 1. `vibe show reply` — answer a user annotation on the page
+
+```bash
+vibe show reply <show-event-id> --message "因为 W30 那周切换了数据源,旧口径少统计了周末的通过数。"
+```
+
+- `<show-event-id>` is copied verbatim from the dispatched annotation message
+ (see "Dispatch guidance" below — the message now prints a ready-to-run
+ command, so the agent never has to construct anything).
+- Auto-resolved: target anchor (from the referenced annotation), session id
+ (injected env), mark kind (`reply`), pairing (this mark answers that
+ annotation).
+- Optional: `--message-file <path>` for long/multiline answers.
+- Errors are instructive: unknown/foreign event id → lists the session's
+ recent annotation ids; already-replied → says so and points to
+ `vibe show marks`.
+
+### 2. `vibe show mark` — proactive callout on an element
+
+```bash
+vibe show mark <target> --message "本区块已切换到新数据源,历史口径见下方注脚。"
+```
+
+- `<target>` (positional, new; `--target` kept as alias for compat):
+ a `mark-*` anchor name (`summary.conclusion`) or a CSS selector
+ (`#revenue-card`, `.chart-title`).
+- Same target marked again → **replaces** the previous note (no stacking).
+- Session id injected; `--scope` stays optional (default `default`).
+
+### 3. `mark-note` attribute — declarative note in page source
+
+```jsx
+<section mark-default="q3.summary" mark-note="这里我改用了新数据源">
+```
+
+- Any element authored by the agent can carry `mark-note="<text>"`; the
+ overlay renders the standard violet mark for it. Pairs naturally with the
+ existing `mark-default` anchor attribute (same naming family).
+- Lifecycle = source lifecycle: edit/remove the attribute and the mark
+ follows on next render. No events involved.
+
+### 4. `vibe show marks` — inspect / tidy
+
+```bash
+vibe show marks # list active marks (id, kind, target, read state)
+vibe show unmark <id|target> [<id|target> ...] # retire one or more marks (space-separated)
+```
+
+`unmark` accepts multiple space-separated ids/targets in one invocation
+(owner-approved 2026-07-23); partial failures report per-item results and
+exit non-zero only if none succeeded.
+
+### Dispatch guidance (teaching the agent, zero prompting burden)
+
+When a user annotation with `intent: "question"` is dispatched, the message
+appended to the agent turn ends with:
+
+```
+用户在页面上提出了疑问。请优先把回答放回页面上用户指的位置(chat 里保留一句简短结论即可):
+ vibe show reply show_evt_1a2b3c4d --message '<你的回答>'
+```
+
+Other intents get no reply exhortation (change/fix expect page edits;
+comment/approve expect acknowledgement), but the event id is always printed
+so `vibe show reply` remains available.
+
+## Lifecycle rules (conversation-bubble model)
+
+1. **Unread is loud, read retires.** A mark renders as the violet dot until
+ the user expands it. Expanding emits `assistant.mark.resolved` (existing
+ event type) → the mark fades to a small gray dot for the rest of the page
+ view and is not rendered on subsequent loads. Read state is event-backed
+ (cross-device), not localStorage — except attribute notes (no event
+ identity), which record read state in localStorage keyed by
+ session+anchor+text-hash.
+2. **Reply marks are paired.** A reply mark references the annotation event
+ it answers. Pair completes when read; a completed pair never re-renders,
+ regardless of later page changes.
+3. **Cap + aggregate.** At most **5** active (unread) marks render inline.
+ Overflow collects into a persistent bottom-right badge (count); its list
+ shows every active mark including inline ones. Agents are also guided to
+ leave at most 1–2 marks per turn.
+4. **Anchor failure degrades, never mis-pins.** Resolution uses the existing
+ multi-level fallback with confidence. `missing`/low-confidence marks are
+ NOT rendered at a guessed position; they appear only in the badge list,
+ labeled "原位置已更新", content still readable.
+5. **Replace, don't stack.** CLI `mark` on the same target replaces; `reply`
+ on an already-answered annotation replaces the previous reply.
+
+## Implementation slices
+
+- **Lane A (avibe)**: `vibe show reply` + `vibe show marks`/`unmark` CLI
+ (reuse mark plumbing; reply resolves the referenced event's anchor and
+ emits `assistant.mark.created` with pairing metadata `replyTo`); dispatch
+ template gains the question-intent guidance block + always prints the
+ event id; `assistant.mark.resolved` accepted from the page (read receipts)
+ — POST path already exists, ensure resolved-by-user authoring is allowed
+ and author-stamped.
+- **Lane R (vibe-show-runtime)**: mark rendering upgrade (unread violet →
+ expand bubble → emit resolved → gray fade); `mark-note` attribute pickup
+ (registry scan alongside `mark-*` anchors); cap-and-aggregate badge +
+ list; missing-anchor list entries; replace semantics on render
+ (same target/pair → newest wins).
+- No frozen-contract changes: new CLI verbs are additive; `replyTo` rides
+ inside the existing mark payload; read receipts use the existing
+ `assistant.mark.resolved` type (author = the reading user).
+
+## Acceptance sketch
+
+1. On-page question → agent runs the printed `vibe show reply` → violet dot
+ appears beside the questioned element; expanding shows the answer; after
+ reading, it fades and never returns on reload.
+2. `vibe show mark #revenue-card --message …` twice → single note (replaced).
+3. Page with 7 unread marks → 5 inline + badge shows 7; clicking badge lists
+ all; reading retires each.
+4. Agent rewrites the page section → orphaned mark moves to the badge list
+ as "原位置已更新" (never mis-pinned).
+5. `mark-note` attribute renders a mark; removing the attribute removes it;
+ read state survives reload via localStorage.
diff --git a/tests/test_show_pages.py b/tests/test_show_pages.py
index e0f62e789..3af89278b 100644
--- a/tests/test_show_pages.py
+++ b/tests/test_show_pages.py
@@ -82,7 +82,8 @@ def test_show_without_subcommand_prints_help(capsys):
assert cli.cmd_show(args) == 0
captured = capsys.readouterr()
assert "Manage the one visual Show Page attached to an Agent Session." in captured.out
- assert "usage: vibe show [-h] {list,path,status,update,mark,event,annotate} ..." in captured.out
+ assert "usage: vibe show [-h]" in captured.out
+ assert "{list,path,status,update,mark,reply,marks,unmark,event,annotate} ..." in " ".join(captured.out.split())
assert "vibe show list" in captured.out
assert "vibe show path --session-id sesk8m4q2p7x" in captured.out
@@ -2074,6 +2075,35 @@ def test_show_update_rotate_share_fails_while_private(monkeypatch, tmp_path, cap
assert payload["code"] == "not_public"
+def _seed_show_cli_session(session_id: str = "ses123") -> None:
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.models import agent_sessions
+ from storage.settings_service import upsert_scope
+
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ now = messages_service._utc_now_iso()
+ with engine.begin() as conn:
+ scope_id = upsert_scope(conn, platform="avibe", scope_type="project", native_id="proj_show", now=now)
+ conn.execute(
+ agent_sessions.insert().values(
+ id=session_id,
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_variant="default",
+ session_anchor=f"anchor_{session_id}",
+ native_session_id="",
+ status="active",
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+
+
def test_show_mark_cli_records_event_and_message(monkeypatch, tmp_path, capsys):
from storage.db import create_sqlite_engine
from storage.models import agent_sessions, messages, show_session_events
@@ -2259,6 +2289,182 @@ def test_show_mark_cli_posts_to_live_ui_when_running(monkeypatch, tmp_path, caps
assert captured["timeout"] == 3
+def test_show_reply_copies_annotation_anchor_and_replaces_prior_reply(monkeypatch, tmp_path, capsys):
+ from core.show_session_events import ShowSessionEventStore
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ _save_config()
+ _seed_show_cli_session()
+ store = ShowSessionEventStore()
+ try:
+ annotation = store.append(
+ "ses123",
+ {
+ "type": "human.annotation.created",
+ "annotation": {
+ "intent": "question",
+ "comment": "Why did this change?",
+ "anchor": {
+ "kind": "text-range",
+ "selector": "#revenue-card",
+ "textQuote": "Revenue",
+ },
+ },
+ },
+ )
+ finally:
+ store.close()
+
+ first_args = cli.build_parser().parse_args(
+ ["show", "reply", annotation["id"], "--session-id", "ses123", "--message", "First answer.", "--json"]
+ )
+ assert cli.cmd_show(first_args) == 0
+ first = json.loads(capsys.readouterr().out)
+
+ second_args = cli.build_parser().parse_args(
+ ["show", "reply", annotation["id"], "--session-id", "ses123", "--message", "Better answer.", "--json"]
+ )
+ assert cli.cmd_show(second_args) == 0
+ second = json.loads(capsys.readouterr().out)
+
+ assert first["mark_id"] == second["mark_id"]
+ assert first["event"]["anchor"] == annotation["anchor"]
+ assert first["event"]["payload"]["target"] == "#revenue-card"
+ assert first["event"]["payload"]["replyTo"] == annotation["id"]
+ assert second["replaced"] is True
+ assert "vibe show marks" in second["replacement_notice"]
+
+ store = ShowSessionEventStore()
+ try:
+ active = store.active_marks("ses123")
+ finally:
+ store.close()
+ assert len(active) == 1
+ assert active[0]["kind"] == "reply"
+ assert active[0]["body"] == "Better answer."
+
+
+def test_show_reply_unknown_id_lists_recent_session_annotation_ids(monkeypatch, tmp_path, capsys):
+ from core.show_session_events import ShowSessionEventStore
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ _save_config()
+ _seed_show_cli_session()
+ store = ShowSessionEventStore()
+ try:
+ recent = store.append(
+ "ses123",
+ {"type": "human.annotation.created", "annotation": {"comment": "Known annotation."}},
+ )
+ finally:
+ store.close()
+
+ args = cli.build_parser().parse_args(
+ ["show", "reply", "show_evt_foreign", "--session-id", "ses123", "--message", "Answer.", "--json"]
+ )
+ assert cli.cmd_show(args) == 1
+ error = json.loads(capsys.readouterr().err)
+ assert error["code"] == "show_annotation_not_found"
+ assert error["details"]["recent_annotation_event_ids"] == [recent["id"]]
+ assert recent["id"] in error["error"]
+
+
+def test_show_mark_positional_target_replaces_same_target(monkeypatch, tmp_path, capsys):
+ from core.show_session_events import ShowSessionEventStore
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ _save_config()
+ _seed_show_cli_session()
+
+ first_args = cli.build_parser().parse_args(
+ ["show", "mark", "#revenue-card", "--session-id", "ses123", "--message", "First note.", "--json"]
+ )
+ assert cli.cmd_show(first_args) == 0
+ first = json.loads(capsys.readouterr().out)
+ second_args = cli.build_parser().parse_args(
+ ["show", "mark", "--target", "#revenue-card", "--session-id", "ses123", "--body", "New note.", "--json"]
+ )
+ assert cli.cmd_show(second_args) == 0
+ second = json.loads(capsys.readouterr().out)
+
+ assert first["mark_id"] == second["mark_id"]
+ assert second["replaced"] is True
+ store = ShowSessionEventStore()
+ try:
+ active = store.active_marks("ses123")
+ finally:
+ store.close()
+ assert [(mark["target"], mark["body"]) for mark in active] == [("#revenue-card", "New note.")]
+
+
+def test_show_marks_filters_resolved_and_unmark_reports_partial_success(monkeypatch, tmp_path, capsys):
+ from core.show_session_events import ShowSessionEventStore, stable_assistant_mark_id
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ _save_config()
+ _seed_show_cli_session()
+ first_id = stable_assistant_mark_id(scope="default", target="#first")
+ second_id = stable_assistant_mark_id(scope="default", target="#second")
+ store = ShowSessionEventStore()
+ try:
+ first = store.append(
+ "ses123",
+ {"type": "assistant.mark.created", "mark": {"id": first_id, "target": "#first", "body": "First."}},
+ )
+ store.append(
+ "ses123",
+ {"type": "assistant.mark.created", "mark": {"id": second_id, "target": "#second", "body": "Second."}},
+ )
+ store.append(
+ "ses123",
+ {
+ "type": "assistant.mark.resolved",
+ "mark": {"id": first_id, "updatedAt": first["payload"]["updatedAt"]},
+ },
+ )
+ finally:
+ store.close()
+
+ marks_args = cli.build_parser().parse_args(["show", "marks", "--session-id", "ses123", "--json"])
+ assert cli.cmd_show(marks_args) == 0
+ listing = json.loads(capsys.readouterr().out)
+ assert listing["marks"] == [
+ {
+ "id": second_id,
+ "kind": "note",
+ "target": "#second",
+ "body_head": "Second.",
+ "read_state": "unread",
+ }
+ ]
+
+ unmark_args = cli.build_parser().parse_args(
+ ["show", "unmark", second_id, "missing-target", "--session-id", "ses123", "--json"]
+ )
+ assert cli.cmd_show(unmark_args) == 0
+ result = json.loads(capsys.readouterr().out)
+ assert result["succeeded"] == 1
+ assert result["failed"] == 1
+ assert [item["ok"] for item in result["results"]] == [True, False]
+
+ missing_args = cli.build_parser().parse_args(
+ ["show", "unmark", "missing-one", "missing-two", "--session-id", "ses123", "--json"]
+ )
+ assert cli.cmd_show(missing_args) == 1
+ missing = json.loads(capsys.readouterr().out)
+ assert missing["succeeded"] == 0
+
+ store = ShowSessionEventStore()
+ try:
+ assert store.active_marks("ses123") == []
+ finally:
+ store.close()
+
+
def test_show_event_cli_records_generic_event(monkeypatch, tmp_path, capsys):
from sqlalchemy import select
diff --git a/tests/test_show_session_events.py b/tests/test_show_session_events.py
index 93d1f3346..ced06b14b 100644
--- a/tests/test_show_session_events.py
+++ b/tests/test_show_session_events.py
@@ -432,8 +432,7 @@ def test_show_event_store_keeps_object_ids_separate_from_event_ids(isolated_stat
"type": "assistant.mark.resolved",
"mark": {
"id": "mark_1",
- "target": "summary",
- "body": "Resolved.",
+ "updatedAt": created["payload"]["updatedAt"],
},
},
)
@@ -447,6 +446,118 @@ def test_show_event_store_keeps_object_ids_separate_from_event_ids(isolated_stat
assert created["id"] != resolved["id"]
+def test_show_event_store_hydrates_read_receipt_from_active_mark(isolated_state):
+ _seed_session()
+
+ store = ShowSessionEventStore()
+ try:
+ created = store.append(
+ "ses_mark",
+ {
+ "type": "assistant.mark.created",
+ "mark": {"id": "mark_1", "target": "summary", "body": "Server body."},
+ "anchor": {"selector": "#summary", "text": "Summary"},
+ },
+ )
+ resolved = store.append(
+ "ses_mark",
+ {
+ "type": "assistant.mark.resolved",
+ "mark": {
+ "id": "mark_1",
+ "updatedAt": created["payload"]["updatedAt"],
+ "target": "forged",
+ "body": "Forged body.",
+ },
+ "anchor": {"selector": "#forged"},
+ },
+ author={"kind": "user", "email": "[email protected]"},
+ )
+ finally:
+ store.close()
+
+ assert resolved["payload"]["target"] == "summary"
+ assert resolved["payload"]["body"] == "Server body."
+ assert resolved["anchor"] == {"selector": "#summary", "text": "Summary"}
+ assert resolved["payload"]["author"] == {"kind": "user", "email": "[email protected]"}
+ assert resolved["transcript_text"] == ""
+ assert resolved["message_id"] is None
+ assert resolved["message"] is None
+
+
+ ("mark", "expected_code"),
+ [
+ ({"id": "missing", "updatedAt": "2026-07-23T00:00:00Z"}, "mark_not_active"),
+ ({"id": "mark_1"}, "mark_version_required"),
+ ],
+)
+def test_show_event_store_rejects_invalid_mark_resolution(isolated_state, mark, expected_code):
+ _seed_session()
+ store = ShowSessionEventStore()
+ try:
+ store.append(
+ "ses_mark",
+ {
+ "type": "assistant.mark.created",
+ "mark": {"id": "mark_1", "target": "summary", "body": "Current."},
+ },
+ )
+ with pytest.raises(ShowSessionEventError) as exc_info:
+ store.append("ses_mark", {"type": "assistant.mark.resolved", "mark": mark})
+ finally:
+ store.close()
+
+ assert exc_info.value.code == expected_code
+
+
+def test_show_event_store_rejects_stale_mark_read_receipt(isolated_state):
+ _seed_session()
+ store = ShowSessionEventStore()
+ try:
+ original = store.append(
+ "ses_mark",
+ {
+ "type": "assistant.mark.created",
+ "mark": {
+ "id": "mark_1",
+ "target": "summary",
+ "body": "Original.",
+ "createdAt": "2026-07-23T00:00:00Z",
+ "updatedAt": "2026-07-23T00:00:00Z",
+ },
+ },
+ )
+ store.append(
+ "ses_mark",
+ {
+ "type": "assistant.mark.updated",
+ "mark": {
+ "id": "mark_1",
+ "target": "summary",
+ "body": "Replacement.",
+ "createdAt": original["payload"]["createdAt"],
+ "updatedAt": "2026-07-23T00:00:01Z",
+ },
+ },
+ )
+ with pytest.raises(ShowSessionEventError) as exc_info:
+ store.append(
+ "ses_mark",
+ {
+ "type": "assistant.mark.resolved",
+ "mark": {"id": "mark_1", "updatedAt": original["payload"]["updatedAt"]},
+ },
+ author={"kind": "local"},
+ )
+ active = store.active_marks("ses_mark")
+ finally:
+ store.close()
+
+ assert exc_info.value.code == "mark_version_conflict"
+ assert [(mark["id"], mark["body"]) for mark in active] == [("mark_1", "Replacement.")]
+
+
def test_show_event_store_records_intent_dispatch_payload(isolated_state):
_seed_session()
@@ -596,3 +707,41 @@ def test_show_event_dispatch_streams_via_stream_dispatch(isolated_state, monkeyp
"turn.chunk",
"turn.end",
]
+
+
+ ("intent", "expects_guidance"),
+ [("question", True), ("change", False)],
+)
+def test_annotation_dispatch_text_adds_event_id_and_question_guidance_only(monkeypatch, intent, expects_guidance):
+ import asyncio
+
+ from vibe import internal_client, ui_server
+
+ captured = []
+
+ async def fake_stream_dispatch(payload, **kwargs):
+ captured.append(payload)
+ if False:
+ yield None
+
+ monkeypatch.setattr(internal_client, "stream_dispatch", fake_stream_dispatch)
+ event = {
+ "id": "show_evt_1a2b3c4d",
+ "type": "human.annotation.created",
+ "session_id": "ses_show",
+ "scope_id": "scope1",
+ "payload": {"intent": intent},
+ "transcript_text": "[show-annotation:default:created] question\n\nWhy?",
+ "message_id": "m1",
+ }
+
+ asyncio.run(ui_server._run_show_event_dispatch(event))
+
+ assert event["transcript_text"] == "[show-annotation:default:created] question\n\nWhy?"
+ assert "Show event id: show_evt_1a2b3c4d" in captured[0]["text"]
+ guidance = (
+ "用户在页面上提出了疑问。请优先把回答放回页面上用户指的位置(chat 里保留一句简短结论即可):\n"
+ " vibe show reply show_evt_1a2b3c4d --message '<你的回答>'"
+ )
+ assert (guidance in captured[0]["text"]) is expects_guidance
diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.py
index c27890552..3e85eba56 100644
--- a/tests/test_ui_show_pages.py
+++ b/tests/test_ui_show_pages.py
@@ -2025,6 +2025,71 @@ def test_private_show_page_records_remote_oauth_author(monkeypatch, tmp_path):
assert event["message"]["metadata"]["author"] == expected_author
+def test_private_show_page_accepts_mark_read_receipt_and_records_reader(monkeypatch, tmp_path):
+ from core.show_session_events import ShowSessionEventStore
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ _create_agent_session("ses123")
+ _create_show_page("ses123", "private")
+ store = ShowSessionEventStore()
+ try:
+ created = store.append(
+ "ses123",
+ {
+ "type": "assistant.mark.created",
+ "mark": {"id": "mark_read", "target": "#summary", "body": "Read this."},
+ },
+ )
+ finally:
+ store.close()
+
+ token = "session-write-token"
+ monkeypatch.setattr("vibe.ui_server.show_event_write_token", lambda session_id: token)
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_access.make_session_cookie(config, "[email protected]", "user-1"),
+ domain="alex.avibe.bot",
+ )
+ response = client.post(
+ "/show/ses123/__show/events",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ headers={
+ "Origin": "https://alex.avibe.bot",
+ "Content-Type": "application/json",
+ "X-Vibe-Show-Token": token,
+ },
+ json={
+ "type": "assistant.mark.resolved",
+ "mark": {
+ "id": "mark_read",
+ "updatedAt": created["payload"]["updatedAt"],
+ "target": "#forged",
+ "body": "Forged body.",
+ "author": {"kind": "user", "email": "[email protected]"},
+ },
+ },
+ )
+
+ assert response.status_code == 201
+ event = response.get_json()["event"]
+ assert event["actor"] == "assistant"
+ assert event["payload"]["role"] == "assistant"
+ assert event["payload"]["target"] == "#summary"
+ assert event["payload"]["body"] == "Read this."
+ assert event["payload"]["author"] == {"kind": "user", "email": "[email protected]"}
+ assert event["transcript_text"] == ""
+ assert event["message_id"] is None
+ assert event["message"] is None
+ store = ShowSessionEventStore()
+ try:
+ assert store.active_marks("ses123") == []
+ finally:
+ store.close()
+
+
def test_private_show_page_sets_show_event_write_cookie(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config(tmp_path)
@@ -2618,6 +2683,100 @@ def test_public_show_page_events_accept_oauth_user_and_record_author(monkeypatch
assert "[email protected]" not in json.dumps(listed)
+def test_public_show_page_accepts_mark_read_receipt_and_records_reader(monkeypatch, tmp_path):
+ from core.show_session_events import ShowSessionEventStore
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ _create_agent_session("ses123")
+ share_id = _create_show_page("ses123", "public")
+ store = ShowSessionEventStore()
+ try:
+ created = store.append(
+ "ses123",
+ {
+ "type": "assistant.mark.created",
+ "mark": {"id": "mark_public_read", "target": "#summary", "body": "Read this."},
+ },
+ )
+ finally:
+ store.close()
+
+ published = []
+ monkeypatch.setattr("vibe.ui_server._publish_show_session_event", published.append)
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_access.make_session_cookie(config, "[email protected]", "user-2"),
+ domain="alex.avibe.bot",
+ )
+ response = client.post(
+ f"/p/{share_id}/__show/events",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ headers=_public_show_write_headers(share_id),
+ json={
+ "type": "assistant.mark.resolved",
+ "mark": {
+ "id": "mark_public_read",
+ "updatedAt": created["payload"]["updatedAt"],
+ "target": "#forged",
+ "body": "Forged body.",
+ "author": {"kind": "local"},
+ },
+ },
+ )
+
+ assert response.status_code == 201
+ public_event = response.get_json()["event"]
+ assert public_event["actor"] == "assistant"
+ assert public_event["payload"]["target"] == "#summary"
+ assert public_event["payload"]["body"] == "Read this."
+ assert public_event["payload"]["author"] == {"kind": "user"}
+ assert published[0]["payload"]["author"] == {"kind": "user", "email": "[email protected]"}
+ assert published[0]["message"] is None
+ store = ShowSessionEventStore()
+ try:
+ assert store.active_marks("ses123") == []
+ finally:
+ store.close()
+
+
+def test_public_show_page_rejects_resolution_for_unknown_mark(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ _create_agent_session("ses123")
+ share_id = _create_show_page("ses123", "public")
+ published = []
+ monkeypatch.setattr("vibe.ui_server._publish_show_session_event", published.append)
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_access.make_session_cookie(config, "[email protected]", "user-2"),
+ domain="alex.avibe.bot",
+ )
+
+ response = client.post(
+ f"/p/{share_id}/__show/events",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ headers=_public_show_write_headers(share_id),
+ json={
+ "type": "assistant.mark.resolved",
+ "mark": {
+ "id": "mark_unknown",
+ "updatedAt": "2026-07-23T00:00:00Z",
+ "target": "#forged",
+ "body": "Forged body.",
+ },
+ },
+ )
+
+ assert response.status_code == 400
+ assert response.get_json()["code"] == "mark_not_active"
+ assert published == []
+
+
def test_public_show_page_events_accept_injected_share_session_id(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _save_config(tmp_path)
diff --git a/vibe/cli.py b/vibe/cli.py
index f2c2a4f08..fcbc76b0d 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -872,6 +872,9 @@ def _show_examples_text() -> str:
status Inspect local path, visibility, active URL, and share state.
update Switch visibility, set a custom public link, rotate share links, or take the page offline.
mark Add an assistant mark event to the session.
+ reply Reply to a dispatched page annotation at its original anchor.
+ marks List active assistant marks.
+ unmark Resolve active assistant marks by id or target.
event Record a generic annotation-layer event.
annotate Control the page's annotation overlay.
@@ -887,7 +890,10 @@ def _show_examples_text() -> str:
vibe show status --session-id sesk8m4q2p7x --json
vibe show update --session-id sesk8m4q2p7x --visibility public
vibe show update --session-id sesk8m4q2p7x --visibility offline
- vibe show mark --session-id sesk8m4q2p7x --target mark-default-summary --body "Review this summary."
+ vibe show mark mark-default-summary --session-id sesk8m4q2p7x --message "Review this summary."
+ vibe show reply show_evt_1a2b3c4d --message "The source changed in W30."
+ vibe show marks --json
+ vibe show unmark mark_1 mark-default-summary
vibe show event --session-id sesk8m4q2p7x --event-json @./show-event.json --json
vibe show annotate --session-id sesk8m4q2p7x --on --mode screenshot
@@ -897,6 +903,9 @@ def _show_examples_text() -> str:
vibe show status --help
vibe show update --help
vibe show mark --help
+ vibe show reply --help
+ vibe show marks --help
+ vibe show unmark --help
vibe show event --help
vibe show annotate --help
"""
@@ -965,8 +974,9 @@ def _show_mark_examples_text() -> str:
a value produced by @avibe/show-sdk's mark helpers.
Examples:
- vibe show mark --session-id sesk8m4q2p7x --target mark-default-summary --body "Review this summary."
- vibe show mark --session-id sesk8m4q2p7x --scope default --target summary --body-file ./comment.txt --json
+ vibe show mark mark-default-summary --session-id sesk8m4q2p7x --message "Review this summary."
+ vibe show mark summary --session-id sesk8m4q2p7x --scope default --message-file ./comment.txt --json
+ vibe show mark --target summary --body "Legacy option aliases still work."
"""
)
@@ -10080,6 +10090,9 @@ def _print_show_page_error(exc: Exception) -> None:
hint = getattr(exc, "hint", None)
if hint:
payload["hint"] = hint
+ details = getattr(exc, "details", None)
+ if details:
+ payload["details"] = details
print(json.dumps(payload, indent=2), file=sys.stderr)
@@ -10281,7 +10294,13 @@ def cmd_show_update(args):
store.close()
-def _read_cli_text_argument(*, value: str | None, file_path: str | None, field_name: str) -> str:
+def _read_cli_text_argument(
+ *,
+ value: str | None,
+ file_path: str | None,
+ field_name: str,
+ help_command: str = "vibe show mark --help",
+) -> str:
if file_path:
source = sys.stdin.read() if file_path == "-" else Path(file_path).read_text(encoding="utf-8")
text = source.strip()
@@ -10291,7 +10310,7 @@ def _read_cli_text_argument(*, value: str | None, file_path: str | None, field_n
raise TaskCliError(
f"{field_name} is required",
code="invalid_arguments",
- help_command="vibe show mark --help",
+ help_command=help_command,
)
return text
@@ -10493,11 +10512,21 @@ def _read_event_json_argument(value: str | None, file_path: str | None) -> dict:
help_command="vibe show event --help",
)
if file_path is not None:
- raw = _read_cli_text_argument(value=None, file_path=file_path, field_name="--event-json-file")
+ raw = _read_cli_text_argument(
+ value=None,
+ file_path=file_path,
+ field_name="--event-json-file",
+ help_command="vibe show event --help",
+ )
else:
raw = value or ""
if raw.startswith("@"):
- raw = _read_cli_text_argument(value=None, file_path=raw[1:], field_name="--event-json")
+ raw = _read_cli_text_argument(
+ value=None,
+ file_path=raw[1:],
+ field_name="--event-json",
+ help_command="vibe show event --help",
+ )
try:
payload = json.loads(raw)
except json.JSONDecodeError as exc:
@@ -10515,21 +10544,87 @@ def _read_event_json_argument(value: str | None, file_path: str | None) -> dict:
return payload
+def _show_mark_target(args) -> str:
+ positional = (getattr(args, "target", None) or "").strip()
+ option = (getattr(args, "target_option", None) or "").strip()
+ if positional and option and positional != option:
+ raise TaskCliError(
+ "positional target and --target must match when both are provided",
+ code="conflicting_mark_targets",
+ help_command="vibe show mark --help",
+ )
+ return _read_cli_text_argument(
+ value=positional or option,
+ file_path=None,
+ field_name="target",
+ help_command="vibe show mark --help",
+ )
+
+
+def _record_show_mark_event(session_id: str, payload: dict, event_store) -> dict:
+ event = _post_show_mark_to_live_ui(session_id, payload)
+ return event if event is not None else event_store.append(session_id, payload)
+
+
+def _reply_target_from_annotation(annotation: dict) -> str:
+ anchor = annotation.get("anchor") if isinstance(annotation.get("anchor"), dict) else {}
+ payload = annotation.get("payload") if isinstance(annotation.get("payload"), dict) else {}
+ scope = str(payload.get("scope") or "default").strip() or "default"
+ for key in ("target", "selector"):
+ value = str(anchor.get(key) or "").strip()
+ if value:
+ return value
+ mark = str(anchor.get("mark") or "").strip()
+ if mark:
+ return f"mark-{scope}-{mark}"
+ anchor_id = str(anchor.get("id") or "").strip()
+ if anchor_id and anchor.get("kind") == "mark":
+ return f"mark-{scope}-{anchor_id}"
+ return f"annotation:{annotation['id']}"
+
+
+def _show_mark_body_head(body: object, *, limit: int = 80) -> str:
+ text = " ".join(str(body or "").split())
+ return text if len(text) <= limit else f"{text[: limit - 3]}..."
+
+
+def _show_mark_listing(mark: dict) -> dict:
+ return {
+ "id": mark.get("id"),
+ "kind": mark.get("kind"),
+ "target": mark.get("target"),
+ "body_head": _show_mark_body_head(mark.get("body")),
+ "read_state": mark.get("read_state") or "unread",
+ }
+
+
def cmd_show_mark(args):
from core.show_pages import ShowPageStore
- from core.show_session_events import ShowSessionEventStore
+ from core.show_session_events import ShowSessionEventStore, stable_assistant_mark_id
page_store = ShowPageStore()
- event_store = None
+ event_store = ShowSessionEventStore()
try:
session_id, session_default_notice = _resolve_show_session_id(args, help_command="vibe show mark --help")
page = page_store.ensure(session_id)
- target = _read_cli_text_argument(value=args.target, file_path=None, field_name="--target")
- body = _read_cli_text_argument(value=args.body, file_path=args.body_file, field_name="--body")
+ target = _show_mark_target(args)
+ body = _read_cli_text_argument(
+ value=args.body,
+ file_path=args.body_file,
+ field_name="--message",
+ help_command="vibe show mark --help",
+ )
+ scope = args.scope or "default"
+ mark_id = stable_assistant_mark_id(scope=scope, target=target)
+ replaced = any(
+ mark.get("kind") == "note" and mark.get("scope") == scope and mark.get("target") == target
+ for mark in event_store.active_marks(session_id)
+ )
payload = {
"type": "assistant.mark.created",
"mark": {
- "scope": args.scope or "default",
+ "id": mark_id,
+ "scope": scope,
"target": target,
"body": body,
},
@@ -10538,18 +10633,17 @@ def cmd_show_mark(args):
payload["anchor"] = {"selector": args.anchor_selector}
if args.anchor_text:
payload["anchor"]["text"] = args.anchor_text
- event = _post_show_mark_to_live_ui(session_id, payload)
- if event is None:
- event_store = ShowSessionEventStore()
- event = event_store.append(session_id, payload)
+ event = _record_show_mark_event(session_id, payload, event_store)
result = _show_page_result(
page,
- message="Assistant mark recorded.",
+ message="Assistant mark replaced." if replaced else "Assistant mark recorded.",
extra={
**({"session_default_notice": session_default_notice} if session_default_notice else {}),
"event": event,
"event_id": event["id"],
+ "mark_id": mark_id,
"message_id": event.get("message_id"),
+ "replaced": replaced,
},
)
if getattr(args, "json", False):
@@ -10567,8 +10661,198 @@ def cmd_show_mark(args):
return 1
finally:
page_store.close()
- if event_store is not None:
- event_store.close()
+ event_store.close()
+
+
+def cmd_show_reply(args):
+ from core.show_pages import ShowPageStore
+ from core.show_session_events import ShowSessionEventStore, stable_assistant_mark_id
+
+ page_store = ShowPageStore()
+ event_store = ShowSessionEventStore()
+ try:
+ session_id, session_default_notice = _resolve_show_session_id(args, help_command="vibe show reply --help")
+ annotation = event_store.get_annotation_event(session_id, args.show_event_id)
+ if annotation is None:
+ recent_ids = event_store.recent_annotation_event_ids(session_id)
+ recent_text = ", ".join(recent_ids) if recent_ids else "none"
+ raise TaskCliError(
+ f"Annotation event {args.show_event_id!r} was not found in this session. "
+ f"Recent annotation event ids: {recent_text}.",
+ code="show_annotation_not_found",
+ hint="Use an event id dispatched for this Agent Session.",
+ help_command="vibe show reply --help",
+ details={"recent_annotation_event_ids": recent_ids},
+ )
+
+ page = page_store.ensure(session_id)
+ body = _read_cli_text_argument(
+ value=args.message,
+ file_path=args.message_file,
+ field_name="--message",
+ help_command="vibe show reply --help",
+ )
+ annotation_payload = annotation.get("payload") or {}
+ scope = str(annotation_payload.get("scope") or "default").strip() or "default"
+ target = _reply_target_from_annotation(annotation)
+ mark_id = stable_assistant_mark_id(scope=scope, reply_to=annotation["id"])
+ replaced = any(mark.get("replyTo") == annotation["id"] for mark in event_store.active_marks(session_id))
+ payload = {
+ "type": "assistant.mark.created",
+ "mark": {
+ "id": mark_id,
+ "scope": scope,
+ "target": target,
+ "body": body,
+ "replyTo": annotation["id"],
+ },
+ "anchor": dict(annotation.get("anchor") or {}),
+ }
+ event = _record_show_mark_event(session_id, payload, event_store)
+ replacement_notice = None
+ if replaced:
+ replacement_notice = "This annotation already had a reply; the active reply was replaced. Run: vibe show marks"
+ result = _show_page_result(
+ page,
+ message="Show Page reply replaced." if replaced else "Show Page reply recorded.",
+ extra={
+ **({"session_default_notice": session_default_notice} if session_default_notice else {}),
+ "event": event,
+ "event_id": event["id"],
+ "mark_id": mark_id,
+ "reply_to": annotation["id"],
+ "replaced": replaced,
+ **({"replacement_notice": replacement_notice} if replacement_notice else {}),
+ },
+ )
+ if getattr(args, "json", False):
+ _print_json(result)
+ else:
+ _print_show_page_result(result)
+ print("")
+ print("Reply:")
+ print(f" Event: {event['id']}")
+ print(f" Mark: {mark_id}")
+ print(f" Reply to: {annotation['id']}")
+ print(f" Target: {target}")
+ if replacement_notice:
+ print(f" Note: {replacement_notice}")
+ return 0
+ except Exception as exc:
+ _print_show_page_error(exc)
+ return 1
+ finally:
+ page_store.close()
+ event_store.close()
+
+
+def cmd_show_marks(args):
+ from core.show_session_events import ShowSessionEventStore
+
+ event_store = ShowSessionEventStore()
+ try:
+ session_id, session_default_notice = _resolve_show_session_id(args, help_command="vibe show marks --help")
+ marks = [_show_mark_listing(mark) for mark in event_store.active_marks(session_id)]
+ result = {
+ "ok": True,
+ "session_id": session_id,
+ "count": len(marks),
+ "marks": marks,
+ **({"session_default_notice": session_default_notice} if session_default_notice else {}),
+ }
+ if getattr(args, "json", False):
+ _print_json(result)
+ else:
+ print(f"Assistant marks ({len(marks)} active):")
+ if not marks:
+ print(" none")
+ for mark in marks:
+ print(f"- {mark['id']} {mark['kind']} {mark['read_state']}")
+ print(f" Target: {mark['target']}")
+ print(f" Body: {mark['body_head']}")
+ return 0
+ except Exception as exc:
+ _print_show_page_error(exc)
+ return 1
+ finally:
+ event_store.close()
+
+
+def cmd_show_unmark(args):
+ from core.show_session_events import ShowSessionEventStore
+
+ event_store = ShowSessionEventStore()
+ try:
+ session_id, session_default_notice = _resolve_show_session_id(args, help_command="vibe show unmark --help")
+ active_marks = event_store.active_marks(session_id)
+ results = []
+ succeeded = 0
+ for identifier in args.identifiers:
+ matches = [
+ mark for mark in active_marks if mark.get("id") == identifier or mark.get("target") == identifier
+ ]
+ if not matches:
+ results.append({"input": identifier, "ok": False, "error": "active mark not found"})
+ continue
+
+ resolved_ids = []
+ event_ids = []
+ errors = []
+ for mark in matches:
+ mark_payload = {
+ key: mark[key]
+ for key in ("id", "scope", "target", "body", "createdAt", "updatedAt", "replyTo")
+ if mark.get(key) is not None
+ }
+ try:
+ event = _record_show_mark_event(
+ session_id,
+ {"type": "assistant.mark.resolved", "mark": mark_payload, "anchor": mark.get("anchor") or {}},
+ event_store,
+ )
+ except Exception as exc:
+ errors.append(str(exc))
+ continue
+ resolved_ids.append(mark["id"])
+ event_ids.append(event["id"])
+ active_marks = [candidate for candidate in active_marks if candidate.get("id") != mark["id"]]
+
+ item_ok = bool(resolved_ids)
+ if item_ok:
+ succeeded += 1
+ results.append(
+ {
+ "input": identifier,
+ "ok": item_ok,
+ "mark_ids": resolved_ids,
+ "event_ids": event_ids,
+ **({"errors": errors} if errors else {}),
+ }
+ )
+
+ result = {
+ "ok": succeeded > 0,
+ "session_id": session_id,
+ "succeeded": succeeded,
+ "failed": len(results) - succeeded,
+ "results": results,
+ **({"session_default_notice": session_default_notice} if session_default_notice else {}),
+ }
+ if getattr(args, "json", False):
+ _print_json(result)
+ else:
+ for item in results:
+ if item["ok"]:
+ print(f"Resolved {item['input']}: {', '.join(item['mark_ids'])}")
+ else:
+ detail = "; ".join(item.get("errors") or []) or item.get("error") or "failed"
+ print(f"Failed {item['input']}: {detail}", file=sys.stderr)
+ return 0 if succeeded > 0 else 1
+ except Exception as exc:
+ _print_show_page_error(exc)
+ return 1
+ finally:
+ event_store.close()
def cmd_show_event(args):
@@ -10704,6 +10988,12 @@ def cmd_show(args):
return cmd_show_update(args)
if args.show_command == "mark":
return cmd_show_mark(args)
+ if args.show_command == "reply":
+ return cmd_show_reply(args)
+ if args.show_command == "marks":
+ return cmd_show_marks(args)
+ if args.show_command == "unmark":
+ return cmd_show_unmark(args)
if args.show_command == "event":
return cmd_show_event(args)
if args.show_command == "annotate":
@@ -11942,7 +12232,7 @@ def build_parser():
show_parser.set_defaults(show_help_parser=show_parser)
show_subparsers = show_parser.add_subparsers(
dest="show_command",
- metavar="{list,path,status,update,mark,event,annotate}",
+ metavar="{list,path,status,update,mark,reply,marks,unmark,event,annotate}",
)
show_subparsers.required = False
@@ -12053,18 +12343,60 @@ def build_parser():
epilog=_show_mark_examples_text(),
formatter_class=argparse.RawDescriptionHelpFormatter,
error_help_command="vibe show mark --help",
- error_hint="Pass --target and --body or --body-file. Pass --session-id outside an Avibe Agent shell.",
+ error_hint="Pass target and --message or --message-file. Pass --session-id outside an Avibe Agent shell.",
)
show_mark_parser.add_argument("--session-id", help="Agent Session ID for the Show Page.")
show_mark_parser.add_argument("--scope", default="default", help='Mark scope. Defaults to "default".')
- show_mark_parser.add_argument("--target", required=True, help="Target mark id or selector.")
+ show_mark_parser.add_argument("target", nargs="?", help="Target mark id or selector.")
+ show_mark_parser.add_argument("--target", dest="target_option", help="Alias for the positional target.")
mark_body_group = show_mark_parser.add_mutually_exclusive_group(required=True)
- mark_body_group.add_argument("--body", help="Assistant mark body text.")
- mark_body_group.add_argument("--body-file", help="Read assistant mark body from a UTF-8 file, or '-' for stdin.")
+ mark_body_group.add_argument("--message", "--body", dest="body", help="Assistant mark body text.")
+ mark_body_group.add_argument(
+ "--message-file",
+ "--body-file",
+ dest="body_file",
+ help="Read assistant mark body from a UTF-8 file, or '-' for stdin.",
+ )
show_mark_parser.add_argument("--anchor-selector", help="Optional DOM selector for the anchored element.")
show_mark_parser.add_argument("--anchor-text", help="Optional selected or summarized anchor text.")
show_mark_parser.add_argument("--json", action="store_true", help="Print machine-readable state.")
+ show_reply_parser = show_subparsers.add_parser(
+ "reply",
+ help="Reply to a human Show Page annotation",
+ description="Create or replace the assistant reply mark paired with one annotation event in this session.",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ error_help_command="vibe show reply --help",
+ error_hint="Pass the dispatched annotation event id and --message or --message-file.",
+ )
+ show_reply_parser.add_argument("show_event_id", help="Human annotation event id from the dispatched message.")
+ show_reply_parser.add_argument("--session-id", help="Agent Session ID for the Show Page.")
+ reply_message_group = show_reply_parser.add_mutually_exclusive_group(required=True)
+ reply_message_group.add_argument("--message", help="Reply body text.")
+ reply_message_group.add_argument("--message-file", help="Read reply text from a UTF-8 file, or '-' for stdin.")
+ show_reply_parser.add_argument("--json", action="store_true", help="Print machine-readable state.")
+
+ show_marks_parser = show_subparsers.add_parser(
+ "marks",
+ help="List active assistant marks",
+ description="List non-resolved assistant reply and note marks for this Agent Session.",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ error_help_command="vibe show marks --help",
+ )
+ show_marks_parser.add_argument("--session-id", help="Agent Session ID for the Show Page.")
+ show_marks_parser.add_argument("--json", action="store_true", help="Print machine-readable state.")
+
+ show_unmark_parser = show_subparsers.add_parser(
+ "unmark",
+ help="Resolve assistant marks",
+ description="Resolve one or more active assistant marks by mark id or exact target.",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ error_help_command="vibe show unmark --help",
+ )
+ show_unmark_parser.add_argument("identifiers", nargs="+", metavar="ID_OR_TARGET")
+ show_unmark_parser.add_argument("--session-id", help="Agent Session ID for the Show Page.")
+ show_unmark_parser.add_argument("--json", action="store_true", help="Print machine-readable state.")
+
show_event_parser = show_subparsers.add_parser(
"event",
help="Record a generic Show Page event",
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index a0fcde780..7e0ef60ec 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -8591,7 +8591,7 @@ async def _run_show_event_dispatch(event_payload: dict[str, Any]) -> None:
return
dispatch_payload = {
"session_id": session_id,
- "text": transcript_text,
+ "text": _show_event_dispatch_text(event_payload),
"scope_id": scope_id,
"user_message_id": event_payload.get("message_id"),
"message_id": event_payload.get("message_id"),
@@ -8612,6 +8612,27 @@ async def _run_show_event_dispatch(event_payload: dict[str, Any]) -> None:
_publish_show_dispatch_event(event_payload, "stream.error", {"reason": "dispatch_failed", "detail": str(exc)})
+def _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
+
+ event_id = str(event_payload.get("id") or "").strip()
+ if not event_id:
+ return transcript_text
+ lines = [transcript_text, "", f"Show event id: {event_id}"]
+ payload = event_payload.get("payload")
+ if isinstance(payload, dict) and payload.get("intent") == "question":
+ lines.extend(
+ [
+ "",
+ "用户在页面上提出了疑问。请优先把回答放回页面上用户指的位置(chat 里保留一句简短结论即可):",
+ f" vibe show reply {event_id} --message '<你的回答>'",
+ ]
+ )
+ return "\n".join(lines)
+
+
def _publish_show_dispatch_event(event_payload: dict[str, Any], event_name: str, data: Any) -> None:
from vibe.sse_broker import broker
@@ -9587,13 +9608,14 @@ async def serve_public_show_page(share_id, asset_path):
if not _public_show_event_write_authorized(share_id, page.session_id):
return jsonify({"ok": False, "code": "show_event_write_forbidden"}), 403
payload = _sanitize_public_show_event_payload(_show_events_payload_from_request())
- if str(payload.get("type") or "").strip() not in HUMAN_EVENT_TYPES:
+ event_type = str(payload.get("type") or "").strip()
+ if event_type not in HUMAN_EVENT_TYPES and event_type != "assistant.mark.resolved":
return (
jsonify(
{
"ok": False,
"code": "unsupported_event_type",
- "error": "Public Show Page writes require a supported human event type.",
+ "error": "Public Show Page writes require a supported human event or mark resolution type.",
}
),
400,