@arbidocs/react 0.5.61 → 0.5.62
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.
- package/dist/ProductionDialog.d-CpzslFn0.d.cts +51 -0
- package/dist/ProductionDialog.d-CpzslFn0.d.ts +51 -0
- package/dist/annotations/freeze/index.cjs +14 -14
- package/dist/annotations/freeze/index.js +3 -3
- package/dist/annotations/index.d.cts +3 -2
- package/dist/annotations/index.d.ts +3 -2
- package/dist/artifacts/index.cjs +12 -12
- package/dist/artifacts/index.js +5 -5
- package/dist/bundle-IC65W2AO.cjs +14 -0
- package/dist/{bundle-DCWPYNGD.cjs.map → bundle-IC65W2AO.cjs.map} +1 -1
- package/dist/bundle-YNOX7VIL.js +5 -0
- package/dist/{bundle-JCKKGEJE.js.map → bundle-YNOX7VIL.js.map} +1 -1
- package/dist/calls/livekit/index.cjs +54 -54
- package/dist/calls/livekit/index.js +6 -6
- package/dist/{chunk-S2W3ZOWG.js → chunk-2LV53J46.js} +85 -16
- package/dist/chunk-2LV53J46.js.map +1 -0
- package/dist/{chunk-H3HYKAS5.cjs → chunk-3BFSALPC.cjs} +3 -3
- package/dist/{chunk-H3HYKAS5.cjs.map → chunk-3BFSALPC.cjs.map} +1 -1
- package/dist/{chunk-2NFUEC5O.js → chunk-3NBPMR3X.js} +3 -3
- package/dist/{chunk-2NFUEC5O.js.map → chunk-3NBPMR3X.js.map} +1 -1
- package/dist/chunk-4DTTEUVY.js +1042 -0
- package/dist/chunk-4DTTEUVY.js.map +1 -0
- package/dist/{chunk-U64WCQP3.js → chunk-AOEJ744V.js} +25 -14
- package/dist/chunk-AOEJ744V.js.map +1 -0
- package/dist/{chunk-4E737GNX.cjs → chunk-BLBXADTN.cjs} +86 -73
- package/dist/chunk-BLBXADTN.cjs.map +1 -0
- package/dist/{chunk-X7JXQT6F.cjs → chunk-DVL7EFZZ.cjs} +42 -46
- package/dist/chunk-DVL7EFZZ.cjs.map +1 -0
- package/dist/{chunk-VAMPYLQ4.cjs → chunk-DZUBZ45Y.cjs} +78 -2
- package/dist/chunk-DZUBZ45Y.cjs.map +1 -0
- package/dist/{chunk-OSWKXZTJ.js → chunk-ER4LFZG3.js} +12 -16
- package/dist/chunk-ER4LFZG3.js.map +1 -0
- package/dist/{chunk-5HDC43MF.js → chunk-G4Z3IP4J.js} +72 -3
- package/dist/chunk-G4Z3IP4J.js.map +1 -0
- package/dist/chunk-GOJHU7RZ.cjs +1122 -0
- package/dist/chunk-GOJHU7RZ.cjs.map +1 -0
- package/dist/{chunk-G76ASVVH.cjs → chunk-GQAXAZN7.cjs} +25 -14
- package/dist/chunk-GQAXAZN7.cjs.map +1 -0
- package/dist/{chunk-TUPSNW3B.cjs → chunk-LMW46NBD.cjs} +11 -11
- package/dist/{chunk-TUPSNW3B.cjs.map → chunk-LMW46NBD.cjs.map} +1 -1
- package/dist/{chunk-KRH55LXW.js → chunk-NCMSQACC.js} +37 -24
- package/dist/chunk-NCMSQACC.js.map +1 -0
- package/dist/{chunk-A2XSLTIP.js → chunk-NIKPG4PW.js} +3 -3
- package/dist/{chunk-A2XSLTIP.js.map → chunk-NIKPG4PW.js.map} +1 -1
- package/dist/{chunk-B6I2HRRF.cjs → chunk-PC4O3JDV.cjs} +3 -3
- package/dist/{chunk-B6I2HRRF.cjs.map → chunk-PC4O3JDV.cjs.map} +1 -1
- package/dist/{chunk-M2SZQBCO.js → chunk-SI7DJWBT.js} +3 -3
- package/dist/{chunk-M2SZQBCO.js.map → chunk-SI7DJWBT.js.map} +1 -1
- package/dist/{chunk-3QK4VVPG.cjs → chunk-TGSEQGM3.cjs} +3 -3
- package/dist/{chunk-3QK4VVPG.cjs.map → chunk-TGSEQGM3.cjs.map} +1 -1
- package/dist/{chunk-LCSUCZVX.cjs → chunk-ZNQPUPX6.cjs} +118 -41
- package/dist/chunk-ZNQPUPX6.cjs.map +1 -0
- package/dist/{chunk-CMNZI4WQ.js → chunk-ZTPJNKF2.js} +4 -4
- package/dist/{chunk-CMNZI4WQ.js.map → chunk-ZTPJNKF2.js.map} +1 -1
- package/dist/document-tools/core.cjs +408 -0
- package/dist/document-tools/core.cjs.map +1 -0
- package/dist/document-tools/core.d.cts +957 -0
- package/dist/document-tools/core.d.ts +957 -0
- package/dist/document-tools/core.js +15 -0
- package/dist/document-tools/core.js.map +1 -0
- package/dist/document-tools/index.cjs +347 -1130
- package/dist/document-tools/index.cjs.map +1 -1
- package/dist/document-tools/index.d.cts +12 -950
- package/dist/document-tools/index.d.ts +12 -950
- package/dist/document-tools/index.js +13 -1034
- package/dist/document-tools/index.js.map +1 -1
- package/dist/index.cjs +1510 -1255
- package/dist/index.cjs.map +1 -1
- package/dist/{index.d-BLw5AN0H.d.cts → index.d-AT7wdTWC.d.cts} +50 -2
- package/dist/{index.d-BLw5AN0H.d.ts → index.d-AT7wdTWC.d.ts} +50 -2
- package/dist/{index.d-DPVj21h1.d.ts → index.d-B0dosFZc.d.cts} +6 -6
- package/dist/{index.d-DPVj21h1.d.cts → index.d-B0dosFZc.d.ts} +6 -6
- package/dist/index.d.cts +145 -69
- package/dist/index.d.ts +145 -69
- package/dist/index.js +346 -121
- package/dist/index.js.map +1 -1
- package/dist/{query-keys.d-DEEMzkLz.d.cts → query-keys.d-BFKQVevT.d.cts} +21 -12
- package/dist/{query-keys.d-DEEMzkLz.d.ts → query-keys.d-BFKQVevT.d.ts} +21 -12
- package/dist/shell/index.cjs +68 -40
- package/dist/shell/index.d.cts +1 -1
- package/dist/shell/index.d.ts +1 -1
- package/dist/shell/index.js +3 -3
- package/dist/store.d-DkFXbWDk.d.ts +35 -0
- package/dist/store.d-GADDvC7w.d.cts +35 -0
- package/dist/ui/index.cjs +149 -149
- package/dist/ui/index.d.cts +1 -1
- package/dist/ui/index.d.ts +1 -1
- package/dist/ui/index.js +2 -2
- package/package.json +11 -3
- package/dist/ProductionDialog.d-BDJwBSzj.d.ts +0 -84
- package/dist/ProductionDialog.d-DjRQFmQw.d.cts +0 -84
- package/dist/bundle-DCWPYNGD.cjs +0 -14
- package/dist/bundle-JCKKGEJE.js +0 -5
- package/dist/chunk-4E737GNX.cjs.map +0 -1
- package/dist/chunk-5HDC43MF.js.map +0 -1
- package/dist/chunk-G76ASVVH.cjs.map +0 -1
- package/dist/chunk-KRH55LXW.js.map +0 -1
- package/dist/chunk-LCSUCZVX.cjs.map +0 -1
- package/dist/chunk-OSWKXZTJ.js.map +0 -1
- package/dist/chunk-S2W3ZOWG.js.map +0 -1
- package/dist/chunk-U64WCQP3.js.map +0 -1
- package/dist/chunk-VAMPYLQ4.cjs.map +0 -1
- package/dist/chunk-X7JXQT6F.cjs.map +0 -1
|
@@ -1,11 +1,10 @@
|
|
|
1
|
-
import { arbiQueryKeys } from './chunk-
|
|
1
|
+
import { arbiQueryKeys } from './chunk-AOEJ744V.js';
|
|
2
|
+
import { useArbiHost, useArbi } from './chunk-R7YNABZY.js';
|
|
2
3
|
import { OWN_SESSION_SLOT } from './chunk-DPYBZDJB.js';
|
|
3
4
|
import { parseVersionRef } from './chunk-NNWMHMEC.js';
|
|
4
|
-
import { useArbiHost, useArbi } from './chunk-R7YNABZY.js';
|
|
5
5
|
import { getUserEncryptionKeypair, sealedBoxDecrypt, sealedBoxEncrypt } from '@arbidocs/client';
|
|
6
6
|
import { useSyncExternalStore, useCallback, useMemo, useRef, useEffect } from 'react';
|
|
7
7
|
import { useQuery, useMutation, useQueryClient, useInfiniteQuery, useQueries } from '@tanstack/react-query';
|
|
8
|
-
import { ArbiApiError } from '@arbidocs/sdk/browser';
|
|
9
8
|
|
|
10
9
|
// src/session/layout.ts
|
|
11
10
|
var PANEL_MODES = ["main", "docked", "overlay", "popout"];
|
|
@@ -1170,16 +1169,7 @@ function useConversationThreads(conversationId, options) {
|
|
|
1170
1169
|
const session = useArbiSessionStore();
|
|
1171
1170
|
return useQuery({
|
|
1172
1171
|
queryKey: arbiQueryKeys.conversationThreads(conversationId ?? ""),
|
|
1173
|
-
queryFn:
|
|
1174
|
-
try {
|
|
1175
|
-
return await arbi.conversations.getThreads(conversationId);
|
|
1176
|
-
} catch (error) {
|
|
1177
|
-
if (error instanceof ArbiApiError && error.status === 404) {
|
|
1178
|
-
return { conversation_ext_id: conversationId, threads: [] };
|
|
1179
|
-
}
|
|
1180
|
-
throw error;
|
|
1181
|
-
}
|
|
1182
|
-
},
|
|
1172
|
+
queryFn: () => arbi.conversations.getThreads(conversationId),
|
|
1183
1173
|
enabled: (options?.enabled ?? true) && !!conversationId && arbi.hasWorkspace,
|
|
1184
1174
|
staleTime: 2 * 60 * 1e3,
|
|
1185
1175
|
refetchOnWindowFocus: () => session.getState().generating[conversationId ?? ""]?.isGenerating ? false : "always",
|
|
@@ -1200,7 +1190,13 @@ function useTags(workspaceId, options) {
|
|
|
1200
1190
|
const key = tagListKey(query);
|
|
1201
1191
|
return useQuery({
|
|
1202
1192
|
queryKey: key ? arbiQueryKeys.tagList(workspace, key) : arbiQueryKeys.tags(workspace),
|
|
1203
|
-
|
|
1193
|
+
// The request names the workspace (opened for this session first when it is not the current
|
|
1194
|
+
// one), so another workspace's tags can be listed and a switch cannot answer for it. The
|
|
1195
|
+
// current workspace's list is also read under the switch guard.
|
|
1196
|
+
queryFn: () => {
|
|
1197
|
+
const list = () => arbi.tags.list({ ...key ? query : {}, workspaceId: workspace });
|
|
1198
|
+
return workspace === arbi.getWorkspaceId() ? arbi.readInWorkspace(workspace, list) : list();
|
|
1199
|
+
},
|
|
1204
1200
|
enabled: (enabled ?? true) && !!workspace && arbi.hasWorkspace && (query.ids === void 0 || query.ids.length > 0),
|
|
1205
1201
|
...key ? {} : { staleTime: Infinity }
|
|
1206
1202
|
});
|
|
@@ -1486,5 +1482,5 @@ function useUserUsageToday(options) {
|
|
|
1486
1482
|
}
|
|
1487
1483
|
|
|
1488
1484
|
export { DEFAULT_DOCUMENT_VIEWER_STATE, EMPTY_SESSION_STATE, MAX_THREAD_TABS, MIN_QUEUED_MESSAGE_VISIBILITY_MS, PROJECT_CREATION_DENIED_REASON, WORKSPACE_LAST_OPENED_KEY, WORKSPACE_STORAGE_KEY, agentControl, browserWorkspaceStorage, clearSealedDrafts, closePanelIn, conversationKey, createArbiLayoutStore, createArbiSessionStore, createArbiWorkspaceStore, createDebouncedWriter, createSealedDraftStorage, createStoragePersist, defaultLayoutState, dmTabId, flushOnPageExit, isPanelOpen, isUsageMetered, layoutActionsOf, nextViewingDocument, openPanelIn, panelPlace, parseSavedLayout, queuedMessages, readWorkspaceLastOpened, restoreLayout, savedLayoutOf, selectDraft, selectIsGenerating, selectViewingDocumentId, threadTabId, useActivity, useAgents, useArbiSession, useArbiSessionState, useArbiSessionStore, useAssistantQuery, useAvailableModels, useBoxRole, useBuiltinCommands, useCanCreateProjects, useConfig, useConfigs, useConversationThreads, useConversations, useCurrentUser, useDeleteAgents, useDocumentVersionList, useFirmPool, useHealth, useMessageDetails, useParsedDocument, useProjectInvoices, useProjectUsage, useProjects, useProjectsUsage, useSessionPageTab, useSessionView, useSignedInSession, useTags, useThumbnails, useTopUpFirmPool, useTransientView, useUserUsageToday, useWorkspaceActivity, useWorkspaces };
|
|
1489
|
-
//# sourceMappingURL=chunk-
|
|
1490
|
-
//# sourceMappingURL=chunk-
|
|
1485
|
+
//# sourceMappingURL=chunk-ER4LFZG3.js.map
|
|
1486
|
+
//# sourceMappingURL=chunk-ER4LFZG3.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/session/layout.ts","../src/session/workspace.ts","../src/chat/run-state.ts","../src/session/store.ts","../src/session/drafts.ts","../src/session/session-hooks.ts","../src/session/signed-in.ts","../src/session/persist.ts","../src/usage-metered.ts","../src/hooks.ts"],"names":["useSyncExternalStore","useMemo"],"mappings":";;;;;;;;;AAwGA,IAAM,WAAA,GAAwC,CAAC,MAAA,EAAQ,QAAA,EAAU,WAAW,QAAQ,CAAA;AAGpF,IAAM,gBAAgB,MAAM,OAAO,MAAA,KAAW,WAAA,IAAe,OAAO,UAAA,IAAc,GAAA;AA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A,EAAS,IAAA,CAAK,SAAA,EAAW,CAAA;AACtE,EAAA,MAAM,UAAA,GAAa,YAAY,GAAA,CAAI,CAAC,MAAM,CAAA,CAAE,WAAW,CAAA,CAAE,IAAA,CAAK,GAAG,CAAA;AACjE,EAAA,MAAM,EAAE,SAAQ,GAAI,IAAA;AACpB,EAAA,MAAM,IAAA,GAAO,OAA2B,MAAS,CAAA;AACjD,EAAA,SAAA,CAAU,MAAM;AACd,IAAA,IAAI,UAAA,KAAe,MAAA,IAAa,UAAA,KAAe,IAAA,CAAK,OAAA,EAAS;AAC7D,IAAA,MAAM,KAAA,GAAQ,KAAK,OAAA,KAAY,MAAA;AAC/B,IAAA,IAAA,CAAK,OAAA,GAAU,UAAA;AACf,IAAA,IAAI,CAAC,KAAA,EAAO,KAAK,OAAA,EAAQ;AAAA,EAC3B,CAAA,EAAG,CAAC,UAAA,EAAY,OAAO,CAAC,CAAA;AACxB,EAAA,OAAO,KAAK,IAAA,EAAM,mBAAA;AACpB;AAOO,SAAS,kBAAkB,OAAA,EAAiC;AACjE,EAAA,MAAM,OAAO,OAAA,EAAQ;AACrB,EAAA,OAAO,QAAA,CAAS;AAAA,IACd,QAAA,EAAU,cAAc,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-ER4LFZG3.js","sourcesContent":["/**\n * The layout part of the session state: the shell (the page on screen, the sidebar, the panels and\n * where each one shows, the area with focus), the open tabs (direct messages, projects), each\n * page's view (its tab, its filters, other view settings) and the grids' saved state. Kits and the\n * host read and change it through the session store; the parts a person arranges (the page, the\n * pinned sidebar, the panels, the views, the grids) are kept across reloads by the host's\n * {@link ArbiSessionPersist}.\n */\n\nimport type { ArbiSessionPersist } from './persist'\n\n/** Where a panel shows: the page's area, docked beside it, over it, or in its own window. */\nexport type ArbiPanelMode = 'main' | 'docked' | 'overlay' | 'popout'\n\nexport interface ArbiPanelsState {\n /** The panel in each place (one each): filling the page, docked, over the page, popped out. */\n main: string | null\n docked: string | null\n overlay: string | null\n popout: string | null\n /** Where each panel last showed (it opens there again). */\n modes: Readonly<Record<string, ArbiPanelMode>>\n /** A floating panel's size. */\n sizes: Readonly<Record<string, { width: number; height: number }>>\n}\n\nexport interface ArbiSidebarState {\n /** Pinned open (on wide screens; phones show a drawer). */\n pinned: boolean\n /** The rail is expanded under the pointer. */\n hovering: boolean\n /** The phone drawer is open. */\n drawerOpen: boolean\n}\n\nexport interface ArbiShellState {\n /** The page on screen (a host's page id). */\n page: string\n sidebar: ArbiSidebarState\n panels: ArbiPanelsState\n /** The area with focus: `main` or a panel id. */\n focusedArea: string\n}\n\n/** A direct-message tab: a person's or agent's id, a group chat's id, or null (a new message). */\nexport interface ArbiDmTab {\n recipientId: string | null\n}\n\nexport interface ArbiTabsState {\n dm: readonly ArbiDmTab[]\n activeDm: string | null\n /** The message a direct-message tab scrolls to once open. */\n dmMessageId: string | null\n projects: readonly string[]\n activeProject: string | null\n}\n\nexport interface ArbiViewsState {\n /** Each page's tab, by page. */\n tabs: Readonly<Record<string, string>>\n /** Each list's quick filters, by list. */\n filters: Readonly<Record<string, unknown>>\n /** Other view settings, by key (a page's view mode, a zoom, a filter box's text). */\n values: Readonly<Record<string, unknown>>\n /** View state kept for this session only, by key (a search's results); not saved. */\n transient: Readonly<Record<string, unknown>>\n}\n\nexport interface ArbiGridLayoutState {\n /** Each grid's saved state (columns, widths, sort), by grid id. */\n states: Readonly<Record<string, unknown>>\n /** Each grid's row height. */\n rowHeights: Readonly<Record<string, number>>\n /** Each timeline's label column width. */\n labelWidths: Readonly<Record<string, number>>\n /** Views an earlier build saved on this device, by grid id (moved to user settings once). */\n savedViews: Readonly<Record<string, readonly unknown[]>>\n}\n\nexport interface ArbiLayoutState {\n shell: ArbiShellState\n tabs: ArbiTabsState\n views: ArbiViewsState\n grid: ArbiGridLayoutState\n}\n\n/** What is kept across reloads. */\nexport interface ArbiSavedLayout {\n version: 1\n /** The pieces an earlier build's own saved state was brought in for (the host's migration). */\n migrated: string[]\n shell: {\n page: string\n sidebarPinned: boolean\n panels: { main: string | null; docked: string | null } & Pick<\n ArbiPanelsState,\n 'modes' | 'sizes'\n >\n }\n views: Omit<ArbiViewsState, 'transient'>\n grid: ArbiGridLayoutState\n}\n\nconst PANEL_MODES: readonly ArbiPanelMode[] = ['main', 'docked', 'overlay', 'popout']\n\n/** Phones start with the sidebar as a drawer, wider screens pinned. */\nconst defaultPinned = () => typeof window === 'undefined' || window.innerWidth >= 640\n\nexport function defaultLayoutState(): ArbiLayoutState {\n return {\n shell: {\n page: 'home',\n sidebar: { pinned: defaultPinned(), hovering: false, drawerOpen: false },\n panels: { main: null, docked: null, overlay: null, popout: null, modes: {}, sizes: {} },\n focusedArea: 'main',\n },\n tabs: { dm: [], activeDm: null, dmMessageId: null, projects: [], activeProject: null },\n views: { tabs: {}, filters: {}, values: {}, transient: {} },\n grid: { states: {}, rowHeights: {}, labelWidths: {}, savedViews: {} },\n }\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\nconst recordOf = <T>(value: unknown, keep: (entry: unknown) => entry is T): Record<string, T> =>\n isRecord(value)\n ? (Object.fromEntries(Object.entries(value).filter(([, v]) => keep(v))) as Record<string, T>)\n : {}\n\nconst isString = (v: unknown): v is string => typeof v === 'string'\nconst isNumber = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v)\nconst isAny = (v: unknown): v is unknown => v !== undefined\nconst isMode = (v: unknown): v is ArbiPanelMode => PANEL_MODES.includes(v as ArbiPanelMode)\nconst isSize = (v: unknown): v is { width: number; height: number } =>\n isRecord(v) && isNumber(v.width) && isNumber(v.height)\nconst isList = (v: unknown): v is unknown[] => Array.isArray(v)\nconst stringOrNull = (v: unknown): string | null => (isString(v) ? v : null)\n\n/**\n * A saved layout as this build reads it: whatever an earlier or a broken save left is dropped\n * rather than read. Never throws; null when there is nothing usable.\n */\nexport function parseSavedLayout(saved: unknown): ArbiSavedLayout | null {\n if (!isRecord(saved) || saved.version !== 1) return null\n const shell = isRecord(saved.shell) ? saved.shell : {}\n const panels = isRecord(shell.panels) ? shell.panels : {}\n const views = isRecord(saved.views) ? saved.views : {}\n const grid = isRecord(saved.grid) ? saved.grid : {}\n const defaults = defaultLayoutState()\n return {\n version: 1,\n migrated: isList(saved.migrated) ? saved.migrated.filter(isString) : [],\n shell: {\n page: isString(shell.page) ? shell.page : defaults.shell.page,\n sidebarPinned:\n typeof shell.sidebarPinned === 'boolean'\n ? shell.sidebarPinned\n : defaults.shell.sidebar.pinned,\n panels: {\n main: stringOrNull(panels.main),\n docked: stringOrNull(panels.docked),\n modes: recordOf(panels.modes, isMode),\n sizes: recordOf(panels.sizes, isSize),\n },\n },\n views: {\n tabs: recordOf(views.tabs, isString),\n filters: recordOf(views.filters, isAny),\n values: recordOf(views.values, isAny),\n },\n grid: {\n states: recordOf(grid.states, isRecord),\n rowHeights: recordOf(grid.rowHeights, isNumber),\n labelWidths: recordOf(grid.labelWidths, isNumber),\n savedViews: recordOf(grid.savedViews, isList),\n },\n }\n}\n\n/** What of a layout is saved. */\nexport function savedLayoutOf(layout: ArbiLayoutState, migrated: string[]): ArbiSavedLayout {\n const { shell, views, grid } = layout\n return {\n version: 1,\n migrated,\n shell: {\n page: shell.page,\n sidebarPinned: shell.sidebar.pinned,\n // A panel over the page or in its own window does not come back after a reload.\n panels: {\n main: shell.panels.main,\n docked: shell.panels.docked,\n modes: shell.panels.modes,\n sizes: shell.panels.sizes,\n },\n },\n views: { tabs: views.tabs, filters: views.filters, values: views.values },\n grid,\n }\n}\n\n/** The layout a saved one restores (the parts not saved keep their current values). */\nexport function restoreLayout(current: ArbiLayoutState, saved: ArbiSavedLayout): ArbiLayoutState {\n return {\n ...current,\n shell: {\n ...current.shell,\n page: saved.shell.page,\n sidebar: { ...current.shell.sidebar, pinned: saved.shell.sidebarPinned },\n panels: { ...current.shell.panels, ...saved.shell.panels },\n },\n views: { ...saved.views, transient: current.views.transient },\n grid: saved.grid,\n }\n}\n\n// ── Changes ─────────────────────────────────────────────────────────────────────────────────────\n\n/** Show a panel in a place: it leaves the place it was in, and what was in that place closes. */\nexport function openPanelIn(\n panels: ArbiPanelsState,\n panelId: string,\n mode: ArbiPanelMode\n): ArbiPanelsState {\n const leave = (slot: string | null) => (slot === panelId ? null : slot)\n const next: ArbiPanelsState = {\n ...panels,\n main: leave(panels.main),\n docked: leave(panels.docked),\n overlay: leave(panels.overlay),\n popout: leave(panels.popout),\n modes: { ...panels.modes, [panelId]: mode },\n }\n // Docked and over the page are both the secondary surface beside the page: one at a time.\n if (mode === 'docked') return { ...next, docked: panelId, overlay: null }\n if (mode === 'overlay') return { ...next, overlay: panelId, docked: null }\n return { ...next, [mode]: panelId }\n}\n\nexport function closePanelIn(panels: ArbiPanelsState, panelId: string): ArbiPanelsState {\n const leave = (slot: string | null) => (slot === panelId ? null : slot)\n return {\n ...panels,\n main: leave(panels.main),\n docked: leave(panels.docked),\n overlay: leave(panels.overlay),\n popout: leave(panels.popout),\n }\n}\n\n/** Where a panel shows now, or null while it is closed. */\nexport function panelPlace(panels: ArbiPanelsState, panelId: string): ArbiPanelMode | null {\n return PANEL_MODES.find((mode) => panels[mode] === panelId) ?? null\n}\n\n/** Whether a panel is open (anywhere). */\nexport const isPanelOpen = (state: { shell: ArbiShellState }, panelId: string): boolean =>\n panelPlace(state.shell.panels, panelId) !== null\n\nexport const dmTabId = (tab: ArbiDmTab): string => tab.recipientId ?? 'new'\n\n/** The actions on the layout (part of {@link ArbiSessionStore}). */\nexport interface ArbiLayoutActions {\n /** Show a page; the focus goes to the page area. */\n setPage(page: string): void\n setSidebar(change: Partial<ArbiSidebarState>): void\n /** Show a panel in a place (`mode`), focused. */\n openPanel(panelId: string, mode: ArbiPanelMode): void\n closePanel(panelId: string): void\n /** Where a panel shows: an open one moves there, a closed one opens there next time. */\n setPanelMode(panelId: string, mode: ArbiPanelMode): void\n setPanelSize(panelId: string, size: { width: number; height: number }): void\n setFocusedArea(area: string): void\n /** Open (or show) a direct-message tab, optionally scrolled to a message. */\n openDmTab(recipientId: string | null, messageId?: string): void\n closeDmTab(tabId: string): void\n /** null: no direct-message tab (the panel's own). */\n selectDmTab(tabId: string | null): void\n clearDmTabs(): void\n setDmMessageId(messageId: string | null): void\n openProjectTab(projectId: string): void\n closeProjectTab(projectId: string): void\n /** null: the projects list. */\n selectProjectTab(projectId: string | null): void\n setPageTab(page: string, tab: string): void\n setViewFilter(key: string, value: unknown): void\n setViewValue(key: string, value: unknown): void\n /** Set (or with `undefined`, drop) view state kept for this session only. */\n setTransientView(key: string, value: unknown): void\n setGridState(gridId: string, state: unknown): void\n clearGridState(gridId: string): void\n setGridRowHeight(gridId: string, height: number): void\n setGridLabelWidth(gridId: string, width: number): void\n setGridSavedViews(gridId: string, views: readonly unknown[]): void\n /**\n * Start over: a sign-in shows the home page with the sidebar at its default and no panel, tab\n * or page tab open; a sign-out also forgets the grids.\n */\n resetLayout(variant: 'login' | 'logout'): void\n}\n\n/** A store of the layout alone; the session stores are built on it. */\nexport interface ArbiLayoutStore extends ArbiLayoutActions {\n getLayout(): ArbiLayoutState\n /** Back to the defaults, everything (unit tests; a reset from an error screen). */\n reset(): void\n subscribe(listener: () => void): () => void\n /** Resolves once the saved layout has been read (at once without a `persist`). */\n hydrated(): Promise<void>\n isHydrated(): boolean\n}\n\nexport interface ArbiLayoutStoreOptions {\n persist?: ArbiSessionPersist<ArbiSavedLayout>\n}\n\nexport function createArbiLayoutStore({ persist }: ArbiLayoutStoreOptions = {}): ArbiLayoutStore {\n let layout = defaultLayoutState()\n let migrated: string[] = []\n let isHydrated = !persist\n const listeners = new Set<() => void>()\n const save = () => {\n // Nothing is saved before the saved layout is read: it would overwrite it with the defaults.\n if (persist && isHydrated) persist.save(savedLayoutOf(layout, migrated))\n }\n const update = (next: ArbiLayoutState) => {\n if (next === layout) return\n const persisted =\n next.views.tabs !== layout.views.tabs ||\n next.views.filters !== layout.views.filters ||\n next.views.values !== layout.views.values ||\n next.grid !== layout.grid ||\n next.shell.page !== layout.shell.page ||\n next.shell.sidebar.pinned !== layout.shell.sidebar.pinned ||\n next.shell.panels !== layout.shell.panels\n layout = next\n listeners.forEach((listener) => listener())\n if (persisted) save()\n }\n const shell = (change: Partial<ArbiShellState>) =>\n update({ ...layout, shell: { ...layout.shell, ...change } })\n const tabs = (change: Partial<ArbiTabsState>) =>\n update({ ...layout, tabs: { ...layout.tabs, ...change } })\n const views = (change: Partial<ArbiViewsState>) =>\n update({ ...layout, views: { ...layout.views, ...change } })\n const grid = (change: Partial<ArbiGridLayoutState>) =>\n update({ ...layout, grid: { ...layout.grid, ...change } })\n\n const hydration: Promise<void> = persist\n ? persist.load().then(\n (saved) => {\n const parsed = parseSavedLayout(saved)\n if (parsed) {\n migrated = parsed.migrated\n layout = restoreLayout(layout, parsed)\n }\n isHydrated = true\n listeners.forEach((listener) => listener())\n },\n () => {\n isHydrated = true\n listeners.forEach((listener) => listener())\n }\n )\n : Promise.resolve()\n\n return {\n getLayout: () => layout,\n reset: () => update(defaultLayoutState()),\n subscribe: (listener) => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n hydrated: () => hydration,\n isHydrated: () => isHydrated,\n setPage: (page) => {\n if (layout.shell.page !== page || layout.shell.focusedArea !== 'main')\n shell({ page, focusedArea: 'main' })\n },\n setSidebar: (change) => {\n const sidebar = { ...layout.shell.sidebar, ...change }\n const current = layout.shell.sidebar\n if (\n sidebar.pinned !== current.pinned ||\n sidebar.hovering !== current.hovering ||\n sidebar.drawerOpen !== current.drawerOpen\n )\n shell({ sidebar })\n },\n openPanel: (panelId, mode) =>\n shell({ panels: openPanelIn(layout.shell.panels, panelId, mode), focusedArea: panelId }),\n closePanel: (panelId) =>\n shell({ panels: closePanelIn(layout.shell.panels, panelId), focusedArea: 'main' }),\n setPanelMode: (panelId, mode) => {\n const panels = layout.shell.panels\n if (panelPlace(panels, panelId) !== null)\n shell({ panels: openPanelIn(panels, panelId, mode), focusedArea: panelId })\n else if (panels.modes[panelId] !== mode)\n shell({ panels: { ...panels, modes: { ...panels.modes, [panelId]: mode } } })\n },\n setPanelSize: (panelId, size) => {\n const panels = layout.shell.panels\n shell({ panels: { ...panels, sizes: { ...panels.sizes, [panelId]: size } } })\n },\n setFocusedArea: (focusedArea) => {\n if (layout.shell.focusedArea !== focusedArea) shell({ focusedArea })\n },\n openDmTab: (recipientId, messageId) => {\n const id = recipientId ?? 'new'\n const dm = layout.tabs.dm.some((tab) => dmTabId(tab) === id)\n ? layout.tabs.dm\n : [...layout.tabs.dm, { recipientId }]\n tabs({ dm, activeDm: id, ...(messageId ? { dmMessageId: messageId } : {}) })\n },\n closeDmTab: (tabId) => {\n const dm = layout.tabs.dm.filter((tab) => dmTabId(tab) !== tabId)\n if (dm.length === layout.tabs.dm.length) return\n if (dm.length === 0) return tabs({ dm, activeDm: null })\n if (layout.tabs.activeDm !== tabId) return tabs({ dm })\n // The tab beside the closed one shows.\n const index = layout.tabs.dm.findIndex((tab) => dmTabId(tab) === tabId)\n tabs({ dm, activeDm: dmTabId(dm[Math.min(index, dm.length - 1)]) })\n },\n selectDmTab: (activeDm) => {\n if (layout.tabs.activeDm !== activeDm) tabs({ activeDm })\n },\n clearDmTabs: () => tabs({ dm: [], activeDm: null }),\n setDmMessageId: (dmMessageId) => {\n if (layout.tabs.dmMessageId !== dmMessageId) tabs({ dmMessageId })\n },\n openProjectTab: (projectId) =>\n tabs({\n projects: layout.tabs.projects.includes(projectId)\n ? layout.tabs.projects\n : [...layout.tabs.projects, projectId],\n activeProject: projectId,\n }),\n closeProjectTab: (projectId) => {\n const projects = layout.tabs.projects.filter((id) => id !== projectId)\n if (projects.length === layout.tabs.projects.length) return\n if (layout.tabs.activeProject !== projectId) return tabs({ projects })\n const index = layout.tabs.projects.indexOf(projectId)\n tabs({\n projects,\n activeProject: projects.length ? projects[Math.min(index, projects.length - 1)] : null,\n })\n },\n selectProjectTab: (activeProject) => {\n if (layout.tabs.activeProject !== activeProject) tabs({ activeProject })\n },\n setPageTab: (page, tab) => {\n if (layout.views.tabs[page] !== tab) views({ tabs: { ...layout.views.tabs, [page]: tab } })\n },\n setViewFilter: (key, value) => views({ filters: { ...layout.views.filters, [key]: value } }),\n setViewValue: (key, value) => {\n if (layout.views.values[key] !== value)\n views({ values: { ...layout.views.values, [key]: value } })\n },\n setTransientView: (key, value) => {\n if (layout.views.transient[key] === value) return\n const transient = { ...layout.views.transient }\n if (value === undefined) delete transient[key]\n else transient[key] = value\n views({ transient })\n },\n setGridState: (gridId, state) => grid({ states: { ...layout.grid.states, [gridId]: state } }),\n clearGridState: (gridId) => {\n if (!(gridId in layout.grid.states)) return\n const states = { ...layout.grid.states }\n delete states[gridId]\n grid({ states })\n },\n setGridRowHeight: (gridId, height) =>\n grid({ rowHeights: { ...layout.grid.rowHeights, [gridId]: height } }),\n setGridLabelWidth: (gridId, width) =>\n grid({ labelWidths: { ...layout.grid.labelWidths, [gridId]: width } }),\n setGridSavedViews: (gridId, saved) =>\n grid({ savedViews: { ...layout.grid.savedViews, [gridId]: saved } }),\n resetLayout: (variant) => {\n const fresh = defaultLayoutState()\n update({\n shell: {\n ...fresh.shell,\n panels: {\n ...fresh.shell.panels,\n modes: layout.shell.panels.modes,\n sizes: layout.shell.panels.sizes,\n },\n },\n tabs: fresh.tabs,\n views: { ...layout.views, tabs: {}, transient: {} },\n grid: variant === 'logout' ? { ...layout.grid, states: {} } : layout.grid,\n })\n },\n }\n}\n","/**\n * The session's selected workspace (`workspaceId`) and where it stands on the server session\n * (`workspaceStatus`). `useSwitchWorkspace` moves both; a session store reads them from here.\n *\n * The selection is kept per tab (sessionStorage), so a reload stays in the workspace and each tab\n * can be in a different one; a new sign-in starts with none ({@link ArbiWorkspaceStore.reset}).\n * The status is never kept: after a reload the server session is new, and\n * `useOpenSelectedWorkspace` opens the kept selection again.\n */\n\nimport type { ArbiWorkspaceStatus } from './store'\n\n/** Where the selection is kept across reloads. */\nexport interface ArbiWorkspaceStorage {\n load(): string | null\n save(workspaceId: string | null): void\n}\n\n/** The selection and its status. */\nexport interface ArbiWorkspaceState {\n workspaceId: string | null\n workspaceStatus: ArbiWorkspaceStatus\n}\n\nexport interface ArbiWorkspaceStore {\n getState(): ArbiWorkspaceState\n subscribe(listener: () => void): () => void\n setWorkspaceId(workspaceId: string | null): void\n setWorkspaceStatus(status: ArbiWorkspaceStatus): void\n /** No workspace, closed (a sign-in or sign-out: the next person starts on the workspace list). */\n reset(): void\n}\n\nexport interface ArbiWorkspaceStoreOptions {\n storage?: ArbiWorkspaceStorage\n /** The selection to start with instead of the kept one. */\n workspaceId?: string | null\n}\n\nexport function createArbiWorkspaceStore({\n storage,\n workspaceId = storage?.load() ?? null,\n}: ArbiWorkspaceStoreOptions = {}): ArbiWorkspaceStore {\n let state: ArbiWorkspaceState = { workspaceId, workspaceStatus: 'closed' }\n const listeners = new Set<() => void>()\n const update = (patch: Partial<ArbiWorkspaceState>) => {\n state = { ...state, ...patch }\n listeners.forEach((listener) => listener())\n }\n const setWorkspaceId = (id: string | null) => {\n storage?.save(id)\n if (state.workspaceId !== id) update({ workspaceId: id })\n }\n return {\n getState: () => state,\n subscribe: (listener) => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n setWorkspaceId,\n setWorkspaceStatus: (workspaceStatus) => {\n if (state.workspaceStatus !== workspaceStatus) update({ workspaceStatus })\n },\n reset: () => {\n storage?.save(null)\n if (state.workspaceId !== null || state.workspaceStatus !== 'closed')\n update({ workspaceId: null, workspaceStatus: 'closed' })\n },\n }\n}\n\n/** The sessionStorage key of the selection (per tab). */\nexport const WORKSPACE_STORAGE_KEY = 'arbi_workspace_id'\n/** The localStorage key of when each workspace was last opened (per browser). */\nexport const WORKSPACE_LAST_OPENED_KEY = 'arbi_workspace_last_opened'\n\nexport interface BrowserWorkspaceStorageOptions {\n /** Default {@link WORKSPACE_STORAGE_KEY}. */\n key?: string\n /** Default {@link WORKSPACE_LAST_OPENED_KEY}. */\n lastOpenedKey?: string\n}\n\n/**\n * The browser's: the selection per tab (sessionStorage), and when each workspace was last opened\n * per browser (localStorage, read with {@link readWorkspaceLastOpened}: \"recently opened\" is a\n * history that outlives a tab, the selection deliberately does not).\n */\nexport function browserWorkspaceStorage({\n key = WORKSPACE_STORAGE_KEY,\n lastOpenedKey = WORKSPACE_LAST_OPENED_KEY,\n}: BrowserWorkspaceStorageOptions = {}): ArbiWorkspaceStorage {\n return {\n load() {\n try {\n return window.sessionStorage.getItem(key)\n } catch {\n return null\n }\n },\n save(workspaceId) {\n try {\n if (!workspaceId) {\n window.sessionStorage.removeItem(key)\n return\n }\n window.sessionStorage.setItem(key, workspaceId)\n const lastOpened = readWorkspaceLastOpened(lastOpenedKey)\n lastOpened[workspaceId] = Date.now()\n window.localStorage.setItem(lastOpenedKey, JSON.stringify(lastOpened))\n } catch {\n // Storage unavailable (private mode, quota): the selection lives in memory only.\n }\n },\n }\n}\n\n/** When each workspace was last opened in this browser (`external_id` → epoch ms). */\nexport function readWorkspaceLastOpened(\n lastOpenedKey = WORKSPACE_LAST_OPENED_KEY\n): Record<string, number> {\n try {\n const raw = window.localStorage.getItem(lastOpenedKey)\n const parsed: unknown = raw ? JSON.parse(raw) : null\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed)\n ? (parsed as Record<string, number>)\n : {}\n } catch {\n return {}\n }\n}\n","/**\n * The 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 createArbiLayoutStore,\n defaultLayoutState,\n type ArbiLayoutActions,\n type ArbiLayoutState,\n type ArbiLayoutStore,\n type ArbiSavedLayout,\n} from './layout'\nimport type { ArbiSessionPersist } from './persist'\nimport { createArbiWorkspaceStore, type ArbiWorkspaceStore } from './workspace'\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, ArbiLayoutState {\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 extends ArbiLayoutActions {\n /** The current state. The same object until something in it changes. */\n getState(): ArbiSessionState\n /** Resolves once the saved layout has been read (at once when none is kept). */\n layoutHydrated(): Promise<void>\n /** Whether the saved layout has been read. */\n isLayoutHydrated(): boolean\n /** Be told when the state may have changed. Returns the unsubscribe. */\n subscribe(listener: () => void): () => void\n setWorkspaceId(id: string | null): void\n setWorkspaceStatus(status: ArbiWorkspaceStatus): void\n /**\n * Drop everything scoped to the workspace being left (the open conversation and its generation,\n * the 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 ...defaultLayoutState(),\n}\n\n/** The viewed document itself (`doc-…`), also while one of its earlier versions is on screen. */\nexport const selectViewingDocumentId = (state: ArbiSessionState): string | null =>\n state.viewingDocument ? parseVersionRef(state.viewingDocument.id).docId : null\n\n/** The conversation key drafts and context are kept under: its id, or `new` for a new chat. */\nexport const conversationKey = (state: 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 /** Keep the layout across reloads (see {@link createStoragePersist}). */\n persist?: ArbiSessionPersist<ArbiSavedLayout>\n /**\n * The selected workspace and its status (default: in memory, from `initial.workspaceId`). Give\n * one kept per tab (`createArbiWorkspaceStore({ storage: browserWorkspaceStorage() })`) for a\n * reload to stay in the workspace.\n */\n workspace?: ArbiWorkspaceStore\n}\n\n/** The layout actions of a session store, on its layout store. */\nexport function layoutActionsOf(layout: ArbiLayoutStore): ArbiLayoutActions {\n const actions = { ...layout } as Partial<ArbiLayoutStore>\n delete actions.getLayout\n delete actions.subscribe\n delete actions.hydrated\n delete actions.isHydrated\n delete actions.reset\n return actions as ArbiLayoutActions\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 {\n draftStorage,\n persist,\n workspace = createArbiWorkspaceStore({ workspaceId: initial.workspaceId ?? null }),\n }: ArbiSessionStoreOptions = {}\n): ArbiSessionStore {\n const layout = createArbiLayoutStore({ persist })\n if (initial.workspaceStatus) workspace.setWorkspaceStatus(initial.workspaceStatus)\n let state: ArbiSessionState = {\n ...EMPTY_SESSION_STATE,\n ...layout.getLayout(),\n ...initial,\n ...workspace.getState(),\n }\n const listeners = new Set<() => void>()\n const update = (patch: Partial<ArbiSessionState>) => {\n state = { ...state, ...patch }\n listeners.forEach((listener) => listener())\n }\n layout.subscribe(() => update(layout.getLayout()))\n workspace.subscribe(() => update(workspace.getState()))\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 ...layoutActionsOf(layout),\n layoutHydrated: () => layout.hydrated(),\n isLayoutHydrated: () => layout.isHydrated(),\n getState: () => state,\n subscribe: (listener) => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n setWorkspaceId: (workspaceId) => {\n workspace.setWorkspaceId(workspaceId)\n // A workspace opens once signed in: the key that opens the saved drafts is there now.\n restoreDrafts()\n },\n setWorkspaceStatus: (workspaceStatus) => workspace.setWorkspaceStatus(workspaceStatus),\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 workspace.setWorkspaceStatus('closed')\n update({\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 { useCallback, useSyncExternalStore } from 'react'\nimport { useArbiHost, type ArbiHostConfig } from '../host/config'\nimport { OWN_SESSION_SLOT } from '../host/merge'\nimport { createArbiSessionStore, type ArbiSessionState, type ArbiSessionStore } from './store'\nimport { createSealedDraftStorage } from './drafts'\n\n/** Who is signed in on the host's `Arbi` (its session), `null` when no one is. */\nfunction signedInUser(host: ArbiHostConfig): string | null {\n const state = host.arbi?.session?.getState()\n return state?.signedIn && state.userExtId ? state.userExtId : null\n}\n\n/** A host's own session: in memory, with its drafts kept sealed for the signed-in person. */\nconst createOwnStore = (host: ArbiHostConfig) =>\n createArbiSessionStore(\n {},\n { draftStorage: createSealedDraftStorage({ owner: () => signedInUser(host) }) }\n )\n\nlet moduleDefault: ArbiSessionStore | null = null\nconst defaultStore = () => (moduleDefault ??= createArbiSessionStore())\n\n/** The session store: its setters, and `getState()` for the state as of now (in callbacks). */\nexport function useArbiSessionStore(): ArbiSessionStore {\n const host = useArbiHost()\n if (host.session) return host.session\n const own = (host as Record<string, unknown>)[OWN_SESSION_SLOT] as\n { current: ArbiSessionStore | null } | undefined\n if (own) return (own.current ??= createOwnStore(host))\n return defaultStore()\n}\n\n/**\n * A slice of the session state; re-renders when it changes. The selector returns a value from the\n * state or a primitive (a new object each call would never settle).\n */\nexport function useArbiSessionState<T>(selector: (state: ArbiSessionState) => T): T {\n const store = useArbiSessionStore()\n const select = () => selector(store.getState())\n return useSyncExternalStore(store.subscribe, select, select)\n}\n\n/**\n * A view setting kept in the session and saved across reloads (`views.values`: a page's view\n * mode, a zoom, a filter box's text), and its setter. `fallback` while none is set.\n */\nexport function useSessionView<T>(key: string, fallback: T): [T, (value: T) => void] {\n const store = useArbiSessionStore()\n const value = useArbiSessionState((state) => state.views.values[key]) as T | undefined\n const set = useCallback((next: T) => store.setViewValue(key, next), [store, key])\n return [value === undefined ? fallback : value, set]\n}\n\n/**\n * View state kept for this session only (`views.transient`: a search's results, a one-shot\n * request), and its setter (`undefined` drops it). `fallback` while none is set.\n */\nexport function useTransientView<T>(key: string, fallback: T): [T, (value: T | undefined) => void] {\n const store = useArbiSessionStore()\n const value = useArbiSessionState((state) => state.views.transient[key]) as T | undefined\n const set = useCallback((next: T | undefined) => store.setTransientView(key, next), [store, key])\n return [value === undefined ? fallback : value, set]\n}\n\n/** A page's selected tab, kept across reloads; the host supplies its default tab. */\nexport function useSessionPageTab(\n page: string,\n fallback: string\n): {\n activeTab: string\n setActiveTab: (tab: string) => void\n} {\n const store = useArbiSessionStore()\n const activeTab = useArbiSessionState((state) => state.views.tabs[page]) || fallback\n const setActiveTab = useCallback((tab: string) => store.setPageTab(page, tab), [store, page])\n return { activeTab, setActiveTab }\n}\n","/**\n * Who is signed in: the host `Arbi`'s session (`arbi.session`, the client's session state), the\n * one source for the user, the sign-in status and the SSO mode. Re-renders when it changes.\n */\n\nimport { useMemo, useSyncExternalStore } from 'react'\nimport type { SessionManager, SessionState, SessionUser } from '@arbidocs/client'\nimport { useArbiHost } from '../host/config'\n\nexport type ArbiSessionStatus = 'signed-out' | 'signed-in'\n\nexport interface ArbiSignedInSession {\n /** `signed-in` once a login finished on this device (also before this tab has a token). */\n status: ArbiSessionStatus\n /** The signed-in user; `null` signed out. */\n user: SessionUser | null\n /** The account signs in through SSO. */\n isSso: boolean\n /** This tab holds a server session (a token). A new tab or an offline unlock does not, yet. */\n hasToken: boolean\n /** The server session key workspace keys are sealed to; `null` until known. */\n serverSessionKey: Uint8Array | null\n}\n\nconst SIGNED_OUT: ArbiSignedInSession = {\n status: 'signed-out',\n user: null,\n isSso: false,\n hasToken: false,\n serverSessionKey: null,\n}\n\nconst noSubscription = () => () => {}\n\n/** The signed-in session of the host's `Arbi`; signed out without one. */\nexport function useArbiSession(): ArbiSignedInSession {\n return useSignedInSession(useArbiHost().arbi?.session ?? null)\n}\n\n/** The same for a session the caller holds (the host building its `Arbi` on it). */\nexport function useSignedInSession(session: SessionManager | null): ArbiSignedInSession {\n const state = useSyncExternalStore<SessionState | null>(\n session ? session.subscribe : noSubscription,\n () => session?.getState() ?? null,\n () => session?.getState() ?? null\n )\n return useMemo(\n () =>\n state?.signedIn\n ? {\n status: 'signed-in',\n user: state.user,\n isSso: state.isSsoMode,\n hasToken: !!state.accessToken,\n serverSessionKey: state.serverSessionKey,\n }\n : { ...SIGNED_OUT, isSso: state?.isSsoMode ?? false },\n [state]\n )\n}\n","/**\n * Keeping the session's layout across reloads: a host gives the session store a\n * {@link ArbiSessionPersist} (where the saved layout is read and written), and the store reads it\n * once at start and writes it after each change. {@link createStoragePersist} makes one from any\n * key-value storage (IndexedDB, `localStorage`), writing at most once per quiet period and on page\n * exit, so a stream of changes (dragging a column) is one write and a reload never loses the last.\n */\n\n/** Where a session store keeps its saved layout. */\nexport interface ArbiSessionPersist<T = unknown> {\n /** The saved value, or null when none (or it cannot be read). Never rejects. */\n load(): Promise<T | null>\n /** Save the latest value (may be written later; the latest one wins). */\n save(value: T): void\n /** Forget the saved value (signing out). */\n clear?(): Promise<void>\n}\n\n/** A key-value storage, asynchronous or not (IndexedDB, `localStorage`). */\nexport interface ArbiKeyValueStorage {\n get(key: string): Promise<string | null> | string | null\n set(key: string, value: string): Promise<void> | void\n remove(key: string): Promise<void> | void\n}\n\nexport interface DebouncedWriterOptions {\n /** Performs the write. Errors are reported through `onError`, never thrown to the caller. */\n write: (key: string, value: string) => Promise<void> | void\n /** Trailing-edge quiet period. */\n delayMs: number\n /** Longest a pending value may wait from its first unwritten change. */\n maxWaitMs: number\n onError?: (key: string, error: unknown) => void\n}\n\nexport interface DebouncedWriter {\n /** Queue `value` as the latest value of `key`. */\n schedule: (key: string, value: string) => void\n /** The value queued for `key` but not yet written, if any. */\n pending: (key: string) => string | undefined\n /** Drop the queued value of `key` without writing it. */\n cancel: (key: string) => void\n /** Write every queued value now. */\n flushAll: () => void\n}\n\ninterface Pending {\n value: string\n timer: ReturnType<typeof setTimeout>\n /** When the first change not yet written was queued. */\n firstQueuedAt: number\n}\n\n/**\n * Per-key debounced writer. Rapid successive writes of one key collapse into a single\n * trailing-edge write `delayMs` after the last call; `maxWaitMs` caps how long a steady stream of\n * changes can postpone it.\n */\nexport function createDebouncedWriter({\n write,\n delayMs,\n maxWaitMs,\n onError,\n}: DebouncedWriterOptions): DebouncedWriter {\n const queue = new Map<string, Pending>()\n\n const run = (key: string, value: string) => {\n try {\n void Promise.resolve(write(key, value)).catch((error: unknown) => onError?.(key, error))\n } catch (error) {\n onError?.(key, error)\n }\n }\n\n const flush = (key: string) => {\n const entry = queue.get(key)\n if (!entry) return\n clearTimeout(entry.timer)\n queue.delete(key)\n run(key, entry.value)\n }\n\n return {\n schedule(key, value) {\n const now = Date.now()\n const existing = queue.get(key)\n if (existing) clearTimeout(existing.timer)\n const firstQueuedAt = existing?.firstQueuedAt ?? now\n const wait = Math.max(0, Math.min(delayMs, firstQueuedAt + maxWaitMs - now))\n queue.set(key, { value, firstQueuedAt, timer: setTimeout(() => flush(key), wait) })\n },\n pending: (key) => queue.get(key)?.value,\n cancel(key) {\n const entry = queue.get(key)\n if (!entry) return\n clearTimeout(entry.timer)\n queue.delete(key)\n },\n flushAll() {\n for (const key of Array.from(queue.keys())) flush(key)\n },\n }\n}\n\n/**\n * Flush `writer` whenever the page may be about to go away: `pagehide`, `visibilitychange` to\n * hidden (often the last event a mobile browser delivers) and `beforeunload`. Returns a function\n * that removes the listeners.\n */\nexport function flushOnPageExit(writer: Pick<DebouncedWriter, 'flushAll'>): () => void {\n if (typeof window === 'undefined' || typeof document === 'undefined') return () => {}\n const flush = () => writer.flushAll()\n const onVisibility = () => {\n if (document.visibilityState === 'hidden') writer.flushAll()\n }\n window.addEventListener('beforeunload', flush)\n window.addEventListener('pagehide', flush)\n document.addEventListener('visibilitychange', onVisibility)\n return () => {\n window.removeEventListener('beforeunload', flush)\n window.removeEventListener('pagehide', flush)\n document.removeEventListener('visibilitychange', onVisibility)\n }\n}\n\nexport interface StoragePersistOptions<T> {\n storage: ArbiKeyValueStorage\n /** The storage key. */\n key: string\n /** Read a value saved under `key` by an earlier build (default: as JSON). Never throws. */\n parse?: (saved: unknown) => T | null\n /**\n * Bring in what an earlier build saved elsewhere: called on every load with what is saved under\n * `key` (null: nothing yet), it returns the value to start from. A value other than the one given\n * is saved under `key` at once, so each piece is brought in once.\n */\n migrate?: (saved: T | null) => Promise<T | null>\n /** Quiet period before a write (default 250 ms), and the longest wait (default 1 s). */\n delayMs?: number\n maxWaitMs?: number\n}\n\n/** A {@link ArbiSessionPersist} on a key-value storage, debounced and flushed on page exit. */\nexport function createStoragePersist<T>({\n storage,\n key,\n parse = (saved) => saved as T,\n migrate,\n delayMs = 250,\n maxWaitMs = 1000,\n}: StoragePersistOptions<T>): ArbiSessionPersist<T> {\n const writer = createDebouncedWriter({\n write: (k, value) => storage.set(k, value),\n delayMs,\n maxWaitMs,\n onError: (k, error) => console.error(`[session] Failed to save ${k}:`, error),\n })\n flushOnPageExit(writer)\n const read = async (): Promise<T | null> => {\n // A queued write is the latest value.\n const pending = writer.pending(key)\n const raw = pending ?? (await storage.get(key))\n if (raw === null || raw === undefined) return null\n return parse(JSON.parse(raw))\n }\n return {\n async load() {\n try {\n const saved = await read()\n if (!migrate) return saved\n const migrated = await migrate(saved)\n if (migrated !== null && migrated !== saved)\n await storage.set(key, JSON.stringify(migrated))\n return migrated\n } catch (error) {\n console.warn('[session] The saved layout could not be read; starting from defaults', error)\n return null\n }\n },\n save: (value) => writer.schedule(key, JSON.stringify(value)),\n async clear() {\n writer.cancel(key)\n await storage.remove(key)\n },\n }\n}\n","/**\n * AI usage is reported in pounds (ex VAT).\n *\n * The usage endpoints (`/v1/user/projects/{id}/usage`, `/me/usage/today`) convert the metered\n * LiteLLM USD spend into £ at the API boundary (fractional, rounded to 2 decimals). The fields are\n * still named `spend` / `total_spend` in the schema, but they hold £, never dollars. Format them\n * with `formatGbp` (re-exported from `@arbidocs/sdk`).\n */\n\n/** The slice of a usage response that tells whether anything was recorded. */\nexport interface UsageTotals {\n total_spend: number\n total_tokens: number\n total_requests: number\n}\n\n/**\n * Was this usage actually metered? A `dev`-plan project with an all-zero response (no spend, no\n * tokens, no requests) is treated as \"not metered\", so the UI shows a note instead of silent\n * zeros. Any recorded tokens or requests mean usage was metered, even when the spend rounds to 0\n * (the backend records usage when billing is off, and a tiny spend can be £0.00).\n */\nexport function isUsageMetered(\n usage: UsageTotals,\n subscription: string | null | undefined\n): boolean {\n const empty = usage.total_spend === 0 && usage.total_tokens === 0 && usage.total_requests === 0\n return !(empty && subscription === 'dev')\n}\n","/**\n * React Query hooks that use the Arbi instance from context.\n */\n\nimport { useEffect, useMemo, useRef } from 'react'\nimport {\n useInfiniteQuery,\n useQuery,\n useQueries,\n useMutation,\n useQueryClient,\n} from '@tanstack/react-query'\nimport {\n type AskHandlers,\n type AskRequest,\n type SSEStreamResult,\n type TagListQuery,\n type ThreadsResponse,\n} from '@arbidocs/sdk/browser'\nimport { useArbi } from './useArbi'\nimport { useArbiSessionStore } from './session'\nimport type { ParsedDocument } from './documents/parsed-types'\nimport { isUsageMetered } from './usage-metered'\nimport { parseVersionRef } from './artifacts/versions'\n\n// ── Query keys ──────────────────────────────────────────────────────────────\n\n// The one key factory (every query and mutation key of the packages and the app): ./query-keys.\nexport { arbiQueryKeys, arbiMutationKeys } from './query-keys'\nimport { arbiQueryKeys } from './query-keys'\n\n// ── Hooks ───────────────────────────────────────────────────────────────────\n\n/** List the logged-in user's workspaces. */\nexport function useWorkspaces(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.workspaces(),\n queryFn: () => arbi.workspaces.list(),\n enabled: (options?.enabled ?? true) && arbi.isLoggedIn,\n })\n}\n\n/** Every version of the document `docId`, oldest first (`is_current` marks the current one). */\nexport function useDocumentVersionList(\n docId: string | null | undefined,\n options?: { enabled?: boolean }\n) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.documentVersions(docId ?? ''),\n queryFn: () => arbi.documents.versions(docId as string),\n enabled: (options?.enabled ?? true) && !!docId && arbi.hasWorkspace,\n })\n}\n\n/**\n * A workspace's conversations (threads and tasks). The list is kept current by its writers and the\n * workspace's events (`conversation-list`), so it is not re-read on every mount; `live` re-reads it\n * on a timer instead, faster while something is generating, for a view that follows runs by itself.\n */\nexport function useConversations(\n workspaceId: string | undefined,\n options?: { enabled?: boolean; live?: boolean }\n) {\n const arbi = useArbi()\n const live = options?.live === true\n return useQuery({\n queryKey: arbiQueryKeys.conversations(workspaceId ?? ''),\n queryFn: () => arbi.readInWorkspace(workspaceId as string, () => arbi.conversations.list()),\n enabled: (options?.enabled ?? true) && !!workspaceId && arbi.hasWorkspace,\n placeholderData: (previous) => previous,\n ...(live\n ? {\n refetchInterval: (query: { state: { data?: Array<{ status?: string | null }> } }) =>\n query.state.data?.some((conversation) => conversation.status === 'generating')\n ? 3000\n : 15000,\n }\n : { staleTime: Infinity, refetchOnMount: false, refetchOnReconnect: false }),\n })\n}\n\n/** The backend's built-in slash commands (`/compact`, `/goal`, …), for a slash menu. */\nexport function useBuiltinCommands() {\n const arbi = useArbi()\n const query = useQuery({\n queryKey: arbiQueryKeys.assistantCommands(),\n queryFn: () => arbi.assistant.commands(),\n staleTime: 30 * 1000,\n enabled: arbi.isLoggedIn,\n })\n // Stable identity so a menu's merge and filter memos do not rerun every render.\n const commands = useMemo(() => query.data ?? [], [query.data])\n return { commands, isLoading: query.isLoading }\n}\n\n/** One stored message with everything the server keeps on it (its trace and metadata). */\nexport function useMessageDetails(\n messageId: string | null | undefined,\n options?: { enabled?: boolean }\n) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.messageDetails(messageId ?? ''),\n queryFn: () => arbi.conversations.getMessage(messageId as string),\n enabled: (options?.enabled ?? true) && !!messageId && arbi.isLoggedIn,\n })\n}\n\n/**\n * A conversation's stored threads (each with its message history, citations data included). The\n * chat engine and the conversation's events keep the cache current, so it is re-read only when\n * stale (2 minutes) or when the page is shown again while this tab is not streaming the\n * conversation (a turn sent from another tab never reaches this one's socket). A conversation with\n * no messages yet (a new to-do, a workflow's task before its run) comes back with no threads. A 404\n * is a conversation this user cannot see (gone, or in a workspace they left): an error, never cached\n * as an empty conversation to write into. `live` re-reads it every few seconds.\n */\nexport function useConversationThreads(\n conversationId: string | undefined,\n options?: { enabled?: boolean; live?: boolean }\n) {\n const arbi = useArbi()\n const session = useArbiSessionStore()\n return useQuery({\n queryKey: arbiQueryKeys.conversationThreads(conversationId ?? ''),\n queryFn: (): Promise<ThreadsResponse> =>\n arbi.conversations.getThreads(conversationId as string),\n enabled: (options?.enabled ?? true) && !!conversationId && arbi.hasWorkspace,\n staleTime: 2 * 60 * 1000,\n refetchOnWindowFocus: () =>\n session.getState().generating[conversationId ?? '']?.isGenerating ? false : 'always',\n refetchInterval: options?.live ? 3000 : false,\n })\n}\n\n/** A tag list query as a stable cache key ('' for every tag). */\nconst tagListKey = (query: TagListQuery): string =>\n [\n query.kind ? `kind:${query.kind}` : '',\n query.parentId ? `parent:${query.parentId}` : '',\n query.ids?.length ? `ids:${query.ids.join(',')}` : '',\n query.include?.length ? `include:${query.include.join(',')}` : '',\n query.linksLimit !== undefined ? `links:${query.linksLimit}` : '',\n ]\n .filter(Boolean)\n .join('|')\n\n/**\n * List tags in a workspace (default: the open one) — all of them, or filtered: `{ kind: 'issue',\n * include: ['links'] }` is every issue with its documents, facts and threads (a table's rows; its\n * columns come from `useTagKindSchema`). `ids: []` asks for nothing.\n *\n * The whole list is read once and then kept current in place: the tag writes patch it\n * (`patchWorkspaceTags`), and an invalidation of the workspace's tags (a WebSocket event, a host\n * refresh) re-reads it. It is never re-read just for being mounted or the window being focused.\n */\nexport function useTags(\n workspaceId?: string | null,\n options?: TagListQuery & { enabled?: boolean }\n) {\n const arbi = useArbi()\n const { enabled, ...query } = options ?? {}\n const workspace = workspaceId ?? (arbi.hasWorkspace ? arbi.getWorkspaceId() : '')\n const key = tagListKey(query)\n return useQuery({\n queryKey: key ? arbiQueryKeys.tagList(workspace, key) : arbiQueryKeys.tags(workspace),\n // The request names the workspace (opened for this session first when it is not the current\n // one), so another workspace's tags can be listed and a switch cannot answer for it. The\n // current workspace's list is also read under the switch guard.\n queryFn: () => {\n const list = () => arbi.tags.list({ ...(key ? query : {}), workspaceId: workspace })\n return workspace === arbi.getWorkspaceId() ? arbi.readInWorkspace(workspace, list) : list()\n },\n enabled:\n (enabled ?? true) &&\n !!workspace &&\n arbi.hasWorkspace &&\n (query.ids === undefined || query.ids.length > 0),\n ...(key ? {} : { staleTime: Infinity }),\n })\n}\n\n/**\n * Batch-fetch first-page thumbnails for a set of documents. Returns a map of\n * doc external id → `data:image/webp` URI (or `null` when no thumbnail exists).\n * Cached for a few minutes since thumbnails are effectively immutable per doc.\n */\nexport function useThumbnails(docIds: string[], options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.thumbnails(docIds),\n queryFn: () => arbi.documents.getThumbnails(docIds),\n enabled: (options?.enabled ?? true) && docIds.length > 0 && arbi.hasWorkspace,\n staleTime: 5 * 60_000,\n })\n}\n\n/**\n * Fetch a document's parsed content (chunks grouped by page) for the review\n * viewer. `stage` defaults to `final` (fully processed); `marker`/`subchunk`\n * expose earlier pipeline stages. `docId` may be a version reference (`doc-…@v2`).\n */\nexport function useParsedDocument(\n docId: string | undefined,\n stage: string = 'final',\n options?: { enabled?: boolean }\n) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.parsedDoc(docId ?? '', stage),\n queryFn: () => {\n // A version reference (`doc-…@v2`) reads that version's parse.\n const { docId: id, version } = parseVersionRef(docId as string)\n return arbi.documents.getParsedContent(\n id,\n stage,\n version ?? undefined\n ) as unknown as Promise<ParsedDocument>\n },\n enabled: (options?.enabled ?? true) && !!docId && arbi.hasWorkspace,\n })\n}\n\n/**\n * Ask the assistant (`arbi.assistant.ask`) as a mutation: one streaming turn, its frames to\n * `handlers`, resolving with the accumulated result.\n */\nexport function useAssistantQuery() {\n const arbi = useArbi()\n return useMutation<SSEStreamResult, Error, { request: AskRequest; handlers?: AskHandlers }>({\n mutationFn: ({ request, handlers }) => arbi.assistant.ask(request, handlers),\n })\n}\n\n/** List agents owned by the current user. */\nexport function useAgents(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.agents(),\n queryFn: () => arbi.agents.list(),\n enabled: (options?.enabled ?? true) && arbi.isLoggedIn,\n })\n}\n\n/**\n * Delete agents. Returns a mutation. Refreshes the agent list, the workflow list and the conversation list\n * (a deleted agent's workflows and work go with it), and drops the deleted agents' own config and workspace queries.\n */\nexport function useDeleteAgents() {\n const arbi = useArbi()\n const qc = useQueryClient()\n return useMutation<unknown, Error, { agentExtIds: string[] }>({\n mutationFn: ({ agentExtIds }) => arbi.agents.delete(agentExtIds),\n onSuccess: (_result, { agentExtIds }) => {\n for (const id of agentExtIds) {\n qc.removeQueries({ queryKey: arbiQueryKeys.agentConfig(id) })\n qc.removeQueries({ queryKey: arbiQueryKeys.agentWorkspaces(id) })\n }\n return Promise.all([\n qc.invalidateQueries({ queryKey: arbiQueryKeys.agents() }),\n qc.invalidateQueries({ queryKey: arbiQueryKeys.workflows() }),\n qc.invalidateQueries({ queryKey: arbiQueryKeys.allConversations() }),\n qc.invalidateQueries({ queryKey: arbiQueryKeys.configs() }),\n ])\n },\n })\n}\n\n/** Authorize a delegated session (generates claim code). Returns a mutation. */\n\n/** Check backend health. */\nexport function useHealth(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.health(),\n queryFn: () => arbi.health.check(),\n enabled: options?.enabled,\n })\n}\n\n/**\n * The deployment's models with their tags (`Standard`, `Premium`), providers and per-token costs,\n * and the default premium model. Static per deployment: read once.\n */\nexport function useAvailableModels(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.availableModels(),\n queryFn: () => arbi.health.models(),\n staleTime: Infinity,\n enabled: (options?.enabled ?? true) && arbi.isLoggedIn,\n })\n}\n\n// ── Behaviour-template configs ───────────────────────────────────────────────\n\n/** List the caller's saved agent configurations (behaviour templates). */\nexport function useConfigs(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.configVersions(),\n queryFn: () => arbi.agentConfig.list(),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n })\n}\n\n/** One saved agent configuration (its models, its tools). Configs change only on a save. */\nexport function useConfig(configId: string | null | undefined, options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.config(configId ?? ''),\n queryFn: () => arbi.agentConfig.get(configId as string),\n staleTime: 10 * 60 * 1000,\n enabled: (options?.enabled ?? true) && !!configId && arbi.isLoggedIn,\n })\n}\n\n// ── Activity feed ─────────────────────────────────────────────────────────────\n\n/**\n * List the caller's durable activity feed, newest first.\n *\n * Activity entries are backend-originated, to-self log lines that are always\n * read — they are deliberately kept out of the normal notifications/DM feed and\n * never affect the unread badge, so this is a separate, opt-in query.\n */\nexport function useActivity(options?: { enabled?: boolean; limit?: number; offset?: number }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.activity(),\n queryFn: () => arbi.dm.listActivity({ limit: options?.limit, offset: options?.offset }),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n })\n}\n\n/**\n * A workspace's activity feed, newest first, a page at a time: thread history, people posting,\n * uploads, new versions and signatures, workflow runs. Only what the caller can see. The pages\n * are `data.pages`; `fetchNextPage` reads the next one while `hasNextPage`.\n */\nexport function useWorkspaceActivity(\n workspaceId: string | null | undefined,\n options?: {\n enabled?: boolean\n limit?: number\n /** Runs before each page, e.g. to (re)open the workspace so titles and names decrypt. */\n beforeFetch?: () => Promise<unknown>\n }\n) {\n const arbi = useArbi()\n return useInfiniteQuery({\n queryKey: arbiQueryKeys.workspaceActivity(workspaceId ?? ''),\n queryFn: async ({ pageParam }) => {\n await options?.beforeFetch?.()\n return arbi.workspaces.activity(workspaceId as string, {\n cursor: pageParam,\n limit: options?.limit,\n })\n },\n initialPageParam: null as string | null,\n getNextPageParam: (page) => page.next_cursor ?? undefined,\n enabled: (options?.enabled ?? true) && !!workspaceId && arbi.isLoggedIn,\n })\n}\n\n// ── Projects, usage & spend ───────────────────────────────────────────────────\n\n/** List the logged-in user's projects (billing accounts). */\nexport function useProjects(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.projects(),\n queryFn: () => arbi.projects.list(),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n })\n}\n\n/**\n * AI usage breakdown for a project's billing period. `monthsBack` selects the period (0 =\n * current, 1 = previous month, …).\n *\n * The response's `total_spend` / `spend` fields are £ of AI usage (format with `formatGbp`).\n * `metered` is `false` when the deployment does not record usage (a `dev`-plan project with all\n * zeros): show \"usage is not metered here\" instead of zeros. It is `undefined` until the usage\n * has loaded.\n */\nexport function useProjectUsage(\n projectExtId: string | undefined,\n monthsBack: number = 0,\n options?: { enabled?: boolean }\n) {\n const arbi = useArbi()\n const usage = useQuery({\n queryKey: arbiQueryKeys.projectUsage(projectExtId ?? '', monthsBack),\n queryFn: () => arbi.projects.usage(projectExtId as string, monthsBack),\n enabled: (options?.enabled ?? true) && !!projectExtId && arbi.isLoggedIn,\n })\n const projects = useProjects({ enabled: !!projectExtId && (options?.enabled ?? true) })\n const subscription = projects.data?.find((p) => p.external_id === projectExtId)?.subscription\n const metered = usage.data ? isUsageMetered(usage.data, subscription) : undefined\n return { ...usage, metered }\n}\n\n/** One day of aggregated usage across projects (for a spend/token trend). */\nexport interface AggregatedDailyUsage {\n date: string\n /** £ of AI usage that day. */\n gbp: number\n totalTokens: number\n apiRequests: number\n}\n\n/** One model group's aggregated usage across projects (for a breakdown). */\nexport interface AggregatedModelGroupUsage {\n model: string\n /** £ of AI usage by this model group. */\n gbp: number\n totalTokens: number\n promptTokens: number\n completionTokens: number\n successfulRequests: number\n}\n\n/** Aggregated AI usage + spend across several projects. */\nexport interface ProjectsUsageAggregate {\n /** Summed usage across the projects, in £ (ex VAT). */\n totalGbp: number\n /** Summed token count across the projects. */\n totalTokens: number\n /** Summed API request count across the projects. */\n totalRequests: number\n /** Per-day totals merged across every project, oldest first. */\n daily: AggregatedDailyUsage[]\n /** Per-model-group totals merged across every project, most £ first. */\n modelGroups: AggregatedModelGroupUsage[]\n /**\n * False when none of the loaded projects records usage (billing is off on this deployment), so\n * zeros mean \"not metered\". True while anything real was recorded, or before data arrived.\n */\n metered: boolean\n /** True while any per-project query is still loading. */\n isLoading: boolean\n /** True if any per-project query errored. */\n isError: boolean\n}\n\n/**\n * Firm-wide AI usage + spend: aggregates {@link useProjectUsage} across several\n * projects (e.g. all of a firm's matters) in parallel and merges the real totals,\n * the daily trend, and the per-model breakdown. Shares the per-project query\n * cache, so it costs nothing extra where a project's usage is already loaded.\n * Numbers are genuine — zero projects (or zero billed work) yields zero totals;\n * callers render that honestly.\n */\nexport function useProjectsUsage(\n projectExtIds: string[],\n monthsBack: number = 0,\n options?: { enabled?: boolean }\n): ProjectsUsageAggregate {\n const arbi = useArbi()\n const enabled = (options?.enabled ?? true) && arbi.isLoggedIn\n const projects = useProjects({ enabled: enabled && projectExtIds.length > 0 })\n const results = useQueries({\n queries: projectExtIds.map((id) => ({\n queryKey: arbiQueryKeys.projectUsage(id, monthsBack),\n queryFn: () => arbi.projects.usage(id, monthsBack),\n enabled: enabled && !!id,\n })),\n })\n\n // Recompute only when a query's data actually changes (not on every parent\n // render — the dashboard re-renders often while a digest streams).\n const signature =\n results.map((r) => `${r.status}:${r.dataUpdatedAt ?? 0}`).join('|') +\n `#${projects.dataUpdatedAt}`\n\n return useMemo(() => {\n const dailyMap = new Map<string, AggregatedDailyUsage>()\n const modelMap = new Map<string, AggregatedModelGroupUsage>()\n let totalGbp = 0\n let anyData = false\n let anyMetered = false\n let totalTokens = 0\n let totalRequests = 0\n\n results.forEach((r, i) => {\n const d = r.data\n if (!d) return\n anyData = true\n const subscription = projects.data?.find(\n (p) => p.external_id === projectExtIds[i]\n )?.subscription\n if (isUsageMetered(d, subscription)) anyMetered = true\n totalGbp += d.total_spend ?? 0\n totalTokens += d.total_tokens ?? 0\n totalRequests += d.total_requests ?? 0\n\n for (const day of d.daily ?? []) {\n const cur = dailyMap.get(day.date) ?? {\n date: day.date,\n gbp: 0,\n totalTokens: 0,\n apiRequests: 0,\n }\n cur.gbp += day.spend ?? 0\n cur.totalTokens += day.total_tokens ?? 0\n cur.apiRequests += day.api_requests ?? 0\n dailyMap.set(day.date, cur)\n }\n\n for (const [model, mg] of Object.entries(d.model_groups ?? {})) {\n const cur = modelMap.get(model) ?? {\n model,\n gbp: 0,\n totalTokens: 0,\n promptTokens: 0,\n completionTokens: 0,\n successfulRequests: 0,\n }\n cur.gbp += mg.spend ?? 0\n cur.totalTokens += mg.total_tokens ?? 0\n cur.promptTokens += mg.prompt_tokens ?? 0\n cur.completionTokens += mg.completion_tokens ?? 0\n cur.successfulRequests += mg.successful_requests ?? 0\n modelMap.set(model, cur)\n }\n })\n\n return {\n totalGbp,\n totalTokens,\n totalRequests,\n daily: [...dailyMap.values()].sort((a, b) => a.date.localeCompare(b.date)),\n modelGroups: [...modelMap.values()].sort(\n (a, b) => b.gbp - a.gbp || b.totalTokens - a.totalTokens\n ),\n metered: !anyData || anyMetered,\n isLoading: results.some((r) => r.isLoading),\n isError: results.some((r) => r.isError),\n }\n }, [signature])\n}\n\n/** List the Stripe invoices for a project's subscription. */\nexport function useProjectInvoices(\n projectExtId: string | undefined,\n options?: { enabled?: boolean }\n) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.projectInvoices(projectExtId ?? ''),\n queryFn: () => arbi.projects.invoices(projectExtId as string),\n enabled: (options?.enabled ?? true) && !!projectExtId && arbi.isLoggedIn,\n })\n}\n\n/**\n * The signed-in user from `GET /v1/user/me`. Refetched on window focus, so a role granted or\n * removed elsewhere shows up without a reload; invalidate `arbiQueryKeys.currentUser()` after a\n * change you made yourself.\n */\nexport function useCurrentUser(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.currentUser(),\n queryFn: () => arbi.user.me(),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n refetchOnWindowFocus: true,\n staleTime: 30_000,\n })\n}\n\n/**\n * The firm's pooled monthly £ of AI usage (Box deployments). A 403 (the caller is not a firm member\n * or Box admin) is not retried: treat an error like `has_pool: false` and show nothing.\n */\nexport function useFirmPool(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.firmPool(),\n queryFn: () => arbi.firm.pool(),\n enabled: (options?.enabled ?? true) && arbi.isLoggedIn,\n retry: false,\n refetchOnWindowFocus: true,\n staleTime: 60_000,\n })\n}\n\n/**\n * Whether this deployment runs under a Box licence (`isBox`) and whether the user administers it in\n * the ARBI portal (`isBoxAdmin`), from the firm pool. Anyone outside the firm gets a 403 (not\n * retried), read as no Box. The API has no Box-admin flag yet: `can_top_up` is true only for a Box\n * admin of a licence central can bill, so admins of a hand-set licence read as members for now.\n */\nexport function useBoxRole(options: { enabled?: boolean } = {}): {\n isBox: boolean\n isBoxAdmin: boolean\n} {\n const { data, isError } = useFirmPool(options)\n const isBox = !isError && !!data?.has_pool\n return { isBox, isBoxAdmin: isBox && !!data?.can_top_up }\n}\n\n/** Buy add-ons for the firm (Box admins). Refreshes the pool; the result may carry an invoice URL. */\nexport function useTopUpFirmPool() {\n const arbi = useArbi()\n const queryClient = useQueryClient()\n return useMutation({\n mutationFn: (aiAddons: number) => arbi.firm.topUp(aiAddons),\n onSuccess: (result) => {\n queryClient.setQueryData(arbiQueryKeys.firmPool(), result.pool)\n },\n })\n}\n\n/** Why \"New project\" / \"New workspace\" is unavailable to someone who may not create them. */\nexport const PROJECT_CREATION_DENIED_REASON =\n 'Only members of your firm can create projects and workspaces.'\n\n/**\n * Whether the signed-in user may create projects and workspaces. `undefined` while the user is\n * loading: callers should neither offer nor refuse creation until it is known.\n */\nexport function useCanCreateProjects(): boolean | undefined {\n const user = useCurrentUser()\n // A role granted or removed in a workspace can change it: re-read when the memberships do.\n const { data: workspaces } = useWorkspaces({ enabled: user.isSuccess })\n const membership = workspaces?.map((w) => w.external_id).join(',')\n const { refetch } = user\n const seen = useRef<string | undefined>(undefined)\n useEffect(() => {\n if (membership === undefined || membership === seen.current) return\n const first = seen.current === undefined\n seen.current = membership\n if (!first) void refetch()\n }, [membership, refetch])\n return user.data?.can_create_projects\n}\n\n/**\n * Today's deployment-wide AI usage (£, `used_gbp`) for the signed-in user: pair it with a project's\n * `daily_cap_per_user` for a \"£ used today\" indicator. Re-read on mount and window focus, and when\n * the host invalidates it after the user's own generation; never polled.\n */\nexport function useUserUsageToday(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.userUsageToday(),\n queryFn: () => arbi.user.usageToday(),\n enabled: (options?.enabled ?? true) && arbi.isLoggedIn,\n refetchOnWindowFocus: true,\n refetchOnMount: 'always',\n staleTime: 15_000,\n })\n}\n"]}
|
|
@@ -2,6 +2,7 @@ import { renderToStaticMarkup } from 'react-dom/server';
|
|
|
2
2
|
import { toast } from 'sonner';
|
|
3
3
|
export { toast } from 'sonner';
|
|
4
4
|
import { create } from 'zustand';
|
|
5
|
+
import { useSyncExternalStore } from 'react';
|
|
5
6
|
|
|
6
7
|
// src/notifications/notify-store.ts
|
|
7
8
|
var MAX_SESSION_NOTIFICATIONS = 5e3;
|
|
@@ -139,7 +140,75 @@ var DEFAULT_NOTIFY_TONE = {
|
|
|
139
140
|
warning: "text-amber-500",
|
|
140
141
|
info: "text-blue-500"
|
|
141
142
|
};
|
|
143
|
+
var artifacts = {};
|
|
144
|
+
var order = [];
|
|
145
|
+
var listeners = /* @__PURE__ */ new Set();
|
|
146
|
+
function subscribe(listener) {
|
|
147
|
+
listeners.add(listener);
|
|
148
|
+
return () => listeners.delete(listener);
|
|
149
|
+
}
|
|
150
|
+
function emit() {
|
|
151
|
+
listeners.forEach((listener) => listener());
|
|
152
|
+
}
|
|
153
|
+
function recordChatArtifact(event, conversationId) {
|
|
154
|
+
const previous = artifacts[event.doc_ext_id];
|
|
155
|
+
const artifact = {
|
|
156
|
+
docExtId: event.doc_ext_id,
|
|
157
|
+
title: event.title,
|
|
158
|
+
content: event.content,
|
|
159
|
+
// The backend schema lags the 'react' mode it also sends; the value passes through unchanged.
|
|
160
|
+
mode: event.mode,
|
|
161
|
+
isComplete: event.is_complete,
|
|
162
|
+
version: event.version,
|
|
163
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
164
|
+
messageExtId: event.message_ext_id ?? void 0,
|
|
165
|
+
conversationId
|
|
166
|
+
};
|
|
167
|
+
artifacts = { ...artifacts, [artifact.docExtId]: artifact };
|
|
168
|
+
if (!previous) order = [...order, artifact.docExtId];
|
|
169
|
+
emit();
|
|
170
|
+
}
|
|
171
|
+
function clearChatArtifacts() {
|
|
172
|
+
if (order.length === 0) return;
|
|
173
|
+
artifacts = {};
|
|
174
|
+
order = [];
|
|
175
|
+
emit();
|
|
176
|
+
}
|
|
177
|
+
function getChatArtifacts() {
|
|
178
|
+
return artifacts;
|
|
179
|
+
}
|
|
180
|
+
function getChatArtifact(documentId) {
|
|
181
|
+
return documentId ? artifacts[documentId] : void 0;
|
|
182
|
+
}
|
|
183
|
+
function useChatArtifact(documentId) {
|
|
184
|
+
return useSyncExternalStore(
|
|
185
|
+
subscribe,
|
|
186
|
+
() => getChatArtifact(documentId),
|
|
187
|
+
() => void 0
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
function useMessageChatArtifact(messageId) {
|
|
191
|
+
return useSyncExternalStore(
|
|
192
|
+
subscribe,
|
|
193
|
+
() => messageId ? Object.values(artifacts).find((artifact) => artifact.messageExtId === messageId) : void 0,
|
|
194
|
+
() => void 0
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
function useConversationChatArtifact(conversationId) {
|
|
198
|
+
return useSyncExternalStore(
|
|
199
|
+
subscribe,
|
|
200
|
+
() => {
|
|
201
|
+
if (!conversationId) return void 0;
|
|
202
|
+
for (let i = order.length - 1; i >= 0; i--) {
|
|
203
|
+
const artifact = artifacts[order[i]];
|
|
204
|
+
if (artifact?.conversationId === conversationId) return artifact;
|
|
205
|
+
}
|
|
206
|
+
return void 0;
|
|
207
|
+
},
|
|
208
|
+
() => void 0
|
|
209
|
+
);
|
|
210
|
+
}
|
|
142
211
|
|
|
143
|
-
export { DEFAULT_NOTIFY_TONE, MAX_SESSION_NOTIFICATIONS, configureNotify, notify, persistNotifyHistory, seedNotifications, selectUnread, useNotify };
|
|
144
|
-
//# sourceMappingURL=chunk-
|
|
145
|
-
//# sourceMappingURL=chunk-
|
|
212
|
+
export { DEFAULT_NOTIFY_TONE, MAX_SESSION_NOTIFICATIONS, clearChatArtifacts, configureNotify, getChatArtifact, getChatArtifacts, notify, persistNotifyHistory, recordChatArtifact, seedNotifications, selectUnread, useChatArtifact, useConversationChatArtifact, useMessageChatArtifact, useNotify };
|
|
213
|
+
//# sourceMappingURL=chunk-G4Z3IP4J.js.map
|
|
214
|
+
//# sourceMappingURL=chunk-G4Z3IP4J.js.map
|