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-selection.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@schlessera/brain-ui-react": patch
---

Show safety history as unavailable for host-only voice histories and unsupported stored session keys instead of sending rejected requests and waiting indefinitely.
13 changes: 12 additions & 1 deletion packages/ui-react/src/lib/safety-client.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { ClientMessage, ServerMessage, SafetyTarget } from "@schlessera/brain-ui-sdk/protocol";
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){
Expand All @@ -10,7 +11,17 @@ export function createSafetyClient(root:BrainUiServices,send:(message:ClientMess
send({type:"safety_unsubscribe",version:1});
send({type:"safety_read",version:1,requestId,target});
}
function selected():void{const id=root.stores.chat.getState().activeSessionId;if(id)read({sessionId:id});else{target=null;requestId=null;store.getState().unavailable("unavailable");if(store.getState().supported)send({type:"safety_unsubscribe",version:1});}}
function selected(): void {
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.
if (id && safetySessionKeySchema.shape.sessionId.safeParse(id).success) read({ sessionId: id });
else {
target = null; requestId = null; awaitingPage = false;
store.getState().unavailable("unavailable");
if (store.getState().supported) send({ type: "safety_unsubscribe", version: 1 });
}
}
const detach=root.stores.chat.subscribe((state,previous)=>{if(state.activeSessionId!==previous.activeSessionId)selected();});
return {
frame(msg:ServerMessage):boolean{
Expand Down
84 changes: 83 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,33 @@ 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 type { ClientMessage } from "@schlessera/brain-ui-sdk/protocol";
import { SAFETY_READ_CAPABILITIES, type ClientMessage, type SafetyPage } from "@schlessera/brain-ui-sdk/protocol";
import { parseClientMessage } from "@schlessera/brain-ui-sdk/schemas";

const hello = { type: "server_hello" as const, protocolRev: 5,
capabilities: { sessionSafetyHistory: true }, safetyCapabilities: SAFETY_READ_CAPABILITIES };
const page: SafetyPage = {
version: 1, identity: { sessionId: "ithaca", historyOwnerId: "odysseus", historyGeneration: "1" },
snapshotId: "voyage_snapshot", cursor: null, highWater: "0", records: [], nextCursor: null,
snapshotComplete: true, detailPruned: false,
projection: { session: { sessionId: "ithaca", historyOwnerId: "odysseus", historyGeneration: "1" },
evidenceRevision: "0", unresolvedCount: 0, earliestUnresolvedId: null, pendingCount: 0,
restriction: "restricted", reasons: ["coverage_unknown"],
coverage: { detectorVersion: 1, state: "incomplete", epochs: [], exclusions: [] } },
};

function supportedClient(activeSessionId: string) {
const chat = createStore<{ activeSessionId: string | null }>(() => ({ activeSessionId }));
const safety = createSafetyStore(), sent: ClientMessage[] = [];
const root = { stores: { chat, safety } } as unknown as BrainUiServices;
const client = createSafetyClient(root, message => { sent.push(message); return true; });
const checkWire = () => {
for (const message of sent) {
expect(parseClientMessage(JSON.stringify(message)), "SAFETY_CLIENT_FRAMES_MATCH_PUBLISHED_PARSER").toMatchObject({ ok: true });
}
};
return { chat, safety, sent, client, checkWire };
}

test("an old host receives no safety read or unsubscribe frames and remains explicitly unavailable",()=>{
for(const id of [null,"ithaca"]){
Expand All @@ -18,3 +44,59 @@ test("an old host receives no safety read or unsubscribe frames and remains expl
}finally{client.dispose();}
}
});

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);
try {
client.frame(hello);
checkWire();
expect(sent.some(message => message.type === "safety_read"), "INVALID_SELECTION_STARTS_NO_READ").toBe(false);
expect(safety.getState()).toMatchObject({ status: "unavailable", requestId: null, normal: false });

chat.setState({ activeSessionId: "ithaca" });
const read = sent.find(message => message.type === "safety_read");
if (read?.type !== "safety_read") throw new Error("Valid selection did not start its read");
expect(safety.getState().status).toBe("loading");
chat.setState({ activeSessionId: id });
expect(sent.at(-1)?.type, "INVALID_SELECTION_UNSUBSCRIBES").toBe("safety_unsubscribe");
client.frame({ type: "safety_history", requestId: read.requestId, page });
expect(safety.getState(), "OLD_PAGE_CANNOT_SETTLE_INVALID_SELECTION").toMatchObject({ status: "unavailable", requestId: null });

client.disconnected();
client.frame(hello);
client.refresh();
checkWire();
expect(sent.filter(message => message.type === "safety_read")).toHaveLength(1);
expect(safety.getState()).toMatchObject({ status: "unavailable", requestId: null, normal: false });
} finally { client.dispose(); }
}
});

test("valid sessions keep paging, subscription and gap recovery on the published wire", () => {
const { chat, safety, sent, client, checkWire } = supportedClient("ithaca");
try {
client.frame(hello);
const read = sent.find(message => message.type === "safety_read");
if (read?.type !== "safety_read") throw new Error("Missing initial read");
expect(read.target).toEqual({ sessionId: "ithaca" });
client.frame({ type: "safety_history", requestId: read.requestId,
page: { ...page, nextCursor: "voyage_page_2", snapshotComplete: false } });
expect(sent.at(-1)).toMatchObject({ type: "safety_read", requestId: read.requestId,
target: { sessionId: "ithaca" }, cursor: "voyage_page_2" });
expect(safety.getState().status).toBe("partial");
client.frame({ type: "safety_history", requestId: read.requestId, page: { ...page, cursor: "voyage_page_2" } });
expect(sent.at(-1)).toMatchObject({ type: "safety_subscribe", identity: page.identity, snapshotId: page.snapshotId });
expect(safety.getState().status).toBe("ready");
checkWire();

client.frame({ type: "safety_unavailable", version: 1, reason: "gap" });
expect(sent.at(-1)).toMatchObject({ type: "safety_read", target: { sessionId: "ithaca" } });
expect(safety.getState().status).toBe("loading");
chat.setState({ activeSessionId: "dialogue:odysseus" });
chat.setState({ activeSessionId: "7f9e2c1a-0000-4000-8000-000000000001" });
expect(sent.at(-1)).toMatchObject({ type: "safety_read", target: { sessionId: chat.getState().activeSessionId } });
client.refresh();
checkWire();
} finally { client.dispose(); }
});
Loading