@arbidocs/react 0.5.26 → 0.5.27

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 (29) hide show
  1. package/dist/artifacts/index.cjs +4 -4
  2. package/dist/artifacts/index.js +3 -3
  3. package/dist/calls/livekit/index.cjs +43 -43
  4. package/dist/calls/livekit/index.js +4 -4
  5. package/dist/{chunk-AXZF5ODQ.cjs → chunk-3ZLRZTKP.cjs} +7 -7
  6. package/dist/{chunk-AXZF5ODQ.cjs.map → chunk-3ZLRZTKP.cjs.map} +1 -1
  7. package/dist/{chunk-LTEMUGPQ.js → chunk-5X4RZ36M.js} +5 -5
  8. package/dist/{chunk-LTEMUGPQ.js.map → chunk-5X4RZ36M.js.map} +1 -1
  9. package/dist/{chunk-UORYHG2Z.js → chunk-CIWI5UFT.js} +3 -3
  10. package/dist/{chunk-UORYHG2Z.js.map → chunk-CIWI5UFT.js.map} +1 -1
  11. package/dist/{chunk-QQLCQP24.js → chunk-CMNZI4WQ.js} +3 -3
  12. package/dist/{chunk-QQLCQP24.js.map → chunk-CMNZI4WQ.js.map} +1 -1
  13. package/dist/{chunk-KTHMMF2M.js → chunk-I4JYI6GY.js} +3 -3
  14. package/dist/{chunk-KTHMMF2M.js.map → chunk-I4JYI6GY.js.map} +1 -1
  15. package/dist/{chunk-GSOAMP6Z.cjs → chunk-NV5G5RR5.cjs} +3 -3
  16. package/dist/{chunk-GSOAMP6Z.cjs.map → chunk-NV5G5RR5.cjs.map} +1 -1
  17. package/dist/{chunk-HMSAYMMX.cjs → chunk-TUPSNW3B.cjs} +3 -3
  18. package/dist/{chunk-HMSAYMMX.cjs.map → chunk-TUPSNW3B.cjs.map} +1 -1
  19. package/dist/{chunk-XMUC5NIJ.cjs → chunk-YMAZYYD5.cjs} +3 -3
  20. package/dist/{chunk-XMUC5NIJ.cjs.map → chunk-YMAZYYD5.cjs.map} +1 -1
  21. package/dist/document-tools/index.cjs +1 -1
  22. package/dist/document-tools/index.js +1 -1
  23. package/dist/index.cjs +823 -823
  24. package/dist/index.js +18 -18
  25. package/dist/shell/index.cjs +33 -33
  26. package/dist/shell/index.js +2 -2
  27. package/dist/ui/index.cjs +164 -164
  28. package/dist/ui/index.js +2 -2
  29. package/package.json +3 -3
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
- var chunkN73IMVFF_cjs = require('./chunk-N73IMVFF.cjs');
4
3
  var chunkRRWAX52L_cjs = require('./chunk-RRWAX52L.cjs');
4
+ var chunkN73IMVFF_cjs = require('./chunk-N73IMVFF.cjs');
5
5
  var chunkZWFMFOGP_cjs = require('./chunk-ZWFMFOGP.cjs');
6
6
  var chunkYIUUTRMQ_cjs = require('./chunk-YIUUTRMQ.cjs');
7
7
  var client = require('@arbidocs/client');
@@ -1051,5 +1051,5 @@ exports.useTopUpFirmPool = useTopUpFirmPool;
1051
1051
  exports.useUserUsageToday = useUserUsageToday;
1052
1052
  exports.useWorkspaceActivity = useWorkspaceActivity;
1053
1053
  exports.useWorkspaces = useWorkspaces;
