Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(vault): keep waiter outcomes out of reply settlement
Call Whiteaefad9489193
diff --git a/core/message_mirror.py b/core/message_mirror.pyindex dcf53fc15..4e34a936c 100644--- a/core/message_mirror.py+++ b/core/message_mirror.py@@ -585,12 +585,19 @@ def agent_message_exists(return None-def mirror_harness_inbound(context: MessageContext, text: str) -> None:+def mirror_harness_inbound(+ context: MessageContext,+ text: str,+ *,+ message_type: str = messages_service.HARNESS_TYPE,+) -> bool:"""Record a harness-originated prompt (scheduled task / watch / webhook).- The backend consumes the prompt as turn input, but the persisted row must- not claim the human authored it. ``author`` and ``type`` therefore use the- first-class harness role while ``source='harness'`` preserves provenance.+ The backend consumes the prompt as turn input for the default harness type,+ but the persisted row must not claim the human authored it. ``author``+ therefore uses the first-class harness role while ``source='harness'``+ preserves provenance. Callers that only need a transcript notification can+ provide a non-input catalog type such as ``notify`` or ``vault``.``author_name`` carries the trigger kind (scheduled / watch / webhook / ...)and ``author_id`` the run-definition id, per the provenance spec.@@ -601,9 +608,9 @@ def mirror_harness_inbound(context: MessageContext, text: str) -> None:scope, IM rows to the delivery channel."""if not text or not text.strip():- return+ return Falseif not context.platform:- return+ return Falsespec = context.platform_specific or {}trigger_kind = spec.get("task_trigger_kind")definition_id = spec.get("task_definition_id")@@ -651,7 +658,7 @@ def mirror_harness_inbound(context: MessageContext, text: str) -> None:row_session_id = session_idsession_row = Noneif scope_id is None and session_row is None:- return+ return Falseappended_row = _append_quietly(conn,scope_id=scope_id,@@ -661,7 +668,7 @@ def mirror_harness_inbound(context: MessageContext, text: str) -> None:source="harness",author_name=trigger_kind,author_id=definition_id,- message_type=messages_service.HARNESS_TYPE,+ message_type=message_type,text=text,metadata=provenance_metadata,native_message_id=context.message_id,@@ -681,8 +688,51 @@ def mirror_harness_inbound(context: MessageContext, text: str) -> None:from core.inbox_events import busbus.publish("inbox.session.updated", inbox_row)+ return Trueexcept Exception:logger.exception("mirror_harness_inbound: unexpected failure on platform=%s", context.platform)+ return False+++def mirror_vault_waiter_outcome(+ *,+ session_id: str,+ request_id: str,+ request_type: str,+ request_status: str,+ message: str,+) -> bool:+ """Persist a Vault result already consumed by a synchronous CLI waiter.++ The waiting Agent turn receives the result from the CLI command itself, so starting a callback+ turn would deliver it twice. The transcript still needs the same first-class Vault provenance+ as an asynchronous callback. A stable native identity makes the mirror idempotent if callback+ bookkeeping is retried after the message commit.+ """++ identity = str(session_id or "").strip()+ vault_request_id = str(request_id or "").strip()+ status = str(request_status or "").strip()+ if not identity or not vault_request_id or not status:+ return False+ return mirror_harness_inbound(+ MessageContext(+ user_id="vault",+ channel_id=identity,+ platform="avibe",+ message_id=f"vault:{vault_request_id}:{status}:waiter",+ platform_specific={+ "agent_session_id": identity,+ "task_trigger_kind": "vault",+ "source_kind": "callback",+ "source_actor": f"vault:{vault_request_id}",+ "vault_request_type": str(request_type or ""),+ "vault_request_status": status,+ },+ ),+ message,+ message_type=messages_service.VAULT_TYPE,+ )def mirror_inbound(context: MessageContext, text: str) -> None:diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.pyindex 53c71a6b9..65c238849 100644--- a/core/scheduled_tasks.py+++ b/core/scheduled_tasks.py@@ -7039,11 +7039,10 @@ class ScheduledTaskService:"""Auto-resume the requesting session when a vault request reaches a terminal state.Mirrors :meth:`_drain_callbacks` but for ``vault_requests`` (which resolve outside the run- store): each row marked ``callback_status='pending'`` is turned into one callback turn via- the shared :func:`enqueue_session_callback` entry, then marked ``sent``/``skipped``/- ``failed``. Delivery is at-least-once, matching the run-store callback drain: enqueue and- the ``sent`` mark are separate writes, so a crash between them re-sends on the next tick.- Per-row isolation keeps one bad row from aborting the batch or being retried forever.+ store). Pending rows use the same processor as the runtime-work lane, so callbacks either+ enqueue one turn or mirror a completed waiter's outcome directly into the transcript before+ being marked ``sent``/``skipped``/``failed``. Delivery is at-least-once; enqueue or mirror+ and the ``sent`` mark are separate writes, with stable identities closing duplicate windows."""if not self._owns_service_instance():return@@ -7063,44 +7062,9 @@ class ScheduledTaskService:logger.error("Vault request callback sweep failed to load: %s", exc, exc_info=True)returnfor row in pending:- request_id = str(row.get("id") or "")- if not request_id:- continue- # Resolve + enqueue as one guarded step so a bad row is marked (not left to retry- # forever) and does not abort the rest of the batch.- status = "skipped"- try:- with engine.begin() as conn:- ready = vault_service.request_callback_ready(conn, row)- if not ready:- # Approved access grant not delivery-ready yet (protected relay in flight);- # leave callback_status='pending' and retry on a later tick.- continue- plan = vault_service.resolve_request_callback(row)- if plan is not None:- enqueue_session_callback(- self.request_store,- 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:- status = "skipped" # session archived / not a valid target — nothing to resume- except Exception as exc:- logger.error("Vault request callback failed for %s: %s", request_id, exc, exc_info=True)- status = "failed"- try:- with engine.begin() as conn:- vault_service.mark_request_callback(conn, request_id, status=status)- except Exception as exc:- # Leave callback_status='pending' → retried next tick (bounded, transient).- logger.error("Vault request callback mark failed for %s: %s", request_id, exc, exc_info=True)- continue+ # Keep the legacy drain aligned with the runtime-work processor, including completed+ # waiter outcomes that belong in the transcript without starting another Agent turn.+ status = self._process_vault_callback_sync(row)if status == "sent":# A callback run was enqueued into the run store; drain it promptly.self._wake_runtime_work(RuntimeWorkLane.REQUESTS)@@ -7177,16 +7141,35 @@ class ScheduledTaskService:return "pending"plan = vault_service.resolve_request_callback(row)if plan is not None:- enqueue_session_callback(- self.request_store,- 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 ""),- },- )+ request_type = str(row.get("request_type") or "")+ request_status = str(row.get("status") or "")+ if vault_service.request_callback_consumed_by_waiter(row):+ from core.message_mirror import mirror_vault_waiter_outcome++ mirrored = mirror_vault_waiter_outcome(+ session_id=plan.session_id,+ request_id=request_id,+ request_type=request_type,+ request_status=request_status,+ message=plan.message,+ )+ if not mirrored:+ # The stable native message id makes this mirror safe to retry. Keep the+ # callback pending so a transient SQLite/dispatch failure is retried by+ # the next sweep instead of losing the waiter's transcript outcome.+ logger.warning("failed to persist Vault waiter outcome for %s; will retry", request_id)+ return "pending"+ else:+ enqueue_session_callback(+ self.request_store,+ session_id=plan.session_id,+ message=plan.message,+ source_actor=f"vault:{request_id}",+ metadata={+ "vault_request_type": request_type,+ "vault_request_status": request_status,+ },+ )status = "sent"except ValueError:status = "skipped"diff --git a/docs/plans/vault-sandbox-protocol-v2.md b/docs/plans/vault-sandbox-protocol-v2.mdindex 153cc32fe..bf31a6862 100644--- a/docs/plans/vault-sandbox-protocol-v2.md+++ b/docs/plans/vault-sandbox-protocol-v2.md@@ -40,9 +40,11 @@ All paths verified in code on 2026-07-09 (avibe `27e2a1b5`, vault-sandbox### Interaction cost today-"Confirm" = a click inside the sandbox iframe card. "Passkey" = a full OS-biometric/PIN prompt (`navigator.credentials.get()`); PRF-unlock and UV-confirm-prompts are indistinguishable to the user.+"Confirm" = a click inside the top-level sandbox authorization window. The+embedded sandbox card is a launcher only; it never acts as the authorization+surface. "Passkey" = a full OS biometric/PIN prompt+(`navigator.credentials.get()`); PRF-unlock and UV-confirm prompts are+indistinguishable to the user.| Flow | Unlocked (within 10-min window) | Locked || --- | --- | --- |@@ -77,8 +79,9 @@ Key code facts:(`VAULT_AUTO_LOCK_MS`, own `setTimeout`, re-armed on `sealValue`) and sandbox`vaultLifecycle.ts:17` (re-armed on `withUnlockedVmk`). The parent reconcilesby polling `status` after operations.-- `unseal` is fully implemented in the sandbox (confirm + passkey + in-sandbox- display/clipboard) and wrapped in `vaultSandboxClient.ts`, but **no parent+- `unseal` is fully implemented in the sandbox (top-level confirm + passkey,+ with display/clipboard kept in the sandbox) and wrapped in+ `vaultSandboxClient.ts`, but **no parentcomponent calls it**.- The sandbox confirm card for `releaseDEK` shows `grantId`, `requestId`,`expiresAt` — raw IDs (`main.ts:943`). The parent approval card shows command,@@ -130,8 +133,9 @@ root of the "unlocked but still prompted every time" experience.- **G1 — One passkey per human intent.** A batch approval is one intent. Anapproval inside a freshly authorized session is one intent already paid for.-- **G2 — The sandbox is *the* authorization surface.** It renders- daemon-endorsed context, in human language, for every consent it collects.+- **G2 — The top-level sandbox is *the* authorization surface.** It renders+ daemon-endorsed context, in human language, for every consent it collects;+ an embedded card only launches that surface.- **G3 — One clock.** The sandbox owns time; the parent renders events.- **G4 — Explicit risk tiers.** Silent / confirm / passkey-always are productdecisions per operation class, configurable where it matters.@@ -149,11 +153,12 @@ root of the "unlocked but still prompted every time" experience.Unlocking is redefined from "VMK becomes available" to "the user grants an**authorization session**": for the next W minutes (default 10, configurable),-operations at or below the *confirm* tier proceed with in-sandbox confirmation-only — no repeated passkey. The unlock ceremony card states exactly that:+operations at or below the *confirm* tier proceed with confirmation in the+top-level sandbox window only — no repeated passkey. The unlock ceremony card+states exactly that:-> Unlock your vault for ~10 minutes. While unlocked, approvals ask for an-> in-sandbox confirmation instead of your passkey. Signing always requires+> Unlock your vault for ~10 minutes. While unlocked, approvals ask for a+> confirmation in the top-level sandbox window instead of your passkey. Signing always requires> your passkey.This turns the existing countdown pill from a lie into the truth.@@ -163,7 +168,7 @@ This turns the existing countdown pill from a lie into the truth.| Tier | Operations | Unlocked (in session) | Locked || --- | --- | --- | --- || **R1 — self custody** | `seal` (create), `status`, `lock` | silent | first op unlocks: 1 passkey |-| **R2 — delegated read** | `approveRelease` (DEK release, incl. batch), `reveal` (display/copy) | **in-sandbox confirm, no passkey** | confirm + 1 passkey (unlock-on-approve, starts session) |+| **R2 — delegated read** | `approveRelease` (DEK release, incl. batch), `reveal` (display/copy) | **top-level sandbox confirm, no passkey** | confirm + 1 passkey (unlock-on-approve, starts session) || **R3 — signing** | `sign` | confirm + **passkey UV, always** | confirm + passkey (PRF; unlocks + authorizes in one prompt) |Sliding renewal stays: any successful R1/R2 operation re-arms the window@@ -174,7 +179,7 @@ currently unused by delete per #833).### 5.3 Why R2 without per-op passkey is sound-What does the per-op UV prompt actually add on top of an in-sandbox confirm?+What does the per-op UV prompt actually add on top of a top-level sandbox confirm?- **It does not add content binding for the user.** The OS prompt shows the RPname, not the operation. The user reads the operation from the sandbox card@@ -326,40 +331,28 @@ display-only).### 6.6 Confirm-surface hardening (prerequisite for R2)-Before any R2/R3 confirm the sandbox verifies its own presentation:-document visible + focused, frame ≥ minimum size, IntersectionObserver-reports ≥ 0.99 visible (v2 `trackVisibility` occlusion detection where the-engine supports it), no pending `ui.show` unacknowledged. Confirm buttons are-dead for the first ~500 ms after render (anti-timing-redress) and may use-hold-to-confirm for release/reveal. Otherwise fail closed with-`sandbox_not_visible` (parent responds by expanding the modal and retrying).-Note the shape of the residual: an XSS with **no user-present** can complete nothing (every R2/R3 needs a real gesture inside the-sandbox document); the residual is exclusively "user present and redressed",-bounded by these checks and by Strict mode.--**Parent surface attestation is advisory telemetry, not an enforced gate.**-While an embedded confirm is up, the parent measures the sandbox iframe-element (rect, own IntersectionObserver reading, computed opacity and-pointer-events) and streams it as per-request `surface` plus `confirm.surface`-events refreshed every ~10 s (wire shape frozen by the parent's-`buildVaultConfirmSurface` unit test and the sandbox's-`parseParentConfirmSurface`). The sandbox records it and logs anomalies but-never fails a ceremony on it, for two reasons. First, it is self-reported by-the very party the sandbox distrusts: a compromised parent fabricates a-perfect reading, so enforcing it adds nothing against the adversary it-targets (overlay redress requires a compromised parent, which lies). Second,-honest parents fail it persistently: IntersectionObserver v2 `trackVisibility`-reports occlusion whenever any ancestor carries a transform, filter, opacity-transition, or animation — ordinary modal CSS. Enforcement therefore only-taxes legitimate users. The browser-truth self-checks above remain the-enforced gate.+R2/R3 authorization is performed in a dedicated top-level sandbox window. The+embedded sandbox only renders a visible launcher and cannot authorize an+operation from its iframe-local hit tests or from a parent-supplied visibility+claim. Each request opens a unique popup window whose URL contains only the+random request id and appearance settings. After the popup signals readiness,+the opener transfers the signed prompt and encrypted wrap metadata through a+same-origin, id-gated `postMessage` handshake; approval metadata is never put+in the URL. The popup validates the opener origin and window source, renders+the confirmation, performs any WebAuthn ceremony, and returns a typed result+through the same channel. The opener applies a five-minute timeout and a+short close grace period for queued mobile-browser messages.++The old iframe visibility and parent-attestation checks remain telemetry-only+compatibility signals while the top-level window is open. The security boundary+is the browser-rendered top-level sandbox page, not the embedder's DOM.## 7. Flow redesigns### 7.1 Approvals (access)-Parent: one click (Approve) on the request card. Parent fetches **one** batch+Parent: one click (Approve) on the request card launches a top-level sandbox+authorization window. Parent fetches **one** batchof signed contexts (`POST /vault/agent-bindings:batch` with the request id;daemon returns per-secret bindings sharing one display block), sends one`approveRelease`. Sandbox: one card — title, session label, command, egress,@@ -425,9 +418,9 @@ triggered from the create form (`setup` immediately continues into the pending### 7.4 RevealSecret detail (protected static) gains "Show value / Copy value" actions-calling `reveal`. R2: confirm in-sandbox, plaintext rendered inside the-sandbox frame only. This closes the orphaned-`unseal` gap with the-already-implemented sandbox surface.+calling `reveal`. R2: confirm in the top-level sandbox authorization window;+after approval, plaintext is rendered inside the sandbox iframe only. This+closes the orphaned-`unseal` gap without moving plaintext into the parent.**Copy-mode caveat**: the system clipboard is a shared resource — once thesandbox writes plaintext there, the parent origin (and any XSS in it) can read@@ -463,7 +456,7 @@ Two user-facing concepts, named apart everywhere (i18n keys, cards, docs):Settings (Vault settings section, daemon-persisted, §6.5): unlock window5/10/30 min (default 10); Strict approvals toggle (default off; on = today's-passkey-per-operation for R2); both enforced in-sandbox. The daemon also+passkey-per-operation for R2); both enforced by the top-level sandbox. The daemon alsoremembers the approver's last grant-duration choice (§7.1) — a storedpreference, not a sandbox-enforced policy.diff --git a/storage/alembic/versions/20260809_0049_vault_message_type.py b/storage/alembic/versions/20260809_0049_vault_message_type.pynew file mode 100644index 000000000..0fb38b316--- /dev/null+++ b/storage/alembic/versions/20260809_0049_vault_message_type.py@@ -0,0 +1,103 @@+"""Index transcript-visible Vault waiter outcomes without settling inbox replies.++Revision ID: 20260809_0049+Revises: 20260808_0048+Create Date: 2026-08-09+"""++from __future__ import annotations++from alembic import op++revision = "20260809_0049"+down_revision = "20260808_0048"+branch_labels = None+depends_on = None++_ORDER_EXPR = "coalesce(delivered_at, created_at)"++UPGRADE_ACTIVITY_PREDICATE = (+ "session_id is not null and type in "+ "('user', 'harness', 'agent_initiated', 'annotation', 'output', "+ "'result', 'notify', 'vault', 'error', 'assistant')"+)+DOWNGRADE_ACTIVITY_PREDICATE = (+ "session_id is not null and type in "+ "('user', 'harness', 'agent_initiated', 'annotation', 'output', "+ "'result', 'notify', 'error', 'assistant')"+)+UPGRADE_USER_SEND_PREDICATE = (+ "session_id is not null and ((author = 'user' and type = 'user') "+ "or (author = 'harness' and type = 'harness') "+ "or (author = 'harness' and type = 'agent_initiated') "+ "or (author = 'harness' and type = 'annotation'))"+)+DOWNGRADE_USER_SEND_PREDICATE = UPGRADE_USER_SEND_PREDICATE+UPGRADE_AGENT_REPLY_PREDICATE = (+ "session_id is not null and type in ('output', 'result', 'notify', 'vault', 'error')"+)+DOWNGRADE_AGENT_REPLY_PREDICATE = (+ "session_id is not null and type in ('output', 'result', 'notify', 'error')"+)+_LEGACY_WAITER_PREDICATE = (+ "type = 'notify' and json_valid(metadata_json) = 1 "+ "and json_extract(metadata_json, '$.source_kind') = 'callback' "+ "and json_extract(metadata_json, '$.source_actor') like 'vault:%'"+)+_VAULT_WAITER_PREDICATE = _LEGACY_WAITER_PREDICATE.replace("type = 'notify'", "type = 'vault'")+++def _replace_indexes(+ *,+ activity_predicate: str,+ agent_reply_predicate: str,+ user_send_predicate: str,+) -> None:+ bind = op.get_bind()+ for name in (+ "ix_messages_inbox_activity",+ "ix_messages_inbox_agent_reply",+ "ix_messages_inbox_user_send",+ ):+ bind.exec_driver_sql(f"drop index if exists {name}")+ bind.exec_driver_sql(+ "create index ix_messages_inbox_activity "+ f"on messages (platform, session_id, {_ORDER_EXPR} desc, id desc) "+ f"where {activity_predicate}"+ )+ bind.exec_driver_sql(+ "create index ix_messages_inbox_agent_reply "+ f"on messages (platform, session_id, {_ORDER_EXPR} desc, id desc) "+ f"where {agent_reply_predicate}"+ )+ bind.exec_driver_sql(+ "create index ix_messages_inbox_user_send "+ f"on messages (platform, session_id, {_ORDER_EXPR} desc, id desc) "+ f"where {user_send_predicate}"+ )+++def upgrade() -> None:+ bind = op.get_bind()+ bind.exec_driver_sql(+ "update messages set type = 'vault' where "+ f"{_LEGACY_WAITER_PREDICATE}"+ )+ _replace_indexes(+ activity_predicate=UPGRADE_ACTIVITY_PREDICATE,+ agent_reply_predicate=UPGRADE_AGENT_REPLY_PREDICATE,+ user_send_predicate=UPGRADE_USER_SEND_PREDICATE,+ )+++def downgrade() -> None:+ bind = op.get_bind()+ bind.exec_driver_sql(+ "update messages set type = 'notify' where "+ f"{_VAULT_WAITER_PREDICATE}"+ )+ _replace_indexes(+ activity_predicate=DOWNGRADE_ACTIVITY_PREDICATE,+ agent_reply_predicate=DOWNGRADE_AGENT_REPLY_PREDICATE,+ user_send_predicate=DOWNGRADE_USER_SEND_PREDICATE,+ )diff --git a/storage/messages_service.py b/storage/messages_service.pyindex 157664d8a..3bc6a1625 100644--- a/storage/messages_service.py+++ b/storage/messages_service.py@@ -34,7 +34,7 @@ from storage.models import ()from storage.pagination import PageRequest, PageResult, page_result_from_limit_plus_onefrom storage.sessions_service import session_agent_display_label-from vibe.message_identity import HARNESS_TYPE, INPUT_TURN_AUTHOR_TYPES+from vibe.message_identity import HARNESS_TYPE, INPUT_TURN_AUTHOR_TYPES, NOTIFY_TYPE, VAULT_TYPEfrom vibe.message_types import types_withdiff --git a/storage/vault_service.py b/storage/vault_service.pyindex f618df76b..aec707e29 100644--- a/storage/vault_service.py+++ b/storage/vault_service.py@@ -1167,11 +1167,11 @@ def _update_request_waiter(waiter["timed_out_at"] = timed_out_atdelivery_payload["waiter"] = waiter- values: dict[str, Any] = {"delivery": json.dumps(delivery_payload)}- if status == "completed" and row_dict.get("callback_status") == "pending":- values["callback_status"] = "skipped"-- conn.execute(vault_requests.update().where(vault_requests.c.id == request_id).values(**values))+ conn.execute(+ vault_requests.update()+ .where(vault_requests.c.id == request_id)+ .values(delivery=json.dumps(delivery_payload))+ )if status == "completed":_skip_sibling_callbacks_for_completed_waiter(conn, request_id)updated = conn.execute(select(vault_requests).where(vault_requests.c.id == request_id)).mappings().one()@@ -1434,6 +1434,13 @@ def request_callback_ready(conn: Connection, row: dict[str, Any]) -> bool:return True+def request_callback_consumed_by_waiter(row: dict[str, Any]) -> bool:+ """Whether the terminal result already returned through a synchronous CLI waiter."""++ _, delivery = _request_json_payloads(row)+ return str(_request_waiter(delivery).get("status") or "") == "completed"++def expire_overdue_requests(conn: Connection) -> None:"""Flip any overdue pending requests to ``expired`` (arming their callback) proactively.diff --git a/tests/test_message_type_catalog.py b/tests/test_message_type_catalog.pyindex a07fa19b6..90264bdb2 100644--- a/tests/test_message_type_catalog.py+++ b/tests/test_message_type_catalog.py@@ -93,6 +93,7 @@ def test_transcript_types_match_current_constant() -> None:"output","result","notify",+ "vault","error",)assert types_with("transcript") == expected@@ -103,7 +104,7 @@ def test_searchable_types_match_current_default_query() -> None:connection = _CaptureConnection()messages_service.search_messages(connection, query="catalog-probe")- expected = ("user", "harness", "annotation", "output", "result")+ expected = ("user", "harness", "annotation", "output", "result", "vault")assert types_with("searchable") == expectedassert _message_type_sequences(connection.statements[-1]) == {expected}@@ -117,6 +118,7 @@ def test_inbox_activity_types_match_current_constant() -> None:"output","result","notify",+ "vault","error","assistant",)@@ -129,7 +131,7 @@ def test_inbox_preview_and_settlement_types_match_current_query() -> None:messages_service.list_inbox_sessions(connection)current_query_sets = _message_type_sequences(connection.statements[-1])- expected_preview = ("output", "result", "notify", "error")+ expected_preview = ("output", "result", "notify", "vault", "error")expected_settlement = ("result", "notify", "error")expected_unread = ("result",)assert types_with("inboxPreview") == expected_previewdiff --git a/tests/test_message_type_python_consumers.py b/tests/test_message_type_python_consumers.pyindex 64b6d938c..5db5f5535 100644--- a/tests/test_message_type_python_consumers.py+++ b/tests/test_message_type_python_consumers.py@@ -13,6 +13,7 @@ def test_backend_failure_predicate_matches_legacy_type_and_event_pair() -> None:"output","result","notify",+ "vault","error","assistant","tool_call",@@ -59,6 +60,7 @@ def test_fork_activity_sets_match_legacy_values() -> None:"output","result","notify",+ "vault","error",}@@ -73,7 +75,7 @@ def test_show_git_input_message_types_match_legacy_values() -> None:def test_mirror_catalog_roles_match_legacy_type_sets() -> None:- assert set(types_with("inboxPreview")) == {"output", "result", "notify", "error"}+ assert set(types_with("inboxPreview")) == {"output", "result", "notify", "vault", "error"}assert {message_typefor message_type in types_with("activityRole")diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.pyindex b19a877bc..c500bafdb 100644--- a/tests/test_sqlite_state_migration.py+++ b/tests/test_sqlite_state_migration.py@@ -31,15 +31,15 @@ from vibe.message_types import build_partial_index_predicatepytestmark = pytest.mark.no_sqlite_template-HEAD_REVISION = "20260808_0048"+HEAD_REVISION = "20260809_0049"MESSAGE_PARTIAL_INDEX_PREDICATES = {"ix_messages_inbox_activity": ("session_id is not null and type in ""('user', 'harness', 'agent_initiated', 'annotation', 'output', "- "'result', 'notify', 'error', 'assistant')"+ "'result', 'notify', 'vault', 'error', 'assistant')"),"ix_messages_inbox_agent_reply": (- "session_id is not null and type in ('output', 'result', 'notify', 'error')"+ "session_id is not null and type in ('output', 'result', 'notify', 'vault', 'error')"),"ix_messages_inbox_user_send": ("session_id is not null and ((author = 'user' and type = 'user') "@@ -77,9 +77,9 @@ def test_message_partial_index_ddl_matches_catalog_contract()-def test_agent_lifecycle_message_index_migration_matches_catalog() -> None:+def test_message_index_migration_matches_catalog() -> None:migration = import_module(- "storage.alembic.versions.20260808_0048_agent_lifecycle_message_indexes"+ "storage.alembic.versions.20260809_0049_vault_message_type")assert migration.UPGRADE_ACTIVITY_PREDICATE == build_partial_index_predicate(@@ -103,6 +103,22 @@ def test_agent_lifecycle_message_index_migration_upgrades_and_downgrades(previous_activity = _index_sql(conn, "ix_messages_inbox_activity")previous_agent_reply = _index_sql(conn, "ix_messages_inbox_agent_reply")previous_user_send = _index_sql(conn, "ix_messages_inbox_user_send")+ conn.execute(+ "insert into messages "+ "(id, platform, author, type, content_json, metadata_json, created_at, updated_at) "+ "values (?, ?, ?, ?, ?, ?, ?, ?)",+ (+ "legacy-vault-waiter",+ "avibe",+ "harness",+ "notify",+ '{"text":"legacy Vault result"}',+ '{"source_kind":"callback","source_actor":"vault:vrq_legacy"}',+ "2026-08-09T00:00:00.000000Z",+ "2026-08-09T00:00:00.000000Z",+ ),+ )+ conn.commit()run_migrations(db_path)@@ -119,6 +135,9 @@ def test_agent_lifecycle_message_index_migration_upgrades_and_downgrades(assert conn.execute("select version_num from alembic_version").fetchone() == (HEAD_REVISION,)+ assert conn.execute(+ "select type from messages where id = ?", ("legacy-vault-waiter",)+ ).fetchone() == ("vault",)command.downgrade(migrations.alembic_config(db_path), "20260806_0047")@@ -126,6 +145,9 @@ def test_agent_lifecycle_message_index_migration_upgrades_and_downgrades(assert _index_sql(conn, "ix_messages_inbox_activity") == previous_activityassert _index_sql(conn, "ix_messages_inbox_agent_reply") == previous_agent_replyassert _index_sql(conn, "ix_messages_inbox_user_send") == previous_user_send+ assert conn.execute(+ "select type from messages where id = ?", ("legacy-vault-waiter",)+ ).fetchone() == ("notify",)class _Pre335Cursor(sqlite3.Cursor):diff --git a/tests/test_vault_cli.py b/tests/test_vault_cli.pyindex 9dfe65e71..9bf79d39a 100644--- a/tests/test_vault_cli.py+++ b/tests/test_vault_cli.py@@ -1069,7 +1069,7 @@ def test_run_waits_for_protected_approval_then_delivers(tmp_path, capfd, monkeypassert deliver.call_args.kwargs["grant_id"] == approved["grant"]["id"]with cli._open_vault_engine().connect() as conn:row = conn.execute(vault_requests.select().where(vault_requests.c.id == approved["request"]["id"])).mappings().one()- assert row["callback_status"] == "skipped"+ assert row["callback_status"] == "pending"assert json.loads(row["delivery"])["waiter"]["status"] == "completed"diff --git a/tests/test_vault_request_callbacks.py b/tests/test_vault_request_callbacks.pyindex c9c176552..c028109b3 100644--- a/tests/test_vault_request_callbacks.py+++ b/tests/test_vault_request_callbacks.py@@ -1,8 +1,8 @@"""P4: vault-request auto-resume callbacks.-A request transition to a terminal state arms ``callback_status='pending'``; the daemon sweep-turns each armed row into exactly one callback turn to the requesting session via the shared-``enqueue_session_callback`` entry (``source_kind='callback'``), then marks it sent/skipped.+A request transition to a terminal state arms ``callback_status='pending'``. The daemon sweep+starts one callback turn for asynchronous results, or mirrors a transcript-only Vault outcome when+a synchronous CLI waiter already returned the result, then marks the callback sent/skipped."""from __future__ import annotations@@ -13,7 +13,10 @@ from datetime import datetime, timedelta, timezoneimport pytestfrom sqlalchemy import select+from core.message_mirror import mirror_harness_inbound+from modules.im import MessageContextfrom storage import vault_service as vs+from storage import messages_servicefrom storage.db import create_sqlite_enginefrom storage.models import metadata, vault_requestsfrom storage.vault_crypto import Sealed@@ -285,7 +288,7 @@ def test_message_and_session_by_type_status(request_type, status, needle):def test_only_no_callback_disables_auto_resume_at_creation():# Only --no-callback pre-disables. --wait must NOT: a finite wait can time out with the# request still pending, and the agent must still be auto-resumed when it later resolves.- # (A wait that observes fulfillment suppresses the redundant callback at that point instead.)+ # (A provision wait suppresses its callback; access waiters retain a transcript-only outcome.)from types import SimpleNamespacefrom vibe import cli@@ -346,7 +349,7 @@ def test_request_callback_ready_defers_while_cli_waiter_is_active(vault):assert vs.request_callback_ready(conn, row) is True-def test_complete_request_waiter_suppresses_redundant_callback(vault):+def test_complete_request_waiter_keeps_visible_outcome_pending(vault):future = (datetime.now(timezone.utc) + timedelta(minutes=1)).isoformat()with vault.begin() as conn:vs.create_secret(conn, name="DONE_GR_KEY", sealed=_sealed(), protection="protected")@@ -357,8 +360,9 @@ def test_complete_request_waiter_suppresses_redundant_callback(vault):vs.complete_request_waiter(conn, req["id"], waiter_id="vw_done")row = _row(conn, req["id"])- assert row["callback_status"] == "skipped"- assert vs.list_pending_request_callbacks(conn) == []+ assert row["callback_status"] == "pending"+ assert vs.request_callback_consumed_by_waiter(row) is True+ assert [pending["id"] for pending in vs.list_pending_request_callbacks(conn)] == [req["id"]]def test_covering_grant_owner_waiter_suppresses_sibling_callbacks(vault):@@ -388,9 +392,9 @@ def test_covering_grant_owner_waiter_suppresses_sibling_callbacks(vault):vs.complete_request_waiter(conn, primary["id"], waiter_id="vw_primary")- assert _callback_status(conn, primary["id"]) == "skipped"+ assert _callback_status(conn, primary["id"]) == "pending"assert _callback_status(conn, sibling["id"]) == "skipped"- assert vs.list_pending_request_callbacks(conn) == []+ assert [pending["id"] for pending in vs.list_pending_request_callbacks(conn)] == [primary["id"]]def test_request_callback_ready_defers_sibling_access_until_covering_grant_ready(vault):@@ -636,3 +640,146 @@ def test_vault_callback_sweep_enqueues_protected_sign_callback(monkeypatch, tmp_assert callback_run.messageassert "Retrieve the signature result with: vibe vault await" in callback_run.messageassert "Do not rerun `vibe vault sign`" in callback_run.message++[email protected]("terminal_status", ["approved", "denied"])+def test_legacy_callback_drain_mirrors_completed_waiter_without_second_agent_turn(+ monkeypatch, tmp_path, terminal_status+):+ import asyncio+ from types import SimpleNamespace++ from core import scheduled_tasks as st+ from storage import messages_service+ from storage.models import agent_sessions, messages+ from storage.settings_service import upsert_scope++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))+ engine = create_sqlite_engine()+ metadata.create_all(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_waiter",+ now=now,+ )+ conn.execute(+ agent_sessions.insert().values(+ id="ses_vault_waiter",+ scope_id=scope_id,+ agent_backend="codex",+ agent_variant="default",+ session_anchor="anchor_vault_waiter",+ native_session_id="",+ status="active",+ metadata_json="{}",+ created_at=now,+ updated_at=now,+ last_active_at=now,+ )+ )+ messages_service.append(+ conn,+ scope_id=scope_id,+ session_id="ses_vault_waiter",+ platform="avibe",+ author="agent",+ source="agent",+ message_type="result",+ text="The previous Agent turn completed.",+ native_message_id="agent:previous-result",+ )+ vs.create_secret(+ conn,+ name="WAIT_RESULT_KEY",+ sealed=_sealed("wait-result"),+ protection="protected",+ )+ req = vs.create_access_request(+ conn,+ "WAIT_RESULT_KEY",+ requester={"session_id": "ses_vault_waiter"},+ delivery={"session_id": "ses_vault_waiter"},+ )+ deadline = (datetime.now(timezone.utc) + timedelta(minutes=1)).isoformat()+ vs.arm_request_waiter(conn, req["id"], waiter_id="vw_visible", deadline_at=deadline)+ if terminal_status == "approved":+ _grant_from_request(conn, req)+ else:+ vs.deny_request(conn, req["id"])+ vs.complete_request_waiter(conn, req["id"], waiter_id="vw_visible")+ row = _row(conn, req["id"])++ request_store = st.TaskExecutionStore(tmp_path / "task_requests")+ service = st.ScheduledTaskService(+ controller=SimpleNamespace(platform_settings_managers={}),+ store=st.ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),+ request_store=request_store,+ )++ with monkeypatch.context() as failed_mirror:+ failed_mirror.setattr(+ "core.message_mirror.mirror_vault_waiter_outcome",+ lambda **_: False,+ )+ assert service._process_vault_callback_sync(row) == "pending"+ with engine.connect() as conn:+ assert _callback_status(conn, req["id"]) == "pending"++ asyncio.run(service._drain_vault_callbacks())+ # The stable native message id also closes the crash window between mirror + callback mark.+ assert service._process_vault_callback_sync(row) == "sent"++ assert request_store.list_pending() == []+ with engine.connect() as conn:+ assert _callback_status(conn, req["id"]) == "sent"+ [message] = conn.execute(+ select(messages).where(+ messages.c.session_id == "ses_vault_waiter",+ messages.c.type == messages_service.VAULT_TYPE,+ )+ ).mappings().all()+ assert message["author"] == "harness"+ assert message["source"] == "harness"+ assert message["type"] == messages_service.VAULT_TYPE+ assert message["author_name"] == "vault"+ assert json.loads(message["metadata_json"]) == {+ "source_kind": "callback",+ "source_actor": f"vault:{req['id']}",+ "vault_request_type": "access",+ "vault_request_status": terminal_status,+ }++ with engine.connect() as conn:+ inbox = messages_service.list_inbox_sessions(+ conn,+ platform="avibe",+ only_session="ses_vault_waiter",+ )+ assert inbox["sessions"][0]["replied"] is False++ # A later direct/harness input remains unanswered: the Vault outcome is a+ # transcript notification, not terminal evidence for an unrelated turn.+ mirror_harness_inbound(+ MessageContext(+ user_id="scheduled",+ channel_id="ses_vault_waiter",+ platform="avibe",+ message_id="harness:newer-input",+ platform_specific={+ "agent_session_id": "ses_vault_waiter",+ "task_trigger_kind": "watch",+ },+ ),+ "A newer harness input",+ )+ with engine.connect() as conn:+ inbox = messages_service.list_inbox_sessions(+ conn,+ platform="avibe",+ only_session="ses_vault_waiter",+ )+ assert inbox["sessions"][0]["replied"] is Truediff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex 23e1c02df..f7c4eb4ca 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -47,6 +47,7 @@ import {import {chatTriggerLink,harnessChipLabelKey,+ isVaultCallback,needsHarnessProvenanceReconcile,vaultCallbackStatusKey,} from '../../lib/chatTrigger';@@ -3954,10 +3955,11 @@ export const MessageRow = memo(function MessageRow({const agentAuthored = isAgentAuthored(message);const isHarness = row.kind === 'harness';const isUser = row.kind === 'user';+ const isVaultNotification = isNotify && isVaultCallback(message);// 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 vaultStatusKey = isVaultCallback(message) ? vaultCallbackStatusKey(message) : null;const messageFontStyle = { fontSize: `${normalizeChatMessageFontSize(messageFontSize)}px` };const resultPresentation = resultFooterParts(message);@@ -4093,7 +4095,10 @@ export const MessageRow = memo(function MessageRow({<div className="inline-flex w-fit max-w-full items-start gap-1.5 rounded-2xl rounded-tl-md border border-gold/30 bg-gold/[0.08] px-3 py-1.5 text-[12px] text-gold"><Bell className="mt-px size-3 shrink-0" /><span className="min-w-0 break-words">- <span className="font-semibold">{t('chat.notifyLabel')}</span>+ <span className="font-semibold">{t(isVaultNotification ? 'chat.source.vault' : 'chat.notifyLabel')}</span>+ {vaultStatusKey && (+ <span className="font-normal text-gold/80"> · {t(vaultStatusKey)}</span>+ )}{resultPresentation.body && (<span className="font-normal text-gold/80"> · {resultPresentation.body}</span>)}diff --git a/ui/src/lib/chatMessageTypes.test.ts b/ui/src/lib/chatMessageTypes.test.tsindex 86909efd2..d2b119384 100644--- a/ui/src/lib/chatMessageTypes.test.ts+++ b/ui/src/lib/chatMessageTypes.test.ts@@ -4,7 +4,7 @@ import { isNotifyMessageType, isTerminalAgentMessage, isTranscriptMessage } fromdescribe('isTranscriptMessage', () => {it('shows the rows the transcript has always shown, and hides process log', () => {- for (const type of ['user', 'harness', 'output', 'result', 'notify', 'error']) {+ for (const type of ['user', 'harness', 'output', 'result', 'notify', 'vault', 'error']) {expect(isTranscriptMessage({ type }), type).toBe(true);}for (const type of ['assistant', 'tool_call', 'draft', 'pending', 'silent', 'future_type']) {diff --git a/ui/src/lib/chatRowKind.test.ts b/ui/src/lib/chatRowKind.test.tsindex 8dac9bf4e..b95bbc07c 100644--- a/ui/src/lib/chatRowKind.test.ts+++ b/ui/src/lib/chatRowKind.test.ts@@ -28,6 +28,7 @@ describe('chatRowKind', () => {expect(row({ author: 'agent', type: 'result' })).toEqual({ kind: 'agent' });expect(row({ author: 'system', type: 'user' })).toEqual({ kind: 'system' });expect(row({ author: 'harness', source: 'harness', type: 'harness' })).toEqual({ kind: 'harness' });+ expect(row({ author: 'harness', source: 'harness', type: 'vault' })).toEqual({ kind: 'harness' });expect(row({ author: 'agent', type: 'notify' })).toEqual({ kind: 'notify' });expect(row({ author: 'agent', type: 'error' })).toEqual({ kind: 'notify' });});diff --git a/ui/src/lib/messageTypes.test.ts b/ui/src/lib/messageTypes.test.tsindex 6e3d34036..5affe1421 100644--- a/ui/src/lib/messageTypes.test.ts+++ b/ui/src/lib/messageTypes.test.ts@@ -46,6 +46,7 @@ const CANONICAL_MESSAGE_TYPES = ['output','result','notify',+ 'vault','error','assistant',] as const;@@ -64,6 +65,7 @@ const wasTranscript = (type: string): boolean =>type === 'annotation' ||type === 'output' ||type === 'result' ||+ type === 'vault' ||type === 'error' ||type === 'notify';diff --git a/ui/src/lib/vaultConfirmSurface.ts b/ui/src/lib/vaultConfirmSurface.tsindex b4121461e..2b90aa44f 100644--- a/ui/src/lib/vaultConfirmSurface.ts+++ b/ui/src/lib/vaultConfirmSurface.ts@@ -2,11 +2,10 @@* Parent-measured visibility attestation of the sandbox iframe (protocol v2 §6.6 addendum / §13).** The parent owns the sandbox iframe, so only it can measure the element from the embedder document;- * the sandbox cannot observe its own frame from inside a cross-origin context. This module is the- * single place the wire shape is built, so its field names + nesting can be frozen by a unit test —- * they must match the sandbox's `parseParentConfirmSurface` contract exactly (`frame.*` plus a- * top-level `sampledAt`). A mismatch here is the contract-shape gap that surfaced as- * "parent frame visibility is not attested".+ * the sandbox cannot observe its own frame from inside a cross-origin context. This module keeps the+ * geometry/observer attestation shape in one place. It intentionally does not send a parent hit-test+ * claim: a compromised embedder can manufacture that boolean, and high-risk authorization now runs+ * in a top-level sandbox confirmation window instead.*/export type VaultConfirmSurface = {frame: {@@ -34,10 +33,10 @@ export type VaultConfirmSurfaceMeasurement = {};/**- * Shape raw parent-side measurements into the exact attestation object the sandbox accepts. Pure and+ * Shape raw parent-side measurements into the attestation object understood by the sandbox. Pure and* honest: it never invents values — a hidden, occluded, or degenerate measurement yields failing- * numbers (e.g. opacity 0, pointerEvents false, zero size) and the sandbox's geometry gate rejects- * it. Fail-closed: a non-numeric opacity becomes 0 rather than silently passing.+ * numbers (e.g. opacity 0, pointerEvents false, zero size). Fail-closed: a non-numeric opacity+ * becomes 0 rather than silently passing.*/export function buildVaultConfirmSurface(measurement: VaultConfirmSurfaceMeasurement): VaultConfirmSurface {const opacity =diff --git a/ui/src/lib/vaultSandboxClient.test.ts b/ui/src/lib/vaultSandboxClient.test.tsnew file mode 100644index 000000000..b0b587805--- /dev/null+++ b/ui/src/lib/vaultSandboxClient.test.ts@@ -0,0 +1,171 @@+// @vitest-environment jsdom++import { afterEach, describe, expect, it, vi } from 'vitest';++import { VaultSandboxClient } from './vaultSandboxClient';+import type { VaultConfirmSurface } from './vaultConfirmSurface';++const visibleSurface: VaultConfirmSurface = {+ frame: {+ frameWidth: 440,+ frameHeight: 640,+ intersectionRatio: 1,+ visibleByIntersectionObserver: true,+ opacity: 1,+ pointerEvents: true,+ },+ sampledAt: 1_700_000_000_000,+};++type TestPendingRequest = {+ timer: number;+ resolve: (value: unknown) => void;+};++type TestVaultSandboxClient = {+ iframe: HTMLIFrameElement;+ backdrop: HTMLDivElement | null;+ pending: Map<string, TestPendingRequest>;+ readyPromise: Promise<unknown>;+ handshaken: boolean;+ modalVisible: boolean;+ interactiveRequests: Set<string>;+ surfaceRefreshTimer: number | null;+ setModalVisible: (visible: boolean) => void;+ startSurfaceRefresh: () => void;+ measureSurface: () => Promise<VaultConfirmSurface | null>;+ request: <T>(+ op: string,+ payload: unknown,+ options: { timeoutMs?: number; interactive?: boolean },+ ) => Promise<T>;+};++afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ Reflect.deleteProperty(document, 'elementFromPoint');+ document.body.replaceChildren();+});++describe('VaultSandboxClient interactive request surface', () => {+ it('attests the expanded frame geometry and observer visibility', async () => {+ const iframe = document.createElement('iframe');+ document.body.appendChild(iframe);+ vi.spyOn(iframe, 'getBoundingClientRect').mockReturnValue({+ x: 100,+ y: 50,+ left: 100,+ top: 50,+ right: 540,+ bottom: 690,+ width: 440,+ height: 640,+ toJSON: () => ({}),+ } as DOMRect);+ vi.stubGlobal(+ 'IntersectionObserver',+ class {+ constructor(private readonly callback: IntersectionObserverCallback) {}+ observe(): void {+ this.callback(+ [{ intersectionRatio: 1, isVisible: false } as unknown as IntersectionObserverEntry],+ this as unknown as IntersectionObserver,+ );+ }+ disconnect(): void {}+ },+ );++ const client = Object.create(VaultSandboxClient.prototype) as TestVaultSandboxClient;+ Object.assign(client, { iframe });+ const surface = await client.measureSurface();++ expect(surface?.frame).toMatchObject({+ frameWidth: 440,+ frameHeight: 640,+ intersectionRatio: 1,+ visibleByIntersectionObserver: false,+ });+ });++ it('expands the iframe before measuring and sending an interactive RPC', async () => {+ const iframe = document.createElement('iframe');+ iframe.style.width = '0';+ iframe.style.height = '0';+ iframe.style.visibility = 'hidden';+ iframe.style.pointerEvents = 'none';+ document.body.appendChild(iframe);++ const client = Object.create(VaultSandboxClient.prototype) as TestVaultSandboxClient;+ Object.assign(client, {+ iframe,+ backdrop: null,+ pending: new Map(),+ readyPromise: Promise.resolve({}),+ handshaken: true,+ modalVisible: false,+ interactiveRequests: new Set(),+ surfaceRefreshTimer: null,+ });+ vi.spyOn(client, 'startSurfaceRefresh').mockImplementation(() => undefined);+ const setModalVisible = vi.spyOn(client, 'setModalVisible');+ const measure = vi.spyOn(client, 'measureSurface').mockImplementation(async () => {+ expect(setModalVisible).toHaveBeenCalledWith(true);+ expect(client['modalVisible']).toBe(true);+ expect(iframe.style.visibility).toBe('visible');+ expect(iframe.style.pointerEvents).toBe('auto');+ return visibleSurface;+ });+ const postMessage = vi.spyOn(iframe.contentWindow!, 'postMessage').mockImplementation(() => undefined);++ const result = client.request<{ blindBoxes: unknown[] }>(+ 'approveRelease',+ { items: [] },+ { interactive: true },+ );+ await vi.waitFor(() => expect(postMessage).toHaveBeenCalledTimes(1));++ const [wire] = postMessage.mock.calls[0];+ expect(measure).toHaveBeenCalledOnce();+ expect(wire).toMatchObject({ op: 'approveRelease', surface: visibleSurface });+ const pending = client.pending.get((wire as { id: string }).id);+ expect(pending).toBeDefined();+ if (!pending) throw new Error('interactive request was not registered');+ window.clearTimeout(pending.timer);+ pending.resolve({ blindBoxes: [] });+ await expect(result).resolves.toEqual({ blindBoxes: [] });+ });++ it('collapses the modal when interactive surface measurement fails before send', async () => {+ const iframe = document.createElement('iframe');+ document.body.appendChild(iframe);++ const client = Object.create(VaultSandboxClient.prototype) as TestVaultSandboxClient;+ Object.assign(client, {+ iframe,+ backdrop: null,+ pending: new Map(),+ readyPromise: Promise.resolve({}),+ handshaken: true,+ modalVisible: false,+ interactiveRequests: new Set(),+ surfaceRefreshTimer: null,+ });+ vi.spyOn(client, 'startSurfaceRefresh').mockImplementation(() => undefined);+ vi.spyOn(client, 'measureSurface').mockRejectedValue(new Error('visibility API failed'));+ const postMessage = vi.spyOn(iframe.contentWindow!, 'postMessage').mockImplementation(() => undefined);++ await expect(+ client.request('approveRelease', { items: [] }, { interactive: true }),+ ).rejects.toThrow('visibility API failed');++ expect(postMessage).not.toHaveBeenCalled();+ expect(client.interactiveRequests.size).toBe(0);+ expect(client.pending.size).toBe(0);+ expect(client.modalVisible).toBe(false);+ expect(client.backdrop).toBeNull();+ expect(iframe.style.visibility).toBe('hidden');+ expect(iframe.style.pointerEvents).toBe('none');+ });+});diff --git a/ui/src/lib/vaultSandboxClient.ts b/ui/src/lib/vaultSandboxClient.tsindex 449f9996e..9b6698d1e 100644--- a/ui/src/lib/vaultSandboxClient.ts+++ b/ui/src/lib/vaultSandboxClient.ts@@ -26,11 +26,9 @@ const DEFAULT_TIMEOUT_MS = 15_000;// Ops that may raise an in-sandbox card (confirm / passkey / plaintext display) can sit open for// as long as the user takes to act, so they get the long ceremony timeout regardless of tier.const INTERACTIVE_TIMEOUT_MS = 5 * 60_000;-// Cadence for refreshing the parent surface attestation while a confirm card is up (protocol v2-// §6.6 addendum / §13). The sandbox fail-closes an embedded R2/R3 confirm unless the parent freshly-// attests the sandbox iframe's on-screen geometry — it cannot observe its own iframe element from a-// cross-origin frame. The sandbox rejects attestations older than 60 s, so we refresh well under-// that cap while the ceremony is pending.+// Cadence for refreshing the parent surface attestation while an embedded card is up. This remains+// useful for compatibility and diagnostics, but high-risk authorization itself is completed in a+// top-level sandbox window and does not trust parent hit-test claims.const SURFACE_REFRESH_INTERVAL_MS = 10_000;type VaultSandboxOp = (typeof REQUIRED_OPS)[number] | 'handshake';@@ -316,9 +314,9 @@ export class VaultSandboxClient {private readyPromise: Promise<ReadyMessage>;private handshaken = false;private modalVisible = false;- // Ids of in-flight interactive (R2/R3) requests whose confirm card the sandbox gates on a fresh- // parent surface attestation. While the modal is up each one's attestation is refreshed on an- // interval; an id is dropped when its request settles (reply, timeout, or teardown).+ // Ids of in-flight interactive requests whose launcher card keeps the iframe expanded. While the+ // modal is up, optional geometry evidence is refreshed; final high-risk authorization happens in+ // the top-level sandbox window and never trusts a parent hit-test claim.private interactiveRequests = new Set<string>();private surfaceRefreshTimer: number | null = null;@@ -420,11 +418,9 @@ export class VaultSandboxClient {}/**- * Measure the sandbox iframe in the parent (embedder) document and package it as the attestation- * the sandbox's confirm-surface gate expects (protocol v2 §6.6 / §13): `getBoundingClientRect()`- * for size, an IntersectionObserver reading for visibility, computed `opacity` and `pointer-events`,- * and `sampledAt = Date.now()`. Measured honestly — a hidden or occluded iframe yields failing- * numbers and the sandbox still fail-closes; the values are never faked to pass the gate.+ * Measure the sandbox iframe in the parent (embedder) document and package geometry/observer+ * evidence for compatibility and diagnostics. No parent hit-test claim is sent because the+ * embedder is not a trusted security authority for the final authorization.*/private async measureSurface(): Promise<VaultConfirmSurface | null> {if (typeof window === 'undefined' || !this.iframe.isConnected) return null;@@ -595,14 +591,21 @@ export class VaultSandboxClient {): Promise<T> {await this.readyPromise;const id = randomId();- // Interactive (R2/R3) ops carry a parent surface attestation and get it refreshed while their- // confirm card is up (protocol v2 §6.6). Measured before send it reflects the still-headless- // worker; the post-`ui.show` refresh replaces it with the visible-modal reading the sandbox- // actually gates on. The `surface` field rides as a top-level sibling of `op`/`payload`. Only- // `approveRelease`/`sign`/`reveal` are interactive here: those are the ops whose sandbox handler- // runs the confirm-surface gate (§13). `setup`/`unlock` are WebAuthn/PRF ceremonies, not in-- // sandbox confirm clicks, so their handlers never assert a parent surface and none is sent.- const surface = options.interactive ? await this.measureSurface() : null;+ // Interactive ops expand the iframe before sending so the launcher card is visible before the+ // request reaches the sandbox. The final authorization is completed in a top-level window;+ // the optional surface evidence remains a compatibility field, never a security decision.+ let surface: VaultConfirmSurface | null = null;+ try {+ if (options.interactive) {+ this.interactiveRequests.add(id);+ this.setModalVisible(true);+ surface = await this.measureSurface();+ }+ } catch (error) {+ this.interactiveRequests.delete(id);+ if (this.interactiveRequests.size === 0 && this.modalVisible) this.setModalVisible(false);+ throw error;+ }const promise = new Promise<T>((resolve, reject) => {const timer = window.setTimeout(() => {this.pending.delete(id);@@ -616,7 +619,6 @@ export class VaultSandboxClient {timer,});});- if (options.interactive) this.interactiveRequests.add(id);this.target.postMessage({ channel: CHANNEL, version: VERSION, id, op, payload: payload ?? {}, ...(surface ? { surface } : {}) },VAULT_SANDBOX_ORIGIN,diff --git a/vibe/message_identity.py b/vibe/message_identity.pyindex 6715d2934..53e716410 100644--- a/vibe/message_identity.py+++ b/vibe/message_identity.py@@ -7,6 +7,8 @@ from typing import Optionalfrom vibe.message_types import input_author_type_pairsHARNESS_TYPE = "harness"+NOTIFY_TYPE = "notify"+VAULT_TYPE = "vault"INPUT_TURN_AUTHOR_TYPES = input_author_type_pairs()diff --git a/vibe/message_types.json b/vibe/message_types.jsonindex 471f2a03c..c45a77de6 100644--- a/vibe/message_types.json+++ b/vibe/message_types.json@@ -80,6 +80,13 @@],"render": "status"},+ "vault": {+ "transcript": true,+ "searchable": true,+ "inboxActivity": true,+ "inboxPreview": true,+ "render": "harness"+ },"error": {"transcript": true,"inboxActivity": true,