diff --git a/.changeset/chat-store-slices.md b/.changeset/chat-store-slices.md new file mode 100644 index 0000000000..4a72bfcb3c --- /dev/null +++ b/.changeset/chat-store-slices.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-react": patch +--- + +The chat store is now built from separate slices for sessions, session status, messages, streaming, approvals, ask-user questions and transcript replay. It behaves as before: the store's state, actions, hooks and selectors are unchanged. diff --git a/docs/decisions/answer-delivery.md b/docs/decisions/answer-delivery.md index 8410fba3c2..cfb5282805 100644 --- a/docs/decisions/answer-delivery.md +++ b/docs/decisions/answer-delivery.md @@ -70,7 +70,7 @@ manufacture an identity, and it was not needed. ## One card per request The store updates a request it already holds and never appends it again -(`addExchange`, `packages/ui-react/src/stores/chat-state.ts:270-301`). A +(`addExchange`, `packages/ui-react/src/stores/chat-slices/ask-user.ts:32-63`). A settled card stays settled, so a late or replayed frame cannot revive a dismissed or answered question. A pending card keeps its payload and the exchange object it is keyed by, so a draft in progress survives a re-send. diff --git a/docs/investigations/live-conversation-investigation.md b/docs/investigations/live-conversation-investigation.md index 0e98526905..03cd358147 100644 --- a/docs/investigations/live-conversation-investigation.md +++ b/docs/investigations/live-conversation-investigation.md @@ -312,7 +312,7 @@ is unknown, not queued against a replacement request. Terminal state invalidates every pending exchange for that turn without waiting for `tool_result`. Current client terminal handling finishes the assistant message and resyncs; its message-state helper only marks streaming false -(`finishAssistantMessage`, `packages/ui-react/src/stores/chat-state.ts:1835-1840`). +(`finishAssistantMessage`, `packages/ui-react/src/stores/chat-slices/streaming.ts:27-32`). This observation is a required integration check, not proof that all cards currently clear. A host terminal event plus local audio drain/discard defines conversation completion; provider turn/audio end does not. diff --git a/docs/plans/navigation-recovery.md b/docs/plans/navigation-recovery.md index 1f5b17afbc..9e7d511c80 100644 --- a/docs/plans/navigation-recovery.md +++ b/docs/plans/navigation-recovery.md @@ -365,11 +365,11 @@ implementation. Any PR moving these lines owns their citation repairs. - New chat: (`{hasMessages && !wide && (`, `packages/ui-react/src/components/chat/chat-page.tsx:702-709`). -- Buffer eviction: (`function evictStale(`, `packages/ui-react/src/stores/chat-state.ts:1086-1102`). +- Buffer eviction: (`function evictStale(`, `packages/ui-react/src/stores/chat-slices/buffers.ts:61-76`). - Root namespace: (`const prefix = options.storagePrefix ??`, `packages/ui-react/src/root.ts:182-237`). -- Clear transcript selection: (`clearMessages: () => {`, `packages/ui-react/src/stores/chat-state.ts:2139-2148`). +- Clear transcript selection: (`clearMessages: () => {`, `packages/ui-react/src/stores/chat-slices/session.ts:116-125`). - Composer draft/acknowledgement: [`const [input, setInput] = useState("");`](https://github.com/schlessera/brain-kit/blob/7bfdc71074f4ff6243e0d7133e83dbb36eb2a971/packages/ui-react/src/components/chat/composer.tsx#L62-L85), before #951 moved the draft into the root's draft store (`stores/draft-state.ts`). @@ -401,7 +401,7 @@ implementation. Any PR moving these lines owns their citation repairs. - Queued acceptance: (`// Queue it as the session's next turn; report queued immediately.`, `packages/ui-server/src/ws/run-session.ts:1089-1134`). -- Approval target: (`function mutateLastAssistant(`, `packages/ui-react/src/stores/chat-state.ts:1233-1263`). +- Approval target: (`function mutateLastAssistant(`, `packages/ui-react/src/stores/chat-slices/buffers.ts:142-172`). ## Bounded follow-up ownership diff --git a/packages/ui-react/src/stores/chat-slices/approvals.ts b/packages/ui-react/src/stores/chat-slices/approvals.ts new file mode 100644 index 0000000000..5c4c57f693 --- /dev/null +++ b/packages/ui-react/src/stores/chat-slices/approvals.ts @@ -0,0 +1,199 @@ +/** + * Approvals (#1361): tool-permission cards — the request, its decision, + * the voice-permission receipt, and the closure, reopening and revocation of + * cards restored from history. + */ +import { POLICY_CHANGE_REVIEW_SCHEMA } from "@schlessera/brain-ui-sdk/tool-contracts"; +import type { ChatMessage, ChatState, SessionChat, ToolCall } from "../chat-state.js"; +import type { ChatSliceContext } from "./buffers.js"; + +export type ApprovalsSliceSlice = Pick; + +export function createApprovalsSlice(ctx: ChatSliceContext): ApprovalsSliceSlice { + const { set, get, nextId, mutateBuffer, mutateToolHolder } = ctx; + return { + requestToolApproval: (key, toolUseId, toolName, input, description, kind, rememberable, turnId) => + mutateBuffer(key, (chat) => { + const msgs = [...chat.messages]; + const request = (previous: ToolCall | undefined, restored: boolean): ToolCall => ({ + id: toolUseId, + name: toolName, + input, + inputJson: JSON.stringify(input, null, 2), + status: "pending_approval", + ...(kind ? { approvalKind: kind } : {}), + ...(kind === "policy" && POLICY_CHANGE_REVIEW_SCHEMA.safeParse(input.policyReview).success ? { policyChange: POLICY_CHANGE_REVIEW_SCHEMA.parse(input.policyReview) } : {}), + ...(rememberable === false ? { approvalRememberable: false } : {}), + ...(description ? { approvalDescription: description } : {}), + // A card already pending keeps what it was; anything else is + // restored when it lands on a message no live turn is streaming. + ...((previous?.status === "pending_approval" ? previous.restored : restored) + ? { restored: true as const, ...(turnId ? { approvalTurnId: turnId } : {}) } + : {}), + }); + // One card per request: a re-delivery updates the card wherever it + // is, and never draws a second one (#964). + const holder = msgs.findLastIndex((m) => m.role === "assistant" && m.toolCalls.some((t) => t.id === toolUseId)); + if (holder !== -1) { + const target = msgs[holder]!; + msgs[holder] = { + ...target, + // A card the host already closed with a reason (#1072) stays + // closed: a late duplicate of its request revives nothing. + toolCalls: target.toolCalls.map((t) => t.id !== toolUseId || (t.readOnly && t.readOnly !== "unlisted") ? t : request(t, !target.isStreaming)), + }; + return { messages: msgs }; + } + // The turn's own answer, when a message carries its id; otherwise + // the latest answer, if it is still streaming or comes after the + // user's latest message, and no other turn owns it. + let index = turnId ? msgs.findLastIndex((m) => m.role === "assistant" && m.turnId === turnId) : -1; + if (index === -1) { + const last = msgs.findLastIndex((m) => m.role === "assistant"); + const lastUser = msgs.findLastIndex((m) => m.role === "user"); + const candidate = last === -1 ? undefined : msgs[last]!; + if (candidate && (candidate.isStreaming || last > lastUser) && (!candidate.turnId || !turnId || candidate.turnId === turnId)) { + index = last; + } + } + if (index === -1) { + // No answer belongs to this turn: the replay ended on the user's + // message. Draw the turn's shell, holding only the card, with no + // invented text (D52 §4, approval recovery). + msgs.push({ + id: nextId(), + role: "assistant", + content: "", + toolCalls: [request(undefined, true)], + parts: [{ kind: "tool", toolIndex: 0 }], + isStreaming: false, + timestamp: Date.now(), + turnShell: true, + ...(turnId ? { turnId } : {}), + }); + return { messages: msgs }; + } + const last = msgs[index]!; + // Check if tool call already exists (from streaming) + const existingIdx = last.toolCalls.findIndex( + (t) => t.name === toolName && t.status === "streaming" + ); + const tools = [...last.toolCalls]; + const toolCall = request(undefined, !last.isStreaming); + let parts = last.parts; + if (existingIdx >= 0) { + tools[existingIdx] = toolCall; + } else { + // Approval request for a tool that never streamed a start event — + // give it a chronological slot too. + parts = [...parts, { kind: "tool", toolIndex: tools.length }]; + tools.push(toolCall); + } + msgs[index] = { ...last, toolCalls: tools, parts }; + return { messages: msgs }; + }), + + applyVoicePermission: (receipt) => { + const key = receipt.sessionId; + const chat = get().buffers[key]; + const owns = (m: ChatMessage, t: ToolCall) => t.id === receipt.toolUseId && (t.approvalTurnId ?? m.turnId ?? m.streamTurnId) === receipt.turnId; + if (!chat?.messages.some(m => m.toolCalls.some(t => owns(m, t) && t.voicePermission !== receipt))) return; + mutateBuffer(key, current => ({ messages: current.messages.map(m => ({ ...m, toolCalls: m.toolCalls.map(t => { + if (!owns(m, t)) return t; + // Receipt state locks decisions through awaitsDecision. Preserve the + // transcript status so ordinary result/recovery routing can still + // recognize an unanswered restored card and record its closure. + return { ...t, voicePermission: receipt }; + }) })) })); + }, + + resolveToolApproval: (key, toolUseId, approved) => + mutateToolHolder(key, toolUseId, (last) => ({ + ...last, + toolCalls: last.toolCalls.map((t) => + t.id === toolUseId + ? { + ...t, + status: approved ? ("approved" as const) : ("denied" as const), + // Don't let approval wait time inflate the duration badge + ...(approved ? { startedAt: Date.now() } : {}), + } + : t + ), + })), + + closeRestoredApprovals: (key, closures) => { + if (closures.length === 0) return; + const byId = new Map(closures.map((c) => [c.toolUseId, c.closure])); + mutateBuffer(key, (chat) => { + let changed = false; + const messages = chat.messages.map((m) => { + if (m.role !== "assistant" || !m.toolCalls.some((t) => byId.has(t.id))) return m; + let touched = false; + const toolCalls = m.toolCalls.map((t) => { + const closure = byId.get(t.id); + if (!closure || !t.restored || t.readOnly === closure) return t; + // Decided on this page: the card already says what happened. + if (t.status === "approved" || t.status === "denied") return t; + if (t.readOnly && t.readOnly !== "unlisted") return t; + touched = true; + return { ...t, readOnly: closure }; + }); + if (!touched) return m; + changed = true; + return { ...m, toolCalls }; + }); + return changed ? { messages } : {}; + }); + }, + + reopenRestoredApprovals: (key, toolUseIds) => { + const reopen = (t: ToolCall) => toolUseIds.includes(t.id) && t.readOnly === "unlisted" && t.status === "pending_approval"; + const chat = key === null ? get().draft : get().buffers[key]; + if (!chat?.messages.some((m) => m.toolCalls.some(reopen))) return; + mutateBuffer(key, (current) => ({ + messages: current.messages.map((m) => { + if (!m.toolCalls.some(reopen)) return m; + return { ...m, toolCalls: m.toolCalls.map((t) => { + if (!reopen(t)) return t; + const { readOnly: _closed, ...open } = t; + return open; + }) }; + }), + })); + }, + + revokeRestoredApprovals: () => + set((state) => { + const revoke = (chat: SessionChat): SessionChat => { + if (!chat.messages.some((m) => m.toolCalls.some((t) => t.restored && t.readOnly !== "revoked"))) return chat; + const messages = chat.messages.map((m) => { + if (!m.toolCalls.some((t) => t.restored && t.readOnly !== "revoked")) return m; + const toolCalls = m.toolCalls.map((t) => { + if (!t.restored || t.readOnly === "revoked") return t; + // The request's identity goes with the authority to answer + // it: the card keeps only what it showed. + const { approvalTurnId: _turn, ...rest } = t; + return { ...rest, id: `revoked-${nextId()}`, readOnly: "revoked" as const }; + }); + if (!m.turnShell) return { ...m, toolCalls }; + const { turnId: _shellTurn, ...shell } = m; + return { ...shell, toolCalls }; + }); + return { ...chat, messages }; + }; + const buffers = Object.fromEntries(Object.entries(state.buffers).map(([id, chat]) => [id, revoke(chat)])); + const changed = Object.keys(buffers).some((id) => buffers[id] !== state.buffers[id]); + const draft = state.draft ? revoke(state.draft) : state.draft; + if (!changed && draft === state.draft) return state; + return { buffers, draft }; + }), + }; +} diff --git a/packages/ui-react/src/stores/chat-slices/ask-user.ts b/packages/ui-react/src/stores/chat-slices/ask-user.ts new file mode 100644 index 0000000000..7887213175 --- /dev/null +++ b/packages/ui-react/src/stores/chat-slices/ask-user.ts @@ -0,0 +1,223 @@ +/** + * Ask-user exchanges (#1361): question, list, rank and form cards, their + * answers, dismissal and reopening, and the delivery state of each answer. + */ +import type { AskUserExchange, ChatState, SessionChat } from "../chat-state.js"; +import type { ChatSliceContext } from "./buffers.js"; + +/** The exchange has an outcome: answered (in any of the four shapes) or dismissed. */ +export function isSettledExchange(exchange: AskUserExchange): boolean { + return !!(exchange.answers || exchange.order || exchange.formAnswers || exchange.cancelled); +} + +/** + * Open an ask exchange: attached to the streaming assistant message, where the + * transcript draws it, and held as the session's pending exchange. `ask_user` + * and `ask_user_list` share the slot, so the composer, the suggestions row and + * the tool-result cleanup treat either the same way. + * + * One request is one card (#910). The host re-delivers a pending request on + * every reconnect and after `session_resume`, and history may already have + * rebuilt it under the same id, so a request already in the buffer is + * UPDATED, never appended again: + * + * - a settled card stays settled: a late or replayed request frame cannot + * revive an answered or dismissed question; + * - a pending card keeps its payload and whatever the user is drafting in it, + * and learns its turn if it did not know it; + * - a request claiming a different turn than the card already holds is a + * contradiction, not an update, and is ignored. The host's receipt is what + * decides which binding is real. + */ +function addExchange( + chat: SessionChat, + exchange: AskUserExchange +): Partial> { + for (let i = chat.messages.length - 1; i >= 0; i--) { + const message = chat.messages[i]!; + const index = message.askUserExchanges?.findIndex((e) => e.requestId === exchange.requestId) ?? -1; + if (index === -1) continue; + const existing = message.askUserExchanges![index]!; + if (isSettledExchange(existing)) return {}; + if (existing.turnId && exchange.turnId && existing.turnId !== exchange.turnId) return {}; + const merged: AskUserExchange = + existing.turnId || !exchange.turnId ? existing : { ...existing, turnId: exchange.turnId }; + const msgs = [...chat.messages]; + const exchanges = [...message.askUserExchanges!]; + exchanges[index] = merged; + msgs[i] = { ...message, askUserExchanges: exchanges }; + const slot = chat.askUser; + const askUser = !slot || slot.requestId === merged.requestId || isSettledExchange(slot) ? merged : slot; + return { messages: msgs, askUser }; + } + const msgs = [...chat.messages]; + const lastIdx = msgs.length - 1; + const last = msgs[lastIdx]; + if (last?.role === "assistant") { + msgs[lastIdx] = { + ...last, + askUserExchanges: [...(last.askUserExchanges ?? []), exchange], + }; + } + return { messages: msgs, askUser: exchange }; +} + +export type AskUserSliceSlice = Pick; + +export function createAskUserSlice(ctx: ChatSliceContext): AskUserSliceSlice { + const { set, mutateBuffer } = ctx; + return { + setAskUserRequest: (key, requestId, questions, turnId) => + mutateBuffer(key, (chat) => addExchange(chat, { requestId, questions, ...(turnId ? { turnId } : {}) })), + + setAskUserListRequest: (key, requestId, list, turnId) => + mutateBuffer(key, (chat) => addExchange(chat, { requestId, questions: [], list, ...(turnId ? { turnId } : {}) })), + + setAskUserRankRequest: (key, requestId, rank, turnId) => + mutateBuffer(key, (chat) => addExchange(chat, { requestId, questions: [], rank, ...(turnId ? { turnId } : {}) })), + + submitAskUserRankOrder: (key, requestId, order, unchanged) => + mutateBuffer(key, (chat) => { + const answeredAt = Date.now(); + const update = (e: AskUserExchange): AskUserExchange => + e.requestId === requestId + ? { ...e, order, unchanged, answeredAt } + : e; + const msgs = chat.messages.map((m) => + m.askUserExchanges?.some((e) => e.requestId === requestId) + ? { ...m, askUserExchanges: m.askUserExchanges.map(update) } + : m + ); + const askUser = + chat.askUser?.requestId === requestId ? update(chat.askUser) : chat.askUser; + return { messages: msgs, askUser }; + }), + + setAskUserFormRequest: (key, requestId, form, turnId) => + mutateBuffer(key, (chat) => addExchange(chat, { requestId, questions: [], form, ...(turnId ? { turnId } : {}) })), + + submitAskUserFormAnswers: (key, requestId, formAnswers, visibleNodes) => + mutateBuffer(key, (chat) => { + const answeredAt = Date.now(); + const update = (e: AskUserExchange): AskUserExchange => + e.requestId === requestId + ? { ...e, formAnswers, visibleNodes, answeredAt } + : e; + const msgs = chat.messages.map((m) => + m.askUserExchanges?.some((e) => e.requestId === requestId) + ? { ...m, askUserExchanges: m.askUserExchanges.map(update) } + : m + ); + const askUser = + chat.askUser?.requestId === requestId ? update(chat.askUser) : chat.askUser; + return { messages: msgs, askUser }; + }), + + submitAskUserListAnswers: (key, requestId, answers, notes) => + mutateBuffer(key, (chat) => { + const answeredAt = Date.now(); + const update = (e: AskUserExchange): AskUserExchange => + e.requestId === requestId + ? { ...e, answers, answeredAt, ...(notes && Object.keys(notes).length ? { notes } : {}) } + : e; + const msgs = chat.messages.map((m) => + m.askUserExchanges?.some((e) => e.requestId === requestId) + ? { ...m, askUserExchanges: m.askUserExchanges.map(update) } + : m + ); + const askUser = + chat.askUser?.requestId === requestId ? update(chat.askUser) : chat.askUser; + return { messages: msgs, askUser }; + }), + + submitAskUserAnswers: (key, requestId, answers, annotations, typed) => + mutateBuffer(key, (chat) => { + const answeredAt = Date.now(); + const update = (e: AskUserExchange): AskUserExchange => + e.requestId === requestId + ? { ...e, answers, annotations, answeredAt, ...(typed ? { typed: true } : {}) } + : e; + const msgs = chat.messages.map((m) => + m.askUserExchanges?.some((e) => e.requestId === requestId) + ? { ...m, askUserExchanges: m.askUserExchanges.map(update) } + : m + ); + const askUser = + chat.askUser?.requestId === requestId ? update(chat.askUser) : chat.askUser; + return { messages: msgs, askUser }; + }), + + cancelAskUser: (key, requestId) => + mutateBuffer(key, (chat) => { + const update = (e: AskUserExchange): AskUserExchange => + e.requestId === requestId ? { ...e, cancelled: true } : e; + const msgs = chat.messages.map((m) => + m.askUserExchanges?.some((e) => e.requestId === requestId) + ? { ...m, askUserExchanges: m.askUserExchanges.map(update) } + : m + ); + const askUser = + chat.askUser?.requestId === requestId ? update(chat.askUser) : chat.askUser; + return { messages: msgs, askUser }; + }), + + reopenAskExchange: (key, requestId) => + mutateBuffer(key, (chat) => { + let reopened: AskUserExchange | null = null; + const msgs = chat.messages.map((m) => { + if (!m.askUserExchanges?.some((e) => e.requestId === requestId)) return m; + return { + ...m, + askUserExchanges: m.askUserExchanges.map((e) => { + if (e.requestId !== requestId) return e; + const { + answers: _a, annotations: _n, notes: _o, order: _r, unchanged: _u, + formAnswers: _f, visibleNodes: _v, typed: _t, answeredAt: _w, cancelled: _c, + ...rest + } = e; + reopened = rest; + return rest; + }), + }; + }); + return reopened ? { messages: msgs, askUser: reopened } : {}; + }), + + deliveries: {}, + setDelivery: (requestId, delivery) => + set((state) => { + const deliveries = { ...state.deliveries }; + if (delivery) deliveries[requestId] = delivery; + else delete deliveries[requestId]; + return { deliveries }; + }), + + clearAskUser: (key) => mutateBuffer(key, () => ({ askUser: null })), + + endTurnQuestions: (key, turnId) => mutateBuffer(key, (chat) => { + const end = (exchange: AskUserExchange): AskUserExchange => { + if ((turnId && exchange.turnId !== turnId) || exchange.answers || exchange.order || exchange.formAnswers || exchange.cancelled) return exchange; + return { ...exchange, cancelled: true, terminal: true }; + }; + return { + messages: chat.messages.map((message) => message.askUserExchanges ? { ...message, askUserExchanges: message.askUserExchanges.map(end) } : message), + askUser: chat.askUser ? end(chat.askUser) : null, + }; + }), + }; +} diff --git a/packages/ui-react/src/stores/chat-slices/buffers.ts b/packages/ui-react/src/stores/chat-slices/buffers.ts new file mode 100644 index 0000000000..90e4176c2d --- /dev/null +++ b/packages/ui-react/src/stores/chat-slices/buffers.ts @@ -0,0 +1,175 @@ +/** + * The buffers every chat slice writes through (#1361): the buffer + * constructor, the shared mutators, the buffer bound and the attachment + * preview URLs a dropped message releases. + */ +import type { StoreApi } from "zustand/vanilla"; +import type { ChatKey, ChatMessage, ChatState, MessagePart, SessionChat } from "../chat-state.js"; + +export type ChatSet = StoreApi["setState"]; +export type ChatGet = StoreApi["getState"]; + +/** What every slice of one chat store shares. */ +export interface ChatSliceContext { + set: ChatSet; + get: ChatGet; + /** A new message id, unique within this store. */ + nextId(): string; + mutateBuffer(key: ChatKey, fn: (chat: SessionChat) => Partial, createIfMissing?: boolean): void; + mutateToolHolder(key: ChatKey, toolUseId: string, fn: (msg: ChatMessage) => ChatMessage): void; + mutateLastAssistant(key: ChatKey, fn: (msg: ChatMessage) => ChatMessage, extra?: (chat: SessionChat) => Partial): void; +} + +/** Retained transcript buffers beyond the active one (LRU-evicted). */ +const MAX_BUFFERS = 8; + +export function emptyChat(): SessionChat { + return { messages: [], isStreaming: false, askUser: null, lastTouched: Date.now() }; +} + +/** Append text to the last part if it has the same kind, else start a new part. */ +export function appendPart( + parts: MessagePart[], + kind: "thinking" | "text", + text: string +): MessagePart[] { + const last = parts[parts.length - 1]; + if (last && last.kind === kind) { + return [...parts.slice(0, -1), { kind, text: last.text + text }]; + } + return [...parts, { kind, text }]; +} + +/** The message with no retry notice: the turn moved on, or ended. */ +export function withoutRetry(message: ChatMessage): ChatMessage { + if (!message.retry) return message; + const { retry: _retry, ...rest } = message; + return rest; +} + +/** Free object URLs held by live message previews before dropping them. */ +export function revokeAttachmentUrls(messages: ChatMessage[], retained: ChatMessage[] = []) { + const kept = new Set(retained.flatMap((m) => (m.attachments ?? []).map((a) => a.previewUrl))); + for (const m of messages) { + for (const a of m.attachments ?? []) { + if (a.previewUrl.startsWith("blob:") && !kept.has(a.previewUrl)) URL.revokeObjectURL(a.previewUrl); + } + } +} + +/** Evict least-recently-touched non-active buffers beyond MAX_BUFFERS. */ +export function evictStale( + buffers: Record, + activeSessionId: string | null +): Record { + const ids = Object.keys(buffers); + if (ids.length <= MAX_BUFFERS) return buffers; + const evictable = ids + .filter((id) => id !== activeSessionId && !buffers[id].isStreaming) + .sort((a, b) => buffers[a].lastTouched - buffers[b].lastTouched); + const next = { ...buffers }; + for (const id of evictable.slice(0, ids.length - MAX_BUFFERS)) { + revokeAttachmentUrls(next[id].messages); + delete next[id]; + } + return next; +} + +/** The shared buffer mutators of one store, over its `set`. */ +export function createChatSliceContext(set: ChatSet, get: ChatGet): ChatSliceContext { + let messageCounter = 0; + function nextId() { + return `msg-${++messageCounter}-${Date.now()}`; + } + + /** + * Immutably update one buffer. Draft mutations (key null) create the draft + * on demand; session mutations require an existing buffer — a frame for an + * evicted/never-opened session must not materialize a partial transcript + * (the view heals via session_resume instead). + */ + function mutateBuffer( + key: ChatKey, + fn: (chat: SessionChat) => Partial, + createIfMissing = false + ): void { + function updated(chat: SessionChat): SessionChat { + const next = { ...chat, ...fn(chat), lastTouched: Date.now() }; + if (!next.journals) return next; + const last = new Map(); + next.messages.forEach((message, index) => { const id = message.turnId ?? message.streamTurnId; if (message.role === "assistant" && id) last.set(id, index); }); + next.messages = next.messages.map((message, index) => { + const id = message.turnId ?? message.streamTurnId, receipt = id && next.journals?.[id]; + if (!receipt || last.get(id!) !== index || message.journal === receipt) return message; + return { ...message, journal: receipt, journalLive: true }; + }); + return next; + } + set((state) => { + if (key === null) { + const draft = state.draft ?? emptyChat(); + return { draft: updated(draft) }; + } + const existing = state.buffers[key] ?? (createIfMissing ? emptyChat() : undefined); + if (!existing) return state; + return { + buffers: { + ...state.buffers, + [key]: updated(existing), + }, + }; + }); + } + + /** + * Update the assistant message that holds tool call `toolUseId`, else the + * last assistant message. A restored approval can sit in a turn shell + * (#964) while the turn's later output streams into a newer message, and + * its decision and result must still reach the card. + */ + function mutateToolHolder(key: ChatKey, toolUseId: string, fn: (msg: ChatMessage) => ChatMessage): void { + mutateBuffer(key, (chat) => { + let index = chat.messages.findLastIndex((m) => m.role === "assistant" && m.toolCalls.some((t) => t.id === toolUseId)); + if (index === -1) index = chat.messages.findLastIndex((m) => m.role === "assistant"); + if (index === -1) return {}; + const msgs = [...chat.messages]; + msgs[index] = fn(msgs[index]!); + return { messages: msgs }; + }); + } + + /** Update the last message of a buffer when it is an assistant message. */ + function mutateLastAssistant( + key: ChatKey, + fn: (msg: ChatMessage) => ChatMessage, + extra?: (chat: SessionChat) => Partial + ): void { + mutateBuffer(key, (chat) => { + const msgs = [...chat.messages]; + // The last ASSISTANT message, not the last message. + // + // A follow-up sent mid-stream appends a user message to the end of the + // buffer while the assistant is still streaming into the message before + // it. Indexing the end therefore aimed every subsequent delta at the + // user's own message, where `role === "assistant"` failed and the write + // was silently discarded — the turn kept running and its output stopped + // appearing. Scanning backwards costs nothing at these lengths and + // leaves single-message behaviour identical. + let index = -1; + for (let i = msgs.length - 1;i >= 0;i--) { + if (msgs[i].role === "assistant") { + index = i; + break; + } + } + let out: Partial = {}; + if (index !== -1) { + msgs[index] = fn(msgs[index]); + out = { messages: msgs }; + } + return extra ? { ...out, ...extra(chat) } : out; + }); + } + + return { set, get, nextId, mutateBuffer, mutateToolHolder, mutateLastAssistant }; +} diff --git a/packages/ui-react/src/stores/chat-slices/messages.ts b/packages/ui-react/src/stores/chat-slices/messages.ts new file mode 100644 index 0000000000..b802d8cb94 --- /dev/null +++ b/packages/ui-react/src/stores/chat-slices/messages.ts @@ -0,0 +1,191 @@ +/** + * Messages (#1361): the user's message, the assistant's streamed text, + * thinking and tool calls, and the per-message annotations a turn adds + * while it runs. + */ +import type { ChatState, SessionChat } from "../chat-state.js"; +import type { ChatSliceContext } from "./buffers.js"; +import { appendPart, withoutRetry } from "./buffers.js"; + +export type MessagesSliceSlice = Pick; + +export function createMessagesSlice(ctx: ChatSliceContext): MessagesSliceSlice { + const { set, nextId, mutateBuffer, mutateToolHolder, mutateLastAssistant } = ctx; + return { + setMessageEffort(key, requestId, thinkingLevel, effectiveThinkingLevel) { + mutateBuffer(key, (chat) => ({ messages: chat.messages.map((message) => message.role === "user" && message.requestId === requestId + ? { ...message, thinkingLevel, ...(effectiveThinkingLevel !== undefined ? { effectiveThinkingLevel } : {}) } : message) })); + }, + + setRetryHandle: (key, retryOfTurnId) => mutateLastAssistant(key, last => ({ ...last, retryOfTurnId })), + + // createIfMissing: a user-initiated send must never be dropped, even when + // the active session's buffer hasn't been materialized yet (cold start + // racing the history replay). + addUserMessage: (key, text, source, attachments, effort, files) => + mutateBuffer( + key, + (chat) => ({ + messages: [ + ...chat.messages, + { + id: nextId(), + role: "user", + content: text, + toolCalls: [], + parts: [], + isStreaming: false, + timestamp: Date.now(), + source: source ?? "typed", + ...effort, + ...(files?.length ? { files } : {}), + ...(attachments && attachments.length > 0 + ? { attachments, attachmentCount: attachments.length } + : {}), + }, + ], + }), + true + ), + + startAssistantMessage: (key, turnId, requestId) => + mutateBuffer(key, (chat) => ({ + messages: [ + ...chat.messages, + { + id: nextId(), + role: "assistant", + content: "", + thinking: "", + toolCalls: [], + parts: [], + isStreaming: true, + timestamp: Date.now(), + ...(turnId ? { turnId } : {}), + ...(requestId ? { requestId } : {}), + }, + ], + isStreaming: true, + })), + + appendText: (key, text) => + mutateLastAssistant(key, (last) => ({ + ...withoutRetry(last), + content: last.content + text, + parts: appendPart(last.parts, "text", text), + })), + + setStatsAnswer: (key, sections) => + mutateLastAssistant(key, (last) => ({ ...last, statsAnswer: sections })), + + setLocalExchange: (key, exchange) => + mutateLastAssistant(key, (last) => ({ ...last, localExchange: exchange })), + + markLocalExchange: (exchangeId, saved, reason) => + set((state) => { + const mark = (chat: SessionChat): SessionChat | null => { + const index = chat.messages.findIndex((m) => m.localExchange?.id === exchangeId); + if (index === -1) return null; + const messages = [...chat.messages]; + const current = messages[index]!; + const { reason: _previous, ...exchange } = current.localExchange!; + messages[index] = { + ...current, + localExchange: { ...exchange, saved, ...(reason ? { reason } : {}) }, + }; + return { ...chat, messages }; + }; + const draft = state.draft ? mark(state.draft) : null; + if (draft) return { draft }; + for (const [key, chat] of Object.entries(state.buffers)) { + const marked = mark(chat); + if (marked) return { buffers: { ...state.buffers, [key]: marked } }; + } + return state; + }), + + appendThinking: (key, text) => + mutateLastAssistant(key, (last) => ({ + ...withoutRetry(last), + thinking: (last.thinking || "") + text, + parts: appendPart(last.parts, "thinking", text), + })), + + startToolCall: (key, toolUseId, toolName) => + mutateLastAssistant(key, (last) => ({ + ...last, + parts: [...last.parts, { kind: "tool", toolIndex: last.toolCalls.length }], + toolCalls: [ + ...last.toolCalls, + { + id: toolUseId, + name: toolName, + input: {}, + inputJson: "", + status: "streaming", + startedAt: Date.now(), + }, + ], + })), + + appendToolInput: (key, partialJson) => + mutateLastAssistant(key, (last) => { + if (last.toolCalls.length === 0) return last; + const tools = [...last.toolCalls]; + const lastTool = tools[tools.length - 1]; + tools[tools.length - 1] = { + ...lastTool, + inputJson: lastTool.inputJson + partialJson, + }; + return { ...last, toolCalls: tools }; + }), + + completeToolCall: (key, toolUseId, toolName, input) => + mutateLastAssistant(key, (last) => ({ + ...last, + toolCalls: last.toolCalls.map((t) => + t.id === toolUseId || (t.name === toolName && t.status === "streaming") + ? { + ...t, + id: toolUseId, + input, + status: "complete" as const, + // Input finished streaming — execution starts about now + startedAt: Date.now(), + } + : t + ), + })), + + setToolResult: (key, toolUseId, output, isError, policyChange) => + mutateToolHolder(key, toolUseId, (last) => ({ + ...last, + toolCalls: last.toolCalls.map((t) => + t.id === toolUseId + ? { + ...t, + output, + isError, + ...(policyChange ? { policyChange } : {}), + status: "complete" as const, + endedAt: Date.now(), + } + : t + ), + })), + }; +} diff --git a/packages/ui-react/src/stores/chat-slices/persistence.ts b/packages/ui-react/src/stores/chat-slices/persistence.ts new file mode 100644 index 0000000000..3e31404b69 --- /dev/null +++ b/packages/ui-react/src/stores/chat-slices/persistence.ts @@ -0,0 +1,88 @@ +/** + * What the chat store keeps in browser storage (#1361): the selected + * session, the state-room dismissals and the pending turn retries. Every + * reader tolerates a missing, corrupt or foreign value. + */ +import type { ChatState, PendingTurnRetry } from "../chat-state.js"; +import type { StoreEnvironment } from "../store-environment.js"; + +export type ChatPersistence = ReturnType; + +export function createChatPersistence(env: StoreEnvironment) { + const SESSION_ID_KEY = env.storageKey("brain-sessionId"); + const HISTORY_SELECTION_KEY = env.storageKey("brain-history-selection"); + function readHistorySelection():{key:string;ownerId:string}|null { + try {const value:unknown=JSON.parse(env.storage()?.getItem(HISTORY_SELECTION_KEY) ?? "null"); + if(value && typeof value === "object" && "key" in value && "ownerId" in value && typeof value.key === "string" && typeof value.ownerId === "string" && value.key.length<=512 && value.ownerId.length<=256)return {key:value.key,ownerId:value.ownerId}; + }catch{/* A corrupt selection grants no routing authority. */}return null; + } + const STATE_ROOM_KEY = env.storageKey("brain-state-room-preferences"); + function readStateRoomPreferences(): ChatState["stateRoomPreferences"] { + try { + const parsed: unknown = JSON.parse(env.storage()?.getItem(STATE_ROOM_KEY) ?? "{}"); + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {}; + return Object.fromEntries(Object.entries(parsed).flatMap(([sessionId, value]) => { + if (!value || typeof value !== "object" || Array.isArray(value)) return []; + const preference = value as { dismissedAllowance?: unknown; invalidatedAt?: unknown; backendId?: unknown; measuredAt?: unknown }; + const valid = (n: unknown): n is number => typeof n === "number" && Number.isSafeInteger(n) && n >= 0; + return [[sessionId, { + ...(valid(preference.dismissedAllowance) && preference.dismissedAllowance > 0 ? { dismissedAllowance: preference.dismissedAllowance } : {}), + ...(valid(preference.invalidatedAt) ? { invalidatedAt: preference.invalidatedAt } : {}), + ...(typeof preference.backendId === "string" && preference.backendId.length <= 200 ? { backendId: preference.backendId } : {}), + ...(valid(preference.measuredAt) ? { measuredAt: preference.measuredAt } : {}), + }]]; + })); + } catch { return {}; } + } + function persistStateRoomPreferences(preferences: ChatState["stateRoomPreferences"]): void { + try { env.storage()?.setItem(STATE_ROOM_KEY, JSON.stringify(preferences)); } catch { /* The in-memory dismissal still holds. */ } + } + + /** + * Persist the active session id to localStorage when a DOM is present (the + * browser). A no-op in non-DOM environments (tests, SSR) so creating the store + * never throws on a missing `localStorage`. + */ + function persistSessionId(id: string | null, ownerId?:string) { + const storage = env.storage(); + if (!storage) return; + if(id && ownerId){storage.setItem(HISTORY_SELECTION_KEY,JSON.stringify({key:id,ownerId}));storage.removeItem(SESSION_ID_KEY);} + else {if(id) storage.setItem(SESSION_ID_KEY,id);else storage.removeItem(SESSION_ID_KEY);storage.removeItem(HISTORY_SELECTION_KEY);} + } + + function readPersistedSessionId(): string | null { + const storage = env.storage(); + if (!storage) return null; + return readHistorySelection()?.key ?? storage.getItem(SESSION_ID_KEY); + } + + + const RETRIES_KEY = env.storageKey("brain-turn-retries"); + function readRetries(): Record { + try { + const value: unknown = JSON.parse(env.storage()?.getItem(RETRIES_KEY) ?? "{}"); + if (!value || typeof value !== "object") return {}; + return Object.fromEntries(Object.entries(value).flatMap(([sessionId, retry]) => { + if (!retry || typeof retry !== "object") return []; + const r = retry as Partial; + return typeof r.requestId === "string" && typeof r.failedTurnId === "string" && (r.state === "waiting" || r.state === "unknown") + ? [[sessionId, { requestId: r.requestId, failedTurnId: r.failedTurnId, state: "unknown" as const }]] : []; + })); + } catch { return {}; } + } + function persistRetries(turnRetries: Record): void { + try { + env.storage()?.setItem(RETRIES_KEY, JSON.stringify(Object.fromEntries(Object.entries(turnRetries).filter(([, r]) => r.state !== "refused")))); + } catch { /* The host also consumes each failed-turn handle once. */ } + } + + return { + readHistorySelection, + readStateRoomPreferences, + persistStateRoomPreferences, + persistSessionId, + readPersistedSessionId, + readRetries, + persistRetries, + }; +} diff --git a/packages/ui-react/src/stores/chat-slices/session.ts b/packages/ui-react/src/stores/chat-slices/session.ts new file mode 100644 index 0000000000..19af7a042a --- /dev/null +++ b/packages/ui-react/src/stores/chat-slices/session.ts @@ -0,0 +1,164 @@ +/** + * Sessions (#1361): which buffer is in view, the draft before a session + * exists and its binding, history ownership and restore failures, and + * withdrawing a send the host refused. + */ +import type { StoreApi } from "zustand/vanilla"; +import type { ChatState, SessionChat } from "../chat-state.js"; +import type { ProviderState } from "../provider-state.js"; +import type { ChatSliceContext } from "./buffers.js"; +import { emptyChat, evictStale, revokeAttachmentUrls } from "./buffers.js"; +import type { ChatPersistence } from "./persistence.js"; + +export type SessionSliceSlice = Pick; + +export function createSessionSlice(ctx: ChatSliceContext, + persistence: ChatPersistence, + provider: StoreApi, + composerDrafts?: StoreApi<{ newChat(): void }>): SessionSliceSlice { + const { set, get } = ctx; + const { readHistorySelection, persistSessionId } = persistence; + const persistedSessionId = persistence.readPersistedSessionId(); + return { + // The stored selection gets its (empty, unconfirmed) buffer, as any + // selection does, so the session's own frames land while its history + // is restored (#1328). + buffers: persistedSessionId ? { [persistedSessionId]: emptyChat() } : {}, + draft: null, + pendingDraftId: null, + detachedDrafts: {}, + // localStorage (not sessionStorage) so the active session id survives the + // PWA process being killed on mobile — that durability is what lets a cold + // relaunch re-request the full transcript instead of showing nothing. + activeSessionId: persistedSessionId, + historyOwners: readHistorySelection() ? {[readHistorySelection()!.key]:readHistorySelection()!.ownerId} : {}, + setHistoryOwner(key,ownerId){ + const historyOwners={...get().historyOwners};if(ownerId)historyOwners[key]=ownerId;else delete historyOwners[key]; + set({historyOwners});if(get().activeSessionId===key)persistSessionId(key,ownerId ?? undefined); + }, + restoreFailures: {}, + failRestore: (sessionId, failure) => + set((state) => (state.buffers[sessionId]?.historyConfirmed && failure.reason !== "missing" + ? state + : { restoreFailures: { ...state.restoreFailures, [sessionId]: failure }, + ...(failure.reason === "missing" && state.buffers[sessionId] ? { buffers: { ...state.buffers, + [sessionId]: { ...state.buffers[sessionId]!, historyConfirmed: undefined } } } : {}), + })), + clearRestoreFailure: (sessionId) => + set((state) => { + if (!state.restoreFailures[sessionId]) return state; + const restoreFailures = { ...state.restoreFailures }; + delete restoreFailures[sessionId]; + return { restoreFailures }; + }), + + startDraftTurn: () => { + const id = + typeof crypto !== "undefined" && "randomUUID" in crypto + ? crypto.randomUUID() + : `draft-${Date.now()}-${Math.random().toString(36).slice(2)}`; + set({ pendingDraftId: id }); + return id; + }, + + bindDraftSession: (sessionId) => + set((state) => { + const adopted = state.buffers[sessionId] ?? state.draft ?? emptyChat(); + const buffers = evictStale( + // This client started the conversation: it holds all of it. + { ...state.buffers, [sessionId]: { ...adopted, lastTouched: Date.now(), historyConfirmed: true } }, + sessionId + ); + const followView = state.activeSessionId === null; + if (followView) persistSessionId(sessionId); + return { + buffers, + draft: null, + pendingDraftId: null, + ...(followView ? { activeSessionId: sessionId } : {}), + }; + }), + + setActiveSession: (sessionId) => + set((state) => { + persistSessionId(sessionId,sessionId ? state.historyOwners[sessionId] : undefined); + if (sessionId === null) return { activeSessionId: null }; + const existing = state.buffers[sessionId]; + const buffers = existing + ? state.buffers + : evictStale({ ...state.buffers, [sessionId]: emptyChat() }, sessionId); + // Selecting a session again is a new attempt at restoring it (#1328). + let restoreFailures = state.restoreFailures; + if (sessionId !== state.activeSessionId && restoreFailures[sessionId]) { + restoreFailures = { ...restoreFailures }; + delete restoreFailures[sessionId]; + } + return { activeSessionId: sessionId, buffers, restoreFailures }; + }), + + clearMessages: () => { + const state = get(); + // A first message still unanswered keeps its transcript, aside: its + // announcement binds it there, not to whatever the view shows next. + const detach = state.draft && state.pendingDraftId ? state.pendingDraftId : null; + if (state.draft && !detach) revokeAttachmentUrls(state.draft.messages); + persistSessionId(null); + // Starting fresh: unpin the provider so the picker unlocks. + provider.getState().setPinned(null); + composerDrafts?.getState().newChat(); + set({ + draft: null, + activeSessionId: null, + ...(detach ? { pendingDraftId: null, detachedDrafts: { ...state.detachedDrafts, [detach]: state.draft! } } : {}), + }); + }, + + bindDetachedDraft: (correlationId, sessionId) => + set((state) => { + const adopted = state.detachedDrafts[correlationId]; + if (!adopted) return state; + const detachedDrafts = { ...state.detachedDrafts }; + delete detachedDrafts[correlationId]; + const existing = state.buffers[sessionId]; + return { + detachedDrafts, + buffers: evictStale( + { ...state.buffers, [sessionId]: existing ?? { ...adopted, lastTouched: Date.now(), historyConfirmed: true } }, + state.activeSessionId ?? sessionId + ), + }; + }), + + withdrawSend: (key, requestId) => + set((state) => { + const strip = (chat: SessionChat): SessionChat => { + const messages = chat.messages.filter((m) => !(m.requestId === requestId && (m.role === "user" || (!m.turnId && !m.content && !m.thinking && m.toolCalls.length === 0)))); + if (messages.length === chat.messages.length) return chat; + return { ...chat, messages, isStreaming: chat.isStreaming && messages.some((m) => m.role === "assistant" && m.isStreaming) }; + }; + if (key !== null) { + const buffer = state.buffers[key]; + return buffer ? { buffers: { ...state.buffers, [key]: strip(buffer) } } : state; + } + const detachedDrafts = Object.fromEntries(Object.entries(state.detachedDrafts).map(([id, chat]) => [id, strip(chat)])); + return { ...(state.draft ? { draft: strip(state.draft) } : {}), detachedDrafts }; + }), + }; +} diff --git a/packages/ui-react/src/stores/chat-slices/status.ts b/packages/ui-react/src/stores/chat-slices/status.ts new file mode 100644 index 0000000000..c20f7895cb --- /dev/null +++ b/packages/ui-react/src/stores/chat-slices/status.ts @@ -0,0 +1,136 @@ +/** + * Session status (#1361): run state and queue notes, backend and + * state-room readings, send and scope-decision receipts, pending turn + * retries, and composer insert requests. + */ +import type { ChatState } from "../chat-state.js"; +import type { ChatSliceContext } from "./buffers.js"; +import type { ChatPersistence } from "./persistence.js"; + +export type StatusSliceSlice = Pick; + +export function createStatusSlice(ctx: ChatSliceContext, persistence: ChatPersistence): StatusSliceSlice { + const { set, get } = ctx; + const { readRetries, persistRetries, readStateRoomPreferences, persistStateRoomPreferences } = persistence; + /** Monotonic per store, so every take is a new request. */ + let composerInsertSeq = 0; + return { + scopeDecisionReceipts: {}, + setScopeDecisionReceipt(receipt) { + const entries = Object.entries(get().scopeDecisionReceipts).filter(([id]) => id !== receipt.eventId).slice(-255); + set({ scopeDecisionReceipts: Object.fromEntries([...entries, [receipt.eventId, receipt]]) }); + }, + chatReceipts: {}, + setChatReceipt(requestId, state, sessionId) { + if (get().chatReceipts[requestId]?.state === "accepted") return; + const entries = Object.entries(get().chatReceipts).filter(([id]) => id !== requestId).slice(-255); + set({ chatReceipts: Object.fromEntries([...entries, [requestId, { state, sessionId }]]) }); + }, + clearChatReceipt(requestId) { + const chatReceipts = { ...get().chatReceipts }; + delete chatReceipts[requestId]; + set({ chatReceipts }); + }, + + turnRetries: readRetries(), + setTurnRetry(sessionId, retry) { + const turnRetries = { ...get().turnRetries }; + if (retry) turnRetries[sessionId] = retry; + else delete turnRetries[sessionId]; + persistRetries(turnRetries); + set({ turnRetries }); + }, + + runStates: {}, + queueNotes: {}, + backendIds: {}, + stateRooms: {}, + stateRoomPreferences: readStateRoomPreferences(), + stateRoomAnnouncements: {}, + setStateRoom(sessionId, observation, historical = false) { + const rooms = { ...get().stateRooms }; + const current = rooms[sessionId]; + if (observation && current && current.observation.observedAt > observation.observedAt) return; + if (historical && current && !current.historical && (!observation || current.observation.observedAt === observation.observedAt)) return; + if (observation) rooms[sessionId] = { observation, historical }; + else delete rooms[sessionId]; + const preferences = { ...get().stateRoomPreferences }; + if (observation && !historical && (preferences[sessionId]?.invalidatedAt !== undefined + || (preferences[sessionId]?.dismissedAllowance !== undefined && preferences[sessionId]!.dismissedAllowance !== observation.allowanceBytes))) { + const dismissed = preferences[sessionId]?.dismissedAllowance; + preferences[sessionId] = { ...(dismissed === observation.allowanceBytes ? { dismissedAllowance: dismissed } : {}) }; + persistStateRoomPreferences(preferences); + } + set({ stateRooms: rooms, stateRoomPreferences: preferences }); + }, + dismissStateRoom(sessionId, allowanceBytes) { + const preferences = { ...get().stateRoomPreferences, [sessionId]: { ...get().stateRoomPreferences[sessionId], dismissedAllowance: allowanceBytes, + backendId: get().backendIds[sessionId], measuredAt: get().stateRooms[sessionId]?.observation.observedAt } }; + persistStateRoomPreferences(preferences); set({ stateRoomPreferences: preferences }); + }, + invalidateStateRoom(sessionId, observedAt) { + const prior = get().stateRoomPreferences[sessionId]; + if (prior?.invalidatedAt === observedAt && prior.dismissedAllowance === undefined) return; + const preferences = { ...get().stateRoomPreferences, [sessionId]: { invalidatedAt: observedAt } }; + persistStateRoomPreferences(preferences); set({ stateRoomPreferences: preferences }); + }, + markStateRoomAnnounced(sessionId, allowanceBytes) { + set({ stateRoomAnnouncements: { ...get().stateRoomAnnouncements, [sessionId]: allowanceBytes } }); + }, + + setRunState: (sessionId, runState, note) => + set((state) => { + const noteChanged = (state.queueNotes[sessionId] ?? undefined) !== note; + if (state.runStates[sessionId] === runState && !noteChanged) return state; + + const runStates = { ...state.runStates }; + if (runState === "idle") delete runStates[sessionId]; + else runStates[sessionId] = runState; + + // The note belongs to the queued state; anything else ends it. A + // `queued` frame with no note also clears, so a queue that drained back + // under the warn mark stops claiming it is heavy. + const queueNotes = { ...state.queueNotes }; + if (runState === "queued" && note) queueNotes[sessionId] = note; + else delete queueNotes[sessionId]; + + return { runStates, queueNotes }; + }), + + setSessionBackend: (sessionId, backendId) => + set((state) => + state.backendIds[sessionId] === backendId + ? state + : { backendIds: { ...state.backendIds, [sessionId]: backendId } } + ), + + composerInsert: null, + requestComposerInsert: (text) => + set({ composerInsert: { seq: ++composerInsertSeq, text } }), + clearComposerInsert: (seq) => + set((state) => (state.composerInsert?.seq === seq ? { composerInsert: null } : state)), + }; +} diff --git a/packages/ui-react/src/stores/chat-slices/streaming.ts b/packages/ui-react/src/stores/chat-slices/streaming.ts new file mode 100644 index 0000000000..273a999043 --- /dev/null +++ b/packages/ui-react/src/stores/chat-slices/streaming.ts @@ -0,0 +1,166 @@ +/** + * Streaming (#1361): how a turn's stream ends — finished, failed or + * retrying — and what arrives after its text: blocks, the journal receipt + * and promoted-link rewrites. + */ +import { rewriteLinkDestinations } from "@schlessera/brain-ui-sdk/internal/client"; +import { rebaseBlocks, rewriteTexts } from "../../lib/promoted-links.js"; +import type { ChatMessage, ChatState } from "../chat-state.js"; +import type { ChatSliceContext } from "./buffers.js"; +import { withoutRetry } from "./buffers.js"; +import { textsOf } from "./transcript.js"; + +export type StreamingSliceSlice = Pick; + +export function createStreamingSlice(ctx: ChatSliceContext): StreamingSliceSlice { + const { nextId, mutateBuffer, mutateLastAssistant } = ctx; + return { + finishAssistantMessage: (key) => + mutateLastAssistant( + key, + (last) => ({ ...withoutRetry(last), isStreaming: false }), + () => ({ isStreaming: false }) + ), + + failAssistantMessage: (key, failure, turnId, replace = false) => + mutateBuffer( + key, + (chat) => { + const msgs = [...chat.messages]; + let index = -1; + if (turnId) { + index = msgs.findLastIndex((m) => m.role === "assistant" && m.turnId === turnId); + } + if (index === -1) { + // The composer opens the turn's message before the turn has an + // id, and a failure with no deltas never stamps one — so the + // last assistant message, unless another turn owns it. + const last = msgs.findLastIndex((m) => m.role === "assistant"); + const owner = last === -1 ? undefined : msgs[last].turnId; + if (last !== -1 && (owner === undefined || owner === turnId)) index = last; + } + if (index === -1) { + msgs.push({ + id: nextId(), + role: "assistant", + content: "", + toolCalls: [], + parts: [], + isStreaming: false, + timestamp: Date.now(), + ...(turnId ? { turnId } : {}), + }); + index = msgs.length - 1; + } + const target = msgs[index]; + msgs[index] = { + ...withoutRetry(target), + isStreaming: false, + failure: target.failure && !replace ? target.failure : failure, + failureLive: true, + ...(turnId ? { turnId } : {}), + }; + // The buffer streams while its newest message does: a follow-up + // already running after this message keeps it streaming. + const streaming = msgs.some((m) => m.role === "assistant" && m.isStreaming); + return { messages: msgs, isStreaming: streaming }; + }, + true + ), + + setRetry: (key, retry) => + mutateLastAssistant(key, (last) => { + if (!last.isStreaming) return last; + return retry ? { ...last, retry } : withoutRetry(last); + }), + + setMessageBlocks: (key, blocks, turnId) => + mutateBuffer(key, (chat) => { + const msgs = [...chat.messages]; + let index = -1; + if (turnId) { + for (let i = msgs.length - 1; i >= 0; i--) { + if (msgs[i].role === "assistant" && msgs[i].turnId === turnId) { + index = i; + break; + } + } + } + if (index === -1) { + // No message carries the turn (an optimistic message opened by + // the composer, or a frame without one): the last assistant + // message, but only once it has finished — never a follow-up + // still streaming. + for (let i = msgs.length - 1; i >= 0; i--) { + if (msgs[i].role === "assistant") { + if (!msgs[i].isStreaming) index = i; + break; + } + } + } + if (index === -1) return {}; + // Blocks are anchored to the streamed text: after promoted links + // rewrote it (#1698), they follow the rewrite. + const rewrite = msgs[index].linkRewrite; + msgs[index] = rewrite + ? { ...msgs[index], blocks: rebaseBlocks(blocks, rewriteTexts(rewrite.texts, rewrite.links).map((result) => result.edits)), + linkRewrite: { ...rewrite, blocks } } + : { ...msgs[index], blocks }; + return { messages: msgs }; + }), + + setTurnJournal: (key, turnId, journal) => mutateBuffer(key, chat => ({ journals: { ...chat.journals, [turnId]: journal } }), true), + + rewriteMessageLinks: (key, links, turnId) => + mutateBuffer(key, (chat) => { + if (links.length === 0) return {}; + const ofTurn = (m: ChatMessage) => m.role === "assistant" && !!turnId && (m.turnId ?? m.streamTurnId) === turnId; + let targets = chat.messages.filter(ofTurn); + if (targets.length === 0) { + // A message the composer opened before any turn was named. + const last = chat.messages.findLast((m) => m.role === "assistant"); + if (last && !(last.turnId ?? last.streamTurnId)) targets = [last]; + } + let changed = false; + const msgs = chat.messages.map((m) => { + if (!targets.includes(m)) return m; + const current = textsOf(m); + // Always from the streamed text, so every edit is in its offsets. + const base = m.linkRewrite && m.linkRewrite.texts.length === current.length + ? m.linkRewrite + : { texts: current, links: {}, ...(m.blocks ? { blocks: m.blocks } : {}) }; + const merged = { ...base.links, ...Object.fromEntries(links.map((link) => [link.from, link.to])) }; + const results = rewriteTexts(base.texts, merged); + if (results.every((result, k) => result.text === current[k])) return m; + changed = true; + let k = 0; + const parts = m.parts.map((part) => (part.kind === "text" ? { ...part, text: results[k++]!.text } : part)); + const texts = results.map((result) => result.text); + const map = new Map(Object.entries(merged)); + // Live, the aggregate is the parts joined; otherwise rewrite it as it is. + const content = m.content === current.join("") + ? texts.join("") + : rewriteLinkDestinations(m.content, (destination) => map.get(destination) ?? destination); + const blocks = base.blocks ? rebaseBlocks(base.blocks, results.map((result) => result.edits)) : undefined; + return { ...m, content, parts, ...(blocks ? { blocks } : {}), linkRewrite: { ...base, links: merged } }; + }); + return changed ? { messages: msgs } : {}; + }), + + stampTurn: (key, turnId) => + mutateLastAssistant(key, (last) => + last.isStreaming && !last.turnId ? { ...last, turnId } : last + ), + + setStreaming: (key, streaming) => mutateBuffer(key, () => ({ isStreaming: streaming })), + }; +} diff --git a/packages/ui-react/src/stores/chat-slices/transcript.ts b/packages/ui-react/src/stores/chat-slices/transcript.ts new file mode 100644 index 0000000000..6ecbaa32c9 --- /dev/null +++ b/packages/ui-react/src/stores/chat-slices/transcript.ts @@ -0,0 +1,432 @@ +/** + * Transcript replay (#1361): history replacing or extending a buffer, and + * the reconciliation that keeps what the reader already saw — exchange + * turns, streamed text, tools and attachment previews. + */ +import type { AskUserExchange, ChatMessage, ChatState, MessagePart, SessionChat, ToolCall } from "../chat-state.js"; +import type { ChatSliceContext } from "./buffers.js"; +import { appendPart, emptyChat, evictStale, revokeAttachmentUrls } from "./buffers.js"; + + +/** + * History rebuilds an exchange from its tool call, which names no turn. When + * the buffer it replaces had already learned the turn from the live request, + * keep it: the answer must be sent with that binding. + */ +export function withKnownTurns(next: ChatMessage[], previous: ChatMessage[]): ChatMessage[] { + const turns = new Map(); + for (const m of previous) for (const e of m.askUserExchanges ?? []) if (e.turnId) turns.set(e.requestId, e.turnId); + if (turns.size === 0) return next; + return next.map((m) => + m.askUserExchanges?.some((e) => !e.turnId && turns.has(e.requestId)) + ? { + ...m, + askUserExchanges: m.askUserExchanges.map((e) => + !e.turnId && turns.has(e.requestId) ? { ...e, turnId: turns.get(e.requestId)! } : e + ), + } + : m + ); +} + +/** + * A history replay of a transcript already on screen (a reconnect's resume or + * snapshot, #1013) keeps what it repeats: a message at the same place with the + * same role and text keeps its id and time, so React keeps its node and the + * reader's place. The streaming answer counts as repeated when one text + * continues the other, and it stays streaming: the host's status after the + * history says whether the turn is still running, and only that ends it. + */ +function drawnText(message: ChatMessage): string { + return message.parts.filter((part) => part.kind === "text").map((part) => part.text).join("") || message.content; +} + +/** Lost deltas leave holes; subsequent deltas retain their order. */ +function includesDrawnText(text: string, drawn: string): boolean { + let at = 0; + for (let i = 0; i < text.length && at < drawn.length; i++) if (text[i] === drawn[at]) at++; + return at === drawn.length; +} + +/** Shared tools keep their chronological IDs even when either copy missed a call. */ +function compatibleToolOrder(a: ToolCall[], b: ToolCall[]): boolean { + const aIds = new Set(a.map((t) => t.id)), bIds = new Set(b.map((t) => t.id)); + const sharedA = a.filter((t) => bIds.has(t.id)), sharedB = b.filter((t) => aIds.has(t.id)); + return sharedA.every((t, i) => t.id === sharedB[i]?.id) + && (sharedA.length > 0 || !a.length || !b.length); +} + +/** The host's display-size bound must not shorten text the page already drew. */ +function keepUnclippedText(next: string | undefined, old: string | undefined): string | undefined { + const elision = next?.match(/\n…\[\d+ chars elided\]$/); + return elision && old?.startsWith(next!.slice(0, elision.index)) ? old : next; +} + +/** Clipped blocks may split a live text part differently from stored entries. */ +function restoreClippedParts(parts: MessagePart[], old: ChatMessage): MessagePart[] { + const offsets = { text: 0, thinking: 0 }; + return parts.map((part, index) => { + if (part.kind === "tool") return part; + const prior = old.parts.filter((p) => p.kind === part.kind).map((p) => (p as { text: string }).text); + const all = prior.join("") || (part.kind === "text" ? old.content : old.thinking ?? ""); + const at = offsets[part.kind]; + const elision = part.text.match(/\n…\[(\d+) chars elided\]$/); + let text = part.text; + if (elision && all.startsWith(text.slice(0, elision.index), at)) { + // Restore through the drawn block containing this prefix, rather than + // swallowing later blocks around a tool or thinking section. + let end = 0; + for (const block of prior) { + end += block.length; + if (end >= at + elision.index! && end > at) break; + } + // Stored blocks can share one live block across missed intervening + // parts. Nonfinal prefixes stop at their stored text boundary. + if (parts.slice(index + 1).some((p) => p.kind === part.kind)) end = Math.min(end, at + elision.index! + Number(elision[1])); + text = all.slice(at, prior.length ? end : all.length); + } + offsets[part.kind] = all.startsWith(text, at) ? at + text.length : at; + return text === part.text ? part : { ...part, text }; + }); +} + +/** A message's text parts, in order. */ +export function textsOf(m: ChatMessage): string[] { + return m.parts.flatMap((part) => (part.kind === "text" ? [part.text] : [])); +} + +export function keepDrawnMessages(next: ChatMessage[], previous: Pick, partial = true): Pick { + // Only the transcript's tail can still be streaming: a message after it + // (a follow-up that started) means its turn is over. + const tail = next.length - 1; + let streaming = false; + const messages = next.map((received, i) => { + const old = previous.messages[i]; + if (!old || old.role !== received.role) return received; + const toolsElided = received.content.match(/\n…\[(\d+) tool calls elided\]$/); + const boundedTools = toolsElided && compatibleToolOrder(received.toolCalls, old.toolCalls); + const content = boundedTools ? received.content.slice(0, toolsElided.index) : received.content; + const unclippedContent = keepUnclippedText(content, old.content)!; + const m: ChatMessage = { + ...received, + content: unclippedContent, + thinking: keepUnclippedText(received.thinking, old.thinking), + parts: restoreClippedParts(received.parts.filter((part) => !boundedTools || part.kind !== "text" || part.text !== toolsElided![0]), old), + toolCalls: [...received.toolCalls, ...(boundedTools ? old.toolCalls.filter((t) => !received.toolCalls.some((n) => n.id === t.id)) : [])].map((tool) => ({ + ...tool, output: keepUnclippedText(tool.output, old.toolCalls.find((t) => t.id === tool.id)?.output), + })), + }; + if (/\n…\[\d+ chars elided\]/.test(content)) m.content = drawnText(m); + if (content !== unclippedContent && unclippedContent === old.content && drawnText(old).startsWith(drawnText(m))) m.content = old.content; + // The array bound can omit a new trailing block while the aggregate + // still carries it. Keep drawn cards, then add the newly proven suffix. + if (m.content.startsWith(old.content) && m.content.length >= old.content.length + && (boundedTools || m.content.length > old.content.length || drawnText(m).length < drawnText(old).length) + && drawnText(m).length <= drawnText(old).length + && (!old.turnId || !m.turnId || old.turnId === m.turnId) + && compatibleToolOrder(old.toolCalls, m.toolCalls)) { + const retained = mergeLive(old, m); + const suffix = m.content.slice(old.content.length); + m.parts = suffix ? appendPart(retained.parts, "text", suffix) : retained.parts; + m.toolCalls = retained.toolCalls; + } + const live = previous.isStreaming && old.isStreaming === true && m.role === "assistant"; + // Claude history adds separators to its aggregate across assistant + // entries; the chronological text parts are the actual drawn text. + const mine = drawnText(old), theirs = drawnText(m); + const provenTurn = m.turnId && m.turnId === (old.turnId ?? old.streamTurnId); + const clipped = received.parts.some((p) => p.kind === "text" && /\n…\[\d+ chars elided\]$/.test(p.text)); + const opening = received.parts.find((p) => p.kind === "text"); + // A bound cannot disprove this drawn continuation: retain even a short + // shared opening until the scoped status settles its turn. Tool/request + // identities and a different proven turn still reject a replacement. + const boundedContinuation = !!boundedTools || (clipped && opening?.kind === "text" && mine.length > 0 + && opening.text.length > 0 && opening.text[0] === mine[0]); + const continuing = live || !!(old.turnId ?? old.streamTurnId); + const same = mine === theirs || boundedContinuation || (continuing && (provenTurn || theirs.startsWith(mine) || mine.startsWith(theirs) + || (mine.length > 0 && theirs.length > 0 && (includesDrawnText(theirs, mine) || includesDrawnText(mine, theirs))))); + // Text alone does not make it the same message: a tool-only answer has + // none, and its cards keep state. A known turn or request must agree. + const shared = Math.min(old.toolCalls.length, m.toolCalls.length); + const compatibleTools = compatibleToolOrder(old.toolCalls, m.toolCalls); + const sameTools = continuing || boundedContinuation ? compatibleTools || (live && provenTurn) + : old.toolCalls.length === m.toolCalls.length && old.toolCalls.slice(0, shared).every((t, k) => t.id === m.toolCalls[k]!.id); + const knownTurn = old.turnId ?? old.streamTurnId; + const sameTurn = !knownTurn || !m.turnId || knownTurn === m.turnId; + if (!same || !sameTools || !sameTurn) return m; + if (live && i === tail) { + streaming = true; + return mergeLive(old, m); + } + if ((continuing && m.role === "assistant" && old.toolCalls.some((t) => !m.toolCalls.some((n) => n.id === t.id))) + || (boundedContinuation && (boundedTools || m.parts.some((p) => p.kind === "text" && /\n…\[\d+ chars elided\]$/.test(p.text))))) { + return { ...mergeLive(old, m), isStreaming: false }; + } + return { ...m, id: old.id, timestamp: old.timestamp, ...(old.attachments ? { attachments: old.attachments } : {}) }; + }); + // Another client can start a turn whose user message this page learns only + // from history. Its live answer moves across that one inserted user, but + // only when the whole earlier prefix repeats. Apply the same answer guards + // at its new position; this never searches older answers for matching text. + const live = previous.messages.at(-1); + const liveAt = previous.messages.length - 1; + // A connect greeting opens an empty placeholder even for a finished turn. + // Only delivered progress or a known turn identifies an answer to move. + if (previous.isStreaming && live?.role === "assistant" && live.isStreaming + && (live.turnId || live.streamTurnId || live.content || live.thinking || live.toolCalls.length || live.askUserExchanges?.length) + && next[liveAt]?.role === "user" + && messages.slice(0, liveAt).every((m, i) => m.id === previous.messages[i]!.id)) { + if (next.length === previous.messages.length + 1 && next.at(-1)?.role === "assistant") { + const answer = keepDrawnMessages([next.at(-1)!], { messages: [live], isStreaming: true }, false); + return { messages: [...messages.slice(0, -1), ...answer.messages], isStreaming: answer.isStreaming }; + } + // A chunk can stop at the inserted user. Keep the answer mounted until + // its chunk arrives, including any deltas received between the chunks. + if (partial && next.length === previous.messages.length) { + return { messages: [...messages, { ...live, turnId: undefined, streamTurnId: live.turnId ?? live.streamTurnId }], isStreaming: true }; + } + } + // The first frame can be only a prefix. Keep its matching drawn suffix + // until the host's post-history status settles the replay: otherwise a + // painted frame between WS tasks unmounts it and loses the scroll anchor. + if (partial && next.length < previous.messages.length) { + const suffix = previous.messages.slice(next.length).map((m) => m.isStreaming + ? { ...m, turnId: undefined, streamTurnId: m.turnId ?? m.streamTurnId } : m); + return { messages: [...messages, ...suffix], isStreaming: previous.isStreaming }; + } + // A backend may keep an answer only once it ends, so a replay mid-turn can + // stop just before the answer on screen. Everything else repeated: the + // answer is still being written, and stays (the turn's end replays again). + if (previous.isStreaming && live?.role === "assistant" && live.isStreaming + && next.length === previous.messages.length - 1 && messages.every((m, i) => m.id === previous.messages[i]!.id)) { + return { messages: [...messages, { ...live, turnId: undefined, streamTurnId: live.turnId ?? live.streamTurnId }], isStreaming: true }; + } + return { messages, isStreaming: streaming }; +} + +/** + * The live answer, from the page's copy and the host's: each may hold + * progress the other lacks (text the page missed while away, a tool or + * thinking that arrived while the history was read). A lagging copy cannot + * erase text already drawn, even if it is longer; the other's tools join + * the retained copy, and its outputs fill that copy's. + * The turn is the history's alone: only a host-proven turn may let the + * reader's view clear a tracker (D52 §4). The frames' turn stays for + * correlation. + */ +function mergeLive(old: ChatMessage, m: ChatMessage): ChatMessage { + const thinkingSize = (message: ChatMessage) => message.parts.reduce((n, p) => n + (p.kind === "thinking" ? p.text.length : 0), 0); + const moreThinking = thinkingSize(m) > thinkingSize(old); + const unresolvedClip = m.parts.some((p) => p.kind === "text" && /\n…\[\d+ chars elided\]$/.test(p.text)); + const base = unresolvedClip || !includesDrawnText(drawnText(m), drawnText(old)) + || (drawnText(old).length === drawnText(m).length && !moreThinking && m.toolCalls.length <= old.toolCalls.length) ? old : m; + const other = base === old ? m : old; + const theirs = new Map(other.toolCalls.map((t) => [t.id, t])); + // A tool the other copy saw finish is that copy's, state and all: an + // approval the host settled meanwhile is not offered again. + const toolCalls = base.toolCalls.map((t) => { + const o = theirs.get(t.id); + if (!o && t.status === "pending_approval") return { ...t, restored: true as const, approvalTurnId: undefined }; + return o && ((o.output !== undefined && t.output === undefined) || ((t.status === "streaming" || t.status === "pending_approval") && o.status !== t.status)) ? o : t; + }); + let parts = [...base.parts]; + for (const t of other.toolCalls) { + if (toolCalls.some((b) => b.id === t.id)) continue; + { + const sourceAt = other.parts.findIndex((p) => p.kind === "tool" && other.toolCalls[p.toolIndex]?.id === t.id); + const following = sourceAt < 0 ? [] : other.parts.slice(sourceAt + 1); + const preceding = sourceAt < 0 ? [] : other.parts.slice(0, sourceAt).filter((p) => p.kind === "tool").map((p) => other.toolCalls[p.toolIndex]!.id); + const start = parts.findLastIndex((p) => p.kind === "tool" && preceding.includes(toolCalls[p.toolIndex]!.id)) + 1; + let at = -1; + // A text block can be the nearest shared boundary. A missed tool may + // also have coalesced two drawn text blocks: split at that boundary. + for (const next of following) { + for (let index = start; index < parts.length; index++) { + const part = parts[index]!; + if (next.kind === "tool") { + if (part.kind === "tool" && toolCalls[part.toolIndex]!.id === other.toolCalls[next.toolIndex]!.id) at = index; + } else if (part.kind === next.kind && next.text.trim().length > 0 && part.text.trim().length > 0) { + const needle = next.text.replace(/\n…\[\d+ chars elided\]$/, ""); + if (!needle.trim()) continue; + const offset = part.text.indexOf(needle); + if (offset >= 0 || needle.startsWith(part.text)) { + at = index; + if (offset > 0) { + parts.splice(index, 1, { ...part, text: part.text.slice(0, offset) }, { ...part, text: part.text.slice(offset) }); + at++; + } + } + } + if (at >= 0) break; + } + if (at >= 0) break; + } + if (at < 0 && sourceAt >= 0 && other === m && start > 0) at = start; + parts.splice(at < 0 ? parts.length : at, 0, { kind: "tool", toolIndex: toolCalls.length }); + } + toolCalls.push(other === old && t.status === "pending_approval" + ? { ...t, restored: true as const, approvalTurnId: undefined } : t); + } + // The union's flat order must agree with its drawn chronology: the next + // replay compares this list too, including a tool inserted in an old gap. + const beforeOrder = [...toolCalls]; + const rank = new Map(parts.filter((p) => p.kind === "tool").map((p, i) => [beforeOrder[p.toolIndex]!.id, i])); + toolCalls.sort((a, b) => (rank.get(a.id) ?? Number.MAX_SAFE_INTEGER) - (rank.get(b.id) ?? Number.MAX_SAFE_INTEGER)); + parts = parts.map((p) => p.kind === "tool" ? { ...p, toolIndex: toolCalls.findIndex((t) => t.id === beforeOrder[p.toolIndex]!.id) } : p); + // Thinking stays between the text/tool parts that bracketed it. Host + // aggregates add separators, so compare the drawn blocks, not that field. + const body = parts.filter((p) => p.kind !== "thinking"); + const thinkingSlots = (source: MessagePart[], sourceTools: ToolCall[], remap = false) => { + const slots = new Map[]>(); + let at = 0; + for (const [index, part] of source.entries()) { + if (part.kind !== "thinking") { at++; continue; } + let slot = at; + if (remap) { + // A recovered tool changes numeric slots. Anchor thinking to a tool + // this copy actually saw, rather than duplicating it at an old index. + const before = source.slice(0, index).filter((p) => p.kind !== "thinking"); + const prior = before.findLastIndex((p) => p.kind === "tool"); + const after = source.slice(index + 1).filter((p) => p.kind !== "thinking"); + const following = after.findIndex((p) => p.kind === "tool"); + const anchor = prior >= 0 ? before[prior] : following >= 0 ? after[following] : undefined; + if (anchor?.kind === "tool") { + const target = body.findIndex((p) => p.kind === "tool" && toolCalls[p.toolIndex]?.id === sourceTools[anchor.toolIndex]?.id); + if (target >= 0) slot = prior >= 0 ? target + before.length - prior : target - following; + } + } + slots.set(slot, [...(slots.get(slot) ?? []), part]); + } + return slots; + }; + const slots = thinkingSlots(parts, toolCalls); + for (const [at, blocks] of thinkingSlots(other.parts, other.toolCalls, true)) { + const mine = slots.get(at) ?? []; + if (blocks.reduce((n, p) => n + p.text.length, 0) > mine.reduce((n, p) => n + p.text.length, 0)) slots.set(at, blocks); + } + parts = body.flatMap((part, at) => [...(slots.get(at) ?? []), part]); + parts.push(...(slots.get(body.length) ?? [])); + const thinking = parts.filter((p) => p.kind === "thinking").map((p) => p.text).join("") || undefined; + // Questions by request: one either copy saw settled is settled, and one + // only the page has drawn stays (its card is the reader's). + const settled = (e: AskUserExchange) => e.answers !== undefined || e.cancelled === true || e.order !== undefined || e.formAnswers !== undefined; + const asks = new Map((base.askUserExchanges ?? []).map((e) => [e.requestId, e])); + for (const e of other.askUserExchanges ?? []) { + const mine = asks.get(e.requestId); + if (!mine || (settled(e) && !settled(mine))) asks.set(e.requestId, e); + } + const askUserExchanges = asks.size ? [...asks.values()] : undefined; + return { + ...base, toolCalls, parts, thinking, askUserExchanges, + // Terminal history is authoritative even when the drawn text is longer. + failure: m.failure ?? base.failure, + retryOfTurnId: m.failure ? m.retryOfTurnId : base.retryOfTurnId, + failureLive: m.failure ? undefined : base.failureLive, + files: m.files ?? base.files, + blocks: m.blocks ?? base.blocks, + id: old.id, timestamp: old.timestamp, isStreaming: true, + turnId: m.turnId, streamTurnId: old.turnId ?? old.streamTurnId, + }; +} + +export type TranscriptSliceSlice = Pick; + +export function createTranscriptSlice(ctx: ChatSliceContext): TranscriptSliceSlice { + const { set, mutateBuffer } = ctx; + return { + historyLoads: {}, + noteHistoryLoaded: (sessionId) => + set((state) => ({ historyLoads: { ...state.historyLoads, [sessionId]: (state.historyLoads[sessionId] ?? 0) + 1 } })), + + setMessages: (key, messages) => + set((state) => { + if (key === null) { + if (state.draft) revokeAttachmentUrls(state.draft.messages); + return { + draft: { ...emptyChat(), messages }, + }; + } + const existing = state.buffers[key]; + const base = existing ? { messages: existing.messages, isStreaming: existing.isStreaming } : null; + const drawn = base ? keepDrawnMessages(withKnownTurns(messages, base.messages), base) : { messages, isStreaming: false }; + if (existing) revokeAttachmentUrls(existing.messages, drawn.messages); + // The first chunk of the host's history: whatever it holds, even + // nothing, the transcript is the host's now (#1328). + const buffers = { + ...state.buffers, + [key]: base + ? { ...emptyChat(), ...drawn, replay: { base, received: messages }, historyConfirmed: true as const } + : { ...emptyChat(), messages, historyConfirmed: true as const }, + }; + const restoreFailures = { ...state.restoreFailures }; + delete restoreFailures[key]; + return { buffers: evictStale(buffers, state.activeSessionId), restoreFailures }; + }), + + appendMessages: (key, messages) => + set((state) => { + if (key === null) { + const draft = state.draft ?? emptyChat(); + return { draft: { ...draft, messages: [...draft.messages, ...messages] } }; + } + const existing = state.buffers[key] ?? emptyChat(); + if (existing.replay) { + // A later chunk of the same replay: reconcile the whole replay so + // far against the transcript it replaced, so a message the first + // chunk kept back as still being written is not drawn twice. The + // answer as it stands now (deltas since) is the live one. + const { base, received } = existing.replay; + const now = existing.messages.at(-1); + const live = base.messages.at(-1); + const current = now && live && now.id === live.id ? { ...base, messages: [...base.messages.slice(0, -1), now] } : base; + const all = [...received, ...messages]; + const drawn = keepDrawnMessages(withKnownTurns(all, current.messages), current); + revokeAttachmentUrls(existing.messages, drawn.messages); + return { + buffers: { + ...state.buffers, + [key]: { ...existing, ...drawn, replay: { base: current, received: all }, lastTouched: Date.now() }, + }, + }; + } + return { + buffers: { + ...state.buffers, + [key]: { + ...existing, + messages: [...existing.messages, ...messages], + lastTouched: Date.now(), + }, + }, + }; + }), + + finishHistoryReplay: (key, keepRunning) => mutateBuffer(key, (existing) => { + if (!existing.replay) return {}; + // Running status cannot make a lagging replay authoritative over + // the live answer and its already drawn prefix. + if (keepRunning && existing.isStreaming) return { replay: undefined }; + const { base, received } = existing.replay; + const now = existing.messages.at(-1); + const live = base.messages.at(-1); + // A full replay is already reconciled. Progress that opened another + // message afterward is live, not an unreceived history suffix. A + // lagging backend can also omit just the answer that was live before + // the replay; retain that answer even if this status ends its turn. + if (received.length >= base.messages.length || now?.id !== live?.id + || (base.isStreaming && live?.isStreaming && received.length === base.messages.length - 1 + && existing.messages.slice(0, received.length).every((m, i) => m.id === base.messages[i]!.id))) { + return { replay: undefined }; + } + const drawn = keepDrawnMessages(withKnownTurns(received, existing.messages), existing, false); + revokeAttachmentUrls(existing.messages, drawn.messages); + return { ...drawn, replay: undefined }; + }), + }; +} diff --git a/packages/ui-react/src/stores/chat-state.ts b/packages/ui-react/src/stores/chat-state.ts index 1c655958e7..5ba46ce632 100644 --- a/packages/ui-react/src/stores/chat-state.ts +++ b/packages/ui-react/src/stores/chat-state.ts @@ -1,8 +1,6 @@ import type { VoicePermissionReceipt } from "../voice/conversation-permissions.js"; -import { POLICY_CHANGE_REVIEW_SCHEMA, type PolicyChangeReview } from "@schlessera/brain-ui-sdk/tool-contracts"; +import type { PolicyChangeReview } from "@schlessera/brain-ui-sdk/tool-contracts"; import { createStore } from "zustand/vanilla"; -import { rewriteLinkDestinations } from "@schlessera/brain-ui-sdk/internal/client"; -import { rebaseBlocks, rewriteTexts } from "../lib/promoted-links.js"; import type { SharedFileMeta, LocalExchange, @@ -27,10 +25,20 @@ import type { StatsSection } from "../lib/stats/compose-stats.js"; import type { ProviderState } from "./provider-state.js"; import type { StoreEnvironment } from "./store-environment.js"; import type { ChatShellState } from "./shell-stores.js"; +import { createApprovalsSlice } from "./chat-slices/approvals.js"; +import { createAskUserSlice } from "./chat-slices/ask-user.js"; +import { createChatSliceContext } from "./chat-slices/buffers.js"; +import { createMessagesSlice } from "./chat-slices/messages.js"; +import { createChatPersistence } from "./chat-slices/persistence.js"; +import { createSessionSlice } from "./chat-slices/session.js"; +import { createStatusSlice } from "./chat-slices/status.js"; +import { createStreamingSlice } from "./chat-slices/streaming.js"; +import { createTranscriptSlice } from "./chat-slices/transcript.js"; import type { AnswerDelivery } from "../lib/answer-delivery/types.js"; import type { RestoredApprovalClosure } from "../lib/restored-approvals.js"; export type { MessagePart }; +export { isSettledExchange } from "./chat-slices/ask-user.js"; export interface ChatMessage { id: string; @@ -243,63 +251,6 @@ export interface AskUserExchange { answeredAt?: number; } -/** The exchange has an outcome: answered (in any of the four shapes) or dismissed. */ -export function isSettledExchange(exchange: AskUserExchange): boolean { - return !!(exchange.answers || exchange.order || exchange.formAnswers || exchange.cancelled); -} - -/** - * Open an ask exchange: attached to the streaming assistant message, where the - * transcript draws it, and held as the session's pending exchange. `ask_user` - * and `ask_user_list` share the slot, so the composer, the suggestions row and - * the tool-result cleanup treat either the same way. - * - * One request is one card (#910). The host re-delivers a pending request on - * every reconnect and after `session_resume`, and history may already have - * rebuilt it under the same id, so a request already in the buffer is - * UPDATED, never appended again: - * - * - a settled card stays settled: a late or replayed request frame cannot - * revive an answered or dismissed question; - * - a pending card keeps its payload and whatever the user is drafting in it, - * and learns its turn if it did not know it; - * - a request claiming a different turn than the card already holds is a - * contradiction, not an update, and is ignored. The host's receipt is what - * decides which binding is real. - */ -function addExchange( - chat: SessionChat, - exchange: AskUserExchange -): Partial> { - for (let i = chat.messages.length - 1; i >= 0; i--) { - const message = chat.messages[i]!; - const index = message.askUserExchanges?.findIndex((e) => e.requestId === exchange.requestId) ?? -1; - if (index === -1) continue; - const existing = message.askUserExchanges![index]!; - if (isSettledExchange(existing)) return {}; - if (existing.turnId && exchange.turnId && existing.turnId !== exchange.turnId) return {}; - const merged: AskUserExchange = - existing.turnId || !exchange.turnId ? existing : { ...existing, turnId: exchange.turnId }; - const msgs = [...chat.messages]; - const exchanges = [...message.askUserExchanges!]; - exchanges[index] = merged; - msgs[i] = { ...message, askUserExchanges: exchanges }; - const slot = chat.askUser; - const askUser = !slot || slot.requestId === merged.requestId || isSettledExchange(slot) ? merged : slot; - return { messages: msgs, askUser }; - } - const msgs = [...chat.messages]; - const lastIdx = msgs.length - 1; - const last = msgs[lastIdx]; - if (last?.role === "assistant") { - msgs[lastIdx] = { - ...last, - askUserExchanges: [...(last.askUserExchanges ?? []), exchange], - }; - } - return { messages: msgs, askUser: exchange }; -} - /** * One session's live transcript state. Every session the user has viewed (or * that bound from the draft) keeps its own buffer, so frames from a background @@ -360,9 +311,6 @@ export type Restoration = */ export type ChatKey = string | null; -/** Retained transcript buffers beyond the active one (LRU-evicted). */ -const MAX_BUFFERS = 8; - export interface PendingTurnRetry { requestId: string; failedTurnId: string; @@ -637,332 +585,6 @@ export interface ChatState { /** Clear the request the composer has applied; a newer one is kept. */ clearComposerInsert: (seq: number) => void; } - -/** - * History rebuilds an exchange from its tool call, which names no turn. When - * the buffer it replaces had already learned the turn from the live request, - * keep it: the answer must be sent with that binding. - */ -function withKnownTurns(next: ChatMessage[], previous: ChatMessage[]): ChatMessage[] { - const turns = new Map(); - for (const m of previous) for (const e of m.askUserExchanges ?? []) if (e.turnId) turns.set(e.requestId, e.turnId); - if (turns.size === 0) return next; - return next.map((m) => - m.askUserExchanges?.some((e) => !e.turnId && turns.has(e.requestId)) - ? { - ...m, - askUserExchanges: m.askUserExchanges.map((e) => - !e.turnId && turns.has(e.requestId) ? { ...e, turnId: turns.get(e.requestId)! } : e - ), - } - : m - ); -} - -/** - * A history replay of a transcript already on screen (a reconnect's resume or - * snapshot, #1013) keeps what it repeats: a message at the same place with the - * same role and text keeps its id and time, so React keeps its node and the - * reader's place. The streaming answer counts as repeated when one text - * continues the other, and it stays streaming: the host's status after the - * history says whether the turn is still running, and only that ends it. - */ -function drawnText(message: ChatMessage): string { - return message.parts.filter((part) => part.kind === "text").map((part) => part.text).join("") || message.content; -} - -/** Lost deltas leave holes; subsequent deltas retain their order. */ -function includesDrawnText(text: string, drawn: string): boolean { - let at = 0; - for (let i = 0; i < text.length && at < drawn.length; i++) if (text[i] === drawn[at]) at++; - return at === drawn.length; -} - -/** Shared tools keep their chronological IDs even when either copy missed a call. */ -function compatibleToolOrder(a: ToolCall[], b: ToolCall[]): boolean { - const aIds = new Set(a.map((t) => t.id)), bIds = new Set(b.map((t) => t.id)); - const sharedA = a.filter((t) => bIds.has(t.id)), sharedB = b.filter((t) => aIds.has(t.id)); - return sharedA.every((t, i) => t.id === sharedB[i]?.id) - && (sharedA.length > 0 || !a.length || !b.length); -} - -/** The host's display-size bound must not shorten text the page already drew. */ -function keepUnclippedText(next: string | undefined, old: string | undefined): string | undefined { - const elision = next?.match(/\n…\[\d+ chars elided\]$/); - return elision && old?.startsWith(next!.slice(0, elision.index)) ? old : next; -} - -/** Clipped blocks may split a live text part differently from stored entries. */ -function restoreClippedParts(parts: MessagePart[], old: ChatMessage): MessagePart[] { - const offsets = { text: 0, thinking: 0 }; - return parts.map((part, index) => { - if (part.kind === "tool") return part; - const prior = old.parts.filter((p) => p.kind === part.kind).map((p) => (p as { text: string }).text); - const all = prior.join("") || (part.kind === "text" ? old.content : old.thinking ?? ""); - const at = offsets[part.kind]; - const elision = part.text.match(/\n…\[(\d+) chars elided\]$/); - let text = part.text; - if (elision && all.startsWith(text.slice(0, elision.index), at)) { - // Restore through the drawn block containing this prefix, rather than - // swallowing later blocks around a tool or thinking section. - let end = 0; - for (const block of prior) { - end += block.length; - if (end >= at + elision.index! && end > at) break; - } - // Stored blocks can share one live block across missed intervening - // parts. Nonfinal prefixes stop at their stored text boundary. - if (parts.slice(index + 1).some((p) => p.kind === part.kind)) end = Math.min(end, at + elision.index! + Number(elision[1])); - text = all.slice(at, prior.length ? end : all.length); - } - offsets[part.kind] = all.startsWith(text, at) ? at + text.length : at; - return text === part.text ? part : { ...part, text }; - }); -} - -/** A message's text parts, in order. */ -function textsOf(m: ChatMessage): string[] { - return m.parts.flatMap((part) => (part.kind === "text" ? [part.text] : [])); -} - -function keepDrawnMessages(next: ChatMessage[], previous: Pick, partial = true): Pick { - // Only the transcript's tail can still be streaming: a message after it - // (a follow-up that started) means its turn is over. - const tail = next.length - 1; - let streaming = false; - const messages = next.map((received, i) => { - const old = previous.messages[i]; - if (!old || old.role !== received.role) return received; - const toolsElided = received.content.match(/\n…\[(\d+) tool calls elided\]$/); - const boundedTools = toolsElided && compatibleToolOrder(received.toolCalls, old.toolCalls); - const content = boundedTools ? received.content.slice(0, toolsElided.index) : received.content; - const unclippedContent = keepUnclippedText(content, old.content)!; - const m: ChatMessage = { - ...received, - content: unclippedContent, - thinking: keepUnclippedText(received.thinking, old.thinking), - parts: restoreClippedParts(received.parts.filter((part) => !boundedTools || part.kind !== "text" || part.text !== toolsElided![0]), old), - toolCalls: [...received.toolCalls, ...(boundedTools ? old.toolCalls.filter((t) => !received.toolCalls.some((n) => n.id === t.id)) : [])].map((tool) => ({ - ...tool, output: keepUnclippedText(tool.output, old.toolCalls.find((t) => t.id === tool.id)?.output), - })), - }; - if (/\n…\[\d+ chars elided\]/.test(content)) m.content = drawnText(m); - if (content !== unclippedContent && unclippedContent === old.content && drawnText(old).startsWith(drawnText(m))) m.content = old.content; - // The array bound can omit a new trailing block while the aggregate - // still carries it. Keep drawn cards, then add the newly proven suffix. - if (m.content.startsWith(old.content) && m.content.length >= old.content.length - && (boundedTools || m.content.length > old.content.length || drawnText(m).length < drawnText(old).length) - && drawnText(m).length <= drawnText(old).length - && (!old.turnId || !m.turnId || old.turnId === m.turnId) - && compatibleToolOrder(old.toolCalls, m.toolCalls)) { - const retained = mergeLive(old, m); - const suffix = m.content.slice(old.content.length); - m.parts = suffix ? appendPart(retained.parts, "text", suffix) : retained.parts; - m.toolCalls = retained.toolCalls; - } - const live = previous.isStreaming && old.isStreaming === true && m.role === "assistant"; - // Claude history adds separators to its aggregate across assistant - // entries; the chronological text parts are the actual drawn text. - const mine = drawnText(old), theirs = drawnText(m); - const provenTurn = m.turnId && m.turnId === (old.turnId ?? old.streamTurnId); - const clipped = received.parts.some((p) => p.kind === "text" && /\n…\[\d+ chars elided\]$/.test(p.text)); - const opening = received.parts.find((p) => p.kind === "text"); - // A bound cannot disprove this drawn continuation: retain even a short - // shared opening until the scoped status settles its turn. Tool/request - // identities and a different proven turn still reject a replacement. - const boundedContinuation = !!boundedTools || (clipped && opening?.kind === "text" && mine.length > 0 - && opening.text.length > 0 && opening.text[0] === mine[0]); - const continuing = live || !!(old.turnId ?? old.streamTurnId); - const same = mine === theirs || boundedContinuation || (continuing && (provenTurn || theirs.startsWith(mine) || mine.startsWith(theirs) - || (mine.length > 0 && theirs.length > 0 && (includesDrawnText(theirs, mine) || includesDrawnText(mine, theirs))))); - // Text alone does not make it the same message: a tool-only answer has - // none, and its cards keep state. A known turn or request must agree. - const shared = Math.min(old.toolCalls.length, m.toolCalls.length); - const compatibleTools = compatibleToolOrder(old.toolCalls, m.toolCalls); - const sameTools = continuing || boundedContinuation ? compatibleTools || (live && provenTurn) - : old.toolCalls.length === m.toolCalls.length && old.toolCalls.slice(0, shared).every((t, k) => t.id === m.toolCalls[k]!.id); - const knownTurn = old.turnId ?? old.streamTurnId; - const sameTurn = !knownTurn || !m.turnId || knownTurn === m.turnId; - if (!same || !sameTools || !sameTurn) return m; - if (live && i === tail) { - streaming = true; - return mergeLive(old, m); - } - if ((continuing && m.role === "assistant" && old.toolCalls.some((t) => !m.toolCalls.some((n) => n.id === t.id))) - || (boundedContinuation && (boundedTools || m.parts.some((p) => p.kind === "text" && /\n…\[\d+ chars elided\]$/.test(p.text))))) { - return { ...mergeLive(old, m), isStreaming: false }; - } - return { ...m, id: old.id, timestamp: old.timestamp, ...(old.attachments ? { attachments: old.attachments } : {}) }; - }); - // Another client can start a turn whose user message this page learns only - // from history. Its live answer moves across that one inserted user, but - // only when the whole earlier prefix repeats. Apply the same answer guards - // at its new position; this never searches older answers for matching text. - const live = previous.messages.at(-1); - const liveAt = previous.messages.length - 1; - // A connect greeting opens an empty placeholder even for a finished turn. - // Only delivered progress or a known turn identifies an answer to move. - if (previous.isStreaming && live?.role === "assistant" && live.isStreaming - && (live.turnId || live.streamTurnId || live.content || live.thinking || live.toolCalls.length || live.askUserExchanges?.length) - && next[liveAt]?.role === "user" - && messages.slice(0, liveAt).every((m, i) => m.id === previous.messages[i]!.id)) { - if (next.length === previous.messages.length + 1 && next.at(-1)?.role === "assistant") { - const answer = keepDrawnMessages([next.at(-1)!], { messages: [live], isStreaming: true }, false); - return { messages: [...messages.slice(0, -1), ...answer.messages], isStreaming: answer.isStreaming }; - } - // A chunk can stop at the inserted user. Keep the answer mounted until - // its chunk arrives, including any deltas received between the chunks. - if (partial && next.length === previous.messages.length) { - return { messages: [...messages, { ...live, turnId: undefined, streamTurnId: live.turnId ?? live.streamTurnId }], isStreaming: true }; - } - } - // The first frame can be only a prefix. Keep its matching drawn suffix - // until the host's post-history status settles the replay: otherwise a - // painted frame between WS tasks unmounts it and loses the scroll anchor. - if (partial && next.length < previous.messages.length) { - const suffix = previous.messages.slice(next.length).map((m) => m.isStreaming - ? { ...m, turnId: undefined, streamTurnId: m.turnId ?? m.streamTurnId } : m); - return { messages: [...messages, ...suffix], isStreaming: previous.isStreaming }; - } - // A backend may keep an answer only once it ends, so a replay mid-turn can - // stop just before the answer on screen. Everything else repeated: the - // answer is still being written, and stays (the turn's end replays again). - if (previous.isStreaming && live?.role === "assistant" && live.isStreaming - && next.length === previous.messages.length - 1 && messages.every((m, i) => m.id === previous.messages[i]!.id)) { - return { messages: [...messages, { ...live, turnId: undefined, streamTurnId: live.turnId ?? live.streamTurnId }], isStreaming: true }; - } - return { messages, isStreaming: streaming }; -} - -/** - * The live answer, from the page's copy and the host's: each may hold - * progress the other lacks (text the page missed while away, a tool or - * thinking that arrived while the history was read). A lagging copy cannot - * erase text already drawn, even if it is longer; the other's tools join - * the retained copy, and its outputs fill that copy's. - * The turn is the history's alone: only a host-proven turn may let the - * reader's view clear a tracker (D52 §4). The frames' turn stays for - * correlation. - */ -function mergeLive(old: ChatMessage, m: ChatMessage): ChatMessage { - const thinkingSize = (message: ChatMessage) => message.parts.reduce((n, p) => n + (p.kind === "thinking" ? p.text.length : 0), 0); - const moreThinking = thinkingSize(m) > thinkingSize(old); - const unresolvedClip = m.parts.some((p) => p.kind === "text" && /\n…\[\d+ chars elided\]$/.test(p.text)); - const base = unresolvedClip || !includesDrawnText(drawnText(m), drawnText(old)) - || (drawnText(old).length === drawnText(m).length && !moreThinking && m.toolCalls.length <= old.toolCalls.length) ? old : m; - const other = base === old ? m : old; - const theirs = new Map(other.toolCalls.map((t) => [t.id, t])); - // A tool the other copy saw finish is that copy's, state and all: an - // approval the host settled meanwhile is not offered again. - const toolCalls = base.toolCalls.map((t) => { - const o = theirs.get(t.id); - if (!o && t.status === "pending_approval") return { ...t, restored: true as const, approvalTurnId: undefined }; - return o && ((o.output !== undefined && t.output === undefined) || ((t.status === "streaming" || t.status === "pending_approval") && o.status !== t.status)) ? o : t; - }); - let parts = [...base.parts]; - for (const t of other.toolCalls) { - if (toolCalls.some((b) => b.id === t.id)) continue; - { - const sourceAt = other.parts.findIndex((p) => p.kind === "tool" && other.toolCalls[p.toolIndex]?.id === t.id); - const following = sourceAt < 0 ? [] : other.parts.slice(sourceAt + 1); - const preceding = sourceAt < 0 ? [] : other.parts.slice(0, sourceAt).filter((p) => p.kind === "tool").map((p) => other.toolCalls[p.toolIndex]!.id); - const start = parts.findLastIndex((p) => p.kind === "tool" && preceding.includes(toolCalls[p.toolIndex]!.id)) + 1; - let at = -1; - // A text block can be the nearest shared boundary. A missed tool may - // also have coalesced two drawn text blocks: split at that boundary. - for (const next of following) { - for (let index = start; index < parts.length; index++) { - const part = parts[index]!; - if (next.kind === "tool") { - if (part.kind === "tool" && toolCalls[part.toolIndex]!.id === other.toolCalls[next.toolIndex]!.id) at = index; - } else if (part.kind === next.kind && next.text.trim().length > 0 && part.text.trim().length > 0) { - const needle = next.text.replace(/\n…\[\d+ chars elided\]$/, ""); - if (!needle.trim()) continue; - const offset = part.text.indexOf(needle); - if (offset >= 0 || needle.startsWith(part.text)) { - at = index; - if (offset > 0) { - parts.splice(index, 1, { ...part, text: part.text.slice(0, offset) }, { ...part, text: part.text.slice(offset) }); - at++; - } - } - } - if (at >= 0) break; - } - if (at >= 0) break; - } - if (at < 0 && sourceAt >= 0 && other === m && start > 0) at = start; - parts.splice(at < 0 ? parts.length : at, 0, { kind: "tool", toolIndex: toolCalls.length }); - } - toolCalls.push(other === old && t.status === "pending_approval" - ? { ...t, restored: true as const, approvalTurnId: undefined } : t); - } - // The union's flat order must agree with its drawn chronology: the next - // replay compares this list too, including a tool inserted in an old gap. - const beforeOrder = [...toolCalls]; - const rank = new Map(parts.filter((p) => p.kind === "tool").map((p, i) => [beforeOrder[p.toolIndex]!.id, i])); - toolCalls.sort((a, b) => (rank.get(a.id) ?? Number.MAX_SAFE_INTEGER) - (rank.get(b.id) ?? Number.MAX_SAFE_INTEGER)); - parts = parts.map((p) => p.kind === "tool" ? { ...p, toolIndex: toolCalls.findIndex((t) => t.id === beforeOrder[p.toolIndex]!.id) } : p); - // Thinking stays between the text/tool parts that bracketed it. Host - // aggregates add separators, so compare the drawn blocks, not that field. - const body = parts.filter((p) => p.kind !== "thinking"); - const thinkingSlots = (source: MessagePart[], sourceTools: ToolCall[], remap = false) => { - const slots = new Map[]>(); - let at = 0; - for (const [index, part] of source.entries()) { - if (part.kind !== "thinking") { at++; continue; } - let slot = at; - if (remap) { - // A recovered tool changes numeric slots. Anchor thinking to a tool - // this copy actually saw, rather than duplicating it at an old index. - const before = source.slice(0, index).filter((p) => p.kind !== "thinking"); - const prior = before.findLastIndex((p) => p.kind === "tool"); - const after = source.slice(index + 1).filter((p) => p.kind !== "thinking"); - const following = after.findIndex((p) => p.kind === "tool"); - const anchor = prior >= 0 ? before[prior] : following >= 0 ? after[following] : undefined; - if (anchor?.kind === "tool") { - const target = body.findIndex((p) => p.kind === "tool" && toolCalls[p.toolIndex]?.id === sourceTools[anchor.toolIndex]?.id); - if (target >= 0) slot = prior >= 0 ? target + before.length - prior : target - following; - } - } - slots.set(slot, [...(slots.get(slot) ?? []), part]); - } - return slots; - }; - const slots = thinkingSlots(parts, toolCalls); - for (const [at, blocks] of thinkingSlots(other.parts, other.toolCalls, true)) { - const mine = slots.get(at) ?? []; - if (blocks.reduce((n, p) => n + p.text.length, 0) > mine.reduce((n, p) => n + p.text.length, 0)) slots.set(at, blocks); - } - parts = body.flatMap((part, at) => [...(slots.get(at) ?? []), part]); - parts.push(...(slots.get(body.length) ?? [])); - const thinking = parts.filter((p) => p.kind === "thinking").map((p) => p.text).join("") || undefined; - // Questions by request: one either copy saw settled is settled, and one - // only the page has drawn stays (its card is the reader's). - const settled = (e: AskUserExchange) => e.answers !== undefined || e.cancelled === true || e.order !== undefined || e.formAnswers !== undefined; - const asks = new Map((base.askUserExchanges ?? []).map((e) => [e.requestId, e])); - for (const e of other.askUserExchanges ?? []) { - const mine = asks.get(e.requestId); - if (!mine || (settled(e) && !settled(mine))) asks.set(e.requestId, e); - } - const askUserExchanges = asks.size ? [...asks.values()] : undefined; - return { - ...base, toolCalls, parts, thinking, askUserExchanges, - // Terminal history is authoritative even when the drawn text is longer. - failure: m.failure ?? base.failure, - retryOfTurnId: m.failure ? m.retryOfTurnId : base.retryOfTurnId, - failureLive: m.failure ? undefined : base.failureLive, - files: m.files ?? base.files, - blocks: m.blocks ?? base.blocks, - id: old.id, timestamp: old.timestamp, isStreaming: true, - turnId: m.turnId, streamTurnId: old.turnId ?? old.streamTurnId, - }; -} - -function emptyChat(): SessionChat { - return { messages: [], isStreaming: false, askUser: null, lastTouched: Date.now() }; -} - /** Frozen empty buffer for selectors when nothing is in view. */ const EMPTY_CHAT: SessionChat = Object.freeze({ messages: Object.freeze([]) as unknown as ChatMessage[], @@ -1015,36 +637,6 @@ export function anyStreaming(state: ChatShellState): boolean { return Object.values(state.buffers).some((b) => b.isStreaming); } -/** Append text to the last part if it has the same kind, else start a new part. */ -function appendPart( - parts: MessagePart[], - kind: "thinking" | "text", - text: string -): MessagePart[] { - const last = parts[parts.length - 1]; - if (last && last.kind === kind) { - return [...parts.slice(0, -1), { kind, text: last.text + text }]; - } - return [...parts, { kind, text }]; -} - -/** The message with no retry notice: the turn moved on, or ended. */ -function withoutRetry(message: ChatMessage): ChatMessage { - if (!message.retry) return message; - const { retry: _retry, ...rest } = message; - return rest; -} - -/** Free object URLs held by live message previews before dropping them. */ -function revokeAttachmentUrls(messages: ChatMessage[], retained: ChatMessage[] = []) { - const kept = new Set(retained.flatMap((m) => (m.attachments ?? []).map((a) => a.previewUrl))); - for (const m of messages) { - for (const a of m.attachments ?? []) { - if (a.previewUrl.startsWith("blob:") && !kept.has(a.previewUrl)) URL.revokeObjectURL(a.previewUrl); - } - } -} - /** * Whether a pending approval may offer "always allow": never for a * destructive-command confirmation, and never when the host said it would @@ -1082,1108 +674,23 @@ export function awaitsDecision(tool: ToolCall): boolean { return tool.status === "pending_approval" && !tool.readOnly && (!tool.voicePermission || tool.voicePermission.phase === "pending"); } -/** Evict least-recently-touched non-active buffers beyond MAX_BUFFERS. */ -function evictStale( - buffers: Record, - activeSessionId: string | null -): Record { - const ids = Object.keys(buffers); - if (ids.length <= MAX_BUFFERS) return buffers; - const evictable = ids - .filter((id) => id !== activeSessionId && !buffers[id].isStreaming) - .sort((a, b) => buffers[a].lastTouched - buffers[b].lastTouched); - const next = { ...buffers }; - for (const id of evictable.slice(0, ids.length - MAX_BUFFERS)) { - revokeAttachmentUrls(next[id].messages); - delete next[id]; - } - return next; -} +/** + * One root's chat store, composed of slices that share its buffers (#1361): + * session, status, messages, streaming, approvals, ask-user and transcript. + */ export function createChatStore(env: StoreEnvironment, provider: StoreApi, composerDrafts?: StoreApi<{ newChat(): void }>) { - let messageCounter = 0; - function nextId() { - return `msg-${++messageCounter}-${Date.now()}`; - } - - const SESSION_ID_KEY = env.storageKey("brain-sessionId"); - const HISTORY_SELECTION_KEY = env.storageKey("brain-history-selection"); - function readHistorySelection():{key:string;ownerId:string}|null { - try {const value:unknown=JSON.parse(env.storage()?.getItem(HISTORY_SELECTION_KEY) ?? "null"); - if(value && typeof value === "object" && "key" in value && "ownerId" in value && typeof value.key === "string" && typeof value.ownerId === "string" && value.key.length<=512 && value.ownerId.length<=256)return {key:value.key,ownerId:value.ownerId}; - }catch{/* A corrupt selection grants no routing authority. */}return null; - } - const STATE_ROOM_KEY = env.storageKey("brain-state-room-preferences"); - function readStateRoomPreferences(): ChatState["stateRoomPreferences"] { - try { - const parsed: unknown = JSON.parse(env.storage()?.getItem(STATE_ROOM_KEY) ?? "{}"); - if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {}; - return Object.fromEntries(Object.entries(parsed).flatMap(([sessionId, value]) => { - if (!value || typeof value !== "object" || Array.isArray(value)) return []; - const preference = value as { dismissedAllowance?: unknown; invalidatedAt?: unknown; backendId?: unknown; measuredAt?: unknown }; - const valid = (n: unknown): n is number => typeof n === "number" && Number.isSafeInteger(n) && n >= 0; - return [[sessionId, { - ...(valid(preference.dismissedAllowance) && preference.dismissedAllowance > 0 ? { dismissedAllowance: preference.dismissedAllowance } : {}), - ...(valid(preference.invalidatedAt) ? { invalidatedAt: preference.invalidatedAt } : {}), - ...(typeof preference.backendId === "string" && preference.backendId.length <= 200 ? { backendId: preference.backendId } : {}), - ...(valid(preference.measuredAt) ? { measuredAt: preference.measuredAt } : {}), - }]]; - })); - } catch { return {}; } - } - function persistStateRoomPreferences(preferences: ChatState["stateRoomPreferences"]): void { - try { env.storage()?.setItem(STATE_ROOM_KEY, JSON.stringify(preferences)); } catch { /* The in-memory dismissal still holds. */ } - } - - /** - * Persist the active session id to localStorage when a DOM is present (the - * browser). A no-op in non-DOM environments (tests, SSR) so creating the store - * never throws on a missing `localStorage`. - */ - function persistSessionId(id: string | null, ownerId?:string) { - const storage = env.storage(); - if (!storage) return; - if(id && ownerId){storage.setItem(HISTORY_SELECTION_KEY,JSON.stringify({key:id,ownerId}));storage.removeItem(SESSION_ID_KEY);} - else {if(id) storage.setItem(SESSION_ID_KEY,id);else storage.removeItem(SESSION_ID_KEY);storage.removeItem(HISTORY_SELECTION_KEY);} - } - - function readPersistedSessionId(): string | null { - const storage = env.storage(); - if (!storage) return null; - return readHistorySelection()?.key ?? storage.getItem(SESSION_ID_KEY); - } - - - const RETRIES_KEY = env.storageKey("brain-turn-retries"); - function readRetries(): Record { - try { - const value: unknown = JSON.parse(env.storage()?.getItem(RETRIES_KEY) ?? "{}"); - if (!value || typeof value !== "object") return {}; - return Object.fromEntries(Object.entries(value).flatMap(([sessionId, retry]) => { - if (!retry || typeof retry !== "object") return []; - const r = retry as Partial; - return typeof r.requestId === "string" && typeof r.failedTurnId === "string" && (r.state === "waiting" || r.state === "unknown") - ? [[sessionId, { requestId: r.requestId, failedTurnId: r.failedTurnId, state: "unknown" as const }]] : []; - })); - } catch { return {}; } - } - - const persistedSessionId = readPersistedSessionId(); + const persistence = createChatPersistence(env); return createStore((set, get) => { - /** - * Immutably update one buffer. Draft mutations (key null) create the draft - * on demand; session mutations require an existing buffer — a frame for an - * evicted/never-opened session must not materialize a partial transcript - * (the view heals via session_resume instead). - */ - function mutateBuffer( - key: ChatKey, - fn: (chat: SessionChat) => Partial, - createIfMissing = false - ): void { - function updated(chat: SessionChat): SessionChat { - const next = { ...chat, ...fn(chat), lastTouched: Date.now() }; - if (!next.journals) return next; - const last = new Map(); - next.messages.forEach((message, index) => { const id = message.turnId ?? message.streamTurnId; if (message.role === "assistant" && id) last.set(id, index); }); - next.messages = next.messages.map((message, index) => { - const id = message.turnId ?? message.streamTurnId, receipt = id && next.journals?.[id]; - if (!receipt || last.get(id!) !== index || message.journal === receipt) return message; - return { ...message, journal: receipt, journalLive: true }; - }); - return next; - } - set((state) => { - if (key === null) { - const draft = state.draft ?? emptyChat(); - return { draft: updated(draft) }; - } - const existing = state.buffers[key] ?? (createIfMissing ? emptyChat() : undefined); - if (!existing) return state; - return { - buffers: { - ...state.buffers, - [key]: updated(existing), - }, - }; - }); - } - - /** - * Update the assistant message that holds tool call `toolUseId`, else the - * last assistant message. A restored approval can sit in a turn shell - * (#964) while the turn's later output streams into a newer message, and - * its decision and result must still reach the card. - */ - function mutateToolHolder(key: ChatKey, toolUseId: string, fn: (msg: ChatMessage) => ChatMessage): void { - mutateBuffer(key, (chat) => { - let index = chat.messages.findLastIndex((m) => m.role === "assistant" && m.toolCalls.some((t) => t.id === toolUseId)); - if (index === -1) index = chat.messages.findLastIndex((m) => m.role === "assistant"); - if (index === -1) return {}; - const msgs = [...chat.messages]; - msgs[index] = fn(msgs[index]!); - return { messages: msgs }; - }); - } - - /** Monotonic per store, so every take is a new request. */ - let composerInsertSeq = 0; - - /** Update the last message of a buffer when it is an assistant message. */ - function mutateLastAssistant( - key: ChatKey, - fn: (msg: ChatMessage) => ChatMessage, - extra?: (chat: SessionChat) => Partial - ): void { - mutateBuffer(key, (chat) => { - const msgs = [...chat.messages]; - // The last ASSISTANT message, not the last message. - // - // A follow-up sent mid-stream appends a user message to the end of the - // buffer while the assistant is still streaming into the message before - // it. Indexing the end therefore aimed every subsequent delta at the - // user's own message, where `role === "assistant"` failed and the write - // was silently discarded — the turn kept running and its output stopped - // appearing. Scanning backwards costs nothing at these lengths and - // leaves single-message behaviour identical. - let index = -1; - for (let i = msgs.length - 1;i >= 0;i--) { - if (msgs[i].role === "assistant") { - index = i; - break; - } - } - let out: Partial = {}; - if (index !== -1) { - msgs[index] = fn(msgs[index]); - out = { messages: msgs }; - } - return extra ? { ...out, ...extra(chat) } : out; - }); - } - + const ctx = createChatSliceContext(set, get); return { - scopeDecisionReceipts: {}, - setScopeDecisionReceipt(receipt) { - const entries = Object.entries(get().scopeDecisionReceipts).filter(([id]) => id !== receipt.eventId).slice(-255); - set({ scopeDecisionReceipts: Object.fromEntries([...entries, [receipt.eventId, receipt]]) }); - }, - chatReceipts: {}, - setChatReceipt(requestId, state, sessionId) { - if (get().chatReceipts[requestId]?.state === "accepted") return; - const entries = Object.entries(get().chatReceipts).filter(([id]) => id !== requestId).slice(-255); - set({ chatReceipts: Object.fromEntries([...entries, [requestId, { state, sessionId }]]) }); - }, - clearChatReceipt(requestId) { - const chatReceipts = { ...get().chatReceipts }; - delete chatReceipts[requestId]; - set({ chatReceipts }); - }, - setMessageEffort(key, requestId, thinkingLevel, effectiveThinkingLevel) { - mutateBuffer(key, (chat) => ({ messages: chat.messages.map((message) => message.role === "user" && message.requestId === requestId - ? { ...message, thinkingLevel, ...(effectiveThinkingLevel !== undefined ? { effectiveThinkingLevel } : {}) } : message) })); - }, - turnRetries: readRetries(), - setTurnRetry(sessionId, retry) { - const turnRetries = { ...get().turnRetries }; - if (retry) turnRetries[sessionId] = retry; - else delete turnRetries[sessionId]; - try { - env.storage()?.setItem(RETRIES_KEY, JSON.stringify(Object.fromEntries(Object.entries(turnRetries).filter(([, r]) => r.state !== "refused")))); - } catch { /* The host also consumes each failed-turn handle once. */ } - set({ turnRetries }); - }, - setRetryHandle: (key, retryOfTurnId) => mutateLastAssistant(key, last => ({ ...last, retryOfTurnId })), - // The stored selection gets its (empty, unconfirmed) buffer, as any - // selection does, so the session's own frames land while its history - // is restored (#1328). - buffers: persistedSessionId ? { [persistedSessionId]: emptyChat() } : {}, - draft: null, - pendingDraftId: null, - detachedDrafts: {}, - // localStorage (not sessionStorage) so the active session id survives the - // PWA process being killed on mobile — that durability is what lets a cold - // relaunch re-request the full transcript instead of showing nothing. - activeSessionId: persistedSessionId, - historyOwners: readHistorySelection() ? {[readHistorySelection()!.key]:readHistorySelection()!.ownerId} : {}, - setHistoryOwner(key,ownerId){ - const historyOwners={...get().historyOwners};if(ownerId)historyOwners[key]=ownerId;else delete historyOwners[key]; - set({historyOwners});if(get().activeSessionId===key)persistSessionId(key,ownerId ?? undefined); - }, - restoreFailures: {}, - failRestore: (sessionId, failure) => - set((state) => (state.buffers[sessionId]?.historyConfirmed && failure.reason !== "missing" - ? state - : { restoreFailures: { ...state.restoreFailures, [sessionId]: failure }, - ...(failure.reason === "missing" && state.buffers[sessionId] ? { buffers: { ...state.buffers, - [sessionId]: { ...state.buffers[sessionId]!, historyConfirmed: undefined } } } : {}), - })), - clearRestoreFailure: (sessionId) => - set((state) => { - if (!state.restoreFailures[sessionId]) return state; - const restoreFailures = { ...state.restoreFailures }; - delete restoreFailures[sessionId]; - return { restoreFailures }; - }), - runStates: {}, - queueNotes: {}, - backendIds: {}, - stateRooms: {}, - stateRoomPreferences: readStateRoomPreferences(), - stateRoomAnnouncements: {}, - setStateRoom(sessionId, observation, historical = false) { - const rooms = { ...get().stateRooms }; - const current = rooms[sessionId]; - if (observation && current && current.observation.observedAt > observation.observedAt) return; - if (historical && current && !current.historical && (!observation || current.observation.observedAt === observation.observedAt)) return; - if (observation) rooms[sessionId] = { observation, historical }; - else delete rooms[sessionId]; - const preferences = { ...get().stateRoomPreferences }; - if (observation && !historical && (preferences[sessionId]?.invalidatedAt !== undefined - || (preferences[sessionId]?.dismissedAllowance !== undefined && preferences[sessionId]!.dismissedAllowance !== observation.allowanceBytes))) { - const dismissed = preferences[sessionId]?.dismissedAllowance; - preferences[sessionId] = { ...(dismissed === observation.allowanceBytes ? { dismissedAllowance: dismissed } : {}) }; - persistStateRoomPreferences(preferences); - } - set({ stateRooms: rooms, stateRoomPreferences: preferences }); - }, - dismissStateRoom(sessionId, allowanceBytes) { - const preferences = { ...get().stateRoomPreferences, [sessionId]: { ...get().stateRoomPreferences[sessionId], dismissedAllowance: allowanceBytes, - backendId: get().backendIds[sessionId], measuredAt: get().stateRooms[sessionId]?.observation.observedAt } }; - persistStateRoomPreferences(preferences); set({ stateRoomPreferences: preferences }); - }, - invalidateStateRoom(sessionId, observedAt) { - const prior = get().stateRoomPreferences[sessionId]; - if (prior?.invalidatedAt === observedAt && prior.dismissedAllowance === undefined) return; - const preferences = { ...get().stateRoomPreferences, [sessionId]: { invalidatedAt: observedAt } }; - persistStateRoomPreferences(preferences); set({ stateRoomPreferences: preferences }); - }, - markStateRoomAnnounced(sessionId, allowanceBytes) { - set({ stateRoomAnnouncements: { ...get().stateRoomAnnouncements, [sessionId]: allowanceBytes } }); - }, - - // createIfMissing: a user-initiated send must never be dropped, even when - // the active session's buffer hasn't been materialized yet (cold start - // racing the history replay). - addUserMessage: (key, text, source, attachments, effort, files) => - mutateBuffer( - key, - (chat) => ({ - messages: [ - ...chat.messages, - { - id: nextId(), - role: "user", - content: text, - toolCalls: [], - parts: [], - isStreaming: false, - timestamp: Date.now(), - source: source ?? "typed", - ...effort, - ...(files?.length ? { files } : {}), - ...(attachments && attachments.length > 0 - ? { attachments, attachmentCount: attachments.length } - : {}), - }, - ], - }), - true - ), - - startAssistantMessage: (key, turnId, requestId) => - mutateBuffer(key, (chat) => ({ - messages: [ - ...chat.messages, - { - id: nextId(), - role: "assistant", - content: "", - thinking: "", - toolCalls: [], - parts: [], - isStreaming: true, - timestamp: Date.now(), - ...(turnId ? { turnId } : {}), - ...(requestId ? { requestId } : {}), - }, - ], - isStreaming: true, - })), - - appendText: (key, text) => - mutateLastAssistant(key, (last) => ({ - ...withoutRetry(last), - content: last.content + text, - parts: appendPart(last.parts, "text", text), - })), - - setStatsAnswer: (key, sections) => - mutateLastAssistant(key, (last) => ({ ...last, statsAnswer: sections })), - - setLocalExchange: (key, exchange) => - mutateLastAssistant(key, (last) => ({ ...last, localExchange: exchange })), - - markLocalExchange: (exchangeId, saved, reason) => - set((state) => { - const mark = (chat: SessionChat): SessionChat | null => { - const index = chat.messages.findIndex((m) => m.localExchange?.id === exchangeId); - if (index === -1) return null; - const messages = [...chat.messages]; - const current = messages[index]!; - const { reason: _previous, ...exchange } = current.localExchange!; - messages[index] = { - ...current, - localExchange: { ...exchange, saved, ...(reason ? { reason } : {}) }, - }; - return { ...chat, messages }; - }; - const draft = state.draft ? mark(state.draft) : null; - if (draft) return { draft }; - for (const [key, chat] of Object.entries(state.buffers)) { - const marked = mark(chat); - if (marked) return { buffers: { ...state.buffers, [key]: marked } }; - } - return state; - }), - - appendThinking: (key, text) => - mutateLastAssistant(key, (last) => ({ - ...withoutRetry(last), - thinking: (last.thinking || "") + text, - parts: appendPart(last.parts, "thinking", text), - })), - - startToolCall: (key, toolUseId, toolName) => - mutateLastAssistant(key, (last) => ({ - ...last, - parts: [...last.parts, { kind: "tool", toolIndex: last.toolCalls.length }], - toolCalls: [ - ...last.toolCalls, - { - id: toolUseId, - name: toolName, - input: {}, - inputJson: "", - status: "streaming", - startedAt: Date.now(), - }, - ], - })), - - appendToolInput: (key, partialJson) => - mutateLastAssistant(key, (last) => { - if (last.toolCalls.length === 0) return last; - const tools = [...last.toolCalls]; - const lastTool = tools[tools.length - 1]; - tools[tools.length - 1] = { - ...lastTool, - inputJson: lastTool.inputJson + partialJson, - }; - return { ...last, toolCalls: tools }; - }), - - completeToolCall: (key, toolUseId, toolName, input) => - mutateLastAssistant(key, (last) => ({ - ...last, - toolCalls: last.toolCalls.map((t) => - t.id === toolUseId || (t.name === toolName && t.status === "streaming") - ? { - ...t, - id: toolUseId, - input, - status: "complete" as const, - // Input finished streaming — execution starts about now - startedAt: Date.now(), - } - : t - ), - })), - - requestToolApproval: (key, toolUseId, toolName, input, description, kind, rememberable, turnId) => - mutateBuffer(key, (chat) => { - const msgs = [...chat.messages]; - const request = (previous: ToolCall | undefined, restored: boolean): ToolCall => ({ - id: toolUseId, - name: toolName, - input, - inputJson: JSON.stringify(input, null, 2), - status: "pending_approval", - ...(kind ? { approvalKind: kind } : {}), - ...(kind === "policy" && POLICY_CHANGE_REVIEW_SCHEMA.safeParse(input.policyReview).success ? { policyChange: POLICY_CHANGE_REVIEW_SCHEMA.parse(input.policyReview) } : {}), - ...(rememberable === false ? { approvalRememberable: false } : {}), - ...(description ? { approvalDescription: description } : {}), - // A card already pending keeps what it was; anything else is - // restored when it lands on a message no live turn is streaming. - ...((previous?.status === "pending_approval" ? previous.restored : restored) - ? { restored: true as const, ...(turnId ? { approvalTurnId: turnId } : {}) } - : {}), - }); - // One card per request: a re-delivery updates the card wherever it - // is, and never draws a second one (#964). - const holder = msgs.findLastIndex((m) => m.role === "assistant" && m.toolCalls.some((t) => t.id === toolUseId)); - if (holder !== -1) { - const target = msgs[holder]!; - msgs[holder] = { - ...target, - // A card the host already closed with a reason (#1072) stays - // closed: a late duplicate of its request revives nothing. - toolCalls: target.toolCalls.map((t) => t.id !== toolUseId || (t.readOnly && t.readOnly !== "unlisted") ? t : request(t, !target.isStreaming)), - }; - return { messages: msgs }; - } - // The turn's own answer, when a message carries its id; otherwise - // the latest answer, if it is still streaming or comes after the - // user's latest message, and no other turn owns it. - let index = turnId ? msgs.findLastIndex((m) => m.role === "assistant" && m.turnId === turnId) : -1; - if (index === -1) { - const last = msgs.findLastIndex((m) => m.role === "assistant"); - const lastUser = msgs.findLastIndex((m) => m.role === "user"); - const candidate = last === -1 ? undefined : msgs[last]!; - if (candidate && (candidate.isStreaming || last > lastUser) && (!candidate.turnId || !turnId || candidate.turnId === turnId)) { - index = last; - } - } - if (index === -1) { - // No answer belongs to this turn: the replay ended on the user's - // message. Draw the turn's shell, holding only the card, with no - // invented text (D52 §4, approval recovery). - msgs.push({ - id: nextId(), - role: "assistant", - content: "", - toolCalls: [request(undefined, true)], - parts: [{ kind: "tool", toolIndex: 0 }], - isStreaming: false, - timestamp: Date.now(), - turnShell: true, - ...(turnId ? { turnId } : {}), - }); - return { messages: msgs }; - } - const last = msgs[index]!; - // Check if tool call already exists (from streaming) - const existingIdx = last.toolCalls.findIndex( - (t) => t.name === toolName && t.status === "streaming" - ); - const tools = [...last.toolCalls]; - const toolCall = request(undefined, !last.isStreaming); - let parts = last.parts; - if (existingIdx >= 0) { - tools[existingIdx] = toolCall; - } else { - // Approval request for a tool that never streamed a start event — - // give it a chronological slot too. - parts = [...parts, { kind: "tool", toolIndex: tools.length }]; - tools.push(toolCall); - } - msgs[index] = { ...last, toolCalls: tools, parts }; - return { messages: msgs }; - }), - - applyVoicePermission: (receipt) => { - const key = receipt.sessionId; - const chat = get().buffers[key]; - const owns = (m: ChatMessage, t: ToolCall) => t.id === receipt.toolUseId && (t.approvalTurnId ?? m.turnId ?? m.streamTurnId) === receipt.turnId; - if (!chat?.messages.some(m => m.toolCalls.some(t => owns(m, t) && t.voicePermission !== receipt))) return; - mutateBuffer(key, current => ({ messages: current.messages.map(m => ({ ...m, toolCalls: m.toolCalls.map(t => { - if (!owns(m, t)) return t; - // Receipt state locks decisions through awaitsDecision. Preserve the - // transcript status so ordinary result/recovery routing can still - // recognize an unanswered restored card and record its closure. - return { ...t, voicePermission: receipt }; - }) })) })); - }, - - resolveToolApproval: (key, toolUseId, approved) => - mutateToolHolder(key, toolUseId, (last) => ({ - ...last, - toolCalls: last.toolCalls.map((t) => - t.id === toolUseId - ? { - ...t, - status: approved ? ("approved" as const) : ("denied" as const), - // Don't let approval wait time inflate the duration badge - ...(approved ? { startedAt: Date.now() } : {}), - } - : t - ), - })), - - closeRestoredApprovals: (key, closures) => { - if (closures.length === 0) return; - const byId = new Map(closures.map((c) => [c.toolUseId, c.closure])); - mutateBuffer(key, (chat) => { - let changed = false; - const messages = chat.messages.map((m) => { - if (m.role !== "assistant" || !m.toolCalls.some((t) => byId.has(t.id))) return m; - let touched = false; - const toolCalls = m.toolCalls.map((t) => { - const closure = byId.get(t.id); - if (!closure || !t.restored || t.readOnly === closure) return t; - // Decided on this page: the card already says what happened. - if (t.status === "approved" || t.status === "denied") return t; - if (t.readOnly && t.readOnly !== "unlisted") return t; - touched = true; - return { ...t, readOnly: closure }; - }); - if (!touched) return m; - changed = true; - return { ...m, toolCalls }; - }); - return changed ? { messages } : {}; - }); - }, - - reopenRestoredApprovals: (key, toolUseIds) => { - const reopen = (t: ToolCall) => toolUseIds.includes(t.id) && t.readOnly === "unlisted" && t.status === "pending_approval"; - const chat = key === null ? get().draft : get().buffers[key]; - if (!chat?.messages.some((m) => m.toolCalls.some(reopen))) return; - mutateBuffer(key, (current) => ({ - messages: current.messages.map((m) => { - if (!m.toolCalls.some(reopen)) return m; - return { ...m, toolCalls: m.toolCalls.map((t) => { - if (!reopen(t)) return t; - const { readOnly: _closed, ...open } = t; - return open; - }) }; - }), - })); - }, - - revokeRestoredApprovals: () => - set((state) => { - const revoke = (chat: SessionChat): SessionChat => { - if (!chat.messages.some((m) => m.toolCalls.some((t) => t.restored && t.readOnly !== "revoked"))) return chat; - const messages = chat.messages.map((m) => { - if (!m.toolCalls.some((t) => t.restored && t.readOnly !== "revoked")) return m; - const toolCalls = m.toolCalls.map((t) => { - if (!t.restored || t.readOnly === "revoked") return t; - // The request's identity goes with the authority to answer - // it: the card keeps only what it showed. - const { approvalTurnId: _turn, ...rest } = t; - return { ...rest, id: `revoked-${nextId()}`, readOnly: "revoked" as const }; - }); - if (!m.turnShell) return { ...m, toolCalls }; - const { turnId: _shellTurn, ...shell } = m; - return { ...shell, toolCalls }; - }); - return { ...chat, messages }; - }; - const buffers = Object.fromEntries(Object.entries(state.buffers).map(([id, chat]) => [id, revoke(chat)])); - const changed = Object.keys(buffers).some((id) => buffers[id] !== state.buffers[id]); - const draft = state.draft ? revoke(state.draft) : state.draft; - if (!changed && draft === state.draft) return state; - return { buffers, draft }; - }), - - setToolResult: (key, toolUseId, output, isError, policyChange) => - mutateToolHolder(key, toolUseId, (last) => ({ - ...last, - toolCalls: last.toolCalls.map((t) => - t.id === toolUseId - ? { - ...t, - output, - isError, - ...(policyChange ? { policyChange } : {}), - status: "complete" as const, - endedAt: Date.now(), - } - : t - ), - })), - - setAskUserRequest: (key, requestId, questions, turnId) => - mutateBuffer(key, (chat) => addExchange(chat, { requestId, questions, ...(turnId ? { turnId } : {}) })), - - setAskUserListRequest: (key, requestId, list, turnId) => - mutateBuffer(key, (chat) => addExchange(chat, { requestId, questions: [], list, ...(turnId ? { turnId } : {}) })), - - setAskUserRankRequest: (key, requestId, rank, turnId) => - mutateBuffer(key, (chat) => addExchange(chat, { requestId, questions: [], rank, ...(turnId ? { turnId } : {}) })), - - submitAskUserRankOrder: (key, requestId, order, unchanged) => - mutateBuffer(key, (chat) => { - const answeredAt = Date.now(); - const update = (e: AskUserExchange): AskUserExchange => - e.requestId === requestId - ? { ...e, order, unchanged, answeredAt } - : e; - const msgs = chat.messages.map((m) => - m.askUserExchanges?.some((e) => e.requestId === requestId) - ? { ...m, askUserExchanges: m.askUserExchanges.map(update) } - : m - ); - const askUser = - chat.askUser?.requestId === requestId ? update(chat.askUser) : chat.askUser; - return { messages: msgs, askUser }; - }), - - setAskUserFormRequest: (key, requestId, form, turnId) => - mutateBuffer(key, (chat) => addExchange(chat, { requestId, questions: [], form, ...(turnId ? { turnId } : {}) })), - - submitAskUserFormAnswers: (key, requestId, formAnswers, visibleNodes) => - mutateBuffer(key, (chat) => { - const answeredAt = Date.now(); - const update = (e: AskUserExchange): AskUserExchange => - e.requestId === requestId - ? { ...e, formAnswers, visibleNodes, answeredAt } - : e; - const msgs = chat.messages.map((m) => - m.askUserExchanges?.some((e) => e.requestId === requestId) - ? { ...m, askUserExchanges: m.askUserExchanges.map(update) } - : m - ); - const askUser = - chat.askUser?.requestId === requestId ? update(chat.askUser) : chat.askUser; - return { messages: msgs, askUser }; - }), - - submitAskUserListAnswers: (key, requestId, answers, notes) => - mutateBuffer(key, (chat) => { - const answeredAt = Date.now(); - const update = (e: AskUserExchange): AskUserExchange => - e.requestId === requestId - ? { ...e, answers, answeredAt, ...(notes && Object.keys(notes).length ? { notes } : {}) } - : e; - const msgs = chat.messages.map((m) => - m.askUserExchanges?.some((e) => e.requestId === requestId) - ? { ...m, askUserExchanges: m.askUserExchanges.map(update) } - : m - ); - const askUser = - chat.askUser?.requestId === requestId ? update(chat.askUser) : chat.askUser; - return { messages: msgs, askUser }; - }), - - submitAskUserAnswers: (key, requestId, answers, annotations, typed) => - mutateBuffer(key, (chat) => { - const answeredAt = Date.now(); - const update = (e: AskUserExchange): AskUserExchange => - e.requestId === requestId - ? { ...e, answers, annotations, answeredAt, ...(typed ? { typed: true } : {}) } - : e; - const msgs = chat.messages.map((m) => - m.askUserExchanges?.some((e) => e.requestId === requestId) - ? { ...m, askUserExchanges: m.askUserExchanges.map(update) } - : m - ); - const askUser = - chat.askUser?.requestId === requestId ? update(chat.askUser) : chat.askUser; - return { messages: msgs, askUser }; - }), - - cancelAskUser: (key, requestId) => - mutateBuffer(key, (chat) => { - const update = (e: AskUserExchange): AskUserExchange => - e.requestId === requestId ? { ...e, cancelled: true } : e; - const msgs = chat.messages.map((m) => - m.askUserExchanges?.some((e) => e.requestId === requestId) - ? { ...m, askUserExchanges: m.askUserExchanges.map(update) } - : m - ); - const askUser = - chat.askUser?.requestId === requestId ? update(chat.askUser) : chat.askUser; - return { messages: msgs, askUser }; - }), - - reopenAskExchange: (key, requestId) => - mutateBuffer(key, (chat) => { - let reopened: AskUserExchange | null = null; - const msgs = chat.messages.map((m) => { - if (!m.askUserExchanges?.some((e) => e.requestId === requestId)) return m; - return { - ...m, - askUserExchanges: m.askUserExchanges.map((e) => { - if (e.requestId !== requestId) return e; - const { - answers: _a, annotations: _n, notes: _o, order: _r, unchanged: _u, - formAnswers: _f, visibleNodes: _v, typed: _t, answeredAt: _w, cancelled: _c, - ...rest - } = e; - reopened = rest; - return rest; - }), - }; - }); - return reopened ? { messages: msgs, askUser: reopened } : {}; - }), - - deliveries: {}, - setDelivery: (requestId, delivery) => - set((state) => { - const deliveries = { ...state.deliveries }; - if (delivery) deliveries[requestId] = delivery; - else delete deliveries[requestId]; - return { deliveries }; - }), - - clearAskUser: (key) => mutateBuffer(key, () => ({ askUser: null })), - - endTurnQuestions: (key, turnId) => mutateBuffer(key, (chat) => { - const end = (exchange: AskUserExchange): AskUserExchange => { - if ((turnId && exchange.turnId !== turnId) || exchange.answers || exchange.order || exchange.formAnswers || exchange.cancelled) return exchange; - return { ...exchange, cancelled: true, terminal: true }; - }; - return { - messages: chat.messages.map((message) => message.askUserExchanges ? { ...message, askUserExchanges: message.askUserExchanges.map(end) } : message), - askUser: chat.askUser ? end(chat.askUser) : null, - }; - }), - - finishAssistantMessage: (key) => - mutateLastAssistant( - key, - (last) => ({ ...withoutRetry(last), isStreaming: false }), - () => ({ isStreaming: false }) - ), - - failAssistantMessage: (key, failure, turnId, replace = false) => - mutateBuffer( - key, - (chat) => { - const msgs = [...chat.messages]; - let index = -1; - if (turnId) { - index = msgs.findLastIndex((m) => m.role === "assistant" && m.turnId === turnId); - } - if (index === -1) { - // The composer opens the turn's message before the turn has an - // id, and a failure with no deltas never stamps one — so the - // last assistant message, unless another turn owns it. - const last = msgs.findLastIndex((m) => m.role === "assistant"); - const owner = last === -1 ? undefined : msgs[last].turnId; - if (last !== -1 && (owner === undefined || owner === turnId)) index = last; - } - if (index === -1) { - msgs.push({ - id: nextId(), - role: "assistant", - content: "", - toolCalls: [], - parts: [], - isStreaming: false, - timestamp: Date.now(), - ...(turnId ? { turnId } : {}), - }); - index = msgs.length - 1; - } - const target = msgs[index]; - msgs[index] = { - ...withoutRetry(target), - isStreaming: false, - failure: target.failure && !replace ? target.failure : failure, - failureLive: true, - ...(turnId ? { turnId } : {}), - }; - // The buffer streams while its newest message does: a follow-up - // already running after this message keeps it streaming. - const streaming = msgs.some((m) => m.role === "assistant" && m.isStreaming); - return { messages: msgs, isStreaming: streaming }; - }, - true - ), - - setRetry: (key, retry) => - mutateLastAssistant(key, (last) => { - if (!last.isStreaming) return last; - return retry ? { ...last, retry } : withoutRetry(last); - }), - - setMessageBlocks: (key, blocks, turnId) => - mutateBuffer(key, (chat) => { - const msgs = [...chat.messages]; - let index = -1; - if (turnId) { - for (let i = msgs.length - 1; i >= 0; i--) { - if (msgs[i].role === "assistant" && msgs[i].turnId === turnId) { - index = i; - break; - } - } - } - if (index === -1) { - // No message carries the turn (an optimistic message opened by - // the composer, or a frame without one): the last assistant - // message, but only once it has finished — never a follow-up - // still streaming. - for (let i = msgs.length - 1; i >= 0; i--) { - if (msgs[i].role === "assistant") { - if (!msgs[i].isStreaming) index = i; - break; - } - } - } - if (index === -1) return {}; - // Blocks are anchored to the streamed text: after promoted links - // rewrote it (#1698), they follow the rewrite. - const rewrite = msgs[index].linkRewrite; - msgs[index] = rewrite - ? { ...msgs[index], blocks: rebaseBlocks(blocks, rewriteTexts(rewrite.texts, rewrite.links).map((result) => result.edits)), - linkRewrite: { ...rewrite, blocks } } - : { ...msgs[index], blocks }; - return { messages: msgs }; - }), - - setTurnJournal: (key, turnId, journal) => mutateBuffer(key, chat => ({ journals: { ...chat.journals, [turnId]: journal } }), true), - - rewriteMessageLinks: (key, links, turnId) => - mutateBuffer(key, (chat) => { - if (links.length === 0) return {}; - const ofTurn = (m: ChatMessage) => m.role === "assistant" && !!turnId && (m.turnId ?? m.streamTurnId) === turnId; - let targets = chat.messages.filter(ofTurn); - if (targets.length === 0) { - // A message the composer opened before any turn was named. - const last = chat.messages.findLast((m) => m.role === "assistant"); - if (last && !(last.turnId ?? last.streamTurnId)) targets = [last]; - } - let changed = false; - const msgs = chat.messages.map((m) => { - if (!targets.includes(m)) return m; - const current = textsOf(m); - // Always from the streamed text, so every edit is in its offsets. - const base = m.linkRewrite && m.linkRewrite.texts.length === current.length - ? m.linkRewrite - : { texts: current, links: {}, ...(m.blocks ? { blocks: m.blocks } : {}) }; - const merged = { ...base.links, ...Object.fromEntries(links.map((link) => [link.from, link.to])) }; - const results = rewriteTexts(base.texts, merged); - if (results.every((result, k) => result.text === current[k])) return m; - changed = true; - let k = 0; - const parts = m.parts.map((part) => (part.kind === "text" ? { ...part, text: results[k++]!.text } : part)); - const texts = results.map((result) => result.text); - const map = new Map(Object.entries(merged)); - // Live, the aggregate is the parts joined; otherwise rewrite it as it is. - const content = m.content === current.join("") - ? texts.join("") - : rewriteLinkDestinations(m.content, (destination) => map.get(destination) ?? destination); - const blocks = base.blocks ? rebaseBlocks(base.blocks, results.map((result) => result.edits)) : undefined; - return { ...m, content, parts, ...(blocks ? { blocks } : {}), linkRewrite: { ...base, links: merged } }; - }); - return changed ? { messages: msgs } : {}; - }), - - stampTurn: (key, turnId) => - mutateLastAssistant(key, (last) => - last.isStreaming && !last.turnId ? { ...last, turnId } : last - ), - - setStreaming: (key, streaming) => mutateBuffer(key, () => ({ isStreaming: streaming })), - - historyLoads: {}, - noteHistoryLoaded: (sessionId) => - set((state) => ({ historyLoads: { ...state.historyLoads, [sessionId]: (state.historyLoads[sessionId] ?? 0) + 1 } })), - - setMessages: (key, messages) => - set((state) => { - if (key === null) { - if (state.draft) revokeAttachmentUrls(state.draft.messages); - return { - draft: { ...emptyChat(), messages }, - }; - } - const existing = state.buffers[key]; - const base = existing ? { messages: existing.messages, isStreaming: existing.isStreaming } : null; - const drawn = base ? keepDrawnMessages(withKnownTurns(messages, base.messages), base) : { messages, isStreaming: false }; - if (existing) revokeAttachmentUrls(existing.messages, drawn.messages); - // The first chunk of the host's history: whatever it holds, even - // nothing, the transcript is the host's now (#1328). - const buffers = { - ...state.buffers, - [key]: base - ? { ...emptyChat(), ...drawn, replay: { base, received: messages }, historyConfirmed: true as const } - : { ...emptyChat(), messages, historyConfirmed: true as const }, - }; - const restoreFailures = { ...state.restoreFailures }; - delete restoreFailures[key]; - return { buffers: evictStale(buffers, state.activeSessionId), restoreFailures }; - }), - - appendMessages: (key, messages) => - set((state) => { - if (key === null) { - const draft = state.draft ?? emptyChat(); - return { draft: { ...draft, messages: [...draft.messages, ...messages] } }; - } - const existing = state.buffers[key] ?? emptyChat(); - if (existing.replay) { - // A later chunk of the same replay: reconcile the whole replay so - // far against the transcript it replaced, so a message the first - // chunk kept back as still being written is not drawn twice. The - // answer as it stands now (deltas since) is the live one. - const { base, received } = existing.replay; - const now = existing.messages.at(-1); - const live = base.messages.at(-1); - const current = now && live && now.id === live.id ? { ...base, messages: [...base.messages.slice(0, -1), now] } : base; - const all = [...received, ...messages]; - const drawn = keepDrawnMessages(withKnownTurns(all, current.messages), current); - revokeAttachmentUrls(existing.messages, drawn.messages); - return { - buffers: { - ...state.buffers, - [key]: { ...existing, ...drawn, replay: { base: current, received: all }, lastTouched: Date.now() }, - }, - }; - } - return { - buffers: { - ...state.buffers, - [key]: { - ...existing, - messages: [...existing.messages, ...messages], - lastTouched: Date.now(), - }, - }, - }; - }), - - finishHistoryReplay: (key, keepRunning) => mutateBuffer(key, (existing) => { - if (!existing.replay) return {}; - // Running status cannot make a lagging replay authoritative over - // the live answer and its already drawn prefix. - if (keepRunning && existing.isStreaming) return { replay: undefined }; - const { base, received } = existing.replay; - const now = existing.messages.at(-1); - const live = base.messages.at(-1); - // A full replay is already reconciled. Progress that opened another - // message afterward is live, not an unreceived history suffix. A - // lagging backend can also omit just the answer that was live before - // the replay; retain that answer even if this status ends its turn. - if (received.length >= base.messages.length || now?.id !== live?.id - || (base.isStreaming && live?.isStreaming && received.length === base.messages.length - 1 - && existing.messages.slice(0, received.length).every((m, i) => m.id === base.messages[i]!.id))) { - return { replay: undefined }; - } - const drawn = keepDrawnMessages(withKnownTurns(received, existing.messages), existing, false); - revokeAttachmentUrls(existing.messages, drawn.messages); - return { ...drawn, replay: undefined }; - }), - - startDraftTurn: () => { - const id = - typeof crypto !== "undefined" && "randomUUID" in crypto - ? crypto.randomUUID() - : `draft-${Date.now()}-${Math.random().toString(36).slice(2)}`; - set({ pendingDraftId: id }); - return id; - }, - - bindDraftSession: (sessionId) => - set((state) => { - const adopted = state.buffers[sessionId] ?? state.draft ?? emptyChat(); - const buffers = evictStale( - // This client started the conversation: it holds all of it. - { ...state.buffers, [sessionId]: { ...adopted, lastTouched: Date.now(), historyConfirmed: true } }, - sessionId - ); - const followView = state.activeSessionId === null; - if (followView) persistSessionId(sessionId); - return { - buffers, - draft: null, - pendingDraftId: null, - ...(followView ? { activeSessionId: sessionId } : {}), - }; - }), - - setActiveSession: (sessionId) => - set((state) => { - persistSessionId(sessionId,sessionId ? state.historyOwners[sessionId] : undefined); - if (sessionId === null) return { activeSessionId: null }; - const existing = state.buffers[sessionId]; - const buffers = existing - ? state.buffers - : evictStale({ ...state.buffers, [sessionId]: emptyChat() }, sessionId); - // Selecting a session again is a new attempt at restoring it (#1328). - let restoreFailures = state.restoreFailures; - if (sessionId !== state.activeSessionId && restoreFailures[sessionId]) { - restoreFailures = { ...restoreFailures }; - delete restoreFailures[sessionId]; - } - return { activeSessionId: sessionId, buffers, restoreFailures }; - }), - - setRunState: (sessionId, runState, note) => - set((state) => { - const noteChanged = (state.queueNotes[sessionId] ?? undefined) !== note; - if (state.runStates[sessionId] === runState && !noteChanged) return state; - - const runStates = { ...state.runStates }; - if (runState === "idle") delete runStates[sessionId]; - else runStates[sessionId] = runState; - - // The note belongs to the queued state; anything else ends it. A - // `queued` frame with no note also clears, so a queue that drained back - // under the warn mark stops claiming it is heavy. - const queueNotes = { ...state.queueNotes }; - if (runState === "queued" && note) queueNotes[sessionId] = note; - else delete queueNotes[sessionId]; - - return { runStates, queueNotes }; - }), - - setSessionBackend: (sessionId, backendId) => - set((state) => - state.backendIds[sessionId] === backendId - ? state - : { backendIds: { ...state.backendIds, [sessionId]: backendId } } - ), - - composerInsert: null, - requestComposerInsert: (text) => - set({ composerInsert: { seq: ++composerInsertSeq, text } }), - clearComposerInsert: (seq) => - set((state) => (state.composerInsert?.seq === seq ? { composerInsert: null } : state)), - - clearMessages: () => { - const state = get(); - // A first message still unanswered keeps its transcript, aside: its - // announcement binds it there, not to whatever the view shows next. - const detach = state.draft && state.pendingDraftId ? state.pendingDraftId : null; - if (state.draft && !detach) revokeAttachmentUrls(state.draft.messages); - persistSessionId(null); - // Starting fresh: unpin the provider so the picker unlocks. - provider.getState().setPinned(null); - composerDrafts?.getState().newChat(); - set({ - draft: null, - activeSessionId: null, - ...(detach ? { pendingDraftId: null, detachedDrafts: { ...state.detachedDrafts, [detach]: state.draft! } } : {}), - }); - }, - - bindDetachedDraft: (correlationId, sessionId) => - set((state) => { - const adopted = state.detachedDrafts[correlationId]; - if (!adopted) return state; - const detachedDrafts = { ...state.detachedDrafts }; - delete detachedDrafts[correlationId]; - const existing = state.buffers[sessionId]; - return { - detachedDrafts, - buffers: evictStale( - { ...state.buffers, [sessionId]: existing ?? { ...adopted, lastTouched: Date.now(), historyConfirmed: true } }, - state.activeSessionId ?? sessionId - ), - }; - }), - - withdrawSend: (key, requestId) => - set((state) => { - const strip = (chat: SessionChat): SessionChat => { - const messages = chat.messages.filter((m) => !(m.requestId === requestId && (m.role === "user" || (!m.turnId && !m.content && !m.thinking && m.toolCalls.length === 0)))); - if (messages.length === chat.messages.length) return chat; - return { ...chat, messages, isStreaming: chat.isStreaming && messages.some((m) => m.role === "assistant" && m.isStreaming) }; - }; - if (key !== null) { - const buffer = state.buffers[key]; - return buffer ? { buffers: { ...state.buffers, [key]: strip(buffer) } } : state; - } - const detachedDrafts = Object.fromEntries(Object.entries(state.detachedDrafts).map(([id, chat]) => [id, strip(chat)])); - return { ...(state.draft ? { draft: strip(state.draft) } : {}), detachedDrafts }; - }), + ...createStatusSlice(ctx, persistence), + ...createSessionSlice(ctx, persistence, provider, composerDrafts), + ...createMessagesSlice(ctx), + ...createApprovalsSlice(ctx), + ...createAskUserSlice(ctx), + ...createStreamingSlice(ctx), + ...createTranscriptSlice(ctx), }; }); - } diff --git a/packages/ui-react/tests/chat-slices.test.ts b/packages/ui-react/tests/chat-slices.test.ts new file mode 100644 index 0000000000..5d2015855f --- /dev/null +++ b/packages/ui-react/tests/chat-slices.test.ts @@ -0,0 +1,481 @@ +/** + * Direct tests of the chat store's slices (#1361). Each slice runs over a + * bare store holding only the shared buffer fields, so a slice that reached + * into another slice's state would fail here before it failed in the + * composed store. + */ +import { afterEach, describe, expect, mock, test } from "bun:test"; +import { createStore, type StoreApi } from "zustand/vanilla"; +import type { MessageLink, TurnFailure, TurnJournalSummary } from "@schlessera/brain-ui-sdk/protocol"; +import { createChatStore, type ChatMessage, type ChatState, type SessionChat } from "../src/stores/chat-state"; +import { createApprovalsSlice } from "../src/stores/chat-slices/approvals"; +import { createAskUserSlice, isSettledExchange } from "../src/stores/chat-slices/ask-user"; +import { createChatSliceContext, emptyChat, evictStale, revokeAttachmentUrls, type ChatSliceContext } from "../src/stores/chat-slices/buffers"; +import { createMessagesSlice } from "../src/stores/chat-slices/messages"; +import { createChatPersistence } from "../src/stores/chat-slices/persistence"; +import { createSessionSlice } from "../src/stores/chat-slices/session"; +import { createStatusSlice } from "../src/stores/chat-slices/status"; +import { createStreamingSlice } from "../src/stores/chat-slices/streaming"; +import { createTranscriptSlice } from "../src/stores/chat-slices/transcript"; +import type { ProviderState } from "../src/stores/provider-state"; +import type { StoreEnvironment } from "../src/stores/store-environment"; + +function memoryStorage(): Storage { + const values = new Map(); + return { + getItem: (key) => values.get(key) ?? null, + setItem: (key, value) => void values.set(key, String(value)), + removeItem: (key) => void values.delete(key), + clear: () => values.clear(), + key: (index) => [...values.keys()][index] ?? null, + get length() { return values.size; }, + }; +} + +function environment(storage: Storage | null = memoryStorage()): StoreEnvironment { + return { storage: () => storage, storageKey: (key: string) => `odysseus:${key}` } as unknown as StoreEnvironment; +} + +/** A bare store: the shared buffer fields plus exactly one slice. */ +function sliceStore(slice: (ctx: ChatSliceContext) => S, base: Partial = {}): StoreApi { + return createStore((set, get) => ({ + buffers: {}, draft: null, activeSessionId: null, restoreFailures: {}, detachedDrafts: {}, pendingDraftId: null, + ...base, + ...slice(createChatSliceContext(set, get)), + }) as unknown as ChatState & S); +} + +function message(overrides: Partial & Pick): ChatMessage { + return { content: "", toolCalls: [], parts: [], isStreaming: false, timestamp: 0, ...overrides }; +} + +function buffer(messages: ChatMessage[], extra: Partial = {}): SessionChat { + return { ...emptyChat(), messages, ...extra }; +} + +function provider() { + const setPinned = mock((pinned: unknown) => void pinned); + return { setPinned, store: createStore(() => ({ setPinned })) as unknown as StoreApi }; +} + +describe("buffers", () => { + const revoke = Object.getOwnPropertyDescriptor(URL, "revokeObjectURL")!; + afterEach(() => { Object.defineProperty(URL, "revokeObjectURL", revoke); }); + + test("a session mutation needs an existing buffer; the draft and createIfMissing make one", () => { + const store = sliceStore((ctx) => ({ ctx })); + const { ctx } = store.getState(); + ctx.mutateBuffer("ithaca", () => ({ isStreaming: true })); + expect(store.getState().buffers).toEqual({}); + ctx.mutateBuffer("ithaca", () => ({ isStreaming: true }), true); + expect(store.getState().buffers.ithaca?.isStreaming).toBe(true); + ctx.mutateBuffer(null, () => ({ isStreaming: true })); + expect(store.getState().draft?.isStreaming).toBe(true); + }); + + test("a turn's journal receipt lands on that turn's last assistant message only", () => { + const journal = { turnId: "t1" } as unknown as TurnJournalSummary; + const store = sliceStore((ctx) => ({ ctx }), { buffers: { ithaca: buffer([ + message({ id: "a1", role: "assistant", turnId: "t1" }), + message({ id: "a2", role: "assistant", turnId: "t1" }), + message({ id: "a3", role: "assistant", turnId: "t2" }), + ]) } }); + store.getState().ctx.mutateBuffer("ithaca", () => ({ journals: { t1: journal } })); + const messages = store.getState().buffers.ithaca!.messages; + expect(messages.map((m) => m.journal ?? null)).toEqual([null, journal, null]); + expect(messages[1]!.journalLive).toBe(true); + }); + + test("the last-assistant mutator skips a follow-up user message; the holder mutator finds the tool's message", () => { + const store = sliceStore((ctx) => ({ ctx }), { buffers: { ithaca: buffer([ + message({ id: "a1", role: "assistant", toolCalls: [{ id: "tool-1", name: "Read", input: {}, inputJson: "", status: "pending_approval" }] }), + message({ id: "a2", role: "assistant" }), + message({ id: "u1", role: "user" }), + ]) } }); + const { ctx } = store.getState(); + ctx.mutateLastAssistant("ithaca", (m) => ({ ...m, content: "last" }), () => ({ isStreaming: true })); + ctx.mutateToolHolder("ithaca", "tool-1", (m) => ({ ...m, content: "holder" })); + const chat = store.getState().buffers.ithaca!; + expect(chat.messages.map((m) => m.content)).toEqual(["holder", "last", ""]); + expect(chat.isStreaming).toBe(true); + }); + + test("ids are unique within one store", () => { + const { ctx } = sliceStore((c) => ({ ctx: c })).getState(); + expect(ctx.nextId()).not.toBe(ctx.nextId()); + }); + + test("eviction keeps the active and streaming buffers and releases the evicted previews", () => { + const revoked: string[] = []; + Object.defineProperty(URL, "revokeObjectURL", { ...revoke, value: (url: string) => void revoked.push(url) }); + const buffers: Record = {}; + for (let i = 0; i < 10; i++) { + buffers[`s${i}`] = buffer([message({ id: `u${i}`, role: "user", attachments: [{ previewUrl: `blob:s${i}` } as never] })], { lastTouched: i, isStreaming: i === 1 }); + } + const kept = evictStale(buffers, "s0"); + expect(Object.keys(kept).sort()).toEqual(["s0", "s1", "s4", "s5", "s6", "s7", "s8", "s9"]); + expect(revoked).toEqual(["blob:s2", "blob:s3"]); + }); + + test("a retained preview and a non-blob preview are never revoked", () => { + const revoked: string[] = []; + Object.defineProperty(URL, "revokeObjectURL", { ...revoke, value: (url: string) => void revoked.push(url) }); + const shown = message({ id: "u1", role: "user", attachments: [{ previewUrl: "blob:kept" }, { previewUrl: "blob:gone" }, { previewUrl: "data:x" }] as never }); + revokeAttachmentUrls([shown], [message({ id: "u1", role: "user", attachments: [{ previewUrl: "blob:kept" }] as never })]); + expect(revoked).toEqual(["blob:gone"]); + }); +}); + +describe("persistence", () => { + test("a history selection outranks the plain session id and clears it", () => { + const storage = memoryStorage(); + const persistence = createChatPersistence(environment(storage)); + persistence.persistSessionId("ithaca"); + expect(persistence.readPersistedSessionId()).toBe("ithaca"); + persistence.persistSessionId("troy", "penelope"); + expect(persistence.readHistorySelection()).toEqual({ key: "troy", ownerId: "penelope" }); + expect(storage.getItem("odysseus:brain-sessionId")).toBeNull(); + expect(persistence.readPersistedSessionId()).toBe("troy"); + persistence.persistSessionId(null); + expect(persistence.readPersistedSessionId()).toBeNull(); + }); + + test("a corrupt selection grants nothing, and no storage reads as empty", () => { + const storage = memoryStorage(); + storage.setItem("odysseus:brain-history-selection", "{not json"); + expect(createChatPersistence(environment(storage)).readHistorySelection()).toBeNull(); + const none = createChatPersistence(environment(null)); + expect(none.readPersistedSessionId()).toBeNull(); + expect(none.readRetries()).toEqual({}); + expect(none.readStateRoomPreferences()).toEqual({}); + }); + + test("retries persist without refused ones and read back as unknown", () => { + const storage = memoryStorage(); + const persistence = createChatPersistence(environment(storage)); + persistence.persistRetries({ + ithaca: { requestId: "r1", failedTurnId: "t1", state: "waiting" }, + troy: { requestId: "r2", failedTurnId: "t2", state: "refused" }, + }); + expect(Object.keys(JSON.parse(storage.getItem("odysseus:brain-turn-retries")!))).toEqual(["ithaca"]); + expect(persistence.readRetries()).toEqual({ ithaca: { requestId: "r1", failedTurnId: "t1", state: "unknown" } }); + }); + + test("state-room preferences keep only valid fields", () => { + const storage = memoryStorage(); + storage.setItem("odysseus:brain-state-room-preferences", JSON.stringify({ + ithaca: { dismissedAllowance: 4096, invalidatedAt: -1, backendId: "claude", measuredAt: 7 }, + troy: "nope", + })); + expect(createChatPersistence(environment(storage)).readStateRoomPreferences()).toEqual({ + ithaca: { dismissedAllowance: 4096, backendId: "claude", measuredAt: 7 }, + }); + }); +}); + +describe("messages slice", () => { + test("a user send creates the buffer it lands in", () => { + const store = sliceStore(createMessagesSlice); + store.getState().addUserMessage("ithaca", "Which way to Ithaca?", undefined, [{ previewUrl: "blob:map" } as never]); + const [sent] = store.getState().buffers.ithaca!.messages; + expect(sent).toMatchObject({ role: "user", content: "Which way to Ithaca?", source: "typed", attachmentCount: 1 }); + }); + + test("streamed text and thinking merge into chronological parts", () => { + const store = sliceStore(createMessagesSlice, { buffers: { ithaca: emptyChat() } }); + const s = store.getState(); + s.startAssistantMessage("ithaca", "t1", "r1"); + s.appendThinking("ithaca", "Sail "); + s.appendText("ithaca", "West"); + s.appendText("ithaca", " by night"); + const [answer] = store.getState().buffers.ithaca!.messages; + expect(answer).toMatchObject({ turnId: "t1", requestId: "r1", isStreaming: true, content: "West by night", thinking: "Sail " }); + expect(answer!.parts).toEqual([{ kind: "thinking", text: "Sail " }, { kind: "text", text: "West by night" }]); + expect(store.getState().buffers.ithaca!.isStreaming).toBe(true); + }); + + test("a tool call streams, completes and takes its result", () => { + const store = sliceStore(createMessagesSlice, { buffers: { ithaca: emptyChat() } }); + const s = store.getState(); + s.startAssistantMessage("ithaca"); + s.startToolCall("ithaca", "tool-1", "Read"); + s.appendToolInput("ithaca", '{"path":'); + s.appendToolInput("ithaca", '"log.md"}'); + s.completeToolCall("ithaca", "tool-1", "Read", { path: "log.md" }); + s.setToolResult("ithaca", "tool-1", "the log", false); + const [tool] = store.getState().buffers.ithaca!.messages[0]!.toolCalls; + expect(tool).toMatchObject({ id: "tool-1", inputJson: '{"path":"log.md"}', input: { path: "log.md" }, output: "the log", status: "complete" }); + }); + + test("a local exchange is marked wherever it is", () => { + const store = sliceStore(createMessagesSlice, { buffers: { ithaca: buffer([message({ id: "a1", role: "assistant" })]) } }); + store.getState().setLocalExchange("ithaca", { id: "x1", saved: "draft", reason: "offline" } as never); + store.getState().markLocalExchange("x1", "saved" as never); + expect(store.getState().buffers.ithaca!.messages[0]!.localExchange).toEqual({ id: "x1", saved: "saved" } as never); + }); +}); + +describe("streaming slice", () => { + test("finishing ends the message's and the buffer's stream", () => { + const store = sliceStore(createStreamingSlice, { buffers: { ithaca: buffer([message({ id: "a1", role: "assistant", isStreaming: true })], { isStreaming: true }) } }); + store.getState().finishAssistantMessage("ithaca"); + expect(store.getState().buffers.ithaca!.isStreaming).toBe(false); + expect(store.getState().buffers.ithaca!.messages[0]!.isStreaming).toBe(false); + }); + + test("a failure no message owns draws its own message for the turn", () => { + const failure = { code: "overloaded" } as unknown as TurnFailure; + const store = sliceStore(createStreamingSlice, { buffers: { ithaca: buffer([message({ id: "a1", role: "assistant", turnId: "t0" })]) } }); + store.getState().failAssistantMessage("ithaca", failure, "t1"); + const messages = store.getState().buffers.ithaca!.messages; + expect(messages).toHaveLength(2); + expect(messages[1]).toMatchObject({ turnId: "t1", failure, failureLive: true, isStreaming: false }); + }); + + test("blocks without a turn wait for the streaming follow-up to finish", () => { + const store = sliceStore(createStreamingSlice, { buffers: { ithaca: buffer([message({ id: "a1", role: "assistant", isStreaming: true })]) } }); + store.getState().setMessageBlocks("ithaca", [{ kind: "x" } as never]); + expect(store.getState().buffers.ithaca!.messages[0]!.blocks).toBeUndefined(); + }); + + test("promoted links rewrite the turn's text and content", () => { + const store = sliceStore(createStreamingSlice, { buffers: { ithaca: buffer([message({ + id: "a1", role: "assistant", turnId: "t1", content: "See [log](inbox/log.md)", parts: [{ kind: "text", text: "See [log](inbox/log.md)" }], + })]) } }); + store.getState().rewriteMessageLinks("ithaca", [{ from: "inbox/log.md", to: "voyage/log.md" } as MessageLink], "t1"); + expect(store.getState().buffers.ithaca!.messages[0]!.content).toBe("See [log](voyage/log.md)"); + }); + + test("the turn is stamped once on the streaming message", () => { + const store = sliceStore(createStreamingSlice, { buffers: { ithaca: buffer([message({ id: "a1", role: "assistant", isStreaming: true })]) } }); + store.getState().stampTurn("ithaca", "t1"); + store.getState().stampTurn("ithaca", "t2"); + expect(store.getState().buffers.ithaca!.messages[0]!.turnId).toBe("t1"); + }); +}); + +describe("approvals slice", () => { + test("a request on a replay that ended on the user's message draws a turn shell, once", () => { + const store = sliceStore(createApprovalsSlice, { buffers: { ithaca: buffer([message({ id: "u1", role: "user" })]) } }); + store.getState().requestToolApproval("ithaca", "tool-1", "Bash", { command: "ls" }, undefined, undefined, undefined, "t1"); + store.getState().requestToolApproval("ithaca", "tool-1", "Bash", { command: "ls" }, undefined, undefined, undefined, "t1"); + const messages = store.getState().buffers.ithaca!.messages; + expect(messages).toHaveLength(2); + expect(messages[1]).toMatchObject({ turnShell: true, turnId: "t1" }); + expect(messages[1]!.toolCalls).toHaveLength(1); + expect(messages[1]!.toolCalls[0]).toMatchObject({ status: "pending_approval", restored: true, approvalTurnId: "t1" }); + }); + + test("a decision reaches the card, and a restored card closes, reopens and is revoked", () => { + const store = sliceStore(createApprovalsSlice, { buffers: { ithaca: buffer([message({ id: "u1", role: "user" })]) } }); + const s = store.getState(); + s.requestToolApproval("ithaca", "tool-1", "Bash", {}); + s.requestToolApproval("ithaca", "tool-2", "Bash", {}); + s.resolveToolApproval("ithaca", "tool-1", true); + const tools = () => store.getState().buffers.ithaca!.messages.flatMap((m) => m.toolCalls); + expect(tools()[0]!.status).toBe("approved"); + s.closeRestoredApprovals("ithaca", [{ toolUseId: "tool-1", closure: "ended" }, { toolUseId: "tool-2", closure: "unlisted" }]); + expect(tools().map((t) => t.readOnly ?? null)).toEqual([null, "unlisted"]); + s.reopenRestoredApprovals("ithaca", ["tool-2"]); + expect(tools()[1]!.readOnly).toBeUndefined(); + s.revokeRestoredApprovals(); + expect(tools().map((t) => t.readOnly)).toEqual(["revoked", "revoked"]); + expect(tools()[1]!.id.startsWith("revoked-")).toBe(true); + }); +}); + +describe("ask-user slice", () => { + const question = [{ question: "Which island?", header: "Island", options: [], multiSelect: false }] as never; + + test("a re-delivered request updates its card instead of drawing another", () => { + const store = sliceStore(createAskUserSlice, { buffers: { ithaca: buffer([message({ id: "a1", role: "assistant", isStreaming: true })]) } }); + store.getState().setAskUserRequest("ithaca", "q1", question); + store.getState().setAskUserRequest("ithaca", "q1", question, "t1"); + const chat = store.getState().buffers.ithaca!; + expect(chat.messages[0]!.askUserExchanges).toHaveLength(1); + expect(chat.askUser).toMatchObject({ requestId: "q1", turnId: "t1" }); + }); + + test("an answer settles the card, a late request leaves it settled, and reopening clears the answer", () => { + const store = sliceStore(createAskUserSlice, { buffers: { ithaca: buffer([message({ id: "a1", role: "assistant" })]) } }); + const s = store.getState(); + s.setAskUserRequest("ithaca", "q1", question); + s.submitAskUserAnswers("ithaca", "q1", { Island: "Ithaca" }); + s.setAskUserRequest("ithaca", "q1", question); + const exchange = () => store.getState().buffers.ithaca!.messages[0]!.askUserExchanges![0]!; + expect(isSettledExchange(exchange())).toBe(true); + s.reopenAskExchange("ithaca", "q1"); + expect(isSettledExchange(exchange())).toBe(false); + expect(store.getState().buffers.ithaca!.askUser?.requestId).toBe("q1"); + }); + + test("a turn's end closes only its unanswered questions", () => { + const store = sliceStore(createAskUserSlice, { buffers: { ithaca: buffer([message({ id: "a1", role: "assistant" })]) } }); + store.getState().setAskUserRequest("ithaca", "q1", question, "t1"); + store.getState().setAskUserRequest("ithaca", "q2", question, "t2"); + store.getState().endTurnQuestions("ithaca", "t1"); + expect(store.getState().buffers.ithaca!.messages[0]!.askUserExchanges!.map((e) => e.terminal ?? false)).toEqual([true, false]); + }); + + test("deliveries are held per request outside the buffers", () => { + const store = sliceStore(createAskUserSlice); + store.getState().setDelivery("q1", { state: "queued" } as never); + expect(store.getState().deliveries).toEqual({ q1: { state: "queued" } } as never); + store.getState().setDelivery("q1", null); + expect(store.getState().deliveries).toEqual({}); + }); +}); + +describe("transcript slice", () => { + test("history confirms the buffer and ends its restore failure", () => { + const store = sliceStore(createTranscriptSlice, { restoreFailures: { ithaca: { reason: "timeout" } } }); + store.getState().setMessages("ithaca", [message({ id: "u1", role: "user", content: "Hello" })]); + expect(store.getState().buffers.ithaca).toMatchObject({ historyConfirmed: true, messages: [{ id: "u1" }] }); + expect(store.getState().restoreFailures).toEqual({}); + }); + + test("a chunked replay keeps the live answer the first chunk held back", () => { + const live = message({ id: "a1", role: "assistant", content: "Sailing west", parts: [{ kind: "text", text: "Sailing west" }], isStreaming: true, turnId: "t1" }); + const store = sliceStore(createTranscriptSlice, { buffers: { ithaca: buffer([message({ id: "u1", role: "user" }), live], { isStreaming: true }) } }); + store.getState().setMessages("ithaca", [message({ id: "h1", role: "user" })]); + store.getState().appendMessages("ithaca", [message({ id: "h2", role: "assistant", turnId: "t1", content: "Sailing", parts: [{ kind: "text", text: "Sailing" }] })]); + store.getState().finishHistoryReplay("ithaca", true); + const chat = store.getState().buffers.ithaca!; + expect(chat.replay).toBeUndefined(); + expect(chat.messages.at(-1)!.content).toBe("Sailing west"); + }); + + test("history loads are counted per session", () => { + const store = sliceStore(createTranscriptSlice); + store.getState().noteHistoryLoaded("ithaca"); + store.getState().noteHistoryLoaded("ithaca"); + expect(store.getState().historyLoads).toEqual({ ithaca: 2 }); + }); +}); + +describe("session slice", () => { + function sessionStore(storage = memoryStorage()) { + const pinned = provider(); + const newChat = mock(() => {}); + const drafts = createStore(() => ({ newChat })); + const persistence = createChatPersistence(environment(storage)); + const store = sliceStore((ctx) => createSessionSlice(ctx, persistence, pinned.store, drafts)); + return { store, storage, setPinned: pinned.setPinned, newChat }; + } + + test("the stored selection is in view, with its owner and an unconfirmed buffer", () => { + const storage = memoryStorage(); + storage.setItem("odysseus:brain-history-selection", JSON.stringify({ key: "troy", ownerId: "penelope" })); + const { store } = sessionStore(storage); + expect(store.getState()).toMatchObject({ activeSessionId: "troy", historyOwners: { troy: "penelope" } }); + expect(store.getState().buffers.troy?.historyConfirmed).toBeUndefined(); + }); + + test("selecting a session persists it and gives it a buffer", () => { + const { store, storage } = sessionStore(); + store.getState().setActiveSession("ithaca"); + expect(storage.getItem("odysseus:brain-sessionId")).toBe("ithaca"); + expect(store.getState().buffers.ithaca).toBeDefined(); + }); + + test("a new chat sets an unanswered first message aside, unpins the provider and clears the composer", () => { + const { store, setPinned, newChat } = sessionStore(); + const s = store.getState(); + store.setState({ draft: buffer([message({ id: "u1", role: "user" })]) }); + const correlation = s.startDraftTurn(); + s.clearMessages(); + expect(store.getState()).toMatchObject({ draft: null, activeSessionId: null, pendingDraftId: null }); + expect(store.getState().detachedDrafts[correlation]?.messages).toHaveLength(1); + expect(setPinned).toHaveBeenCalledWith(null); + expect(newChat).toHaveBeenCalledTimes(1); + s.bindDetachedDraft(correlation, "ithaca"); + expect(store.getState().buffers.ithaca).toMatchObject({ historyConfirmed: true, messages: [{ id: "u1" }] }); + }); + + test("a bound draft becomes the session in view", () => { + const { store } = sessionStore(); + store.setState({ draft: buffer([message({ id: "u1", role: "user" })]) }); + store.getState().bindDraftSession("ithaca"); + expect(store.getState()).toMatchObject({ activeSessionId: "ithaca", draft: null, buffers: { ithaca: { historyConfirmed: true } } }); + }); + + test("a withdrawn send leaves the transcript", () => { + const { store } = sessionStore(); + store.setState({ buffers: { ithaca: buffer([message({ id: "u1", role: "user", requestId: "r1" }), message({ id: "a1", role: "assistant", requestId: "r1", isStreaming: true })], { isStreaming: true }) } }); + store.getState().withdrawSend("ithaca", "r1"); + expect(store.getState().buffers.ithaca).toMatchObject({ messages: [], isStreaming: false }); + }); + + test("a restore failure is kept until a confirmed buffer outranks it", () => { + const { store } = sessionStore(); + store.getState().failRestore("ithaca", { reason: "timeout" }); + expect(store.getState().restoreFailures).toEqual({ ithaca: { reason: "timeout" } }); + store.getState().clearRestoreFailure("ithaca"); + expect(store.getState().restoreFailures).toEqual({}); + }); +}); + +describe("status slice", () => { + function statusStore(storage = memoryStorage()) { + return { store: sliceStore((ctx) => createStatusSlice(ctx, createChatPersistence(environment(storage)))), storage }; + } + + test("a queue note lives only while the session is queued", () => { + const { store } = statusStore(); + store.getState().setRunState("ithaca", "queued", "Three ahead"); + expect(store.getState()).toMatchObject({ runStates: { ithaca: "queued" }, queueNotes: { ithaca: "Three ahead" } }); + store.getState().setRunState("ithaca", "idle"); + expect(store.getState()).toMatchObject({ runStates: {}, queueNotes: {} }); + }); + + test("an accepted chat receipt is not overwritten", () => { + const { store } = statusStore(); + store.getState().setChatReceipt("r1", "accepted", "ithaca"); + store.getState().setChatReceipt("r1", "refused"); + expect(store.getState().chatReceipts).toEqual({ r1: { state: "accepted", sessionId: "ithaca" } }); + }); + + test("a turn retry is stored and read back by the next store", () => { + const { store, storage } = statusStore(); + store.getState().setTurnRetry("ithaca", { requestId: "r1", failedTurnId: "t1", state: "waiting" }); + expect(statusStore(storage).store.getState().turnRetries).toEqual({ ithaca: { requestId: "r1", failedTurnId: "t1", state: "unknown" } }); + }); + + test("a dismissed state room is remembered against its allowance", () => { + const { store, storage } = statusStore(); + store.getState().setSessionBackend("ithaca", "claude"); + store.getState().setStateRoom("ithaca", { observedAt: 5, allowanceBytes: 4096 } as never); + store.getState().dismissStateRoom("ithaca", 4096); + expect(statusStore(storage).store.getState().stateRoomPreferences).toEqual({ ithaca: { dismissedAllowance: 4096, backendId: "claude", measuredAt: 5 } }); + }); + + test("each composer insert is a new request, and only its own seq clears it", () => { + const { store } = statusStore(); + store.getState().requestComposerInsert("Ask about Ithaca"); + const first = store.getState().composerInsert!.seq; + store.getState().requestComposerInsert("Ask about Ithaca"); + store.getState().clearComposerInsert(first); + expect(store.getState().composerInsert).toEqual({ seq: first + 1, text: "Ask about Ithaca" }); + }); +}); + +describe("composition", () => { + test("the slices own disjoint keys that make up the whole store", () => { + const ctx = createChatSliceContext(() => {}, () => ({}) as ChatState); + const persistence = createChatPersistence(environment()); + const slices = { + status: createStatusSlice(ctx, persistence), + session: createSessionSlice(ctx, persistence, provider().store), + messages: createMessagesSlice(ctx), + approvals: createApprovalsSlice(ctx), + askUser: createAskUserSlice(ctx), + streaming: createStreamingSlice(ctx), + transcript: createTranscriptSlice(ctx), + }; + const owners = new Map(); + for (const [name, slice] of Object.entries(slices)) for (const key of Object.keys(slice)) owners.set(key, [...(owners.get(key) ?? []), name]); + expect([...owners].filter(([, names]) => names.length > 1)).toEqual([]); + const store = createChatStore(environment(), provider().store); + expect([...owners.keys()].sort()).toEqual(Object.keys(store.getState()).sort()); + }); +});