diff --git a/.changeset/chat-safety-review-controls.md b/.changeset/chat-safety-review-controls.md new file mode 100644 index 0000000000..3820c2fc85 --- /dev/null +++ b/.changeset/chat-safety-review-controls.md @@ -0,0 +1,11 @@ +--- +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-ui-server": minor +"@schlessera/brain-ui-react": minor +--- + +Show host-owned safety triggers beside their exact tool entries, with honest turn-event fallback, accessible persistent details and owner-only individual review. Keep B/C restricted after reviewing A, retain historical human verdicts, and never replay decisions or replace newer live evidence with a receipt. Add opt-in durable tool correlation while preserving older readers' strict sidecar shape, continuing the approved pre-1.0 change to unconditional restriction. + +Keep last-read safety evidence visible and read-only during reconnect, preserving reading position while requiring a fresh complete snapshot before review controls return. + +Keep safety hints and persistent details on the named anchored-popover layer beneath navigation and destination panels. diff --git a/api-report/ui-react.txt b/api-report/ui-react.txt index a283e00cb2..2755fb9d2d 100644 --- a/api-report/ui-react.txt +++ b/api-report/ui-react.txt @@ -1246,6 +1246,302 @@ signatures (every public export and the types it is made of) timeZone: null | string; }>; refreshModels: () => Promise; + safetyCommit: (requestId: string, body: SafetyReviewBody, signal: AbortSignal) => Promise<{ + code: "capacity" | "not_finalized" | "recording_failed" | "request_conflict" | "request_expired" | "resync_required" | "retired" | "stale_revision" | "unauthorized" | "unavailable"; + currentProjection: null | { + coverage: { + detectorVersion: 1; + epochs: { + acknowledged: string[]; + backendId: string; + endSequence: null | string; + id: string; + mandatory: string[]; + reason: null | string; + startSequence: string; + status: "complete" | "incomplete" | "unknown"; + }[]; + exclusions: string[]; + state: "complete" | "incomplete" | "unknown"; + }; + earliestUnresolvedId: null | string; + evidenceRevision: string; + pendingCount: number; + reasons: ("capacity" | "coverage_unknown" | "recording_failed" | "recording_pending" | "unresolved")[]; + restriction: "normal" | "restricted"; + session: null | { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + unresolvedCount: number; + }; + reason: string; + receipt: { + occurrenceId: string; + operationId: null | string; + projection: null | { + coverage: { + detectorVersion: 1; + epochs: { + acknowledged: string[]; + backendId: string; + endSequence: null | string; + id: string; + mandatory: string[]; + reason: null | string; + startSequence: string; + status: "complete" | "incomplete" | "unknown"; + }[]; + exclusions: string[]; + state: "complete" | "incomplete" | "unknown"; + }; + earliestUnresolvedId: null | string; + evidenceRevision: string; + pendingCount: number; + reasons: ("capacity" | "coverage_unknown" | "recording_failed" | "recording_pending" | "unresolved")[]; + restriction: "normal" | "restricted"; + session: null | { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + unresolvedCount: number; + }; + reason: null | string; + requestId: null | string; + session: { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + stage: "prepared" | "refused" | "verdict_committed"; + verdict: "committed" | "unresolved"; + version: 1; + }; + retryable: false; + version: 1; + } | { + currentProjection: null | { + coverage: { + detectorVersion: 1; + epochs: { + acknowledged: string[]; + backendId: string; + endSequence: null | string; + id: string; + mandatory: string[]; + reason: null | string; + startSequence: string; + status: "complete" | "incomplete" | "unknown"; + }[]; + exclusions: string[]; + state: "complete" | "incomplete" | "unknown"; + }; + earliestUnresolvedId: null | string; + evidenceRevision: string; + pendingCount: number; + reasons: ("capacity" | "coverage_unknown" | "recording_failed" | "recording_pending" | "unresolved")[]; + restriction: "normal" | "restricted"; + session: null | { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + unresolvedCount: number; + }; + receipt: { + occurrenceId: string; + operationId: null | string; + projection: null | { + coverage: { + detectorVersion: 1; + epochs: { + acknowledged: string[]; + backendId: string; + endSequence: null | string; + id: string; + mandatory: string[]; + reason: null | string; + startSequence: string; + status: "complete" | "incomplete" | "unknown"; + }[]; + exclusions: string[]; + state: "complete" | "incomplete" | "unknown"; + }; + earliestUnresolvedId: null | string; + evidenceRevision: string; + pendingCount: number; + reasons: ("capacity" | "coverage_unknown" | "recording_failed" | "recording_pending" | "unresolved")[]; + restriction: "normal" | "restricted"; + session: null | { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + unresolvedCount: number; + }; + reason: null | string; + requestId: null | string; + session: { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + stage: "prepared" | "refused" | "verdict_committed"; + verdict: "committed" | "unresolved"; + version: 1; + }; + version: 1; + }>; + safetyPrepare: (body: SafetyReviewBody, signal: AbortSignal) => Promise<{ + code: "capacity" | "not_finalized" | "recording_failed" | "request_conflict" | "request_expired" | "resync_required" | "retired" | "stale_revision" | "unauthorized" | "unavailable"; + currentProjection: null | { + coverage: { + detectorVersion: 1; + epochs: { + acknowledged: string[]; + backendId: string; + endSequence: null | string; + id: string; + mandatory: string[]; + reason: null | string; + startSequence: string; + status: "complete" | "incomplete" | "unknown"; + }[]; + exclusions: string[]; + state: "complete" | "incomplete" | "unknown"; + }; + earliestUnresolvedId: null | string; + evidenceRevision: string; + pendingCount: number; + reasons: ("capacity" | "coverage_unknown" | "recording_failed" | "recording_pending" | "unresolved")[]; + restriction: "normal" | "restricted"; + session: null | { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + unresolvedCount: number; + }; + reason: string; + receipt: { + occurrenceId: string; + operationId: null | string; + projection: null | { + coverage: { + detectorVersion: 1; + epochs: { + acknowledged: string[]; + backendId: string; + endSequence: null | string; + id: string; + mandatory: string[]; + reason: null | string; + startSequence: string; + status: "complete" | "incomplete" | "unknown"; + }[]; + exclusions: string[]; + state: "complete" | "incomplete" | "unknown"; + }; + earliestUnresolvedId: null | string; + evidenceRevision: string; + pendingCount: number; + reasons: ("capacity" | "coverage_unknown" | "recording_failed" | "recording_pending" | "unresolved")[]; + restriction: "normal" | "restricted"; + session: null | { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + unresolvedCount: number; + }; + reason: null | string; + requestId: null | string; + session: { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + stage: "prepared" | "refused" | "verdict_committed"; + verdict: "committed" | "unresolved"; + version: 1; + }; + retryable: false; + version: 1; + } | { + currentProjection: null | { + coverage: { + detectorVersion: 1; + epochs: { + acknowledged: string[]; + backendId: string; + endSequence: null | string; + id: string; + mandatory: string[]; + reason: null | string; + startSequence: string; + status: "complete" | "incomplete" | "unknown"; + }[]; + exclusions: string[]; + state: "complete" | "incomplete" | "unknown"; + }; + earliestUnresolvedId: null | string; + evidenceRevision: string; + pendingCount: number; + reasons: ("capacity" | "coverage_unknown" | "recording_failed" | "recording_pending" | "unresolved")[]; + restriction: "normal" | "restricted"; + session: null | { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + unresolvedCount: number; + }; + receipt: { + occurrenceId: string; + operationId: null | string; + projection: null | { + coverage: { + detectorVersion: 1; + epochs: { + acknowledged: string[]; + backendId: string; + endSequence: null | string; + id: string; + mandatory: string[]; + reason: null | string; + startSequence: string; + status: "complete" | "incomplete" | "unknown"; + }[]; + exclusions: string[]; + state: "complete" | "incomplete" | "unknown"; + }; + earliestUnresolvedId: null | string; + evidenceRevision: string; + pendingCount: number; + reasons: ("capacity" | "coverage_unknown" | "recording_failed" | "recording_pending" | "unresolved")[]; + restriction: "normal" | "restricted"; + session: null | { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + unresolvedCount: number; + }; + reason: null | string; + requestId: null | string; + session: { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + stage: "prepared" | "refused" | "verdict_committed"; + verdict: "committed" | "unresolved"; + version: 1; + }; + version: 1; + }>; saveDictationSettings: (settings: DictationSettings) => Promise; saveLivePersonaSelection: (value: string, revision: number) => Promise; saveLiveSettings: (update: VoiceLiveSettingsUpdate) => Promise; @@ -1761,6 +2057,302 @@ signatures (every public export and the types it is made of) timeZone: null | string; }>; refreshModels: () => Promise; + safetyCommit: (requestId: string, body: import("@schlessera/brain-ui-sdk").SafetyReviewBody, signal: AbortSignal) => Promise<{ + code: "capacity" | "not_finalized" | "recording_failed" | "request_conflict" | "request_expired" | "resync_required" | "retired" | "stale_revision" | "unauthorized" | "unavailable"; + currentProjection: null | { + coverage: { + detectorVersion: 1; + epochs: { + acknowledged: string[]; + backendId: string; + endSequence: null | string; + id: string; + mandatory: string[]; + reason: null | string; + startSequence: string; + status: "complete" | "incomplete" | "unknown"; + }[]; + exclusions: string[]; + state: "complete" | "incomplete" | "unknown"; + }; + earliestUnresolvedId: null | string; + evidenceRevision: string; + pendingCount: number; + reasons: ("capacity" | "coverage_unknown" | "recording_failed" | "recording_pending" | "unresolved")[]; + restriction: "normal" | "restricted"; + session: null | { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + unresolvedCount: number; + }; + reason: string; + receipt: { + occurrenceId: string; + operationId: null | string; + projection: null | { + coverage: { + detectorVersion: 1; + epochs: { + acknowledged: string[]; + backendId: string; + endSequence: null | string; + id: string; + mandatory: string[]; + reason: null | string; + startSequence: string; + status: "complete" | "incomplete" | "unknown"; + }[]; + exclusions: string[]; + state: "complete" | "incomplete" | "unknown"; + }; + earliestUnresolvedId: null | string; + evidenceRevision: string; + pendingCount: number; + reasons: ("capacity" | "coverage_unknown" | "recording_failed" | "recording_pending" | "unresolved")[]; + restriction: "normal" | "restricted"; + session: null | { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + unresolvedCount: number; + }; + reason: null | string; + requestId: null | string; + session: { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + stage: "prepared" | "refused" | "verdict_committed"; + verdict: "committed" | "unresolved"; + version: 1; + }; + retryable: false; + version: 1; + } | { + currentProjection: null | { + coverage: { + detectorVersion: 1; + epochs: { + acknowledged: string[]; + backendId: string; + endSequence: null | string; + id: string; + mandatory: string[]; + reason: null | string; + startSequence: string; + status: "complete" | "incomplete" | "unknown"; + }[]; + exclusions: string[]; + state: "complete" | "incomplete" | "unknown"; + }; + earliestUnresolvedId: null | string; + evidenceRevision: string; + pendingCount: number; + reasons: ("capacity" | "coverage_unknown" | "recording_failed" | "recording_pending" | "unresolved")[]; + restriction: "normal" | "restricted"; + session: null | { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + unresolvedCount: number; + }; + receipt: { + occurrenceId: string; + operationId: null | string; + projection: null | { + coverage: { + detectorVersion: 1; + epochs: { + acknowledged: string[]; + backendId: string; + endSequence: null | string; + id: string; + mandatory: string[]; + reason: null | string; + startSequence: string; + status: "complete" | "incomplete" | "unknown"; + }[]; + exclusions: string[]; + state: "complete" | "incomplete" | "unknown"; + }; + earliestUnresolvedId: null | string; + evidenceRevision: string; + pendingCount: number; + reasons: ("capacity" | "coverage_unknown" | "recording_failed" | "recording_pending" | "unresolved")[]; + restriction: "normal" | "restricted"; + session: null | { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + unresolvedCount: number; + }; + reason: null | string; + requestId: null | string; + session: { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + stage: "prepared" | "refused" | "verdict_committed"; + verdict: "committed" | "unresolved"; + version: 1; + }; + version: 1; + }>; + safetyPrepare: (body: import("@schlessera/brain-ui-sdk").SafetyReviewBody, signal: AbortSignal) => Promise<{ + code: "capacity" | "not_finalized" | "recording_failed" | "request_conflict" | "request_expired" | "resync_required" | "retired" | "stale_revision" | "unauthorized" | "unavailable"; + currentProjection: null | { + coverage: { + detectorVersion: 1; + epochs: { + acknowledged: string[]; + backendId: string; + endSequence: null | string; + id: string; + mandatory: string[]; + reason: null | string; + startSequence: string; + status: "complete" | "incomplete" | "unknown"; + }[]; + exclusions: string[]; + state: "complete" | "incomplete" | "unknown"; + }; + earliestUnresolvedId: null | string; + evidenceRevision: string; + pendingCount: number; + reasons: ("capacity" | "coverage_unknown" | "recording_failed" | "recording_pending" | "unresolved")[]; + restriction: "normal" | "restricted"; + session: null | { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + unresolvedCount: number; + }; + reason: string; + receipt: { + occurrenceId: string; + operationId: null | string; + projection: null | { + coverage: { + detectorVersion: 1; + epochs: { + acknowledged: string[]; + backendId: string; + endSequence: null | string; + id: string; + mandatory: string[]; + reason: null | string; + startSequence: string; + status: "complete" | "incomplete" | "unknown"; + }[]; + exclusions: string[]; + state: "complete" | "incomplete" | "unknown"; + }; + earliestUnresolvedId: null | string; + evidenceRevision: string; + pendingCount: number; + reasons: ("capacity" | "coverage_unknown" | "recording_failed" | "recording_pending" | "unresolved")[]; + restriction: "normal" | "restricted"; + session: null | { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + unresolvedCount: number; + }; + reason: null | string; + requestId: null | string; + session: { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + stage: "prepared" | "refused" | "verdict_committed"; + verdict: "committed" | "unresolved"; + version: 1; + }; + retryable: false; + version: 1; + } | { + currentProjection: null | { + coverage: { + detectorVersion: 1; + epochs: { + acknowledged: string[]; + backendId: string; + endSequence: null | string; + id: string; + mandatory: string[]; + reason: null | string; + startSequence: string; + status: "complete" | "incomplete" | "unknown"; + }[]; + exclusions: string[]; + state: "complete" | "incomplete" | "unknown"; + }; + earliestUnresolvedId: null | string; + evidenceRevision: string; + pendingCount: number; + reasons: ("capacity" | "coverage_unknown" | "recording_failed" | "recording_pending" | "unresolved")[]; + restriction: "normal" | "restricted"; + session: null | { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + unresolvedCount: number; + }; + receipt: { + occurrenceId: string; + operationId: null | string; + projection: null | { + coverage: { + detectorVersion: 1; + epochs: { + acknowledged: string[]; + backendId: string; + endSequence: null | string; + id: string; + mandatory: string[]; + reason: null | string; + startSequence: string; + status: "complete" | "incomplete" | "unknown"; + }[]; + exclusions: string[]; + state: "complete" | "incomplete" | "unknown"; + }; + earliestUnresolvedId: null | string; + evidenceRevision: string; + pendingCount: number; + reasons: ("capacity" | "coverage_unknown" | "recording_failed" | "recording_pending" | "unresolved")[]; + restriction: "normal" | "restricted"; + session: null | { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + unresolvedCount: number; + }; + reason: null | string; + requestId: null | string; + session: { + historyGeneration: string; + historyOwnerId: string; + sessionId: string; + }; + stage: "prepared" | "refused" | "verdict_committed"; + verdict: "committed" | "unresolved"; + version: 1; + }; + version: 1; + }>; saveDictationSettings: (settings: import("@schlessera/brain-ui-sdk").DictationSettings) => Promise; saveLivePersonaSelection: (value: string, revision: number) => Promise; saveLiveSettings: (update: import("@schlessera/brain-ui-sdk").VoiceLiveSettingsUpdate) => Promise; diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index ad46e0a53f..2d67778245 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -13966,6 +13966,7 @@ signatures (every public export and the types it is made of) }>; }, z.core.$strict>, z.ZodObject<{ cursor: z.ZodOptional>; + includeEntries: z.ZodOptional>; limit: z.ZodOptional; requestId: z.ZodString; target: z.ZodUnion>; + includeEntries: z.ZodOptional>; limit: z.ZodOptional; requestId: z.ZodString; target: z.ZodUnion; + entry: z.ZodOptional; + toolUseId: z.ZodString; + }, z.core.$strict>>; epochId: z.ZodString; exposure: z.ZodEnum<{ finalized: "finalized"; @@ -19103,6 +19109,10 @@ signatures (every public export and the types it is made of) bindingId: z.ZodString; detailPruned: z.ZodBoolean; detector: z.ZodNullable; + entry: z.ZodOptional; + toolUseId: z.ZodString; + }, z.core.$strict>>; epochId: z.ZodString; exposure: z.ZodEnum<{ finalized: "finalized"; @@ -19595,6 +19605,10 @@ signatures (every public export and the types it is made of) bindingId: z.ZodString; detailPruned: z.ZodBoolean; detector: z.ZodNullable; + entry: z.ZodOptional; + toolUseId: z.ZodString; + }, z.core.$strict>>; epochId: z.ZodString; exposure: z.ZodEnum<{ finalized: "finalized"; @@ -24460,6 +24474,10 @@ signatures (every public export and the types it is made of) bindingId: z.ZodString; detailPruned: z.ZodBoolean; detector: z.ZodNullable; + entry: z.ZodOptional; + toolUseId: z.ZodString; + }, z.core.$strict>>; epochId: z.ZodString; exposure: z.ZodEnum<{ finalized: "finalized"; @@ -24613,6 +24631,10 @@ signatures (every public export and the types it is made of) bindingId: z.ZodString; detailPruned: z.ZodBoolean; detector: z.ZodNullable; + entry: z.ZodOptional; + toolUseId: z.ZodString; + }, z.core.$strict>>; epochId: z.ZodString; exposure: z.ZodEnum<{ finalized: "finalized"; @@ -25287,6 +25309,10 @@ signatures (every public export and the types it is made of) bindingId: z.ZodString; detailPruned: z.ZodBoolean; detector: z.ZodNullable; + entry: z.ZodOptional; + toolUseId: z.ZodString; + }, z.core.$strict>>; epochId: z.ZodString; exposure: z.ZodEnum<{ finalized: "finalized"; @@ -25456,6 +25482,10 @@ signatures (every public export and the types it is made of) bindingId: z.ZodString; detailPruned: z.ZodBoolean; detector: z.ZodNullable; + entry: z.ZodOptional; + toolUseId: z.ZodString; + }, z.core.$strict>>; epochId: z.ZodString; exposure: z.ZodEnum<{ finalized: "finalized"; diff --git a/api-report/ui-server.txt b/api-report/ui-server.txt index bed60fcd68..6de0ae57a3 100644 --- a/api-report/ui-server.txt +++ b/api-report/ui-server.txt @@ -1086,6 +1086,10 @@ signatures (every public export and the types it is made of) tool_web_input: "tool_web_input"; unproxied_shell_input: "unproxied_shell_input"; }>; + entry: z.ZodOptional; + toolUseId: z.ZodString; + }, z.core.$strict>>; epochId: z.ZodString; exposure: z.ZodEnum<{ finalized: "finalized"; diff --git a/docs/decisions/answer-delivery.md b/docs/decisions/answer-delivery.md index 6ee9f0649a..b6dd28dae0 100644 --- a/docs/decisions/answer-delivery.md +++ b/docs/decisions/answer-delivery.md @@ -234,7 +234,7 @@ Before this, the terminal frame replaced an unanswered card with a dismissed stub, and its draft went with the controls. Now the card stays the editable question under a prompt that says the turn ended or timed out (`const [endedDismissed`, -`packages/ui-react/src/components/chat/message-bubble.tsx:632-650`). Its +`packages/ui-react/src/components/chat/message-bubble.tsx:633-651`). Its Submit sends no frame to the ended request. It records the answer locally as a `closed`/`ended` delivery, so the card shows the shipped Not delivered footer with Copy answer and Send as message (R1). Send as message is the only diff --git a/docs/http-api.md b/docs/http-api.md index 067c84b637..70c948b582 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -2087,6 +2087,14 @@ and `detailPruned`. Responses are `Cache-Control: no-store` and at most 262144 UTF-8 bytes. No request invokes a verdict, policy writer, backend turn or provider transcript write. +Optional `entries=1` includes the host-owned `entry:{kind:"tool",toolUseId}` +only where recorded. The same choice is required on every cursor page; its +subscription inherits it. No other `entries` value is accepted. The default +response retains the original strict version-1 record shape. Correlation +requires both the exact host turn and tool identity; opaque network input and +unknown legacy attribution remain separate named turn events. Minimal entry +identity survives detail pruning; retirement removes it with the evidence. + The live principal must belong to the retained history's account (#3952). A principal id always matches itself. Two different ids match only when both resolve to the same account partition in every auth mode, which today means diff --git a/docs/integration-contract/http.md b/docs/integration-contract/http.md index a3b89cb4c4..421460b697 100644 --- a/docs/integration-contract/http.md +++ b/docs/integration-contract/http.md @@ -1169,6 +1169,11 @@ detector completeness are separate; neither omitted details nor a review receipt replace the aggregate. Route absence and refused reads are explicitly unavailable. Existing history visibility and mutation authority remain intact. +Additively for #3605, `entries=1` requests explicit bounded tool-entry +correlation on this read. No other value or duplicate parameter is accepted. +The cursor and subsequent subscription retain that choice. Omitting it keeps +the original strict version-1 record shape. This metadata grants no authority +and never infers attribution for opaque transport. ### Selectable dictation providers (additive, #3707) diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 881af24e3d..8cab503d83 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -5291,7 +5291,38 @@ its read-only reason additionally accepts `owner_required` or null; optional literal review lifetime/body bounds describe a supporting host. Absent or unsupported capability remains unavailable and grants no mutation authority. -### Native recovery quarantine status (#3816) +## Chat safety review controls (additive, #3605) + +`createBrainApi` adds `safetyPrepare(body, signal)` and +`safetyCommit(requestId, body, signal)` for the existing two-phase owner HTTP +review. Both parse the bounded SDK response, including refusal receipts. +There is no retry queue or persisted mutation authority. A lost commit response +remains unknown until a new read; reconnect and reload never send a verdict. + +The React transcript renders host-owned sidecars independently of chat message +objects. An explicit turn/tool correlation places a 44px safety indicator on +that entry and on its collapsed run. Uncorrelated input has a named turn event. +Persistent details expose source, observation time, provenance, finalization and +individual human verdicts. The narrow review is **Only this trigger**; a safe +shield means **Marked safe by you**, never objective verification or removal of +provider context. Standing-rule choices remain absent. Receipt projections +never replace newer live evidence; only complete, zero-unresolved, healthy +coverage can display **Normal policy restored**. Auth loss, selection changes +and retirement discard pending authority. Any retained detail during a same-chat +refresh is read-only until the new snapshot completes. + + +Transport loss retains already read evidence as **last read**, with review +capability, pending request authority and normal-policy claims removed. The +notice and entry indicators keep their geometry while the same owner obtains +a fresh snapshot. This display cache is partitioned by the host's opaque +principal key, active session and auth epoch; a missing principal key creates +a new partition at every hello. It grants no authority. New principals, auth +loss, explicit unavailable/retired reads and deletion purge retained details. +Late updates from a disconnected socket cannot loosen the retained facts, and +recovery never resumes a prepared decision. + +## Native recovery quarantine status (#3816) `NativeManagerReady` gains optional `recovery` with `quarantinedIntents`, `stagingChargedBytes` (null when no safe stage bound is known) and @@ -5308,6 +5339,8 @@ absent stage directory or invalid UUID charges zero; a surviving stage retains its independently persisted historical tmpfs cap. Public `/api/health` remains unchanged. +## Journal cleanup diagnostics (additive, #3815) + The journal host's additive `cleanupStatus()` method (#3815) returns `{ retained: { pending, failed, retainedBytes }, lastFailure }`, the same current accounting and historical diagnostic record exposed as diff --git a/docs/integration-contract/wire.md b/docs/integration-contract/wire.md index d55cb10b44..962702142a 100644 --- a/docs/integration-contract/wire.md +++ b/docs/integration-contract/wire.md @@ -3132,6 +3132,18 @@ After declaring the same capability in `client_hello`, clients may send: is `{sessionId}` or the exact provisional `{turnId,bindingId}`. Reads cannot discover/create a session by guessing aliases. The host replies `safety_history: {type,requestId,page:SafetyPage}`. + Additively for #3605, hosts advertise the independent boolean + `server_hello.capabilities.sessionSafetyEntryCorrelation`. Only after this + declaration may a client add `includeEntries:true`. Opted-in occurrence + records may contain `entry:{kind:"tool",toolUseId}`; the tool ID uses the + existing bounded ID grammar. Both the occurrence's host `turnId` and this + explicit tool identity must match a displayed entry. A host operation UUID, + names, arguments, timing and adjacency do not establish that join. Absent + correlation uses a separately named turn event. The snapshot pins this + choice for all pages and its subscription; changing it through a cursor + refuses. Default reads and subscriptions retain the original strict record + shape, and `safetyCapabilities` itself is unchanged for older clients. + Minimal correlation survives detail pruning and is deleted with its evidence. - `safety_subscribe`: `{type,version:1,requestId,identity,afterRevision,snapshotId}`. One selected history subscription per connection replaces its predecessor. `identity` is the canonical `{sessionId,historyOwnerId,historyGeneration}` diff --git a/packages/ui-kit/vitest.config.ts b/packages/ui-kit/vitest.config.ts index 20bc3a25fa..660e7ece92 100644 --- a/packages/ui-kit/vitest.config.ts +++ b/packages/ui-kit/vitest.config.ts @@ -6,6 +6,7 @@ import { mermaidMedia, mermaidOutput, mermaidScreenComparison } from "../ui-reac import { consumerParityViewport } from "./tests/visual/consumer-parity-viewport.ts"; import { artifactParityRoute } from "./tests/visual/artifact-parity-route.ts"; import { storageServer } from "../ui-react/tests/browser/storage-server-command.ts"; +import { safetyServer } from "../ui-react/tests/browser/safety-server-command.ts"; import { policyServer } from "../ui-react/tests/browser/policy-server-command.ts"; import { hygieneLoop } from "../ui-react/tests/browser/hygiene-loop-command.ts"; import { hygieneLifecycleFailures } from "../ui-react/tests/browser/hygiene-lifecycle-failures.ts"; @@ -173,7 +174,7 @@ export default mergeConfig( browser: { enabled: true, screenshotFailures: false, - commands: { recordingProof, rankTap, conversationServer, mermaidMedia, mermaidOutput, mermaidScreenComparison, buttonCapture, overlayMouse, dictationMotion, policyServer, storageServer, hygieneLoop, hygieneServer, hygieneLifecycle, hygieneContextLifecycle, hygieneLifecycleCleanup, hygieneLifecycleFailures, dispatchActions, safetyGapChats, sheetInput, focusCapture, formViewport, formConsumerStyles, rankFooterFonts, codeHighlightFailure, codeHighlightFailureCount, offlineScene, coldCapture, shareReview, transcriptionHttp, startRequestLog, requestLog, grantMicrophone }, + commands: { safetyServer, recordingProof, rankTap, conversationServer, mermaidMedia, mermaidOutput, mermaidScreenComparison, buttonCapture, overlayMouse, dictationMotion, policyServer, storageServer, hygieneLoop, hygieneServer, hygieneLifecycle, hygieneContextLifecycle, hygieneLifecycleCleanup, hygieneLifecycleFailures, dispatchActions, safetyGapChats, sheetInput, focusCapture, formViewport, formConsumerStyles, rankFooterFonts, codeHighlightFailure, codeHighlightFailureCount, offlineScene, coldCapture, shareReview, transcriptionHttp, startRequestLog, requestLog, grantMicrophone }, // The fake microphone plays the generated 10-second fixture // (#1016). Chromium reads the file at launch, so it is written // when this config loads; the fake UI grants the permission. diff --git a/packages/ui-react/src/components/chat/chat-page.tsx b/packages/ui-react/src/components/chat/chat-page.tsx index ce5affc3bb..a63a5230de 100644 --- a/packages/ui-react/src/components/chat/chat-page.tsx +++ b/packages/ui-react/src/components/chat/chat-page.tsx @@ -16,6 +16,7 @@ import { useWebSocket } from "../../hooks/use-websocket.js"; import { useTrackerSeen } from "../../hooks/use-tracker-seen.js"; import { MaskEditor } from "../images/mask-editor.js"; import { MessageBubble } from "./message-bubble.js"; +import { SessionSafety } from "./safety-indicator.js"; import { useWorkRestore } from "../../hooks/use-local-work.js"; import { messageFingerprint } from "../../lib/local-work.js"; @@ -738,6 +739,7 @@ export function ChatPage() { className="mx-auto max-w-3xl divide-y divide-border/20" > {dialogueNotice &&

{dialogueNotice}

} + {dialoguePage?.coverage === "legacy" &&

Earlier spoken dialogue was not saved.

} {dialoguePage?.before !== undefined && + + {/* Why a restored card is read-only (D52 §4 R3), on its own line so the words wrap at a phone's width instead of leaving the header row. */} diff --git a/packages/ui-react/src/lib/api-client.ts b/packages/ui-react/src/lib/api-client.ts index fe9bbb51ba..4dccf3d716 100644 --- a/packages/ui-react/src/lib/api-client.ts +++ b/packages/ui-react/src/lib/api-client.ts @@ -3,6 +3,8 @@ import { POLICY_CHANGE_REVIEW_SCHEMA } from "@schlessera/brain-ui-sdk/tool-contr import { apiBase } from "./backend.js"; import { readSyncResult } from "./sync-stream.js"; import { classifySessionRecoveryResponse } from "@schlessera/brain-ui-sdk/schemas"; +import { safetyReviewResponseSchema } from "@schlessera/brain-ui-sdk/schemas"; +import type { SafetyReviewBody } from "@schlessera/brain-ui-sdk/protocol"; import type { HygieneReviewRead, HygieneReviewCommand, HygienePreviewRequest, HygienePreviewResponse, HygieneWorktreeDetailsRead, SessionRecoveryResult, WorkerHostStatus } from "@schlessera/brain-ui-sdk/protocol"; import type { ContentRendererDeclaration, ConfiguredModule, ModuleSettingsSnapshot, ModuleSettingsMigrationPreview } from "@schlessera/brain-ui-sdk"; @@ -353,7 +355,17 @@ export function createBrainApi( return (await fetchResponse(path, init)).json(); } + async function safetyReview(body:SafetyReviewBody,requestId:string|null,signal:AbortSignal) { + const path=`/sessions/${encodeURIComponent(body.session.sessionId)}/safety/reviews/${requestId===null?"prepare":`${encodeURIComponent(requestId)}/commit`}`; + const res=await request(`${getBase()}${path}`,{method:"POST",cache:"no-store",headers:{"Content-Type":"application/json"},body:JSON.stringify(body),signal}); + const value=await res.json(),parsed=safetyReviewResponseSchema.safeParse(value); + if(!parsed.success)throw new ApiRequestError(typeof value?.reason==="string"?value.reason:"Safety review unavailable",res.status); + return parsed.data; + } + return { + safetyPrepare: (body:SafetyReviewBody,signal:AbortSignal)=>safetyReview(body,null,signal), + safetyCommit: (requestId:string,body:SafetyReviewBody,signal:AbortSignal)=>safetyReview(body,requestId,signal), turnJournal: (sessionId: string, turnId: string, signal?: AbortSignal) => fetchJson(`/sessions/${encodeURIComponent(sessionId)}/turns/${encodeURIComponent(turnId)}/journal`, { signal }), turnJournalPreview: (sessionId: string, turnId: string, sequence: number, signal?: AbortSignal) => fetchJson<{ inline: boolean; before?: string; after?: string; reason?: string; beforeBytes?: number; afterBytes?: number }>(`/sessions/${encodeURIComponent(sessionId)}/turns/${encodeURIComponent(turnId)}/journal/${sequence}/preview`, { signal }), agentPolicy: (signal?: AbortSignal) => fetchJson("/agent-policy", { cache: "no-store", ...(signal ? { signal } : {}) }), diff --git a/packages/ui-react/src/lib/safety-client.ts b/packages/ui-react/src/lib/safety-client.ts index a8ca2abab9..06c1b3bd8b 100644 --- a/packages/ui-react/src/lib/safety-client.ts +++ b/packages/ui-react/src/lib/safety-client.ts @@ -9,7 +9,7 @@ export function createSafetyClient(root:BrainUiServices,send:(message:ClientMess if(disposed||!store.getState().supported)return; target=next;requestId=crypto.randomUUID();awaitingPage=true;store.getState().begin(requestId); send({type:"safety_unsubscribe",version:1}); - send({type:"safety_read",version:1,requestId,target}); + send({type:"safety_read",version:1,requestId,target,...(store.getState().entryCorrelation?{includeEntries:true as const}:{})}); } function selected(): void { const id = root.stores.chat.getState().activeSessionId; @@ -23,18 +23,19 @@ export function createSafetyClient(root:BrainUiServices,send:(message:ClientMess } } const detach=root.stores.chat.subscribe((state,previous)=>{if(state.activeSessionId!==previous.activeSessionId)selected();}); + const detachRefresh=store.subscribe((state,previous)=>{if(state.refreshTick!==previous.refreshTick)selected();}); return { frame(msg:ServerMessage):boolean{ if(disposed)return false; if(msg.type==="server_hello"){ - requestId=null;store.getState().reset(msg.capabilities?.sessionSafetyHistory===true&&msg.safetyCapabilities?.read===true);selected();return false; + requestId=null;store.getState().reset(msg.capabilities?.sessionSafetyHistory===true&&msg.safetyCapabilities?.read===true,msg.safetyCapabilities??null,msg.capabilities?.sessionSafetyEntryCorrelation===true,msg.principalKey?`host:${msg.principalKey}`:`unbound:${crypto.randomUUID()}`);selected();return false; } if(msg.type==="chat_retired"){store.getState().retire(msg.sessionId,msg.historyOwnerIds);if(target&&"sessionId" in target&&target.sessionId===msg.sessionId){requestId=null;target=null;store.getState().unavailable("retired");}return false;} if(msg.type==="safety_history"){ if(msg.requestId!==requestId||!target||!awaitingPage)return true; if(msg.page.cursor!==store.getState().nextCursor)return true; if(!store.getState().page(msg.requestId,msg.page)){read(target);return true;} - if(msg.page.nextCursor)send({type:"safety_read",version:1,requestId:msg.requestId,target,cursor:msg.page.nextCursor}); + if(msg.page.nextCursor)send({type:"safety_read",version:1,requestId:msg.requestId,target,cursor:msg.page.nextCursor,...(store.getState().entryCorrelation?{includeEntries:true as const}:{})}); else{awaitingPage=false;send({type:"safety_subscribe",version:1,requestId:msg.requestId,identity:msg.page.identity,afterRevision:msg.page.highWater,snapshotId:msg.page.snapshotId});}return true; } if(msg.type==="safety_update"){ @@ -53,7 +54,7 @@ export function createSafetyClient(root:BrainUiServices,send:(message:ClientMess return false; }, refresh():void{selected();}, - disconnected():void{requestId=null;store.getState().reset();}, - dispose():void{disposed=true;requestId=null;detach();store.getState().reset();}, + disconnected():void{requestId=null;awaitingPage=true;store.getState().disconnected();}, + dispose():void{disposed=true;requestId=null;detach();detachRefresh();store.getState().reset();}, }; } diff --git a/packages/ui-react/src/lib/safety-evidence.ts b/packages/ui-react/src/lib/safety-evidence.ts new file mode 100644 index 0000000000..a985e71185 --- /dev/null +++ b/packages/ui-react/src/lib/safety-evidence.ts @@ -0,0 +1,32 @@ +import type { SafetyRecord } from "@schlessera/brain-ui-sdk/protocol"; + +type SafetyOccurrence = Extract; +export interface SafetyEvidence { + occurrence:SafetyOccurrence; + exposure:SafetyOccurrence["exposure"]; + decision:Extract|null; +} +const cache=new WeakMap,Map>(); +const tools=new WeakMap,Map>(); +/** Immutable IDs join evidence. Names, timing, arguments and adjacency never do. */ +export function safetyEvidence(records:Record):Map { + const old=cache.get(records);if(old)return old; + const entries=new Map(),latest=new Map(); + for(const r of Object.values(records))if(r.kind==="occurrence"){ + entries.set(r.id,{occurrence:r,exposure:r.exposure,decision:null});latest.set(r.id,BigInt(r.sequence)); + } + for(const r of Object.values(records)){ + const entry=entries.get(r.occurrenceId);if(!entry)continue; + if(r.kind==="safe_decision")entry.decision=r; + if(r.kind==="exposure"&&BigInt(r.sequence)>latest.get(r.occurrenceId)!){entry.exposure=r.state;latest.set(r.occurrenceId,BigInt(r.sequence));} + } + const index=new Map(); + for(const e of entries.values())if(e.occurrence.entry){const key=`${e.occurrence.turnId}\0${e.occurrence.entry.toolUseId}`,group=index.get(key)??[];group.push(e);index.set(key,group);} + cache.set(records,entries);tools.set(records,index);return entries; +} +export function entryEvidence(records:Record,turnId:string|undefined,toolIds:readonly string[]):SafetyEvidence[] { + if(!turnId)return []; + safetyEvidence(records); + const index=tools.get(records)!; + return [...new Set(toolIds)].flatMap(id=>index.get(`${turnId}\0${id}`)??[]); +} diff --git a/packages/ui-react/src/lib/safety-reviewer.ts b/packages/ui-react/src/lib/safety-reviewer.ts new file mode 100644 index 0000000000..3ce53c0180 --- /dev/null +++ b/packages/ui-react/src/lib/safety-reviewer.ts @@ -0,0 +1,58 @@ +import type { SafetyReviewBody } from "@schlessera/brain-ui-sdk/protocol"; +import type { BrainUiServices } from "../root.js"; +import { safetyEvidence } from "./safety-evidence.js"; + +export type SafetyReviewProgress={stage:"pending"|"committed"|"refused"|"unknown";message:string}; +/** Ephemeral, explicit user action only. No persistence, retry or optimistic clear. */ +export function createSafetyReviewer(root:BrainUiServices,changed:(value:SafetyReviewProgress)=>void) { + let controller:AbortController|null=null,disposed=false,committing=false; + const cancel=()=>{ + if(!controller||controller.signal.aborted)return; + controller.abort(); + if(!disposed)changed({stage:committing?"unknown":"refused",message:committing?"Review cancelled; the result is unknown. Refresh evidence to check. No decision will be sent again.":"Review cancelled because its owner or evidence changed. No decision was sent."}); + }; + const offSafety=root.stores.safety.subscribe((s,old)=>{ + if(s.status!=="ready"||s.requestId!==old.requestId||JSON.stringify(s.identity)!==JSON.stringify(old.identity)||!s.capabilities?.review)cancel(); + }); + const offChat=root.stores.chat.subscribe((s,old)=>{if(s.activeSessionId!==old.activeSessionId)cancel();}); + const offAuth=root.authLock.state.subscribe(s=>{if(s.phase!=="active")cancel();}); + return { + async markSafe(occurrenceId:string):Promise { + if(disposed||controller)return; + const s=root.stores.safety.getState(),identity=s.identity,epoch=root.authLock.epoch(),requestId=s.requestId; + const evidence=safetyEvidence(s.records).get(occurrenceId); + if(s.status!=="ready"||!s.capabilities?.review||!identity||!("sessionId" in identity)||root.stores.chat.getState().activeSessionId!==identity.sessionId|| + !evidence||evidence.decision||evidence.exposure!=="finalized"||root.authLock.state.getState().phase!=="active")return; + const body:SafetyReviewBody={version:1,session:identity,occurrenceId,expectedEvidenceRevision:s.revision,verdict:"safe"}; + const owned=controller=new AbortController(); + const live=()=>!disposed&&!owned.signal.aborted&&root.authLock.epoch()===epoch&&root.authLock.state.getState().phase==="active"&& + root.stores.chat.getState().activeSessionId===identity.sessionId&&root.stores.safety.getState().requestId===requestId&& + JSON.stringify(root.stores.safety.getState().identity)===JSON.stringify(identity)&&root.stores.safety.getState().capabilities?.review===true; + const matches=(value:{session:unknown;occurrenceId:string})=>JSON.stringify(value.session)===JSON.stringify(identity)&&value.occurrenceId===occurrenceId; + changed({stage:"pending",message:"Recording your decision…"}); + let dispatched=false; + try { + const prepared=await root.api.safetyPrepare(body,owned.signal); + if(!live())return; + if(!matches(prepared.receipt)||prepared.receipt.stage!=="prepared"||!prepared.receipt.requestId||prepared.receipt.reason|| + root.stores.safety.getState().revision!==body.expectedEvidenceRevision){ + changed({stage:"refused",message:"The evidence changed or this trigger cannot be reviewed. Read the current evidence before trying again."}); + controller=null;root.stores.safety.getState().refresh();return; + } + dispatched=true;committing=true; + const result=await root.api.safetyCommit(prepared.receipt.requestId,body,owned.signal); + if(!live())return; + if(!matches(result.receipt)||result.receipt.requestId!==prepared.receipt.requestId)throw new Error("Different safety receipt"); + const committed=result.receipt.stage==="verdict_committed"&&result.receipt.verdict==="committed"&&!result.receipt.reason; + changed({stage:committed?"committed":"refused",message:committed?"Decision recorded. Reading current restrictions…":"The host refused this decision. Read current evidence before trying again."}); + // Historical receipts and even their live projection do not replace + // newer subscription data. Obtain a complete fresh read instead. + controller=null;root.stores.safety.getState().refresh(); + } catch { + if(!live())return; + changed({stage:dispatched?"unknown":"refused",message:dispatched?"The result is unknown. Refresh evidence to check; this decision will not be sent again.":"Could not prepare this review. Refresh evidence before trying again."}); + } finally {if(controller===owned)controller=null;committing=false;} + }, + dispose(){disposed=true;cancel();offSafety();offChat();offAuth();}, + }; +} diff --git a/packages/ui-react/src/stores/safety-state.ts b/packages/ui-react/src/stores/safety-state.ts index 8707b990e6..70f71dad38 100644 --- a/packages/ui-react/src/stores/safety-state.ts +++ b/packages/ui-react/src/stores/safety-state.ts @@ -1,18 +1,23 @@ /** Host evidence is kept beside chat state, never in its message objects. */ import { createStore } from "zustand/vanilla"; -import type { SafetyIdentity, SafetyPage, SafetyUpdate, SafetyRecord, SafetyHistoryProjection } from "@schlessera/brain-ui-sdk/protocol"; +import type { SafetyCapabilities, SafetyIdentity, SafetyPage, SafetyUpdate, SafetyRecord, SafetyHistoryProjection } from "@schlessera/brain-ui-sdk/protocol"; const same=(a:unknown,b:unknown)=>JSON.stringify(a)===JSON.stringify(b); export interface SafetyState { supported:boolean; status:"unavailable"|"loading"|"partial"|"ready"; reason:string|null; identity:SafetyIdentity|null; projection:SafetyHistoryProjection|null; records:Record; revision:string; snapshotId:string|null; requestId:string|null; normal:boolean; nextCursor:string|null; - reset(supported?:boolean):void; begin(requestId:string):void; page(requestId:string,page:SafetyPage):boolean; + capabilities:SafetyCapabilities|null; historyScopeKey:string|null; entryCorrelation:boolean; refreshTick:number; refresh():void; disconnected():void; + reset(supported?:boolean,capabilities?:SafetyCapabilities|null,entryCorrelation?:boolean,historyScopeKey?:string|null):void; begin(requestId:string):void; page(requestId:string,page:SafetyPage):boolean; update(update:SafetyUpdate):boolean; unavailable(reason:string):void; retire(sessionId?:string,ownerIds?:string[]):void; } const empty={status:"unavailable" as const,reason:"unavailable",identity:null,projection:null,records:{},revision:"0",snapshotId:null,requestId:null,normal:false,nextCursor:null}; export function createSafetyStore(){ - return createStore()((set,get)=>({supported:false,...empty, - reset(supported=false){set({...empty,supported});}, + return createStore()((set,get)=>({supported:false,...empty,capabilities:null,historyScopeKey:null,entryCorrelation:false,refreshTick:0, + refresh(){set({refreshTick:get().refreshTick+1});}, + reset(supported=false,capabilities=null,entryCorrelation=false,historyScopeKey=null){set({...empty,supported,capabilities,entryCorrelation,historyScopeKey});}, + // Retain historical facts while transport is down, without authority or a + // claim of current normal policy. Auth loss/disposal still use reset. + disconnected(){set({status:"unavailable",reason:"disconnected",normal:false,capabilities:null,requestId:null,snapshotId:null,nextCursor:null});}, begin(requestId){set({...empty,supported:get().supported,status:"loading",reason:null,requestId});}, page(requestId,page){ const s=get();if(!s.supported||s.requestId!==requestId)return false; @@ -49,7 +54,7 @@ export function createSafetyStore(){ if(Object.keys(records).length>100000){set({normal:false,status:"partial",reason:"capacity"});return false;} set({records,projection:update.projection,revision:update.toRevision,normal:update.projection.restriction==="normal"});return true; }, - unavailable(reason){set({...empty,supported:get().supported,reason});}, + unavailable(reason){set({...empty,supported:get().supported,reason,...(reason==="unauthorized"?{capabilities:null}:{})});}, retire(sessionId,ownerIds){const i=get().identity;if(i&&"sessionId" in i&&(i.sessionId===sessionId||ownerIds?.includes(i.historyOwnerId)))set({...empty,supported:get().supported,reason:"retired"});}, })); } diff --git a/packages/ui-react/tests/browser/connection-replay.layout.tsx b/packages/ui-react/tests/browser/connection-replay.layout.tsx index 44c17f18f8..b3ecc92f7d 100644 --- a/packages/ui-react/tests/browser/connection-replay.layout.tsx +++ b/packages/ui-react/tests/browser/connection-replay.layout.tsx @@ -18,9 +18,9 @@ async function replayCardReady(host: HTMLElement, phase: "summary" | "header" | // Resolve again on every painted sample, including after cancellation or // replacement. No rejected Animation.finished promise is swallowed. const column = host.querySelector("[data-reading-column]"); - const messages = [...(column?.children ?? [])] as HTMLElement[]; + const messages = [...(column?.querySelectorAll(":scope > [data-arrival-key]") ?? [])] as HTMLElement[]; const header = [...host.querySelectorAll("button")].find(b => b.textContent?.includes("check rope")); - const detail = header?.parentElement?.querySelector(".whitespace-pre-wrap"); + const detail = header?.closest("[data-tool-call]")?.querySelector(".whitespace-pre-wrap"); const expansion = detail?.closest(".overflow-hidden"); const visible = (el: HTMLElement | undefined | null) => !!el?.isConnected && el.getClientRects().length > 0 && el.getBoundingClientRect().height > 0 && el.getBoundingClientRect().width > 0 @@ -83,7 +83,7 @@ for (const { theme, width } of [{ theme: "dark", width: 320 }, { theme: "light", const field = host.querySelector("textarea[data-composer]")!; field.focus(); await frame(); - const nodes = [...column.children]; + const nodes = [...column.querySelectorAll(":scope > [data-arrival-key]")]; expect(nodes.length, "nonempty transcript with a suffix to protect").toBe(30); expect(scroller.scrollHeight - scroller.clientHeight).toBeGreaterThan(500); const first = nodes.find((node) => node.getBoundingClientRect().bottom > scroller.getBoundingClientRect().top)!; @@ -176,10 +176,10 @@ for (const finished of [false, true]) for (const splitRun of [false, true]) for expect(header, "a real live tool card is present").toBeDefined(); await page.getByRole("button", { name: /check rope/ }).click(); await replayCardReady(host, "expanded"); - const detail = header.parentElement!.querySelector(".whitespace-pre-wrap"); + const detail = header.closest("[data-tool-call]")!.querySelector(".whitespace-pre-wrap"); expect(detail, "the card is expanded before the fault").not.toBeNull(); const field = host.querySelector("textarea[data-composer]")!; field.focus(); await frame(); - const message = header.closest("[data-reading-column]")!.children[1]!; + const message = header.closest("[data-arrival-key]")!; net.drop({ announce: true }); await frame(); net.recover(); ui.connection.reconnectNow(); await expect.poll(() => net.socket()?.readyState).toBe(1); const replayEnd = splitRun && !finished ? " Rope held. Live oars." : " Rope held."; @@ -206,7 +206,7 @@ for (const finished of [false, true]) for (const splitRun of [false, true]) for // This control tests the readiness helper, not replay behavior or Motion duration. test("expanded readiness follows a cancelled animation's replacement", async (ctx) => { const host = document.createElement("div"); - host.innerHTML = '
check rope
'; + host.innerHTML = '
check rope
'; document.body.append(host); const owner = host.querySelector(".overflow-hidden")!; const first = owner.animate([{ transform: "translateY(6px)" }, { transform: "none" }], { duration: 500 }); diff --git a/packages/ui-react/tests/browser/conversation-contextual.offline.tsx b/packages/ui-react/tests/browser/conversation-contextual.offline.tsx index 923125f534..71f4e80eba 100644 --- a/packages/ui-react/tests/browser/conversation-contextual.offline.tsx +++ b/packages/ui-react/tests/browser/conversation-contextual.offline.tsx @@ -1009,6 +1009,9 @@ for (const theme of ["light", "dark"] as const) for (const width of [320, 1280]) await expect.poll(() => s.host.querySelectorAll("[data-arrival-key]").length).toBe(40); const scroll = s.host.querySelector("[data-arrival-key]")!.parentElement!.parentElement!; scroll.scrollTop = 0; scroll.dispatchEvent(new Event("scroll")); + // Establish the reveal button's browser interaction position before measuring + // prepend recovery; the safety notice can move it within the clipped viewport. + page.getByRole("button", { name: /Show .*earlier/ }).element().scrollIntoView({ block: "center", behavior: "instant" }); const anchor = s.host.querySelector("[data-arrival-key]")!; const top = anchor.getBoundingClientRect().top; await userEvent.click(page.getByRole("button", { name: /Show .*earlier/ })); diff --git a/packages/ui-react/tests/browser/promoted-links.layout.tsx b/packages/ui-react/tests/browser/promoted-links.layout.tsx index 6d8d449057..deb30342f8 100644 --- a/packages/ui-react/tests/browser/promoted-links.layout.tsx +++ b/packages/ui-react/tests/browser/promoted-links.layout.tsx @@ -66,7 +66,7 @@ for (const width of [320, 1280]) { socket.deliver({ type: "status", sessionId: SESSION, turnId: TURN, status: "idle" }); await frame(); const column = host.querySelector("[data-reading-column]")!; - const bubbles = [...column.children]; + const bubbles = [...column.querySelectorAll(":scope > [data-arrival-key]")]; const answer = bubbles.at(-1)!; // A link into turn temp is not a file in the brain: the reader cannot open it. await expect.poll(() => answer.textContent).toContain("voyage report"); @@ -94,7 +94,7 @@ for (const width of [320, 1280]) { // The same words, the same bubbles, nothing added: no marker, no remount. for (const words of ["voyage report", "is ready; Penelope has", "her copy"]) expect(answer.textContent).toContain(words); expect(answer.isConnected && removed === 0, "no message was removed even briefly").toBe(true); - expect([...column.children]).toEqual(bubbles); + expect([...column.querySelectorAll(":scope > [data-arrival-key]")]).toEqual(bubbles); expect(host.textContent).not.toMatch(/expired|promot|copied|moved/i); // No reload: nothing was asked of the host. expect(net.frames.slice(sentBefore).map((f) => JSON.parse(String(f.data)).type)).toEqual([]); diff --git a/packages/ui-react/tests/browser/safety-review.layout.tsx b/packages/ui-react/tests/browser/safety-review.layout.tsx new file mode 100644 index 0000000000..a4d78007ac --- /dev/null +++ b/packages/ui-react/tests/browser/safety-review.layout.tsx @@ -0,0 +1,132 @@ +/// +import {afterAll,afterEach,beforeAll,expect,test} from 'vitest'; +import {commands,page,userEvent} from 'vitest/browser'; +import {createRoot,type Root} from 'react-dom/client'; +import {flushSync} from 'react-dom'; +import {createBrainUiRoot,type BrainUiRoot} from '../../src/root.js'; +import {BrainUiProvider} from '../../src/root-context.js'; +import {MessageBubble} from '../../src/components/chat/message-bubble.js'; +import {createSafetyClient} from '../../src/lib/safety-client.js'; +import {SessionSafety} from '../../src/components/chat/safety-indicator.js'; +import {parseServerMessage} from '@schlessera/brain-ui-sdk/schemas'; +import type {ChatMessage} from '../../src/stores/chat-store.js'; +import type {ClientMessage,SafetyPage} from '@schlessera/brain-ui-sdk/protocol'; +let fixture:{id:string;url:string}|undefined,ui:BrainUiRoot|undefined,socket:WebSocket|undefined,renderer:Root|undefined,host:HTMLDivElement|undefined; +let safetyClient:ReturnType|undefined; +let styles:HTMLStyleElement;const oldTheme=document.documentElement.dataset.theme,viewport={width:innerWidth,height:innerHeight}; +beforeAll(async()=>{styles=document.createElement('style');styles.textContent=await commands.formConsumerStyles();document.head.append(styles);}); +afterAll(async()=>{styles.remove();await page.viewport(viewport.width,viewport.height);}); +async function disposeView(){safetyClient?.dispose();safetyClient=undefined;if(renderer)flushSync(()=>renderer!.unmount());renderer=undefined;ui?.dispose();ui=undefined;socket?.close();socket=undefined;host?.remove();host=undefined;} +afterEach(async()=>{await disposeView();if(fixture)await commands.safetyServer({op:'stop',id:fixture.id});fixture=undefined;if(oldTheme===undefined)delete document.documentElement.dataset.theme;else document.documentElement.dataset.theme=oldTheme;}); +const patch=(patch:Record={})=>commands.safetyServer({op:'set',id:fixture!.id,patch}) as Promise<{page:SafetyPage;commits:number;prepares:number;decisions:Array<{occurrence_id:string}>}>; +const noop=()=>{}; +const message:ChatMessage={id:'odysseus-answer',turnId:'voyage',role:'assistant',content:'Voyage notes retained.',isStreaming:false,timestamp:Date.UTC(2026,6,12,10), + toolCalls:[{id:'tool_a',name:'WebFetch',inputJson:'{}',input:{url:'https://example.com/odyssey'},output:'Odysseus voyage notes',status:'complete'},{id:'tool_c',name:'WebFetch',inputJson:'{}',input:{url:'https://example.com/odyssey'},output:'Penelope voyage notes',status:'complete'}], + parts:[{kind:'tool',toolIndex:0},{kind:'tool',toolIndex:1},{kind:'text',text:'Voyage notes retained.'}]}; +async function view(){ + const f=fixture!; + ui=createBrainUiRoot({storage:null,config:{backendUrl:f.url},request:async(url,init)=>{ + if(!String(url).includes('/safety/reviews/'))return Response.json({providers:[]}); + const result=await patch({action:'request',path:new URL(url).pathname,body:init?.body}) as unknown as {status:number;body:unknown}; + if(init?.signal?.aborted)throw new DOMException('Aborted','AbortError');return Response.json(result.body,{status:result.status}); + }}); + const frames:unknown[]=[],sent:unknown[]=[];const current=ui;current.stores.chat.setState({activeSessionId:'ithaca',buffers:{ithaca:{messages:[message],isStreaming:false,askUser:null,lastTouched:message.timestamp}}}); + current.stores.connection.getState().setWsStatus('connected'); + socket=new WebSocket(f.url.replace('http:','ws:')+'/ws');const ws=socket; + current.connection.send=(m:ClientMessage)=>{sent.push(m);if(ws.readyState!==WebSocket.OPEN)return false;ws.send(JSON.stringify(m));return true;}; + const client=safetyClient=createSafetyClient(current,m=>{sent.push(m);if(socket?.readyState!==WebSocket.OPEN)return false;socket.send(JSON.stringify(m));return true;}); + ws.onopen=()=>ws.send(JSON.stringify({type:'client_hello',protocolRev:5,capabilities:{sessionSafetyHistory:true,chatDeletion:true}})); + ws.onmessage=e=>{frames.push(JSON.parse(String(e.data)));const parsed=parseServerMessage(String(e.data));if(!parsed.ok)throw new Error(parsed.error);client.frame(parsed.message);}; + host=document.createElement('div');host.style.maxWidth='100%';document.body.append(host);renderer=createRoot(host); + flushSync(()=>renderer!.render()); + try{await expect.poll(()=>current.stores.safety.getState().status,{timeout:5000}).toBe('ready');}catch(error){throw new Error(`${String(error)} Frames:${JSON.stringify(frames)} Sent:${JSON.stringify(sent)} Safety:${JSON.stringify(current.stores.safety.getState())} Session:${current.stores.chat.getState().activeSessionId}`);} +} +async function scene(width:number,theme:string){await page.viewport(width,900);document.documentElement.dataset.theme=theme;fixture=await commands.safetyServer({op:'start'}) as typeof fixture;await view();} +function buttonForTool(){const all=[...host!.querySelectorAll('[data-safety-indicator] button')];return all.find(b=>b.getAttribute('aria-label')?.includes('2 unresolved'))!;} + +for(const width of [320,1280])for(const theme of ['light','dark'])test(`${width} ${theme}: collapsed counts, native touch, exact scope, A/B/C and reload`,async()=>{ + await scene(width,theme); + expect(host!.textContent,'OPAQUE_TRAFFIC_HAS_OWN_NAMED_TURN_EVENT').toContain('Network input; tool attribution unavailable'); + const indicator=buttonForTool();expect(indicator,'COLLAPSED_RUN_RETAINS_BOTH_TRIGGERS').toBeTruthy(); + const box=indicator.getBoundingClientRect();expect(box.width).toBeGreaterThanOrEqual(44);expect(box.height).toBeGreaterThanOrEqual(44); + indicator.focus();await expect.poll(()=>getComputedStyle(indicator.parentElement!.querySelector('[role=tooltip]')!).opacity).toBe('1'); + const tooltipLayer=getComputedStyle(indicator.parentElement!.querySelector('[role=tooltip]')!).zIndex; + await commands.rankTap({x:box.x+box.width/2,y:box.y+box.height/2}); + const panel=page.getByRole('dialog',{name:'Safety trigger details'});await expect.element(panel).toBeVisible(); + const popoverLayer=getComputedStyle(document.documentElement).getPropertyValue('--bk-z-popover').trim();expect(popoverLayer).not.toBe(''); + expect({tooltip:tooltipLayer,details:getComputedStyle(document.querySelector('[data-safety-details]')!).zIndex},'SAFETY_SURFACES_USE_NAMED_POPOVER_LAYER').toEqual({tooltip:popoverLayer,details:popoverLayer}); + expect(indicator.getAttribute('aria-expanded')).toBe('true');expect(document.querySelector('[data-safety-details]')!.textContent).toContain('Source provenance unavailable'); + await userEvent.click(page.getByRole('button',{name:'Mark as safe',exact:true}).first()); + expect(document.querySelector('[data-safety-details]')!.textContent).toContain('Only this trigger'); + expect(document.querySelector('[data-safety-details]')!.textContent).not.toMatch(/trust this origin|future repositories|Verified safe/i); + await userEvent.click(page.getByRole('button',{name:'Mark this trigger as safe',exact:true})); + await expect.poll(()=>ui!.stores.safety.getState().projection?.unresolvedCount,{timeout:5000}).toBe(2); + const state=await patch();expect(state.commits,'ONE_EXPLICIT_VERDICT').toBe(1);expect(state.decisions).toHaveLength(1); + expect(host!.textContent).not.toContain('Normal policy restored'); + const reopener=indicator; + await expect.element(panel).toBeVisible(); + await expect.element(page.getByText('Marked safe by you',{exact:true}).first()).toBeVisible(); + await page.screenshot({element:document.querySelector('[data-safety-details]') as HTMLElement,path:`../../.vitest-attachments/safety-review/${theme}-${width}.png`}); + const bounds=document.querySelector('[data-safety-details]')!.getBoundingClientRect();expect(bounds.left).toBeGreaterThanOrEqual(0);expect(bounds.right).toBeLessThanOrEqual(innerWidth); + await userEvent.keyboard('{Escape}');expect(document.querySelector('[data-safety-details]')).toBeNull();expect(document.activeElement).toBe(reopener); + await userEvent.keyboard('{Enter}');await expect.element(panel).toBeVisible();await userEvent.click(page.getByRole('button',{name:'Outside safety details'}));expect(document.querySelector('[data-safety-details]')).toBeNull(); + await disposeView();await view();expect((await patch()).commits,'RELOAD_NEVER_REPLAYS_A_VERDICT').toBe(1);expect(ui!.stores.safety.getState().projection?.unresolvedCount).toBe(2); +}); + +test('open delivery, pruning, recorder loss and explicit unavailable evidence remain restrictive',async()=>{ + await scene(320,'dark');await patch({action:'add',id:'tool_open',finalized:false}); + await expect.poll(()=>ui!.stores.safety.getState().projection?.unresolvedCount,{timeout:5000}).toBe(4); + const fallback=host!.querySelector('[data-safety-turn-event] button')!;await userEvent.click(fallback); + expect(document.querySelector('[data-safety-details]')!.textContent,'OPEN_DELIVERY_EXPLAINS_REFUSAL').toContain('Input is still arriving'); + const section=[...document.querySelectorAll('[data-safety-trigger]')].find(e=>e.textContent?.includes('Input is still arriving'))!; + expect(section.querySelector('[role=button]'),'OPEN_DELIVERY_OFFERS_NO_GRANT').toBeNull(); + await userEvent.keyboard('{Escape}');await patch({action:'prune'});ui!.stores.safety.getState().refresh();await expect.poll(()=>ui!.stores.safety.getState().status).toBe('ready'); + expect(host!.querySelectorAll('[data-safety-indicator]').length).toBeGreaterThan(0); + await patch({action:'loss'});await expect.poll(()=>ui!.stores.safety.getState().projection?.reasons,{timeout:5000}).toContain('recording_failed'); + expect(host!.textContent).toContain('Recording is unavailable');expect(host!.textContent).not.toContain('Normal policy restored');expect((await patch()).commits).toBe(0); +}); + +test('only a complete healthy zero-trigger read restores normal; partial state never does',async()=>{ + await scene(320,'light'); + for(let remaining=3;remaining>0;remaining--){ + const button=[...host!.querySelectorAll('[data-safety-indicator] button')].find(b=>b.getClientRects().length>0&&b.getAttribute('aria-label')?.startsWith('Safety restrictions'))!; + await userEvent.click(button);await userEvent.click(page.getByRole('button',{name:'Mark as safe',exact:true}).first()); + await userEvent.click(page.getByRole('button',{name:'Mark this trigger as safe',exact:true})); + await expect.poll(()=>ui!.stores.safety.getState().status==='ready'&&ui!.stores.safety.getState().projection?.unresolvedCount===remaining-1,{timeout:5000}).toBe(true); + await userEvent.keyboard('{Escape}'); + } + expect(host!.textContent,'COMPLETE_ZERO_UNRESOLVED_RESTORES_NORMAL').toContain('Normal policy restored'); + expect((await patch()).commits).toBe(3); + flushSync(()=>ui!.stores.safety.setState({status:'partial',normal:true})); + expect(host!.textContent,'PARTIAL_STATE_CANNOT_PRINT_NORMAL').not.toContain('Normal policy restored'); +}); + +test('read-only clients keep evidence without grant controls and retirement purges an open panel',async()=>{ + await scene(320,'dark');flushSync(()=>ui!.stores.safety.setState({capabilities:{...ui!.stores.safety.getState().capabilities!,review:false}})); + await userEvent.click(buttonForTool());const panel=page.getByRole('dialog',{name:'Safety trigger details'});await expect.element(panel).toBeVisible(); + expect(document.querySelector('[data-safety-details]')!.textContent).toContain('Only the authenticated owner'); + expect([...document.querySelectorAll('[data-safety-details] [role=button]')].some(e=>e.textContent==='Mark as safe'),'READ_ONLY_VIEW_OFFERS_NO_GRANT').toBe(false); + await patch({action:'retire'});await expect.poll(()=>ui!.stores.safety.getState().reason,{timeout:5000}).toBe('retired'); + expect(document.querySelector('[data-safety-details]'),'RETIRED_HISTORY_PURGES_OPEN_DETAILS').toBeNull(); + expect(host!.querySelectorAll('[data-safety-indicator]').length).toBe(0);expect(Object.keys(ui!.stores.safety.getState().records)).toEqual([]); +}); + +test('same-owner disconnect and replay keep read-only evidence geometry without resuming a decision',async()=>{ + await scene(320,'dark');const indicator=buttonForTool(),notice=host!.querySelector('[data-session-safety]')!; + await userEvent.click(indicator);await userEvent.click(page.getByRole('button',{name:'Mark as safe',exact:true}).first()); + const before=notice.getBoundingClientRect(),buttons=host!.querySelectorAll('[data-safety-indicator]').length; + const client=safetyClient!,current=ui!;socket!.close();flushSync(()=>client.disconnected()); + expect(host!.querySelectorAll('[data-safety-indicator]').length,'DISCONNECT_RETAINS_READ_ONLY_INDICATORS').toBe(buttons); + expect(notice.getBoundingClientRect().height,'DISCONNECT_RETAINS_NOTICE_HEIGHT').toBe(before.height); + expect(current.stores.safety.getState().normal,'DISCONNECTED_EVIDENCE_CANNOT_RESTORE_NORMAL').toBe(false); + expect(document.querySelector('[data-safety-details]')!.textContent).toContain('Current evidence is unavailable'); + expect(document.querySelector('[data-safety-details]')!.textContent).not.toContain('Mark this trigger as safe'); + socket=new WebSocket(fixture!.url.replace('http:','ws:')+'/ws');const next=socket; + next.onopen=()=>next.send(JSON.stringify({type:'client_hello',protocolRev:5,capabilities:{sessionSafetyHistory:true,chatDeletion:true}})); + next.onmessage=e=>{const parsed=parseServerMessage(String(e.data));if(!parsed.ok)throw new Error(parsed.error);client.frame(parsed.message);}; + await expect.poll(()=>current.stores.safety.getState().status,{timeout:5000}).toBe('ready'); + expect(notice.getBoundingClientRect().height,'REPLAY_RETAINS_NOTICE_HEIGHT').toBe(before.height); + expect(indicator.isConnected,'REPLAY_RETAINS_ORIGINAL_INDICATOR_NODE').toBe(true); + expect(document.querySelector('[data-safety-details]')!.textContent,'RECONNECT_DISCARDS_UNSUBMITTED_SCOPE_CHOICE').not.toContain('Mark this trigger as safe'); + expect((await patch()).commits,'RECONNECT_DOES_NOT_SEND_A_DECISION').toBe(0); +}); diff --git a/packages/ui-react/tests/browser/safety-server-command.ts b/packages/ui-react/tests/browser/safety-server-command.ts new file mode 100644 index 0000000000..ffabdac4eb --- /dev/null +++ b/packages/ui-react/tests/browser/safety-server-command.ts @@ -0,0 +1,31 @@ +/// +import { spawn, type ChildProcess } from "node:child_process"; +import { once } from "node:events"; +import { resolve } from "node:path"; +import type { BrowserCommand } from "vitest/node"; +type Op = { op: "start" } | { op: "set"; id: string; patch: Record } | { op: "stop"; id: string }; +const servers = new Map string }>(); +/** Real owner HTTP and WS evidence comes from a loopback server inside the pinned offline container. */ +export const safetyServer: BrowserCommand<[Op], unknown> = async (_ctx, input) => { + if (input.op === "start") { + const child = spawn(process.env.BUN_BIN ?? "bun", ["--preload", resolve("../../scripts/test-network-child-preload.ts"), resolve("../ui-react/tests/fixtures/safety-browser-server.ts")], + { cwd: resolve("../.."), env: process.env, stdio: ["ignore", "pipe", "pipe"] }); + let stdout = "", stderr = ""; child.stderr!.on("data", bytes => { stderr += String(bytes); }); + const url = await new Promise((resolve, reject) => { + const timer = setTimeout(() => { child.kill(); reject(new Error(`Safety fixture timed out: ${stderr}`)); }, 15_000); + child.once("error", error => { clearTimeout(timer); reject(error); }); + child.once("exit", (code, signal) => { clearTimeout(timer); reject(new Error(`Safety fixture exited ${code}/${signal}: ${stderr}`)); }); + child.stdout!.on("data", bytes => { stdout += String(bytes); if (stdout.includes("\n")) { clearTimeout(timer); try { resolve(JSON.parse(stdout.split("\n")[0]!).url); } catch (error) { reject(error); } } }); + }); + const id = crypto.randomUUID(); servers.set(id, { process: child, url, diagnostics: () => stderr }); return { id, url }; + } + const server = servers.get(input.id); if (!server) throw new Error("Unknown safety fixture"); + if (input.op === "set") { + const response = await fetch(`${server.url}/fixture`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(input.patch) }); + if (!response.ok) throw new Error(`Safety fixture failed: ${response.status} ${server.diagnostics()}`); + return response.json(); + } + const ended = once(server.process, "exit"); server.process.kill("SIGTERM"); const [code, signal] = await ended; + servers.delete(input.id); if (code !== 0 || signal !== null) throw new Error(`Safety fixture cleanup failed ${code}/${signal}: ${server.diagnostics()}`); +}; +declare module "vitest/browser" { interface BrowserCommands { safetyServer: (input: Op) => Promise } } diff --git a/packages/ui-react/tests/browser/tool-renderer-boundary.layout.tsx b/packages/ui-react/tests/browser/tool-renderer-boundary.layout.tsx index eda4b2b6b3..4e1e6176a7 100644 --- a/packages/ui-react/tests/browser/tool-renderer-boundary.layout.tsx +++ b/packages/ui-react/tests/browser/tool-renderer-boundary.layout.tsx @@ -38,7 +38,7 @@ function mount(view: (props: { calls: ToolCall[] }) => ReactNode, calls: ToolCal return render; } const reports = (spy: ReturnType) => spy.mock.calls.filter((args: unknown[]) => String(args[0]).includes("renderer for the odyssey_rigging tool failed")); -const headers = () => [...host!.querySelectorAll(".relative.ml-1 > div > button")]; +const headers = () => [...host!.querySelectorAll("[data-tool-call] > div > button")]; test("a renderer that throws from its header falls back to the generic view and keeps the other rows", async () => { const errors = vi.spyOn(console, "error").mockImplementation(() => {}); diff --git a/packages/ui-react/tests/connection-continuity-runtime.test.ts b/packages/ui-react/tests/connection-continuity-runtime.test.ts index 0b0e047b19..9081083cbd 100644 --- a/packages/ui-react/tests/connection-continuity-runtime.test.ts +++ b/packages/ui-react/tests/connection-continuity-runtime.test.ts @@ -619,7 +619,7 @@ async function mark(page: Page) { const field = document.querySelector("textarea[data-composer]")!; const column = document.querySelector("[data-reading-column]")!; const top = column.parentElement!.getBoundingClientRect().top; - const nodes = [...column.children]; + const nodes = [...column.querySelectorAll(":scope > [data-arrival-key]")]; const first = nodes.find((n) => n.getBoundingClientRect().bottom > top + 1)!; const images = [...column.querySelectorAll("img")]; const pills = [...document.querySelectorAll('[data-row-half="right"] [data-pill]')]; @@ -817,7 +817,7 @@ async function finishRecoveredTurn(s: Scene, cell: Cell) { expect(await s.page.evaluate(() => { const marks = (window as unknown as { __marks: { nodes: Element[] } }).__marks; const column = document.querySelector("[data-reading-column]")!; - return marks.nodes.at(-1)?.isConnected && column.children[1] === marks.nodes.at(-1); + return marks.nodes.at(-1)?.isConnected && column.querySelectorAll(":scope > [data-arrival-key]")[1] === marks.nodes.at(-1); }), "recovered text and the terminal replay kept the original answer node").toBe(true); expect(await s.page.locator('[data-row-half="right"] [data-pill]').count(), "the queued follow-up was taken").toBe(0); } catch (error) { diff --git a/packages/ui-react/tests/fixtures/safety-browser-server.ts b/packages/ui-react/tests/fixtures/safety-browser-server.ts new file mode 100644 index 0000000000..8bfc72703f --- /dev/null +++ b/packages/ui-react/tests/fixtures/safety-browser-server.ts @@ -0,0 +1,41 @@ +/** Keyless loopback browser fixture: real writer, owner HTTP and WS sidecars. */ +import {retireChat} from '../../../ui-server/src/ws/chat-lifecycle.js'; +import {Hono} from 'hono'; +import {safetyHistoryFixture} from '../../../ui-server/tests/helpers/safety-history-fixture.js'; +import {createSafetyCollector} from '../../../ui-server/src/governance/safety-collector.js'; +import {createWsUpgrade,websocket} from '../../../ui-server/src/ws/connection.js'; +import {pruneSafetyDetail} from '../../../ui-server/src/governance/safety-store.js'; +import type {AppEnv} from '../../../ui-server/src/app-env.js'; +const f=await safetyHistoryFixture(true,true),at=Date.UTC(2026,6,12,10); +const observedWrites={...f.writes,firstTaint:(input:Parameters[0])=>f.writes.firstTaint({...input,at}),record:(input:Parameters[0])=>f.writes.record({...input,at})}; +const collector=createSafetyCollector(f.db,observedWrites,{turnId:'voyage',bindingId:f.bindingId,backendId:'claude',sessionId:()=> 'ithaca',shellProxied:()=>true,signal:new AbortController().signal}); +async function tool(id:string,finalized=true){await collector.begin(id,'WebFetch',{url:'https://example.com/odyssey'});if(finalized)await collector.result(id,'WebFetch','Odysseus reviews voyage notes.',true);} +await tool('tool_a');await f.add('B',true);await tool('tool_c'); +const app=new Hono(); +// Test-only bootstrap supplies the fixture principal to a real WS host. HTTP +// mutations below still traverse the actual cookie/Origin/owner route stack. +app.get('/ws',async(c,next)=>{c.set('principal',f.principal);return next();},createWsUpgrade(f.host)); +const inner=f.url.replace('ws:','http:').replace('/ws','');let commits=0,prepares=0; +app.post('/fixture',async c=>{ + const input=await c.req.json(); + if(input.action==='request'){ + if(typeof input.path!=='string'||!/^\/api\/sessions\/ithaca\/safety\/reviews\/(prepare|[A-Za-z0-9_-]+\/commit)$/.test(input.path))return c.json({error:'invalid fixture route'},400); + if(input.path.endsWith('/commit'))commits++;else prepares++; + const response=await fetch(inner+input.path,{method:'POST',headers:{cookie:f.cookie,origin:inner,'content-type':'application/json'},body:input.body}); + return c.json({status:response.status,body:await response.json()}); + } + if(input.action==='retire'){ + const result=retireChat(f.db,{operationId:'odysseus-retire',principalId:f.principal.id,target:{sessionId:'ithaca'},expected:{backendId:'claude',generation:1},removableBackends:['claude'],at:Date.now()}); + if(result.status!=='retired')throw new Error('Fixture retirement failed');f.host.chatRetired(f.principal.id,result);return c.json({retired:true,commits,prepares}); + } + if(input.action==='add')await tool(input.id??'tool_d',input.finalized!==false); + if(input.action==='prune')pruneSafetyDetail(f.db,Number.MAX_SAFE_INTEGER); + if(input.action==='loss')await f.writes.safetyFail('voyage'); + f.history.poll(); + const page=await f.history.read(f.principal,{sessionId:'ithaca'},null,100,true); + return c.json({page,commits,prepares,decisions:f.db.query('SELECT occurrence_id FROM safety_decisions').all()}); +}); +const server=Bun.serve({hostname:'127.0.0.1',port:0,fetch:app.fetch,websocket}); +console.log(JSON.stringify({url:`http://127.0.0.1:${server.port}`})); +let closing=false;async function close(){if(closing)return;closing=true;try{server.stop(true);await f.close();process.exit(0);}catch(error){console.error(error);process.exit(1);}} +process.on('SIGTERM',()=>void close());process.on('SIGINT',()=>void close()); diff --git a/packages/ui-react/tests/safety-client.test.ts b/packages/ui-react/tests/safety-client.test.ts index 4ac4044924..da0f82b054 100644 --- a/packages/ui-react/tests/safety-client.test.ts +++ b/packages/ui-react/tests/safety-client.test.ts @@ -45,6 +45,36 @@ test("an old host receives no safety read or unsubscribe frames and remains expl } }); +test('entry correlation is requested only after the independent host capability',()=>{ + for(const entries of [false,true]){ + const chat=createStore<{activeSessionId:string|null}>(()=>({activeSessionId:'ithaca'})),safety=createSafetyStore(),sent:ClientMessage[]=[]; + const root={stores:{chat,safety}} as unknown as BrainUiServices,client=createSafetyClient(root,m=>{sent.push(m);return true;}); + try{ + client.frame({type:'server_hello',protocolRev:5,capabilities:{sessionSafetyHistory:true,...(entries?{sessionSafetyEntryCorrelation:true}:{})},safetyCapabilities:{version:1,read:true,review:false,originRules:false,repositoryRules:false,recipientRules:false,readOnlyReason:'owner_required',detectorVersion:1,limits:{pageRecords:100,frameBytes:262144,cursorBytes:512,cursorLifetimeMs:300000}}}); + const read=sent.find(m=>m.type==='safety_read');expect(read?.type).toBe('safety_read'); + if(entries)expect(read).toHaveProperty('includeEntries',true);else expect(read,'OLD_HOST_NEVER_RECEIVES_UNKNOWN_READ_FIELD').not.toHaveProperty('includeEntries'); + expect(safety.getState().capabilities?.review).toBe(false); + safety.getState().refresh();expect(sent.filter(m=>m.type==='safety_read')).toHaveLength(2);expect(sent.every(m=>!m.type.includes('review'))).toBe(true); + }finally{client.dispose();} + } +}); + +test('disconnect retains only read-only facts; stale frames and a different owner cannot regain authority',async()=>{ + const {safetyHistoryFixture}=await import('../../ui-server/tests/helpers/safety-history-fixture'); + const f=await safetyHistoryFixture(true,true),chat=createStore<{activeSessionId:string|null}>(()=>({activeSessionId:'ithaca'})),safety=createSafetyStore(),sent:ClientMessage[]=[]; + const root={stores:{chat,safety}} as unknown as BrainUiServices,client=createSafetyClient(root,m=>{sent.push(m);return true;}); + try{ + const a=await f.add('A'),hello={type:'server_hello' as const,protocolRev:5,principalKey:'odysseus_owner',capabilities:{sessionSafetyHistory:true},safetyCapabilities:f.reviews!.capabilities(f.principal)}; + client.frame(hello);const read=sent.find(m=>m.type==='safety_read');if(read?.type!=='safety_read')throw new Error('Missing read'); + const page=await f.history.read(f.principal,{sessionId:'ithaca'});client.frame({type:'safety_history',requestId:read.requestId,page}); + client.disconnected();expect(safety.getState().records[a.id],'DISCONNECT_RETAINS_IMMUTABLE_FACT').toBeDefined();expect(safety.getState().capabilities,'DISCONNECT_DISCARDS_REVIEW_AUTHORITY').toBeNull();expect(safety.getState().normal).toBe(false); + client.frame({type:'safety_update',update:{version:1,identity:page.identity,fromRevision:page.highWater,toRevision:String(BigInt(page.highWater)+1n),projection:{...page.projection,evidenceRevision:String(BigInt(page.highWater)+1n),restriction:'normal',unresolvedCount:0},records:[]}}); + expect(safety.getState().projection?.unresolvedCount,'LATE_SOCKET_UPDATE_CANNOT_LOOSEN_DISCONNECTED_FACTS').toBe(1); + client.frame({...hello,principalKey:'penelope_owner'});expect(safety.getState().records,'NEW_OWNER_PURGES_OLD_HISTORY_CACHE').toEqual({});expect(safety.getState().historyScopeKey).toBe('host:penelope_owner'); + const keys=[safety.getState().historyScopeKey];client.frame({...hello,principalKey:undefined});keys.push(safety.getState().historyScopeKey);client.frame({...hello,principalKey:undefined});expect(safety.getState().historyScopeKey,'MISSING_OWNER_KEY_NEVER_REUSES_A_DISPLAY_PARTITION').not.toBe(keys.at(-1)); + }finally{client.dispose();await f.close();} +}); + test("host-only and invalid selections remain unavailable across selection, reload and reconnect", () => { for (const id of ["dialogue:7f9e2c1a-0000-4000-8000-000000000001", "voyage notes", "", "a".repeat(129)]) { const { chat, safety, sent, client, checkWire } = supportedClient(id); diff --git a/packages/ui-react/tests/safety-evidence.test.ts b/packages/ui-react/tests/safety-evidence.test.ts new file mode 100644 index 0000000000..3a17eb60cb --- /dev/null +++ b/packages/ui-react/tests/safety-evidence.test.ts @@ -0,0 +1,21 @@ +import {test,expect} from 'bun:test'; +import {entryEvidence,safetyEvidence} from '../src/lib/safety-evidence'; +import type {SafetyRecord} from '@schlessera/brain-ui-sdk/protocol'; +const occurrence=(id:string,turnId:string,toolUseId?:string):SafetyRecord=>({kind:'occurrence',id,sequence:'1',observedAt:Date.UTC(2026,6,12,10),turnId,bindingId:'voyage_binding',occurrenceId:id,detailPruned:false,epochId:'voyage_binding',detector:'tool_web_input',source:'web_fetch',operationId:'tool_a',signalId:'signal_a',exposureId:'exposure_a',exposure:'open',summary:'Recorded input exposure',provenance:null,...(toolUseId?{entry:{kind:'tool',toolUseId}}:{})}); + +test('only an explicit exact turn/tool pair can attach evidence, including repeated tool IDs',()=>{ + const records={a:occurrence('a','turn_a','tool_a'),b:occurrence('b','turn_b','tool_a'),legacy:occurrence('legacy','turn_a')}; + expect(entryEvidence(records,'turn_a',['tool_a']).map(e=>e.occurrence.id),'EXACT_TURN_TOOL_JOIN').toEqual(['a']); + expect(entryEvidence(records,'turn_c',['tool_a']),'DIFFERENT_TURN_CANNOT_BORROW_TOOL_ID').toEqual([]); + expect(entryEvidence(records,undefined,['tool_a'])).toEqual([]); + expect(entryEvidence(records,'turn_a',['other'])).toEqual([]); + expect(entryEvidence({legacy:records.legacy},'turn_a',['tool_a']),'OPERATION_ID_NEVER_STANDS_IN_FOR_TOOL_ID').toEqual([]); +}); + +test('exposure and human decisions join only their immutable occurrence, independent of delivery order',()=>{ + const a=occurrence('a','turn_a','tool_a'),b=occurrence('b','turn_a','tool_b'); + const record=(id:string,sequence:string,occurrenceId:string,state:'finalized'|'interrupted_unknown'):SafetyRecord=>({kind:'exposure',id,sequence,observedAt:0,turnId:'turn_a',bindingId:'voyage_binding',occurrenceId,detailPruned:false,state}); + const records={a,b,newer:record('final','3','a','finalized'),older:record('old','2','a','interrupted_unknown'),decision:{id:'decision',sequence:'4',observedAt:1,turnId:'turn_a',bindingId:'voyage_binding',occurrenceId:'a',detailPruned:false,kind:'safe_decision',session:{sessionId:'ithaca',historyOwnerId:'odysseus',historyGeneration:'1'},requestId:'request',principalId:'owner',verdict:'safe',channel:'owner_history'} as SafetyRecord}; + const entries=safetyEvidence(records);expect(entries.get('a')?.exposure).toBe('finalized');expect(entries.get('a')?.decision?.id).toBe('decision'); + expect(entries.get('b')?.decision,'A_VERDICT_NEVER_RESOLVES_B').toBeNull();expect(entries.get('b')?.exposure).toBe('open'); +}); diff --git a/packages/ui-react/tests/safety-reviewer.test.ts b/packages/ui-react/tests/safety-reviewer.test.ts new file mode 100644 index 0000000000..253aec9d0f --- /dev/null +++ b/packages/ui-react/tests/safety-reviewer.test.ts @@ -0,0 +1,105 @@ +import {test,expect} from 'bun:test'; +import {createStore} from 'zustand/vanilla'; +import {safetyHistoryFixture} from '../../ui-server/tests/helpers/safety-history-fixture'; +import {createSafetyStore} from '../src/stores/safety-state'; +import {createBrainApi} from '../src/lib/api-client'; +import {createSafetyReviewer,type SafetyReviewProgress} from '../src/lib/safety-reviewer'; +import type {BrainUiServices} from '../src/root'; + +async function fixture(){ + const host=await safetyHistoryFixture(true,true),a=await host.add('A'),b=await host.add('B'),c=await host.add('C'); + const safety=createSafetyStore(),chat=createStore(()=>({activeSessionId:'ithaca' as string|null})),auth=createStore(()=>({phase:'active' as 'active'|'locked'})); + safety.getState().reset(true,host.reviews!.capabilities(host.principal)); + const page=await host.history.read(host.principal,{sessionId:'ithaca'}); + safety.getState().begin('snapshot');safety.getState().page('snapshot',page); + const origin=host.url.replace('ws:','http:').replace('/ws',''),requests:string[]=[],progress:SafetyReviewProgress[]=[]; + let epoch=0,transport:(url:string,init:RequestInit)=>Promise=(url,init)=>fetch(url,init); + const api=createBrainApi(()=>origin+'/api',(url,init)=>{requests.push(url);return transport(url,{...init,headers:{...init?.headers,cookie:host.cookie,origin}});}); + const root={api,stores:{safety,chat},authLock:{state:auth,epoch:()=>epoch}} as unknown as BrainUiServices; + const reviewer=createSafetyReviewer(root,p=>progress.push(p)); + return {host,a,b,c,safety,chat,auth,requests,progress,root,reviewer,setTransport(next:typeof transport){transport=next;},revoke(){epoch++;auth.setState({phase:'locked'});},async close(){reviewer.dispose();await host.close();}}; +} +const gate=()=>{let release!:(v:Response)=>void;const promise=new Promise(r=>{release=r;});let entered!:()=>void;const arrived=new Promise(r=>{entered=r;});return {release,promise,entered,arrived};}; + +test('an explicit real owner review affects only A and never installs a receipt projection',async()=>{ + const f=await fixture();try{ + await f.reviewer.markSafe(f.a.id); + expect(f.requests.map(u=>u.split('/reviews/')[1])).toHaveLength(2); + expect(f.progress.at(-1)?.stage,'ONLY_HOST_COMMITTED_VERDICT_REPORTS_SUCCESS').toBe('committed'); + const current=await f.host.history.read(f.host.principal,{sessionId:'ithaca'}); + expect(current.projection.unresolvedCount,'B_AND_C_STAY_UNRESOLVED').toBe(2); + expect(current.records.filter(r=>r.kind==='safe_decision').map(r=>r.occurrenceId)).toEqual([f.a.id]); + expect(f.safety.getState().projection?.unresolvedCount,'RECEIPT_CANNOT_OVERWRITE_LIVE_AGGREGATE').toBe(3); + expect(f.safety.getState().normal).toBe(false);expect(f.safety.getState().refreshTick).toBe(1); + f.safety.getState().refresh();expect(f.requests,'REFRESH_NEVER_REPLAYS_A_VERDICT').toHaveLength(2); + }finally{await f.close();} +}); + +test('owner loss while prepare is returning cancels commit and settles the pending state',async()=>{ + const f=await fixture(),hold=gate();let prepared:Response;try{ + f.setTransport(async(url,init)=>{const response=await fetch(url,init);prepared=Response.json(await response.json(),{status:response.status});hold.entered();return hold.promise;}); + const pending=f.reviewer.markSafe(f.a.id);await hold.arrived;f.revoke();hold.release(prepared!);await pending; + expect(f.requests,'AUTH_LOSS_CANNOT_COMMIT_PREPARED_AUTHORITY').toHaveLength(1); + expect(f.host.db.query('SELECT COUNT(*) n FROM safety_decisions').get()).toEqual({n:0}); + expect(f.progress.at(-1)?.stage,'CANCELLED_REVIEW_IS_NOT_FOREVER_PENDING').not.toBe('pending'); + }finally{await f.close();} +}); + +test('a new trigger while prepare waits is refused by real commit and cannot clear any trigger',async()=>{ + const f=await fixture();try{ + f.setTransport(async(url,init)=>{const response=await fetch(url,init);if(url.endsWith('/prepare'))await f.host.add('D');return response;}); + await f.reviewer.markSafe(f.a.id); + expect(f.requests).toHaveLength(2);expect(f.progress.at(-1)?.stage).toBe('refused'); + expect(f.host.db.query('SELECT COUNT(*) n FROM safety_decisions').get(),'STALE_HOST_REVISION_CANNOT_COMMIT').toEqual({n:0}); + expect((await f.host.history.read(f.host.principal,{sessionId:'ithaca'})).projection.unresolvedCount).toBe(4); + }finally{await f.close();} +}); + +test('late commit receipts do not replace a newer live B/C/D projection',async()=>{ + const f=await fixture();try{ + f.setTransport(async(url,init)=>{ + const response=await fetch(url,init); + if(url.endsWith('/commit')){ + await f.host.add('D');const next=await f.host.history.read(f.host.principal,{sessionId:'ithaca'}); + const old=f.safety.getState();expect(old.update({version:1,identity:next.identity,fromRevision:old.revision,toRevision:next.highWater,projection:next.projection,records:next.records.filter(r=>BigInt(r.sequence)>BigInt(old.revision))})).toBe(true); + } + return response; + }); + await f.reviewer.markSafe(f.a.id); + expect(f.safety.getState().projection?.unresolvedCount,'LATE_RECEIPT_RETAINS_NEWER_B_C_D').toBe(3); + expect(f.safety.getState().normal).toBe(false); + expect(Object.values(f.safety.getState().records).filter(r=>r.kind==='safe_decision').map(r=>r.occurrenceId)).toEqual([f.a.id]); + }finally{await f.close();} +}); + +test('a lost commit response remains unknown and no refresh replays it',async()=>{ + const f=await fixture();try{ + f.setTransport(async(url,init)=>{const result=await fetch(url,init);if(url.endsWith('/commit'))throw new Error('Controlled receipt loss');return result;}); + await f.reviewer.markSafe(f.a.id);expect(f.progress.at(-1)?.stage,'LOST_RECEIPT_IS_UNKNOWN').toBe('unknown'); + expect(f.host.db.query('SELECT COUNT(*) n FROM safety_decisions').get()).toEqual({n:1}); + f.safety.getState().refresh();expect(f.requests,'NO_AUTOMATIC_REPLAY_AFTER_UNKNOWN_RESULT').toHaveLength(2);expect(f.safety.getState().normal).toBe(false); + }finally{await f.close();} +}); + +test('read-only capability and changed chat selection never send a verdict',async()=>{ + const f=await fixture();try{ + f.safety.setState({capabilities:{...f.safety.getState().capabilities!,review:false}});await f.reviewer.markSafe(f.a.id); + expect(f.requests,'READ_ONLY_CAPABILITY_CANNOT_REVIEW').toHaveLength(0); + f.safety.setState({capabilities:f.host.reviews!.capabilities(f.host.principal)}); + const hold=gate();let response:Response; + f.setTransport(async(url,init)=>{const raw=await fetch(url,init);response=Response.json(await raw.json(),{status:raw.status});hold.entered();return hold.promise;}); + const pending=f.reviewer.markSafe(f.a.id);await hold.arrived;f.chat.setState({activeSessionId:'troy'});hold.release(response!);await pending; + expect(f.requests,'SELECTING_ANOTHER_CHAT_WITHDRAWS_PREPARED_AUTHORITY').toHaveLength(1); + expect(f.host.db.query('SELECT COUNT(*) n FROM safety_decisions').get()).toEqual({n:0}); + }finally{await f.close();} +}); + +test('disconnect after preparation discards authority and a fresh read never resumes the review',async()=>{ + const f=await fixture(),hold=gate();let prepared:Response;try{ + f.setTransport(async(url,init)=>{const response=await fetch(url,init);prepared=Response.json(await response.json(),{status:response.status});hold.entered();return hold.promise;}); + const pending=f.reviewer.markSafe(f.a.id);await hold.arrived;f.safety.getState().disconnected();hold.release(prepared!);await pending; + expect(f.requests,'DISCONNECT_CANNOT_RESUME_PREPARED_REVIEW').toHaveLength(1); + const page=await f.host.history.read(f.host.principal,{sessionId:'ithaca'});f.safety.getState().reset(true,f.host.reviews!.capabilities(f.host.principal));f.safety.getState().begin('reconnected');f.safety.getState().page('reconnected',page); + expect(f.requests,'FRESH_READ_NEVER_REPLAYS_A_DECISION').toHaveLength(1);expect(f.host.db.query('SELECT COUNT(*) n FROM safety_decisions').get()).toEqual({n:0}); + }finally{await f.close();} +}); diff --git a/packages/ui-sdk/src/safety.ts b/packages/ui-sdk/src/safety.ts index d31c8b35d1..8759565c77 100644 --- a/packages/ui-sdk/src/safety.ts +++ b/packages/ui-sdk/src/safety.ts @@ -22,7 +22,7 @@ const provenance = z.union([z.null(), z.strictObject({ kind: z.literal("web_orig const common = { id, sequence: revision, observedAt: time, turnId: id, bindingId: id, occurrenceId: id, detailPruned: z.boolean() }; export const safetyRecordSchema = z.discriminatedUnion("kind", [ z.strictObject({ ...common, kind:z.literal("occurrence"), epochId:id, detector:id.nullable(), source, operationId:id.nullable(), signalId:id.nullable(), exposureId:id.nullable(), exposure, - summary:text(2048), provenance }), + summary:text(2048), provenance, entry:z.strictObject({kind:z.literal("tool"),toolUseId:id}).optional() }), z.strictObject({ ...common, kind:z.literal("exposure"), state:exposure }), z.strictObject({ ...common, kind:z.literal("safe_decision"), session:safetySessionKeySchema, requestId:id, principalId:id, verdict:z.literal("safe"), channel:z.enum(["owner_history","owner_settings"]) }), ]); @@ -63,7 +63,7 @@ export type SafetyReviewBody = z.infer; export type SafetyReviewReceipt = z.infer; export type SafetyReviewResponse = z.infer; -export const clientSafetyReadSchema = z.strictObject({type:z.literal("safety_read"),requestId:id,version:z.literal(1),target:safetyTargetSchema,cursor:z.string().max(512).nullable().optional(),limit:z.number().int().min(1).max(100).optional()}); +export const clientSafetyReadSchema = z.strictObject({type:z.literal("safety_read"),requestId:id,version:z.literal(1),target:safetyTargetSchema,cursor:z.string().max(512).nullable().optional(),limit:z.number().int().min(1).max(100).optional(),includeEntries:z.literal(true).optional()}); export const clientSafetySubscribeSchema = z.strictObject({type:z.literal("safety_subscribe"),requestId:id,version:z.literal(1),identity:safetyIdentitySchema,afterRevision:revision,snapshotId:id}); export const clientSafetyUnsubscribeSchema = z.strictObject({type:z.literal("safety_unsubscribe"),version:z.literal(1)}); export const serverSafetyHistorySchema = z.strictObject({type:z.literal("safety_history"),requestId:id,page:safetyPageSchema}); diff --git a/packages/ui-server/src/governance/occurrence.ts b/packages/ui-server/src/governance/occurrence.ts index b29f61bbae..e4f49c8e97 100644 --- a/packages/ui-server/src/governance/occurrence.ts +++ b/packages/ui-server/src/governance/occurrence.ts @@ -4,6 +4,8 @@ import { z } from "zod"; const id = z.string().regex(/^[A-Za-z0-9_-]{1,128}$/); export const OccurrenceSchema = z.strictObject({ id, epochId: id, operationId: id.nullable(), signalId: id, exposureId: id, + /** Captured by the host collector, never inferred from display content. */ + entry: z.strictObject({kind:z.literal("tool"),toolUseId:id}).optional(), detector: z.enum(["tool_web_input", "tool_file_input", "tool_search_output", "external_mcp_input", "attachment_input", "compute_input", "unproxied_shell_input", "proxy_input", "explicit_untrusted_input"]), // Observation of a result is not proof that input delivery has ended. diff --git a/packages/ui-server/src/governance/safety-collector.ts b/packages/ui-server/src/governance/safety-collector.ts index 839abd45ba..b0d8d0d337 100644 --- a/packages/ui-server/src/governance/safety-collector.ts +++ b/packages/ui-server/src/governance/safety-collector.ts @@ -33,6 +33,12 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option const base=()=>({turnId:options.turnId,sessionId:options.sessionId(),actor:options.actor??"interactive" as const,model:null,profile:null}); const marked=(path:string)=>isMarkedUntrusted(db,path); const hash=(value:string)=>new Bun.CryptoHasher("sha256").update(value).digest("hex"); + const observed=(toolUseId:string,detector:Parameters[1],operationId:string)=>{ + const item=occurrence(options.bindingId,detector,operationId,"open"); + if(/^[A-Za-z0-9_-]{1,128}$/.test(toolUseId))item.entry={kind:"tool",toolUseId}; + item.admission={trusted:false,policyHash:options.policyHash??null,trustRevision:"0"}; + return item; + }; const assertLive=()=>{if(options.signal.aborted)throw new Error("Safety input collection cancelled");}; // `held`: the failure came from begin(), which the backend awaits before it // runs the tool. A refused reservation there, with a producer that did stop, @@ -100,7 +106,7 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option op.inputHashes.add(inputHash);op.admitted=false;operations.set(toolUseId,op); for(const signal of inputTaintSignals(tool,input,options.brainPath,marked,options.shellProxied())){ if(op.signals.some(prior=>prior.detector===signal.detector&&prior.key===signal.key))continue; - const item=occurrence(options.bindingId,signal.detector,op.id,"open");item.admission={trusted:false,policyHash:options.policyHash??null,trustRevision:"0"}; + const item=observed(toolUseId,signal.detector,op.id); await writes.firstTaint({...base(),kind:"taint",payload:{source:signal.source,tool,detail:null,occurrence:item}},{beforeDelivery:true}); op.occurrences.push(item.id);op.signals.push(signal); } @@ -122,13 +128,13 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option if(op.done){if(op.outputHash!==outputHash)throw new Error("Conflicting safety result delivery");return;} // Each separately delivered external result segment has its own exposure. for(const _segment of (segments??[]).slice(1))for(const signal of op.signals.filter(signal=>["compute_input","external_mcp_input","attachment_input","tool_web_input"].includes(signal.detector))){ - const item=occurrence(options.bindingId,signal.detector,op.id,"open");item.admission={trusted:false,policyHash:options.policyHash??null,trustRevision:"0"}; + const item=observed(toolUseId,signal.detector,op.id); await writes.firstTaint({...base(),kind:"taint",payload:{source:signal.source,tool,detail:null,occurrence:item}});op.occurrences.push(item.id); } // Record output independently, before the backend releases it to the // model. Its bytes already exist, so a refusal here is never "before delivery". for(const signal of outputTaintSignals(tool,output,options.brainPath,marked)){ - const item=occurrence(options.bindingId,signal.detector,op.id,"open");item.admission={trusted:false,policyHash:options.policyHash??null,trustRevision:"0"}; + const item=observed(toolUseId,signal.detector,op.id); await writes.firstTaint({...base(),kind:"taint",payload:{source:signal.source,tool,detail:null,occurrence:item}});op.occurrences.push(item.id); } const state=finalized&&!['Bash','bash'].includes(tool)?"finalized":"interrupted_unknown"; diff --git a/packages/ui-server/src/governance/safety-history.ts b/packages/ui-server/src/governance/safety-history.ts index ffbbf65a90..f8154f1b12 100644 --- a/packages/ui-server/src/governance/safety-history.ts +++ b/packages/ui-server/src/governance/safety-history.ts @@ -13,7 +13,7 @@ export class SafetyReadUnavailable extends Error { constructor(readonly reason: Reason = "unavailable") { super(reason); } } interface Snapshot { id:string; principalId:string; target:SafetyTarget; identity:SafetyIdentity; highWater:string; - projection:SafetyPage["projection"]; membership:string; expiresAt:number; pruned:number; bytes:number } + projection:SafetyPage["projection"]; membership:string; expiresAt:number; pruned:number; bytes:number; entries:boolean } interface Row { id:string; sequence:string; observed_at:number; kind:string; occurrence_id:string; source:string|null; detector:string|null; state:string|null; payload:string; detail_pruned:number; turn_id:string; collection_id:string } const same = (a:unknown,b:unknown) => JSON.stringify(a)===JSON.stringify(b); @@ -26,7 +26,7 @@ const wireId = (value:string) => { export class SafetyHistory { private readonly subscriptions = new Mapboolean; - send:(value:SafetyUpdate|Unavailable)=>void; busy:boolean }>(); + send:(value:SafetyUpdate|Unavailable)=>void; busy:boolean; entries:boolean }>(); private readonly snapshots = new Map(); private readonly cursors = new Map(); private retainedBytes = 0; @@ -103,7 +103,7 @@ export class SafetyHistory { if(failed){p.coverage.state="incomplete";if(!p.reasons.includes("recording_failed"))p.reasons.push("recording_failed");}} return p as SafetyPage["projection"]; } - private records(identity:SafetyIdentity,after:string,through:string,limit:number):SafetyRecord[] { + private records(identity:SafetyIdentity,after:string,through:string,limit:number,entries:boolean):SafetyRecord[] { const {sql,args}=this.scope(identity); const rows=this.db.query(`SELECT * FROM ( SELECT r.*,c.turn_id FROM safety_records r JOIN safety_collections c ON c.id=r.collection_id WHERE ${sql} @@ -124,7 +124,7 @@ export class SafetyHistory { // model text, prompt or page body cross this read boundary. return {...common,kind:"occurrence",epochId:o?.epochId??r.collection_id,detector:r.detector,source:r.source??"legacy_unknown",operationId:o?.operationId??null, signalId:o?.signalId??null,exposureId:o?.exposureId??null,exposure:r.state??"interrupted_unknown",summary:r.source==="egress_connection"?"Network input; operation attribution unavailable":"Recorded input exposure", - provenance:o?.provenance??null} as SafetyRecord; + provenance:o?.provenance??null,...(entries&&(o?.entry??p.entry)?{entry:o?.entry??p.entry}:{})} as SafetyRecord; }); } private drop(id:string):void { @@ -140,7 +140,7 @@ export class SafetyHistory { return ()=>{const left=this.pendingReads.get(principal.id)!-1;if(left)this.pendingReads.set(principal.id,left);else this.pendingReads.delete(principal.id);}; } /** Every await precedes fresh authority, identity and clock checks. */ - async read(principal:Principal,target:SafetyTarget,cursor:string|null=null,limit:number=50):Promise { + async read(principal:Principal,target:SafetyTarget,cursor:string|null=null,limit:number=50,entries=false):Promise { if(!Number.isInteger(limit)||limit<1||limit>100||cursor!==null&&cursor.length>512)throw new SafetyReadUnavailable(); this.authorize(principal,target); const release=this.reserveRead(principal); @@ -150,7 +150,7 @@ export class SafetyHistory { let snapshot:Snapshot,after="0"; if(cursor!==null){ const position=this.cursors.get(cursor),s=position&&this.snapshots.get(position.snapshotId); - if(!s||s.principalId!==principal.id||!same(s.target,target))throw new SafetyReadUnavailable("expired"); + if(!s||s.principalId!==principal.id||!same(s.target,target)||s.entries!==entries)throw new SafetyReadUnavailable("expired"); snapshot=s;after=position!.after; if(!same(identity,s.identity))throw new SafetyReadUnavailable("generation_changed"); if(this.membership(identity,s.highWater)!==s.membership)throw new SafetyReadUnavailable("gap"); @@ -159,10 +159,10 @@ export class SafetyHistory { if(this.snapshots.size>=256||[...this.snapshots.values()].filter(s=>s.principalId===principal.id).length>=32)throw new SafetyReadUnavailable("capacity"); const projection=this.projection(identity),size=bytes(projection)+2048; if(this.retainedBytes+size>4194304)throw new SafetyReadUnavailable("capacity"); - snapshot={id:crypto.randomUUID(),principalId:principal.id,target,identity,projection,highWater:projection.evidenceRevision,membership:this.membership(identity,projection.evidenceRevision),expiresAt:this.clock()+300000,pruned:this.pruned(identity),bytes:size}; + snapshot={id:crypto.randomUUID(),principalId:principal.id,target,identity,projection,highWater:projection.evidenceRevision,membership:this.membership(identity,projection.evidenceRevision),expiresAt:this.clock()+300000,pruned:this.pruned(identity),bytes:size,entries}; this.snapshots.set(snapshot.id,snapshot);this.retainedBytes+=size; } - const fetched=this.records(identity,after,snapshot.highWater,limit+1),records:SafetyRecord[]=[]; + const fetched=this.records(identity,after,snapshot.highWater,limit+1,snapshot.entries),records:SafetyRecord[]=[]; const page:SafetyPage={version:1,identity,snapshotId:snapshot.id,cursor,highWater:snapshot.highWater,projection:snapshot.projection,records,nextCursor:null,snapshotComplete:false,detailPruned:snapshot.pruned>0}; for(const record of fetched.slice(0,limit)){if(bytes({...page,records:[...records,record]})>261000)break;records.push(record);} if(fetched.length&&!records.length)throw new SafetyReadUnavailable("capacity"); @@ -183,13 +183,13 @@ export class SafetyHistory { } async delta(principal:Principal,identity:SafetyIdentity,after:string,snapshotId:string):Promise { const anchor=this.anchor(principal,identity,after,snapshotId); - const result=await this.readDelta(principal,identity,after,anchor.membership); + const result=await this.readDelta(principal,identity,after,anchor.membership,anchor.entries); this.anchor(principal,identity,after,snapshotId); this.delivery(principal,identity,snapshotId,result.update.projection); if(this.membership(identity,result.update.toRevision)!==result.membership)throw new SafetyReadUnavailable("gap"); return result.update; } - private async readDelta(principal:Principal,identity:SafetyIdentity,after:string,membership:string):Promise<{update:SafetyUpdate;membership:string}> { + private async readDelta(principal:Principal,identity:SafetyIdentity,after:string,membership:string,entries:boolean):Promise<{update:SafetyUpdate;membership:string}> { const target:SafetyTarget="sessionId" in identity?{sessionId:identity.sessionId}:identity; this.authorize(principal,target);const release=this.reserveRead(principal); try{await this.settled(); @@ -198,7 +198,7 @@ export class SafetyHistory { if(this.membership(identity,after)!==membership)throw new SafetyReadUnavailable("gap"); const projection=this.projection(identity); if(BigInt(after)>BigInt(projection.evidenceRevision))throw new SafetyReadUnavailable("gap"); - const records=this.records(identity,after,projection.evidenceRevision,101); + const records=this.records(identity,after,projection.evidenceRevision,101,entries); const update:SafetyUpdate={version:1,identity,fromRevision:after,toRevision:projection.evidenceRevision,projection,records}; if(records.length>100||bytes(update)>262000)throw new SafetyReadUnavailable("capacity"); this.authorize(principal,target);this.clock(); @@ -209,7 +209,7 @@ export class SafetyHistory { subscribe(key:object,principal:Principal,identity:SafetyIdentity,revision:string,snapshotId:string,valid:()=>boolean,send:(value:SafetyUpdate|Unavailable)=>void):void { if(!this.subscriptions.has(key)&&this.subscriptions.size>=256)throw new SafetyReadUnavailable("capacity"); const anchor=this.anchor(principal,identity,revision,snapshotId); - this.subscriptions.set(key,{principal,identity,revision,membership:anchor.membership,projectionHash:fingerprint(anchor.projection),valid,send,busy:false});this.poll(); + this.subscriptions.set(key,{principal,identity,revision,membership:anchor.membership,projectionHash:fingerprint(anchor.projection),valid,send,busy:false,entries:anchor.entries});this.poll(); } unsubscribe(key:object):void {this.subscriptions.delete(key);} revoke(principalIds:readonly string[]):void { @@ -241,7 +241,7 @@ export class SafetyHistory { for(const [key,s] of this.subscriptions){ if(!s.valid()||!this.valid(s.principal)){this.subscriptions.delete(key);continue;} if(s.busy)continue;s.busy=true; - void this.readDelta(s.principal,s.identity,s.revision,s.membership).then(({update,membership})=>{ + void this.readDelta(s.principal,s.identity,s.revision,s.membership,s.entries).then(({update,membership})=>{ if(this.subscriptions.get(key)!==s||!s.valid()||!this.valid(s.principal))return; try{this.delivery(s.principal,s.identity,undefined,update.projection); if(this.membership(s.identity,update.toRevision)!==membership)throw new SafetyReadUnavailable("gap"); diff --git a/packages/ui-server/src/governance/safety-store.ts b/packages/ui-server/src/governance/safety-store.ts index e3d37ca8e9..fc2a928182 100644 --- a/packages/ui-server/src/governance/safety-store.ts +++ b/packages/ui-server/src/governance/safety-store.ts @@ -311,7 +311,7 @@ function appendRecord(db:Database,c:Collection,id:string,kind:"occurrence"|"expo kind,occurrenceId,source,detector,state,payload})); if(bytes>SAFETY_LIMITS.occurrenceBytes)throw new SafetyCapacityExhausted("Safety occurrence byte limit exceeded","turn"); const previous=one(db,"SELECT * FROM safety_records WHERE id=?",id); - if(previous){if(previous.collection_id!==c.id||(previous.detail_pruned ? previous.payload!==JSON.stringify({sha256:new Bun.CryptoHasher("sha256").update(json).digest("hex")}) : previous.payload!==json))throw new SafetyUnavailable("Conflicting safety occurrence identity");return;} + if(previous){if(previous.collection_id!==c.id||(previous.detail_pruned ? JSON.parse(previous.payload).sha256!==new Bun.CryptoHasher("sha256").update(json).digest("hex") : previous.payload!==json))throw new SafetyUnavailable("Conflicting safety occurrence identity");return;} const rows=kind==="occurrence"?(state==="finalized"?2:4):0, reserved=kind==="occurrence"?bytes+VERDICT_BYTES+(state==="finalized"?0:2*TERMINAL_BYTES):0; if(kind==="exposure"&&bytes>TERMINAL_BYTES)throw new SafetyCapacityExhausted("Safety terminal reserve exceeded","turn"); @@ -501,7 +501,10 @@ export function recoverSafetyCollections(db:Database):void { export function pruneSafetyDetail(db:Database,before:number):number { return db.transaction(()=>{ const rows=db.query("SELECT id,payload FROM safety_records WHERE observed_at8192||Object.keys(c.req.query()).some(k=>k!=="cursor"&&k!=="limit")||Object.values(c.req.queries()).some(values=>values.length!==1))return c.json({version:1,reason:"unavailable"},400); + if(Buffer.byteLength(c.req.url)>8192||Object.keys(c.req.query()).some(k=>!["cursor","limit","entries"].includes(k))||Object.values(c.req.queries()).some(values=>values.length!==1)||c.req.query("entries")!==undefined&&c.req.query("entries")!=="1")return c.json({version:1,reason:"unavailable"},400); const target={sessionId:c.req.param("id")},cursor=c.req.query("cursor")??null,raw=c.req.query("limit"); if(!/^[A-Za-z0-9_-]{1,128}$/.test(target.sessionId)||cursor!==null&&(!cursor||cursor.length>512)||raw!==undefined&&(!/^[1-9][0-9]{0,2}$/.test(raw)||Number(raw)>100))return c.json({version:1,reason:"unavailable"},400); try{ - const page=await history.read(principal,target,cursor,raw?Number(raw):50); + const page=await history.read(principal,target,cursor,raw?Number(raw):50,c.req.query("entries")==="1"); if(!valid(principal))return c.json({version:1,reason:"unauthorized"},401); history.delivery(principal,page.identity,page.snapshotId); return c.json(page); diff --git a/packages/ui-server/src/ws/connection.ts b/packages/ui-server/src/ws/connection.ts index dd2e503773..093c322427 100644 --- a/packages/ui-server/src/ws/connection.ts +++ b/packages/ui-server/src/ws/connection.ts @@ -91,7 +91,7 @@ export function createWsHandlers(host: WsHost, principal: Principal) { principalKey: answerQueueKey(principal.id), ...(host.safetyHistory ? {safetyCapabilities: host.ownerSafetyReviews?.capabilities(principal) ?? SAFETY_READ_CAPABILITIES} : {}), capabilities: { - ...(host.safetyHistory ? {sessionSafetyHistory:true} : {}), + ...(host.safetyHistory ? {sessionSafetyHistory:true,sessionSafetyEntryCorrelation:true} : {}), multiSession: true, askUser: true, askUserList: true, diff --git a/packages/ui-server/src/ws/handlers/safety.ts b/packages/ui-server/src/ws/handlers/safety.ts index ce6afd9e54..f382ea04aa 100644 --- a/packages/ui-server/src/ws/handlers/safety.ts +++ b/packages/ui-server/src/ws/handlers/safety.ts @@ -6,7 +6,7 @@ export const handleSafetyRead:ClientMessageHandler<"safety_read">=async({host,ws if(!connection.capabilities?.sessionSafetyHistory||!live())return; try{ if(!host.safetyHistory)throw new SafetyReadUnavailable(); - const page=await host.safetyHistory.read(connection.principal,msg.target,msg.cursor??null,msg.limit); + const page=await host.safetyHistory.read(connection.principal,msg.target,msg.cursor??null,msg.limit,msg.includeEntries===true); host.safetyHistory.delivery(connection.principal,page.identity,page.snapshotId); if(live())host.sendMessage(ws,{type:"safety_history",requestId:msg.requestId,page}); }catch(error){if(live())host.sendMessage(ws,{type:"safety_unavailable",requestId:msg.requestId,version:1,reason:error instanceof SafetyReadUnavailable?error.reason:"unavailable"});} diff --git a/packages/ui-server/tests/safety-entry-correlation.test.ts b/packages/ui-server/tests/safety-entry-correlation.test.ts new file mode 100644 index 0000000000..7a80a686df --- /dev/null +++ b/packages/ui-server/tests/safety-entry-correlation.test.ts @@ -0,0 +1,60 @@ +import {test,expect} from 'bun:test'; +import {safetyHistoryFixture} from './helpers/safety-history-fixture'; +import {createSafetyCollector} from '../src/governance/safety-collector'; +import {SafetyHistory} from '../src/governance/safety-history'; +import {pruneSafetyDetail} from '../src/governance/safety-store'; + +test('explicit tool entry survives real collection, opt-in paging, pruning and restart',async()=>{ + const f=await safetyHistoryFixture(); + try{ + const collector=createSafetyCollector(f.db,f.writes,{turnId:'voyage',bindingId:f.bindingId,backendId:'claude',sessionId:()=> 'ithaca',shellProxied:()=>true,signal:new AbortController().signal}); + await collector.begin('toolu_odysseus_read','WebFetch',{url:'https://example.com/voyage'}); + await collector.result('toolu_odysseus_read','WebFetch','Odysseus sailing notes',true); + const old=await f.history.read(f.principal,{sessionId:'ithaca'}); + expect(old.records.find(r=>r.kind==='occurrence'),'DEFAULT_READERS_RETAIN_STRICT_SHAPE').not.toHaveProperty('entry'); + const opted=await f.history.read(f.principal,{sessionId:'ithaca'},null,50,true); + expect(opted.records.find(r=>r.kind==='occurrence'),'EXACT_HOST_TOOL_CORRELATION').toHaveProperty('entry',{kind:'tool',toolUseId:'toolu_odysseus_read'}); + pruneSafetyDetail(f.db,Number.MAX_SAFE_INTEGER); + const pruned=await f.history.read(f.principal,{sessionId:'ithaca'},null,50,true); + expect(pruned.records.find(r=>r.kind==='occurrence'),'PRUNING_RETAINS_MINIMAL_ENTRY_ID').toHaveProperty('entry',{kind:'tool',toolUseId:'toolu_odysseus_read'}); + const restarted=new SafetyHistory(f.db,p=>p.id===f.principal.id,()=>f.writer.idle());try{ + const recovered=await restarted.read(f.principal,{sessionId:'ithaca'},null,50,true); + expect(recovered.records.find(r=>r.kind==='occurrence'),'RESTART_RETAINS_MINIMAL_ENTRY_ID').toHaveProperty('entry',{kind:'tool',toolUseId:'toolu_odysseus_read'}); + }finally{restarted.close();} + }finally{await f.close();} +}); + +test('old WS readers retain their strict shape; opting in pins entry correlation through live deltas',async()=>{ + const f=await safetyHistoryFixture(true,true); + try{ + const collector=createSafetyCollector(f.db,f.writes,{turnId:'voyage',bindingId:f.bindingId,backendId:'claude',sessionId:()=> 'ithaca',shellProxied:()=>true,signal:new AbortController().signal}); + await collector.begin('tool_a','WebFetch',{url:'https://example.com/odyssey'});await collector.result('tool_a','WebFetch','Voyage notes',true); + const old=await f.connect();expect(old.hello.type==='server_hello'&&old.hello.capabilities?.sessionSafetyEntryCorrelation).toBe(true); + expect(old.hello.type==='server_hello'&&old.hello.safetyCapabilities).not.toHaveProperty('entryCorrelation'); + old.send({type:'safety_read',version:1,requestId:'old',target:{sessionId:'ithaca'}}); + const original=await old.until(m=>m.type==='safety_history');if(original.type!=='safety_history')throw new Error('Missing page'); + expect(original.page.records.find(r=>r.kind==='occurrence'),'OLD_READER_SHAPE_REMAINS_STRICT').not.toHaveProperty('entry'); + const next=await f.connect();next.send({type:'safety_read',version:1,requestId:'new',target:{sessionId:'ithaca'},includeEntries:true}); + const frame=await next.until(m=>m.type==='safety_history');if(frame.type!=='safety_history')throw new Error('Missing page'); + expect(frame.page.records.find(r=>r.kind==='occurrence')).toHaveProperty('entry',{kind:'tool',toolUseId:'tool_a'}); + next.send({type:'safety_subscribe',version:1,requestId:'new',identity:frame.page.identity,afterRevision:frame.page.highWater,snapshotId:frame.page.snapshotId}); + await collector.begin('tool_c','WebFetch',{url:'https://example.com/odyssey'});await collector.result('tool_c','WebFetch','Penelope notes',true);f.history.poll(); + const update=await next.until(m=>m.type==='safety_update'&&m.update.records.some(r=>r.kind==='occurrence'&&r.entry?.toolUseId==='tool_c')); + expect(update.type,'OPTED_SUBSCRIPTION_RETAINS_HOST_TOOL_ID').toBe('safety_update'); + const paged=await f.history.read(f.principal,{sessionId:'ithaca'},null,1,true);expect(paged.nextCursor).not.toBeNull(); + // Await the worker normally: Bun's native rejects matcher does not + // service worker messages while awaiting this otherwise pending idle. + let refusal:unknown;try{await f.history.read(f.principal,{sessionId:'ithaca'},paged.nextCursor,1,false);}catch(error){refusal=error;} + expect(refusal,'CURSOR_CANNOT_CHANGE_NEGOTIATED_SHAPE').toHaveProperty('reason','expired'); + }finally{await f.close();} +}); + +test('opaque and unsupported tool identities never acquire a guessed entry',async()=>{ + const f=await safetyHistoryFixture();try{ + await f.add('network',true); + const collector=createSafetyCollector(f.db,f.writes,{turnId:'voyage',bindingId:f.bindingId,backendId:'claude',sessionId:()=> 'ithaca',shellProxied:()=>true,signal:new AbortController().signal}); + await collector.begin('opaque|tool','WebFetch',{url:'https://example.com/odyssey'});await collector.result('opaque|tool','WebFetch','Odysseus notes',true); + const page=await f.history.read(f.principal,{sessionId:'ithaca'},null,50,true); + for(const r of page.records.filter(r=>r.kind==='occurrence'))expect(r,'NO_NAME_OR_TIMING_ATTRIBUTION').not.toHaveProperty('entry'); + }finally{await f.close();} +});