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(ui): anchor vault key requests to chat replies (#1222)

Call White164069a72501
diff --git a/core/message_mirror.py b/core/message_mirror.py
index 60fc173ab..dcf53fc15 100644
--- a/core/message_mirror.py
+++ b/core/message_mirror.py
@@ -609,6 +609,16 @@ def mirror_harness_inbound(context: MessageContext, text: str) -> None:
definition_id = spec.get("task_definition_id")
session_id = spec.get("agent_session_id")
suppress_delivery = bool(spec.get("suppress_delivery"))
+ provenance_metadata = {
+ key: value
+ for key in (
+ "source_kind",
+ "source_actor",
+ "vault_request_type",
+ "vault_request_status",
+ )
+ if (value := spec.get(key)) not in (None, "")
+ }
try:
engine = get_cached_sqlite_engine()
appended_row = None
@@ -653,6 +663,7 @@ def mirror_harness_inbound(context: MessageContext, text: str) -> None:
author_id=definition_id,
message_type=messages_service.HARNESS_TYPE,
text=text,
+ metadata=provenance_metadata,
native_message_id=context.message_id,
parent_native_message_id=context.thread_id,
)
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index d7007c312..53c71a6b9 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -921,6 +921,7 @@ def enqueue_session_callback(
message: str,
source_actor: str,
parent_run_id: Optional[str] = None,
+ metadata: Optional[dict[str, Any]] = None,
) -> Optional["TaskExecutionRequest"]:
"""Enqueue a callback turn into an existing agent session — the shared entry used by Agent
Run / watch / scheduled-task callbacks and vault-request auto-resume. Resolves the session's
@@ -948,7 +949,10 @@ def enqueue_session_callback(
source_actor=source_actor,
parent_run_id=parent_run_id,
delivery_intent=delivery_intent_for_trigger("callback"),
- metadata={"callback_parent_run_id": parent_run_id} if parent_run_id else {},
+ metadata={
+ **(metadata or {}),
+ **({"callback_parent_run_id": parent_run_id} if parent_run_id else {}),
+ },
callback_parent_to_arm=parent_run_id,
)
@@ -7079,6 +7083,10 @@ class ScheduledTaskService:
session_id=plan.session_id,
message=plan.message,
source_actor=f"vault:{request_id}",
+ metadata={
+ "vault_request_type": str(row.get("request_type") or ""),
+ "vault_request_status": str(row.get("status") or ""),
+ },
)
status = "sent"
except ValueError:
@@ -7174,6 +7182,10 @@ class ScheduledTaskService:
session_id=plan.session_id,
message=plan.message,
source_actor=f"vault:{request_id}",
+ metadata={
+ "vault_request_type": str(row.get("request_type") or ""),
+ "vault_request_status": str(row.get("status") or ""),
+ },
)
status = "sent"
except ValueError:
@@ -10145,6 +10157,8 @@ class ScheduledTaskService:
"vibe_agent_id": agent_id,
"source_kind": (metadata or {}).get("source_kind"),
"source_actor": (metadata or {}).get("source_actor"),
+ "vault_request_type": (metadata or {}).get("vault_request_type"),
+ "vault_request_status": (metadata or {}).get("vault_request_status"),
"parent_run_id": (metadata or {}).get("parent_run_id"),
"callback_session_id": (metadata or {}).get("callback_session_id"),
"suppress_delivery": bool(target_info.suppress_delivery) if target_info else False,
diff --git a/storage/messages_service.py b/storage/messages_service.py
index a3e9ce18a..157664d8a 100644
--- a/storage/messages_service.py
+++ b/storage/messages_service.py
@@ -30,6 +30,7 @@ from storage.models import (
scope_settings,
scopes,
session_turns,
+ vault_requests,
)
from storage.pagination import PageRequest, PageResult, page_result_from_limit_plus_one
from storage.sessions_service import session_agent_display_label
@@ -148,9 +149,10 @@ def _attach_harness_provenance(
records none). Resolve it read-side: message → its ``agent_runs`` row
(``id == <execution_id>``) → the run's ``source_actor`` (the session that
triggered the callback) → that session's title, so the Chat chip can name the
- source and deep-link to ``/chat/<source_session_id>``. No schema/write-path
- change. Batched: at most two extra queries per page, only when such a message
- is present.
+ source and deep-link to ``/chat/<source_session_id>``. Vault callbacks additionally
+ resolve their ``vault:<request_id>`` actor into stable request type/status metadata
+ so the transcript can label the callback as coming from Vault. Batched: at most
+ two extra queries per page, only when such a message is present.
"""
exec_by_msg: dict[str, str] = {}
for payload in payloads:
@@ -209,43 +211,69 @@ def _attach_harness_provenance(
# so an unexpected source_actor shape can't become a bogus /chat target.
if source_id and ":" not in source_id:
source_by_exec[exec_id] = source_id
- if not source_by_exec:
+ vault_by_exec: dict[str, tuple[str, dict[str, Any] | None]] = {}
+ vault_request_ids: set[str] = set()
+ for exec_id, run in runs.items():
+ actor = str(run["source_actor"] or "").strip()
+ if run["source_kind"] == "callback" and actor.startswith("vault:"):
+ request_id = actor[len("vault:"):].strip()
+ if request_id:
+ vault_by_exec[exec_id] = (request_id, None)
+ vault_request_ids.add(request_id)
+ if vault_request_ids:
+ request_rows = {
+ str(row["id"]): dict(row)
+ for row in conn.execute(
+ select(
+ vault_requests.c.id,
+ vault_requests.c.request_type,
+ vault_requests.c.status,
+ ).where(vault_requests.c.id.in_(vault_request_ids))
+ ).mappings()
+ }
+ vault_by_exec = {
+ exec_id: (request_id, request_rows.get(request_id))
+ for exec_id, (request_id, _row) in vault_by_exec.items()
+ }
+ if not source_by_exec and not vault_by_exec:
return payloads
meta_by_session: dict[str, dict[str, Optional[str]]] = {}
- for row in conn.execute(
- select(
- agent_sessions.c.id,
- agent_sessions.c.title,
- agent_sessions.c.agent_name,
- agent_sessions.c.agent_backend,
- agents.c.name.label("catalog_agent_name"),
- agents.c.archived_at.label("catalog_agent_archived_at"),
- agents.c.metadata_json.label("catalog_agent_metadata_json"),
- )
- .select_from(
- agent_sessions.outerjoin(
- agents,
- or_(
- agents.c.id == agent_sessions.c.agent_id,
- and_(
- agent_sessions.c.agent_id.is_(None),
- agents.c.name == agent_sessions.c.agent_name,
+ if source_by_exec:
+ for row in conn.execute(
+ select(
+ agent_sessions.c.id,
+ agent_sessions.c.title,
+ agent_sessions.c.agent_name,
+ agent_sessions.c.agent_backend,
+ agents.c.name.label("catalog_agent_name"),
+ agents.c.archived_at.label("catalog_agent_archived_at"),
+ agents.c.metadata_json.label("catalog_agent_metadata_json"),
+ )
+ .select_from(
+ agent_sessions.outerjoin(
+ agents,
+ or_(
+ agents.c.id == agent_sessions.c.agent_id,
+ and_(
+ agent_sessions.c.agent_id.is_(None),
+ agents.c.name == agent_sessions.c.agent_name,
+ ),
),
- ),
+ )
)
- )
- .where(
- agent_sessions.c.id.in_(set(source_by_exec.values()))
- )
- ).mappings():
- meta_by_session[row["id"]] = {
- "title": row["title"],
- "agent_name": session_agent_display_label(row),
- }
+ .where(
+ agent_sessions.c.id.in_(set(source_by_exec.values()))
+ )
+ ).mappings():
+ meta_by_session[row["id"]] = {
+ "title": row["title"],
+ "agent_name": session_agent_display_label(row),
+ }
for payload in payloads:
- source_id = source_by_exec.get(exec_by_msg.get(payload["id"], ""))
+ exec_id = exec_by_msg.get(payload["id"], "")
+ source_id = source_by_exec.get(exec_id)
# Only attach when the source session still exists (is in meta_by_session);
# a stale/imported/deleted source would otherwise write source_session_id
# and produce a dead /chat/<missing id> link with only the fallback label.
@@ -254,6 +282,16 @@ def _attach_harness_provenance(
payload["source_session_id"] = source_id
payload["source_session_title"] = meta.get("title")
payload["source_session_agent_name"] = meta.get("agent_name")
+ vault_info = vault_by_exec.get(exec_id)
+ if vault_info is not None:
+ request_id, request = vault_info
+ metadata = dict(payload.get("metadata") or {})
+ metadata.setdefault("source_kind", "callback")
+ metadata.setdefault("source_actor", f"vault:{request_id}")
+ if request is not None:
+ metadata.setdefault("vault_request_type", request.get("request_type"))
+ metadata.setdefault("vault_request_status", request.get("status"))
+ payload["metadata"] = metadata
return payloads
@@ -709,6 +747,10 @@ def list_session_messages(
after_id: Optional[str] = None,
before_id: Optional[str] = None,
around_id: Optional[str] = None,
+ around_native_id: Optional[str] = None,
+ around_native_platform: Optional[str] = None,
+ around_turn_id: Optional[str] = None,
+ around_run_id: Optional[str] = None,
limit: int = 50,
types: Optional[Iterable[str]] = None,
tail: bool = False,
@@ -722,13 +764,18 @@ def list_session_messages(
``before_id`` returns the page immediately older than that row, still in
chronological order. This powers upward history loading from the chat page.
- ``around_id`` centers a window on a specific message (deep-link / search
- jump): up to ``limit`` rows strictly older + the anchor + up to ``limit`` rows
- strictly newer, merged chronologically. It takes precedence over
- ``after_id`` / ``before_id`` / ``tail``. ``next_before_id`` is set when older
- rows remain, ``next_after_id`` when newer rows remain, so the chat can page in
- both directions from the centered window. An unknown ``around_id`` returns no
- messages and null cursors.
+ ``around_id`` centers a window on a durable message id (deep-link / search
+ jump). ``around_native_id`` provides the equivalent lookup for a platform
+ native message id when a legacy caller context has not retained the durable
+ row id; ``around_native_platform`` disambiguates native ids reused by another
+ platform in the same session. ``around_turn_id`` and ``around_run_id`` resolve the initial accepted
+ delivery for a stable Agent turn/run before applying the same window logic.
+ Up to ``limit`` rows are returned on either side of the anchor,
+ merged chronologically. These modes take precedence over ``after_id`` /
+ ``before_id`` / ``tail``. ``next_before_id`` is set when older rows remain,
+ ``next_after_id`` when newer rows remain, so the chat can page in both
+ directions from the centered window. An unknown anchor returns no messages
+ and null cursors.
``tail`` returns the most-recent ``limit`` rows (still chronological) instead
of the oldest page — used by the Chat page's reconnect/visibility gap
@@ -741,18 +788,78 @@ def list_session_messages(
if types is not None:
query = query.where(messages.c.type.in_(list(types)))
effective_limit = min(max(int(limit), 1), 500)
- if around_id:
+ if around_id or around_native_id or around_turn_id or around_run_id:
# Window centered on a specific message (deep-link / search jump). Resolve
# the anchor's (created_at, id); an unknown id (or one in another session)
# yields an empty window. ``query`` already carries the type/metadata
# filter, so the older/anchor/newer sub-queries inherit it — the anchor
# only appears if it is itself transcript-visible.
order_value = transcript_order_value()
+ anchor_id = around_id
anchor = conn.execute(
select(order_value).where(
- messages.c.id == around_id, messages.c.session_id == session_id
+ messages.c.id == anchor_id, messages.c.session_id == session_id
)
).scalar_one_or_none()
+ if anchor is None and around_native_id:
+ native_query = select(messages.c.id).where(
+ messages.c.native_message_id == around_native_id,
+ messages.c.session_id == session_id,
+ )
+ if around_native_platform:
+ native_query = native_query.where(messages.c.platform == around_native_platform)
+ anchor_id = conn.execute(native_query.order_by(messages.c.id.asc()).limit(1)).scalar_one_or_none()
+ if anchor_id is not None:
+ anchor = conn.execute(
+ select(order_value).where(
+ messages.c.id == anchor_id, messages.c.session_id == session_id
+ )
+ ).scalar_one_or_none()
+ if anchor is None and around_turn_id:
+ anchor_id = conn.execute(
+ select(message_deliveries.c.message_id)
+ .where(
+ message_deliveries.c.turn_id == around_turn_id,
+ message_deliveries.c.session_id == session_id,
+ message_deliveries.c.message_id.is_not(None),
+ )
+ .order_by(message_deliveries.c.turn_position.asc(), message_deliveries.c.id.asc())
+ .limit(1)
+ ).scalar_one_or_none()
+ if anchor_id is not None:
+ anchor = conn.execute(
+ select(order_value).where(
+ messages.c.id == anchor_id, messages.c.session_id == session_id
+ )
+ ).scalar_one_or_none()
+ if anchor is None and around_run_id:
+ anchor_id = conn.execute(
+ select(message_deliveries.c.message_id)
+ .select_from(message_deliveries.join(agent_runs, agent_runs.c.delivery_id == message_deliveries.c.id))
+ .where(
+ agent_runs.c.id == around_run_id,
+ message_deliveries.c.session_id == session_id,
+ message_deliveries.c.message_id.is_not(None),
+ )
+ .order_by(message_deliveries.c.turn_position.asc(), message_deliveries.c.id.asc())
+ .limit(1)
+ ).scalar_one_or_none()
+ if anchor_id is None:
+ anchor_id = conn.execute(
+ select(messages.c.id)
+ .where(
+ messages.c.native_message_id == f"agent_run:{around_run_id}",
+ messages.c.session_id == session_id,
+ )
+ .order_by(messages.c.id.asc())
+ .limit(1)
+ ).scalar_one_or_none()
+ if anchor_id is not None:
+ anchor = conn.execute(
+ select(order_value).where(
+ messages.c.id == anchor_id, messages.c.session_id == session_id
+ )
+ ).scalar_one_or_none()
if anchor is None:
return {"messages": [], "next_after_id": None, "next_before_id": None}
@@ -760,7 +867,7 @@ def list_session_messages(
query.where(
or_(
order_value < anchor,
- and_(order_value == anchor, messages.c.id < around_id),
+ and_(order_value == anchor, messages.c.id < anchor_id),
)
)
.order_by(order_value.desc(), messages.c.id.desc())
@@ -773,14 +880,14 @@ def list_session_messages(
anchor_rows = [
_row_to_payload(dict(row))
- for row in conn.execute(query.where(messages.c.id == around_id)).mappings().all()
+ for row in conn.execute(query.where(messages.c.id == anchor_id)).mappings().all()
]
newer_q = (
query.where(
or_(
order_value > anchor,
- and_(order_value == anchor, messages.c.id > around_id),
+ and_(order_value == anchor, messages.c.id > anchor_id),
)
)
.order_by(order_value.asc(), messages.c.id.asc())
@@ -795,6 +902,7 @@ def list_session_messages(
"messages": merged,
"next_after_id": newer[-1]["id"] if has_newer and newer else None,
"next_before_id": older[0]["id"] if has_older and older else None,
+ "anchor_id": anchor_id,
}
if tail:
# Newest ``limit`` rows, then flip back to chronological for the caller.
diff --git a/storage/vault_service.py b/storage/vault_service.py
index 77dbce147..f618df76b 100644
--- a/storage/vault_service.py
+++ b/storage/vault_service.py
@@ -41,6 +41,8 @@ from storage.models import (
vault_operation_challenges,
vault_requests,
vault_secrets,
+ message_deliveries,
+ session_turns,
)
from storage.vault_addresses import derive_addresses
from storage.vault_crypto import Sealed
@@ -2649,6 +2651,42 @@ def record_deliveries(conn: Connection, names: list[str], *, requester: Any = No
audit(conn, "delivered", secret_name=name, requester=requester, delivery={"mode": mode})
+def _active_session_turn_anchor(
+ conn: Connection,
+ session_id: str | None,
+) -> tuple[str | None, str | None]:
+ """Return the current Turn's durable message and Turn identities.
+
+ Claude's SDK client keeps one session-level caller environment, so a command
+ spawned during a later turn cannot carry that turn's native message id. The
+ durable Turn/initial Delivery already owns the identity we need and is safe to
+ use while the turn is starting or active. A message id is returned only after
+ acceptance has materialized it; the Turn id remains usable before then.
+ """
+ identity = str(session_id or "").strip()
+ if not identity:
+ return None, None
+ row = conn.execute(
+ select(
+ session_turns.c.id.label("turn_id"),
+ message_deliveries.c.message_id,
+ )
+ .join(
+ message_deliveries,
+ message_deliveries.c.id == session_turns.c.initial_delivery_id,
+ )
+ .where(session_turns.c.session_id == identity)
+ .where(session_turns.c.state.in_(("starting", "active")))
+ .order_by(session_turns.c.updated_at.desc(), session_turns.c.id.desc())
+ .limit(1)
+ ).mappings().first()
+ if row is None:
+ return None, None
+ message_id = str(row.get("message_id") or "").strip() or None
+ turn_id = str(row.get("turn_id") or "").strip() or None
+ return message_id, turn_id
+
+
def create_provision_request(
conn: Connection,
name: str,
@@ -2677,7 +2715,13 @@ def create_provision_request(
raise SecretNameCaseConflictError(name, pending_name)
status = "fulfilled" if already else "pending"
normalized_spec = normalize_provision_spec(spec)
- session_id = requester.get("session_id") if isinstance(requester, dict) else None
+ requester_payload = dict(requester) if isinstance(requester, dict) else requester
+ session_id = requester_payload.get("session_id") if isinstance(requester_payload, dict) else None
+ resolved_message_id = message_id
+ if isinstance(requester_payload, dict) and not resolved_message_id:
+ _, derived_turn_id = _active_session_turn_anchor(conn, session_id)
+ if derived_turn_id and not str(requester_payload.get("turn_id") or "").strip():
+ requester_payload["turn_id"] = derived_turn_id
card = _secure_input_card(name, request_id=request_id, reason=reason, spec=normalized_spec, session_id=session_id)
delivery_payload: dict[str, Any] = {"card": card}
if reason:
@@ -2690,10 +2734,10 @@ def create_provision_request(
id=request_id,
request_type="provision",
secret_name=name,
- requester=json.dumps(requester) if requester is not None else None,
+ requester=json.dumps(requester_payload) if requester_payload is not None else None,
delivery=json.dumps(delivery_payload),
status=status,
- message_id=message_id,
+ message_id=resolved_message_id,
created_at=now,
decided_at=now if already else None,
)
@@ -2703,7 +2747,7 @@ def create_provision_request(
if pending_name is not None and pending_name != name:
raise SecretNameCaseConflictError(name, pending_name) from exc
raise VaultServiceError("failed to create provision request") from exc
- audit(conn, "provision_requested", secret_name=name, requester=requester, request_id=request_id)
+ audit(conn, "provision_requested", secret_name=name, requester=requester_payload, request_id=request_id)
return {
"id": request_id,
"secret_name": name,
diff --git a/tests/test_message_mirror.py b/tests/test_message_mirror.py
index 9b5914b12..218ee3249 100644
--- a/tests/test_message_mirror.py
+++ b/tests/test_message_mirror.py
@@ -931,6 +931,55 @@ def test_harness_inbound_avibe_session_scoped(isolated_state):
assert row["content_text"] == "the watched condition fired"
+def test_harness_inbound_mirrors_vault_callback_provenance(isolated_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_vault", now=now)
+ conn.execute(
+ agent_sessions.insert().values(
+ id="ses_vault_callback",
+ scope_id=scope_id,
+ agent_backend="claude",
+ agent_variant="default",
+ session_anchor="anchor_ses_vault_callback",
+ native_session_id="",
+ status="active",
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+
+ ctx = MessageContext(
+ user_id="scheduled",
+ channel_id="ses_vault_callback",
+ platform="avibe",
+ message_id="agent_run:exec_vault_callback",
+ platform_specific={
+ "agent_session_id": "ses_vault_callback",
+ "task_trigger_kind": "agent_run",
+ "source_kind": "callback",
+ "source_actor": "vault:vrq_1",
+ "vault_request_type": "access",
+ "vault_request_status": "denied",
+ },
+ )
+ mirror_harness_inbound(ctx, "The user declined your vault access request.")
+
+ with engine.connect() as conn:
+ row = conn.execute(
+ select(messages).where(messages.c.session_id == "ses_vault_callback")
+ ).mappings().one()
+ assert json.loads(row["metadata_json"]) == {
+ "source_kind": "callback",
+ "source_actor": "vault:vrq_1",
+ "vault_request_type": "access",
+ "vault_request_status": "denied",
+ }
+
+
def test_background_standalone_persists_full_turn_without_realtime_delivery(isolated_state):
from core import inbox_events
diff --git a/tests/test_message_search.py b/tests/test_message_search.py
index d28f1e810..c47ce8f8f 100644
--- a/tests/test_message_search.py
+++ b/tests/test_message_search.py
@@ -71,6 +71,7 @@ def _insert_msg(
source=None,
msg_id=None,
delivered_at=None,
+ native_message_id=None,
):
"""Direct insert so a test controls created_at / type / platform / text.
@@ -87,6 +88,7 @@ def _insert_msg(
author=author,
type=resolved_type,
source=source,
+ native_message_id=native_message_id,
content_text=text,
content_json="{}",
metadata_json="{}",
@@ -616,6 +618,38 @@ def test_around_unknown_id_returns_empty(isolated_state):
assert page == {"messages": [], "next_after_id": None, "next_before_id": None}
+def test_around_native_id_resolves_to_durable_anchor(isolated_state):
+ """Legacy platform caller ids center the same durable transcript window."""
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_session(conn, scope_id, "ses_native")
+ _insert_msg(conn, scope_id, "ses_native", "user", "before", "2026-06-02T10:01:00Z")
+ _insert_msg(
+ conn,
+ scope_id,
+ "ses_native",
+ "user",
+ "native anchor",
+ "2026-06-02T10:02:00Z",
+ native_message_id="slack-123",
+ )
+ _insert_msg(conn, scope_id, "ses_native", "agent", "after", "2026-06-02T10:03:00Z")
+
+ with engine.connect() as conn:
+ page = messages_service.list_session_messages(
+ conn,
+ session_id="ses_native",
+ around_native_id="slack-123",
+ limit=1,
+ types=("user", "result"),
+ )
+
+ assert [message["text"] for message in page["messages"]] == ["before", "native anchor", "after"]
+ assert page["next_before_id"] is None
+ assert page["next_after_id"] is None
+
+
def test_around_takes_precedence_over_before_and_tail(isolated_state):
"""``around_id`` wins over ``before_id`` / ``tail`` when several are passed."""
engine = create_sqlite_engine()
diff --git a/tests/test_messages_service.py b/tests/test_messages_service.py
index 1accfeb6f..42732f132 100644
--- a/tests/test_messages_service.py
+++ b/tests/test_messages_service.py
@@ -16,7 +16,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from storage import message_deliveries, messages_service
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
-from storage.models import agent_runs, agent_sessions, messages, scopes
+from storage.models import agent_runs, agent_sessions, messages, scopes, vault_requests
from storage.pagination import PageRequest
from storage.settings_service import upsert_scope
from vibe.message_identity import HARNESS_TYPE
@@ -241,13 +241,23 @@ def _seed_titled_agent_session(conn, scope_id, session_id, *, title, agent_name)
)
-def _insert_agent_run(conn, run_id, *, session_id, source_kind, source_actor=None, parent_run_id=None):
+def _insert_agent_run(
+ conn,
+ run_id,
+ *,
+ session_id,
+ source_kind,
+ source_actor=None,
+ parent_run_id=None,
+ delivery_id=None,
+):
now = messages_service._utc_now_iso()
conn.execute(
agent_runs.insert().values(
id=run_id, run_type="agent_run", status="succeeded", cancel_requested=0,
source_kind=source_kind, source_actor=source_actor, parent_run_id=parent_run_id,
- session_id=session_id, created_at=now, updated_at=now, metadata_json="{}",
+ session_id=session_id, delivery_id=delivery_id,
+ created_at=now, updated_at=now, metadata_json="{}",
)
)
@@ -330,6 +340,49 @@ def test_agent_run_provenance_skips_missing_source_session(isolated_state):
assert "source_session_id" not in by_id["msg_ghost"]
+def test_vault_callback_message_provenance_enrichment(isolated_state):
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_session(conn, scope_id, "ses_target")
+ _insert_agent_run(
+ conn,
+ "execVault",
+ session_id="ses_target",
+ source_kind="callback",
+ source_actor="vault:vrq_access",
+ )
+ conn.execute(
+ vault_requests.insert().values(
+ id="vrq_access",
+ request_type="access",
+ secret_name="PROD_KEY",
+ requester='{"session_id":"ses_target"}',
+ status="denied",
+ created_at="2026-05-30T10:00:00Z",
+ decided_at="2026-05-30T10:00:01Z",
+ )
+ )
+ _insert_harness_msg(
+ conn,
+ scope_id,
+ "ses_target",
+ author_name="agent_run",
+ native_message_id="agent_run:execVault",
+ msg_id="msg_vault",
+ created_at="2026-05-30T10:00:02Z",
+ )
+
+ with engine.connect() as conn:
+ result = messages_service.list_session_messages(conn, session_id="ses_target")
+
+ message = next(row for row in result["messages"] if row["id"] == "msg_vault")
+ assert message["metadata"]["source_kind"] == "callback"
+ assert message["metadata"]["source_actor"] == "vault:vrq_access"
+ assert message["metadata"]["vault_request_type"] == "access"
+ assert message["metadata"]["vault_request_status"] == "denied"
+
+
@pytest.mark.parametrize(
("native_message_id", "expected_kind", "expected_definition_id"),
[
@@ -2119,6 +2172,151 @@ def test_list_session_messages_tail_returns_recent_window(isolated_state):
assert recent["next_after_id"] is None
+def test_list_session_messages_resolves_turn_and_run_anchors(isolated_state):
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ session_id = "ses_anchor_identity"
+ _seed_session(conn, scope_id, session_id)
+ delivery = message_deliveries.insert_delivery(
+ conn,
+ delivery_id="msg_anchor_identity",
+ session_id=session_id,
+ priority="p1",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type="user",
+ text="anchor prompt",
+ ),
+ dispatch_text="anchor prompt",
+ now="2026-08-08T00:00:00Z",
+ )
+ claimed = message_deliveries.claim_start_batch(
+ conn,
+ turn_id="trn_anchor_identity",
+ session_id=session_id,
+ backend="claude",
+ deliveries=[delivery],
+ dispatch_text="anchor prompt",
+ attempt_id="atm_anchor_identity",
+ )
+ assert message_deliveries.bind_native_start(
+ conn,
+ "trn_anchor_identity",
+ expected_version=int(claimed["turn"]["version"]),
+ runtime_key="anchor-runtime",
+ runtime_turn_id="anchor-runtime-turn",
+ native_turn_id="anchor-native-turn",
+ ) is not None
+ assert message_deliveries.materialize_start_acceptance(
+ conn,
+ turn_id="trn_anchor_identity",
+ evidence={"kind": "anchor_identity_test"},
+ )
+ _insert_agent_run(
+ conn,
+ "run_anchor_identity",
+ session_id=session_id,
+ source_kind="agent",
+ delivery_id=delivery["id"],
+ )
+ with engine.connect() as conn:
+ by_turn = messages_service.list_session_messages(
+ conn,
+ session_id=session_id,
+ around_turn_id="trn_anchor_identity",
+ )
+ by_run = messages_service.list_session_messages(
+ conn,
+ session_id=session_id,
+ around_run_id="run_anchor_identity",
+ )
+ assert by_turn["anchor_id"] == delivery["id"]
+ assert by_run["anchor_id"] == delivery["id"]
+ assert [row["id"] for row in by_turn["messages"]] == [delivery["id"]]
+ assert [row["id"] for row in by_run["messages"]] == [delivery["id"]]
+
+
+def test_list_session_messages_resolves_legacy_run_anchor(isolated_state):
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ session_id = "ses_legacy_run_anchor"
+ _seed_session(conn, scope_id, session_id)
+ legacy = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author="agent",
+ message_type="result",
+ source="harness",
+ text="legacy run anchor",
+ native_message_id="agent_run:run_legacy_anchor",
+ )
+ _insert_agent_run(
+ conn,
+ "run_legacy_anchor",
+ session_id=session_id,
+ source_kind="agent",
+ )
+
+ with engine.connect() as conn:
+ anchored = messages_service.list_session_messages(
+ conn,
+ session_id=session_id,
+ around_run_id="run_legacy_anchor",
+ )
+
+ assert anchored["anchor_id"] == legacy["id"]
+ assert [row["id"] for row in anchored["messages"]] == [legacy["id"]]
+
+
+def test_list_session_messages_scopes_native_anchor_by_platform(isolated_state):
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ session_id = "ses_native_platform_anchor"
+ _seed_session(conn, scope_id, session_id)
+ slack = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="slack",
+ author="agent",
+ message_type="result",
+ text="slack reply",
+ native_message_id="same-native-id",
+ )
+ discord = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="discord",
+ author="agent",
+ message_type="result",
+ text="discord reply",
+ native_message_id="same-native-id",
+ )
+
+ with engine.connect() as conn:
+ anchored = messages_service.list_session_messages(
+ conn,
+ session_id=session_id,
+ around_native_id="same-native-id",
+ around_native_platform="discord",
+ )
+
+ assert anchored["anchor_id"] == discord["id"]
+ assert any(row["id"] == discord["id"] for row in anchored["messages"])
+ assert slack["id"] != discord["id"]
+
+
def test_list_session_messages_before_id_returns_older_window(isolated_state):
"""The chat page opens on the recent tail, then pages upward from the first
loaded row to recover the older transcript without replacing the tail."""
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index 56269a2fe..465c320e5 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -1124,6 +1124,36 @@ def test_build_context_assigns_hook_message_id() -> None:
assert context.platform_specific["task_trigger_kind"] == "hook"
+def test_build_context_forwards_vault_callback_outcome_metadata() -> None:
+ settings_manager = SimpleNamespace(get_store=lambda: SimpleNamespace(get_user=lambda *_args, **_kwargs: None))
+ controller = SimpleNamespace(
+ platform_settings_managers={"slack": settings_manager},
+ get_im_client_for_context=lambda _context: SimpleNamespace(
+ should_use_thread_for_reply=lambda: True,
+ should_use_thread_for_dm_session=lambda: False,
+ ),
+ )
+ service = ScheduledTaskService(controller=controller, store=ScheduledTaskStore(Path("/tmp/nonexistent-scheduled.json")))
+ target = parse_session_key("slack::channel::C123")
+
+ context = asyncio.run(
+ service._build_context(
+ target,
+ execution_id="exec-vault",
+ trigger_kind="agent_run",
+ metadata={
+ "source_kind": "callback",
+ "source_actor": "vault:vrq_1",
+ "vault_request_type": "access",
+ "vault_request_status": "denied",
+ },
+ )
+ )
+
+ assert context.platform_specific["vault_request_type"] == "access"
+ assert context.platform_specific["vault_request_status"] == "denied"
+
+
def test_build_context_carries_the_definition_name_for_display() -> None:
"""The prompt echo names what fired, so the label cannot be an opaque id."""
diff --git a/tests/test_vault_request_callbacks.py b/tests/test_vault_request_callbacks.py
index 416f10dd3..c9c176552 100644
--- a/tests/test_vault_request_callbacks.py
+++ b/tests/test_vault_request_callbacks.py
@@ -555,13 +555,20 @@ def test_enqueue_session_callback_uses_callback_source(monkeypatch):
monkeypatch.setattr(st, "resolve_session_id_target", lambda sid: _Target())
- out = st.enqueue_session_callback(_Store(), session_id="ses_x", message="resume now", source_actor="vault:vrq_1")
+ out = st.enqueue_session_callback(
+ _Store(),
+ session_id="ses_x",
+ message="resume now",
+ source_actor="vault:vrq_1",
+ metadata={"vault_request_status": "denied"},
+ )
assert out is not None and out.id == "run_1"
assert calls["source_kind"] == "callback"
assert calls["session_policy"] == "existing"
assert calls["session_id"] == "ses_x"
assert calls["message"] == "resume now"
assert calls["source_actor"] == "vault:vrq_1"
+ assert calls["metadata"] == {"vault_request_status": "denied"}
# Nothing to send → no enqueue.
assert st.enqueue_session_callback(_Store(), session_id="", message="x", source_actor="a") is None
diff --git a/tests/test_vault_service.py b/tests/test_vault_service.py
index 36d000953..e14359784 100644
--- a/tests/test_vault_service.py
+++ b/tests/test_vault_service.py
@@ -13,7 +13,16 @@ from sqlalchemy.exc import IntegrityError
from storage import vault_service as vs, vault_webauthn
from storage.db import create_sqlite_engine
-from storage.models import metadata, state_meta, vault_auth_factors, vault_grants, vault_requests, vault_secrets
+from storage.models import (
+ agent_sessions,
+ metadata,
+ state_meta,
+ vault_auth_factors,
+ vault_grants,
+ vault_requests,
+ vault_secrets,
+)
+from storage import message_deliveries
from storage.vault_crypto import Sealed
from tests.vault_webauthn_helpers import WebAuthnTestCredential
@@ -144,6 +153,99 @@ def test_provision_request_rejects_case_only_duplicate_secret(vault):
assert exc.value.existing_name == "OpenAIKey"
+def test_provision_request_uses_active_turn_as_plain_claude_anchor(vault):
+ now = "2026-08-08T00:00:00+00:00"
+ session_id = "ses_claude_anchor"
+ delivery_id = "del_claude_anchor"
+ turn_id = "turn_claude_anchor"
+ with vault.begin() as conn:
+ conn.execute(
+ agent_sessions.insert().values(
+ id=session_id,
+ scope_id=None,
+ agent_id=None,
+ agent_name="claude",
+ agent_backend="claude",
+ agent_variant="claude",
+ model=None,
+ reasoning_effort=None,
+ session_anchor=session_id,
+ workdir="/tmp",
+ native_session_id="",
+ title=None,
+ status="active",
+ visibility="foreground",
+ pinned=0,
+ agent_status="busy",
+ composer_draft_text=None,
+ composer_draft_updated_at=None,
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+ delivery = message_deliveries.insert_delivery(
+ conn,
+ delivery_id=delivery_id,
+ session_id=session_id,
+ priority="p0",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=None,
+ session_id=session_id,
+ platform="avibe",
+ author="user",
+ source="user",
+ text="request a key",
+ ),
+ dispatch_text="request a key",
+ now=now,
+ )
+ message_deliveries.claim_start_batch(
+ conn,
+ turn_id=turn_id,
+ session_id=session_id,
+ backend="claude",
+ deliveries=[delivery],
+ dispatch_text="request a key",
+ )
+ request = vs.create_provision_request(
+ conn,
+ "CLAUDE_KEY",
+ requester={"source": "agent-cli", "session_id": session_id},
+ )
+
+ assert request["status"] == "pending"
+ row = request
+ assert row["id"]
+ with vault.connect() as conn:
+ stored = conn.execute(select(vault_requests).where(vault_requests.c.id == row["id"])).mappings().one()
+ assert stored["message_id"] is None
+ assert json.loads(stored["requester"])["turn_id"] == turn_id
+
+
+def test_provision_request_does_not_store_derived_delivery_as_reply_anchor(vault, monkeypatch):
+ monkeypatch.setattr(
+ vs,
+ "_active_session_turn_anchor",
+ lambda conn, session_id: ("msg_initial_delivery", "turn_active"),
+ )
+
+ with vault.begin() as conn:
+ request = vs.create_provision_request(
+ conn,
+ "DERIVED_KEY",
+ requester={"source": "agent-cli", "session_id": "ses_active"},
+ )
+ stored = conn.execute(
+ select(vault_requests).where(vault_requests.c.id == request["id"])
+ ).mappings().one()
+
+ assert stored["message_id"] is None
+ assert json.loads(stored["requester"])["turn_id"] == "turn_active"
+
+
def test_provision_request_rejects_case_only_duplicate_pending_request(vault):
with vault.begin() as conn:
pending = vs.create_provision_request(conn, "openAiKey")
diff --git a/ui/src/components/ui/vault-request-card.test.tsx b/ui/src/components/ui/vault-request-card.test.tsx
new file mode 100644
index 000000000..df8a6d73e
--- /dev/null
+++ b/ui/src/components/ui/vault-request-card.test.tsx
@@ -0,0 +1,79 @@
+// @vitest-environment jsdom
+
+import { createInstance } from 'i18next';
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import en from '@/i18n/en.json';
+import type { VaultRequest } from '@/context/ApiContext';
+import { VaultProvisionDialogProvider, VaultRequestCard } from './vault-request-card';
+
+vi.mock('./vault-secret-dialog', () => ({
+ VaultSecretDialog: ({
+ open,
+ onOpenChange,
+ onCancel,
+ }: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ onCancel?: () => void;
+ }) => open ? (
+ <div role="dialog">
+ <button type="button" aria-label="close dialog" onClick={() => onOpenChange(false)}>Close</button>
+ <button type="button" onClick={onCancel}>Ignore</button>
+ </div>
+ ) : null,
+}));
+
+const i18n = createInstance();
+void i18n.use(initReactI18next).init({
+ lng: 'en',
+ fallbackLng: 'en',
+ resources: { en: { translation: en } },
+ interpolation: { escapeValue: false },
+});
+
+const request = {
+ id: 'vrq_test',
+ request_type: 'provision',
+ secret_name: 'CHAINBOT_CLOUDFLARE_API_TOKEN',
+ requester: {},
+ delivery: {},
+ status: 'pending',
+ message_id: null,
+ created_at: '2026-08-08T00:00:00Z',
+ decided_at: null,
+ expires_at: null,
+ card: { request_type: 'provision' },
+} satisfies VaultRequest;
+
+const renderProvisionCard = (onProvisionRequestHidden = vi.fn()) => render(
+ <I18nextProvider i18n={i18n}>
+ <VaultProvisionDialogProvider
+ requests={[request]}
+ onResolved={vi.fn()}
+ onProvisionRequestHidden={onProvisionRequestHidden}
+ >
+ <VaultRequestCard request={request} onResolved={vi.fn()} />
+ </VaultProvisionDialogProvider>
+ </I18nextProvider>,
+);
+
+describe('VaultRequestCard provision dialog dismissal', () => {
+ afterEach(() => cleanup());
+
+ it('keeps the card after close and hides it after Ignore', () => {
+ const onProvisionRequestHidden = vi.fn();
+ renderProvisionCard(onProvisionRequestHidden);
+
+ fireEvent.click(screen.getByRole('button', { name: /provide/i }));
+ fireEvent.click(screen.getByRole('button', { name: 'close dialog' }));
+ expect(screen.getByText(request.secret_name)).toBeTruthy();
+
+ fireEvent.click(screen.getByRole('button', { name: /provide/i }));
+ fireEvent.click(screen.getByRole('button', { name: 'Ignore' }));
+ expect(screen.queryByText(request.secret_name)).toBeNull();
+ expect(onProvisionRequestHidden).toHaveBeenCalledWith(request.id);
+ });
+});
diff --git a/ui/src/components/ui/vault-request-card.tsx b/ui/src/components/ui/vault-request-card.tsx
index ad6860caf..388cdf30e 100644
--- a/ui/src/components/ui/vault-request-card.tsx
+++ b/ui/src/components/ui/vault-request-card.tsx
@@ -19,25 +19,42 @@ function requestType(request: VaultRequest): RequestType {
type OpenProvisionDialog = (request: VaultRequest) => void;
-const VaultProvisionDialogContext = createContext<OpenProvisionDialog | null>(null);
+type VaultProvisionDialogContextValue = {
+ open: OpenProvisionDialog;
+ isDismissed: (requestId: string) => boolean;
+};
+
+const VaultProvisionDialogContext = createContext<VaultProvisionDialogContextValue | null>(null);
export const VaultProvisionDialogProvider: React.FC<{
requests: VaultRequest[];
onResolved: () => void;
+ onProvisionRequestHidden?: (requestId: string) => void;
disabled?: boolean;
children: ReactNode;
-}> = ({ requests, onResolved, disabled = false, children }) => {
+}> = ({ requests, onResolved, onProvisionRequestHidden, disabled = false, children }) => {
const [activeRequestId, setActiveRequestId] = useState<string | null>(null);
+ const [dismissedRequestIds, setDismissedRequestIds] = useState<Set<string>>(() => new Set());
const openProvisionDialog = useCallback((request: VaultRequest) => {
setActiveRequestId(request.id);
}, []);
+ const dismissProvisionDialog = useCallback((requestId: string) => {
+ setActiveRequestId(null);
+ onProvisionRequestHidden?.(requestId);
+ setDismissedRequestIds((current) => {
+ if (current.has(requestId)) return current;
+ return new Set(current).add(requestId);
+ });
+ }, [onProvisionRequestHidden]);
const activeRequest = useMemo(
() => requests.find((request) => request.id === activeRequestId && requestType(request) === 'provision'),
[activeRequestId, requests],
);
return (
- <VaultProvisionDialogContext.Provider value={disabled ? null : openProvisionDialog}>
+ <VaultProvisionDialogContext.Provider
+ value={disabled ? null : { open: openProvisionDialog, isDismissed: (id) => dismissedRequestIds.has(id) }}
+ >
{children}
{activeRequest ? (
<VaultSecretDialog
@@ -46,7 +63,9 @@ export const VaultProvisionDialogProvider: React.FC<{
if (!open) setActiveRequestId(null);
}}
request={activeRequest}
+ onCancel={() => dismissProvisionDialog(activeRequest.id)}
onCreated={() => {
+ onProvisionRequestHidden?.(activeRequest.id);
setActiveRequestId(null);
onResolved();
}}
@@ -65,8 +84,8 @@ export const VaultRequestCard: React.FC<{ request: VaultRequest; onResolved: ()
const { t } = useTranslation();
const [open, setOpen] = useState(false);
const type = useMemo(() => requestType(request), [request]);
- const openProvisionDialog = useContext(VaultProvisionDialogContext);
- const externallyOwnedProvision = type === 'provision' && openProvisionDialog !== null;
+ const provisionDialog = useContext(VaultProvisionDialogContext);
+ const externallyOwnedProvision = type === 'provision' && provisionDialog !== null;
const card = (request.card ?? {}) as {
kind?: string;
protection?: string;
@@ -94,6 +113,8 @@ export const VaultRequestCard: React.FC<{ request: VaultRequest; onResolved: ()
? { icon: <PenTool className="size-4" />, tint: 'bg-violet/15 text-violet', title: t('vaults.approval.signTitle'), action: t('vaults.requests.review') }
: { icon: <LockKeyhole className="size-4" />, tint: 'bg-gold/15 text-gold', title: t('vaults.approval.accessTitle'), action: t('vaults.requests.review') };
+ if (type === 'provision' && provisionDialog?.isDismissed(request.id)) return null;
+
return (
<>
<div className="flex items-center gap-3 rounded-xl border border-border bg-surface px-3.5 py-3">
@@ -116,7 +137,7 @@ export const VaultRequestCard: React.FC<{ request: VaultRequest; onResolved: ()
size="sm"
className="shrink-0"
onClick={() => {
- if (externallyOwnedProvision) openProvisionDialog(request);
+ if (externallyOwnedProvision) provisionDialog.open(request);
else setOpen(true);
}}
>
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index 2757fd6d8..23e1c02df 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -20,7 +20,14 @@ import { isTerminalAgentMessage, isTranscriptMessage } from '../../lib/chatMessa
import { chatRowKind, drawsEmptyBodyPlaceholder, isAgentAuthored } from '../../lib/chatRowKind';
import { useIosKeyboardInset } from '../../lib/useIosKeyboardInset';
import { isProxyMediaUrl } from '../../lib/mediaProxy';
-import { isVaultApprovalRequest, placeVaultProvisionRequests } from '../../lib/vaultRequestPlacement';
+import {
+ isVaultApprovalRequest,
+ placeVaultProvisionRequests,
+ vaultRequestSourceMessageId,
+ vaultRequestSourcePlatform,
+ vaultRequestSourceRunId,
+ vaultRequestSourceTurnId,
+} from '../../lib/vaultRequestPlacement';
import { localPath, type ShowPageLinkInfo } from '../../lib/showPageLinks';
import { showPageEmbeddedPath } from '../../apps/showPageAvatar';
import { downloadFile, fileMeta } from '../../lib/filesApi';
@@ -41,6 +48,7 @@ import {
chatTriggerLink,
harnessChipLabelKey,
needsHarnessProvenanceReconcile,
+ vaultCallbackStatusKey,
} from '../../lib/chatTrigger';
import { AnnotationMessage } from './AnnotationMessage';
import { AGENT_BUBBLE, SYSTEM_BUBBLE, USER_BUBBLE } from './chatBubble';
@@ -49,8 +57,10 @@ import { useFileDrop } from '../../lib/useFileDrop';
import { quoteText } from '../../lib/quoteText';
import {
isTranscriptWindowDisjoint,
+ mergeAnchorWindow,
mergeById,
insertMessageOrdered,
+ transcriptWindowsOverlap,
} from '../../lib/transcriptOrder';
import { AgentRoutePicker } from './AgentRoutePicker';
import {
@@ -156,6 +166,7 @@ const emptyRuntimeState = (): SessionRuntimeState => ({
// detach the live tail (historical-window) instead of growing the DOM with rows
// below the viewport.
const MAX_RETAINED_MESSAGES = 300;
+const VAULT_ANCHOR_RETRY_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 16_000, 30_000] as const;
// Display label for the archive chord (⇧⌘D / Ctrl+Shift+D). Resolved once at
// module load — the platform can't change mid-session — and shown as the archive
@@ -185,6 +196,7 @@ export const ChatPage: React.FC = () => {
// re-render / visibility gap-recovery can't re-trigger the jump.
const [searchParams, setSearchParams] = useSearchParams();
const deepLinkMessageId = searchParams.get('msg');
+ const deepLinkMessageIdRef = useLatestRef(deepLinkMessageId);
// A "show me the chat" navigation carries ?view=chat (see sessionChatPath({ showChat:
// true })) — a general signal that this navigation must leave Show Page mode.
const showChatSignal = searchParams.get('view') === 'chat';
@@ -263,6 +275,7 @@ export const ChatPage: React.FC = () => {
// render that flips ``readOnly``. An effect would first commit one frame with
// the chat surface still hidden and the iframe already gone — a blank chat.
const showPageActive = isShowPageActive(readOnly, showPageMode);
+ const showPageActiveRef = useLatestRef(showPageActive);
// True while the share popover is open. The popover floats over the Show Page
// iframe; making the iframe inert lets an outside tap there reach the parent
// document so the (non-modal) popover dismisses, without modal-blocking the
@@ -392,10 +405,16 @@ export const ChatPage: React.FC = () => {
const [agents, setAgents] = useState<VibeAgentBrief[]>([]);
const [defaultAgentName, setDefaultAgentName] = useState<string | null>(null);
const [messages, setMessages] = useState<WorkbenchMessage[]>([]);
+ const [vaultResolvedSourceIds, setVaultResolvedSourceIds] = useState<Map<string, string>>(
+ () => new Map(),
+ );
const provisionPlacement = useMemo(
- () => placeVaultProvisionRequests(messages, vaultRequests),
- [messages, vaultRequests],
+ () => placeVaultProvisionRequests(messages, vaultRequests, vaultResolvedSourceIds),
+ [messages, vaultRequests, vaultResolvedSourceIds],
);
+ const provisionPlacementRef = useLatestRef(provisionPlacement);
+ const vaultRequestsRef = useLatestRef(vaultRequests);
+ const hiddenVaultRequestIdsRef = useRef<Set<string>>(new Set());
const transcriptTailVaultRequests = useMemo(
() => [...pendingApprovals, ...provisionPlacement.unanchored],
[pendingApprovals, provisionPlacement],
@@ -406,6 +425,30 @@ export const ChatPage: React.FC = () => {
// can still read the current transcript without listing ``messages`` as a dep.
const messagesRef = useRef(messages);
messagesRef.current = messages;
+ const vaultAnchorFetchesRef = useRef<Set<string>>(new Set());
+ const vaultAnchorRetryAttemptsRef = useRef<Map<string, number>>(new Map());
+ const vaultAnchorRetryExhaustedRef = useRef<Set<string>>(new Set());
+ const vaultAnchorRetryWaitingRef = useRef<Set<string>>(new Set());
+ const vaultAnchorInFlightRef = useRef(false);
+ const vaultAnchorMergeRef = useRef<{
+ anchorMessageId: string;
+ nextBeforeId: string | null;
+ result: ReturnType<typeof mergeAnchorWindow>;
+ } | null>(null);
+ const deepLinkWindowHandledRef = useRef(false);
+ const [vaultAnchorCycle, setVaultAnchorCycle] = useState(0);
+ const markVaultRequestHidden = useCallback((requestId: string) => {
+ hiddenVaultRequestIdsRef.current.add(requestId);
+ // A user dismissal is an explicit retry boundary for deferred or exhausted
+ // anchors, so a later request can try again immediately.
+ vaultAnchorRetryAttemptsRef.current.clear();
+ vaultAnchorRetryExhaustedRef.current.clear();
+ vaultAnchorRetryWaitingRef.current.clear();
+ // A deferred request is intentionally left un-fetched while another card
+ // owns the visible historical window. Hiding that card is the state change
+ // that makes the deferred request eligible for its next anchor attempt.
+ setVaultAnchorCycle((cycle) => cycle + 1);
+ }, []);
const [olderCursor, setOlderCursor] = useState<string | null>(null);
const [loadingOlder, setLoadingOlder] = useState(false);
const loadingOlderRef = useRef(false);
@@ -436,6 +479,7 @@ export const ChatPage: React.FC = () => {
// scroll to once its window is in the DOM, the id to highlight (~3s fade), and
// the last ``msg`` value already handled so the jump effect runs once per value.
const [jumpTarget, setJumpTarget] = useState<string | null>(null);
+ const jumpTargetRef = useLatestRef(jumpTarget);
const [highlightedId, setHighlightedId] = useState<string | null>(null);
const handledJumpRef = useRef<string | null>(null);
const highlightTimerRef = useRef<number | null>(null);
@@ -658,6 +702,252 @@ export const ChatPage: React.FC = () => {
const sessionIdRef = useRef(sessionId);
sessionIdRef.current = sessionId;
+ // Legacy provision rows may be created after their Agent reply and therefore
+ // cannot be placed from `created_at` alone. When the originating user message
+ // is outside the retained tail, fetch a small around-window once so the card
+ // can join its real turn instead of falling back to a fixed-looking footer.
+ useEffect(() => {
+ if (
+ !sessionId ||
+ loading ||
+ session?.id !== sessionId ||
+ deepLinkMessageId ||
+ jumpTarget ||
+ showPageActive ||
+ deepLinkWindowHandledRef.current ||
+ provisionPlacement.unanchored.length === 0
+ ) return;
+ if (vaultAnchorInFlightRef.current) return;
+ const request = provisionPlacement.unanchored.find((candidate) => {
+ const sourceMessageId = vaultRequestSourceMessageId(candidate);
+ const requestMessageId = typeof candidate.message_id === 'string' && candidate.message_id.trim()
+ ? candidate.message_id
+ : null;
+ const sourceTurnId = vaultRequestSourceTurnId(candidate);
+ const sourceRunId = vaultRequestSourceRunId(candidate);
+ const messageAnchorId = requestMessageId ?? sourceMessageId;
+ const anchorKey = messageAnchorId
+ ? `message:${messageAnchorId}`
+ : sourceTurnId
+ ? `turn:${sourceTurnId}`
+ : sourceRunId
+ ? `run:${sourceRunId}`
+ : null;
+ return (
+ Boolean(anchorKey) &&
+ !hiddenVaultRequestIdsRef.current.has(candidate.id) &&
+ !vaultAnchorRetryExhaustedRef.current.has(`${candidate.id}:${anchorKey}`) &&
+ !vaultAnchorRetryWaitingRef.current.has(`${candidate.id}:${anchorKey}`) &&
+ !vaultAnchorFetchesRef.current.has(`${candidate.id}:${anchorKey}`)
+ );
+ });
+ if (!request) return;
+ const sourceMessageId = vaultRequestSourceMessageId(request);
+ const requestMessageId = typeof request.message_id === 'string' && request.message_id.trim()
+ ? request.message_id
+ : null;
+ const sourceTurnId = vaultRequestSourceTurnId(request);
+ const sourceRunId = vaultRequestSourceRunId(request);
+ const sourcePlatform = vaultRequestSourcePlatform(request);
+ const messageAnchorId = requestMessageId ?? sourceMessageId;
+ const anchorKey = messageAnchorId
+ ? `message:${messageAnchorId}`
+ : sourceTurnId
+ ? `turn:${sourceTurnId}`
+ : sourceRunId
+ ? `run:${sourceRunId}`
+ : null;
+ if (!anchorKey) return;
+ const fetchKey = `${request.id}:${anchorKey}`;
+ vaultAnchorFetchesRef.current.add(fetchKey);
+ vaultAnchorInFlightRef.current = true;
+ let retryDelayMs: number | null = null;
+ let deferredByVisibleAnchor = false;
+ let deferredByMissingReply = false;
+ let deferredByHiddenSurface = false;
+ const loadedSource = messageAnchorId
+ ? messagesRef.current.find(
+ (message) => message.id === messageAnchorId || (
+ message.native_message_id === messageAnchorId &&
+ (!sourcePlatform || message.platform === sourcePlatform)
+ ),
+ )
+ : undefined;
+ const fetchAnchorWindow = async () => {
+ const first = await api.listSessionMessages(sessionId, {
+ ...(loadedSource
+ ? { aroundId: loadedSource.id }
+ : requestMessageId
+ ? { aroundId: requestMessageId }
+ : sourceMessageId
+ ? {
+ aroundNativeId: sourceMessageId,
+ ...(sourcePlatform ? { aroundNativePlatform: sourcePlatform } : {}),
+ }
+ : sourceTurnId
+ ? { aroundTurnId: sourceTurnId }
+ : { aroundRunId: sourceRunId! }),
+ limit: 50,
+ cache: false,
+ });
+ if (first.messages.length > 0 || loadedSource || requestMessageId || !sourceMessageId) return first;
+ // A legacy request may already carry the durable id. Keep that compatibility
+ // path after the native lookup so IM requests resolve before window fetch.
+ return api.listSessionMessages(sessionId, {
+ aroundId: sourceMessageId,
+ limit: 50,
+ cache: false,
+ });
+ };
+ void fetchAnchorWindow()
+ .then((res) => {
+ if (
+ sessionId !== sessionIdRef.current ||
+ deepLinkMessageIdRef.current ||
+ jumpTargetRef.current
+ ) {
+ vaultAnchorFetchesRef.current.delete(fetchKey);
+ return;
+ }
+ if (showPageActiveRef.current) {
+ // The request may resolve after the user switches to Show Page. Release
+ // the key so leaving that surface re-arms the fetch without committing a
+ // historical transcript window into the hidden chat view.
+ deferredByHiddenSurface = true;
+ vaultAnchorFetchesRef.current.delete(fetchKey);
+ return;
+ }
+ const requestStillPending = vaultRequestsRef.current.some(
+ (candidate) => candidate.id === request.id && candidate.status === 'pending',
+ );
+ const requestStillUnanchored = provisionPlacementRef.current.unanchored.some(
+ (candidate) => candidate.id === request.id,
+ );
+ if (
+ !requestStillPending ||
+ !requestStillUnanchored ||
+ hiddenVaultRequestIdsRef.current.has(request.id)
+ ) {
+ vaultAnchorFetchesRef.current.delete(fetchKey);
+ return;
+ }
+ vaultAnchorRetryAttemptsRef.current.delete(fetchKey);
+ vaultAnchorRetryExhaustedRef.current.delete(fetchKey);
+ vaultAnchorRetryWaitingRef.current.delete(fetchKey);
+ const resolvedAnchorId = res.anchor_id;
+ if (resolvedAnchorId) {
+ setVaultResolvedSourceIds((previous) => {
+ if (previous.get(request.id) === resolvedAnchorId) return previous;
+ const next = new Map(previous);
+ next.set(request.id, resolvedAnchorId);
+ return next;
+ });
+ }
+ const incoming = res.messages.filter(isTranscriptMessage);
+ if (incoming.length === 0) {
+ // A Turn anchor can be known before its initial Delivery is accepted.
+ // Release the key and wait for the next transcript update to retry once
+ // the around-turn lookup can resolve a durable message.
+ deferredByMissingReply = true;
+ vaultAnchorFetchesRef.current.delete(fetchKey);
+ return;
+ }
+ const existing = messagesRef.current;
+ const disjoint = existing.length > 0 && !transcriptWindowsOverlap(existing, incoming);
+ const preservesVisibleAnchor = [...provisionPlacementRef.current.byMessageId.values()].some(
+ (candidates) => candidates.some(
+ (candidate) => candidate.id !== request.id &&
+ candidate.status === 'pending' &&
+ !hiddenVaultRequestIdsRef.current.has(candidate.id),
+ ),
+ );
+ if (disjoint && preservesVisibleAnchor) {
+ // Another request currently owns the visible historical window. Let
+ // the next placement cycle retry this request once that anchor is
+ // fulfilled or dismissed.
+ deferredByVisibleAnchor = true;
+ vaultAnchorFetchesRef.current.delete(fetchKey);
+ return;
+ }
+ // An around-fetch can land wholly outside the retained live tail. Do
+ // not union those ranges: the missing rows would be rendered as if
+ // they were adjacent. Replace the tail with a historical window,
+ // matching the existing deep-link behavior, so the anchor stays in a
+ // coherent transcript and the user gets an explicit latest reload.
+ const anchorWindow = disjoint ? incoming : mergeById(existing, incoming);
+ const sourceMessageIds = res.anchor_id
+ ? new Map([[request.id, res.anchor_id]])
+ : undefined;
+ const placement = placeVaultProvisionRequests(anchorWindow, [request], sourceMessageIds);
+ if (!placement.byMessageId.size) {
+ // The source turn may be visible before its Agent reply is persisted.
+ // Release the key and wait for the next transcript update to retry;
+ // cycling immediately here would spin on the same incomplete window.
+ deferredByMissingReply = true;
+ vaultAnchorFetchesRef.current.delete(fetchKey);
+ return;
+ }
+ const anchorMessageId = placement.byMessageId.keys().next().value;
+ if (typeof anchorMessageId !== 'string') return;
+ if (disjoint) {
+ const incomingBeforeExisting = isTranscriptWindowDisjoint(incoming[incoming.length - 1], existing[0]);
+ const nextHistoricalWindow = Boolean(res.next_after_id) || incomingBeforeExisting;
+ if (nextHistoricalWindow) historicalWindowRef.current = true;
+ setMessages(incoming);
+ setOlderCursor(res.next_before_id ?? null);
+ setHistoricalWindow(nextHistoricalWindow);
+ setJumpTarget(anchorMessageId);
+ } else {
+ setMessages((previous) => {
+ const result = mergeAnchorWindow(
+ previous,
+ incoming,
+ anchorMessageId,
+ MAX_RETAINED_MESSAGES,
+ followingTailRef.current,
+ );
+ if (result.replaced || result.detachedTail) historicalWindowRef.current = true;
+ vaultAnchorMergeRef.current = {
+ anchorMessageId,
+ nextBeforeId: res.next_before_id ?? null,
+ result,
+ };
+ return result.messages;
+ });
+ }
+ // A completed anchor is gated by placement itself. Release the fetch key
+ // so a later retained-window trim can re-arm the request and recover it.
+ vaultAnchorFetchesRef.current.delete(fetchKey);
+ })
+ .catch(() => {
+ // Retry transient failures with bounded exponential backoff. Once the
+ // budget is exhausted, wait for an explicit reload/dismissal boundary
+ // instead of polling an unavailable backend for the life of the chat.
+ const attempt = vaultAnchorRetryAttemptsRef.current.get(fetchKey) ?? 0;
+ if (attempt < VAULT_ANCHOR_RETRY_DELAYS_MS.length) {
+ vaultAnchorRetryAttemptsRef.current.set(fetchKey, attempt + 1);
+ vaultAnchorRetryWaitingRef.current.add(fetchKey);
+ retryDelayMs = VAULT_ANCHOR_RETRY_DELAYS_MS[attempt];
+ } else {
+ vaultAnchorRetryAttemptsRef.current.delete(fetchKey);
+ vaultAnchorRetryExhaustedRef.current.add(fetchKey);
+ }
+ vaultAnchorFetchesRef.current.delete(fetchKey);
+ })
+ .finally(() => {
+ if (sessionId !== sessionIdRef.current) return;
+ vaultAnchorInFlightRef.current = false;
+ if (retryDelayMs !== null) {
+ window.setTimeout(() => {
+ vaultAnchorRetryWaitingRef.current.delete(fetchKey);
+ if (sessionId === sessionIdRef.current) setVaultAnchorCycle((cycle) => cycle + 1);
+ }, retryDelayMs);
+ } else if (!deferredByVisibleAnchor && !deferredByMissingReply && !deferredByHiddenSurface) {
+ setVaultAnchorCycle((cycle) => cycle + 1);
+ }
+ });
+ }, [api, deepLinkMessageId, jumpTarget, loading, provisionPlacement.unanchored, session?.id, sessionId, showPageActive, vaultAnchorCycle]);
+
const appendMessage = useCallback((msg: WorkbenchMessage) => {
setMessages((prev) => {
// Ordered single-row insert (deduped, no full re-sort) so an out-of-order
@@ -780,6 +1070,19 @@ export const ChatPage: React.FC = () => {
trimmedOldestRef.current = false;
setOlderCursor(messages[0]?.id ?? null);
}
+ const anchorMerge = vaultAnchorMergeRef.current;
+ if (anchorMerge) {
+ vaultAnchorMergeRef.current = null;
+ if (messages.some((message) => message.id === anchorMerge.anchorMessageId)) {
+ if (anchorMerge.result.replaced || anchorMerge.result.detachedTail) setHistoricalWindow(true);
+ setJumpTarget(anchorMerge.anchorMessageId);
+ setOlderCursor(
+ anchorMerge.result.trimmedOldest
+ ? messages[0]?.id ?? null
+ : anchorMerge.nextBeforeId,
+ );
+ }
+ }
}, [messages]);
// Reconcile against durable storage after a window where ``message.new`` could
@@ -906,6 +1209,13 @@ export const ChatPage: React.FC = () => {
setMessages(tailMessages);
setOlderCursor(res.next_before_id ?? null);
setHistoricalWindow(false);
+ // A deliberate return to the live tail is the retry boundary for requests
+ // deferred while another disjoint anchor window was visible.
+ vaultAnchorFetchesRef.current.clear();
+ vaultAnchorRetryAttemptsRef.current.clear();
+ vaultAnchorRetryExhaustedRef.current.clear();
+ vaultAnchorRetryWaitingRef.current.clear();
+ deepLinkWindowHandledRef.current = false;
// Returning to the live tail from a historical window: activity ingestion was
// suppressed while scrolled away, so resync groups from storage — a turn that
// finished in history still gets its chip without a full reload.
@@ -1084,6 +1394,14 @@ export const ChatPage: React.FC = () => {
// loading state until refresh() resolves the new session.
setSession(null);
setMessages([]);
+ setVaultResolvedSourceIds(new Map());
+ vaultAnchorFetchesRef.current.clear();
+ vaultAnchorRetryAttemptsRef.current.clear();
+ vaultAnchorRetryExhaustedRef.current.clear();
+ vaultAnchorRetryWaitingRef.current.clear();
+ vaultAnchorInFlightRef.current = false;
+ deepLinkWindowHandledRef.current = false;
+ hiddenVaultRequestIdsRef.current.clear();
setOlderCursor(null);
setHistoricalWindow(false);
oldestLoadedIdRef.current = null;
@@ -1749,6 +2067,9 @@ export const ChatPage: React.FC = () => {
// the loaded session matches the route) — before that the loaded-vs-around
// decision and the scroll target wouldn't be meaningful.
if (loading || session?.id !== sessionId) return;
+ // A vault anchor swap may already be in flight. Let it finish first, then
+ // re-run this effect from the cycle tick so two centered windows cannot race.
+ if (vaultAnchorInFlightRef.current) return;
handledJumpRef.current = targetMsg;
const requestSessionId = sessionId;
@@ -1800,8 +2121,10 @@ export const ChatPage: React.FC = () => {
// reload the live tail; if not, it already reaches the tail and can keep
// normal pinned/follow behavior.
setMessages(window);
+ const reachesHistoricalWindow = Boolean(res.next_after_id);
+ deepLinkWindowHandledRef.current = reachesHistoricalWindow;
setOlderCursor(res.next_before_id ?? null);
- setHistoricalWindow(Boolean(res.next_after_id));
+ setHistoricalWindow(reachesHistoricalWindow);
setJumpTarget(targetMsg);
startHighlight(targetMsg);
clearParam();
@@ -1824,7 +2147,7 @@ export const ChatPage: React.FC = () => {
// window is dropped and ``?msg`` stays unhandled (Codex P2). The closure
// still reads ``session`` for the ``!session`` / ``session.id !== sessionId``
// readiness checks; it only needs to re-run when the id changes.
- }, [deepLinkMessageId, sessionId, loading, session?.id, api, selectChatView, startHighlight, setSearchParams]);
+ }, [api, deepLinkMessageId, loading, selectChatView, session?.id, sessionId, setSearchParams, startHighlight, vaultAnchorCycle]);
// Re-arm the jump guard once ``?msg=`` is gone. ``clearParam`` (above) nulls
// the param after handling, so without this re-selecting the SAME search hit
@@ -2103,6 +2426,7 @@ export const ChatPage: React.FC = () => {
key={sessionId ?? 'no-session'}
requests={vaultRequests}
onResolved={refreshVaultRequests}
+ onProvisionRequestHidden={markVaultRequestHidden}
disabled={readOnly}
>
{/* Mobile: a FIXED full-screen flex column (the AppShell brand header is
@@ -3633,6 +3957,7 @@ export const MessageRow = memo(function MessageRow({
// 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;
+ const vaultStatusKey = isHarness ? vaultCallbackStatusKey(message) : null;
const messageFontStyle = { fontSize: `${normalizeChatMessageFontSize(messageFontSize)}px` };
const resultPresentation = resultFooterParts(message);
@@ -3820,6 +4145,12 @@ export const MessageRow = memo(function MessageRow({
{t(harnessChipLabelKey(message))}
</span>
)}
+ {vaultStatusKey && (
+ <>
+ <span className="shrink-0 text-[11px] text-muted">·</span>
+ <span className="shrink-0 text-[11px] text-muted">{t(vaultStatusKey)}</span>
+ </>
+ )}
{triggerLink?.kind === 'source' && (
// A9a: agent-callback shows the SOURCE session + links to its chat.
<>
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index ca12ed408..c7fa7d5af 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -683,7 +683,7 @@ export type ApiContextType = {
/** Counts of resources permanently reclaimed when archiving this session
* (bound tasks/watches + active runs) — drives the irreversible-confirm dialog. */
getArchivePreview: (sessionId: string) => Promise<{ tasks: number; watches: number; runs: number; queued: number }>;
- listSessionMessages: (sessionId: string, params?: { afterId?: string; beforeId?: string; aroundId?: string; limit?: number; tail?: boolean; cache?: boolean }) => Promise<{ messages: WorkbenchMessage[]; next_after_id: string | null; next_before_id?: string | null }>;
+ listSessionMessages: (sessionId: string, params?: { afterId?: string; beforeId?: string; aroundId?: string; aroundNativeId?: string; aroundNativePlatform?: string; aroundTurnId?: string; aroundRunId?: string; limit?: number; tail?: boolean; cache?: boolean }) => Promise<{ messages: WorkbenchMessage[]; next_after_id: string | null; next_before_id?: string | null; anchor_id?: string | null }>;
// Chat Activity panel (GET /api/sessions/<id>/activity): summary of turn groups
// for chips, and one group's rows for lazy expand. Only used when the
// ``ui.show_agent_activity`` toggle is on (see lib/agentActivity).
@@ -3143,6 +3143,10 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
if (params?.afterId) search.set('after_id', params.afterId);
if (params?.beforeId) search.set('before_id', params.beforeId);
if (params?.aroundId) search.set('around_id', params.aroundId);
+ if (params?.aroundNativeId) search.set('around_native_id', params.aroundNativeId);
+ if (params?.aroundNativePlatform) search.set('around_native_platform', params.aroundNativePlatform);
+ if (params?.aroundTurnId) search.set('around_turn_id', params.aroundTurnId);
+ if (params?.aroundRunId) search.set('around_run_id', params.aroundRunId);
if (params?.limit) search.set('limit', String(params.limit));
if (params?.tail) search.set('tail', '1');
const qs = search.toString();
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 20587d484..f1fa638a1 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -3167,6 +3167,13 @@
"showIntent": "Page action",
"harness": "From agent",
"from": "From",
+ "vault": "From Vault",
+ "vaultProvided": "Secret provided",
+ "vaultAccessApproved": "Access approved",
+ "vaultSigned": "Signature complete",
+ "vaultDenied": "Denied",
+ "vaultFailed": "Failed",
+ "vaultExpired": "Expired",
"agentFallback": "agent"
},
"annotation": {
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index a00b6d4b0..e617ff60f 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -3167,6 +3167,13 @@
"showIntent": "页面操作",
"harness": "来自 Agent",
"from": "来自",
+ "vault": "来自 Vault",
+ "vaultProvided": "填写完成",
+ "vaultAccessApproved": "访问已批准",
+ "vaultSigned": "签名完成",
+ "vaultDenied": "已拒绝",
+ "vaultFailed": "处理失败",
+ "vaultExpired": "已过期",
"agentFallback": "智能体"
},
"annotation": {
diff --git a/ui/src/lib/chatTrigger.test.ts b/ui/src/lib/chatTrigger.test.ts
index 93e782d3c..d28124617 100644
--- a/ui/src/lib/chatTrigger.test.ts
+++ b/ui/src/lib/chatTrigger.test.ts
@@ -1,6 +1,11 @@
import { describe, expect, it } from 'vitest';
-import { chatTriggerLink, harnessChipLabelKey, needsHarnessProvenanceReconcile } from './chatTrigger';
+import {
+ chatTriggerLink,
+ harnessChipLabelKey,
+ needsHarnessProvenanceReconcile,
+ vaultCallbackStatusKey,
+} from './chatTrigger';
type Msg = Parameters<typeof chatTriggerLink>[0];
const msg = (over: Partial<Msg>): Msg => ({
@@ -126,6 +131,33 @@ describe('harnessChipLabelKey (leading-label key by source presence)', () => {
expect(key({ author_name: null, source_session_id: null })).toBe('chat.source.harness');
});
+ it('labels Vault callbacks separately from Agent callbacks', () => {
+ const metadata = {
+ source_kind: 'callback',
+ source_actor: 'vault:vrq_1',
+ vault_request_type: 'access',
+ vault_request_status: 'denied',
+ };
+ expect(key({ author_name: 'agent_run', metadata })).toBe('chat.source.vault');
+ expect(vaultCallbackStatusKey(msg({ author_name: 'agent_run', metadata }))).toBe('chat.source.vaultDenied');
+ });
+
+ it('uses the Vault outcome wording for provision, access, and sign callbacks', () => {
+ const callback = (requestType: string, status: string) =>
+ vaultCallbackStatusKey(msg({
+ metadata: {
+ source_kind: 'callback',
+ source_actor: 'vault:vrq_1',
+ vault_request_type: requestType,
+ vault_request_status: status,
+ },
+ }));
+ expect(callback('provision', 'fulfilled')).toBe('chat.source.vaultProvided');
+ expect(callback('access', 'approved')).toBe('chat.source.vaultAccessApproved');
+ expect(callback('sign', 'approved')).toBe('chat.source.vaultSigned');
+ expect(callback('access', 'expired')).toBe('chat.source.vaultExpired');
+ });
+
it('every non-agent Harness trigger keeps its own self-contained label', () => {
expect(key({ author_name: 'watch' })).toBe('chat.source.watch');
expect(key({ author_name: 'webhook' })).toBe('chat.source.webhook');
diff --git a/ui/src/lib/chatTrigger.ts b/ui/src/lib/chatTrigger.ts
index 55649c5a2..492951372 100644
--- a/ui/src/lib/chatTrigger.ts
+++ b/ui/src/lib/chatTrigger.ts
@@ -55,7 +55,45 @@ type TriggerFields = Pick<
| 'source_session_id'
| 'source_session_title'
| 'source_session_agent_name'
->;
+> & { metadata?: Record<string, unknown> };
+
+const VAULT_CALLBACK_STATUS_KEYS: Record<string, string> = {
+ 'provision:fulfilled': 'chat.source.vaultProvided',
+ 'access:approved': 'chat.source.vaultAccessApproved',
+ 'sign:approved': 'chat.source.vaultSigned',
+ 'access:denied': 'chat.source.vaultDenied',
+ 'sign:denied': 'chat.source.vaultDenied',
+ 'provision:denied': 'chat.source.vaultDenied',
+ 'access:failed': 'chat.source.vaultFailed',
+ 'sign:failed': 'chat.source.vaultFailed',
+ 'provision:failed': 'chat.source.vaultFailed',
+ 'access:expired': 'chat.source.vaultExpired',
+ 'sign:expired': 'chat.source.vaultExpired',
+ 'provision:expired': 'chat.source.vaultExpired',
+};
+
+function vaultCallbackMetadata(message: TriggerFields): { requestType: string; status: string } | null {
+ if (message.source !== 'harness') return null;
+ const metadata = message.metadata;
+ const sourceActor = typeof metadata?.source_actor === 'string' ? metadata.source_actor : '';
+ if (!sourceActor.startsWith('vault:')) return null;
+ const requestType = typeof metadata?.vault_request_type === 'string' ? metadata.vault_request_type : '';
+ const status = typeof metadata?.vault_request_status === 'string' ? metadata.vault_request_status : '';
+ return { requestType, status };
+}
+
+export function isVaultCallback(message: TriggerFields): boolean {
+ if (message.source !== 'harness') return false;
+ const metadata = message.metadata;
+ const sourceActor = typeof metadata?.source_actor === 'string' ? metadata.source_actor : '';
+ return sourceActor.startsWith('vault:');
+}
+
+export function vaultCallbackStatusKey(message: TriggerFields): string | null {
+ const metadata = vaultCallbackMetadata(message);
+ if (!metadata) return null;
+ return VAULT_CALLBACK_STATUS_KEYS[`${metadata.requestType}:${metadata.status}`] ?? null;
+}
// ``agentFallback`` is the localized word for "agent" (chat.source.agentFallback);
// passed in so this stays a pure, translation-free mapper.
@@ -96,6 +134,7 @@ export function chatTriggerLink(message: TriggerFields, agentFallback: string):
// Pure so the branch is unit-tested alongside chatTriggerLink.
export function harnessChipLabelKey(message: TriggerFields): string {
if (message.source === 'harness' && message.source_session_id) return 'chat.source.from';
+ if (isVaultCallback(message)) return 'chat.source.vault';
const kind = message.author_name;
if (kind === 'show_intent') return 'chat.source.showIntent';
if (kind === 'watch') return 'chat.source.watch';
diff --git a/ui/src/lib/transcriptOrder.test.ts b/ui/src/lib/transcriptOrder.test.ts
index 0e7bc1d4b..35f0a2da0 100644
--- a/ui/src/lib/transcriptOrder.test.ts
+++ b/ui/src/lib/transcriptOrder.test.ts
@@ -4,9 +4,11 @@ import type { WorkbenchMessage } from '../context/ApiContext';
import {
byCreatedThenId,
isTranscriptWindowDisjoint,
+ mergeAnchorWindow,
mergeById,
insertMessageOrdered,
messageOrderTimeMs,
+ transcriptWindowsOverlap,
timestampOrderTimeMs,
transcriptOrderTimeMs,
} from './transcriptOrder';
@@ -89,6 +91,64 @@ describe('isTranscriptWindowDisjoint', () => {
});
});
+describe('transcriptWindowsOverlap', () => {
+ it('detects a shared row between fetched windows', () => {
+ expect(transcriptWindowsOverlap([mk('a', t(1)), mk('b', t(2))], [mk('b', t(2)), mk('c', t(3))])).toBe(true);
+ expect(transcriptWindowsOverlap([mk('a', t(1))], [mk('b', t(2))])).toBe(false);
+ expect(transcriptWindowsOverlap([], [mk('b', t(2))])).toBe(false);
+ });
+});
+
+describe('mergeAnchorWindow', () => {
+ it('keeps the owning reply when a following-tail trim would drop it', () => {
+ const existing = Array.from({ length: 4 }, (_, index) => mk(`tail-${index}`, t(index + 4)));
+ const incoming = [mk('owner', t(1)), mk('tail-0', t(4))];
+
+ expect(mergeAnchorWindow(existing, incoming, 'owner', 4, true)).toEqual({
+ messages: incoming,
+ replaced: true,
+ detachedTail: false,
+ trimmedOldest: false,
+ });
+ });
+
+ it('keeps the owning reply when trimming from the newest side', () => {
+ const existing = Array.from({ length: 4 }, (_, index) => mk(`head-${index}`, t(index)));
+ const incoming = [mk('head-3', t(3)), mk('owner', t(4))];
+
+ expect(mergeAnchorWindow(existing, incoming, 'owner', 4, false)).toEqual({
+ messages: incoming,
+ replaced: true,
+ detachedTail: true,
+ trimmedOldest: false,
+ });
+ });
+
+ it('marks a newest-side trim historical even when the anchor is retained', () => {
+ const existing = Array.from({ length: 4 }, (_, index) => mk(`head-${index}`, t(index)));
+ const incoming = [mk('head-0', t(0)), mk('new-tail', t(4))];
+
+ expect(mergeAnchorWindow(existing, incoming, 'head-0', 4, false)).toEqual({
+ messages: existing,
+ replaced: false,
+ detachedTail: true,
+ trimmedOldest: false,
+ });
+ });
+
+ it('reports when a following-tail trim discards older rows', () => {
+ const existing = Array.from({ length: 4 }, (_, index) => mk(`tail-${index}`, t(index + 4)));
+ const incoming = [mk('old', t(1)), mk('tail-0', t(4))];
+
+ expect(mergeAnchorWindow(existing, incoming, 'tail-0', 4, true)).toEqual({
+ messages: existing,
+ replaced: false,
+ detachedTail: false,
+ trimmedOldest: true,
+ });
+ });
+});
+
describe('mergeById', () => {
it('dedupes by id and sorts into durable order', () => {
const existing = [mk('p1', t(1))];
@@ -143,6 +203,27 @@ describe('mergeById', () => {
expect(row.author_id).toBe('def_watch');
});
+ it('merges Vault provenance metadata into an existing live row', () => {
+ const live = {
+ id: 'm1',
+ created_at: t(1),
+ metadata: { source_kind: 'callback', source_actor: 'vault:vrq_1' },
+ } as unknown as WorkbenchMessage;
+ const enriched = {
+ id: 'm1',
+ created_at: t(1),
+ metadata: {
+ source_kind: 'callback',
+ source_actor: 'vault:vrq_1',
+ vault_request_type: 'access',
+ vault_request_status: 'denied',
+ },
+ } as unknown as WorkbenchMessage;
+
+ const [row] = mergeById([live], [enriched]);
+ expect(row.metadata).toEqual(enriched.metadata);
+ });
+
it('does not overwrite an already-resolved source-session id with a null reconcile', () => {
const existing = { id: 'm1', created_at: t(1), source_session_id: 'ses_src' } as unknown as WorkbenchMessage;
const incoming = { id: 'm1', created_at: t(1), source_session_id: null } as unknown as WorkbenchMessage;
diff --git a/ui/src/lib/transcriptOrder.ts b/ui/src/lib/transcriptOrder.ts
index 6426c1119..13f4711a0 100644
--- a/ui/src/lib/transcriptOrder.ts
+++ b/ui/src/lib/transcriptOrder.ts
@@ -60,6 +60,64 @@ export const isTranscriptWindowDisjoint = (
tailOldest: WorkbenchMessage,
): boolean => byCreatedThenId(tailOldest, previousNewest) > 0;
+/** Whether two fetched transcript windows share at least one durable row. */
+export const transcriptWindowsOverlap = (
+ left: WorkbenchMessage[],
+ right: WorkbenchMessage[],
+): boolean => {
+ if (left.length === 0 || right.length === 0) return false;
+ const leftIds = new Set(left.map((message) => message.id));
+ return right.some((message) => leftIds.has(message.id));
+};
+
+const RECONCILE_METADATA_KEYS = [
+ 'source_kind',
+ 'source_actor',
+ 'vault_request_type',
+ 'vault_request_status',
+] as const;
+
+function mergeReconcileMetadata(
+ existing: WorkbenchMessage,
+ incoming: WorkbenchMessage,
+): WorkbenchMessage {
+ const existingMetadata = existing.metadata ?? {};
+ const incomingMetadata = incoming.metadata ?? {};
+ const metadata = { ...existingMetadata };
+ let changed = false;
+ for (const key of RECONCILE_METADATA_KEYS) {
+ const value = incomingMetadata[key];
+ if (value !== undefined && value !== null && value !== existingMetadata[key]) {
+ metadata[key] = value;
+ changed = true;
+ }
+ }
+ return changed ? { ...existing, metadata } : existing;
+}
+
+/** Merge a fetched anchor window without trimming away the row it is meant to reveal. */
+export const mergeAnchorWindow = (
+ existing: WorkbenchMessage[],
+ incoming: WorkbenchMessage[],
+ anchorMessageId: string,
+ maxMessages: number,
+ followingTail: boolean,
+): { messages: WorkbenchMessage[]; replaced: boolean; detachedTail: boolean; trimmedOldest: boolean } => {
+ const merged = mergeById(existing, incoming);
+ if (merged.length <= maxMessages) {
+ return { messages: merged, replaced: false, detachedTail: false, trimmedOldest: false };
+ }
+
+ const retained = followingTail ? merged.slice(-maxMessages) : merged.slice(0, maxMessages);
+ const detachedTail = !followingTail;
+ if (retained.some((message) => message.id === anchorMessageId)) {
+ return { messages: retained, replaced: false, detachedTail, trimmedOldest: followingTail };
+ }
+ // The capped union would discard the owning reply. Keep the coherent centered
+ // response instead; the caller marks it historical and can scroll to the anchor.
+ return { messages: incoming, replaced: true, detachedTail, trimmedOldest: false };
+};
+
// Union two row sets, deduped by id and re-sorted into durable order. Used by the
// BATCH paths (initial snapshot, reconcile, older-page load), so a fast agent
// result that arrives over /api/events *before* its prompt row still lands in the
@@ -85,9 +143,13 @@ export const mergeById = (
inc &&
((m.source_session_id == null && inc.source_session_id != null) ||
(m.author_name == null && inc.author_name != null) ||
- (m.author_id == null && inc.author_id != null))
+ (m.author_id == null && inc.author_id != null) ||
+ RECONCILE_METADATA_KEYS.some((key) => {
+ const value = inc.metadata?.[key];
+ return value !== undefined && value !== null && value !== m.metadata?.[key];
+ }))
) {
- return {
+ const patchedMessage = {
...m,
...(m.source_session_id == null && inc.source_session_id != null
? {
@@ -99,6 +161,7 @@ export const mergeById = (
...(m.author_name == null && inc.author_name != null ? { author_name: inc.author_name } : {}),
...(m.author_id == null && inc.author_id != null ? { author_id: inc.author_id } : {}),
};
+ return mergeReconcileMetadata(patchedMessage, inc);
}
return m;
});
diff --git a/ui/src/lib/vaultRequestPlacement.test.ts b/ui/src/lib/vaultRequestPlacement.test.ts
index 8c78af2f2..ec8012cfe 100644
--- a/ui/src/lib/vaultRequestPlacement.test.ts
+++ b/ui/src/lib/vaultRequestPlacement.test.ts
@@ -7,7 +7,12 @@ import {
vaultRequestType,
} from './vaultRequestPlacement';
-const message = (id: string, createdAt: string, author = 'agent'): WorkbenchMessage => ({
+const message = (
+ id: string,
+ createdAt: string,
+ author = 'agent',
+ deliveredAt: string | null = null,
+): WorkbenchMessage => ({
id,
scope_id: null,
session_id: 'ses_test',
@@ -24,7 +29,7 @@ const message = (id: string, createdAt: string, author = 'agent'): WorkbenchMess
metadata: {},
created_at: createdAt,
updated_at: createdAt,
- delivered_at: null,
+ delivered_at: deliveredAt,
read_at: null,
});
@@ -96,6 +101,16 @@ describe('placeVaultProvisionRequests', () => {
expect(placed.unanchored).toEqual([]);
});
+ it('keeps an unresolved explicit reply id unanchored', () => {
+ const placed = placeVaultProvisionRequests(
+ [message('unrelated-reply', '2026-07-30T10:01:00Z')],
+ [request('missing-reply', 'provision', '2026-07-30T10:00:00Z', 'trimmed-reply')],
+ );
+
+ expect(placed.byMessageId).toEqual(new Map());
+ expect(placed.unanchored.map((item) => item.id)).toEqual(['missing-reply']);
+ });
+
it('anchors legacy requests to the first Agent reply after creation', () => {
const placed = placeVaultProvisionRequests(
messages,
@@ -159,6 +174,143 @@ describe('placeVaultProvisionRequests', () => {
expect(placed.byMessageId.has('agent-owner')).toBe(false);
});
+ it('uses the requester input message when the request was persisted after its reply', () => {
+ const source = message('source-user', '2026-07-30T10:00:00Z', 'user');
+ const reply = message('owner-reply', '2026-07-30T10:01:00Z', 'agent');
+ const placed = placeVaultProvisionRequests(
+ [source, reply],
+ [request('late', 'provision', '2026-07-30T10:02:00Z', null, { message_id: source.id })],
+ );
+
+ expect(placed.byMessageId.get(reply.id)?.map((item) => item.id)).toEqual(['late']);
+ expect(placed.unanchored).toEqual([]);
+ });
+
+ it('resolves a native requester message id to its durable transcript row', () => {
+ const source = { ...message('source-user', '2026-07-30T10:00:00Z', 'user'), native_message_id: 'slack-source' };
+ const reply = message('owner-reply', '2026-07-30T10:01:00Z', 'agent');
+ const placed = placeVaultProvisionRequests(
+ [source, reply],
+ [request('native-late', 'provision', '2026-07-30T10:02:00Z', null, { message_id: 'slack-source' })],
+ );
+
+ expect(placed.byMessageId.get(reply.id)?.map((item) => item.id)).toEqual(['native-late']);
+ expect(placed.unanchored).toEqual([]);
+ });
+
+ it('scopes native requester matching to the originating platform', () => {
+ const webSource = {
+ ...message('web-source', '2026-07-30T10:00:00Z', 'user'),
+ platform: 'web',
+ native_message_id: 'shared-source',
+ };
+ const webReply = { ...message('web-reply', '2026-07-30T10:01:00Z'), platform: 'web' };
+ const slackSource = {
+ ...message('slack-source', '2026-07-30T10:02:00Z', 'user'),
+ platform: 'slack',
+ native_message_id: 'shared-source',
+ };
+ const slackReply = { ...message('slack-reply', '2026-07-30T10:03:00Z'), platform: 'slack' };
+ const placed = placeVaultProvisionRequests(
+ [webSource, webReply, slackSource, slackReply],
+ [request('native-platform', 'provision', '2026-07-30T10:04:00Z', null, {
+ message_id: 'shared-source',
+ platform: 'slack',
+ })],
+ );
+
+ expect(placed.byMessageId.get(slackReply.id)?.map((item) => item.id)).toEqual(['native-platform']);
+ expect(placed.byMessageId.has(webReply.id)).toBe(false);
+ expect(placed.unanchored).toEqual([]);
+ });
+
+ it('uses a resolved durable source override for stable turn identities', () => {
+ const source = message('source-user', '2026-07-30T10:00:00Z', 'user');
+ const reply = message('owner-reply', '2026-07-30T10:01:00Z', 'agent');
+ const placed = placeVaultProvisionRequests(
+ [source, reply],
+ [request('turn-late', 'provision', '2026-07-30T10:02:00Z', null, { turn_id: 'turn-owner' })],
+ new Map([['turn-late', source.id]]),
+ );
+
+ expect(placed.byMessageId.get(reply.id)?.map((item) => item.id)).toEqual(['turn-late']);
+ expect(placed.unanchored).toEqual([]);
+ });
+
+ it('does not cross a later input when resolving from the requester message', () => {
+ const source = message('source-user', '2026-07-30T10:00:00Z', 'user');
+ const boundary = message('later-user', '2026-07-30T10:01:00Z', 'user');
+ const reply = message('unrelated-reply', '2026-07-30T10:02:00Z', 'agent');
+ const placed = placeVaultProvisionRequests(
+ [source, boundary, reply],
+ [request('late', 'provision', '2026-07-30T10:03:00Z', null, { message_id: source.id })],
+ );
+
+ expect([...placed.byMessageId]).toEqual([]);
+ expect(placed.unanchored.map((item) => item.id)).toEqual(['late']);
+ });
+
+ it('does not timestamp-place an unresolved explicit source onto another turn', () => {
+ const unrelatedReply = message('unrelated-reply', '2026-07-30T10:02:00Z', 'agent');
+ const placed = placeVaultProvisionRequests(
+ [unrelatedReply],
+ [request('missing-source', 'provision', '2026-07-30T10:01:00Z', null, { message_id: 'trimmed-source' })],
+ );
+
+ expect([...placed.byMessageId]).toEqual([]);
+ expect(placed.unanchored.map((item) => item.id)).toEqual(['missing-source']);
+ });
+
+ it('keeps a delayed reply when the next input arrives after request creation', () => {
+ const source = message('source-user', '2026-07-30T10:00:00Z', 'user');
+ const reply = message('owner-reply', '2026-07-30T10:01:00Z', 'agent');
+ const laterUser = message('later-user', '2026-07-30T10:03:00Z', 'user');
+ const unrelatedReply = message('unrelated-reply', '2026-07-30T10:04:00Z', 'agent');
+ const placed = placeVaultProvisionRequests(
+ [source, reply, laterUser, unrelatedReply],
+ [request('late', 'provision', '2026-07-30T10:02:00Z', null, { message_id: source.id })],
+ );
+
+ expect(placed.byMessageId.get(reply.id)?.map((item) => item.id)).toEqual(['late']);
+ expect(placed.byMessageId.has(unrelatedReply.id)).toBe(false);
+ expect(placed.unanchored).toEqual([]);
+ });
+
+ it('uses transcript time for queued source-turn boundaries', () => {
+ const source = message('source-user', '2026-07-30T10:00:00Z', 'user');
+ const ownerReply = message('owner-reply', '2026-07-30T10:00:30Z', 'agent');
+ const queuedInput = message(
+ 'queued-input',
+ '2026-07-30T09:59:00Z',
+ 'user',
+ '2026-07-30T10:02:00Z',
+ );
+ const unrelatedReply = message('unrelated-reply', '2026-07-30T10:03:00Z');
+ const placed = placeVaultProvisionRequests(
+ [source, ownerReply, queuedInput, unrelatedReply],
+ [request('late', 'provision', '2026-07-30T10:01:00Z', null, { message_id: source.id })],
+ );
+
+ expect(placed.byMessageId.get(ownerReply.id)?.map((item) => item.id)).toEqual(['late']);
+ expect(placed.byMessageId.has(unrelatedReply.id)).toBe(false);
+ expect(placed.unanchored).toEqual([]);
+ });
+
+ it('ignores a stale requester message when a later turn owns the request', () => {
+ const source = message('stale-source', '2026-07-30T10:00:00Z', 'user');
+ const oldReply = message('old-reply', '2026-07-30T10:00:10Z', 'agent');
+ const actualSource = message('actual-source', '2026-07-30T10:01:00Z', 'user');
+ const actualReply = message('actual-reply', '2026-07-30T10:02:00Z', 'agent');
+ const placed = placeVaultProvisionRequests(
+ [source, oldReply, actualSource, actualReply],
+ [request('late', 'provision', '2026-07-30T10:01:30Z', null, { message_id: source.id })],
+ );
+
+ expect(placed.byMessageId.get(actualReply.id)?.map((item) => item.id)).toEqual(['late']);
+ expect(placed.byMessageId.has(oldReply.id)).toBe(false);
+ expect(placed.unanchored).toEqual([]);
+ });
+
it('keeps approvals out of message placement and leaves unmatched provisions visible', () => {
const placed = placeVaultProvisionRequests(messages, [
request('approval', 'access', '2026-07-30T10:00:00Z'),
@@ -178,4 +330,21 @@ describe('placeVaultProvisionRequests', () => {
expect([...placed.byMessageId]).toEqual([]);
expect(placed.unanchored.map((item) => item.id)).toEqual(['older']);
});
+
+ it('uses transcript-entry time when a queued row was accepted after the request', () => {
+ const queuedInput = message(
+ 'queued-input',
+ '2026-07-30T09:59:00Z',
+ 'user',
+ '2026-07-30T10:02:00Z',
+ );
+ const unrelatedReply = message('unrelated-reply', '2026-07-30T10:03:00Z');
+ const placed = placeVaultProvisionRequests(
+ [queuedInput, unrelatedReply],
+ [request('trimmed', 'provision', '2026-07-30T10:01:00Z')],
+ );
+
+ expect([...placed.byMessageId]).toEqual([]);
+ expect(placed.unanchored.map((item) => item.id)).toEqual(['trimmed']);
+ });
});
diff --git a/ui/src/lib/vaultRequestPlacement.ts b/ui/src/lib/vaultRequestPlacement.ts
index 3c626fe39..2d4809559 100644
--- a/ui/src/lib/vaultRequestPlacement.ts
+++ b/ui/src/lib/vaultRequestPlacement.ts
@@ -1,7 +1,7 @@
import type { VaultRequest, WorkbenchMessage } from '@/context/ApiContext';
import { chatRowKind } from '@/lib/chatRowKind';
import { specFor } from '@/lib/messageTypes';
-import { messageOrderTimeMs, timestampOrderTimeMs } from '@/lib/transcriptOrder';
+import { messageOrderTimeMs, timestampOrderTimeMs, transcriptOrderTimeMs } from '@/lib/transcriptOrder';
export type VaultRequestType = 'access' | 'sign' | 'provision' | 'other';
@@ -41,6 +41,31 @@ function record(value: unknown): Record<string, unknown> {
: {};
}
+/** The transcript message that started the turn which created a request. */
+export function vaultRequestSourceMessageId(request: VaultRequest): string | null {
+ const requester = record(request.requester);
+ const messageId = requester.message_id;
+ return typeof messageId === 'string' && messageId.trim() ? messageId : null;
+}
+
+export function vaultRequestSourceTurnId(request: VaultRequest): string | null {
+ const requester = record(request.requester);
+ const turnId = requester.turn_id;
+ return typeof turnId === 'string' && turnId.trim() ? turnId : null;
+}
+
+export function vaultRequestSourceRunId(request: VaultRequest): string | null {
+ const requester = record(request.requester);
+ const runId = requester.run_id;
+ return typeof runId === 'string' && runId.trim() ? runId : null;
+}
+
+export function vaultRequestSourcePlatform(request: VaultRequest): string | null {
+ const requester = record(request.requester);
+ const platform = requester.platform;
+ return typeof platform === 'string' && platform.trim() ? platform : null;
+}
+
function sameRequestTurn(request: VaultRequest, message: WorkbenchMessage): boolean {
const requester = record(request.requester);
const metadata = record(message.metadata);
@@ -66,6 +91,42 @@ function inferReplyWithinTurn(
return undefined;
}
+function inferReplyFromSourceMessage(
+ messages: WorkbenchMessage[],
+ sourceMessageId: string,
+ requestTime: number,
+ sourcePlatform: string | null,
+): WorkbenchMessage | undefined {
+ const sourceIndex = messages.findIndex(
+ (message) => message.id === sourceMessageId || (
+ message.native_message_id === sourceMessageId &&
+ (!sourcePlatform || message.platform === sourcePlatform)
+ ),
+ );
+ if (sourceIndex < 0) return undefined;
+ let replyBeforeRequest: WorkbenchMessage | undefined;
+
+ for (const message of messages.slice(sourceIndex + 1)) {
+ if (isInputTurn(message)) {
+ // A request may be persisted after its reply but before the next input.
+ // In that case the recorded pre-request reply is still the owner. Only
+ // discard the source identity when the later input predates the request.
+ const messageTime = transcriptOrderTimeMs(message);
+ return replyBeforeRequest && !Number.isNaN(requestTime) &&
+ !Number.isNaN(messageTime) && messageTime >= requestTime
+ ? replyBeforeRequest
+ : undefined;
+ }
+ if (!isAgentReply(message)) continue;
+ if (Number.isNaN(requestTime) || messageOrderTimeMs(message) >= requestTime) return message;
+ // Some legacy request rows point at an older input even though the request
+ // was persisted after that turn's reply. Keep it as a fallback only when
+ // the source turn never crosses another input boundary.
+ replyBeforeRequest ??= message;
+ }
+ return replyBeforeRequest;
+}
+
/** Attach provision requests to the Agent reply that announced them.
*
* Newer producers can set `message_id` explicitly. Historical CLI-created rows
@@ -76,31 +137,58 @@ function inferReplyWithinTurn(
export function placeVaultProvisionRequests(
messages: WorkbenchMessage[],
requests: VaultRequest[],
+ sourceMessageIds: ReadonlyMap<string, string> = new Map(),
): VaultProvisionPlacement {
const byMessageId = new Map<string, VaultRequest[]>();
const unanchored: VaultRequest[] = [];
const messagesById = new Map(messages.map((message) => [message.id, message]));
const agentMessages = messages.filter(isAgentReply);
- const firstLoadedTime = messages.length > 0 ? messageOrderTimeMs(messages[0]) : Number.NaN;
+ // Window coverage follows transcript-entry order. A queued row can be authored
+ // before the request but only enter the visible transcript after it, so its
+ // message-id clock must not make a trimmed request look loaded.
+ const firstLoadedTime = messages.length > 0 ? transcriptOrderTimeMs(messages[0]) : Number.NaN;
for (const request of requests) {
if (vaultRequestType(request) !== 'provision') continue;
- const explicit = request.message_id ? messagesById.get(request.message_id) : undefined;
+ const explicitReplyId = typeof request.message_id === 'string' && request.message_id.trim()
+ ? request.message_id
+ : null;
+ const explicit = explicitReplyId ? messagesById.get(explicitReplyId) : undefined;
if (explicit && isAgentReply(explicit)) {
appendRequest(byMessageId, explicit.id, request);
continue;
}
+ const explicitReplyUnresolved = Boolean(explicitReplyId && (!explicit || !isAgentReply(explicit)));
const requestTime = timestampOrderTimeMs(request.created_at);
const sameTurn = agentMessages.find((message) => sameRequestTurn(request, message));
+ // The request row can be written after the Agent reply has already been
+ // persisted, so its creation timestamp is not a reliable turn boundary.
+ // Newer requesters carry the input message id; use that identity first.
+ const explicitSource = vaultRequestSourceMessageId(request);
+ const fromSource = explicitSource ?? sourceMessageIds.get(request.id) ?? null;
+ const sourcePlatform = vaultRequestSourcePlatform(request);
+ const sourceResolved = Boolean(fromSource && messages.some(
+ (message) => message.id === fromSource || (
+ message.native_message_id === fromSource &&
+ (!sourcePlatform || message.platform === sourcePlatform)
+ ),
+ ));
+ const sourceUnresolved = Boolean(explicitSource && !sourceResolved);
// Do not guess when the request predates the retained message window: its
// real owner may have been trimmed, and attaching it to the first visible
// later reply would move the card to an unrelated turn.
const windowCoversRequest = Number.isNaN(firstLoadedTime) || firstLoadedTime <= requestTime;
- const inferred = sameTurn ?? (Number.isNaN(requestTime) || !windowCoversRequest
+ const fromSourceReply = fromSource
+ ? inferReplyFromSourceMessage(messages, fromSource, requestTime, sourcePlatform)
+ : undefined;
+ const inferred = explicitReplyUnresolved
? undefined
- : inferReplyWithinTurn(messages, requestTime));
+ : sameTurn ?? fromSourceReply
+ ?? (sourceUnresolved || Number.isNaN(requestTime) || !windowCoversRequest
+ ? undefined
+ : inferReplyWithinTurn(messages, requestTime));
if (inferred) appendRequest(byMessageId, inferred.id, request);
else unanchored.push(request);
}
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 1ebfe770b..777629d7b 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -7207,6 +7207,12 @@ def sessions_messages_list(session_id: str):
# ``around_id`` centers the window on a specific message (search deep-link
# jump); it takes precedence over after/before/tail in the service.
around_id = request.args.get("around_id") or None
+ # Legacy IM caller contexts may carry only the platform-native message id;
+ # storage resolves it to the durable row before applying cursor pagination.
+ around_native_id = request.args.get("around_native_id") or None
+ around_native_platform = request.args.get("around_native_platform") or None
+ around_turn_id = request.args.get("around_turn_id") or None
+ around_run_id = request.args.get("around_run_id") or None
# ``tail=1`` returns the most-recent window (for the Chat page's gap recovery)
# instead of the oldest page.
tail = request.args.get("tail") == "1"
@@ -7228,6 +7234,10 @@ def sessions_messages_list(session_id: str):
after_id=after_id,
before_id=before_id,
around_id=around_id,
+ around_native_id=around_native_id,
+ around_native_platform=around_native_platform,
+ around_turn_id=around_turn_id,
+ around_run_id=around_run_id,
limit=limit,
types=messages_service.TRANSCRIPT_TYPES,
tail=tail,