@arbidocs/react 0.5.74 → 0.5.75

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +5 -0
  2. package/dist/artifacts/index.cjs +9 -9
  3. package/dist/artifacts/index.js +3 -3
  4. package/dist/calls/livekit/index.cjs +48 -48
  5. package/dist/calls/livekit/index.js +3 -3
  6. package/dist/{chunk-6PNLCGMJ.js → chunk-2MECTZLS.js} +9 -5
  7. package/dist/chunk-2MECTZLS.js.map +1 -0
  8. package/dist/{chunk-R7YNABZY.js → chunk-2Y6LJNWA.js} +2 -2
  9. package/dist/{chunk-R7YNABZY.js.map → chunk-2Y6LJNWA.js.map} +1 -1
  10. package/dist/{chunk-YWU7HEHL.js → chunk-33PVGKXT.js} +78 -4
  11. package/dist/chunk-33PVGKXT.js.map +1 -0
  12. package/dist/{chunk-Y7S2SQH3.cjs → chunk-5YGUBXXH.cjs} +2 -2
  13. package/dist/{chunk-Y7S2SQH3.cjs.map → chunk-5YGUBXXH.cjs.map} +1 -1
  14. package/dist/{chunk-BF7ABX3X.cjs → chunk-6RSVGLQY.cjs} +106 -31
  15. package/dist/chunk-6RSVGLQY.cjs.map +1 -0
  16. package/dist/{chunk-2LV53J46.js → chunk-JHN4PKWX.js} +3 -3
  17. package/dist/{chunk-2LV53J46.js.map → chunk-JHN4PKWX.js.map} +1 -1
  18. package/dist/{chunk-ZTPJNKF2.js → chunk-LC276BI7.js} +5 -5
  19. package/dist/chunk-LC276BI7.js.map +1 -0
  20. package/dist/{chunk-GOJHU7RZ.cjs → chunk-MWW54PY6.cjs} +25 -25
  21. package/dist/{chunk-GOJHU7RZ.cjs.map → chunk-MWW54PY6.cjs.map} +1 -1
  22. package/dist/{chunk-4DTTEUVY.js → chunk-O2HDONQE.js} +4 -4
  23. package/dist/{chunk-4DTTEUVY.js.map → chunk-O2HDONQE.js.map} +1 -1
  24. package/dist/{chunk-SI7DJWBT.js → chunk-OR6B7IL2.js} +3 -3
  25. package/dist/{chunk-SI7DJWBT.js.map → chunk-OR6B7IL2.js.map} +1 -1
  26. package/dist/{chunk-LMW46NBD.cjs → chunk-OY4PYCJH.cjs} +5 -5
  27. package/dist/chunk-OY4PYCJH.cjs.map +1 -0
  28. package/dist/{chunk-C5SVEWPU.cjs → chunk-PMHFLOXY.cjs} +27 -22
  29. package/dist/chunk-PMHFLOXY.cjs.map +1 -0
  30. package/dist/{chunk-TGSEQGM3.cjs → chunk-QEVM3F5X.cjs} +4 -4
  31. package/dist/{chunk-TGSEQGM3.cjs.map → chunk-QEVM3F5X.cjs.map} +1 -1
  32. package/dist/{chunk-ZNQPUPX6.cjs → chunk-RDERZWMO.cjs} +16 -16
  33. package/dist/{chunk-ZNQPUPX6.cjs.map → chunk-RDERZWMO.cjs.map} +1 -1
  34. package/dist/document-tools/core.cjs +99 -99
  35. package/dist/document-tools/core.js +3 -3
  36. package/dist/document-tools/index.cjs +101 -101
  37. package/dist/document-tools/index.js +4 -4
  38. package/dist/index.cjs +992 -896
  39. package/dist/index.cjs.map +1 -1
  40. package/dist/index.d.cts +59 -12
  41. package/dist/index.d.ts +59 -12
  42. package/dist/index.js +117 -31
  43. package/dist/index.js.map +1 -1
  44. package/dist/shell/index.cjs +32 -32
  45. package/dist/shell/index.js +1 -1
  46. package/dist/viewers/index.cjs +2 -2
  47. package/dist/viewers/index.js +1 -1
  48. package/package.json +3 -3
  49. package/dist/chunk-6PNLCGMJ.js.map +0 -1
  50. package/dist/chunk-BF7ABX3X.cjs.map +0 -1
  51. package/dist/chunk-C5SVEWPU.cjs.map +0 -1
  52. package/dist/chunk-LMW46NBD.cjs.map +0 -1
  53. package/dist/chunk-YWU7HEHL.js.map +0 -1
  54. package/dist/chunk-ZTPJNKF2.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/chat/run-state.ts","../src/session/thread-tabs.ts","../src/session/chat.ts","../src/session/layout.ts","../src/session/workspace.ts","../src/session/store.ts","../src/session/drafts.ts","../src/session/session-hooks.ts","../src/session/signed-in.ts","../src/session/persist.ts","../src/usage-metered.ts","../src/hooks.ts"],"names":["threads","isRecord","stringOrNull","recordOf","isString","parseVersionRef","getUserEncryptionKeypair","sealedBoxEncrypt","sealedBoxDecrypt","useArbiHost","OWN_SESSION_SLOT","useSyncExternalStore","useCallback","useMemo","useArbi","useQuery","arbiQueryKeys","useMutation","useQueryClient","useInfiniteQuery","useQueries","useRef","useEffect"],"mappings":";;;;;;;;;;;AAkCO,IAAM,gCAAA,GAAmC;AAEhD,IAAM,SAAA,GAAY,CAChB,MAAA,EACA,MAAA,KAEA,OAAO,WAAA,CAAY,MAAA,CAAO,OAAA,CAAQ,MAAM,CAAA,CAAE,GAAA,CAAI,CAAC,CAAC,EAAA,EAAI,QAAQ,CAAA,KAAM,CAAC,IAAI,MAAA,CAAO,QAAQ,CAAC,CAAC,CAAC,CAAA;AAW3F,SAAS,oBAAA,CACP,UACA,eAAA,EACa;AACb,EAAA,MAAM,IAAA,GAAO,gBAAgB,IAAA,EAAK;AAClC,EAAA,MAAM,KAAA,uBAAY,GAAA,EAAY;AAC9B,EAAA,IAAI,MAAA,GAAS,CAAA;AACb,EAAA,KAAA,MAAW,WAAW,QAAA,EAAU;AAC9B,IAAA,IAAI,MAAA,IAAU,KAAK,MAAA,EAAQ;AAC3B,IAAA,MAAM,OAAA,GAAU,OAAA,CAAQ,OAAA,CAAQ,IAAA,EAAK;AACrC,IAAA,IAAI,CAAC,OAAA,EAAS;AACd,IAAA,MAAM,SAAA,GAAY,MAAA,KAAW,CAAA,GAAI,EAAA,GAAK,MAAA;AACtC,IAAA,IAAI,IAAA,CAAK,UAAA,CAAW,SAAA,GAAY,OAAA,EAAS,MAAM,CAAA,EAAG;AAChD,MAAA,KAAA,CAAM,GAAA,CAAI,QAAQ,QAAQ,CAAA;AAC1B,MAAA,MAAA,IAAU,SAAA,CAAU,SAAS,OAAA,CAAQ,MAAA;AAAA,IACvC;AAAA,EACF;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CAAK,SAAA,EAAW,CAAA;AACtE,EAAA,MAAM,UAAA,GAAa,YAAY,GAAA,CAAI,CAAC,MAAM,CAAA,CAAE,WAAW,CAAA,CAAE,IAAA,CAAK,GAAG,CAAA;AACjE,EAAA,MAAM,EAAE,SAAQ,GAAI,IAAA;AACpB,EAAA,MAAM,IAAA,GAAOK,aAA2B,MAAS,CAAA;AACjD,EAAAC,eAAA,CAAU,MAAM;AACd,IAAA,IAAI,UAAA,KAAe,MAAA,IAAa,UAAA,KAAe,IAAA,CAAK,OAAA,EAAS;AAC7D,IAAA,MAAM,KAAA,GAAQ,KAAK,OAAA,KAAY,MAAA;AAC/B,IAAA,IAAA,CAAK,OAAA,GAAU,UAAA;AACf,IAAA,IAAI,CAAC,KAAA,EAAO,KAAK,OAAA,EAAQ;AAAA,EAC3B,CAAA,EAAG,CAAC,UAAA,EAAY,OAAO,CAAC,CAAA;AACxB,EAAA,OAAO,KAAK,IAAA,EAAM,mBAAA;AACpB;AAOO,SAAS,kBAAkB,OAAA,EAAiC;AACjE,EAAA,MAAM,OAAOR,yBAAA,EAAQ;AACrB,EAAA,OAAOC,mBAAA,CAAS;AAAA,IACd,QAAA,EAAUC,gCAAc,cAAA,EAAe;AAAA,IACvC,OAAA,EAAS,MAAM,IAAA,CAAK,IAAA,CAAK,UAAA,EAAW;AAAA,IACpC,OAAA,EAAA,CAAU,OAAA,EAAS,OAAA,IAAW,IAAA,KAAS,IAAA,CAAK,UAAA;AAAA,IAC5C,oBAAA,EAAsB,IAAA;AAAA,IACtB,cAAA,EAAgB,QAAA;AAAA,IAChB,SAAA,EAAW;AAAA,GACZ,CAAA;AACH","file":"chunk-BF7ABX3X.cjs","sourcesContent":["/**\n * The live state of a running turn that is not in the threads cache: follow-ups waiting in the\n * agent bar's queue box, and the run-control state (pause / resume / report). Both are keyed by the\n * streaming answer's id (the response id) and live in the session (`ArbiSessionState`); these are\n * the pure updates every session store applies.\n */\n\nimport type { ProbeAnswerEvent } from '@arbidocs/sdk/browser'\n\n/** A follow-up the person sent while a turn ran, shown in the agent bar until it is its own turn. */\nexport interface QueuedMessage {\n /** The client's own id, unique across turns. */\n clientId: string\n content: string\n /** The stored user message, once the server confirmed the follow-up. */\n serverId: string | null\n acknowledged: boolean\n /** When it was queued (epoch ms): a follow-up stays readable for a moment. */\n createdAt: number\n}\n\n/** Queued follow-ups per running answer (response id). */\nexport type QueuedMessages = Readonly<Record<string, readonly QueuedMessage[]>>\n\n/**\n * Control state of a running agent turn:\n * - `running` normal streaming.\n * - `pausing` the person sent /pause; awaiting the server's confirmed halt (optimistic).\n * - `paused` the server confirmed the loop halted at a boundary.\n * - `resuming` the person sent /resume; awaiting the stream to flow again (optimistic).\n */\nexport type AgentRunControlState = 'running' | 'pausing' | 'paused' | 'resuming'\n\n/** How long a confirmed follow-up stays in the queue box at least, so it can be read. */\nexport const MIN_QUEUED_MESSAGE_VISIBILITY_MS = 800\n\nconst mapQueues = (\n queues: QueuedMessages,\n update: (messages: readonly QueuedMessage[]) => QueuedMessage[]\n): QueuedMessages =>\n Object.fromEntries(Object.entries(queues).map(([id, messages]) => [id, update(messages)]))\n\n/**\n * The client ids of the queued prompts a steering interjection delivered.\n *\n * The backend joins every prompt it steers into one run with a blank line, in the order they were\n * sent. Prompts the backend queued as turns of their own stay in the queue between them, so the\n * steered ones need not be first, or even adjacent: walk the queue in order and take each prompt\n * that is the next part of the delivered text. Nothing is taken unless the whole text is accounted\n * for.\n */\nfunction findConsumedMessages(\n messages: readonly QueuedMessage[],\n combinedContent: string\n): Set<string> {\n const text = combinedContent.trim()\n const taken = new Set<string>()\n let cursor = 0\n for (const message of messages) {\n if (cursor >= text.length) break\n const content = message.content.trim()\n if (!content) continue\n const separator = cursor === 0 ? '' : '\\n\\n'\n if (text.startsWith(separator + content, cursor)) {\n taken.add(message.clientId)\n cursor += separator.length + content.length\n }\n }\n return cursor === text.length ? taken : new Set()\n}\n\n/** The queue updates. Client ids are unique, so the per-entry ones find it under any turn. */\nexport const queuedMessages = {\n add: (q: QueuedMessages, responseId: string, message: QueuedMessage): QueuedMessages => ({\n ...q,\n [responseId]: [...(q[responseId] ?? []), message],\n }),\n acknowledge: (q: QueuedMessages, clientId: string, serverId: string | null): QueuedMessages =>\n mapQueues(q, (messages) =>\n messages.map((m) => (m.clientId === clientId ? { ...m, serverId, acknowledged: true } : m))\n ),\n remove: (q: QueuedMessages, clientId: string): QueuedMessages =>\n mapQueues(q, (messages) => messages.filter((m) => m.clientId !== clientId)),\n removeByServerId: (q: QueuedMessages, serverId: string): QueuedMessages =>\n mapQueues(q, (messages) => messages.filter((m) => m.serverId !== serverId)),\n removeByContent: (q: QueuedMessages, responseId: string, content: string): QueuedMessages => {\n let removed = false\n return {\n ...q,\n [responseId]: (q[responseId] ?? []).filter((m) => {\n if (!removed && m.content === content) {\n removed = true\n return false\n }\n return true\n }),\n }\n },\n /** Take out the prompts a steering interjection delivered into the run. */\n consume: (q: QueuedMessages, responseId: string, combinedContent: string): QueuedMessages => {\n const messages = q[responseId] ?? []\n const consumed = findConsumedMessages(messages, combinedContent)\n return { ...q, [responseId]: messages.filter((m) => !consumed.has(m.clientId)) }\n },\n clear: (q: QueuedMessages, responseId: string): QueuedMessages => ({ ...q, [responseId]: [] }),\n /** Move the entries still waiting on a finished turn to the turn that is now running. */\n move: (q: QueuedMessages, fromResponseId: string, toResponseId: string): QueuedMessages => {\n const waiting = q[fromResponseId] ?? []\n if (fromResponseId === toResponseId || waiting.length === 0) return q\n return { ...q, [fromResponseId]: [], [toResponseId]: [...(q[toResponseId] ?? []), ...waiting] }\n },\n /** Find a queued follow-up by its client id, under whichever turn holds it. */\n find: (q: QueuedMessages, clientId: string): QueuedMessage | undefined =>\n Object.values(q)\n .flat()\n .find((m) => m.clientId === clientId),\n}\n\n/** The transient control state of the running turns, per response id. */\nexport interface AgentControlMaps {\n agentControlStates: Readonly<Record<string, AgentRunControlState>>\n agentProbeAnswers: Readonly<Record<string, ProbeAnswerEvent>>\n agentProbePending: Readonly<Record<string, boolean>>\n}\n\nconst without = <T>(record: Readonly<Record<string, T>>, key: string): Record<string, T> => {\n const next = { ...record }\n delete next[key]\n return next\n}\n\n/** The control updates. */\nexport const agentControl = {\n setState: (c: AgentControlMaps, id: string, state: AgentRunControlState): AgentControlMaps => ({\n ...c,\n agentControlStates: { ...c.agentControlStates, [id]: state },\n }),\n /** A probe answered: the latest answer, and nothing pending any more. */\n setProbeAnswer: (c: AgentControlMaps, id: string, probe: ProbeAnswerEvent): AgentControlMaps => ({\n ...c,\n agentProbeAnswers: { ...c.agentProbeAnswers, [id]: probe },\n agentProbePending: { ...c.agentProbePending, [id]: false },\n }),\n setProbePending: (c: AgentControlMaps, id: string, pending: boolean): AgentControlMaps => ({\n ...c,\n agentProbePending: { ...c.agentProbePending, [id]: pending },\n }),\n /** The turn is over: drop its control state. */\n clear: (c: AgentControlMaps, id: string): AgentControlMaps => ({\n agentControlStates: without(c.agentControlStates, id),\n agentProbeAnswers: without(c.agentProbeAnswers, id),\n agentProbePending: without(c.agentProbePending, id),\n }),\n}\n","/**\n * The thread tabs: the conversations open in the Threads page (`ConnectedThreadTabs` shows them),\n * each with the composer it was left with, so switching back finds its line, its edit, its model and\n * its scroll position (its draft is the chat state's, kept per conversation: `ArbiChatState.drafts`).\n * They are part of the layout's `tabs` and kept across reloads (without what was typed: a host keeps\n * drafts sealed, `ArbiDraftStorage`).\n *\n * The changes here are pure: each takes the tabs and the composer being left, and says what the\n * composer shows next, so a session store (the in-memory one, or a host's adapter over its own\n * composer state) applies them to whatever holds the composer.\n */\n\n/** The composer a thread tab was left with. */\nexport interface ArbiThreadTabView {\n /** The message the conversation continued from (its line). */\n cursor: string | null\n /** The question being edited, or null. */\n editingMessageId: string | null\n /** The draft the edit put aside (in memory only; never in the saved layout). */\n preEditDraft: string | null\n /** The line the edit put aside. */\n preEditCursor: string | null\n /** The config (model) chosen for the conversation. */\n chatModel: string | undefined\n /** The model name its picker showed. */\n chatModelName: string | undefined\n /** Where its messages were scrolled to (null: at the latest). */\n scrollTop: number | null\n}\n\n/** A thread tab: a conversation's, or a new chat's (`conversationId` null). */\nexport interface ArbiThreadTab {\n conversationId: string | null\n /** The composer it was left with; absent until it is left. */\n view?: ArbiThreadTabView\n}\n\n/** A thread tab's id: its conversation's id, or `new` for a new chat. */\nexport const threadTabId = (tab: ArbiThreadTab): string => tab.conversationId ?? 'new'\n\n/** The most thread tabs kept (opening one more closes the oldest one not on screen). */\nexport const MAX_THREAD_TABS = 12\n\nexport interface ArbiThreadTabsState {\n /** The open thread tabs, in the order they were opened. */\n threads: readonly ArbiThreadTab[]\n /** The tab on screen (`threadTabId`), or null while the thread list is. */\n activeThread: string | null\n /** The scroll position a tab switch brought back, until the thread view takes it. */\n threadScrollRestore: number | null\n}\n\n/** The open conversation and the composer it had (what a tab left is saved with). */\nexport interface ArbiThreadComposer {\n conversationId: string | null\n view: ArbiThreadTabView\n}\n\n/**\n * What a change shows: a conversation in its tab, with the composer it comes back with (undefined:\n * a fresh one, at its latest message); `list`: the thread list, no conversation open; null: the\n * composer stays as it is.\n */\nexport type ArbiThreadTabShow =\n { conversationId: string | null; view: ArbiThreadTabView | undefined } | 'list' | null\n\nexport interface ArbiThreadTabsChange {\n tabs: ArbiThreadTabsState\n show: ArbiThreadTabShow\n}\n\nconst withView = (\n threads: readonly ArbiThreadTab[],\n tabId: string | null,\n view: ArbiThreadTabView\n): ArbiThreadTab[] =>\n threads.map((tab) => (tabId !== null && threadTabId(tab) === tabId ? { ...tab, view } : tab))\n\n/** Show an open tab, saving the composer being left into the tab on screen. */\nexport function selectThreadTabIn(\n tabs: ArbiThreadTabsState,\n tabId: string,\n leaving: ArbiThreadComposer\n): ArbiThreadTabsChange {\n const target = tabs.threads.find((tab) => threadTabId(tab) === tabId)\n if (!target) return { tabs, show: null }\n const isActive = tabs.activeThread === tabId\n // An active tab showing its own conversation is already there. One whose conversation was cleared\n // under it (an earlier build saved that) is opened again, not left as a title over an empty chat.\n if (isActive && leaving.conversationId === target.conversationId) return { tabs, show: null }\n return {\n tabs: {\n ...tabs,\n // Re-opening the active tab saves nothing: its live composer is the cleared one.\n threads: isActive ? tabs.threads : withView(tabs.threads, tabs.activeThread, leaving.view),\n activeThread: tabId,\n threadScrollRestore: target.view?.scrollTop ?? null,\n },\n show: { conversationId: target.conversationId, view: target.view },\n }\n}\n\n/**\n * Open a conversation in its tab (null: a new chat). An open tab is shown at its latest message; a\n * new chat's lone tab is replaced by a conversation's; otherwise a tab is added at the end (the\n * oldest one not on screen closes past {@link MAX_THREAD_TABS}).\n */\nexport function openThreadTabIn(\n tabs: ArbiThreadTabsState,\n conversationId: string | null,\n leaving: ArbiThreadComposer\n): ArbiThreadTabsChange & { tabId: string } {\n const tabId = conversationId ?? 'new'\n const existing = tabs.threads.find((tab) => threadTabId(tab) === tabId)\n if (existing) {\n // Opening a thread lands on its latest message, as from the list, not where it was left.\n const threads = tabs.threads.map((tab) =>\n threadTabId(tab) === tabId && tab.view\n ? { ...tab, view: { ...tab.view, scrollTop: null, cursor: null } }\n : tab\n )\n return { tabId, ...selectThreadTabIn({ ...tabs, threads }, tabId, leaving) }\n }\n const fresh = { conversationId, view: undefined }\n const onlyNewChat = tabs.threads.length === 1 && tabs.threads[0].conversationId === null\n if (conversationId && onlyNewChat)\n return {\n tabId,\n tabs: { ...tabs, threads: [{ conversationId }], activeThread: tabId },\n show: fresh,\n }\n let threads = [...withView(tabs.threads, tabs.activeThread, leaving.view), { conversationId }]\n if (threads.length > MAX_THREAD_TABS) {\n // The new tab (last) stays; the first other one not on screen closes.\n const evict = threads.findIndex(\n (tab, i) => i < threads.length - 1 && threadTabId(tab) !== tabs.activeThread\n )\n if (evict !== -1) threads = threads.filter((_, i) => i !== evict)\n }\n return { tabId, tabs: { ...tabs, threads, activeThread: tabId }, show: fresh }\n}\n\n/** Close a tab; closing the one on screen shows the one beside it, the last one the list. */\nexport function closeThreadTabIn(tabs: ArbiThreadTabsState, tabId: string): ArbiThreadTabsChange {\n const threads = tabs.threads.filter((tab) => threadTabId(tab) !== tabId)\n if (threads.length === 0)\n return { tabs: { ...tabs, threads: [], activeThread: null }, show: 'list' }\n if (tabs.activeThread !== tabId) return { tabs: { ...tabs, threads }, show: null }\n const index = tabs.threads.findIndex((tab) => threadTabId(tab) === tabId)\n const next = threads[Math.min(index, threads.length - 1)]\n return {\n tabs: { ...tabs, threads, activeThread: threadTabId(next) },\n show: { conversationId: next.conversationId, view: next.view },\n }\n}\n\n/**\n * Show the thread list; the tabs stay open (the one left keeps its composer). A thread opened from\n * the list is a fresh start: it opens at its latest message, not at a stale scroll position.\n */\nexport function showThreadListIn(\n tabs: ArbiThreadTabsState,\n leaving: ArbiThreadComposer\n): ArbiThreadTabsState {\n return {\n ...tabs,\n activeThread: null,\n threads: tabs.threads.map((tab) =>\n threadTabId(tab) === tabs.activeThread\n ? { ...tab, view: { ...leaving.view, scrollTop: null } }\n : tab.view\n ? { ...tab, view: { ...tab.view, scrollTop: null } }\n : tab\n ),\n }\n}\n\n/**\n * A conversation's tab is now `toId`'s (a new chat got its id): the tab named `fromId`, wherever it\n * is and whether or not it is on screen. When `toId` already has a tab, that one stays.\n */\nexport function renameThreadTabIn(\n tabs: ArbiThreadTabsState,\n fromId: string,\n toId: string\n): ArbiThreadTabsState {\n if (fromId === toId || !tabs.threads.some((tab) => threadTabId(tab) === fromId)) return tabs\n const taken = tabs.threads.some((tab) => threadTabId(tab) === toId)\n return {\n ...tabs,\n activeThread: tabs.activeThread === fromId ? toId : tabs.activeThread,\n threads: taken\n ? tabs.threads.filter((tab) => threadTabId(tab) !== fromId)\n : tabs.threads.map((tab) =>\n threadTabId(tab) === fromId ? { ...tab, conversationId: toId } : tab\n ),\n }\n}\n\n// ── Saving ──────────────────────────────────────────────────────────────────────────────────────\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\nconst stringOrNull = (v: unknown): string | null => (typeof v === 'string' ? v : null)\nconst stringOrUndefined = (v: unknown): string | undefined =>\n typeof v === 'string' ? v : undefined\n\n/** A saved tab's composer as this build reads it (never with typed text). */\nfunction parseView(value: unknown): ArbiThreadTabView | undefined {\n if (!isRecord(value)) return undefined\n return {\n cursor: stringOrNull(value.cursor),\n editingMessageId: stringOrNull(value.editingMessageId),\n preEditDraft: null,\n preEditCursor: stringOrNull(value.preEditCursor),\n chatModel: stringOrUndefined(value.chatModel),\n chatModelName: stringOrUndefined(value.chatModelName),\n scrollTop:\n typeof value.scrollTop === 'number' && Number.isFinite(value.scrollTop)\n ? value.scrollTop\n : null,\n }\n}\n\n/**\n * Saved thread tabs as this build reads them: unreadable entries are dropped, and no tab is on\n * screen when the one named is not open. Never throws.\n */\nexport function parseSavedThreadTabs(\n threads: unknown,\n activeThread: unknown\n): Pick<ArbiThreadTabsState, 'threads' | 'activeThread'> {\n const tabs: ArbiThreadTab[] = []\n for (const entry of Array.isArray(threads) ? threads : []) {\n if (!isRecord(entry)) continue\n const { conversationId } = entry\n if (conversationId !== null && typeof conversationId !== 'string') continue\n const view = parseView(entry.view)\n const tab: ArbiThreadTab = view ? { conversationId, view } : { conversationId }\n // One tab per conversation.\n if (!tabs.some((t) => threadTabId(t) === threadTabId(tab))) tabs.push(tab)\n }\n const active = typeof activeThread === 'string' ? activeThread : null\n return {\n threads: tabs,\n activeThread: active && tabs.some((tab) => threadTabId(tab) === active) ? active : null,\n }\n}\n\n/** The tabs as saved: without what was typed. */\nexport const savedThreadTabs = (threads: readonly ArbiThreadTab[]): ArbiThreadTab[] =>\n threads.map((tab) => (tab.view ? { ...tab, view: { ...tab.view, preEditDraft: null } } : tab))\n","/**\n * The session's chat state: the open conversation and its composer (line, draft, edit, model), the\n * turns running in each conversation, the documents and facts in each conversation's context, and\n * the agent bar's queue and run control. One implementation for every host: the in-memory session\n * store is built on it, and so is ARBI-frontend's (which keeps it across reloads).\n *\n * The open composer and the thread tabs move together: a thread tab change (`openThreadTab` and the\n * like) is the layout's (`layout.threads`) applied here, and readers are told once, after both have\n * moved ({@link ArbiChatStore.batch}), so none sees a tab over another tab's conversation.\n *\n * Kept across reloads (with a `persist`): the open conversation and its line, the context documents\n * and facts, each agent chat's agent and the chosen model. The drafts are kept apart, sealed to the\n * person ({@link ArbiDraftStorage}); everything else lives for the visit.\n */\n\nimport type { components } from '@arbidocs/client'\nimport type { ProbeAnswerEvent } from '@arbidocs/sdk/browser'\nimport {\n agentControl,\n queuedMessages,\n type AgentControlMaps,\n type AgentRunControlState,\n type QueuedMessage,\n type QueuedMessages,\n} from '../chat/run-state'\nimport type { ArbiDraftStorage } from './drafts'\nimport type { ArbiLayoutStore } from './layout'\nimport type { ArbiSessionPersist } from './persist'\nimport { threadTabId, type ArbiThreadComposer, type ArbiThreadTabShow } from './thread-tabs'\n\n/** Generation in one conversation. */\nexport interface ArbiConversationGeneration {\n isGenerating: boolean\n error: string | null\n /** When the running turn started (epoch ms), once the server named its answer. */\n startTime: number | null\n /** The answer being streamed (its response id), once the server named it. */\n streamingAssistantId?: string | null\n /** The server's elapsed time for the running turn (seconds). */\n backendElapsed?: number | null\n /** The question of a send that failed, for Retry. */\n lastFailedMessage?: string | null\n /** The local stream of the running turn, which Stop aborts (absent for an attached run). */\n abortController?: AbortController | null\n}\n\n/** A document in a conversation's context; a pinned one stays there across turns. */\nexport interface ArbiConversationDocument {\n docId: string\n isPinned: boolean\n}\n\n/** An answer's timer: when its run started (epoch ms) and how long it took (seconds). */\nexport interface ArbiMessageTimer {\n startTime: number\n elapsedTime: number\n}\n\n/** A send's structured tools (`MessageInput.tools`). */\nexport type TurnTools = components['schemas']['MessageInput']['tools']\n\nexport interface ArbiChatState extends AgentControlMaps {\n /** The open conversation, or null for a new one / none. */\n conversationId: string | null\n /** Generation state per conversation id. */\n generating: Readonly<Record<string, ArbiConversationGeneration>>\n /** Personal Assistant mode for new conversations. */\n paMode: boolean\n /** The documents in each conversation's context, per conversation id. */\n conversationDocuments: Readonly<Record<string, readonly ArbiConversationDocument[]>>\n /**\n * Per conversation id: true while an empty chat follows the workspace's documents (set by\n * `useDocumentAutoAdd`); any other change of its documents is a choice and turns it off.\n * Missing for a selection made before this was recorded.\n */\n conversationDocumentAutoAdd: Readonly<Record<string, boolean>>\n /** The facts in each conversation's context, per conversation id (`new` for a new chat). */\n conversationFacts: Readonly<Record<string, readonly string[]>>\n /** The message the open conversation continues from: the leaf of the line being viewed. */\n cursor: string | null\n /** A follow-up the backend suggested for a conversation, offered in its composer. */\n suggestedQuery: { conversationExtId: string; text: string } | null\n /** Follow-ups waiting in a running turn's agent bar, per response id. */\n queuedMessages: QueuedMessages\n /**\n * What is typed in each composer, per conversation id (`new` for a new chat): the open one's\n * (`selectDraft`) and each open thread tab's. A host may keep them across reloads, stored locally\n * and encrypted ({@link ArbiDraftStorage}).\n */\n drafts: Readonly<Record<string, string>>\n /** The question being edited in the open conversation (sent as a new branch), or null. */\n editingMessageId: string | null\n /** A message a link opened the conversation at: its thread opens and the view goes to it. */\n deepLinkMessageId: string | null\n /** The citation whose sources are open (`<message id>-<citation number>`), or null. */\n activeCitationKey: string | null\n /** The config (model) chosen for the open conversation; absent: the person's last one. */\n chatModel: string | undefined\n /** The model name the open conversation's picker shows (an edit or a launch sets it). */\n chatModelName: string | undefined\n /** The mode a new conversation starts in: `always` answers, `mentioned` only when @mentioned. */\n newConversationAssistantMode: 'always' | 'mentioned'\n /** Structured tools a launch wants on the next send (the send consumes them). */\n pendingTools: TurnTools | null\n /**\n * Send the open composer's draft as soon as the conversation is ready (a launch that composed it);\n * the send clears it.\n */\n autoSendDraft: boolean\n /** The owned agent each agent chat runs through, per conversation id. */\n agentChatOwners: Readonly<Record<string, string>>\n /** A new agent chat about to start: its agent and workspace. */\n newAgentChat: { agentId: string; workspaceId: string } | null\n /**\n * The document a new chat about to start is bound to (`doc-…`): set only by starting a chat from\n * a document (\"Chat about this document\") or attaching it in the new chat, never by a document\n * merely being open. Starting another new chat clears it; the first turn moves it to the\n * conversation (`chat/thread-document`).\n */\n newChatDocumentId: string | null\n /** Each answer's timer, saved when it stops showing (`<conversation id>:<message id>`). */\n messageTimers: Readonly<Record<string, ArbiMessageTimer>>\n}\n\n/** The chat's changes: every session store has them (`ArbiSessionStore`). */\nexport interface ArbiChatActions {\n /** Open a conversation in its thread tab (null: a new chat), as `openThreadTab`. */\n setConversationId(id: string | null): void\n /** Start or end a conversation's turn; `abortController` is its local stream, which Stop aborts. */\n setConversationGenerating(\n conversationId: string,\n isGenerating: boolean,\n abortController?: AbortController | null\n ): void\n setPaMode(enabled: boolean): void\n /** Set a conversation's documents; `autoAdd` marks an automatic pick (default: the user's). */\n setConversationDocuments(\n conversationId: string,\n documents: ArbiConversationDocument[],\n autoAdd?: boolean\n ): void\n setConversationFacts(conversationId: string, factIds: string[]): void\n /** The answer a conversation is streaming; `startTime` defaults to now (a re-attach passes the run's). */\n setStreamingAssistantId(conversationId: string, assistantId: string, startTime?: number): void\n setBackendElapsed(conversationId: string, seconds: number): void\n /**\n * A new chat got its server id: its generation, documents, facts, draft and tab move from\n * `fromId` (`new`) to `toId`, and it stays the open conversation.\n */\n moveConversation(fromId: string, toId: string): void\n setCursor(messageId: string | null): void\n setSuggestedQuery(suggestion: ArbiChatState['suggestedQuery']): void\n addQueuedMessage(responseId: string, message: QueuedMessage): void\n acknowledgeQueuedMessage(clientId: string, serverId: string | null): void\n removeQueuedMessage(clientId: string): void\n removeQueuedMessageByServerId(serverId: string): void\n consumeQueuedMessage(responseId: string, combinedContent: string): void\n clearQueuedMessages(responseId: string): void\n moveQueuedMessages(fromResponseId: string, toResponseId: string): void\n setAgentControlState(responseId: string, state: AgentRunControlState): void\n setAgentProbeAnswer(responseId: string, probe: ProbeAnswerEvent): void\n setAgentProbePending(responseId: string, pending: boolean): void\n clearAgentControl(responseId: string): void\n /** Set what is typed in the open conversation's composer. */\n setDraft(text: string): void\n /** The config (model) the open conversation's turns use; undefined: the person's last one. */\n setChatModel(model: string | undefined): void\n setChatModelName(model: string | undefined): void\n /**\n * Show a conversation in its thread tab (null: a new chat) at its latest message, opening the tab\n * when it is not open (`tabs.threads`); it is also the Threads page's tab. Returns the tab's id.\n */\n openThreadTab(conversationId: string | null): string\n /** Close a thread tab; closing the one on screen shows the one beside it, else the thread list. */\n closeThreadTab(tabId: string): void\n /**\n * Show a thread tab's conversation with the composer it was left with, or (null) the thread list;\n * the tabs stay open.\n */\n selectThreadTab(tabId: string | null): void\n setNewConversationAssistantMode(mode: 'always' | 'mentioned'): void\n /** Start a new chat with an owned agent (null: an ordinary new chat). */\n setNewAgentChat(chat: { agentId: string; workspaceId: string } | null): void\n /** Bind the new chat to a document (null: unbound). Opening a new chat's tab clears it. */\n setNewChatDocumentId(documentId: string | null): void\n /** Edit a question: the composer holds it (its draft and line come back on cancel). */\n startEditing(messageId: string, content: string): void\n /** Leave the edit: the composer gets its draft back, and the view the line it was on. */\n cancelEditing(): void\n /** The edit was sent: leave it. */\n completeEditing(): void\n setDeepLinkMessageId(messageId: string | null): void\n setActiveCitationKey(key: string | null): void\n setPendingTools(tools: TurnTools | null): void\n setAutoSendDraft(on: boolean): void\n setAgentChatOwner(conversationId: string, agentId: string): void\n /** Save an answer's timer (`<conversation id>:<message id>`). */\n setMessageTimer(key: string, timer: ArbiMessageTimer): void\n clearMessageTimer(key: string): void\n /** A send failed: the turn stops, with the server's words and the question to retry. */\n setConversationError(\n conversationId: string,\n error: string | null,\n lastFailedMessage?: string | null\n ): void\n clearConversationError(conversationId: string): void\n /** Stop the conversation's local stream and end its turn. */\n abortConversationGeneration(conversationId: string): void\n /**\n * Leave the open conversation for a new one (its conversation was deleted): no line, edit, model\n * or document binding, Personal Assistant mode off.\n */\n startNewConversation(): void\n}\n\nexport interface ArbiChatStore extends ArbiChatActions {\n /** The current state. The same object until something in it changes. */\n getState(): ArbiChatState\n /** Be told after each change (once per batch). Returns the unsubscribe. */\n subscribe(listener: () => void): () => void\n /**\n * `listener`, told after the batch running when it is called (at once outside one): a session\n * store subscribes its readers to the layout and the rest through this, so a thread tab change\n * reaches them once.\n */\n settled(listener: () => void): () => void\n /** Drop a reader's notification still waiting for a batch to end (it unsubscribed). */\n forget(listener: () => void): void\n /** Run `change`, telling readers once when it is done. */\n batch<T>(change: () => T): T\n /** Resolves once the saved chat state has been read (at once without a `persist`). */\n hydrated(): Promise<void>\n isHydrated(): boolean\n /**\n * Bring back the saved drafts once they can be opened (the person's key is there once signed in\n * and a workspace is open); a draft typed meanwhile wins over its saved copy. Safe to call often.\n */\n restoreDrafts(): void\n /**\n * The workspace is being left: its turns stop (the server finishes them), and its conversation,\n * composers, thread tabs, facts, timers and the new chat's documents are dropped. Saved\n * conversations keep their documents.\n */\n leave(): void\n /**\n * Start over (sign-in, sign-out): everything is dropped and every running turn stopped, except\n * the agent chats' agents, which another person's sign-in drops.\n */\n reset(): void\n}\n\n/** What is kept across reloads. */\nexport interface ArbiSavedChat {\n version: 1\n /** The pieces an earlier build's own saved state was brought in for (the host's migration). */\n migrated: string[]\n conversationId: string | null\n cursor: string | null\n conversationDocuments: Record<string, ArbiConversationDocument[]>\n conversationDocumentAutoAdd: Record<string, boolean>\n conversationFacts: Record<string, string[]>\n agentChatOwners: Record<string, string>\n /** Who the agent chats belong to (null: not known, as in an earlier build's save). */\n agentChatOwnersUser: string | null\n chatModel: string | null\n}\n\nexport const EMPTY_CHAT_STATE: ArbiChatState = {\n conversationId: null,\n generating: {},\n paMode: false,\n conversationDocuments: {},\n conversationDocumentAutoAdd: {},\n conversationFacts: {},\n cursor: null,\n suggestedQuery: null,\n queuedMessages: {},\n agentControlStates: {},\n agentProbeAnswers: {},\n agentProbePending: {},\n drafts: {},\n editingMessageId: null,\n deepLinkMessageId: null,\n activeCitationKey: null,\n chatModel: undefined,\n chatModelName: undefined,\n newConversationAssistantMode: 'always',\n pendingTools: null,\n autoSendDraft: false,\n agentChatOwners: {},\n newAgentChat: null,\n newChatDocumentId: null,\n messageTimers: {},\n}\n\n// ── Saving ──────────────────────────────────────────────────────────────────────────────────────\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\nconst isString = (v: unknown): v is string => typeof v === 'string'\nconst stringOrNull = (v: unknown): string | null => (isString(v) ? v : null)\n\nconst recordOf = <T>(value: unknown, read: (entry: unknown) => T | null): Record<string, T> => {\n if (!isRecord(value)) return {}\n const out: Record<string, T> = {}\n for (const [key, entry] of Object.entries(value)) {\n const parsed = read(entry)\n if (parsed !== null) out[key] = parsed\n }\n return out\n}\n\nconst readDocuments = (value: unknown): ArbiConversationDocument[] | null =>\n Array.isArray(value)\n ? value\n .filter((doc): doc is Record<string, unknown> => isRecord(doc) && isString(doc.docId))\n .map((doc) => ({ docId: doc.docId as string, isPinned: doc.isPinned === true }))\n : null\n\nconst readFacts = (value: unknown): string[] | null =>\n Array.isArray(value) ? Array.from(new Set(value.filter(isString))) : null\n\n/**\n * A saved chat state as this build reads it: whatever an earlier or a broken save left is dropped\n * rather than read. Never throws; null when there is nothing usable.\n */\nexport function parseSavedChat(saved: unknown): ArbiSavedChat | null {\n if (!isRecord(saved) || saved.version !== 1) return null\n return {\n version: 1,\n migrated: Array.isArray(saved.migrated) ? saved.migrated.filter(isString) : [],\n conversationId: stringOrNull(saved.conversationId),\n cursor: stringOrNull(saved.cursor),\n conversationDocuments: recordOf(saved.conversationDocuments, readDocuments),\n conversationDocumentAutoAdd: recordOf(saved.conversationDocumentAutoAdd, (v) =>\n typeof v === 'boolean' ? v : null\n ),\n conversationFacts: recordOf(saved.conversationFacts, readFacts),\n agentChatOwners: recordOf(saved.agentChatOwners, (v) => (isString(v) ? v : null)),\n agentChatOwnersUser: stringOrNull(saved.agentChatOwnersUser),\n chatModel: stringOrNull(saved.chatModel),\n }\n}\n\n/** What of a chat state is saved. */\nexport function savedChatOf(\n state: ArbiChatState,\n migrated: string[],\n agentChatOwnersUser: string | null = null\n): ArbiSavedChat {\n return {\n version: 1,\n migrated,\n conversationId: state.conversationId,\n cursor: state.cursor,\n conversationDocuments: state.conversationDocuments as Record<\n string,\n ArbiConversationDocument[]\n >,\n conversationDocumentAutoAdd: { ...state.conversationDocumentAutoAdd },\n conversationFacts: state.conversationFacts as Record<string, string[]>,\n agentChatOwners: { ...state.agentChatOwners },\n agentChatOwnersUser,\n chatModel: state.chatModel ?? null,\n }\n}\n\nconst SAVED_FIELDS = [\n 'conversationId',\n 'cursor',\n 'conversationDocuments',\n 'conversationDocumentAutoAdd',\n 'conversationFacts',\n 'agentChatOwners',\n 'chatModel',\n] as const satisfies readonly (keyof ArbiChatState)[]\n\n// ── The store ───────────────────────────────────────────────────────────────────────────────────\n\nexport interface ArbiChatStoreOptions {\n /** The layout whose thread tabs the composer moves with. */\n layout: ArbiLayoutStore\n /** Keep the open conversation, the context and the model across reloads. */\n persist?: ArbiSessionPersist<ArbiSavedChat>\n /** Keep the composers' drafts across reloads (see `createSealedDraftStorage`). */\n draftStorage?: ArbiDraftStorage\n /** Where the open conversation is scrolled to, saved with its tab when another one shows. */\n scrollTop?: () => number | null\n /**\n * The signed-in user (default: the draft storage's owner). The agent chats' agents are kept over a\n * sign-in of the same person and dropped when another person signs in.\n */\n user?: () => string | null\n /** The state to start from (unit tests, a host's initial state); a saved one fills it in. */\n initial?: Partial<ArbiChatState>\n}\n\n/** A per-conversation record without the unsent new chat's entry. */\nfunction withoutNew<T>(record: Readonly<Record<string, T>>): Record<string, T> {\n const saved = { ...record }\n delete saved.new\n return saved\n}\n\n/** `record` with `fromId`'s entry under `toId` (the same record when it has none). */\nfunction moveKey<T>(\n record: Readonly<Record<string, T>>,\n fromId: string,\n toId: string\n): Readonly<Record<string, T>> {\n if (!(fromId in record)) return record\n const next = { ...record, [toId]: record[fromId] }\n delete next[fromId]\n return next\n}\n\nconst NO_EDIT = { draft: '', cursor: null as string | null }\n\nexport function createArbiChatStore({\n layout,\n persist,\n draftStorage,\n scrollTop = () => null,\n user = () => draftStorage?.owner() ?? null,\n initial,\n}: ArbiChatStoreOptions): ArbiChatStore {\n let state: ArbiChatState = { ...EMPTY_CHAT_STATE, ...initial }\n let migrated: string[] = []\n // Whose agent chats `agentChatOwners` records (null: not known yet).\n let ownersUser: string | null = null\n let isHydrated = !persist\n\n // Readers are told once per batch: a thread tab change moves the layout's tabs and the composer.\n const listeners = new Set<() => void>()\n const waiting = new Set<() => void>()\n let depth = 0\n const settle = (listener: () => void) => (depth > 0 ? waiting.add(listener) : listener())\n const notify = () => listeners.forEach(settle)\n const batch = <T>(change: () => T): T => {\n depth += 1\n try {\n return change()\n } finally {\n depth -= 1\n if (depth === 0) {\n const told = [...waiting]\n waiting.clear()\n told.forEach((listener) => listener())\n }\n }\n }\n\n const save = () => {\n // Nothing is saved before the saved state is read: it would overwrite it with the defaults.\n if (persist && isHydrated) persist.save(savedChatOf(state, migrated, ownersUser))\n }\n const update = (patch: Partial<ArbiChatState>) => {\n const next = { ...state, ...patch }\n const saved = SAVED_FIELDS.some((key) => next[key] !== state[key])\n state = next\n notify()\n if (saved) save()\n }\n\n // The draft and line the composer had when an edit began, given back when it is cancelled.\n let preEdit = NO_EDIT\n\n // ── Drafts ──\n // The saved drafts come back once the person's key is there; nothing is written before (it would\n // replace the saved ones). Whose they are is checked on each restore: another person's never carry\n // over to the next sign-in.\n let draftsRestored = !draftStorage\n let restoring = false\n let draftsOwner = draftStorage?.owner() ?? null\n const setDrafts = (drafts: Readonly<Record<string, string>>) => {\n if (drafts === state.drafts) return\n update({ drafts })\n if (draftsRestored) draftStorage?.save(drafts)\n }\n const setDraftOf = (key: string, text: string) => {\n if ((state.drafts[key] ?? '') === text) return\n const drafts = { ...state.drafts }\n if (text) drafts[key] = text\n else delete drafts[key]\n setDrafts(drafts)\n }\n /** The drafts of the open composer and the open thread tabs; any other is gone with its tab. */\n const keptDrafts = (drafts: Readonly<Record<string, string>>) => {\n const open = new Set(layout.getLayout().tabs.threads.map(threadTabId))\n open.add(state.conversationId ?? 'new')\n const keys = Object.keys(drafts)\n if (keys.every((key) => open.has(key))) return drafts\n return Object.fromEntries(keys.filter((key) => open.has(key)).map((key) => [key, drafts[key]]))\n }\n const restoreDrafts = () => {\n if (!draftStorage) return\n const owner = draftStorage.owner()\n if (owner !== draftsOwner) {\n if (draftsOwner !== null) update({ drafts: {} })\n draftsOwner = owner\n draftsRestored = false\n }\n if (draftsRestored || restoring || owner === null) return\n restoring = true\n // The tabs are read first: their drafts come back with them.\n void Promise.all([layout.hydrated(), hydration])\n .then(() => draftStorage.load())\n .then(\n (saved) => {\n restoring = false\n if (!saved || draftStorage.owner() !== owner) return\n draftsRestored = true\n setDrafts(keptDrafts({ ...saved, ...state.drafts }))\n draftStorage.save(state.drafts)\n },\n () => {\n restoring = false\n }\n )\n }\n // The session ended: what was typed goes with it.\n draftStorage?.onClear(() => {\n draftsRestored = false\n draftsOwner = null\n preEdit = NO_EDIT\n if (Object.keys(state.drafts).length > 0) update({ drafts: {} })\n })\n\n // ── The composer and the thread tabs ──\n const composer = (): ArbiThreadComposer => ({\n conversationId: state.conversationId,\n view: {\n cursor: state.cursor,\n editingMessageId: state.editingMessageId,\n preEditDraft: state.editingMessageId ? preEdit.draft : null,\n preEditCursor: state.editingMessageId ? preEdit.cursor : null,\n chatModel: state.chatModel,\n chatModelName: state.chatModelName,\n scrollTop: scrollTop(),\n },\n })\n /** Show what a thread tab change shows: a tab's own composer, or a fresh one (`list`: none). */\n const show = (next: ArbiThreadTabShow) => {\n if (next === null) return\n const target = next === 'list' ? { conversationId: null, view: undefined } : next\n const view = target.view\n preEdit = view\n ? { draft: view.preEditDraft ?? '', cursor: view.preEditCursor ?? null }\n : NO_EDIT\n update({\n conversationId: target.conversationId,\n cursor: view?.cursor ?? null,\n editingMessageId: view?.editingMessageId ?? null,\n chatModel: view?.chatModel,\n chatModelName: view?.chatModelName,\n })\n // A conversation opened afresh starts with an empty composer.\n if (!view) setDraftOf(target.conversationId ?? 'new', '')\n }\n const afterTabs = () => setDrafts(keptDrafts(state.drafts))\n const openThreadTab = (conversationId: string | null): string =>\n batch(() => {\n // Starting a new chat starts it unbound, whatever document is open.\n update(\n conversationId === null\n ? { newAgentChat: null, newChatDocumentId: null }\n : { newAgentChat: null }\n )\n const { tabId, show: next } = layout.threads.open(conversationId, composer())\n show(next)\n layout.setPageTab('conversations', tabId)\n afterTabs()\n return tabId\n })\n\n // ── Hydration ──\n const hydration: Promise<void> = persist\n ? persist.load().then(\n (saved) => {\n const parsed = parseSavedChat(saved)\n if (parsed) {\n migrated = parsed.migrated\n ownersUser ??= parsed.agentChatOwnersUser\n // What changed before the save was read stays. The saved line and model are the saved\n // conversation's: another conversation opened meanwhile does not inherit them.\n const conversationId = state.conversationId ?? parsed.conversationId\n const savedOpen = conversationId === parsed.conversationId\n state = {\n ...state,\n conversationId,\n cursor: state.cursor ?? (savedOpen ? parsed.cursor : null),\n chatModel:\n state.chatModel ?? (savedOpen ? (parsed.chatModel ?? undefined) : undefined),\n conversationDocuments: {\n ...parsed.conversationDocuments,\n ...state.conversationDocuments,\n },\n conversationDocumentAutoAdd: {\n ...parsed.conversationDocumentAutoAdd,\n ...state.conversationDocumentAutoAdd,\n },\n conversationFacts: { ...parsed.conversationFacts, ...state.conversationFacts },\n agentChatOwners: { ...parsed.agentChatOwners, ...state.agentChatOwners },\n }\n }\n isHydrated = true\n notify()\n },\n () => {\n isHydrated = true\n notify()\n }\n )\n : Promise.resolve()\n\n // An active thread tab shows its own conversation: an earlier build could save a thread's tab as\n // active with the conversation cleared (its title over an empty chat on every load). Once both the\n // tabs and the saved conversation are read, the conversation follows the tab.\n void Promise.all([layout.hydrated(), hydration]).then(() => {\n const { threads, activeThread } = layout.getLayout().tabs\n const tab = activeThread ? threads.find((t) => threadTabId(t) === activeThread) : null\n if (tab && state.conversationId !== tab.conversationId)\n update({ conversationId: tab.conversationId })\n })\n\n const generationOf = (conversationId: string) => state.generating[conversationId]\n const setGeneration = (conversationId: string, generation: ArbiConversationGeneration) =>\n update({ generating: { ...state.generating, [conversationId]: generation } })\n const stopAll = () =>\n Object.values(state.generating).forEach((generation) => generation.abortController?.abort())\n\n return {\n getState: () => state,\n subscribe: (listener) => {\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n waiting.delete(listener)\n }\n },\n settled: (listener) => () => settle(listener),\n forget: (listener) => void waiting.delete(listener),\n batch,\n hydrated: () => hydration,\n isHydrated: () => isHydrated,\n restoreDrafts,\n leave: () =>\n batch(() => {\n stopAll()\n preEdit = NO_EDIT\n update({\n conversationId: null,\n cursor: null,\n editingMessageId: null,\n chatModel: undefined,\n chatModelName: undefined,\n newConversationAssistantMode: 'always',\n paMode: false,\n generating: {},\n // Saved conversations keep their documents; the unsent new chat's belong to this workspace.\n conversationDocuments: withoutNew(state.conversationDocuments),\n conversationDocumentAutoAdd: withoutNew(state.conversationDocumentAutoAdd),\n conversationFacts: {},\n newAgentChat: null,\n newChatDocumentId: null,\n messageTimers: {},\n })\n layout.threads.clear()\n // The composers were this workspace's.\n setDrafts({})\n }),\n reset: () =>\n batch(() => {\n stopAll()\n preEdit = NO_EDIT\n // What was typed is the person's: their sealed copy goes with their session (sign-out).\n // The agent chats' agents stay unless another person signs in: an agent chat opened again\n // after the same person signs back in must still reach its agent.\n const signedIn = user()\n const keepOwners = signedIn === null || ownersUser === null || signedIn === ownersUser\n if (signedIn !== null) ownersUser = signedIn\n update({ ...EMPTY_CHAT_STATE, agentChatOwners: keepOwners ? state.agentChatOwners : {} })\n }),\n setConversationId: (id) => void openThreadTab(id),\n openThreadTab,\n closeThreadTab: (tabId) =>\n batch(() => {\n show(layout.threads.close(tabId))\n layout.setPageTab('conversations', layout.getLayout().tabs.activeThread ?? 'history')\n afterTabs()\n }),\n selectThreadTab: (tabId) =>\n batch(() => {\n if (tabId !== null) {\n show(layout.threads.select(tabId, composer()))\n layout.setPageTab('conversations', tabId)\n return\n }\n // The list leaves the open thread (so the URL is the list's); its tab keeps its composer.\n layout.threads.showList(composer())\n preEdit = NO_EDIT\n update({ conversationId: null, cursor: null, editingMessageId: null })\n layout.setPageTab('conversations', 'history')\n afterTabs()\n }),\n moveConversation: (fromId, toId) =>\n batch(() => {\n update({\n generating: moveKey(state.generating, fromId, toId),\n conversationDocuments: moveKey(state.conversationDocuments, fromId, toId),\n conversationDocumentAutoAdd: moveKey(state.conversationDocumentAutoAdd, fromId, toId),\n conversationFacts: moveKey(state.conversationFacts, fromId, toId),\n conversationId: state.conversationId ?? toId,\n })\n // The new chat's tab is now the conversation's, and what is typed stays where it was typed.\n layout.threads.rename(fromId, toId)\n setDrafts(moveKey(state.drafts, fromId, toId))\n }),\n setConversationGenerating: (conversationId, isGenerating, abortController) => {\n const current = generationOf(conversationId)\n setGeneration(conversationId, {\n ...current,\n isGenerating,\n error: isGenerating ? null : (current?.error ?? null),\n // Starting with an explicit null means generation this client does not own (an attach to a\n // run started elsewhere): it must not inherit a finished local turn's controller, or the\n // view takes it for a local stream and detaches, which makes it attachable again (an\n // endless loop that froze the tab after Stop). Stopping keeps the controller: the finished\n // turn's bookkeeping still matches on it.\n abortController:\n isGenerating && abortController === null\n ? null\n : (abortController ?? current?.abortController ?? null),\n // The run's start is set when the server names its answer (setStreamingAssistantId).\n startTime: null,\n streamingAssistantId: null,\n ...(isGenerating ? { lastFailedMessage: null, backendElapsed: null } : {}),\n })\n },\n setStreamingAssistantId: (conversationId, streamingAssistantId, startTime = Date.now()) =>\n setGeneration(conversationId, {\n ...(generationOf(conversationId) ?? { isGenerating: false, error: null }),\n streamingAssistantId,\n startTime,\n }),\n setBackendElapsed: (conversationId, backendElapsed) =>\n setGeneration(conversationId, {\n ...(generationOf(conversationId) ?? { isGenerating: false, error: null, startTime: null }),\n backendElapsed,\n }),\n setConversationError: (conversationId, error, lastFailedMessage) => {\n const current = generationOf(conversationId)\n setGeneration(conversationId, {\n ...current,\n isGenerating: false,\n error,\n startTime: current?.startTime ?? null,\n lastFailedMessage: lastFailedMessage ?? current?.lastFailedMessage ?? null,\n })\n },\n clearConversationError: (conversationId) =>\n setGeneration(conversationId, {\n ...(generationOf(conversationId) ?? { isGenerating: false, startTime: null }),\n error: null,\n lastFailedMessage: null,\n }),\n abortConversationGeneration: (conversationId) => {\n const current = generationOf(conversationId)\n current?.abortController?.abort()\n setGeneration(conversationId, {\n ...(current ?? { error: null, startTime: null }),\n isGenerating: false,\n abortController: null,\n })\n },\n setPaMode: (paMode) => {\n if (state.paMode !== paMode) update({ paMode })\n },\n setConversationDocuments: (conversationId, documents, autoAdd = false) =>\n update({\n conversationDocuments: { ...state.conversationDocuments, [conversationId]: documents },\n conversationDocumentAutoAdd: {\n ...state.conversationDocumentAutoAdd,\n [conversationId]: autoAdd,\n },\n }),\n setConversationFacts: (conversationId, factIds) =>\n update({\n conversationFacts: {\n ...state.conversationFacts,\n [conversationId]: Array.from(new Set(factIds)),\n },\n }),\n setCursor: (cursor) => {\n if (state.cursor !== cursor) update({ cursor })\n },\n setSuggestedQuery: (suggestedQuery) => update({ suggestedQuery }),\n addQueuedMessage: (id, message) =>\n update({ queuedMessages: queuedMessages.add(state.queuedMessages, id, message) }),\n acknowledgeQueuedMessage: (clientId, serverId) =>\n update({\n queuedMessages: queuedMessages.acknowledge(state.queuedMessages, clientId, serverId),\n }),\n removeQueuedMessage: (clientId) =>\n update({ queuedMessages: queuedMessages.remove(state.queuedMessages, clientId) }),\n removeQueuedMessageByServerId: (serverId) =>\n update({ queuedMessages: queuedMessages.removeByServerId(state.queuedMessages, serverId) }),\n consumeQueuedMessage: (id, content) =>\n update({ queuedMessages: queuedMessages.consume(state.queuedMessages, id, content) }),\n clearQueuedMessages: (id) =>\n update({ queuedMessages: queuedMessages.clear(state.queuedMessages, id) }),\n moveQueuedMessages: (from, to) =>\n update({ queuedMessages: queuedMessages.move(state.queuedMessages, from, to) }),\n setAgentControlState: (id, control) => update(agentControl.setState(state, id, control)),\n setAgentProbeAnswer: (id, probe) => update(agentControl.setProbeAnswer(state, id, probe)),\n setAgentProbePending: (id, pending) => update(agentControl.setProbePending(state, id, pending)),\n clearAgentControl: (id) => update(agentControl.clear(state, id)),\n setDraft: (text) => setDraftOf(state.conversationId ?? 'new', text),\n setChatModel: (chatModel) => {\n if (state.chatModel !== chatModel) update({ chatModel })\n },\n setChatModelName: (chatModelName) => {\n if (state.chatModelName !== chatModelName) update({ chatModelName })\n },\n setNewConversationAssistantMode: (newConversationAssistantMode) => {\n if (state.newConversationAssistantMode !== newConversationAssistantMode)\n update({ newConversationAssistantMode })\n },\n setNewAgentChat: (newAgentChat) => {\n const current = state.newAgentChat\n if (\n current?.agentId !== newAgentChat?.agentId ||\n current?.workspaceId !== newAgentChat?.workspaceId\n )\n update({ newAgentChat })\n },\n setNewChatDocumentId: (newChatDocumentId) => {\n if (state.newChatDocumentId !== newChatDocumentId) update({ newChatDocumentId })\n },\n startEditing: (messageId, content) =>\n batch(() => {\n const key = state.conversationId ?? 'new'\n preEdit = { draft: state.drafts[key] ?? '', cursor: state.cursor }\n update({ editingMessageId: messageId })\n setDraftOf(key, content)\n }),\n cancelEditing: () => {\n if (!state.editingMessageId) return\n const restore = preEdit\n preEdit = NO_EDIT\n batch(() => {\n update({ editingMessageId: null, cursor: restore.cursor })\n setDraftOf(state.conversationId ?? 'new', restore.draft)\n })\n },\n completeEditing: () => {\n preEdit = NO_EDIT\n if (state.editingMessageId) update({ editingMessageId: null })\n },\n setDeepLinkMessageId: (deepLinkMessageId) => {\n if (state.deepLinkMessageId !== deepLinkMessageId) update({ deepLinkMessageId })\n },\n setActiveCitationKey: (activeCitationKey) => {\n if (state.activeCitationKey !== activeCitationKey) update({ activeCitationKey })\n },\n setPendingTools: (pendingTools) => update({ pendingTools }),\n setAutoSendDraft: (autoSendDraft) => {\n if (state.autoSendDraft !== autoSendDraft) update({ autoSendDraft })\n },\n setAgentChatOwner: (conversationId, agentId) => {\n const signedIn = user()\n ownersUser = signedIn ?? ownersUser\n update({ agentChatOwners: { ...state.agentChatOwners, [conversationId]: agentId } })\n },\n setMessageTimer: (key, timer) =>\n update({ messageTimers: { ...state.messageTimers, [key]: timer } }),\n clearMessageTimer: (key) => {\n if (!(key in state.messageTimers)) return\n const messageTimers = { ...state.messageTimers }\n delete messageTimers[key]\n update({ messageTimers })\n },\n startNewConversation: () =>\n batch(() => {\n preEdit = NO_EDIT\n update({\n conversationId: null,\n cursor: null,\n editingMessageId: null,\n chatModel: undefined,\n chatModelName: undefined,\n newConversationAssistantMode: 'always',\n paMode: false,\n newChatDocumentId: null,\n })\n }),\n }\n}\n","/**\n * The layout part of the session state: the shell (the page on screen, the sidebar, the panels and\n * where each one shows, the area with focus), the open tabs (threads, direct messages, projects),\n * each page's view (its tab, its filters, other view settings) and the grids' saved state. Kits and\n * the host read and change it through the session store; the parts a person arranges (the page, the\n * pinned sidebar, the panels, the thread tabs, the views, the grids) are kept across reloads by the\n * host's {@link ArbiSessionPersist}.\n */\n\nimport type { ArbiSessionPersist } from './persist'\nimport {\n closeThreadTabIn,\n openThreadTabIn,\n parseSavedThreadTabs,\n renameThreadTabIn,\n savedThreadTabs,\n selectThreadTabIn,\n showThreadListIn,\n type ArbiThreadComposer,\n type ArbiThreadTabShow,\n type ArbiThreadTabsState,\n} from './thread-tabs'\n\n/** Where a panel shows: the page's area, docked beside it, over it, or in its own window. */\nexport type ArbiPanelMode = 'main' | 'docked' | 'overlay' | 'popout'\n\nexport interface ArbiPanelsState {\n /** The panel in each place (one each): filling the page, docked, over the page, popped out. */\n main: string | null\n docked: string | null\n overlay: string | null\n popout: string | null\n /** Where each panel last showed (it opens there again). */\n modes: Readonly<Record<string, ArbiPanelMode>>\n /** A floating panel's size. */\n sizes: Readonly<Record<string, { width: number; height: number }>>\n}\n\nexport interface ArbiSidebarState {\n /** Pinned open (on wide screens; phones show a drawer). */\n pinned: boolean\n /** The rail is expanded under the pointer. */\n hovering: boolean\n /** The phone drawer is open. */\n drawerOpen: boolean\n}\n\nexport interface ArbiShellState {\n /** The page on screen (a host's page id). */\n page: string\n sidebar: ArbiSidebarState\n panels: ArbiPanelsState\n /** The area with focus: `main` or a panel id. */\n focusedArea: string\n}\n\n/** A direct-message tab: a person's or agent's id, a group chat's id, or null (a new message). */\nexport interface ArbiDmTab {\n recipientId: string | null\n}\n\nexport interface ArbiTabsState extends ArbiThreadTabsState {\n dm: readonly ArbiDmTab[]\n activeDm: string | null\n /** The message a direct-message tab scrolls to once open. */\n dmMessageId: string | null\n projects: readonly string[]\n activeProject: string | null\n}\n\nexport interface ArbiViewsState {\n /** Each page's tab, by page. */\n tabs: Readonly<Record<string, string>>\n /** Each list's quick filters, by list. */\n filters: Readonly<Record<string, unknown>>\n /** Other view settings, by key (a page's view mode, a zoom, a filter box's text). */\n values: Readonly<Record<string, unknown>>\n /** View state kept for this session only, by key (a search's results); not saved. */\n transient: Readonly<Record<string, unknown>>\n}\n\nexport interface ArbiGridLayoutState {\n /** Each grid's saved state (columns, widths, sort), by grid id. */\n states: Readonly<Record<string, unknown>>\n /** Each grid's row height. */\n rowHeights: Readonly<Record<string, number>>\n /** Each timeline's label column width. */\n labelWidths: Readonly<Record<string, number>>\n /** Views an earlier build saved on this device, by grid id (moved to user settings once). */\n savedViews: Readonly<Record<string, readonly unknown[]>>\n}\n\nexport interface ArbiLayoutState {\n shell: ArbiShellState\n tabs: ArbiTabsState\n views: ArbiViewsState\n grid: ArbiGridLayoutState\n}\n\n/** What is kept across reloads. */\nexport interface ArbiSavedLayout {\n version: 1\n /** The pieces an earlier build's own saved state was brought in for (the host's migration). */\n migrated: string[]\n shell: {\n page: string\n sidebarPinned: boolean\n panels: { main: string | null; docked: string | null } & Pick<\n ArbiPanelsState,\n 'modes' | 'sizes'\n >\n }\n /** The open thread tabs (without what was typed in them) and the one on screen. */\n tabs: Pick<ArbiThreadTabsState, 'threads' | 'activeThread'>\n views: Omit<ArbiViewsState, 'transient'>\n grid: ArbiGridLayoutState\n}\n\nconst PANEL_MODES: readonly ArbiPanelMode[] = ['main', 'docked', 'overlay', 'popout']\n\n/** Phones start with the sidebar as a drawer, wider screens pinned. */\nconst defaultPinned = () => typeof window === 'undefined' || window.innerWidth >= 640\n\nexport function defaultLayoutState(): ArbiLayoutState {\n return {\n shell: {\n page: 'home',\n sidebar: { pinned: defaultPinned(), hovering: false, drawerOpen: false },\n panels: { main: null, docked: null, overlay: null, popout: null, modes: {}, sizes: {} },\n focusedArea: 'main',\n },\n tabs: {\n threads: [],\n activeThread: null,\n threadScrollRestore: null,\n dm: [],\n activeDm: null,\n dmMessageId: null,\n projects: [],\n activeProject: null,\n },\n views: { tabs: {}, filters: {}, values: {}, transient: {} },\n grid: { states: {}, rowHeights: {}, labelWidths: {}, savedViews: {} },\n }\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\nconst recordOf = <T>(value: unknown, keep: (entry: unknown) => entry is T): Record<string, T> =>\n isRecord(value)\n ? (Object.fromEntries(Object.entries(value).filter(([, v]) => keep(v))) as Record<string, T>)\n : {}\n\nconst isString = (v: unknown): v is string => typeof v === 'string'\nconst isNumber = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v)\nconst isAny = (v: unknown): v is unknown => v !== undefined\nconst isMode = (v: unknown): v is ArbiPanelMode => PANEL_MODES.includes(v as ArbiPanelMode)\nconst isSize = (v: unknown): v is { width: number; height: number } =>\n isRecord(v) && isNumber(v.width) && isNumber(v.height)\nconst isList = (v: unknown): v is unknown[] => Array.isArray(v)\nconst stringOrNull = (v: unknown): string | null => (isString(v) ? v : null)\n\n/**\n * A saved layout as this build reads it: whatever an earlier or a broken save left is dropped\n * rather than read. Never throws; null when there is nothing usable.\n */\nexport function parseSavedLayout(saved: unknown): ArbiSavedLayout | null {\n if (!isRecord(saved) || saved.version !== 1) return null\n const shell = isRecord(saved.shell) ? saved.shell : {}\n const panels = isRecord(shell.panels) ? shell.panels : {}\n const tabs = isRecord(saved.tabs) ? saved.tabs : {}\n const views = isRecord(saved.views) ? saved.views : {}\n const grid = isRecord(saved.grid) ? saved.grid : {}\n const defaults = defaultLayoutState()\n return {\n version: 1,\n migrated: isList(saved.migrated) ? saved.migrated.filter(isString) : [],\n shell: {\n page: isString(shell.page) ? shell.page : defaults.shell.page,\n sidebarPinned:\n typeof shell.sidebarPinned === 'boolean'\n ? shell.sidebarPinned\n : defaults.shell.sidebar.pinned,\n panels: {\n main: stringOrNull(panels.main),\n docked: stringOrNull(panels.docked),\n modes: recordOf(panels.modes, isMode),\n sizes: recordOf(panels.sizes, isSize),\n },\n },\n tabs: parseSavedThreadTabs(tabs.threads, tabs.activeThread),\n views: {\n tabs: recordOf(views.tabs, isString),\n filters: recordOf(views.filters, isAny),\n values: recordOf(views.values, isAny),\n },\n grid: {\n states: recordOf(grid.states, isRecord),\n rowHeights: recordOf(grid.rowHeights, isNumber),\n labelWidths: recordOf(grid.labelWidths, isNumber),\n savedViews: recordOf(grid.savedViews, isList),\n },\n }\n}\n\n/** What of a layout is saved. */\nexport function savedLayoutOf(layout: ArbiLayoutState, migrated: string[]): ArbiSavedLayout {\n const { shell, tabs, views, grid } = layout\n return {\n version: 1,\n migrated,\n shell: {\n page: shell.page,\n sidebarPinned: shell.sidebar.pinned,\n // A panel over the page or in its own window does not come back after a reload.\n panels: {\n main: shell.panels.main,\n docked: shell.panels.docked,\n modes: shell.panels.modes,\n sizes: shell.panels.sizes,\n },\n },\n tabs: { threads: savedThreadTabs(tabs.threads), activeThread: tabs.activeThread },\n views: { tabs: views.tabs, filters: views.filters, values: views.values },\n grid,\n }\n}\n\n/** The layout a saved one restores (the parts not saved keep their current values). */\nexport function restoreLayout(current: ArbiLayoutState, saved: ArbiSavedLayout): ArbiLayoutState {\n return {\n ...current,\n shell: {\n ...current.shell,\n page: saved.shell.page,\n sidebar: { ...current.shell.sidebar, pinned: saved.shell.sidebarPinned },\n panels: { ...current.shell.panels, ...saved.shell.panels },\n },\n tabs: { ...current.tabs, ...saved.tabs },\n views: { ...saved.views, transient: current.views.transient },\n grid: saved.grid,\n }\n}\n\n// ── Changes ─────────────────────────────────────────────────────────────────────────────────────\n\n/** Show a panel in a place: it leaves the place it was in, and what was in that place closes. */\nexport function openPanelIn(\n panels: ArbiPanelsState,\n panelId: string,\n mode: ArbiPanelMode\n): ArbiPanelsState {\n const leave = (slot: string | null) => (slot === panelId ? null : slot)\n const next: ArbiPanelsState = {\n ...panels,\n main: leave(panels.main),\n docked: leave(panels.docked),\n overlay: leave(panels.overlay),\n popout: leave(panels.popout),\n modes: { ...panels.modes, [panelId]: mode },\n }\n // Docked and over the page are both the secondary surface beside the page: one at a time.\n if (mode === 'docked') return { ...next, docked: panelId, overlay: null }\n if (mode === 'overlay') return { ...next, overlay: panelId, docked: null }\n return { ...next, [mode]: panelId }\n}\n\nexport function closePanelIn(panels: ArbiPanelsState, panelId: string): ArbiPanelsState {\n const leave = (slot: string | null) => (slot === panelId ? null : slot)\n return {\n ...panels,\n main: leave(panels.main),\n docked: leave(panels.docked),\n overlay: leave(panels.overlay),\n popout: leave(panels.popout),\n }\n}\n\n/** Where a panel shows now, or null while it is closed. */\nexport function panelPlace(panels: ArbiPanelsState, panelId: string): ArbiPanelMode | null {\n return PANEL_MODES.find((mode) => panels[mode] === panelId) ?? null\n}\n\n/** Whether a panel is open (anywhere). */\nexport const isPanelOpen = (state: { shell: ArbiShellState }, panelId: string): boolean =>\n panelPlace(state.shell.panels, panelId) !== null\n\nexport const dmTabId = (tab: ArbiDmTab): string => tab.recipientId ?? 'new'\n\n/** The actions on the layout (part of {@link ArbiSessionStore}). */\nexport interface ArbiLayoutActions {\n /** Show a page; the focus goes to the page area. */\n setPage(page: string): void\n setSidebar(change: Partial<ArbiSidebarState>): void\n /** Show a panel in a place (`mode`), focused. */\n openPanel(panelId: string, mode: ArbiPanelMode): void\n closePanel(panelId: string): void\n /** Where a panel shows: an open one moves there, a closed one opens there next time. */\n setPanelMode(panelId: string, mode: ArbiPanelMode): void\n setPanelSize(panelId: string, size: { width: number; height: number }): void\n setFocusedArea(area: string): void\n /** Open (or show) a direct-message tab, optionally scrolled to a message. */\n openDmTab(recipientId: string | null, messageId?: string): void\n closeDmTab(tabId: string): void\n /** null: no direct-message tab (the panel's own). */\n selectDmTab(tabId: string | null): void\n clearDmTabs(): void\n setDmMessageId(messageId: string | null): void\n openProjectTab(projectId: string): void\n closeProjectTab(projectId: string): void\n /** null: the projects list. */\n selectProjectTab(projectId: string | null): void\n setPageTab(page: string, tab: string): void\n setViewFilter(key: string, value: unknown): void\n setViewValue(key: string, value: unknown): void\n /** Set (or with `undefined`, drop) view state kept for this session only. */\n setTransientView(key: string, value: unknown): void\n setGridState(gridId: string, state: unknown): void\n clearGridState(gridId: string): void\n setGridRowHeight(gridId: string, height: number): void\n setGridLabelWidth(gridId: string, width: number): void\n setGridSavedViews(gridId: string, views: readonly unknown[]): void\n /**\n * Start over: a sign-in shows the home page with the sidebar at its default and no panel, tab\n * or page tab open; a sign-out also forgets the grids.\n */\n resetLayout(variant: 'login' | 'logout'): void\n}\n\n/**\n * The thread tabs' changes on a layout store. Each takes the composer being left (saved into the tab\n * on screen) and says what the composer shows next; the session store applies that to whatever\n * holds the composer (`ArbiSessionStore.openThreadTab` and the like are built on these).\n */\nexport interface ArbiThreadTabsController {\n open(\n conversationId: string | null,\n leaving: ArbiThreadComposer\n ): { tabId: string; show: ArbiThreadTabShow }\n close(tabId: string): ArbiThreadTabShow\n select(tabId: string, leaving: ArbiThreadComposer): ArbiThreadTabShow\n showList(leaving: ArbiThreadComposer): void\n /** The tab of `fromId` is now `toId`'s (a new chat got its id). */\n rename(fromId: string, toId: string): void\n clear(): void\n /** The scroll position the last tab switch brought back (once; null after). */\n consumeScrollRestore(): number | null\n}\n\n/** A store of the layout alone; the session stores are built on it. */\nexport interface ArbiLayoutStore extends ArbiLayoutActions {\n getLayout(): ArbiLayoutState\n /** Back to the defaults, everything (unit tests; a reset from an error screen). */\n reset(): void\n subscribe(listener: () => void): () => void\n /** Resolves once the saved layout has been read (at once without a `persist`). */\n hydrated(): Promise<void>\n isHydrated(): boolean\n /** The thread tabs' changes (not session actions: the session store's apply them). */\n threads: ArbiThreadTabsController\n}\n\nexport interface ArbiLayoutStoreOptions {\n persist?: ArbiSessionPersist<ArbiSavedLayout>\n /** The layout to start from (unit tests, a host's initial state); a saved one replaces it. */\n initial?: Partial<ArbiLayoutState>\n}\n\nexport function createArbiLayoutStore({\n persist,\n initial,\n}: ArbiLayoutStoreOptions = {}): ArbiLayoutStore {\n let layout: ArbiLayoutState = { ...defaultLayoutState(), ...initial }\n let migrated: string[] = []\n let isHydrated = !persist\n const listeners = new Set<() => void>()\n const save = () => {\n // Nothing is saved before the saved layout is read: it would overwrite it with the defaults.\n if (persist && isHydrated) persist.save(savedLayoutOf(layout, migrated))\n }\n const update = (next: ArbiLayoutState) => {\n if (next === layout) return\n const persisted =\n next.tabs.threads !== layout.tabs.threads ||\n next.tabs.activeThread !== layout.tabs.activeThread ||\n next.views.tabs !== layout.views.tabs ||\n next.views.filters !== layout.views.filters ||\n next.views.values !== layout.views.values ||\n next.grid !== layout.grid ||\n next.shell.page !== layout.shell.page ||\n next.shell.sidebar.pinned !== layout.shell.sidebar.pinned ||\n next.shell.panels !== layout.shell.panels\n layout = next\n listeners.forEach((listener) => listener())\n if (persisted) save()\n }\n const shell = (change: Partial<ArbiShellState>) =>\n update({ ...layout, shell: { ...layout.shell, ...change } })\n const tabs = (change: Partial<ArbiTabsState>) =>\n update({ ...layout, tabs: { ...layout.tabs, ...change } })\n const views = (change: Partial<ArbiViewsState>) =>\n update({ ...layout, views: { ...layout.views, ...change } })\n const grid = (change: Partial<ArbiGridLayoutState>) =>\n update({ ...layout, grid: { ...layout.grid, ...change } })\n\n const hydration: Promise<void> = persist\n ? persist.load().then(\n (saved) => {\n const parsed = parseSavedLayout(saved)\n if (parsed) {\n migrated = parsed.migrated\n layout = restoreLayout(layout, parsed)\n }\n isHydrated = true\n listeners.forEach((listener) => listener())\n },\n () => {\n isHydrated = true\n listeners.forEach((listener) => listener())\n }\n )\n : Promise.resolve()\n\n return {\n getLayout: () => layout,\n reset: () => update(defaultLayoutState()),\n subscribe: (listener) => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n hydrated: () => hydration,\n isHydrated: () => isHydrated,\n threads: {\n open: (conversationId, leaving) => {\n const change = openThreadTabIn(layout.tabs, conversationId, leaving)\n tabs(change.tabs)\n return { tabId: change.tabId, show: change.show }\n },\n close: (tabId) => {\n const change = closeThreadTabIn(layout.tabs, tabId)\n tabs(change.tabs)\n return change.show\n },\n select: (tabId, leaving) => {\n const change = selectThreadTabIn(layout.tabs, tabId, leaving)\n if (change.tabs !== layout.tabs) tabs(change.tabs)\n return change.show\n },\n showList: (leaving) => tabs(showThreadListIn(layout.tabs, leaving)),\n rename: (fromId, toId) => {\n const next = renameThreadTabIn(layout.tabs, fromId, toId)\n if (next !== layout.tabs) tabs(next)\n },\n clear: () => {\n if (layout.tabs.threads.length > 0 || layout.tabs.activeThread !== null)\n tabs({ threads: [], activeThread: null })\n },\n consumeScrollRestore: () => {\n const value = layout.tabs.threadScrollRestore\n if (value !== null) tabs({ threadScrollRestore: null })\n return value\n },\n },\n setPage: (page) => {\n if (layout.shell.page !== page || layout.shell.focusedArea !== 'main')\n shell({ page, focusedArea: 'main' })\n },\n setSidebar: (change) => {\n const sidebar = { ...layout.shell.sidebar, ...change }\n const current = layout.shell.sidebar\n if (\n sidebar.pinned !== current.pinned ||\n sidebar.hovering !== current.hovering ||\n sidebar.drawerOpen !== current.drawerOpen\n )\n shell({ sidebar })\n },\n openPanel: (panelId, mode) =>\n shell({ panels: openPanelIn(layout.shell.panels, panelId, mode), focusedArea: panelId }),\n closePanel: (panelId) =>\n shell({ panels: closePanelIn(layout.shell.panels, panelId), focusedArea: 'main' }),\n setPanelMode: (panelId, mode) => {\n const panels = layout.shell.panels\n if (panelPlace(panels, panelId) !== null)\n shell({ panels: openPanelIn(panels, panelId, mode), focusedArea: panelId })\n else if (panels.modes[panelId] !== mode)\n shell({ panels: { ...panels, modes: { ...panels.modes, [panelId]: mode } } })\n },\n setPanelSize: (panelId, size) => {\n const panels = layout.shell.panels\n shell({ panels: { ...panels, sizes: { ...panels.sizes, [panelId]: size } } })\n },\n setFocusedArea: (focusedArea) => {\n if (layout.shell.focusedArea !== focusedArea) shell({ focusedArea })\n },\n openDmTab: (recipientId, messageId) => {\n const id = recipientId ?? 'new'\n const dm = layout.tabs.dm.some((tab) => dmTabId(tab) === id)\n ? layout.tabs.dm\n : [...layout.tabs.dm, { recipientId }]\n tabs({ dm, activeDm: id, ...(messageId ? { dmMessageId: messageId } : {}) })\n },\n closeDmTab: (tabId) => {\n const dm = layout.tabs.dm.filter((tab) => dmTabId(tab) !== tabId)\n if (dm.length === layout.tabs.dm.length) return\n if (dm.length === 0) return tabs({ dm, activeDm: null })\n if (layout.tabs.activeDm !== tabId) return tabs({ dm })\n // The tab beside the closed one shows.\n const index = layout.tabs.dm.findIndex((tab) => dmTabId(tab) === tabId)\n tabs({ dm, activeDm: dmTabId(dm[Math.min(index, dm.length - 1)]) })\n },\n selectDmTab: (activeDm) => {\n if (layout.tabs.activeDm !== activeDm) tabs({ activeDm })\n },\n clearDmTabs: () => tabs({ dm: [], activeDm: null }),\n setDmMessageId: (dmMessageId) => {\n if (layout.tabs.dmMessageId !== dmMessageId) tabs({ dmMessageId })\n },\n openProjectTab: (projectId) =>\n tabs({\n projects: layout.tabs.projects.includes(projectId)\n ? layout.tabs.projects\n : [...layout.tabs.projects, projectId],\n activeProject: projectId,\n }),\n closeProjectTab: (projectId) => {\n const projects = layout.tabs.projects.filter((id) => id !== projectId)\n if (projects.length === layout.tabs.projects.length) return\n if (layout.tabs.activeProject !== projectId) return tabs({ projects })\n const index = layout.tabs.projects.indexOf(projectId)\n tabs({\n projects,\n activeProject: projects.length ? projects[Math.min(index, projects.length - 1)] : null,\n })\n },\n selectProjectTab: (activeProject) => {\n if (layout.tabs.activeProject !== activeProject) tabs({ activeProject })\n },\n setPageTab: (page, tab) => {\n if (layout.views.tabs[page] !== tab) views({ tabs: { ...layout.views.tabs, [page]: tab } })\n },\n setViewFilter: (key, value) => views({ filters: { ...layout.views.filters, [key]: value } }),\n setViewValue: (key, value) => {\n if (layout.views.values[key] !== value)\n views({ values: { ...layout.views.values, [key]: value } })\n },\n setTransientView: (key, value) => {\n if (layout.views.transient[key] === value) return\n const transient = { ...layout.views.transient }\n if (value === undefined) delete transient[key]\n else transient[key] = value\n views({ transient })\n },\n setGridState: (gridId, state) => grid({ states: { ...layout.grid.states, [gridId]: state } }),\n clearGridState: (gridId) => {\n if (!(gridId in layout.grid.states)) return\n const states = { ...layout.grid.states }\n delete states[gridId]\n grid({ states })\n },\n setGridRowHeight: (gridId, height) =>\n grid({ rowHeights: { ...layout.grid.rowHeights, [gridId]: height } }),\n setGridLabelWidth: (gridId, width) =>\n grid({ labelWidths: { ...layout.grid.labelWidths, [gridId]: width } }),\n setGridSavedViews: (gridId, saved) =>\n grid({ savedViews: { ...layout.grid.savedViews, [gridId]: saved } }),\n resetLayout: (variant) => {\n const fresh = defaultLayoutState()\n update({\n shell: {\n ...fresh.shell,\n panels: {\n ...fresh.shell.panels,\n modes: layout.shell.panels.modes,\n sizes: layout.shell.panels.sizes,\n },\n },\n tabs: fresh.tabs,\n views: { ...layout.views, tabs: {}, transient: {} },\n grid: variant === 'logout' ? { ...layout.grid, states: {} } : layout.grid,\n })\n },\n }\n}\n","/**\n * The session's selected workspace (`workspaceId`) and where it stands on the server session\n * (`workspaceStatus`). `useSwitchWorkspace` moves both; a session store reads them from here.\n *\n * The selection is kept per tab (sessionStorage), so a reload stays in the workspace and each tab\n * can be in a different one; a new sign-in starts with none ({@link ArbiWorkspaceStore.reset}).\n * The status is never kept: after a reload the server session is new, and\n * `useOpenSelectedWorkspace` opens the kept selection again.\n */\n\nimport type { ArbiWorkspaceStatus } from './store'\n\n/** Where the selection is kept across reloads. */\nexport interface ArbiWorkspaceStorage {\n load(): string | null\n save(workspaceId: string | null): void\n}\n\n/** The selection and its status. */\nexport interface ArbiWorkspaceState {\n workspaceId: string | null\n workspaceStatus: ArbiWorkspaceStatus\n}\n\nexport interface ArbiWorkspaceStore {\n getState(): ArbiWorkspaceState\n subscribe(listener: () => void): () => void\n setWorkspaceId(workspaceId: string | null): void\n setWorkspaceStatus(status: ArbiWorkspaceStatus): void\n /** No workspace, closed (a sign-in or sign-out: the next person starts on the workspace list). */\n reset(): void\n}\n\nexport interface ArbiWorkspaceStoreOptions {\n storage?: ArbiWorkspaceStorage\n /** The selection to start with instead of the kept one. */\n workspaceId?: string | null\n}\n\nexport function createArbiWorkspaceStore({\n storage,\n workspaceId = storage?.load() ?? null,\n}: ArbiWorkspaceStoreOptions = {}): ArbiWorkspaceStore {\n let state: ArbiWorkspaceState = { workspaceId, workspaceStatus: 'closed' }\n const listeners = new Set<() => void>()\n const update = (patch: Partial<ArbiWorkspaceState>) => {\n state = { ...state, ...patch }\n listeners.forEach((listener) => listener())\n }\n const setWorkspaceId = (id: string | null) => {\n storage?.save(id)\n if (state.workspaceId !== id) update({ workspaceId: id })\n }\n return {\n getState: () => state,\n subscribe: (listener) => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n setWorkspaceId,\n setWorkspaceStatus: (workspaceStatus) => {\n if (state.workspaceStatus !== workspaceStatus) update({ workspaceStatus })\n },\n reset: () => {\n storage?.save(null)\n if (state.workspaceId !== null || state.workspaceStatus !== 'closed')\n update({ workspaceId: null, workspaceStatus: 'closed' })\n },\n }\n}\n\n/** The sessionStorage key of the selection (per tab). */\nexport const WORKSPACE_STORAGE_KEY = 'arbi_workspace_id'\n/** The localStorage key of when each workspace was last opened (per browser). */\nexport const WORKSPACE_LAST_OPENED_KEY = 'arbi_workspace_last_opened'\n\nexport interface BrowserWorkspaceStorageOptions {\n /** Default {@link WORKSPACE_STORAGE_KEY}. */\n key?: string\n /** Default {@link WORKSPACE_LAST_OPENED_KEY}. */\n lastOpenedKey?: string\n}\n\n/**\n * The browser's: the selection per tab (sessionStorage), and when each workspace was last opened\n * per browser (localStorage, read with {@link readWorkspaceLastOpened}: \"recently opened\" is a\n * history that outlives a tab, the selection deliberately does not).\n */\nexport function browserWorkspaceStorage({\n key = WORKSPACE_STORAGE_KEY,\n lastOpenedKey = WORKSPACE_LAST_OPENED_KEY,\n}: BrowserWorkspaceStorageOptions = {}): ArbiWorkspaceStorage {\n return {\n load() {\n try {\n return window.sessionStorage.getItem(key)\n } catch {\n return null\n }\n },\n save(workspaceId) {\n try {\n if (!workspaceId) {\n window.sessionStorage.removeItem(key)\n return\n }\n window.sessionStorage.setItem(key, workspaceId)\n const lastOpened = readWorkspaceLastOpened(lastOpenedKey)\n lastOpened[workspaceId] = Date.now()\n window.localStorage.setItem(lastOpenedKey, JSON.stringify(lastOpened))\n } catch {\n // Storage unavailable (private mode, quota): the selection lives in memory only.\n }\n },\n }\n}\n\n/** When each workspace was last opened in this browser (`external_id` → epoch ms). */\nexport function readWorkspaceLastOpened(\n lastOpenedKey = WORKSPACE_LAST_OPENED_KEY\n): Record<string, number> {\n try {\n const raw = window.localStorage.getItem(lastOpenedKey)\n const parsed: unknown = raw ? JSON.parse(raw) : null\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed)\n ? (parsed as Record<string, number>)\n : {}\n } catch {\n return {}\n }\n}\n","/**\n * The session state every block reads and writes: the selected workspace, the layout, the chat (the\n * open conversation and its composer, generation per conversation, the context documents and facts)\n * and the documents being viewed and selected.\n *\n * An {@link ArbiSessionStore} is the adapter a host gives as its configuration's `session`. It is\n * made of parts ({@link composeArbiSessionStore}): the layout (`createArbiLayoutStore`), the\n * workspace (`createArbiWorkspaceStore`), the chat (`createArbiChatStore`) and the documents\n * ({@link createArbiDocumentSessionStore}, or a host's own over its state). Hosts without state of\n * their own use {@link createArbiSessionStore}, every part in memory.\n */\n\nimport { parseVersionRef } from '../artifacts/versions'\nimport {\n createArbiChatStore,\n EMPTY_CHAT_STATE,\n type ArbiChatActions,\n type ArbiChatState,\n type ArbiChatStore,\n} from './chat'\nimport type { ArbiDraftStorage } from './drafts'\nimport {\n createArbiLayoutStore,\n defaultLayoutState,\n type ArbiLayoutActions,\n type ArbiLayoutState,\n type ArbiLayoutStore,\n type ArbiSavedLayout,\n} from './layout'\nimport type { ArbiSessionPersist } from './persist'\nimport {\n createArbiWorkspaceStore,\n type ArbiWorkspaceState,\n type ArbiWorkspaceStore,\n} from './workspace'\n\nexport type {\n ArbiConversationDocument,\n ArbiConversationGeneration,\n ArbiMessageTimer,\n TurnTools,\n} from './chat'\n\n/** The document being viewed. */\nexport interface ArbiViewingDocument {\n /** The document (`doc-…`), or a version reference (`doc-…@v2`) while an earlier version shows. */\n id: string\n /** The page being read, when known. */\n page: number | null\n /** The passage being read, when one is. */\n passageId: string | null\n}\n\n/** A tab of the document viewer. */\nexport type ArbiViewerTab = 'pdf' | 'edit' | 'html' | 'docx' | 'xlsx' | 'versions' | 'preview'\n\n/**\n * The document viewer's own state, shared with whatever opens documents (a citation opens the text\n * view, Compare from a documents list opens the redline): the open tab, the document compared with\n * the one viewed, and a tab asked for when a document was opened (applied once it has loaded).\n */\nexport interface ArbiDocumentViewerState {\n tab: ArbiViewerTab\n /** The document (or version reference) compared with the viewed one, or null. */\n compareId: string | null\n /** A tab to show once `documentId` has loaded (a signature request opens on the PDF). */\n tabRequest: { documentId: string; tab: ArbiViewerTab } | null\n /** The text view's size, a multiplier of the normal size: a reading preference. */\n textScale: number\n /** A phone user picked the PDF by hand: documents stop opening on the text view. */\n phonePdfChosen: boolean\n}\n\n/**\n * Where the selected workspace stands on the server session: `opening` while a switch waits for\n * `/open` (the host may cover the page), `open` once workspace-scoped requests may run.\n */\nexport type ArbiWorkspaceStatus = 'closed' | 'opening' | 'open'\n\n/** The documents being viewed and selected. */\nexport interface ArbiDocumentSessionState {\n viewingDocument: ArbiViewingDocument | null\n documentViewer: ArbiDocumentViewerState\n /** The documents selected in document lists. */\n selectedDocumentIds: readonly string[]\n /** The document read in full with each turn (one at a time). */\n pinnedDocumentId: string | null\n}\n\nexport interface ArbiSessionState\n extends ArbiChatState, ArbiDocumentSessionState, ArbiLayoutState, ArbiWorkspaceState {}\n\n/** What to view: page and passage are left unchanged when omitted. */\nexport interface ArbiViewingDocumentInput {\n id: string\n page?: number | null\n passageId?: string | null\n}\n\n/** The documents' changes. */\nexport interface ArbiDocumentSessionActions {\n /**\n * View a document, or none. Viewing another document resets the page; `page` and `passageId`\n * set them when given.\n */\n setViewingDocument(document: ArbiViewingDocumentInput | null): void\n /** Change the document viewer's state; fields not given stay. */\n setDocumentViewer(change: Partial<ArbiDocumentViewerState>): void\n setSelectedDocumentIds(ids: string[]): void\n setPinnedDocumentId(id: string | null): void\n}\n\n/** The documents part of a session store. */\nexport interface ArbiDocumentSessionStore extends ArbiDocumentSessionActions {\n /** The current state. The same object until something in it changes. */\n getState(): ArbiDocumentSessionState\n subscribe(listener: () => void): () => void\n /** The workspace is being left: nothing is viewed, selected or pinned. */\n leave(): void\n}\n\nexport interface ArbiSessionStore\n extends ArbiLayoutActions, ArbiChatActions, ArbiDocumentSessionActions {\n /** The current state. The same object until something in it changes. */\n getState(): ArbiSessionState\n /** Resolves once the saved layout has been read (at once when none is kept). */\n layoutHydrated(): Promise<void>\n /** Whether the saved layout has been read. */\n isLayoutHydrated(): boolean\n /** Be told when the state may have changed. Returns the unsubscribe. */\n subscribe(listener: () => void): () => void\n setWorkspaceId(id: string | null): void\n setWorkspaceStatus(status: ArbiWorkspaceStatus): void\n /**\n * Drop everything scoped to the workspace being left (the open conversation and its generation,\n * the thread tabs, the viewed document, the selection, the context documents and facts), before a\n * switch. A host with workspace-scoped state of its own clears that too.\n */\n leaveWorkspace(): void\n}\n\nexport const DEFAULT_DOCUMENT_VIEWER_STATE: ArbiDocumentViewerState = {\n tab: 'pdf',\n compareId: null,\n tabRequest: null,\n textScale: 1,\n phonePdfChosen: false,\n}\n\nconst EMPTY_DOCUMENT_STATE: ArbiDocumentSessionState = {\n viewingDocument: null,\n documentViewer: DEFAULT_DOCUMENT_VIEWER_STATE,\n selectedDocumentIds: [],\n pinnedDocumentId: null,\n}\n\nexport const EMPTY_SESSION_STATE: ArbiSessionState = {\n workspaceId: null,\n workspaceStatus: 'closed',\n ...EMPTY_CHAT_STATE,\n ...EMPTY_DOCUMENT_STATE,\n ...defaultLayoutState(),\n}\n\n/** The viewed document itself (`doc-…`), also while one of its earlier versions is on screen. */\nexport const selectViewingDocumentId = (state: ArbiSessionState): string | null =>\n state.viewingDocument ? parseVersionRef(state.viewingDocument.id).docId : null\n\n/** The conversation key drafts and context are kept under: its id, or `new` for a new chat. */\nexport const conversationKey = (state: Pick<ArbiChatState, 'conversationId'>): string =>\n state.conversationId ?? 'new'\n\n/** What is typed in the open conversation's composer. */\nexport const selectDraft = (state: Pick<ArbiChatState, 'conversationId' | 'drafts'>): string =>\n state.drafts[conversationKey(state)] ?? ''\n\n/** Whether `conversationId` is generating. */\nexport const selectIsGenerating =\n (conversationId: string | null | undefined) =>\n (state: Pick<ArbiChatState, 'generating'>): boolean =>\n !!conversationId && !!state.generating[conversationId]?.isGenerating\n\n/** The next viewing document, given the current one (shared by every store implementation). */\nexport function nextViewingDocument(\n current: ArbiViewingDocument | null,\n input: ArbiViewingDocumentInput | null\n): ArbiViewingDocument | null {\n if (!input) return null\n const same = current?.id === input.id\n return {\n id: input.id,\n page: input.page !== undefined ? input.page : same ? (current?.page ?? null) : null,\n passageId: input.passageId !== undefined ? input.passageId : (current?.passageId ?? null),\n }\n}\n\n/** The documents part in memory. */\nexport function createArbiDocumentSessionStore(\n initial: Partial<ArbiDocumentSessionState> = {}\n): ArbiDocumentSessionStore {\n let state: ArbiDocumentSessionState = { ...EMPTY_DOCUMENT_STATE, ...initial }\n const listeners = new Set<() => void>()\n const update = (patch: Partial<ArbiDocumentSessionState>) => {\n state = { ...state, ...patch }\n listeners.forEach((listener) => listener())\n }\n return {\n getState: () => state,\n subscribe: (listener) => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n setViewingDocument: (input) =>\n update({ viewingDocument: nextViewingDocument(state.viewingDocument, input) }),\n setDocumentViewer: (change) => {\n const next = { ...state.documentViewer, ...change }\n const keys = Object.keys(change) as (keyof ArbiDocumentViewerState)[]\n if (keys.some((key) => next[key] !== state.documentViewer[key]))\n update({ documentViewer: next })\n },\n setSelectedDocumentIds: (ids) => update({ selectedDocumentIds: ids }),\n setPinnedDocumentId: (pinnedDocumentId) => update({ pinnedDocumentId }),\n leave: () => update({ viewingDocument: null, selectedDocumentIds: [], pinnedDocumentId: null }),\n }\n}\n\n/** The layout actions of a session store, on its layout store. */\nexport function layoutActionsOf(layout: ArbiLayoutStore): ArbiLayoutActions {\n const actions = { ...layout } as Partial<ArbiLayoutStore>\n delete actions.getLayout\n delete actions.subscribe\n delete actions.hydrated\n delete actions.isHydrated\n delete actions.reset\n delete actions.threads\n return actions as ArbiLayoutActions\n}\n\n/** The chat actions of a session store, on its chat store. */\nfunction chatActionsOf(chat: ArbiChatStore): ArbiChatActions {\n const actions = { ...chat } as Partial<ArbiChatStore>\n delete actions.getState\n delete actions.subscribe\n delete actions.settled\n delete actions.forget\n delete actions.batch\n delete actions.hydrated\n delete actions.isHydrated\n delete actions.restoreDrafts\n delete actions.leave\n delete actions.reset\n return actions as ArbiChatActions\n}\n\n/** The parts a session store is made of. */\nexport interface ArbiSessionParts {\n layout: ArbiLayoutStore\n workspace: ArbiWorkspaceStore\n chat: ArbiChatStore\n documents: ArbiDocumentSessionStore\n}\n\n/**\n * A session store made of its parts: its state is theirs, and readers are told once per change (a\n * thread tab change moves the layout and the chat: once, after both).\n */\nexport function composeArbiSessionStore({\n layout,\n workspace,\n chat,\n documents,\n}: ArbiSessionParts): ArbiSessionStore {\n let last: { parts: readonly unknown[]; state: ArbiSessionState } | null = null\n const getState = (): ArbiSessionState => {\n const parts = [\n layout.getLayout(),\n workspace.getState(),\n documents.getState(),\n chat.getState(),\n ] as const\n // The same object while no part has changed (useSyncExternalStore).\n if (last && parts.every((part, i) => part === last!.parts[i])) return last.state\n const [l, w, d, c] = parts\n last = { parts, state: { ...l, ...w, ...d, ...c } }\n return last.state\n }\n // A workspace opens once signed in: the key that opens the saved drafts is there then.\n chat.restoreDrafts()\n workspace.subscribe(() => chat.restoreDrafts())\n return {\n ...layoutActionsOf(layout),\n ...chatActionsOf(chat),\n getState,\n layoutHydrated: () => layout.hydrated(),\n isLayoutHydrated: () => layout.isHydrated(),\n subscribe: (onChange) => {\n const told = chat.settled(onChange)\n const unsubscribe = [\n chat.subscribe(onChange),\n layout.subscribe(told),\n workspace.subscribe(told),\n documents.subscribe(told),\n ]\n return () => {\n chat.forget(onChange)\n unsubscribe.forEach((stop) => stop())\n }\n },\n setWorkspaceId: (id) => workspace.setWorkspaceId(id),\n setWorkspaceStatus: (status) => workspace.setWorkspaceStatus(status),\n leaveWorkspace: () =>\n chat.batch(() => {\n workspace.setWorkspaceStatus('closed')\n chat.leave()\n documents.leave()\n }),\n setViewingDocument: (input) => documents.setViewingDocument(input),\n setDocumentViewer: (change) => documents.setDocumentViewer(change),\n setSelectedDocumentIds: (ids) => documents.setSelectedDocumentIds(ids),\n setPinnedDocumentId: (id) => documents.setPinnedDocumentId(id),\n }\n}\n\n/** Options of {@link createArbiSessionStore}. */\nexport interface ArbiSessionStoreOptions {\n /** Keep the composers' drafts across reloads (see {@link createSealedDraftStorage}). */\n draftStorage?: ArbiDraftStorage\n /** Keep the layout across reloads (see {@link createStoragePersist}). */\n persist?: ArbiSessionPersist<ArbiSavedLayout>\n /**\n * The selected workspace and its status (default: in memory, from `initial.workspaceId`). Give\n * one kept per tab (`createArbiWorkspaceStore({ storage: browserWorkspaceStorage() })`) for a\n * reload to stay in the workspace.\n */\n workspace?: ArbiWorkspaceStore\n}\n\n/** An in-memory session store: the default for hosts without state of their own. */\nexport function createArbiSessionStore(\n initial: Partial<ArbiSessionState> = {},\n {\n draftStorage,\n persist,\n workspace = createArbiWorkspaceStore({ workspaceId: initial.workspaceId ?? null }),\n }: ArbiSessionStoreOptions = {}\n): ArbiSessionStore {\n const {\n shell,\n tabs,\n views,\n grid,\n workspaceStatus,\n viewingDocument,\n documentViewer,\n selectedDocumentIds,\n pinnedDocumentId,\n ...chatInitial\n } = initial\n // The workspace is the workspace store's.\n delete (chatInitial as Partial<ArbiSessionState>).workspaceId\n const defined = <T extends object>(parts: T): Partial<T> =>\n Object.fromEntries(Object.entries(parts).filter(([, part]) => part !== undefined)) as Partial<T>\n const layout = createArbiLayoutStore({ persist, initial: defined({ shell, tabs, views, grid }) })\n if (workspaceStatus) workspace.setWorkspaceStatus(workspaceStatus)\n return composeArbiSessionStore({\n layout,\n workspace,\n chat: createArbiChatStore({ layout, draftStorage, initial: chatInitial }),\n documents: createArbiDocumentSessionStore(\n defined({ viewingDocument, documentViewer, selectedDocumentIds, pinnedDocumentId })\n ),\n })\n}\n","/**\n * The composers' drafts kept across reloads: stored locally and encrypted, sealed to the signed-in\n * person's own key like the other data kept on the device, so nothing typed is readable at rest.\n *\n * Bound to the person: a record is kept under the user it belongs to and opened only while that\n * user is signed in (`owner`), never by whoever's key happens to be on the device, so a signed-out\n * page, a demo session or another account never sees it. Like the offline mail, the drafts never\n * outlive the session: a sign-out clears them (`clearSealedDrafts`).\n */\n\nimport { getUserEncryptionKeypair, sealedBoxDecrypt, sealedBoxEncrypt } from '@arbidocs/client'\n\n/** Where a session store keeps its drafts (see `createArbiSessionStore`). */\nexport interface ArbiDraftStorage {\n /** The saved drafts, or null while they cannot be opened yet (no one is signed in). */\n load(): Promise<Record<string, string> | null>\n /** Save the drafts (all of them: the record replaces what was saved). */\n save(drafts: Readonly<Record<string, string>>): void\n /** Who the drafts belong to now: the signed-in user, `null` signed out. */\n owner(): string | null\n /** Forget the saved drafts and any write still pending (the session ended). */\n clear(): void\n /** Be told when the drafts were cleared (the session store drops its copy). */\n onClear(listener: () => void): () => void\n}\n\n/** A key-value store the drafts are written to (`localStorage` by default). */\nexport interface DraftKeyValueStore {\n getItem(key: string): string | null\n setItem(key: string, value: string): void\n removeItem(key: string): void\n}\n\n/** How long typing settles before the drafts are written. */\nconst SAVE_DELAY_MS = 500\n\nconst encoder = new TextEncoder()\nconst decoder = new TextDecoder()\n\n/** What is stored: the drafts sealed to the owner's key, and who the owner is. */\ninterface StoredDrafts {\n owner: string\n sealed: string\n}\n\nfunction parseStored(raw: string | null): StoredDrafts | null {\n if (!raw) return null\n try {\n const parsed = JSON.parse(raw) as Partial<StoredDrafts> | null\n return parsed && typeof parsed.owner === 'string' && typeof parsed.sealed === 'string'\n ? { owner: parsed.owner, sealed: parsed.sealed }\n : null\n } catch {\n return null\n }\n}\n\n/** Every sealed draft storage made on this page, so a sign-out clears them all. */\nconst storages = new Set<ArbiDraftStorage>()\n\n/** The session ended (sign-out, or it could not be recovered): clear every saved draft. */\nexport function clearSealedDrafts(): void {\n for (const storage of [...storages]) storage.clear()\n}\n\nexport interface SealedDraftStorageOptions {\n /** The record's key in `storage`. */\n key?: string\n storage?: DraftKeyValueStore\n /**\n * The signed-in user (a stable id, e.g. the user's external id), `null` when no one is: the\n * drafts are opened and written only for them.\n */\n owner: () => string | null\n}\n\n/**\n * Drafts sealed to the signed-in person's key, in `storage` under `key`, for `owner` only. A record\n * of another user is removed unread; one that cannot be opened (damaged) reads as no drafts.\n */\nexport function createSealedDraftStorage({\n key = 'arbi-drafts',\n storage = typeof localStorage === 'undefined' ? undefined : localStorage,\n owner,\n}: SealedDraftStorageOptions): ArbiDraftStorage {\n let timer: ReturnType<typeof setTimeout> | undefined\n // Bumped by clear(): a write that started before it never lands after it.\n let generation = 0\n const listeners = new Set<() => void>()\n\n const remove = () => {\n try {\n storage?.removeItem(key)\n } catch {\n // Storage blocked: nothing was kept either.\n }\n }\n\n const write = async (drafts: Readonly<Record<string, string>>, written: number) => {\n if (!storage) return\n try {\n const user = owner()\n if (!user) return\n if (Object.keys(drafts).length === 0) {\n if (parseStored(storage.getItem(key))?.owner === user) storage.removeItem(key)\n return\n }\n const keypair = await getUserEncryptionKeypair()\n if (!keypair || written !== generation || owner() !== user) return\n // A plain Uint8Array of this realm, which is what the sealing accepts.\n const plain = Uint8Array.from(encoder.encode(JSON.stringify(drafts)))\n const record: StoredDrafts = {\n owner: user,\n sealed: sealedBoxEncrypt(plain, keypair.publicKey),\n }\n storage.setItem(key, JSON.stringify(record))\n } catch {\n // Storage full or blocked: the drafts stay in memory for this visit.\n }\n }\n\n const draftStorage: ArbiDraftStorage = {\n owner,\n load: async () => {\n const user = owner()\n if (!user) return null\n const keypair = await getUserEncryptionKeypair()\n if (!keypair || owner() !== user) return null\n try {\n const raw = storage?.getItem(key) ?? null\n if (!raw) return {}\n const stored = parseStored(raw)\n if (!stored || stored.owner !== user) {\n // Another user's (or an unreadable) record is not this person's to keep or open.\n remove()\n return {}\n }\n const plain = sealedBoxDecrypt(stored.sealed, keypair.secretKey)\n const drafts = JSON.parse(decoder.decode(plain)) as unknown\n if (!drafts || typeof drafts !== 'object') return {}\n return Object.fromEntries(\n Object.entries(drafts).filter((entry): entry is [string, string] => {\n return typeof entry[1] === 'string'\n })\n )\n } catch {\n return {}\n }\n },\n save: (drafts) => {\n clearTimeout(timer)\n const written = generation\n timer = setTimeout(() => void write(drafts, written), SAVE_DELAY_MS)\n },\n clear: () => {\n clearTimeout(timer)\n timer = undefined\n generation++\n remove()\n for (const listener of [...listeners]) listener()\n },\n onClear: (listener) => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n }\n storages.add(draftStorage)\n return draftStorage\n}\n","/**\n * The session state the blocks share (see `./store`). A host passes its own {@link ArbiSessionStore}\n * as the host configuration's `session` (ARBI-frontend backs it with its zustand store). Without\n * one, each top-level `<ArbiHost>` keeps an in-memory one, and blocks rendered with no host share a\n * module default, so a standalone block still coordinates with its siblings. A host's own store\n * keeps the composers' drafts across reloads, sealed to the person signed in on the host's `Arbi`\n * and only for them; the module default (no host, so no one signed in) keeps them in memory.\n */\n\nimport { useCallback, useSyncExternalStore } from 'react'\nimport { useArbiHost, type ArbiHostConfig } from '../host/config'\nimport { OWN_SESSION_SLOT } from '../host/merge'\nimport { createArbiSessionStore, type ArbiSessionState, type ArbiSessionStore } from './store'\nimport { createSealedDraftStorage } from './drafts'\n\n/** Who is signed in on the host's `Arbi` (its session), `null` when no one is. */\nfunction signedInUser(host: ArbiHostConfig): string | null {\n const state = host.arbi?.session?.getState()\n return state?.signedIn && state.userExtId ? state.userExtId : null\n}\n\n/** A host's own session: in memory, with its drafts kept sealed for the signed-in person. */\nconst createOwnStore = (host: ArbiHostConfig) =>\n createArbiSessionStore(\n {},\n { draftStorage: createSealedDraftStorage({ owner: () => signedInUser(host) }) }\n )\n\nlet moduleDefault: ArbiSessionStore | null = null\nconst defaultStore = () => (moduleDefault ??= createArbiSessionStore())\n\n/** The session store: its setters, and `getState()` for the state as of now (in callbacks). */\nexport function useArbiSessionStore(): ArbiSessionStore {\n const host = useArbiHost()\n if (host.session) return host.session\n const own = (host as Record<string, unknown>)[OWN_SESSION_SLOT] as\n { current: ArbiSessionStore | null } | undefined\n if (own) return (own.current ??= createOwnStore(host))\n return defaultStore()\n}\n\n/**\n * A slice of the session state; re-renders when it changes. The selector returns a value from the\n * state or a primitive (a new object each call would never settle).\n */\nexport function useArbiSessionState<T>(selector: (state: ArbiSessionState) => T): T {\n const store = useArbiSessionStore()\n const select = () => selector(store.getState())\n return useSyncExternalStore(store.subscribe, select, select)\n}\n\n/**\n * A view setting kept in the session and saved across reloads (`views.values`: a page's view\n * mode, a zoom, a filter box's text), and its setter. `fallback` while none is set.\n */\nexport function useSessionView<T>(key: string, fallback: T): [T, (value: T) => void] {\n const store = useArbiSessionStore()\n const value = useArbiSessionState((state) => state.views.values[key]) as T | undefined\n const set = useCallback((next: T) => store.setViewValue(key, next), [store, key])\n return [value === undefined ? fallback : value, set]\n}\n\n/**\n * View state kept for this session only (`views.transient`: a search's results, a one-shot\n * request), and its setter (`undefined` drops it). `fallback` while none is set.\n */\nexport function useTransientView<T>(key: string, fallback: T): [T, (value: T | undefined) => void] {\n const store = useArbiSessionStore()\n const value = useArbiSessionState((state) => state.views.transient[key]) as T | undefined\n const set = useCallback((next: T | undefined) => store.setTransientView(key, next), [store, key])\n return [value === undefined ? fallback : value, set]\n}\n\n/** A page's selected tab, kept across reloads; the host supplies its default tab. */\nexport function useSessionPageTab(\n page: string,\n fallback: string\n): {\n activeTab: string\n setActiveTab: (tab: string) => void\n} {\n const store = useArbiSessionStore()\n const activeTab = useArbiSessionState((state) => state.views.tabs[page]) || fallback\n const setActiveTab = useCallback((tab: string) => store.setPageTab(page, tab), [store, page])\n return { activeTab, setActiveTab }\n}\n","/**\n * Who is signed in: the host `Arbi`'s session (`arbi.session`, the client's session state), the\n * one source for the user, the sign-in status and the SSO mode. Re-renders when it changes.\n */\n\nimport { useMemo, useSyncExternalStore } from 'react'\nimport type { SessionManager, SessionState, SessionUser } from '@arbidocs/client'\nimport { useArbiHost } from '../host/config'\n\nexport type ArbiSessionStatus = 'signed-out' | 'signed-in'\n\nexport interface ArbiSignedInSession {\n /** `signed-in` once a login finished on this device (also before this tab has a token). */\n status: ArbiSessionStatus\n /** The signed-in user; `null` signed out. */\n user: SessionUser | null\n /** The account signs in through SSO. */\n isSso: boolean\n /** This tab holds a server session (a token). A new tab or an offline unlock does not, yet. */\n hasToken: boolean\n /** The server session key workspace keys are sealed to; `null` until known. */\n serverSessionKey: Uint8Array | null\n}\n\nconst SIGNED_OUT: ArbiSignedInSession = {\n status: 'signed-out',\n user: null,\n isSso: false,\n hasToken: false,\n serverSessionKey: null,\n}\n\nconst noSubscription = () => () => {}\n\n/** The signed-in session of the host's `Arbi`; signed out without one. */\nexport function useArbiSession(): ArbiSignedInSession {\n return useSignedInSession(useArbiHost().arbi?.session ?? null)\n}\n\n/** The same for a session the caller holds (the host building its `Arbi` on it). */\nexport function useSignedInSession(session: SessionManager | null): ArbiSignedInSession {\n const state = useSyncExternalStore<SessionState | null>(\n session ? session.subscribe : noSubscription,\n () => session?.getState() ?? null,\n () => session?.getState() ?? null\n )\n return useMemo(\n () =>\n state?.signedIn\n ? {\n status: 'signed-in',\n user: state.user,\n isSso: state.isSsoMode,\n hasToken: !!state.accessToken,\n serverSessionKey: state.serverSessionKey,\n }\n : { ...SIGNED_OUT, isSso: state?.isSsoMode ?? false },\n [state]\n )\n}\n","/**\n * Keeping the session's layout across reloads: a host gives the session store a\n * {@link ArbiSessionPersist} (where the saved layout is read and written), and the store reads it\n * once at start and writes it after each change. {@link createStoragePersist} makes one from any\n * key-value storage (IndexedDB, `localStorage`), writing at most once per quiet period and on page\n * exit, so a stream of changes (dragging a column) is one write and a reload never loses the last.\n */\n\n/** Where a session store keeps its saved layout. */\nexport interface ArbiSessionPersist<T = unknown> {\n /** The saved value, or null when none (or it cannot be read). Never rejects. */\n load(): Promise<T | null>\n /** Save the latest value (may be written later; the latest one wins). */\n save(value: T): void\n /** Forget the saved value (signing out). */\n clear?(): Promise<void>\n}\n\n/** A key-value storage, asynchronous or not (IndexedDB, `localStorage`). */\nexport interface ArbiKeyValueStorage {\n get(key: string): Promise<string | null> | string | null\n set(key: string, value: string): Promise<void> | void\n remove(key: string): Promise<void> | void\n}\n\nexport interface DebouncedWriterOptions {\n /** Performs the write. Errors are reported through `onError`, never thrown to the caller. */\n write: (key: string, value: string) => Promise<void> | void\n /** Trailing-edge quiet period. */\n delayMs: number\n /** Longest a pending value may wait from its first unwritten change. */\n maxWaitMs: number\n onError?: (key: string, error: unknown) => void\n}\n\nexport interface DebouncedWriter {\n /** Queue `value` as the latest value of `key`. */\n schedule: (key: string, value: string) => void\n /** The value queued for `key` but not yet written, if any. */\n pending: (key: string) => string | undefined\n /** Drop the queued value of `key` without writing it. */\n cancel: (key: string) => void\n /** Write every queued value now. */\n flushAll: () => void\n}\n\ninterface Pending {\n value: string\n timer: ReturnType<typeof setTimeout>\n /** When the first change not yet written was queued. */\n firstQueuedAt: number\n}\n\n/**\n * Per-key debounced writer. Rapid successive writes of one key collapse into a single\n * trailing-edge write `delayMs` after the last call; `maxWaitMs` caps how long a steady stream of\n * changes can postpone it.\n */\nexport function createDebouncedWriter({\n write,\n delayMs,\n maxWaitMs,\n onError,\n}: DebouncedWriterOptions): DebouncedWriter {\n const queue = new Map<string, Pending>()\n\n const run = (key: string, value: string) => {\n try {\n void Promise.resolve(write(key, value)).catch((error: unknown) => onError?.(key, error))\n } catch (error) {\n onError?.(key, error)\n }\n }\n\n const flush = (key: string) => {\n const entry = queue.get(key)\n if (!entry) return\n clearTimeout(entry.timer)\n queue.delete(key)\n run(key, entry.value)\n }\n\n return {\n schedule(key, value) {\n const now = Date.now()\n const existing = queue.get(key)\n if (existing) clearTimeout(existing.timer)\n const firstQueuedAt = existing?.firstQueuedAt ?? now\n const wait = Math.max(0, Math.min(delayMs, firstQueuedAt + maxWaitMs - now))\n queue.set(key, { value, firstQueuedAt, timer: setTimeout(() => flush(key), wait) })\n },\n pending: (key) => queue.get(key)?.value,\n cancel(key) {\n const entry = queue.get(key)\n if (!entry) return\n clearTimeout(entry.timer)\n queue.delete(key)\n },\n flushAll() {\n for (const key of Array.from(queue.keys())) flush(key)\n },\n }\n}\n\n/**\n * Flush `writer` whenever the page may be about to go away: `pagehide`, `visibilitychange` to\n * hidden (often the last event a mobile browser delivers) and `beforeunload`. Returns a function\n * that removes the listeners.\n */\nexport function flushOnPageExit(writer: Pick<DebouncedWriter, 'flushAll'>): () => void {\n if (typeof window === 'undefined' || typeof document === 'undefined') return () => {}\n const flush = () => writer.flushAll()\n const onVisibility = () => {\n if (document.visibilityState === 'hidden') writer.flushAll()\n }\n window.addEventListener('beforeunload', flush)\n window.addEventListener('pagehide', flush)\n document.addEventListener('visibilitychange', onVisibility)\n return () => {\n window.removeEventListener('beforeunload', flush)\n window.removeEventListener('pagehide', flush)\n document.removeEventListener('visibilitychange', onVisibility)\n }\n}\n\nexport interface StoragePersistOptions<T> {\n storage: ArbiKeyValueStorage\n /** The storage key. */\n key: string\n /** Read a value saved under `key` by an earlier build (default: as JSON). Never throws. */\n parse?: (saved: unknown) => T | null\n /**\n * Bring in what an earlier build saved elsewhere: called on every load with what is saved under\n * `key` (null: nothing yet), it returns the value to start from. A value other than the one given\n * is saved under `key` at once, so each piece is brought in once.\n */\n migrate?: (saved: T | null) => Promise<T | null>\n /** Quiet period before a write (default 250 ms), and the longest wait (default 1 s). */\n delayMs?: number\n maxWaitMs?: number\n}\n\n/** A {@link ArbiSessionPersist} on a key-value storage, debounced and flushed on page exit. */\nexport function createStoragePersist<T>({\n storage,\n key,\n parse = (saved) => saved as T,\n migrate,\n delayMs = 250,\n maxWaitMs = 1000,\n}: StoragePersistOptions<T>): ArbiSessionPersist<T> {\n const writer = createDebouncedWriter({\n write: (k, value) => storage.set(k, value),\n delayMs,\n maxWaitMs,\n onError: (k, error) => console.error(`[session] Failed to save ${k}:`, error),\n })\n flushOnPageExit(writer)\n const read = async (): Promise<T | null> => {\n // A queued write is the latest value.\n const pending = writer.pending(key)\n const raw = pending ?? (await storage.get(key))\n if (raw === null || raw === undefined) return null\n return parse(JSON.parse(raw))\n }\n return {\n async load() {\n try {\n const saved = await read()\n if (!migrate) return saved\n const migrated = await migrate(saved)\n if (migrated !== null && migrated !== saved)\n await storage.set(key, JSON.stringify(migrated))\n return migrated\n } catch (error) {\n console.warn('[session] The saved layout could not be read; starting from defaults', error)\n return null\n }\n },\n save: (value) => writer.schedule(key, JSON.stringify(value)),\n async clear() {\n writer.cancel(key)\n await storage.remove(key)\n },\n }\n}\n","/**\n * AI usage is reported in pounds (ex VAT).\n *\n * The usage endpoints (`/v1/user/projects/{id}/usage`, `/me/usage/today`) convert the metered\n * LiteLLM USD spend into £ at the API boundary (fractional, rounded to 2 decimals). The fields are\n * still named `spend` / `total_spend` in the schema, but they hold £, never dollars. Format them\n * with `formatGbp` (re-exported from `@arbidocs/sdk`).\n */\n\n/** The slice of a usage response that tells whether anything was recorded. */\nexport interface UsageTotals {\n total_spend: number\n total_tokens: number\n total_requests: number\n}\n\n/**\n * Was this usage actually metered? A `dev`-plan project with an all-zero response (no spend, no\n * tokens, no requests) is treated as \"not metered\", so the UI shows a note instead of silent\n * zeros. Any recorded tokens or requests mean usage was metered, even when the spend rounds to 0\n * (the backend records usage when billing is off, and a tiny spend can be £0.00).\n */\nexport function isUsageMetered(\n usage: UsageTotals,\n subscription: string | null | undefined\n): boolean {\n const empty = usage.total_spend === 0 && usage.total_tokens === 0 && usage.total_requests === 0\n return !(empty && subscription === 'dev')\n}\n","/**\n * React Query hooks that use the Arbi instance from context.\n */\n\nimport { useEffect, useMemo, useRef } from 'react'\nimport {\n useInfiniteQuery,\n useQuery,\n useQueries,\n useMutation,\n useQueryClient,\n} from '@tanstack/react-query'\nimport {\n type AskHandlers,\n type AskRequest,\n type SSEStreamResult,\n type TagListQuery,\n type ThreadsResponse,\n} from '@arbidocs/sdk/browser'\nimport { useArbi } from './useArbi'\nimport { useArbiSessionStore } from './session'\nimport type { ParsedDocument } from './documents/parsed-types'\nimport { isUsageMetered } from './usage-metered'\nimport { parseVersionRef } from './artifacts/versions'\n\n// ── Query keys ──────────────────────────────────────────────────────────────\n\n// The one key factory (every query and mutation key of the packages and the app): ./query-keys.\nexport { arbiQueryKeys, arbiMutationKeys } from './query-keys'\nimport { arbiQueryKeys } from './query-keys'\n\n// ── Hooks ───────────────────────────────────────────────────────────────────\n\n/** List the logged-in user's workspaces. */\nexport function useWorkspaces(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.workspaces(),\n queryFn: () => arbi.workspaces.list(),\n enabled: (options?.enabled ?? true) && arbi.isLoggedIn,\n })\n}\n\n/** Every version of the document `docId`, oldest first (`is_current` marks the current one). */\nexport function useDocumentVersionList(\n docId: string | null | undefined,\n options?: { enabled?: boolean }\n) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.documentVersions(docId ?? ''),\n queryFn: () => arbi.documents.versions(docId as string),\n enabled: (options?.enabled ?? true) && !!docId && arbi.hasWorkspace,\n })\n}\n\n/**\n * A workspace's conversations (threads and tasks). The list is kept current by its writers and the\n * workspace's events (`conversation-list`), so it is not re-read on every mount; `live` re-reads it\n * on a timer instead, faster while something is generating, for a view that follows runs by itself.\n */\nexport function useConversations(\n workspaceId: string | undefined,\n options?: { enabled?: boolean; live?: boolean }\n) {\n const arbi = useArbi()\n const live = options?.live === true\n return useQuery({\n queryKey: arbiQueryKeys.conversations(workspaceId ?? ''),\n queryFn: () => arbi.readInWorkspace(workspaceId as string, () => arbi.conversations.list()),\n enabled: (options?.enabled ?? true) && !!workspaceId && arbi.hasWorkspace,\n placeholderData: (previous) => previous,\n ...(live\n ? {\n refetchInterval: (query: { state: { data?: Array<{ status?: string | null }> } }) =>\n query.state.data?.some((conversation) => conversation.status === 'generating')\n ? 3000\n : 15000,\n }\n : { staleTime: Infinity, refetchOnMount: false, refetchOnReconnect: false }),\n })\n}\n\n/** The backend's built-in slash commands (`/compact`, `/goal`, …), for a slash menu. */\nexport function useBuiltinCommands() {\n const arbi = useArbi()\n const query = useQuery({\n queryKey: arbiQueryKeys.assistantCommands(),\n queryFn: () => arbi.assistant.commands(),\n staleTime: 30 * 1000,\n enabled: arbi.isLoggedIn,\n })\n // Stable identity so a menu's merge and filter memos do not rerun every render.\n const commands = useMemo(() => query.data ?? [], [query.data])\n return { commands, isLoading: query.isLoading }\n}\n\n/** One stored message with everything the server keeps on it (its trace and metadata). */\nexport function useMessageDetails(\n messageId: string | null | undefined,\n options?: { enabled?: boolean }\n) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.messageDetails(messageId ?? ''),\n queryFn: () => arbi.conversations.getMessage(messageId as string),\n enabled: (options?.enabled ?? true) && !!messageId && arbi.isLoggedIn,\n })\n}\n\n/**\n * A conversation's stored threads (each with its message history, citations data included). The\n * chat engine and the conversation's events keep the cache current, so it is re-read only when\n * stale (2 minutes) or when the page is shown again while this tab is not streaming the\n * conversation (a turn sent from another tab never reaches this one's socket). A conversation with\n * no messages yet (a new to-do, a workflow's task before its run) comes back with no threads. A 404\n * is a conversation this user cannot see (gone, or in a workspace they left): an error, never cached\n * as an empty conversation to write into. `live` re-reads it every few seconds.\n */\nexport function useConversationThreads(\n conversationId: string | undefined,\n options?: { enabled?: boolean; live?: boolean }\n) {\n const arbi = useArbi()\n const session = useArbiSessionStore()\n return useQuery({\n queryKey: arbiQueryKeys.conversationThreads(conversationId ?? ''),\n queryFn: (): Promise<ThreadsResponse> =>\n arbi.conversations.getThreads(conversationId as string),\n enabled: (options?.enabled ?? true) && !!conversationId && arbi.hasWorkspace,\n staleTime: 2 * 60 * 1000,\n refetchOnWindowFocus: () =>\n session.getState().generating[conversationId ?? '']?.isGenerating ? false : 'always',\n refetchInterval: options?.live ? 3000 : false,\n })\n}\n\n/** A tag list query as a stable cache key ('' for every tag). */\nconst tagListKey = (query: TagListQuery): string =>\n [\n query.kind ? `kind:${query.kind}` : '',\n query.parentId ? `parent:${query.parentId}` : '',\n query.ids?.length ? `ids:${query.ids.join(',')}` : '',\n query.include?.length ? `include:${query.include.join(',')}` : '',\n query.linksLimit !== undefined ? `links:${query.linksLimit}` : '',\n ]\n .filter(Boolean)\n .join('|')\n\n/**\n * List tags in a workspace (default: the open one) — all of them, or filtered: `{ kind: 'issue',\n * include: ['links'] }` is every issue with its documents, facts and threads (a table's rows; its\n * columns come from `useTagKindSchema`). `ids: []` asks for nothing.\n *\n * The whole list is read once and then kept current in place: the tag writes patch it\n * (`patchWorkspaceTags`), and an invalidation of the workspace's tags (a WebSocket event, a host\n * refresh) re-reads it. It is never re-read just for being mounted or the window being focused.\n */\nexport function useTags(\n workspaceId?: string | null,\n options?: TagListQuery & { enabled?: boolean }\n) {\n const arbi = useArbi()\n const { enabled, ...query } = options ?? {}\n const workspace = workspaceId ?? (arbi.hasWorkspace ? arbi.getWorkspaceId() : '')\n const key = tagListKey(query)\n return useQuery({\n queryKey: key ? arbiQueryKeys.tagList(workspace, key) : arbiQueryKeys.tags(workspace),\n // The request names the workspace (opened for this session first when it is not the current\n // one), so another workspace's tags can be listed and a switch cannot answer for it. The\n // current workspace's list is also read under the switch guard.\n queryFn: () => {\n const list = () => arbi.tags.list({ ...(key ? query : {}), workspaceId: workspace })\n return workspace === arbi.getWorkspaceId() ? arbi.readInWorkspace(workspace, list) : list()\n },\n enabled:\n (enabled ?? true) &&\n !!workspace &&\n arbi.hasWorkspace &&\n (query.ids === undefined || query.ids.length > 0),\n ...(key ? {} : { staleTime: Infinity }),\n })\n}\n\n/**\n * Batch-fetch first-page thumbnails for a set of documents. Returns a map of\n * doc external id → `data:image/webp` URI (or `null` when no thumbnail exists).\n * Cached for a few minutes since thumbnails are effectively immutable per doc.\n */\nexport function useThumbnails(docIds: string[], options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.thumbnails(docIds),\n queryFn: () => arbi.documents.getThumbnails(docIds),\n enabled: (options?.enabled ?? true) && docIds.length > 0 && arbi.hasWorkspace,\n staleTime: 5 * 60_000,\n })\n}\n\n/**\n * Fetch a document's parsed content (chunks grouped by page) for the review\n * viewer. `stage` defaults to `final` (fully processed); `marker`/`subchunk`\n * expose earlier pipeline stages. `docId` may be a version reference (`doc-…@v2`).\n */\nexport function useParsedDocument(\n docId: string | undefined,\n stage: string = 'final',\n options?: { enabled?: boolean }\n) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.parsedDoc(docId ?? '', stage),\n queryFn: () => {\n // A version reference (`doc-…@v2`) reads that version's parse.\n const { docId: id, version } = parseVersionRef(docId as string)\n return arbi.documents.getParsedContent(\n id,\n stage,\n version ?? undefined\n ) as unknown as Promise<ParsedDocument>\n },\n enabled: (options?.enabled ?? true) && !!docId && arbi.hasWorkspace,\n })\n}\n\n/**\n * Ask the assistant (`arbi.assistant.ask`) as a mutation: one streaming turn, its frames to\n * `handlers`, resolving with the accumulated result.\n */\nexport function useAssistantQuery() {\n const arbi = useArbi()\n return useMutation<SSEStreamResult, Error, { request: AskRequest; handlers?: AskHandlers }>({\n mutationFn: ({ request, handlers }) => arbi.assistant.ask(request, handlers),\n })\n}\n\n/** List agents owned by the current user. */\nexport function useAgents(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.agents(),\n queryFn: () => arbi.agents.list(),\n enabled: (options?.enabled ?? true) && arbi.isLoggedIn,\n })\n}\n\n/**\n * Delete agents. Returns a mutation. Refreshes the agent list, the workflow list and the conversation list\n * (a deleted agent's workflows and work go with it), and drops the deleted agents' own config and workspace queries.\n */\nexport function useDeleteAgents() {\n const arbi = useArbi()\n const qc = useQueryClient()\n return useMutation<unknown, Error, { agentExtIds: string[] }>({\n mutationFn: ({ agentExtIds }) => arbi.agents.delete(agentExtIds),\n onSuccess: (_result, { agentExtIds }) => {\n for (const id of agentExtIds) {\n qc.removeQueries({ queryKey: arbiQueryKeys.agentConfig(id) })\n qc.removeQueries({ queryKey: arbiQueryKeys.agentWorkspaces(id) })\n }\n return Promise.all([\n qc.invalidateQueries({ queryKey: arbiQueryKeys.agents() }),\n qc.invalidateQueries({ queryKey: arbiQueryKeys.workflows() }),\n qc.invalidateQueries({ queryKey: arbiQueryKeys.allConversations() }),\n qc.invalidateQueries({ queryKey: arbiQueryKeys.configs() }),\n ])\n },\n })\n}\n\n/** Authorize a delegated session (generates claim code). Returns a mutation. */\n\n/** Check backend health. */\nexport function useHealth(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.health(),\n queryFn: () => arbi.health.check(),\n enabled: options?.enabled,\n })\n}\n\n/**\n * The deployment's models with their tags (`Standard`, `Premium`), providers and per-token costs,\n * and the default premium model. Static per deployment: read once.\n */\nexport function useAvailableModels(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.availableModels(),\n queryFn: () => arbi.health.models(),\n staleTime: Infinity,\n enabled: (options?.enabled ?? true) && arbi.isLoggedIn,\n })\n}\n\n// ── Behaviour-template configs ───────────────────────────────────────────────\n\n/** List the caller's saved agent configurations (behaviour templates). */\nexport function useConfigs(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.configVersions(),\n queryFn: () => arbi.agentConfig.list(),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n })\n}\n\n/** One saved agent configuration (its models, its tools). Configs change only on a save. */\nexport function useConfig(configId: string | null | undefined, options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.config(configId ?? ''),\n queryFn: () => arbi.agentConfig.get(configId as string),\n staleTime: 10 * 60 * 1000,\n enabled: (options?.enabled ?? true) && !!configId && arbi.isLoggedIn,\n })\n}\n\n// ── Activity feed ─────────────────────────────────────────────────────────────\n\n/**\n * List the caller's durable activity feed, newest first.\n *\n * Activity entries are backend-originated, to-self log lines that are always\n * read — they are deliberately kept out of the normal notifications/DM feed and\n * never affect the unread badge, so this is a separate, opt-in query.\n */\nexport function useActivity(options?: { enabled?: boolean; limit?: number; offset?: number }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.activity(),\n queryFn: () => arbi.dm.listActivity({ limit: options?.limit, offset: options?.offset }),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n })\n}\n\n/**\n * A workspace's activity feed, newest first, a page at a time: thread history, people posting,\n * uploads, new versions and signatures, workflow runs. Only what the caller can see. The pages\n * are `data.pages`; `fetchNextPage` reads the next one while `hasNextPage`.\n */\nexport function useWorkspaceActivity(\n workspaceId: string | null | undefined,\n options?: {\n enabled?: boolean\n limit?: number\n /** Runs before each page, e.g. to (re)open the workspace so titles and names decrypt. */\n beforeFetch?: () => Promise<unknown>\n }\n) {\n const arbi = useArbi()\n return useInfiniteQuery({\n queryKey: arbiQueryKeys.workspaceActivity(workspaceId ?? ''),\n queryFn: async ({ pageParam }) => {\n await options?.beforeFetch?.()\n return arbi.workspaces.activity(workspaceId as string, {\n cursor: pageParam,\n limit: options?.limit,\n })\n },\n initialPageParam: null as string | null,\n getNextPageParam: (page) => page.next_cursor ?? undefined,\n enabled: (options?.enabled ?? true) && !!workspaceId && arbi.isLoggedIn,\n })\n}\n\n// ── Projects, usage & spend ───────────────────────────────────────────────────\n\n/** List the logged-in user's projects (billing accounts). */\nexport function useProjects(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.projects(),\n queryFn: () => arbi.projects.list(),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n })\n}\n\n/**\n * AI usage breakdown for a project's billing period. `monthsBack` selects the period (0 =\n * current, 1 = previous month, …).\n *\n * The response's `total_spend` / `spend` fields are £ of AI usage (format with `formatGbp`).\n * `metered` is `false` when the deployment does not record usage (a `dev`-plan project with all\n * zeros): show \"usage is not metered here\" instead of zeros. It is `undefined` until the usage\n * has loaded.\n */\nexport function useProjectUsage(\n projectExtId: string | undefined,\n monthsBack: number = 0,\n options?: { enabled?: boolean }\n) {\n const arbi = useArbi()\n const usage = useQuery({\n queryKey: arbiQueryKeys.projectUsage(projectExtId ?? '', monthsBack),\n queryFn: () => arbi.projects.usage(projectExtId as string, monthsBack),\n enabled: (options?.enabled ?? true) && !!projectExtId && arbi.isLoggedIn,\n })\n const projects = useProjects({ enabled: !!projectExtId && (options?.enabled ?? true) })\n const subscription = projects.data?.find((p) => p.external_id === projectExtId)?.subscription\n const metered = usage.data ? isUsageMetered(usage.data, subscription) : undefined\n return { ...usage, metered }\n}\n\n/** One day of aggregated usage across projects (for a spend/token trend). */\nexport interface AggregatedDailyUsage {\n date: string\n /** £ of AI usage that day. */\n gbp: number\n totalTokens: number\n apiRequests: number\n}\n\n/** One model group's aggregated usage across projects (for a breakdown). */\nexport interface AggregatedModelGroupUsage {\n model: string\n /** £ of AI usage by this model group. */\n gbp: number\n totalTokens: number\n promptTokens: number\n completionTokens: number\n successfulRequests: number\n}\n\n/** Aggregated AI usage + spend across several projects. */\nexport interface ProjectsUsageAggregate {\n /** Summed usage across the projects, in £ (ex VAT). */\n totalGbp: number\n /** Summed token count across the projects. */\n totalTokens: number\n /** Summed API request count across the projects. */\n totalRequests: number\n /** Per-day totals merged across every project, oldest first. */\n daily: AggregatedDailyUsage[]\n /** Per-model-group totals merged across every project, most £ first. */\n modelGroups: AggregatedModelGroupUsage[]\n /**\n * False when none of the loaded projects records usage (billing is off on this deployment), so\n * zeros mean \"not metered\". True while anything real was recorded, or before data arrived.\n */\n metered: boolean\n /** True while any per-project query is still loading. */\n isLoading: boolean\n /** True if any per-project query errored. */\n isError: boolean\n}\n\n/**\n * Firm-wide AI usage + spend: aggregates {@link useProjectUsage} across several\n * projects (e.g. all of a firm's matters) in parallel and merges the real totals,\n * the daily trend, and the per-model breakdown. Shares the per-project query\n * cache, so it costs nothing extra where a project's usage is already loaded.\n * Numbers are genuine — zero projects (or zero billed work) yields zero totals;\n * callers render that honestly.\n */\nexport function useProjectsUsage(\n projectExtIds: string[],\n monthsBack: number = 0,\n options?: { enabled?: boolean }\n): ProjectsUsageAggregate {\n const arbi = useArbi()\n const enabled = (options?.enabled ?? true) && arbi.isLoggedIn\n const projects = useProjects({ enabled: enabled && projectExtIds.length > 0 })\n const results = useQueries({\n queries: projectExtIds.map((id) => ({\n queryKey: arbiQueryKeys.projectUsage(id, monthsBack),\n queryFn: () => arbi.projects.usage(id, monthsBack),\n enabled: enabled && !!id,\n })),\n })\n\n // Recompute only when a query's data actually changes (not on every parent\n // render — the dashboard re-renders often while a digest streams).\n const signature =\n results.map((r) => `${r.status}:${r.dataUpdatedAt ?? 0}`).join('|') +\n `#${projects.dataUpdatedAt}`\n\n return useMemo(() => {\n const dailyMap = new Map<string, AggregatedDailyUsage>()\n const modelMap = new Map<string, AggregatedModelGroupUsage>()\n let totalGbp = 0\n let anyData = false\n let anyMetered = false\n let totalTokens = 0\n let totalRequests = 0\n\n results.forEach((r, i) => {\n const d = r.data\n if (!d) return\n anyData = true\n const subscription = projects.data?.find(\n (p) => p.external_id === projectExtIds[i]\n )?.subscription\n if (isUsageMetered(d, subscription)) anyMetered = true\n totalGbp += d.total_spend ?? 0\n totalTokens += d.total_tokens ?? 0\n totalRequests += d.total_requests ?? 0\n\n for (const day of d.daily ?? []) {\n const cur = dailyMap.get(day.date) ?? {\n date: day.date,\n gbp: 0,\n totalTokens: 0,\n apiRequests: 0,\n }\n cur.gbp += day.spend ?? 0\n cur.totalTokens += day.total_tokens ?? 0\n cur.apiRequests += day.api_requests ?? 0\n dailyMap.set(day.date, cur)\n }\n\n for (const [model, mg] of Object.entries(d.model_groups ?? {})) {\n const cur = modelMap.get(model) ?? {\n model,\n gbp: 0,\n totalTokens: 0,\n promptTokens: 0,\n completionTokens: 0,\n successfulRequests: 0,\n }\n cur.gbp += mg.spend ?? 0\n cur.totalTokens += mg.total_tokens ?? 0\n cur.promptTokens += mg.prompt_tokens ?? 0\n cur.completionTokens += mg.completion_tokens ?? 0\n cur.successfulRequests += mg.successful_requests ?? 0\n modelMap.set(model, cur)\n }\n })\n\n return {\n totalGbp,\n totalTokens,\n totalRequests,\n daily: [...dailyMap.values()].sort((a, b) => a.date.localeCompare(b.date)),\n modelGroups: [...modelMap.values()].sort(\n (a, b) => b.gbp - a.gbp || b.totalTokens - a.totalTokens\n ),\n metered: !anyData || anyMetered,\n isLoading: results.some((r) => r.isLoading),\n isError: results.some((r) => r.isError),\n }\n }, [signature])\n}\n\n/** List the Stripe invoices for a project's subscription. */\nexport function useProjectInvoices(\n projectExtId: string | undefined,\n options?: { enabled?: boolean }\n) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.projectInvoices(projectExtId ?? ''),\n queryFn: () => arbi.projects.invoices(projectExtId as string),\n enabled: (options?.enabled ?? true) && !!projectExtId && arbi.isLoggedIn,\n })\n}\n\n/**\n * The signed-in user from `GET /v1/user/me`. Refetched on window focus, so a role granted or\n * removed elsewhere shows up without a reload; invalidate `arbiQueryKeys.currentUser()` after a\n * change you made yourself.\n */\nexport function useCurrentUser(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.currentUser(),\n queryFn: () => arbi.user.me(),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n refetchOnWindowFocus: true,\n staleTime: 30_000,\n })\n}\n\n/**\n * The firm's pooled monthly £ of AI usage (Box deployments). A 403 (the caller is not a firm member\n * or Box admin) is not retried: treat an error like `has_pool: false` and show nothing.\n */\nexport function useFirmPool(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.firmPool(),\n queryFn: () => arbi.firm.pool(),\n enabled: (options?.enabled ?? true) && arbi.isLoggedIn,\n retry: false,\n refetchOnWindowFocus: true,\n staleTime: 60_000,\n })\n}\n\n/**\n * Whether this deployment runs under a Box licence (`isBox`) and whether the user administers it in\n * the ARBI portal (`isBoxAdmin`), from the firm pool. Anyone outside the firm gets a 403 (not\n * retried), read as no Box. The API has no Box-admin flag yet: `can_top_up` is true only for a Box\n * admin of a licence central can bill, so admins of a hand-set licence read as members for now.\n */\nexport function useBoxRole(options: { enabled?: boolean } = {}): {\n isBox: boolean\n isBoxAdmin: boolean\n} {\n const { data, isError } = useFirmPool(options)\n const isBox = !isError && !!data?.has_pool\n return { isBox, isBoxAdmin: isBox && !!data?.can_top_up }\n}\n\n/** Buy add-ons for the firm (Box admins). Refreshes the pool; the result may carry an invoice URL. */\nexport function useTopUpFirmPool() {\n const arbi = useArbi()\n const queryClient = useQueryClient()\n return useMutation({\n mutationFn: (aiAddons: number) => arbi.firm.topUp(aiAddons),\n onSuccess: (result) => {\n queryClient.setQueryData(arbiQueryKeys.firmPool(), result.pool)\n },\n })\n}\n\n/** Why \"New project\" / \"New workspace\" is unavailable to someone who may not create them. */\nexport const PROJECT_CREATION_DENIED_REASON =\n 'Only members of your firm can create projects and workspaces.'\n\n/**\n * Whether the signed-in user may create projects and workspaces. `undefined` while the user is\n * loading: callers should neither offer nor refuse creation until it is known.\n */\nexport function useCanCreateProjects(): boolean | undefined {\n const user = useCurrentUser()\n // A role granted or removed in a workspace can change it: re-read when the memberships do.\n const { data: workspaces } = useWorkspaces({ enabled: user.isSuccess })\n const membership = workspaces?.map((w) => w.external_id).join(',')\n const { refetch } = user\n const seen = useRef<string | undefined>(undefined)\n useEffect(() => {\n if (membership === undefined || membership === seen.current) return\n const first = seen.current === undefined\n seen.current = membership\n if (!first) void refetch()\n }, [membership, refetch])\n return user.data?.can_create_projects\n}\n\n/**\n * Today's deployment-wide AI usage (£, `used_gbp`) for the signed-in user: pair it with a project's\n * `daily_cap_per_user` for a \"£ used today\" indicator. Re-read on mount and window focus, and when\n * the host invalidates it after the user's own generation; never polled.\n */\nexport function useUserUsageToday(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.userUsageToday(),\n queryFn: () => arbi.user.usageToday(),\n enabled: (options?.enabled ?? true) && arbi.isLoggedIn,\n refetchOnWindowFocus: true,\n refetchOnMount: 'always',\n staleTime: 15_000,\n })\n}\n"]}