From 949b6c39dacaaf705449f2422c0b8db34d124704 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 15:14:18 +0000 Subject: [PATCH 1/3] fix(ui-react): recover safety history and name unresolved sources --- .../safety-history-recovery-and-reason.md | 5 ++ .../src/components/chat/safety-indicator.tsx | 2 +- packages/ui-react/src/lib/safety-client.ts | 5 +- .../tests/browser/safety-review.layout.tsx | 25 +++++++++- .../tests/fixtures/safety-browser-server.ts | 7 ++- packages/ui-react/tests/safety-client.test.ts | 47 +++++++++++++++++++ 6 files changed, 86 insertions(+), 5 deletions(-) create mode 100644 .changeset/safety-history-recovery-and-reason.md diff --git a/.changeset/safety-history-recovery-and-reason.md b/.changeset/safety-history-recovery-and-reason.md new file mode 100644 index 0000000000..d64eb09c1a --- /dev/null +++ b/.changeset/safety-history-recovery-and-reason.md @@ -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. diff --git a/packages/ui-react/src/components/chat/safety-indicator.tsx b/packages/ui-react/src/components/chat/safety-indicator.tsx index a417af5bc4..8cd6349a14 100644 --- a/packages/ui-react/src/components/chat/safety-indicator.tsx +++ b/packages/ui-react/src/components/chat/safety-indicator.tsx @@ -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))});}; diff --git a/packages/ui-react/src/lib/safety-client.ts b/packages/ui-react/src/lib/safety-client.ts index 06c1b3bd8b..73b79b808b 100644 --- a/packages/ui-react/src/lib/safety-client.ts +++ b/packages/ui-react/src/lib/safety-client.ts @@ -47,8 +47,9 @@ export function createSafetyClient(root:BrainUiServices,send:(message:ClientMess } 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); + // Lost subscriptions need a fresh snapshot; never replay a mutation. + // Capacity while paging is a read refusal, not another dropped delta. + const again=target&&(["gap","expired","generation_changed"].includes(msg.reason)||msg.reason==="capacity"&&!awaitingPage); store.getState().unavailable(msg.reason);requestId=null;if(again&&target)read(target);return true; } return false; diff --git a/packages/ui-react/tests/browser/safety-review.layout.tsx b/packages/ui-react/tests/browser/safety-review.layout.tsx index a1cec2975d..b1d7cb8fd6 100644 --- a/packages/ui-react/tests/browser/safety-review.layout.tsx +++ b/packages/ui-react/tests/browser/safety-review.layout.tsx @@ -21,7 +21,7 @@ afterEach(async()=>{await disposeView();if(fixture)await commands.safetyServer({ 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'}], + 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!; @@ -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('[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'); +}); diff --git a/packages/ui-react/tests/fixtures/safety-browser-server.ts b/packages/ui-react/tests/fixtures/safety-browser-server.ts index 8bfc72703f..b0bc71824c 100644 --- a/packages/ui-react/tests/fixtures/safety-browser-server.ts +++ b/packages/ui-react/tests/fixtures/safety-browser-server.ts @@ -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'; @@ -10,7 +11,11 @@ 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'); +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(); // Test-only bootstrap supplies the fixture principal to a real WS host. HTTP // mutations below still traverse the actual cookie/Origin/owner route stack. diff --git a/packages/ui-react/tests/safety-client.test.ts b/packages/ui-react/tests/safety-client.test.ts index da0f82b054..e7ba046ad1 100644 --- a/packages/ui-react/tests/safety-client.test.ts +++ b/packages/ui-react/tests/safety-client.test.ts @@ -130,3 +130,50 @@ 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"); + client.frame({ type: "safety_history", requestId: fresh.requestId, + page: { ...page, snapshotId: "recovery_snapshot", nextCursor: "recovery_page_2", snapshotComplete: false } }); + expect(safety.getState().status).toBe("partial"); + expect(sent.at(-1)).toMatchObject({ type: "safety_read", requestId: fresh.requestId, cursor: "recovery_page_2" }); + client.frame({ type: "safety_history", requestId: fresh.requestId, + page: { ...page, snapshotId: "recovery_snapshot", cursor: "recovery_page_2" } }); + expect(safety.getState().status).toBe("ready"); + expect(sent.at(-1)).toMatchObject({ type: "safety_subscribe", requestId: fresh.requestId, snapshotId: "recovery_snapshot" }); + 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(); } + }); +} From f4b11154ce9440c755b4bd9a11981c935965c257 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 15:19:33 +0000 Subject: [PATCH 2/3] fix(ui-react): bound consecutive safety capacity recovery --- packages/ui-react/src/lib/safety-client.ts | 15 ++++-- packages/ui-react/tests/safety-client.test.ts | 50 +++++++++++++++++++ 2 files changed, 61 insertions(+), 4 deletions(-) diff --git a/packages/ui-react/src/lib/safety-client.ts b/packages/ui-react/src/lib/safety-client.ts index 73b79b808b..3ae984effc 100644 --- a/packages/ui-react/src/lib/safety-client.ts +++ b/packages/ui-react/src/lib/safety-client.ts @@ -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; @@ -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. @@ -43,13 +44,19 @@ 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; // Lost subscriptions need a fresh snapshot; never replay a mutation. - // Capacity while paging is a read refusal, not another dropped delta. - const again=target&&(["gap","expired","generation_changed"].includes(msg.reason)||msg.reason==="capacity"&&!awaitingPage); + // 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&&(["gap","expired","generation_changed"].includes(msg.reason)||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; diff --git a/packages/ui-react/tests/safety-client.test.ts b/packages/ui-react/tests/safety-client.test.ts index e7ba046ad1..57cfd05ea4 100644 --- a/packages/ui-react/tests/safety-client.test.ts +++ b/packages/ui-react/tests/safety-client.test.ts @@ -177,3 +177,53 @@ for (const reason of ["capacity", "unauthorized", "unavailable"] as const) { } 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(); } + } +}); From 5b021368134959324d917c71e377dfbb66ba38c1 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 15:25:50 +0000 Subject: [PATCH 3/3] fix(ui-react): fence stale safety loss notices during recovery --- packages/ui-react/src/lib/safety-client.ts | 6 +- packages/ui-react/tests/safety-client.test.ts | 70 +++++++++++++++++-- 2 files changed, 71 insertions(+), 5 deletions(-) diff --git a/packages/ui-react/src/lib/safety-client.ts b/packages/ui-react/src/lib/safety-client.ts index 3ae984effc..fb8003254a 100644 --- a/packages/ui-react/src/lib/safety-client.ts +++ b/packages/ui-react/src/lib/safety-client.ts @@ -51,11 +51,15 @@ export function createSafetyClient(root:BrainUiServices,send:(message:ClientMess } if(msg.type==="safety_unavailable"){ if(msg.requestId&&msg.requestId!==requestId)return true; + 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&&(["gap","expired","generation_changed"].includes(msg.reason)||msg.reason==="capacity"&&!awaitingPage&&!capacityRecoveryUsed); + 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; } diff --git a/packages/ui-react/tests/safety-client.test.ts b/packages/ui-react/tests/safety-client.test.ts index 57cfd05ea4..6999ead275 100644 --- a/packages/ui-react/tests/safety-client.test.ts +++ b/packages/ui-react/tests/safety-client.test.ts @@ -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, @@ -150,14 +150,30 @@ for (const reason of ["gap", "expired", "generation_changed", "capacity"] as con 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: { ...page, snapshotId: "recovery_snapshot", nextCursor: "recovery_page_2", snapshotComplete: false } }); + 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: { ...page, snapshotId: "recovery_snapshot", cursor: "recovery_page_2" } }); + page: { ...normalPage, records: lastRecords, cursor: "recovery_page_2" } }); expect(safety.getState().status).toBe("ready"); - expect(sent.at(-1)).toMatchObject({ type: "safety_subscribe", requestId: fresh.requestId, snapshotId: "recovery_snapshot" }); + 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(); } }); @@ -227,3 +243,49 @@ test("only a valid advancing subscription update rearms capacity recovery", () = } 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(); } +});