1054
- //# sourceMappingURL=chunk-GSOAMP6Z.cjs.map
1055
- //# sourceMappingURL=chunk-GSOAMP6Z.cjs.map
1054
+ //# sourceMappingURL=chunk-NV5G5RR5.cjs.map
1055
+ //# sourceMappingURL=chunk-NV5G5RR5.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/chat/run-state.ts","../src/session/store.ts","../src/session/drafts.ts","../src/session/session-hooks.ts","../src/session/signed-in.ts","../src/usage-metered.ts","../src/hooks.ts"],"names":["parseVersionRef","getUserEncryptionKeypair","sealedBoxEncrypt","sealedBoxDecrypt","useArbiHost","OWN_SESSION_SLOT","useSyncExternalStore","useMemo","useArbi","useQuery","arbiQueryKeys","ArbiApiError","useMutation","useQueryClient","useInfiniteQuery","useQueries","useRef","useEffect"],"mappings":";;;;;;;;;;;;AAkCO,IAAM,gCAAA,GAAmC;AAEhD,IAAM,SAAA,GAAY,CAChB,MAAA,EACA,MAAA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ACpB;AAOO,SAAS,kBAAkB,OAAA,EAAiC;AACjE,EAAA,MAAM,OAAOT,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-GSOAMP6Z.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 session state every block reads and writes: the selected workspace, the current conversation,\n * the document being viewed, the document selection, generation per conversation, Personal\n * Assistant mode and the documents in each conversation.\n *\n * An {@link ArbiSessionStore} is the adapter a host gives as its configuration's `session`:\n * a host with its own state (ARBI-frontend's zustand store) maps its fields onto\n * {@link ArbiSessionState} and its actions onto the setters, so there is one source of truth.\n * Other hosts use {@link createArbiSessionStore}, an in-memory store.\n */\n\nimport type { components } from '@arbidocs/client'\nimport type { ProbeAnswerEvent } from '@arbidocs/sdk/browser'\nimport { parseVersionRef } from '../artifacts/versions'\nimport type { ArbiDraftStorage } from './drafts'\nimport {\n agentControl,\n queuedMessages,\n type AgentControlMaps,\n type AgentRunControlState,\n type QueuedMessage,\n type QueuedMessages,\n} from '../chat/run-state'\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/** Generation in one conversation. */\nexport interface ArbiConversationGeneration {\n isGenerating: boolean\n error: string | null\n /** When the running turn started (epoch ms). */\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/**\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\nexport interface ArbiSessionState extends AgentControlMaps {\n /** The selected workspace (`wrk-…`). */\n workspaceId: string | null\n /** Whether it is open on the server session (`useSwitchWorkspace` moves it). */\n workspaceStatus: ArbiWorkspaceStatus\n /** The open conversation, or null for a new one / none. */\n conversationId: string | null\n viewingDocument: ArbiViewingDocument | null\n documentViewer: ArbiDocumentViewerState\n /** The documents selected in document lists. */\n selectedDocumentIds: readonly string[]\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 * {@link 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 document read in full with each turn (one at a time). */\n pinnedDocumentId: string | null\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 conversation's composer, per conversation id (`new` for a new chat).\n * The open conversation's is {@link selectDraft}. A host may keep them across reloads, stored\n * locally 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 open thread tabs, least recently used first (`ConnectedThreadTabs` shows them). */\n threadTabs: readonly ArbiThreadTab[]\n /** The thread tab on screen (`threadTabId`), or null while the thread list is. */\n activeThreadTabId: string | null\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/** 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 thread tab: a conversation's, or a new chat's (`conversationId` null). */\nexport interface ArbiThreadTab {\n conversationId: string | null\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 (the least recently used goes first). */\nexport const MAX_THREAD_TABS = 12\n\n/** A send's structured tools (`MessageInput.tools`). */\nexport type TurnTools = components['schemas']['MessageInput']['tools']\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\nexport interface ArbiSessionStore {\n /** The current state. The same object until something in it changes. */\n getState(): ArbiSessionState\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 viewed document, the selection, the context documents and facts), before a switch. A host\n * with workspace-scoped state of its own clears that too.\n */\n leaveWorkspace(): void\n setConversationId(id: string | null): void\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 /** 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 setPinnedDocumentId(id: string | null): 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 and facts move from `fromId` (`new`) to\n * `toId`, and it stays the open conversation.\n */\n moveConversation(fromId: string, toId: string): void\n setCursor(messageId: string | null): void\n setSuggestedQuery(suggestion: ArbiSessionState['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), opening the tab when it is not open.\n * Returns the tab's id.\n */\n openThreadTab(conversationId: string | null): string\n /** Close a thread tab; closing the one on screen shows the last other, else the thread list. */\n closeThreadTab(tabId: string): void\n /** Show a thread tab's conversation, or (null) the thread list; the tabs stay open. */\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 /** Leave the open conversation for a new one (its conversation was deleted). */\n startNewConversation(): 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\nexport const EMPTY_SESSION_STATE: ArbiSessionState = {\n workspaceId: null,\n workspaceStatus: 'closed',\n conversationId: null,\n viewingDocument: null,\n documentViewer: DEFAULT_DOCUMENT_VIEWER_STATE,\n selectedDocumentIds: [],\n generating: {},\n paMode: false,\n conversationDocuments: {},\n conversationDocumentAutoAdd: {},\n conversationFacts: {},\n pinnedDocumentId: null,\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 threadTabs: [],\n activeThreadTabId: null,\n newConversationAssistantMode: 'always',\n pendingTools: null,\n autoSendDraft: false,\n agentChatOwners: {},\n newAgentChat: null,\n newChatDocumentId: null,\n messageTimers: {},\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: ArbiSessionState): string => state.conversationId ?? 'new'\n\n/** What is typed in the open conversation's composer. */\nexport const selectDraft = (state: ArbiSessionState): string =>\n state.drafts[conversationKey(state)] ?? ''\n\n/** Whether `conversationId` is generating. */\nexport const selectIsGenerating =\n (conversationId: string | null | undefined) =>\n (state: ArbiSessionState): 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/** Options of {@link createArbiSessionStore}. */\nexport interface ArbiSessionStoreOptions {\n /** Keep the composers' drafts across reloads (see {@link createSealedDraftStorage}). */\n draftStorage?: ArbiDraftStorage\n}\n\n/** An in-memory session store: the default for hosts without state of their own. */\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 { new: _new, ...saved } = record\n return saved\n}\n\nexport function createArbiSessionStore(\n initial: Partial<ArbiSessionState> = {},\n { draftStorage }: ArbiSessionStoreOptions = {}\n): ArbiSessionStore {\n let state: ArbiSessionState = { ...EMPTY_SESSION_STATE, ...initial }\n const listeners = new Set<() => void>()\n const update = (patch: Partial<ArbiSessionState>) => {\n state = { ...state, ...patch }\n listeners.forEach((listener) => listener())\n }\n // The draft and line the composer had when an edit began, given back when it is cancelled.\n let preEdit: { draft: string; cursor: string | null } = { draft: '', cursor: null }\n // The saved drafts come back once the person's key is there (it is not before sign-in); a draft\n // typed meanwhile wins over its saved copy.\n let draftsRestored = !draftStorage\n // Whose drafts the store holds: another person's never carry over to the next sign-in.\n let draftsOwner = draftStorage?.owner() ?? null\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) return\n draftsRestored = true\n void draftStorage.load().then(\n (saved) => {\n if (saved && draftStorage.owner() === owner)\n update({ drafts: { ...saved, ...state.drafts } })\n else draftsRestored = false\n },\n () => {\n draftsRestored = 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 = { draft: '', cursor: null }\n if (Object.keys(state.drafts).length > 0) update({ drafts: {} })\n })\n restoreDrafts()\n const setDrafts = (drafts: Record<string, string>) => {\n update({ drafts })\n 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 return {\n getState: () => state,\n subscribe: (listener) => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n setWorkspaceId: (workspaceId) => {\n if (state.workspaceId !== workspaceId) update({ workspaceId })\n // A workspace opens once signed in: the key that opens the saved drafts is there now.\n restoreDrafts()\n },\n setWorkspaceStatus: (workspaceStatus) => {\n if (state.workspaceStatus !== workspaceStatus) update({ workspaceStatus })\n },\n leaveWorkspace: () => {\n // A turn streaming in the workspace being left stops here (the server finishes it).\n Object.values(state.generating).forEach((generation) => generation.abortController?.abort())\n update({\n workspaceStatus: 'closed',\n conversationId: null,\n cursor: null,\n viewingDocument: null,\n selectedDocumentIds: [],\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 pinnedDocumentId: null,\n newAgentChat: null,\n newChatDocumentId: null,\n messageTimers: {},\n threadTabs: [],\n activeThreadTabId: null,\n })\n },\n setConversationId: (conversationId) => {\n // Another conversation opens on its own line, not on the edit or line of the one before.\n if (state.conversationId !== conversationId)\n update({ conversationId, cursor: null, editingMessageId: null })\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 setConversationGenerating: (conversationId, isGenerating, abortController = null) => {\n const current = state.generating[conversationId]\n update({\n generating: {\n ...state.generating,\n [conversationId]: {\n ...current,\n isGenerating,\n error: isGenerating ? null : (current?.error ?? null),\n startTime: isGenerating ? Date.now() : null,\n streamingAssistantId: isGenerating ? (current?.streamingAssistantId ?? null) : null,\n backendElapsed: isGenerating ? (current?.backendElapsed ?? null) : null,\n abortController,\n },\n },\n })\n },\n setStreamingAssistantId: (conversationId, streamingAssistantId, startTime = Date.now()) => {\n const current = state.generating[conversationId]\n update({\n generating: {\n ...state.generating,\n [conversationId]: {\n ...(current ?? { isGenerating: false, error: null }),\n streamingAssistantId,\n startTime,\n },\n },\n })\n },\n setBackendElapsed: (conversationId, backendElapsed) => {\n const current = state.generating[conversationId] ?? {\n isGenerating: false,\n error: null,\n startTime: null,\n }\n update({\n generating: { ...state.generating, [conversationId]: { ...current, backendElapsed } },\n })\n },\n moveConversation: (fromId, toId) => {\n const move = <T>(record: Readonly<Record<string, T>>): Record<string, T> => {\n const next = { ...record }\n if (fromId in next) {\n next[toId] = next[fromId]\n delete next[fromId]\n }\n return next\n }\n update({\n generating: move(state.generating),\n conversationDocuments: move(state.conversationDocuments),\n conversationDocumentAutoAdd: move(state.conversationDocumentAutoAdd),\n conversationFacts: move(state.conversationFacts),\n conversationId: state.conversationId ?? toId,\n // The new chat's tab is now the conversation's.\n threadTabs: state.threadTabs.map((tab) =>\n threadTabId(tab) === fromId ? { conversationId: toId } : tab\n ),\n activeThreadTabId: state.activeThreadTabId === fromId ? toId : state.activeThreadTabId,\n })\n // What is typed stays in the composer it was typed in.\n if (fromId in state.drafts) setDrafts(move(state.drafts))\n },\n setConversationFacts: (conversationId, factIds) =>\n update({ conversationFacts: { ...state.conversationFacts, [conversationId]: factIds } }),\n setPinnedDocumentId: (pinnedDocumentId) => update({ pinnedDocumentId }),\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(conversationKey(state), text),\n setChatModel: (chatModel) => {\n if (state.chatModel !== chatModel) update({ chatModel })\n },\n openThreadTab: (conversationId) => {\n const id = conversationId ?? 'new'\n const others = state.threadTabs.filter((tab) => threadTabId(tab) !== id)\n const threadTabs = [...others, { conversationId }].slice(-MAX_THREAD_TABS)\n // Starting a new chat starts it unbound, whatever document is open.\n update({\n threadTabs,\n activeThreadTabId: id,\n ...(conversationId === null ? { newChatDocumentId: null } : {}),\n })\n if (state.conversationId !== conversationId)\n update({ conversationId, cursor: null, editingMessageId: null })\n return id\n },\n closeThreadTab: (tabId) => {\n const threadTabs = state.threadTabs.filter((tab) => threadTabId(tab) !== tabId)\n if (threadTabs.length === state.threadTabs.length) return\n if (state.activeThreadTabId !== tabId) return update({ threadTabs })\n const next = threadTabs.at(-1)\n update({ threadTabs, activeThreadTabId: next ? threadTabId(next) : null })\n if (next && state.conversationId !== next.conversationId)\n update({ conversationId: next.conversationId, cursor: null, editingMessageId: null })\n },\n selectThreadTab: (tabId) => {\n if (tabId === null) {\n if (state.activeThreadTabId !== null) update({ activeThreadTabId: null })\n return\n }\n const tab = state.threadTabs.find((t) => threadTabId(t) === tabId)\n if (!tab) return\n update({ activeThreadTabId: tabId })\n if (state.conversationId !== tab.conversationId)\n update({ conversationId: tab.conversationId, cursor: null, editingMessageId: null })\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 preEdit = { draft: selectDraft(state), cursor: state.cursor }\n update({ editingMessageId: messageId })\n setDraftOf(conversationKey(state), content)\n },\n cancelEditing: () => {\n if (!state.editingMessageId) return\n update({ editingMessageId: null, cursor: preEdit.cursor })\n setDraftOf(conversationKey(state), preEdit.draft)\n preEdit = { draft: '', cursor: null }\n },\n completeEditing: () => {\n preEdit = { draft: '', cursor: null }\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 update({ agentChatOwners: { ...state.agentChatOwners, [conversationId]: agentId } }),\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 setConversationError: (conversationId, error, lastFailedMessage) => {\n const current = state.generating[conversationId]\n update({\n generating: {\n ...state.generating,\n [conversationId]: {\n ...current,\n isGenerating: false,\n error,\n startTime: current?.startTime ?? null,\n lastFailedMessage: lastFailedMessage ?? current?.lastFailedMessage ?? null,\n },\n },\n })\n },\n clearConversationError: (conversationId) => {\n const current = state.generating[conversationId]\n update({\n generating: {\n ...state.generating,\n [conversationId]: {\n ...(current ?? { isGenerating: false, startTime: null }),\n error: null,\n lastFailedMessage: null,\n },\n },\n })\n },\n abortConversationGeneration: (conversationId) => {\n const current = state.generating[conversationId]\n current?.abortController?.abort()\n update({\n generating: {\n ...state.generating,\n [conversationId]: {\n ...(current ?? { error: null, startTime: null }),\n isGenerating: false,\n abortController: null,\n },\n },\n })\n },\n startNewConversation: () =>\n update({\n conversationId: null,\n cursor: null,\n editingMessageId: null,\n newChatDocumentId: null,\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 }\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 { 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 * 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 * 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 ArbiApiError,\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) has no threads: the server's 404\n * is 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: async (): Promise<ThreadsResponse> => {\n try {\n return await arbi.conversations.getThreads(conversationId as string)\n } catch (error) {\n if (error instanceof ArbiApiError && error.status === 404) {\n return { conversation_ext_id: conversationId, threads: [] } as unknown as ThreadsResponse\n }\n throw error\n }\n },\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 queryFn: () => arbi.readInWorkspace(workspace, () => arbi.tags.list(key ? query : undefined)),\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"]}
1
+ {"version":3,"sources":["../src/chat/run-state.ts","../src/session/store.ts","../src/session/drafts.ts","../src/session/session-hooks.ts","../src/session/signed-in.ts","../src/usage-metered.ts","../src/hooks.ts"],"names":["parseVersionRef","getUserEncryptionKeypair","sealedBoxEncrypt","sealedBoxDecrypt","useArbiHost","OWN_SESSION_SLOT","useSyncExternalStore","useMemo","useArbi","useQuery","arbiQueryKeys","ArbiApiError","useMutation","useQueryClient","useInfiniteQuery","useQueries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;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,OAAOT,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-NV5G5RR5.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 session state every block reads and writes: the selected workspace, the current conversation,\n * the document being viewed, the document selection, generation per conversation, Personal\n * Assistant mode and the documents in each conversation.\n *\n * An {@link ArbiSessionStore} is the adapter a host gives as its configuration's `session`:\n * a host with its own state (ARBI-frontend's zustand store) maps its fields onto\n * {@link ArbiSessionState} and its actions onto the setters, so there is one source of truth.\n * Other hosts use {@link createArbiSessionStore}, an in-memory store.\n */\n\nimport type { components } from '@arbidocs/client'\nimport type { ProbeAnswerEvent } from '@arbidocs/sdk/browser'\nimport { parseVersionRef } from '../artifacts/versions'\nimport type { ArbiDraftStorage } from './drafts'\nimport {\n agentControl,\n queuedMessages,\n type AgentControlMaps,\n type AgentRunControlState,\n type QueuedMessage,\n type QueuedMessages,\n} from '../chat/run-state'\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/** Generation in one conversation. */\nexport interface ArbiConversationGeneration {\n isGenerating: boolean\n error: string | null\n /** When the running turn started (epoch ms). */\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/**\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\nexport interface ArbiSessionState extends AgentControlMaps {\n /** The selected workspace (`wrk-…`). */\n workspaceId: string | null\n /** Whether it is open on the server session (`useSwitchWorkspace` moves it). */\n workspaceStatus: ArbiWorkspaceStatus\n /** The open conversation, or null for a new one / none. */\n conversationId: string | null\n viewingDocument: ArbiViewingDocument | null\n documentViewer: ArbiDocumentViewerState\n /** The documents selected in document lists. */\n selectedDocumentIds: readonly string[]\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 * {@link 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 document read in full with each turn (one at a time). */\n pinnedDocumentId: string | null\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 conversation's composer, per conversation id (`new` for a new chat).\n * The open conversation's is {@link selectDraft}. A host may keep them across reloads, stored\n * locally 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 open thread tabs, least recently used first (`ConnectedThreadTabs` shows them). */\n threadTabs: readonly ArbiThreadTab[]\n /** The thread tab on screen (`threadTabId`), or null while the thread list is. */\n activeThreadTabId: string | null\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/** 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 thread tab: a conversation's, or a new chat's (`conversationId` null). */\nexport interface ArbiThreadTab {\n conversationId: string | null\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 (the least recently used goes first). */\nexport const MAX_THREAD_TABS = 12\n\n/** A send's structured tools (`MessageInput.tools`). */\nexport type TurnTools = components['schemas']['MessageInput']['tools']\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\nexport interface ArbiSessionStore {\n /** The current state. The same object until something in it changes. */\n getState(): ArbiSessionState\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 viewed document, the selection, the context documents and facts), before a switch. A host\n * with workspace-scoped state of its own clears that too.\n */\n leaveWorkspace(): void\n setConversationId(id: string | null): void\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 /** 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 setPinnedDocumentId(id: string | null): 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 and facts move from `fromId` (`new`) to\n * `toId`, and it stays the open conversation.\n */\n moveConversation(fromId: string, toId: string): void\n setCursor(messageId: string | null): void\n setSuggestedQuery(suggestion: ArbiSessionState['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), opening the tab when it is not open.\n * Returns the tab's id.\n */\n openThreadTab(conversationId: string | null): string\n /** Close a thread tab; closing the one on screen shows the last other, else the thread list. */\n closeThreadTab(tabId: string): void\n /** Show a thread tab's conversation, or (null) the thread list; the tabs stay open. */\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 /** Leave the open conversation for a new one (its conversation was deleted). */\n startNewConversation(): 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\nexport const EMPTY_SESSION_STATE: ArbiSessionState = {\n workspaceId: null,\n workspaceStatus: 'closed',\n conversationId: null,\n viewingDocument: null,\n documentViewer: DEFAULT_DOCUMENT_VIEWER_STATE,\n selectedDocumentIds: [],\n generating: {},\n paMode: false,\n conversationDocuments: {},\n conversationDocumentAutoAdd: {},\n conversationFacts: {},\n pinnedDocumentId: null,\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 threadTabs: [],\n activeThreadTabId: null,\n newConversationAssistantMode: 'always',\n pendingTools: null,\n autoSendDraft: false,\n agentChatOwners: {},\n newAgentChat: null,\n newChatDocumentId: null,\n messageTimers: {},\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: ArbiSessionState): string => state.conversationId ?? 'new'\n\n/** What is typed in the open conversation's composer. */\nexport const selectDraft = (state: ArbiSessionState): string =>\n state.drafts[conversationKey(state)] ?? ''\n\n/** Whether `conversationId` is generating. */\nexport const selectIsGenerating =\n (conversationId: string | null | undefined) =>\n (state: ArbiSessionState): 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/** Options of {@link createArbiSessionStore}. */\nexport interface ArbiSessionStoreOptions {\n /** Keep the composers' drafts across reloads (see {@link createSealedDraftStorage}). */\n draftStorage?: ArbiDraftStorage\n}\n\n/** An in-memory session store: the default for hosts without state of their own. */\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 { new: _new, ...saved } = record\n return saved\n}\n\nexport function createArbiSessionStore(\n initial: Partial<ArbiSessionState> = {},\n { draftStorage }: ArbiSessionStoreOptions = {}\n): ArbiSessionStore {\n let state: ArbiSessionState = { ...EMPTY_SESSION_STATE, ...initial }\n const listeners = new Set<() => void>()\n const update = (patch: Partial<ArbiSessionState>) => {\n state = { ...state, ...patch }\n listeners.forEach((listener) => listener())\n }\n // The draft and line the composer had when an edit began, given back when it is cancelled.\n let preEdit: { draft: string; cursor: string | null } = { draft: '', cursor: null }\n // The saved drafts come back once the person's key is there (it is not before sign-in); a draft\n // typed meanwhile wins over its saved copy.\n let draftsRestored = !draftStorage\n // Whose drafts the store holds: another person's never carry over to the next sign-in.\n let draftsOwner = draftStorage?.owner() ?? null\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) return\n draftsRestored = true\n void draftStorage.load().then(\n (saved) => {\n if (saved && draftStorage.owner() === owner)\n update({ drafts: { ...saved, ...state.drafts } })\n else draftsRestored = false\n },\n () => {\n draftsRestored = 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 = { draft: '', cursor: null }\n if (Object.keys(state.drafts).length > 0) update({ drafts: {} })\n })\n restoreDrafts()\n const setDrafts = (drafts: Record<string, string>) => {\n update({ drafts })\n 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 return {\n getState: () => state,\n subscribe: (listener) => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n setWorkspaceId: (workspaceId) => {\n if (state.workspaceId !== workspaceId) update({ workspaceId })\n // A workspace opens once signed in: the key that opens the saved drafts is there now.\n restoreDrafts()\n },\n setWorkspaceStatus: (workspaceStatus) => {\n if (state.workspaceStatus !== workspaceStatus) update({ workspaceStatus })\n },\n leaveWorkspace: () => {\n // A turn streaming in the workspace being left stops here (the server finishes it).\n Object.values(state.generating).forEach((generation) => generation.abortController?.abort())\n update({\n workspaceStatus: 'closed',\n conversationId: null,\n cursor: null,\n viewingDocument: null,\n selectedDocumentIds: [],\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 pinnedDocumentId: null,\n newAgentChat: null,\n newChatDocumentId: null,\n messageTimers: {},\n threadTabs: [],\n activeThreadTabId: null,\n })\n },\n setConversationId: (conversationId) => {\n // Another conversation opens on its own line, not on the edit or line of the one before.\n if (state.conversationId !== conversationId)\n update({ conversationId, cursor: null, editingMessageId: null })\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 setConversationGenerating: (conversationId, isGenerating, abortController = null) => {\n const current = state.generating[conversationId]\n update({\n generating: {\n ...state.generating,\n [conversationId]: {\n ...current,\n isGenerating,\n error: isGenerating ? null : (current?.error ?? null),\n startTime: isGenerating ? Date.now() : null,\n streamingAssistantId: isGenerating ? (current?.streamingAssistantId ?? null) : null,\n backendElapsed: isGenerating ? (current?.backendElapsed ?? null) : null,\n abortController,\n },\n },\n })\n },\n setStreamingAssistantId: (conversationId, streamingAssistantId, startTime = Date.now()) => {\n const current = state.generating[conversationId]\n update({\n generating: {\n ...state.generating,\n [conversationId]: {\n ...(current ?? { isGenerating: false, error: null }),\n streamingAssistantId,\n startTime,\n },\n },\n })\n },\n setBackendElapsed: (conversationId, backendElapsed) => {\n const current = state.generating[conversationId] ?? {\n isGenerating: false,\n error: null,\n startTime: null,\n }\n update({\n generating: { ...state.generating, [conversationId]: { ...current, backendElapsed } },\n })\n },\n moveConversation: (fromId, toId) => {\n const move = <T>(record: Readonly<Record<string, T>>): Record<string, T> => {\n const next = { ...record }\n if (fromId in next) {\n next[toId] = next[fromId]\n delete next[fromId]\n }\n return next\n }\n update({\n generating: move(state.generating),\n conversationDocuments: move(state.conversationDocuments),\n conversationDocumentAutoAdd: move(state.conversationDocumentAutoAdd),\n conversationFacts: move(state.conversationFacts),\n conversationId: state.conversationId ?? toId,\n // The new chat's tab is now the conversation's.\n threadTabs: state.threadTabs.map((tab) =>\n threadTabId(tab) === fromId ? { conversationId: toId } : tab\n ),\n activeThreadTabId: state.activeThreadTabId === fromId ? toId : state.activeThreadTabId,\n })\n // What is typed stays in the composer it was typed in.\n if (fromId in state.drafts) setDrafts(move(state.drafts))\n },\n setConversationFacts: (conversationId, factIds) =>\n update({ conversationFacts: { ...state.conversationFacts, [conversationId]: factIds } }),\n setPinnedDocumentId: (pinnedDocumentId) => update({ pinnedDocumentId }),\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(conversationKey(state), text),\n setChatModel: (chatModel) => {\n if (state.chatModel !== chatModel) update({ chatModel })\n },\n openThreadTab: (conversationId) => {\n const id = conversationId ?? 'new'\n const others = state.threadTabs.filter((tab) => threadTabId(tab) !== id)\n const threadTabs = [...others, { conversationId }].slice(-MAX_THREAD_TABS)\n // Starting a new chat starts it unbound, whatever document is open.\n update({\n threadTabs,\n activeThreadTabId: id,\n ...(conversationId === null ? { newChatDocumentId: null } : {}),\n })\n if (state.conversationId !== conversationId)\n update({ conversationId, cursor: null, editingMessageId: null })\n return id\n },\n closeThreadTab: (tabId) => {\n const threadTabs = state.threadTabs.filter((tab) => threadTabId(tab) !== tabId)\n if (threadTabs.length === state.threadTabs.length) return\n if (state.activeThreadTabId !== tabId) return update({ threadTabs })\n const next = threadTabs.at(-1)\n update({ threadTabs, activeThreadTabId: next ? threadTabId(next) : null })\n if (next && state.conversationId !== next.conversationId)\n update({ conversationId: next.conversationId, cursor: null, editingMessageId: null })\n },\n selectThreadTab: (tabId) => {\n if (tabId === null) {\n if (state.activeThreadTabId !== null) update({ activeThreadTabId: null })\n return\n }\n const tab = state.threadTabs.find((t) => threadTabId(t) === tabId)\n if (!tab) return\n update({ activeThreadTabId: tabId })\n if (state.conversationId !== tab.conversationId)\n update({ conversationId: tab.conversationId, cursor: null, editingMessageId: null })\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 preEdit = { draft: selectDraft(state), cursor: state.cursor }\n update({ editingMessageId: messageId })\n setDraftOf(conversationKey(state), content)\n },\n cancelEditing: () => {\n if (!state.editingMessageId) return\n update({ editingMessageId: null, cursor: preEdit.cursor })\n setDraftOf(conversationKey(state), preEdit.draft)\n preEdit = { draft: '', cursor: null }\n },\n completeEditing: () => {\n preEdit = { draft: '', cursor: null }\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 update({ agentChatOwners: { ...state.agentChatOwners, [conversationId]: agentId } }),\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 setConversationError: (conversationId, error, lastFailedMessage) => {\n const current = state.generating[conversationId]\n update({\n generating: {\n ...state.generating,\n [conversationId]: {\n ...current,\n isGenerating: false,\n error,\n startTime: current?.startTime ?? null,\n lastFailedMessage: lastFailedMessage ?? current?.lastFailedMessage ?? null,\n },\n },\n })\n },\n clearConversationError: (conversationId) => {\n const current = state.generating[conversationId]\n update({\n generating: {\n ...state.generating,\n [conversationId]: {\n ...(current ?? { isGenerating: false, startTime: null }),\n error: null,\n lastFailedMessage: null,\n },\n },\n })\n },\n abortConversationGeneration: (conversationId) => {\n const current = state.generating[conversationId]\n current?.abortController?.abort()\n update({\n generating: {\n ...state.generating,\n [conversationId]: {\n ...(current ?? { error: null, startTime: null }),\n isGenerating: false,\n abortController: null,\n },\n },\n })\n },\n startNewConversation: () =>\n update({\n conversationId: null,\n cursor: null,\n editingMessageId: null,\n newChatDocumentId: null,\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 }\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 { 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 * 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 * 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 ArbiApiError,\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) has no threads: the server's 404\n * is 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: async (): Promise<ThreadsResponse> => {\n try {\n return await arbi.conversations.getThreads(conversationId as string)\n } catch (error) {\n if (error instanceof ArbiApiError && error.status === 404) {\n return { conversation_ext_id: conversationId, threads: [] } as unknown as ThreadsResponse\n }\n throw error\n }\n },\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 queryFn: () => arbi.readInWorkspace(workspace, () => arbi.tags.list(key ? query : undefined)),\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"]}
@@ -2,8 +2,8 @@
2
2
 
