Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/safety-history-recovery-and-reason.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@schlessera/brain-ui-react": patch
---

Reload safety evidence after a subscription exceeds its delta capacity, and name an unresolved source in grouped safety indicators when earlier triggers have been marked safe.
2 changes: 1 addition & 1 deletion packages/ui-react/src/components/chat/safety-indicator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ function SafetyIndicator({entries:currentEntries}:{entries:SafetyEvidence[]}) {
useEffect(()=>{setOpen(false);},[scope,auth]);
const unresolved=entries.filter(e=>!e.decision).length,unknown=entries.some(e=>e.occurrence.detailPruned||e.occurrence.source==="legacy_unknown");
const name=unresolved?`Safety restrictions: ${unresolved} unresolved trigger${unresolved===1?"":"s"}`:`Marked safe by you${entries.length>1?`: ${entries.length} triggers`:""}: show details`;
const reason=unresolved?`${sources[entries[0]!.occurrence.source]} · Only this trigger can be reviewed`:"Human decision retained; content remains in the model context";
const reason=unresolved?`${sources[entries.find(e=>!e.decision)!.occurrence.source]} · Only this trigger can be reviewed`:"Human decision retained; content remains in the model context";
useLayoutEffect(()=>{
if(!open)return;
const place=()=>{const r=trigger.current?.getBoundingClientRect();if(r)setPosition({left:Math.max(12,Math.min(r.left,innerWidth-Math.min(384,innerWidth-24)-12)),top:Math.max(12,Math.min(r.bottom+4,innerHeight-Math.min(520,innerHeight*.65)-12))});};
Expand Down
20 changes: 16 additions & 4 deletions packages/ui-react/src/lib/safety-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { safetySessionKeySchema } from "@schlessera/brain-ui-sdk/schemas";
import type { BrainUiServices } from "../root.js";
/** One selected read subscription per socket. All reconnects start a fresh snapshot. */
export function createSafetyClient(root:BrainUiServices,send:(message:ClientMessage)=>boolean){
let target:SafetyTarget|null=null,requestId:string|null=null,disposed=false,awaitingPage=false;
let target:SafetyTarget|null=null,requestId:string|null=null,disposed=false,awaitingPage=false,capacityRecoveryUsed=false;
const store=root.stores.safety;
function read(next:SafetyTarget):void{
if(disposed||!store.getState().supported)return;
Expand All @@ -12,6 +12,7 @@ export function createSafetyClient(root:BrainUiServices,send:(message:ClientMess
send({type:"safety_read",version:1,requestId,target,...(store.getState().entryCorrelation?{includeEntries:true as const}:{})});
}
function selected(): void {
capacityRecoveryUsed=false;
const id = root.stores.chat.getState().activeSessionId;
// Host-only voice histories and older persisted keys are chat selections.
// Validate against the shared wire schema before starting a safety read.
Expand Down Expand Up @@ -43,12 +44,23 @@ export function createSafetyClient(root:BrainUiServices,send:(message:ClientMess
// snapshot's final subscription replays everything after its watermark.
if(awaitingPage)return true;
if(JSON.stringify(store.getState().identity)!==JSON.stringify(msg.update.identity))return true;
if(!store.getState().update(msg.update)&&target)read(target);return true;
const revision=store.getState().revision;
if(!store.getState().update(msg.update)){if(target)read(target);}
else if(BigInt(msg.update.toRevision)>BigInt(revision))capacityRecoveryUsed=false;
return true;
}
if(msg.type==="safety_unavailable"){
if(msg.requestId&&msg.requestId!==requestId)return true;
// Expiry/gap needs an explicit fresh snapshot; never replay a mutation.
const again=target&&["gap","expired","generation_changed"].includes(msg.reason);
const resync=["gap","expired","generation_changed"].includes(msg.reason);
// Uncorrelated loss notices may belong to the replaced subscription.
// A refusal of the active read must carry that read's request ID.
if(awaitingPage&&!msg.requestId&&(resync||msg.reason==="capacity"))return true;
// Lost subscriptions need a fresh snapshot; never replay a mutation.
// The wire does not distinguish a dropped delta from a refused subscribe.
// Allow one capacity resnapshot until live progress or explicit refresh;
// completing pages alone cannot prove the subscription was accepted.
const again=target&&(resync||msg.reason==="capacity"&&!awaitingPage&&!capacityRecoveryUsed);
if(msg.reason==="capacity")capacityRecoveryUsed=true;
store.getState().unavailable(msg.reason);requestId=null;if(again&&target)read(target);return true;
}
return false;
Expand Down
25 changes: 24 additions & 1 deletion packages/ui-react/tests/browser/safety-review.layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ afterEach(async()=>{await disposeView();if(fixture)await commands.safetyServer({
const patch=(patch:Record<string,unknown>={})=>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'}],
toolCalls:[{id:'tool_a',name:'WebFetch',inputJson:'{}',input:{url:'https://example.com/odyssey'},output:'Odysseus voyage notes',status:'complete'},{id:'tool_c',name:'Read',inputJson:'{}',input:{file_path:'workspaces/ithaca/voyage.md'},output:'Penelope voyage notes',status:'complete'}],
parts:[{kind:'tool',toolIndex:0},{kind:'tool',toolIndex:1},{kind:'text',text:'Voyage notes retained.'}]};
async function view(independentSocket=false){
const f=fixture!;
Expand Down Expand Up @@ -161,3 +161,26 @@ test('two live owner views keep independent review scope and converge after ever
await disposeView();ui=first.ui;socket=first.socket;renderer=first.renderer;host=first.host;safetyClient=first.client;
}
});

for(const theme of ['light','dark'])test(`${theme}: a mixed reviewed group names its remaining unresolved source on hover and focus`,async()=>{
await scene(320,theme);
const indicator=buttonForTool();
await userEvent.click(indicator);
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().projection?.unresolvedCount).toBe(2);
await userEvent.keyboard('{Escape}');
const tooltip=indicator.parentElement!.querySelector<HTMLElement>('[role=tooltip]')!;
expect(indicator.getAttribute('aria-label'),'GROUP_REASON_NAMES_UNRESOLVED_SOURCE').toContain('Workspace read');
expect(indicator.getAttribute('aria-label')).not.toContain('Web fetch');
indicator.focus();
await expect.poll(()=>getComputedStyle(tooltip).opacity).toBe('1');
expect(tooltip.textContent,'FOCUS_REASON_NAMES_UNRESOLVED_SOURCE').toContain('Workspace read');
await userEvent.click(page.getByRole('button',{name:'Outside safety details'}));
await userEvent.hover(indicator);
await expect.poll(()=>getComputedStyle(tooltip).opacity).toBe('1');
expect(tooltip.textContent,'HOVER_REASON_NAMES_UNRESOLVED_SOURCE').toContain('Workspace read');
await userEvent.click(indicator);
expect(document.querySelectorAll('[data-safety-trigger]')).toHaveLength(2);
expect(document.querySelector('[data-safety-details]')!.textContent).toContain('Marked safe by you');
});
7 changes: 6 additions & 1 deletion packages/ui-react/tests/fixtures/safety-browser-server.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/** Keyless loopback browser fixture: real writer, owner HTTP and WS sidecars. */
import {occurrence} from '../../../ui-server/src/governance/occurrence.js';
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';
Expand All @@ -10,7 +11,11 @@ const f=await safetyHistoryFixture(true,true),at=Date.UTC(2026,6,12,10);
const observedWrites={...f.writes,firstTaint:(input:Parameters<typeof f.writes.firstTaint>[0])=>f.writes.firstTaint({...input,at}),record:(input:Parameters<typeof f.writes.record>[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');
await tool('tool_a');await f.add('B',true);
const workspace=occurrence(f.bindingId,'tool_file_input','tool_c','finalized');
workspace.entry={kind:'tool',toolUseId:'tool_c'};
await observedWrites.record({kind:'taint',sessionId:'ithaca',turnId:'voyage',actor:'interactive',model:null,profile:'governed',
payload:{source:'workspace_read',tool:'Read',detail:'Odysseus voyage notes',occurrence:workspace}});
const app=new Hono<AppEnv>();
// Test-only bootstrap supplies the fixture principal to a real WS host. HTTP
// mutations below still traverse the actual cookie/Origin/owner route stack.
Expand Down
161 changes: 160 additions & 1 deletion packages/ui-react/tests/safety-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { createStore } from "zustand/vanilla";
import { createSafetyStore } from "../src/stores/safety-state";
import { createSafetyClient } from "../src/lib/safety-client";
import type { BrainUiServices } from "../src/root";
import { SAFETY_READ_CAPABILITIES, type ClientMessage, type SafetyPage } from "@schlessera/brain-ui-sdk/protocol";
import { SAFETY_READ_CAPABILITIES, type ClientMessage, type SafetyPage, type SafetyRecord } from "@schlessera/brain-ui-sdk/protocol";
import { parseClientMessage } from "@schlessera/brain-ui-sdk/schemas";

const hello = { type: "server_hello" as const, protocolRev: 5,
Expand Down Expand Up @@ -130,3 +130,162 @@ test("valid sessions keep paging, subscription and gap recovery on the published
checkWire();
} finally { client.dispose(); }
});

for (const reason of ["gap", "expired", "generation_changed", "capacity"] as const) {
test(`${reason} subscription loss obtains a fresh paginated snapshot without reselection`, () => {
const { safety, sent, client, checkWire } = supportedClient("ithaca");
try {
client.frame(hello);
const initial = sent.find(message => message.type === "safety_read");
if (initial?.type !== "safety_read") throw new Error("Missing initial read");
client.frame({ type: "safety_history", requestId: initial.requestId, page });
expect(safety.getState().status).toBe("ready");
const before = sent.length;
client.frame({ type: "safety_unavailable", version: 1, reason });
const fresh = sent.slice(before).find(message => message.type === "safety_read");
expect(fresh, "SUBSCRIPTION_LOSS_REQUESTS_FRESH_SNAPSHOT").toBeDefined();
if (fresh?.type !== "safety_read") throw new Error("Missing recovery read");
expect(fresh.requestId).not.toBe(initial.requestId);
expect(fresh).not.toHaveProperty("cursor");
expect(safety.getState()).toMatchObject({ status: "loading", normal: false });
client.frame({ type: "safety_history", requestId: initial.requestId, page });
expect(safety.getState().status, "STALE_PAGE_CANNOT_COMPLETE_RECOVERY").toBe("loading");
const recordsFor = (id: string, sequence: string): SafetyRecord[] => [
{ kind: "occurrence", id, occurrenceId: id, sequence, observedAt: Date.UTC(2026, 6, 12), turnId: "voyage",
bindingId: "voyage_binding", detailPruned: false, epochId: "voyage_binding", detector: "tool_web_input",
source: "web_fetch", operationId: id, signalId: id, exposureId: id, exposure: "finalized", summary: "Voyage notes", provenance: null },
{ kind: "safe_decision", id: `${id}_safe`, occurrenceId: id, sequence: String(BigInt(sequence) + 1n),
observedAt: Date.UTC(2026, 6, 12), turnId: "voyage", bindingId: "voyage_binding", detailPruned: false,
session: page.projection.session!, requestId: `${id}_review`, principalId: "odysseus", verdict: "safe", channel: "owner_history" },
];
const firstRecords = recordsFor("reviewed_web_a", "1"), lastRecords = recordsFor("reviewed_web_b", "3");
const normalPage: SafetyPage = { ...page, snapshotId: "recovery_snapshot", highWater: "4",
projection: { ...page.projection, evidenceRevision: "4", unresolvedCount: 0, restriction: "normal", reasons: [],
coverage: { ...page.projection.coverage, state: "complete" } } };
client.frame({ type: "safety_history", requestId: fresh.requestId,
page: { ...normalPage, records: firstRecords, nextCursor: "recovery_page_2", snapshotComplete: false } });
expect(safety.getState().status).toBe("partial");
expect(safety.getState().normal, "PARTIAL_RECOVERY_CANNOT_RESTORE_NORMAL").toBe(false);
expect(safety.getState().records.reviewed_web_a, "FIRST_RECOVERY_PAGE_RETAINS_EVIDENCE").toEqual(firstRecords[0]);
expect(sent.at(-1)).toMatchObject({ type: "safety_read", requestId: fresh.requestId, cursor: "recovery_page_2" });
client.frame({ type: "safety_history", requestId: fresh.requestId,
page: { ...normalPage, records: lastRecords, cursor: "recovery_page_2" } });
expect(safety.getState().status).toBe("ready");
expect(safety.getState().normal).toBe(true);
expect(Object.values(safety.getState().records), "RECOVERY_RETAINS_EVERY_PAGE").toEqual([...firstRecords, ...lastRecords]);
expect(sent.at(-1), "RECOVERY_SUBSCRIBES_AT_SNAPSHOT_HIGH_WATER").toMatchObject({ type: "safety_subscribe", requestId: fresh.requestId, snapshotId: "recovery_snapshot", afterRevision: "4" });
checkWire();
} finally { client.dispose(); }
});
}

for (const reason of ["capacity", "unauthorized", "unavailable"] as const) {
test(`${reason} read refusal does not loop snapshots`, () => {
const { safety, sent, client } = supportedClient("ithaca");
try {
client.frame(hello);
const initial = sent.find(message => message.type === "safety_read");
if (initial?.type !== "safety_read") throw new Error("Missing read");
const before = sent.length;
client.frame({ type: "safety_unavailable", version: 1, requestId: initial.requestId, reason });
expect(sent.length, "READ_REFUSAL_DOES_NOT_RETRY_IN_A_LOOP").toBe(before);
expect(safety.getState()).toMatchObject({ status: "unavailable", reason, normal: false });
} finally { client.dispose(); }
});
}

test("consecutive capacity refusals stop after one recovery snapshot until explicit refresh", () => {
const { safety, sent, client } = supportedClient("ithaca");
const complete = () => {
const read = sent.findLast(message => message.type === "safety_read");
if (read?.type !== "safety_read") throw new Error("Missing read");
client.frame({ type: "safety_history", requestId: read.requestId, page });
return read.requestId;
};
try {
client.frame(hello);
const initial = complete();
client.frame({ type: "safety_unavailable", version: 1, requestId: initial, reason: "capacity" });
const recovery = complete();
expect(recovery).not.toBe(initial);
const before = sent.length;
client.frame({ type: "safety_unavailable", version: 1, requestId: recovery, reason: "capacity" });
expect(sent.length, "CONSECUTIVE_CAPACITY_REFUSALS_HAVE_BOUNDED_RECOVERY").toBe(before);
expect(safety.getState()).toMatchObject({ status: "unavailable", reason: "capacity", normal: false });
client.frame({ type: "safety_unavailable", version: 1, reason: "capacity" });
expect(sent.length).toBe(before);
client.refresh();
expect(sent.filter(message => message.type === "safety_read")).toHaveLength(3);
expect(safety.getState().status).toBe("loading");
} finally { client.dispose(); }
});

test("only a valid advancing subscription update rearms capacity recovery", () => {
for (const advances of [false, true]) {
const { safety, sent, client } = supportedClient("ithaca");
try {
client.frame(hello);
const complete = () => {
const read = sent.findLast(message => message.type === "safety_read");
if (read?.type !== "safety_read") throw new Error("Missing read");
client.frame({ type: "safety_history", requestId: read.requestId, page });
};
complete();
client.frame({ type: "safety_unavailable", version: 1, reason: "capacity" });
complete();
const revision = advances ? "1" : "0";
client.frame({ type: "safety_update", update: { version: 1, identity: page.identity,
fromRevision: "0", toRevision: revision, records: [], projection: { ...page.projection, evidenceRevision: revision } } });
const before = sent.length;
client.frame({ type: "safety_unavailable", version: 1, reason: "capacity" });
expect(sent.length > before, "ONLY_ADVANCING_CONTIGUOUS_UPDATE_REARMS_CAPACITY_RECOVERY").toBe(advances);
expect(safety.getState().status).toBe(advances ? "loading" : "unavailable");
} finally { client.dispose(); }
}
});

for (const reason of ["capacity", "gap", "expired", "generation_changed"] as const) {
test(`uncorrelated ${reason} notices cannot interrupt an in-progress recovery snapshot`, () => {
const { safety, sent, client } = supportedClient("ithaca");
try {
client.frame(hello);
const initial = sent.findLast(message => message.type === "safety_read");
if (initial?.type !== "safety_read") throw new Error("Missing read");
client.frame({ type: "safety_history", requestId: initial.requestId, page });
client.frame({ type: "safety_unavailable", version: 1, requestId: initial.requestId, reason: "capacity" });
const recovery = sent.findLast(message => message.type === "safety_read");
if (recovery?.type !== "safety_read") throw new Error("Missing recovery read");
const before = sent.length;
client.frame({ type: "safety_unavailable", version: 1, reason });
expect(safety.getState(), "UNCORRELATED_LOSS_CANNOT_CANCEL_RECOVERY").toMatchObject({ status: "loading", requestId: recovery.requestId });
expect(sent.length).toBe(before);
client.frame({ type: "safety_history", requestId: recovery.requestId,
page: { ...page, nextCursor: "recovery_page_2", snapshotComplete: false } });
const paging = sent.length;
client.frame({ type: "safety_unavailable", version: 1, reason });
expect(safety.getState(), "UNCORRELATED_LOSS_CANNOT_CANCEL_PARTIAL_RECOVERY").toMatchObject({ status: "partial", requestId: recovery.requestId });
expect(sent.length).toBe(paging);
client.frame({ type: "safety_history", requestId: recovery.requestId, page: { ...page, cursor: "recovery_page_2" } });
expect(safety.getState().status).toBe("ready");
} finally { client.dispose(); }
});
}

test("a correlated capacity refusal terminates the active recovery page", () => {
const { safety, sent, client } = supportedClient("ithaca");
try {
client.frame(hello);
const initial = sent.findLast(message => message.type === "safety_read");
if (initial?.type !== "safety_read") throw new Error("Missing read");
client.frame({ type: "safety_history", requestId: initial.requestId, page });
client.frame({ type: "safety_unavailable", version: 1, requestId: initial.requestId, reason: "capacity" });
const recovery = sent.findLast(message => message.type === "safety_read");
if (recovery?.type !== "safety_read") throw new Error("Missing recovery read");
client.frame({ type: "safety_history", requestId: recovery.requestId,
page: { ...page, nextCursor: "recovery_page_2", snapshotComplete: false } });
const before = sent.length;
client.frame({ type: "safety_unavailable", version: 1, requestId: recovery.requestId, reason: "capacity" });
expect(sent.length).toBe(before);
expect(safety.getState(), "ACTIVE_READ_CAPACITY_REFUSAL_REMAINS_TERMINAL").toMatchObject({ status: "unavailable", requestId: null, reason: "capacity", normal: false });
} finally { client.dispose(); }
});
Loading