3
3
  var chunkVAMPYLQ4_cjs = require('./chunk-VAMPYLQ4.cjs');
4
4
  var chunkN73IMVFF_cjs = require('./chunk-N73IMVFF.cjs');
5
- var chunkKC474WVG_cjs = require('./chunk-KC474WVG.cjs');
6
5
  var chunkZWFMFOGP_cjs = require('./chunk-ZWFMFOGP.cjs');
6
+ var chunkKC474WVG_cjs = require('./chunk-KC474WVG.cjs');
7
7
  var chunkHJDR5HEO_cjs = require('./chunk-HJDR5HEO.cjs');
8
8
  var chunkS6A6FSG7_cjs = require('./chunk-S6A6FSG7.cjs');
9
9
  var chunkRCKA7BEF_cjs = require('./chunk-RCKA7BEF.cjs');
@@ -540,5 +540,5 @@ exports.toMessageMentions = toMessageMentions;
540
540
  exports.useOpenDocumentId = useOpenDocumentId;
541
541
  exports.useRegisterOpenDocument = useRegisterOpenDocument;
542
542
  exports.useTurnDocumentId = useTurnDocumentId;
543
- //# sourceMappingURL=chunk-HMSAYMMX.cjs.map
544
- //# sourceMappingURL=chunk-HMSAYMMX.cjs.map
543
+ //# sourceMappingURL=chunk-TUPSNW3B.cjs.map
544
+ //# sourceMappingURL=chunk-TUPSNW3B.cjs.map