@arbidocs/react 0.5.2 → 0.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/dist/artifacts/index.cjs +2 -2
  2. package/dist/artifacts/index.js +1 -1
  3. package/dist/calls/livekit/index.cjs +41 -41
  4. package/dist/calls/livekit/index.js +2 -2
  5. package/dist/{chunk-KYEWJVD2.cjs → chunk-IFPSLIRL.cjs} +18 -4
  6. package/dist/chunk-IFPSLIRL.cjs.map +1 -0
  7. package/dist/{chunk-SQTHTE2Y.cjs → chunk-J62MWU4O.cjs} +5 -5
  8. package/dist/{chunk-SQTHTE2Y.cjs.map → chunk-J62MWU4O.cjs.map} +1 -1
  9. package/dist/{chunk-DGMK3EUN.js → chunk-QVGAUQSD.js} +135 -16
  10. package/dist/chunk-QVGAUQSD.js.map +1 -0
  11. package/dist/{chunk-ZI2VJOID.cjs → chunk-TYZFRV7P.cjs} +145 -16
  12. package/dist/chunk-TYZFRV7P.cjs.map +1 -0
  13. package/dist/{chunk-5DI27KJG.js → chunk-X2OC2LCD.js} +18 -4
  14. package/dist/chunk-X2OC2LCD.js.map +1 -0
  15. package/dist/{chunk-BF5ASP3L.js → chunk-Y3LBWRXS.js} +3 -3
  16. package/dist/{chunk-BF5ASP3L.js.map → chunk-Y3LBWRXS.js.map} +1 -1
  17. package/dist/index.cjs +457 -389
  18. package/dist/index.cjs.map +1 -1
  19. package/dist/{index.d-Bvp6rKNo.d.ts → index.d-C_Fa1zTU.d.cts} +85 -20
  20. package/dist/{index.d-Bvp6rKNo.d.cts → index.d-C_Fa1zTU.d.ts} +85 -20
  21. package/dist/index.d.cts +23 -3
  22. package/dist/index.d.ts +23 -3
  23. package/dist/index.js +36 -9
  24. package/dist/index.js.map +1 -1
  25. package/dist/shell/index.cjs +64 -24
  26. package/dist/shell/index.d.cts +1 -1
  27. package/dist/shell/index.d.ts +1 -1
  28. package/dist/shell/index.js +1 -1
  29. package/package.json +3 -3
  30. package/dist/chunk-5DI27KJG.js.map +0 -1
  31. package/dist/chunk-DGMK3EUN.js.map +0 -1
  32. package/dist/chunk-KYEWJVD2.cjs.map +0 -1
  33. package/dist/chunk-ZI2VJOID.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/search/session.ts","../src/notifications/Toaster.tsx","../src/lib/format-relative-time.ts","../src/notifications/NotificationBell.tsx","../src/host/ArbiHost.tsx","../src/chat/mentions.ts","../src/chat/open-document.ts","../src/chat/thread-document.ts"],"names":["createStore","storage","jsx","Sonner","CheckCircle2","XCircle","AlertTriangle","Info","useState","useNotify","selectUnread","DEFAULT_NOTIFY_TONE","jsxs","DropdownMenu","DropdownMenuTrigger","Bell","DropdownMenuContent","CheckCheck","cn","BellOff","DropdownMenuItem","X","ScrollArea","useContext","ArbiHostContext","useMemo","mergeHostConfig","OWN_SESSION_SLOT","useRef","useEffect","useSyncExternalStore","parseVersionRef","listeners","entries"],"mappings":";;;;;;;;;;;;;;;AA8BA,IAAM,KAAA,GAAyD;AAAA,EAC7D,KAAA,EAAO,EAAA;AAAA,EACP,SAAS,EAAC;AAAA,EACV,QAAA,EAAU,KAAA;AAAA,EACV,MAAA,EAAQ,MAAA;AAAA,EACR,KAAA,EAAO,IAAA;AAAA,EACP,OAAA,EAAS;AACX,CAAA;AAEO,SAAS,mBAAA,GAAqC;AACnD,EAAA,OAAOA,mBAAA,CAAgC,OAAO,EAAE,GAAG,OAAO,WAAA,EAAa,IAAA,EAAM,GAAA,EAAK,CAAA,EAAE,CAAE,CAAA;AACxF;AAGO,IAAM,sBAAqC,mBAAA;AAG3C,SAAS,kBAAA,CACd,WAAA,EACA,OAAA,GAAyB,mBAAA,EACnB;AACN,EAAA,OAAA,CAAQ,QAAA,CAAS,CAAC,CAAA,MAAO;AAAA,IACvB,GAAG,KAAA;AAAA,IACH,WAAA,EAAa,WAAA,KAAgB,MAAA,GAAY,CAAA,CAAE,WAAA,GAAc,WAAA;AAAA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AAA;AACT;AAGO,SAAS,gBAAgB,KAAA,EAA8D;AAC5F,EAAA,OAAO,MAAM,cAAA,GAAiB,gBAAA,CAAiB,KAAA,CAAM,cAAc,IAAI,KAAA,CAAM,iBAAA;AAC/E;AAOO,SAAS,qBACd,OAAA,EACA,cAAA,EACA,aAA4B,OAAA,CAAQ,QAAA,GAAW,iBAAA,EACzC;AACN,EAAA,IAAI,CAAC,UAAA,EAAY;AACjB,EAAA,kBAAA,CAAmB,gBAAgB,UAAU,CAAA;AAC7C,EAAA,IAAI,QAAQ,QAAA,EAAS,CAAE,sBAAsB,UAAA,EAAY,OAAA,CAAQ,qBAAqB,IAAI,CAAA;AAC5F;AAGO,SAAS,4BAAA,GAAqC;AACnD,EAAA,QAAA,GAAW,EAAC;AACZ,EAAA,IAAI;AACF,IAAA,OAAA,EAAQ,EAAG,WAAW,WAAW,CAAA;AAAA,EACnC,CAAA,CAAA,MAAQ;AAAA,EAER;AACA,EAAAD,UAAAA,CAAU,OAAA,CAAQ,CAAC,CAAA,KAAM,GAAG,CAAA;AAC9B;AAGO,SAAS,6BAAA,GAAsC;AACpD,EAAA,QAAA,GAAW,IAAA;AACX,EAAAA,UAAAA,CAAU,OAAA,CAAQ,CAAC,CAAA,KAAM,GAAG,CAAA;AAC9B","file":"chunk-TYZFRV7P.cjs","sourcesContent":["/**\n * A search's state outside any component: the query last searched, its passages, and whether it\n * is running. A page that shows the shared session (`sharedSearchSession`) keeps its results when\n * it is left and opened again, another surface can hand it a query to run on arrival\n * ({@link requestSearch}), and {@link persistSearchSession} keeps the last query across reloads.\n */\nimport { createStore, type StoreApi } from 'zustand/vanilla'\nimport type { SearchChunk } from '@arbidocs/sdk/browser'\n\nexport type SearchStatus = 'idle' | 'running' | 'done' | 'error'\n\nexport interface SearchSessionState {\n /** The workspace the query and results belong to. */\n workspaceId: string | null\n /** The query last searched, or handed over to run. */\n query: string\n /** The last search's passages, best first. */\n results: SearchChunk[]\n /** A search has finished with results to show (cleared by {@link clearSearchSession}). */\n searched: boolean\n status: SearchStatus\n error: string | null\n /** A query handed over by {@link requestSearch}, run once by the page that shows the session. */\n pending: string | null\n /** Counts searches, so the reply to an older one never overwrites a newer one. */\n run: number\n}\n\nexport type SearchSession = StoreApi<SearchSessionState>\n\nconst EMPTY: Omit<SearchSessionState, 'workspaceId' | 'run'> = {\n query: '',\n results: [],\n searched: false,\n status: 'idle',\n error: null,\n pending: null,\n}\n\nexport function createSearchSession(): SearchSession {\n return createStore<SearchSessionState>(() => ({ ...EMPTY, workspaceId: null, run: 0 }))\n}\n\n/** The session a host's search page shows. */\nexport const sharedSearchSession: SearchSession = createSearchSession()\n\n/** Back to nothing searched (in `workspaceId` when given); a running search's reply is dropped. */\nexport function clearSearchSession(\n workspaceId?: string | null,\n session: SearchSession = sharedSearchSession\n): void {\n session.setState((s) => ({\n ...EMPTY,\n workspaceId: workspaceId === undefined ? s.workspaceId : workspaceId,\n run: s.run + 1,\n }))\n}\n\n/**\n * Hand a query to the search page, which runs it when it shows the session (the user already\n * asked once; the page must not wait for a second Enter).\n */\nexport function requestSearch(\n query: string,\n workspaceId: string | null,\n session: SearchSession = sharedSearchSession\n): void {\n clearSearchSession(workspaceId, session)\n session.setState({ query, pending: query })\n}\n\n/** The handed-over query, once: the next call returns null. */\nexport function takePendingSearch(session: SearchSession = sharedSearchSession): string | null {\n const { pending } = session.getState()\n if (pending !== null) session.setState({ pending: null })\n return pending\n}\n\ninterface SavedSearch {\n query?: string\n workspaceId?: string | null\n}\n\n/**\n * Keep the last query (and its workspace) in `storage` under `key`, so the search box shows it\n * after a reload. Results are not kept. Returns the unsubscribe.\n */\nexport function persistSearchSession(\n key: string,\n storage: Pick<Storage, 'getItem' | 'setItem'> | undefined = globalThis.localStorage,\n session: SearchSession = sharedSearchSession\n): () => void {\n if (!storage) return () => {}\n try {\n const saved = JSON.parse(storage.getItem(key) ?? 'null') as SavedSearch | null\n if (saved && typeof saved.query === 'string' && !session.getState().query)\n session.setState({ query: saved.query, workspaceId: saved.workspaceId ?? null })\n } catch {\n // Unreadable: start empty.\n }\n let last = ''\n return session.subscribe(({ query, workspaceId }) => {\n const next = JSON.stringify({ query, workspaceId })\n if (next === last) return\n last = next\n try {\n storage.setItem(key, next)\n } catch {\n // Storage full or blocked: the query is simply not kept.\n }\n })\n}\n","/**\n * Toaster — the one shared toast surface, built on sonner (the mature engine:\n * stacking, swipe-to-dismiss, a11y, timing). Mount once near the app root; any\n * code then calls `notify.*(...)` (or the re-exported `toast`) from anywhere.\n *\n * Firm-agnostic: every sonner `ToasterProps` passes through, so a consumer sets\n * its own `position` / `theme` / `toastOptions`. The defaults give a neutral\n * shadcn-token card that both apps can override.\n */\nimport { Toaster as Sonner, type ToasterProps } from 'sonner'\n\nexport type { ToasterProps }\n\nconst DEFAULT_TOAST_OPTIONS: ToasterProps['toastOptions'] = {\n classNames: {\n toast:\n 'group toast group-[.toaster]:bg-card group-[.toaster]:text-foreground group-[.toaster]:border group-[.toaster]:border-border group-[.toaster]:shadow-lg group-[.toaster]:rounded-lg',\n description: 'group-[.toast]:text-muted-foreground',\n actionButton: 'group-[.toast]:bg-primary group-[.toast]:text-primary-foreground',\n cancelButton: 'group-[.toast]:bg-muted group-[.toast]:text-muted-foreground',\n },\n}\n\nexport function Toaster({ toastOptions, ...props }: ToasterProps) {\n return (\n <Sonner\n className=\"toaster group\"\n toastOptions={toastOptions ?? DEFAULT_TOAST_OPTIONS}\n {...props}\n />\n )\n}\n","/** Relative-time formatting shared by the notification bell, the DM kit and the app's thread lists\n * (no type imports, so the SDK-free `/shell` entry can use it). */\n\nconst FORMATTERS = new Map<Intl.RelativeTimeFormatStyle, Intl.RelativeTimeFormat>()\nconst DIVISIONS: Array<{ amount: number; unit: Intl.RelativeTimeFormatUnit }> = [\n { amount: 60, unit: 'seconds' },\n { amount: 60, unit: 'minutes' },\n { amount: 24, unit: 'hours' },\n { amount: 7, unit: 'days' },\n { amount: 4.34524, unit: 'weeks' },\n { amount: 12, unit: 'months' },\n { amount: Number.POSITIVE_INFINITY, unit: 'years' },\n]\n\nfunction formatter(style: Intl.RelativeTimeFormatStyle): Intl.RelativeTimeFormat {\n let f = FORMATTERS.get(style)\n if (!f) {\n f = new Intl.RelativeTimeFormat(undefined, { numeric: 'auto', style })\n FORMATTERS.set(style, f)\n }\n return f\n}\n\nexport interface FormatRelativeTimeOptions {\n /** The reference instant in epoch milliseconds (default: now). */\n now?: number\n /** `long` (default): \"2 hours ago\"; `short`: \"2 hr. ago\", for tight rows. */\n style?: Intl.RelativeTimeFormatStyle\n}\n\n/** Relative time of an ISO timestamp, past or future: \"2 hours ago\", \"in 3 days\", \"just now\".\n * Empty for an unparseable timestamp. */\nexport function formatRelativeTime(iso: string, options: FormatRelativeTimeOptions = {}): string {\n const then = Date.parse(iso)\n if (Number.isNaN(then)) return ''\n let duration = (then - (options.now ?? Date.now())) / 1000\n if (Math.abs(duration) < 45) return 'just now'\n for (const division of DIVISIONS) {\n if (Math.abs(duration) < division.amount) {\n return formatter(options.style ?? 'long').format(Math.round(duration), division.unit)\n }\n duration /= division.amount\n }\n return ''\n}\n","/**\n * NotificationBell — the topbar notification centre: a bell with an unread badge\n * that opens a dropdown of recorded entries (newest first) with an unread dot,\n * relative time and optional deep-link. \"Mark all read\" clears the badge. Backed\n * by the shared {@link useNotify} store (the same one the <Toaster/> renders).\n *\n * Firm-agnostic: navigation is a callback (`onNavigate`), styling tracks semantic\n * tokens, and per-variant glyph colours are overridable via `toneClassNames`.\n */\nimport { useState, type ReactElement } from 'react'\nimport {\n Bell,\n BellOff,\n CheckCheck,\n CheckCircle2,\n AlertTriangle,\n XCircle,\n Info,\n X,\n} from 'lucide-react'\nimport {\n DropdownMenu,\n DropdownMenuTrigger,\n DropdownMenuContent,\n DropdownMenuItem,\n} from '../ui/dropdown-menu'\nimport { ScrollArea } from '../ui/scroll-area'\nimport { cn } from '../lib/utils'\nimport { formatRelativeTime } from '../lib/format-relative-time'\nimport {\n useNotify,\n selectUnread,\n DEFAULT_NOTIFY_TONE,\n type NotifyVariant,\n type AppNotification,\n} from './notify-store'\n\nconst GLYPH: Record<NotifyVariant, typeof Info> = {\n success: CheckCircle2,\n error: XCircle,\n warning: AlertTriangle,\n info: Info,\n}\n\n/** Entries the panel lists, newest first. */\nconst BELL_LIMIT = 100\n\n/** What a custom bell trigger needs to render itself. */\nexport interface NotificationBellTriggerState {\n /** Unread count (0 when none). */\n unread: number\n /** Accessible name, including the count: \"Notifications, 2 unread\". */\n ariaLabel: string\n testId: string\n}\n\nexport interface NotificationBellProps {\n /**\n * Replaces the default icon button with the host's own trigger (for example a labelled sidebar\n * row). It must forward its ref and rest props: it is mounted as the dropdown trigger.\n */\n renderTrigger?: (state: NotificationBellTriggerState) => ReactElement\n /** Called with an entry's `href` when it's clicked (e.g. router navigate). */\n onNavigate?: (href: string) => void\n /** Open this entry in the host notification centre instead of following its link. */\n onSelectNotification?: (notification: AppNotification) => void\n /** Called after an entry is locally marked read — the hook for a backend\n * bridge to propagate read state upstream (filter by the ids it owns). */\n onMarkRead?: (id: string) => void\n /** Called after \"Mark all read\" — same upstream-propagation hook. */\n onMarkAllRead?: () => void\n /** Show the store's toast mute switch in the header — the bell is where notification\n * behaviour is controlled. */\n showMuteToggle?: boolean\n /** Override per-variant glyph colours (e.g. brand emerald for success). */\n toneClassNames?: Partial<Record<NotifyVariant, string>>\n emptyText?: string\n /** Footer link to the app's full notification surface. Omit to hide. */\n onViewAll?: () => void\n viewAllLabel?: string\n testId?: string\n /** Where the panel opens relative to the bell (a sidebar-footer bell opens upward). */\n side?: 'top' | 'right' | 'bottom' | 'left'\n align?: 'start' | 'center' | 'end'\n}\n\nexport function NotificationBell({\n renderTrigger,\n onNavigate,\n onSelectNotification,\n onMarkRead,\n onMarkAllRead,\n showMuteToggle = false,\n toneClassNames,\n emptyText = \"You're all caught up.\",\n onViewAll,\n viewAllLabel = 'View all',\n testId = 'notifications',\n side = 'bottom',\n align = 'end',\n}: NotificationBellProps) {\n const [open, setOpen] = useState(false)\n const notifications = useNotify((s) => s.notifications)\n const unread = useNotify(selectUnread)\n const markAllRead = useNotify((s) => s.markAllRead)\n const markRead = useNotify((s) => s.markRead)\n const muted = useNotify((s) => s.muted)\n const setMuted = useNotify((s) => s.setMuted)\n const tone = (v: NotifyVariant) => toneClassNames?.[v] ?? DEFAULT_NOTIFY_TONE[v]\n\n // Ambient entries (routine session activity — \"Opening workspace…\") are kept\n // for the log but never surfaced in the bell panel: they never badge and are\n // always filtered out here. The panel is the recent history; a host's\n // notification page (`onViewAll`) holds the rest.\n const visible = notifications.filter((n) => !n.ambient).slice(0, BELL_LIMIT)\n\n return (\n <DropdownMenu open={open} onOpenChange={setOpen}>\n <DropdownMenuTrigger asChild>\n {renderTrigger ? (\n renderTrigger({\n unread,\n ariaLabel: `Notifications${unread ? `, ${unread} unread` : ''}`,\n testId,\n })\n ) : (\n <button\n className=\"relative flex size-9 pointer-coarse:size-11 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground\"\n data-testid={testId}\n aria-label={`Notifications${unread ? `, ${unread} unread` : ''}`}\n title=\"Notifications\"\n >\n <Bell className=\"size-5\" />\n {unread > 0 && (\n <span\n className=\"absolute -right-0.5 -top-0.5 flex min-w-4 items-center justify-center rounded-full bg-primary px-1 text-xs font-semibold leading-4 text-primary-foreground\"\n data-testid={`${testId}-badge`}\n >\n {unread > 9 ? '9+' : unread}\n </span>\n )}\n </button>\n )}\n </DropdownMenuTrigger>\n <DropdownMenuContent\n align={align}\n side={side}\n sideOffset={8}\n collisionPadding={12}\n className=\"w-60 rounded-lg border-border/60 p-0 shadow-lg\"\n data-testid={`${testId}-panel`}\n data-topbar-popover=\"\"\n >\n <div className=\"flex items-center justify-between gap-3 border-b border-border px-3.5 py-2.5 pointer-coarse:py-0\">\n <p className=\"text-sm font-semibold text-foreground\">Notifications</p>\n <div className=\"flex items-center gap-3 pointer-coarse:gap-1\">\n {unread > 0 && (\n <button\n onClick={() => {\n markAllRead()\n onMarkAllRead?.()\n }}\n className=\"flex items-center gap-1 text-xs font-medium text-primary transition-colors hover:opacity-80 pointer-coarse:min-h-11 pointer-coarse:px-2\"\n data-testid={`${testId}-mark-all`}\n >\n <CheckCheck className=\"size-3.5\" /> Mark all read\n </button>\n )}\n {showMuteToggle && (\n <button\n onClick={() => setMuted(!muted)}\n aria-pressed={muted}\n title={muted ? 'Unmute notifications' : 'Mute notifications'}\n aria-label={muted ? 'Unmute notifications' : 'Mute notifications'}\n className={cn(\n 'flex size-6 items-center justify-center rounded-md transition-colors hover:bg-accent pointer-coarse:size-11',\n muted ? 'text-foreground' : 'text-muted-foreground hover:text-foreground'\n )}\n data-testid={`${testId}-mute`}\n >\n <BellOff className=\"size-3.5\" />\n </button>\n )}\n {/* Explicit close — the dropdown otherwise only dismisses via\n tap-outside/Escape, which isn't discoverable on touch and (at\n mobile width, see blocks.css) the panel covers most\n of the screen so there's nothing to tap outside of. Radix\n closes a DropdownMenu on any item select by default, so a\n plain item with no other effect doubles as a close button. */}\n <DropdownMenuItem\n className=\"flex size-6 items-center justify-center rounded-md p-0 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus:bg-accent pointer-coarse:size-11\"\n aria-label=\"Close notifications\"\n data-testid={`${testId}-close`}\n >\n <X className=\"size-3.5\" />\n </DropdownMenuItem>\n </div>\n </div>\n {muted && (\n <p\n className=\"border-b border-border/60 bg-amber-500/10 px-3.5 py-1.5 text-xs text-muted-foreground\"\n data-testid={`${testId}-muted-note`}\n >\n Toasts are muted — everything still lands here.\n </p>\n )}\n\n {visible.length === 0 ? (\n <div className=\"px-3.5 py-10 text-center text-sm text-muted-foreground\">{emptyText}</div>\n ) : (\n <ScrollArea className=\"max-h-[380px]\">\n <ul data-testid={`${testId}-list`}>\n {visible.map((n) => {\n const Glyph = GLYPH[n.variant]\n return (\n <li key={n.id}>\n <button\n onClick={() => {\n markRead(n.id)\n if (!n.read) onMarkRead?.(n.id)\n setOpen(false)\n if (onSelectNotification) {\n onSelectNotification(n)\n return\n }\n // The specific action wins over the generic deep link.\n if (n.onSelect) n.onSelect()\n else if (n.href) onNavigate?.(n.href)\n }}\n className={cn(\n 'flex w-full items-start gap-3 border-b border-border/60 px-3.5 py-3 text-left transition-colors hover:bg-accent',\n !n.read && 'bg-accent/40'\n )}\n data-testid={`${testId}-item`}\n data-notification-id={n.id}\n >\n <Glyph className={cn('mt-0.5 size-4 shrink-0', tone(n.variant))} />\n <div className=\"min-w-0 flex-1\">\n <p className=\"text-sm font-medium leading-snug text-foreground\">\n {n.title}\n </p>\n {n.description && (\n <p className=\"mt-0.5 line-clamp-2 text-xs leading-relaxed text-muted-foreground\">\n {n.description}\n </p>\n )}\n <p className=\"mt-1 text-xs text-muted-foreground/80\">\n {formatRelativeTime(new Date(n.ts).toISOString())}\n </p>\n </div>\n {!n.read && (\n <span className=\"mt-1.5 size-2 shrink-0 rounded-full bg-primary\" />\n )}\n </button>\n </li>\n )\n })}\n </ul>\n </ScrollArea>\n )}\n {onViewAll && (\n // A real menu item, not a bare button: selecting it must CLOSE the\n // dropdown on its way to the full surface.\n <DropdownMenuItem\n onClick={onViewAll}\n className=\"justify-center rounded-none border-t border-border px-3.5 py-2.5 text-xs font-medium text-primary focus:text-primary pointer-coarse:min-h-11\"\n data-testid={`${testId}-view-all`}\n >\n {viewAllLabel}\n </DropdownMenuItem>\n )}\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n","/**\n * `<ArbiHost config>`: the one place a host app hands its configuration to every hook and kit.\n *\n * <ArbiHost config={{ arbi, session, documents, calendar, mail, account, … }}>\n * <App />\n * </ArbiHost>\n *\n * Every field is optional and has a default (see `ArbiHostConfig`); a kit reads its domain from\n * the config (`useArbiHost().documents`, `useHost().billing` in blocks). A nested `<ArbiHost>`\n * overrides only the fields it gives and inherits the rest (`environment` field by field), for a\n * subtree that opens projects in its own tabs, say. There is no other host provider: a new domain\n * is a new optional field, never a new provider.\n *\n * SDK-free (this module, ./context and ./merge are all it reaches), so a marketing site that only sets the\n * blocks environment does not bundle the SDK.\n */\n\nimport { useContext, useMemo, useState, type ComponentType, type ReactNode } from 'react'\nimport { ArbiHostContext } from './context'\nimport { mergeHostConfig, OWN_SESSION_SLOT } from './merge'\n\n/** A sign-in layer mounted inside the host (`defaultHost` in `@arbidocs/blocks/connect`). */\nexport interface ArbiHostConnection {\n Provider: ComponentType<{ children: ReactNode }>\n}\n\nexport interface ArbiHostProps<Config extends object> {\n config: Config\n children?: ReactNode\n}\n\n/**\n * Provide the host configuration. Typed by the package it is imported from: `@arbidocs/react`'s\n * takes the react domains, `@arbidocs/blocks`' the blocks domains as well.\n */\nexport function ArbiHost<Config extends object>({\n config,\n children,\n}: ArbiHostProps<Config>): React.ReactElement {\n const parent = useContext(ArbiHostContext)\n // A top-level host without a session store gets its own, made on first use (useArbiSessionStore).\n const [ownSession] = useState(() => ({ current: null as unknown }))\n const value = useMemo(() => {\n const merged = mergeHostConfig(parent, config)\n return merged[OWN_SESSION_SLOT] ? merged : { ...merged, [OWN_SESSION_SLOT]: ownSession }\n }, [parent, config, ownSession])\n const Connection = (config as { connection?: ArbiHostConnection }).connection?.Provider\n return (\n <ArbiHostContext.Provider value={value}>\n {Connection ? <Connection>{children}</Connection> : children}\n </ArbiHostContext.Provider>\n )\n}\n","/**\n * @mentions in chat text: pure helpers shared by the composer (autocomplete, extraction) and\n * the message renderer (chips). No React, no SDK.\n *\n * A mention lives in two places: the readable `@Label` text in the message content, and a\n * structured entry on the message (`{ type, user_ext_id, label }`) that the server reads to share\n * the conversation and notify. The composer only ever inserts `@<label>` for a known candidate,\n * so the structured list can be recovered from the text at send time ({@link extractMentions});\n * the renderer turns each stored mention back into a chip ({@link linkMentions}).\n */\n\n/** Who can be mentioned: a workspace member, or the assistant. */\nexport type MentionKind = 'user' | 'assistant'\n\n/** One entry of the mention autocomplete. */\nexport interface MentionCandidate {\n /** User external id (`usr-…`) for a person; any stable key (e.g. `assistant`) for the assistant. */\n id: string\n kind: MentionKind\n /** Inserted as `@<label>`. For people this must be the server's display name (given + family). */\n label: string\n /** Secondary line in the menu (email, role, …). */\n description?: string\n}\n\n/** The structured mention a message carries (the API's `MessageMention`). */\nexport interface MessageMentionRef {\n type: MentionKind\n user_ext_id?: string | null\n label?: string | null\n}\n\n/** Longest text after `@` that still counts as a query in progress. */\nconst MAX_QUERY_LENGTH = 40\n\n/**\n * The `@query` the caret is in, if any: the `@` must start the text or follow whitespace, and the\n * query may contain spaces (names do) but no newline. Returns the index of the `@` and the query.\n */\nexport function findMentionQuery(\n text: string,\n caret: number\n): { start: number; query: string } | null {\n const before = text.slice(0, caret)\n const at = before.lastIndexOf('@')\n if (at < 0) return null\n if (at > 0 && !/\\s/.test(before[at - 1])) return null\n const query = before.slice(at + 1)\n if (query.length > MAX_QUERY_LENGTH || query.includes('\\n') || query.startsWith(' ')) return null\n return { start: at, query }\n}\n\n/** Candidates matching a query: label prefix (or word-prefix) matches, prefix matches first. */\nexport function filterMentionCandidates(\n candidates: ReadonlyArray<MentionCandidate>,\n query: string\n): MentionCandidate[] {\n const q = query.trim().toLowerCase()\n if (!q) return candidates.slice()\n const scored: Array<{ c: MentionCandidate; score: number }> = []\n for (const c of candidates) {\n const label = c.label.toLowerCase()\n if (label.startsWith(q)) scored.push({ c, score: 0 })\n else if (label.split(/\\s+/).some((word) => word.startsWith(q))) scored.push({ c, score: 1 })\n else if (c.description?.toLowerCase().startsWith(q)) scored.push({ c, score: 2 })\n }\n return scored.sort((a, b) => a.score - b.score).map((s) => s.c)\n}\n\n/** Replace the `@query` at `start…caret` with `@<label> `; returns the new text and caret. */\nexport function insertMention(\n text: string,\n start: number,\n caret: number,\n label: string\n): { text: string; caret: number } {\n const inserted = `@${label} `\n return {\n text: text.slice(0, start) + inserted + text.slice(caret),\n caret: start + inserted.length,\n }\n}\n\n/** Every `[from, to)` range where `@<label>` occurs as a whole token. */\nfunction tokenRanges(text: string, label: string): Array<[number, number]> {\n const needle = `@${label}`\n const ranges: Array<[number, number]> = []\n let from = 0\n for (;;) {\n const i = text.indexOf(needle, from)\n if (i < 0) break\n const end = i + needle.length\n const startsToken = i === 0 || /\\s|\\(|\\[/.test(text[i - 1])\n const endsToken = end === text.length || !/[\\p{L}\\p{N}_]/u.test(text[end])\n if (startsToken && endsToken) ranges.push([i, end])\n from = end\n }\n return ranges\n}\n\n/**\n * The candidates mentioned in `text`, in order of first appearance. Longer labels win overlaps,\n * so `@Bob Smith` is Bob Smith, not a separate `@Bob`.\n */\nexport function extractMentions(\n text: string,\n candidates: ReadonlyArray<MentionCandidate>\n): MentionCandidate[] {\n const taken: Array<[number, number]> = []\n const found: Array<{ c: MentionCandidate; at: number }> = []\n const byLength = [...candidates].sort((a, b) => b.label.length - a.label.length)\n for (const c of byLength) {\n if (!c.label) continue\n for (const [from, to] of tokenRanges(text, c.label)) {\n if (taken.some(([a, b]) => from < b && to > a)) continue\n taken.push([from, to])\n if (!found.some((f) => f.c.id === c.id)) found.push({ c, at: from })\n }\n }\n return found.sort((a, b) => a.at - b.at).map((f) => f.c)\n}\n\n/** The API payload for mentioned candidates. */\nexport function toMessageMentions(mentioned: ReadonlyArray<MentionCandidate>): MessageMentionRef[] {\n return mentioned.map((c) =>\n c.kind === 'assistant' ? { type: 'assistant' } : { type: 'user', user_ext_id: c.id }\n )\n}\n\n/** Fragment prefix of the links {@link linkMentions} writes. */\nexport const MENTION_HREF_PREFIX = '#mention-'\n\n/** Escape the characters that would end a markdown link text early. */\nfunction escapeLinkText(label: string): string {\n return label.replace(/[[\\]\\\\]/g, (ch) => `\\\\${ch}`)\n}\n\n/**\n * Turn each stored mention's `@<label>` in `content` into a markdown link\n * `[@<label>](#mention-<id>)`, so a markdown renderer can draw it as a chip (see\n * {@link mentionFromHref}). Text that no longer matches (a renamed user) stays plain text.\n * `assistantLabels` lists other names the assistant may have been mentioned by.\n */\nexport function linkMentions(\n content: string,\n mentions: ReadonlyArray<MessageMentionRef> | null | undefined,\n assistantLabels: ReadonlyArray<string> = []\n): string {\n if (!mentions || mentions.length === 0 || !content) return content\n const targets: Array<{ label: string; id: string }> = []\n for (const m of mentions) {\n const id = m.type === 'assistant' ? 'assistant' : m.user_ext_id\n if (!id) continue\n const labels = m.type === 'assistant' ? [m.label ?? '', ...assistantLabels] : [m.label ?? '']\n for (const label of labels) if (label) targets.push({ label, id })\n }\n targets.sort((a, b) => b.label.length - a.label.length)\n const replacements: Array<{ from: number; to: number; text: string }> = []\n for (const { label, id } of targets) {\n for (const [from, to] of tokenRanges(content, label)) {\n if (replacements.some((r) => from < r.to && to > r.from)) continue\n replacements.push({\n from,\n to,\n text: `[@${escapeLinkText(label)}](${MENTION_HREF_PREFIX}${id})`,\n })\n }\n }\n replacements.sort((a, b) => b.from - a.from)\n let out = content\n for (const r of replacements) out = out.slice(0, r.from) + r.text + out.slice(r.to)\n return out\n}\n\n/** The mention a `#mention-…` href points at, or null for any other href. */\nexport function mentionFromHref(\n href: string | null | undefined\n): { kind: MentionKind; id: string } | null {\n if (!href?.startsWith(MENTION_HREF_PREFIX)) return null\n const id = href.slice(MENTION_HREF_PREFIX.length)\n if (!id) return null\n return { kind: id === 'assistant' ? 'assistant' : 'user', id }\n}\n\n/** A recipient alone is not a message. */\nexport function hasMessageBody(value: string, recipientLabel = 'ARBI'): boolean {\n const text = value.trim()\n return !!text && text.toLowerCase() !== `@${recipientLabel}`.toLowerCase()\n}\n","import { useEffect, useRef, useSyncExternalStore } from 'react'\nimport { parseVersionRef } from '../artifacts/versions'\n\n/**\n * Drafting mode: the documents open beside the chat, and which one a chat turn drafts in.\n *\n * A viewer registers the document it shows (`useRegisterOpenDocument`). Being open binds nothing:\n * a turn names a document (`active_artifact_ext_id`, read with `takeDocumentForTurn` as the\n * question is sent) only when its thread is bound to it (`./thread-document`: started from the\n * document, or attached in that thread), when the document was made in that thread, or when the\n * open document is ambient (an email draft open in the composer). The server then binds the live\n * document to the turn: a Word document is read on demand and edited as tracked changes in the\n * open editor, and what the assistant saves becomes a child version of it. The request carries a\n * reference, never the content.\n *\n * The named document is always the subject, also while one of its earlier versions is on screen\n * read-only: a version still names its document. Sending a turn then returns the viewer to the live\n * document (`showLive`), where the assistant's edits appear as they are made. (Pinning a specific\n * version as a source is a separate feature: it does not go through here.)\n *\n * A module-level registry (not React context), like `useChatSurface`, so a viewer and a chat agree\n * wherever they sit in the tree; the most recently opened document is on top and closing it hands\n * back to the one before. It is not the session state's viewing document (`useArbiSessionState`):\n * it holds what mounted viewers can draft in (saved documents only, with the callback that shows\n * the live one again), and a turn reads it outside React. A viewer on the session's viewing\n * document passes that as `shownId` (it may be a version reference, resolved here the same way as\n * `selectViewingDocumentId` does).\n */\n\n/** What a viewer knows about the document it shows. */\nexport interface SavedDocumentInput {\n /** The document (`doc-…`), never a version reference. */\n documentId: string | null | undefined\n /** An unsaved draft (client-minted id, no backend record). */\n isDraft: boolean\n /** Still streaming: nothing is persisted yet. */\n isStreaming: boolean\n /** An image, audio or video artifact: there is no text to draft in. */\n isBlobArtifact: boolean\n /** The loaded document record. */\n documentData:\n | { external_id?: string | null; wp_type?: string | null; file_name?: string | null }\n | null\n | undefined\n}\n\n/**\n * The saved, content-backed document a chat can draft in, or null. Only a saved artifact or Word\n * document counts: drafts, an artifact still streaming and blob artifacts do not.\n */\nexport function savedDocumentIdFor(input: SavedDocumentInput): string | null {\n const { documentId, isDraft, isStreaming, isBlobArtifact, documentData } = input\n if (!documentId || isDraft || isStreaming || isBlobArtifact) return null\n if (\n documentData?.wp_type !== 'artifact' &&\n !documentData?.file_name?.toLowerCase().endsWith('.docx')\n )\n return null\n // A stale record of the previously viewed document is not this one.\n if (documentData.external_id !== documentId) return null\n return documentId\n}\n\nexport interface OpenDocumentRegistration {\n /** The saved document the viewer shows (`doc-…`); null or empty registers nothing. */\n documentId: string | null | undefined\n /** What is on screen: the document itself, or one of its earlier versions (`doc-…@v2`). */\n shownId?: string | null\n /** Show the live document again. Called when a turn starts while an earlier version is shown. */\n showLive?: () => void\n /** The workspace the document belongs to; a chat in another workspace does not draft in it. */\n workspaceId?: string | null\n /** The thread the document was made in: that thread drafts in it without being bound to it. */\n conversationId?: string | null\n /**\n * Drafted in by whichever chat is beside it, bound or not (an email draft open in the composer:\n * the composer is a drafting surface of its own).\n */\n ambient?: boolean\n}\n\ninterface Entry {\n documentId: string\n current: () => OpenDocumentRegistration\n}\n\nlet entries: Entry[] = []\nconst listeners = new Set<() => void>()\n\nfunction subscribe(listener: () => void): () => void {\n listeners.add(listener)\n return () => listeners.delete(listener)\n}\n\nfunction emit() {\n listeners.forEach((l) => l())\n}\n\nconst top = (): Entry | undefined => entries[entries.length - 1]\n\n/**\n * Registers the document a viewer shows as the open document while the caller is mounted and\n * `documentId` is set. Pass `savedDocumentIdFor(...)`, or the id of a document known to be saved.\n */\nexport function useRegisterOpenDocument(registration: OpenDocumentRegistration): void {\n const latest = useRef(registration)\n const { documentId, workspaceId, conversationId, ambient } = registration\n useEffect(() => {\n latest.current = registration\n })\n // What decides which chat drafts in it changed (its record loaded): readers re-render.\n useEffect(() => {\n if (documentId) emit()\n }, [documentId, workspaceId, conversationId, ambient])\n useEffect(() => {\n if (!documentId) return\n const entry: Entry = { documentId, current: () => latest.current }\n entries = [...entries, entry]\n emit()\n return () => {\n entries = entries.filter((e) => e !== entry)\n emit()\n }\n }, [documentId])\n}\n\n/** The open document's id (the most recently opened), or null. Re-renders when it changes. */\nexport function useOpenDocumentId(options?: { workspaceId?: string | null }): string | null {\n const workspaceId = options?.workspaceId ?? null\n return useSyncExternalStore(\n subscribe,\n () => openDocumentId({ workspaceId }),\n () => null\n )\n}\n\n/** The open document's id (the most recently opened); with `workspaceId`, only one of it. */\nexport function openDocumentId(options?: { workspaceId?: string | null }): string | null {\n const entry = top()\n if (!entry || !inWorkspace(entry, options?.workspaceId)) return null\n return entry.documentId\n}\n\nfunction inWorkspace(entry: Entry, workspaceId: string | null | undefined): boolean {\n const own = entry.current().workspaceId\n return !workspaceId || !own || own === workspaceId\n}\n\n/** What a turn is about to be sent in: its conversation and the document its thread is bound to. */\nexport interface TurnDocumentInput {\n /** The thread's bound document (`threadDocumentId` / the session's `newChatDocumentId`). */\n boundDocumentId: string | null | undefined\n /** The conversation (null: a new chat). */\n conversationId: string | null | undefined\n /** The chat's workspace: an open document of another workspace is never picked up. */\n workspaceId?: string | null\n}\n\n/** The document a turn drafts in, and the open viewer showing it (if one is). */\nfunction pickTurnDocument({\n boundDocumentId,\n conversationId,\n workspaceId,\n}: TurnDocumentInput): { documentId: string; entry: Entry | undefined } | null {\n // A bound thread names its document on every turn, open or not.\n if (boundDocumentId) {\n const entry = [...entries].reverse().find((e) => e.documentId === boundDocumentId)\n return { documentId: boundDocumentId, entry }\n }\n // Unbound: only a document made in this thread, or an ambient one (an email draft).\n for (let i = entries.length - 1; i >= 0; i--) {\n const entry = entries[i]\n if (!inWorkspace(entry, workspaceId)) continue\n const { ambient, conversationId: madeIn } = entry.current()\n if (ambient || (conversationId && madeIn === conversationId))\n return { documentId: entry.documentId, entry }\n }\n return null\n}\n\n/** The document a turn sent now would draft in, or null. Re-renders as documents open and close. */\nexport function useTurnDocumentId(input: TurnDocumentInput): string | null {\n const { boundDocumentId = null, conversationId = null, workspaceId = null } = input\n return useSyncExternalStore(\n subscribe,\n () => pickTurnDocument({ boundDocumentId, conversationId, workspaceId })?.documentId ?? null,\n () => null\n )\n}\n\n/**\n * The document an assistant turn about to be sent drafts in, or null. Call it once per turn as the\n * question is sent: when an earlier version of the document is on screen, the viewer returns to the\n * live document, where the assistant's edits appear.\n */\nexport function takeDocumentForTurn(input: TurnDocumentInput): string | null {\n const picked = pickTurnDocument(input)\n if (!picked) return null\n const { documentId, entry } = picked\n if (entry) {\n const { shownId, showLive } = entry.current()\n if (shownId && shownId !== documentId && parseVersionRef(shownId).docId === documentId)\n showLive?.()\n }\n return documentId\n}\n","/**\n * A thread's document: the one document a conversation drafts in, part of the conversation.\n *\n * A thread is bound to a document only when it was started from it (\"Chat about this document\" in\n * the viewer) or the person attached it in that thread. Only that thread names it on its turns\n * (`active_artifact_ext_id`), on every turn and after a reload. A document merely open or docked\n * beside the chat binds nothing: a new chat (the ask bar, the new-chat button, the thread\n * launcher, home) starts unbound, so a question there never becomes an edit of whatever is open.\n *\n * A new chat's binding is the session's `newChatDocumentId` (opening a new chat clears it); the\n * first turn moves it here, under the conversation's id. Saved threads' bindings are kept on the\n * device (`localStorage`), so a reload keeps them.\n */\n\n/** What this module needs of the session store (structural: the shell entry stays light). */\ninterface NewChatSession {\n getState(): { conversationId: string | null; newChatDocumentId: string | null }\n setNewChatDocumentId(documentId: string | null): void\n}\n\nconst STORAGE_KEY = 'arbi-thread-documents'\n/** The most bindings kept (the oldest go first). */\nconst MAX_BINDINGS = 500\n\nlet bindings: Record<string, string> | null = null\nconst listeners = new Set<() => void>()\n\nfunction storage(): Storage | undefined {\n try {\n return typeof localStorage === 'undefined' ? undefined : localStorage\n } catch {\n return undefined\n }\n}\n\nfunction load(): Record<string, string> {\n if (bindings) return bindings\n bindings = {}\n try {\n const parsed = JSON.parse(storage()?.getItem(STORAGE_KEY) ?? 'null') as unknown\n if (parsed && typeof parsed === 'object')\n for (const [conversationId, documentId] of Object.entries(parsed))\n if (typeof documentId === 'string') bindings[conversationId] = documentId\n } catch {\n // Damaged or blocked: no bindings.\n }\n return bindings\n}\n\nfunction save(next: Record<string, string>) {\n const ids = Object.keys(next)\n if (ids.length > MAX_BINDINGS)\n ids.slice(0, ids.length - MAX_BINDINGS).forEach((id) => delete next[id])\n bindings = next\n try {\n storage()?.setItem(STORAGE_KEY, JSON.stringify(next))\n } catch {\n // Storage full or blocked: the binding holds for this visit.\n }\n listeners.forEach((l) => l())\n}\n\nexport function subscribeThreadDocuments(listener: () => void): () => void {\n listeners.add(listener)\n return () => listeners.delete(listener)\n}\n\n/** The document a saved conversation is bound to, or null. */\nexport function threadDocumentId(conversationId: string | null | undefined): string | null {\n return conversationId ? (load()[conversationId] ?? null) : null\n}\n\n/** Bind a saved conversation to a document, or (null) unbind it. */\nexport function bindThreadDocument(conversationId: string, documentId: string | null): void {\n const current = load()\n if ((current[conversationId] ?? null) === documentId) return\n const next = { ...current }\n delete next[conversationId]\n if (documentId) next[conversationId] = documentId\n save(next)\n}\n\n/** The most recently bound conversation of a document, or null. */\nexport function latestThreadOfDocument(documentId: string): string | null {\n const entries = Object.entries(load())\n for (let i = entries.length - 1; i >= 0; i--)\n if (entries[i][1] === documentId) return entries[i][0]\n return null\n}\n\n/** The document the open conversation is bound to (its saved binding, or the new chat's). */\nexport function boundDocumentOf(state: ReturnType<NewChatSession['getState']>): string | null {\n return state.conversationId ? threadDocumentId(state.conversationId) : state.newChatDocumentId\n}\n\n/**\n * A new chat got its server id: the document it was bound to is now the conversation's. Call it\n * beside `session.moveConversation('new', id)`; `documentId` is the binding its first turn was sent\n * with (default: the session's new-chat binding).\n */\nexport function adoptNewChatDocument(\n session: NewChatSession,\n conversationId: string,\n documentId: string | null = session.getState().newChatDocumentId\n): void {\n if (!documentId) return\n bindThreadDocument(conversationId, documentId)\n if (session.getState().newChatDocumentId === documentId) session.setNewChatDocumentId(null)\n}\n\n/** Test seam: forget every binding (and what is stored). */\nexport function resetThreadDocumentsForTests(): void {\n bindings = {}\n try {\n storage()?.removeItem(STORAGE_KEY)\n } catch {\n // Nothing stored.\n }\n listeners.forEach((l) => l())\n}\n\n/** Test seam: read the stored bindings again, as a reload does. */\nexport function reloadThreadDocumentsForTests(): void {\n bindings = null\n listeners.forEach((l) => l())\n}\n"]}
@@ -136,6 +136,7 @@ var EMPTY_SESSION_STATE = {
136
136
  autoSendDraft: false,
137
137
  agentChatOwners: {},
138
138
  newAgentChat: null,
139
+ newChatDocumentId: null,
139
140
  messageTimers: {}
140
141
  };
141
142
  var selectViewingDocumentId = (state) => state.viewingDocument ? parseVersionRef(state.viewingDocument.id).docId : null;
@@ -232,6 +233,7 @@ function createArbiSessionStore(initial = {}, { draftStorage } = {}) {
232
233
  conversationFacts: {},
233
234
  pinnedDocumentId: null,
234
235
  newAgentChat: null,
236
+ newChatDocumentId: null,
235
237
  messageTimers: {},
236
238
  threadTabs: [],
237
239
  activeThreadTabId: null
@@ -339,7 +341,11 @@ function createArbiSessionStore(initial = {}, { draftStorage } = {}) {
339
341
  const id = conversationId ?? "new";
340
342
  const others = state.threadTabs.filter((tab) => threadTabId(tab) !== id);
341
343
  const threadTabs = [...others, { conversationId }].slice(-MAX_THREAD_TABS);
342
- update({ threadTabs, activeThreadTabId: id });
344
+ update({
345
+ threadTabs,
346
+ activeThreadTabId: id,
347
+ ...conversationId === null ? { newChatDocumentId: null } : {}
348
+ });
343
349
  if (state.conversationId !== conversationId)
344
350
  update({ conversationId, cursor: null, editingMessageId: null });
345
351
  return id;
@@ -376,6 +382,9 @@ function createArbiSessionStore(initial = {}, { draftStorage } = {}) {
376
382
  if (current?.agentId !== newAgentChat?.agentId || current?.workspaceId !== newAgentChat?.workspaceId)
377
383
  update({ newAgentChat });
378
384
  },
385
+ setNewChatDocumentId: (newChatDocumentId) => {
386
+ if (state.newChatDocumentId !== newChatDocumentId) update({ newChatDocumentId });
387
+ },
379
388
  startEditing: (messageId, content) => {
380
389
  preEdit = { draft: selectDraft(state), cursor: state.cursor };
381
390
  update({ editingMessageId: messageId });
@@ -451,7 +460,12 @@ function createArbiSessionStore(initial = {}, { draftStorage } = {}) {
451
460
  }
452
461
  });
453
462
  },
454
- startNewConversation: () => update({ conversationId: null, cursor: null, editingMessageId: null }),
463
+ startNewConversation: () => update({
464
+ conversationId: null,
465
+ cursor: null,
466
+ editingMessageId: null,
467
+ newChatDocumentId: null
468
+ }),
455
469
  setPaMode: (paMode) => {
456
470
  if (state.paMode !== paMode) update({ paMode });
457
471
  },
@@ -982,5 +996,5 @@ function useUserUsageToday(options) {
982
996
  }
983
997
 
984
998
  export { DEFAULT_DOCUMENT_VIEWER_STATE, EMPTY_SESSION_STATE, MAX_THREAD_TABS, MIN_QUEUED_MESSAGE_VISIBILITY_MS, PROJECT_CREATION_DENIED_REASON, agentControl, clearSealedDrafts, conversationKey, createArbiSessionStore, createSealedDraftStorage, isUsageMetered, nextViewingDocument, queuedMessages, selectDraft, selectIsGenerating, selectViewingDocumentId, threadTabId, useActivity, useAgents, useArbiSession, useArbiSessionState, useArbiSessionStore, useAssistantQuery, useAvailableModels, useBuiltinCommands, useCanCreateProjects, useConfig, useConfigs, useConversationThreads, useConversations, useCurrentUser, useDeleteAgents, useDocumentVersionList, useFirmPool, useHealth, useMessageDetails, useParsedDocument, useProjectInvoices, useProjectUsage, useProjects, useProjectsUsage, useSignedInSession, useTags, useThumbnails, useTopUpFirmPool, useUserUsageToday, useWorkspaceActivity, useWorkspaces };
985
- //# sourceMappingURL=chunk-5DI27KJG.js.map
986
- //# sourceMappingURL=chunk-5DI27KJG.js.map
999
+ //# sourceMappingURL=chunk-X2OC2LCD.js.map
1000
+ //# sourceMappingURL=chunk-X2OC2LCD.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/chat/run-state.ts","../src/session/store.ts","../src/session/drafts.ts","../src/session/session-hooks.ts","../src/session/signed-in.ts","../src/usage-metered.ts","../src/hooks.ts"],"names":["useSyncExternalStore","useMemo"],"mappings":";;;;;;;;;;AAkCO,IAAM,gCAAA,GAAmC;AAEhD,IAAM,SAAA,GAAY,CAChB,MAAA,EACA,MAAA,KAEA,OAAO,WAAA,CAAY,MAAA,CAAO,OAAA,CAAQ,MAAM,CAAA,CAAE,GAAA,CAAI,CAAC,CAAC,EAAA,EAAI,QAAQ,CAAA,KAAM,CAAC,IAAI,MAAA,CAAO,QAAQ,CAAC,CAAC,CAAC,CAAA;AAW3F,SAAS,oBAAA,CACP,UACA,eAAA,EACa;AACb,EAAA,MAAM,IAAA,GAAO,gBAAgB,IAAA,EAAK;AAClC,EAAA,MAAM,KAAA,uBAAY,GAAA,EAAY;AAC9B,EAAA,IAAI,MAAA,GAAS,CAAA;AACb,EAAA,KAAA,MAAW,WAAW,QAAA,EAAU;AAC9B,IAAA,IAAI,MAAA,IAAU,KAAK,MAAA,EAAQ;AAC3B,IAAA,MAAM,OA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AAA,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-X2OC2LCD.js","sourcesContent":["/**\n * The live state of a running turn that is not in the threads cache: follow-ups waiting in the\n * agent bar's queue box, and the run-control state (pause / resume / report). Both are keyed by the\n * streaming answer's id (the response id) and live in the session (`ArbiSessionState`); these are\n * the pure updates every session store applies.\n */\n\nimport type { ProbeAnswerEvent } from '@arbidocs/sdk/browser'\n\n/** A follow-up the person sent while a turn ran, shown in the agent bar until it is its own turn. */\nexport interface QueuedMessage {\n /** The client's own id, unique across turns. */\n clientId: string\n content: string\n /** The stored user message, once the server confirmed the follow-up. */\n serverId: string | null\n acknowledged: boolean\n /** When it was queued (epoch ms): a follow-up stays readable for a moment. */\n createdAt: number\n}\n\n/** Queued follow-ups per running answer (response id). */\nexport type QueuedMessages = Readonly<Record<string, readonly QueuedMessage[]>>\n\n/**\n * Control state of a running agent turn:\n * - `running` normal streaming.\n * - `pausing` the person sent /pause; awaiting the server's confirmed halt (optimistic).\n * - `paused` the server confirmed the loop halted at a boundary.\n * - `resuming` the person sent /resume; awaiting the stream to flow again (optimistic).\n */\nexport type AgentRunControlState = 'running' | 'pausing' | 'paused' | 'resuming'\n\n/** How long a confirmed follow-up stays in the queue box at least, so it can be read. */\nexport const MIN_QUEUED_MESSAGE_VISIBILITY_MS = 800\n\nconst mapQueues = (\n queues: QueuedMessages,\n update: (messages: readonly QueuedMessage[]) => QueuedMessage[]\n): QueuedMessages =>\n Object.fromEntries(Object.entries(queues).map(([id, messages]) => [id, update(messages)]))\n\n/**\n * The client ids of the queued prompts a steering interjection delivered.\n *\n * The backend joins every prompt it steers into one run with a blank line, in the order they were\n * sent. Prompts the backend queued as turns of their own stay in the queue between them, so the\n * steered ones need not be first, or even adjacent: walk the queue in order and take each prompt\n * that is the next part of the delivered text. Nothing is taken unless the whole text is accounted\n * for.\n */\nfunction findConsumedMessages(\n messages: readonly QueuedMessage[],\n combinedContent: string\n): Set<string> {\n const text = combinedContent.trim()\n const taken = new Set<string>()\n let cursor = 0\n for (const message of messages) {\n if (cursor >= text.length) break\n const content = message.content.trim()\n if (!content) continue\n const separator = cursor === 0 ? '' : '\\n\\n'\n if (text.startsWith(separator + content, cursor)) {\n taken.add(message.clientId)\n cursor += separator.length + content.length\n }\n }\n return cursor === text.length ? taken : new Set()\n}\n\n/** The queue updates. Client ids are unique, so the per-entry ones find it under any turn. */\nexport const queuedMessages = {\n add: (q: QueuedMessages, responseId: string, message: QueuedMessage): QueuedMessages => ({\n ...q,\n [responseId]: [...(q[responseId] ?? []), message],\n }),\n acknowledge: (q: QueuedMessages, clientId: string, serverId: string | null): QueuedMessages =>\n mapQueues(q, (messages) =>\n messages.map((m) => (m.clientId === clientId ? { ...m, serverId, acknowledged: true } : m))\n ),\n remove: (q: QueuedMessages, clientId: string): QueuedMessages =>\n mapQueues(q, (messages) => messages.filter((m) => m.clientId !== clientId)),\n removeByServerId: (q: QueuedMessages, serverId: string): QueuedMessages =>\n mapQueues(q, (messages) => messages.filter((m) => m.serverId !== serverId)),\n removeByContent: (q: QueuedMessages, responseId: string, content: string): QueuedMessages => {\n let removed = false\n return {\n ...q,\n [responseId]: (q[responseId] ?? []).filter((m) => {\n if (!removed && m.content === content) {\n removed = true\n return false\n }\n return true\n }),\n }\n },\n /** Take out the prompts a steering interjection delivered into the run. */\n consume: (q: QueuedMessages, responseId: string, combinedContent: string): QueuedMessages => {\n const messages = q[responseId] ?? []\n const consumed = findConsumedMessages(messages, combinedContent)\n return { ...q, [responseId]: messages.filter((m) => !consumed.has(m.clientId)) }\n },\n clear: (q: QueuedMessages, responseId: string): QueuedMessages => ({ ...q, [responseId]: [] }),\n /** Move the entries still waiting on a finished turn to the turn that is now running. */\n move: (q: QueuedMessages, fromResponseId: string, toResponseId: string): QueuedMessages => {\n const waiting = q[fromResponseId] ?? []\n if (fromResponseId === toResponseId || waiting.length === 0) return q\n return { ...q, [fromResponseId]: [], [toResponseId]: [...(q[toResponseId] ?? []), ...waiting] }\n },\n /** Find a queued follow-up by its client id, under whichever turn holds it. */\n find: (q: QueuedMessages, clientId: string): QueuedMessage | undefined =>\n Object.values(q)\n .flat()\n .find((m) => m.clientId === clientId),\n}\n\n/** The transient control state of the running turns, per response id. */\nexport interface AgentControlMaps {\n agentControlStates: Readonly<Record<string, AgentRunControlState>>\n agentProbeAnswers: Readonly<Record<string, ProbeAnswerEvent>>\n agentProbePending: Readonly<Record<string, boolean>>\n}\n\nconst without = <T>(record: Readonly<Record<string, T>>, key: string): Record<string, T> => {\n const next = { ...record }\n delete next[key]\n return next\n}\n\n/** The control updates. */\nexport const agentControl = {\n setState: (c: AgentControlMaps, id: string, state: AgentRunControlState): AgentControlMaps => ({\n ...c,\n agentControlStates: { ...c.agentControlStates, [id]: state },\n }),\n /** A probe answered: the latest answer, and nothing pending any more. */\n setProbeAnswer: (c: AgentControlMaps, id: string, probe: ProbeAnswerEvent): AgentControlMaps => ({\n ...c,\n agentProbeAnswers: { ...c.agentProbeAnswers, [id]: probe },\n agentProbePending: { ...c.agentProbePending, [id]: false },\n }),\n setProbePending: (c: AgentControlMaps, id: string, pending: boolean): AgentControlMaps => ({\n ...c,\n agentProbePending: { ...c.agentProbePending, [id]: pending },\n }),\n /** The turn is over: drop its control state. */\n clear: (c: AgentControlMaps, id: string): AgentControlMaps => ({\n agentControlStates: without(c.agentControlStates, id),\n agentProbeAnswers: without(c.agentProbeAnswers, id),\n agentProbePending: without(c.agentProbePending, id),\n }),\n}\n","/**\n * The session state every block reads and writes: the selected workspace, the current conversation,\n * the document being viewed, the document selection, generation per conversation, Personal\n * Assistant mode and the documents in each conversation.\n *\n * An {@link ArbiSessionStore} is the adapter a host gives as its configuration's `session`:\n * a host with its own state (ARBI-frontend's zustand store) maps its fields onto\n * {@link ArbiSessionState} and its actions onto the setters, so there is one source of truth.\n * Other hosts use {@link createArbiSessionStore}, an in-memory store.\n */\n\nimport type { components } from '@arbidocs/client'\nimport type { ProbeAnswerEvent } from '@arbidocs/sdk/browser'\nimport { parseVersionRef } from '../artifacts/versions'\nimport type { ArbiDraftStorage } from './drafts'\nimport {\n agentControl,\n queuedMessages,\n type AgentControlMaps,\n type AgentRunControlState,\n type QueuedMessage,\n type QueuedMessages,\n} from '../chat/run-state'\n\n/** The document being viewed. */\nexport interface ArbiViewingDocument {\n /** The document (`doc-…`), or a version reference (`doc-…@v2`) while an earlier version shows. */\n id: string\n /** The page being read, when known. */\n page: number | null\n /** The passage being read, when one is. */\n passageId: string | null\n}\n\n/** A tab of the document viewer. */\nexport type ArbiViewerTab = 'pdf' | 'edit' | 'html' | 'docx' | 'xlsx' | 'versions' | 'preview'\n\n/**\n * The document viewer's own state, shared with whatever opens documents (a citation opens the text\n * view, Compare from a documents list opens the redline): the open tab, the document compared with\n * the one viewed, and a tab asked for when a document was opened (applied once it has loaded).\n */\nexport interface ArbiDocumentViewerState {\n tab: ArbiViewerTab\n /** The document (or version reference) compared with the viewed one, or null. */\n compareId: string | null\n /** A tab to show once `documentId` has loaded (a signature request opens on the PDF). */\n tabRequest: { documentId: string; tab: ArbiViewerTab } | null\n /** The text view's size, a multiplier of the normal size: a reading preference. */\n textScale: number\n /** A phone user picked the PDF by hand: documents stop opening on the text view. */\n phonePdfChosen: boolean\n}\n\n/** Generation in one conversation. */\nexport interface ArbiConversationGeneration {\n isGenerating: boolean\n error: string | null\n /** When the running turn started (epoch ms). */\n startTime: number | null\n /** The answer being streamed (its response id), once the server named it. */\n streamingAssistantId?: string | null\n /** The server's elapsed time for the running turn (seconds). */\n backendElapsed?: number | null\n /** The question of a send that failed, for Retry. */\n lastFailedMessage?: string | null\n /** The local stream of the running turn, which Stop aborts (absent for an attached run). */\n abortController?: AbortController | null\n}\n\n/** A document in a conversation's context; a pinned one stays there across turns. */\nexport interface ArbiConversationDocument {\n docId: string\n isPinned: boolean\n}\n\n/**\n * Where the selected workspace stands on the server session: `opening` while a switch waits for\n * `/open` (the host may cover the page), `open` once workspace-scoped requests may run.\n */\nexport type ArbiWorkspaceStatus = 'closed' | 'opening' | 'open'\n\nexport interface ArbiSessionState extends AgentControlMaps {\n /** The selected workspace (`wrk-…`). */\n workspaceId: string | null\n /** Whether it is open on the server session (`useSwitchWorkspace` moves it). */\n workspaceStatus: ArbiWorkspaceStatus\n /** The open conversation, or null for a new one / none. */\n conversationId: string | null\n viewingDocument: ArbiViewingDocument | null\n documentViewer: ArbiDocumentViewerState\n /** The documents selected in document lists. */\n selectedDocumentIds: readonly string[]\n /** Generation state per conversation id. */\n generating: Readonly<Record<string, ArbiConversationGeneration>>\n /** Personal Assistant mode for new conversations. */\n paMode: boolean\n /** The documents in each conversation's context, per conversation id. */\n conversationDocuments: Readonly<Record<string, readonly ArbiConversationDocument[]>>\n /**\n * Per conversation id: true while an empty chat follows the workspace's documents (set by\n * {@link useDocumentAutoAdd}); any other change of its documents is a choice and turns it off.\n * Missing for a selection made before this was recorded.\n */\n conversationDocumentAutoAdd: Readonly<Record<string, boolean>>\n /** The facts in each conversation's context, per conversation id (`new` for a new chat). */\n conversationFacts: Readonly<Record<string, readonly string[]>>\n /** The document read in full with each turn (one at a time). */\n pinnedDocumentId: string | null\n /** The message the open conversation continues from: the leaf of the line being viewed. */\n cursor: string | null\n /** A follow-up the backend suggested for a conversation, offered in its composer. */\n suggestedQuery: { conversationExtId: string; text: string } | null\n /** Follow-ups waiting in a running turn's agent bar, per response id. */\n queuedMessages: QueuedMessages\n /**\n * What is typed in each conversation's composer, per conversation id (`new` for a new chat).\n * The open conversation's is {@link selectDraft}. A host may keep them across reloads, stored\n * locally and encrypted ({@link ArbiDraftStorage}).\n */\n drafts: Readonly<Record<string, string>>\n /** The question being edited in the open conversation (sent as a new branch), or null. */\n editingMessageId: string | null\n /** A message a link opened the conversation at: its thread opens and the view goes to it. */\n deepLinkMessageId: string | null\n /** The citation whose sources are open (`<message id>-<citation number>`), or null. */\n activeCitationKey: string | null\n /** The config (model) chosen for the open conversation; absent: the person's last one. */\n chatModel: string | undefined\n /** The model name the open conversation's picker shows (an edit or a launch sets it). */\n chatModelName: string | undefined\n /** The open thread tabs, least recently used first (`ConnectedThreadTabs` shows them). */\n threadTabs: readonly ArbiThreadTab[]\n /** The thread tab on screen (`threadTabId`), or null while the thread list is. */\n activeThreadTabId: string | null\n /** The mode a new conversation starts in: `always` answers, `mentioned` only when @mentioned. */\n newConversationAssistantMode: 'always' | 'mentioned'\n /** Structured tools a launch wants on the next send (the send consumes them). */\n pendingTools: TurnTools | null\n /**\n * Send the open composer's draft as soon as the conversation is ready (a launch that composed it);\n * the send clears it.\n */\n autoSendDraft: boolean\n /** The owned agent each agent chat runs through, per conversation id. */\n agentChatOwners: Readonly<Record<string, string>>\n /** A new agent chat about to start: its agent and workspace. */\n newAgentChat: { agentId: string; workspaceId: string } | null\n /**\n * The document a new chat about to start is bound to (`doc-…`): set only by starting a chat from\n * a document (\"Chat about this document\") or attaching it in the new chat, never by a document\n * merely being open. Starting another new chat clears it; the first turn moves it to the\n * conversation (`chat/thread-document`).\n */\n newChatDocumentId: string | null\n /** Each answer's timer, saved when it stops showing (`<conversation id>:<message id>`). */\n messageTimers: Readonly<Record<string, ArbiMessageTimer>>\n}\n\n/** An answer's timer: when its run started (epoch ms) and how long it took (seconds). */\nexport interface ArbiMessageTimer {\n startTime: number\n elapsedTime: number\n}\n\n/** A thread tab: a conversation's, or a new chat's (`conversationId` null). */\nexport interface ArbiThreadTab {\n conversationId: string | null\n}\n\n/** A thread tab's id: its conversation's id, or `new` for a new chat. */\nexport const threadTabId = (tab: ArbiThreadTab): string => tab.conversationId ?? 'new'\n\n/** The most thread tabs kept (the least recently used goes first). */\nexport const MAX_THREAD_TABS = 12\n\n/** A send's structured tools (`MessageInput.tools`). */\nexport type TurnTools = components['schemas']['MessageInput']['tools']\n\n/** What to view: page and passage are left unchanged when omitted. */\nexport interface ArbiViewingDocumentInput {\n id: string\n page?: number | null\n passageId?: string | null\n}\n\nexport interface ArbiSessionStore {\n /** The current state. The same object until something in it changes. */\n getState(): ArbiSessionState\n /** Be told when the state may have changed. Returns the unsubscribe. */\n subscribe(listener: () => void): () => void\n setWorkspaceId(id: string | null): void\n setWorkspaceStatus(status: ArbiWorkspaceStatus): void\n /**\n * Drop everything scoped to the workspace being left (the open conversation and its generation,\n * the viewed document, the selection, the context documents and facts), before a switch. A host\n * with workspace-scoped state of its own clears that too.\n */\n leaveWorkspace(): void\n setConversationId(id: string | null): void\n /**\n * View a document, or none. Viewing another document resets the page; `page` and `passageId`\n * set them when given.\n */\n setViewingDocument(document: ArbiViewingDocumentInput | null): void\n /** Change the document viewer's state; fields not given stay. */\n setDocumentViewer(change: Partial<ArbiDocumentViewerState>): void\n setSelectedDocumentIds(ids: string[]): void\n /** Start or end a conversation's turn; `abortController` is its local stream, which Stop aborts. */\n setConversationGenerating(\n conversationId: string,\n isGenerating: boolean,\n abortController?: AbortController | null\n ): void\n setPaMode(enabled: boolean): void\n /** Set a conversation's documents; `autoAdd` marks an automatic pick (default: the user's). */\n setConversationDocuments(\n conversationId: string,\n documents: ArbiConversationDocument[],\n autoAdd?: boolean\n ): void\n setConversationFacts(conversationId: string, factIds: string[]): void\n setPinnedDocumentId(id: string | null): void\n /** The answer a conversation is streaming; `startTime` defaults to now (a re-attach passes the run's). */\n setStreamingAssistantId(conversationId: string, assistantId: string, startTime?: number): void\n setBackendElapsed(conversationId: string, seconds: number): void\n /**\n * A new chat got its server id: its generation, documents and facts move from `fromId` (`new`) to\n * `toId`, and it stays the open conversation.\n */\n moveConversation(fromId: string, toId: string): void\n setCursor(messageId: string | null): void\n setSuggestedQuery(suggestion: ArbiSessionState['suggestedQuery']): void\n addQueuedMessage(responseId: string, message: QueuedMessage): void\n acknowledgeQueuedMessage(clientId: string, serverId: string | null): void\n removeQueuedMessage(clientId: string): void\n removeQueuedMessageByServerId(serverId: string): void\n consumeQueuedMessage(responseId: string, combinedContent: string): void\n clearQueuedMessages(responseId: string): void\n moveQueuedMessages(fromResponseId: string, toResponseId: string): void\n setAgentControlState(responseId: string, state: AgentRunControlState): void\n setAgentProbeAnswer(responseId: string, probe: ProbeAnswerEvent): void\n setAgentProbePending(responseId: string, pending: boolean): void\n clearAgentControl(responseId: string): void\n /** Set what is typed in the open conversation's composer. */\n setDraft(text: string): void\n /** The config (model) the open conversation's turns use; undefined: the person's last one. */\n setChatModel(model: string | undefined): void\n setChatModelName(model: string | undefined): void\n /**\n * Show a conversation in its thread tab (null: a new chat), opening the tab when it is not open.\n * Returns the tab's id.\n */\n openThreadTab(conversationId: string | null): string\n /** Close a thread tab; closing the one on screen shows the last other, else the thread list. */\n closeThreadTab(tabId: string): void\n /** Show a thread tab's conversation, or (null) the thread list; the tabs stay open. */\n selectThreadTab(tabId: string | null): void\n setNewConversationAssistantMode(mode: 'always' | 'mentioned'): void\n /** Start a new chat with an owned agent (null: an ordinary new chat). */\n setNewAgentChat(chat: { agentId: string; workspaceId: string } | null): void\n /** Bind the new chat to a document (null: unbound). Opening a new chat's tab clears it. */\n setNewChatDocumentId(documentId: string | null): void\n /** Edit a question: the composer holds it (its draft and line come back on cancel). */\n startEditing(messageId: string, content: string): void\n /** Leave the edit: the composer gets its draft back, and the view the line it was on. */\n cancelEditing(): void\n /** The edit was sent: leave it. */\n completeEditing(): void\n setDeepLinkMessageId(messageId: string | null): void\n setActiveCitationKey(key: string | null): void\n setPendingTools(tools: TurnTools | null): void\n setAutoSendDraft(on: boolean): void\n setAgentChatOwner(conversationId: string, agentId: string): void\n /** Save an answer's timer (`<conversation id>:<message id>`). */\n setMessageTimer(key: string, timer: ArbiMessageTimer): void\n clearMessageTimer(key: string): void\n /** A send failed: the turn stops, with the server's words and the question to retry. */\n setConversationError(\n conversationId: string,\n error: string | null,\n lastFailedMessage?: string | null\n ): void\n clearConversationError(conversationId: string): void\n /** Stop the conversation's local stream and end its turn. */\n abortConversationGeneration(conversationId: string): void\n /** Leave the open conversation for a new one (its conversation was deleted). */\n startNewConversation(): void\n}\n\nexport const DEFAULT_DOCUMENT_VIEWER_STATE: ArbiDocumentViewerState = {\n tab: 'pdf',\n compareId: null,\n tabRequest: null,\n textScale: 1,\n phonePdfChosen: false,\n}\n\nexport const EMPTY_SESSION_STATE: ArbiSessionState = {\n workspaceId: null,\n workspaceStatus: 'closed',\n conversationId: null,\n viewingDocument: null,\n documentViewer: DEFAULT_DOCUMENT_VIEWER_STATE,\n selectedDocumentIds: [],\n generating: {},\n paMode: false,\n conversationDocuments: {},\n conversationDocumentAutoAdd: {},\n conversationFacts: {},\n pinnedDocumentId: null,\n cursor: null,\n suggestedQuery: null,\n queuedMessages: {},\n agentControlStates: {},\n agentProbeAnswers: {},\n agentProbePending: {},\n drafts: {},\n editingMessageId: null,\n deepLinkMessageId: null,\n activeCitationKey: null,\n chatModel: undefined,\n chatModelName: undefined,\n threadTabs: [],\n activeThreadTabId: null,\n newConversationAssistantMode: 'always',\n pendingTools: null,\n autoSendDraft: false,\n agentChatOwners: {},\n newAgentChat: null,\n newChatDocumentId: null,\n messageTimers: {},\n}\n\n/** The viewed document itself (`doc-…`), also while one of its earlier versions is on screen. */\nexport const selectViewingDocumentId = (state: ArbiSessionState): string | null =>\n state.viewingDocument ? parseVersionRef(state.viewingDocument.id).docId : null\n\n/** The conversation key drafts and context are kept under: its id, or `new` for a new chat. */\nexport const conversationKey = (state: ArbiSessionState): string => state.conversationId ?? 'new'\n\n/** What is typed in the open conversation's composer. */\nexport const selectDraft = (state: ArbiSessionState): string =>\n state.drafts[conversationKey(state)] ?? ''\n\n/** Whether `conversationId` is generating. */\nexport const selectIsGenerating =\n (conversationId: string | null | undefined) =>\n (state: ArbiSessionState): boolean =>\n !!conversationId && !!state.generating[conversationId]?.isGenerating\n\n/** The next viewing document, given the current one (shared by every store implementation). */\nexport function nextViewingDocument(\n current: ArbiViewingDocument | null,\n input: ArbiViewingDocumentInput | null\n): ArbiViewingDocument | null {\n if (!input) return null\n const same = current?.id === input.id\n return {\n id: input.id,\n page: input.page !== undefined ? input.page : same ? (current?.page ?? null) : null,\n passageId: input.passageId !== undefined ? input.passageId : (current?.passageId ?? null),\n }\n}\n\n/** Options of {@link createArbiSessionStore}. */\nexport interface ArbiSessionStoreOptions {\n /** Keep the composers' drafts across reloads (see {@link createSealedDraftStorage}). */\n draftStorage?: ArbiDraftStorage\n}\n\n/** An in-memory session store: the default for hosts without state of their own. */\n/** A per-conversation record without the unsent new chat's entry. */\nfunction withoutNew<T>(record: Readonly<Record<string, T>>): Record<string, T> {\n const { new: _new, ...saved } = record\n return saved\n}\n\nexport function createArbiSessionStore(\n initial: Partial<ArbiSessionState> = {},\n { draftStorage }: ArbiSessionStoreOptions = {}\n): ArbiSessionStore {\n let state: ArbiSessionState = { ...EMPTY_SESSION_STATE, ...initial }\n const listeners = new Set<() => void>()\n const update = (patch: Partial<ArbiSessionState>) => {\n state = { ...state, ...patch }\n listeners.forEach((listener) => listener())\n }\n // The draft and line the composer had when an edit began, given back when it is cancelled.\n let preEdit: { draft: string; cursor: string | null } = { draft: '', cursor: null }\n // The saved drafts come back once the person's key is there (it is not before sign-in); a draft\n // typed meanwhile wins over its saved copy.\n let draftsRestored = !draftStorage\n // Whose drafts the store holds: another person's never carry over to the next sign-in.\n let draftsOwner = draftStorage?.owner() ?? null\n const restoreDrafts = () => {\n if (!draftStorage) return\n const owner = draftStorage.owner()\n if (owner !== draftsOwner) {\n if (draftsOwner !== null) update({ drafts: {} })\n draftsOwner = owner\n draftsRestored = false\n }\n if (draftsRestored) return\n draftsRestored = true\n void draftStorage.load().then(\n (saved) => {\n if (saved && draftStorage.owner() === owner)\n update({ drafts: { ...saved, ...state.drafts } })\n else draftsRestored = false\n },\n () => {\n draftsRestored = false\n }\n )\n }\n // The session ended: what was typed goes with it.\n draftStorage?.onClear(() => {\n draftsRestored = false\n draftsOwner = null\n preEdit = { draft: '', cursor: null }\n if (Object.keys(state.drafts).length > 0) update({ drafts: {} })\n })\n restoreDrafts()\n const setDrafts = (drafts: Record<string, string>) => {\n update({ drafts })\n draftStorage?.save(drafts)\n }\n const setDraftOf = (key: string, text: string) => {\n if ((state.drafts[key] ?? '') === text) return\n const drafts = { ...state.drafts }\n if (text) drafts[key] = text\n else delete drafts[key]\n setDrafts(drafts)\n }\n return {\n getState: () => state,\n subscribe: (listener) => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n setWorkspaceId: (workspaceId) => {\n if (state.workspaceId !== workspaceId) update({ workspaceId })\n // A workspace opens once signed in: the key that opens the saved drafts is there now.\n restoreDrafts()\n },\n setWorkspaceStatus: (workspaceStatus) => {\n if (state.workspaceStatus !== workspaceStatus) update({ workspaceStatus })\n },\n leaveWorkspace: () => {\n // A turn streaming in the workspace being left stops here (the server finishes it).\n Object.values(state.generating).forEach((generation) => generation.abortController?.abort())\n update({\n workspaceStatus: 'closed',\n conversationId: null,\n cursor: null,\n viewingDocument: null,\n selectedDocumentIds: [],\n generating: {},\n // Saved conversations keep their documents; the unsent new chat's belong to this workspace.\n conversationDocuments: withoutNew(state.conversationDocuments),\n conversationDocumentAutoAdd: withoutNew(state.conversationDocumentAutoAdd),\n conversationFacts: {},\n pinnedDocumentId: null,\n newAgentChat: null,\n newChatDocumentId: null,\n messageTimers: {},\n threadTabs: [],\n activeThreadTabId: null,\n })\n },\n setConversationId: (conversationId) => {\n // Another conversation opens on its own line, not on the edit or line of the one before.\n if (state.conversationId !== conversationId)\n update({ conversationId, cursor: null, editingMessageId: null })\n },\n setViewingDocument: (input) =>\n update({ viewingDocument: nextViewingDocument(state.viewingDocument, input) }),\n setDocumentViewer: (change) => {\n const next = { ...state.documentViewer, ...change }\n const keys = Object.keys(change) as (keyof ArbiDocumentViewerState)[]\n if (keys.some((key) => next[key] !== state.documentViewer[key]))\n update({ documentViewer: next })\n },\n setSelectedDocumentIds: (ids) => update({ selectedDocumentIds: ids }),\n setConversationGenerating: (conversationId, isGenerating, abortController = null) => {\n const current = state.generating[conversationId]\n update({\n generating: {\n ...state.generating,\n [conversationId]: {\n ...current,\n isGenerating,\n error: isGenerating ? null : (current?.error ?? null),\n startTime: isGenerating ? Date.now() : null,\n streamingAssistantId: isGenerating ? (current?.streamingAssistantId ?? null) : null,\n backendElapsed: isGenerating ? (current?.backendElapsed ?? null) : null,\n abortController,\n },\n },\n })\n },\n setStreamingAssistantId: (conversationId, streamingAssistantId, startTime = Date.now()) => {\n const current = state.generating[conversationId]\n update({\n generating: {\n ...state.generating,\n [conversationId]: {\n ...(current ?? { isGenerating: false, error: null }),\n streamingAssistantId,\n startTime,\n },\n },\n })\n },\n setBackendElapsed: (conversationId, backendElapsed) => {\n const current = state.generating[conversationId] ?? {\n isGenerating: false,\n error: null,\n startTime: null,\n }\n update({\n generating: { ...state.generating, [conversationId]: { ...current, backendElapsed } },\n })\n },\n moveConversation: (fromId, toId) => {\n const move = <T>(record: Readonly<Record<string, T>>): Record<string, T> => {\n const next = { ...record }\n if (fromId in next) {\n next[toId] = next[fromId]\n delete next[fromId]\n }\n return next\n }\n update({\n generating: move(state.generating),\n conversationDocuments: move(state.conversationDocuments),\n conversationDocumentAutoAdd: move(state.conversationDocumentAutoAdd),\n conversationFacts: move(state.conversationFacts),\n conversationId: state.conversationId ?? toId,\n // The new chat's tab is now the conversation's.\n threadTabs: state.threadTabs.map((tab) =>\n threadTabId(tab) === fromId ? { conversationId: toId } : tab\n ),\n activeThreadTabId: state.activeThreadTabId === fromId ? toId : state.activeThreadTabId,\n })\n // What is typed stays in the composer it was typed in.\n if (fromId in state.drafts) setDrafts(move(state.drafts))\n },\n setConversationFacts: (conversationId, factIds) =>\n update({ conversationFacts: { ...state.conversationFacts, [conversationId]: factIds } }),\n setPinnedDocumentId: (pinnedDocumentId) => update({ pinnedDocumentId }),\n setCursor: (cursor) => {\n if (state.cursor !== cursor) update({ cursor })\n },\n setSuggestedQuery: (suggestedQuery) => update({ suggestedQuery }),\n addQueuedMessage: (id, message) =>\n update({ queuedMessages: queuedMessages.add(state.queuedMessages, id, message) }),\n acknowledgeQueuedMessage: (clientId, serverId) =>\n update({\n queuedMessages: queuedMessages.acknowledge(state.queuedMessages, clientId, serverId),\n }),\n removeQueuedMessage: (clientId) =>\n update({ queuedMessages: queuedMessages.remove(state.queuedMessages, clientId) }),\n removeQueuedMessageByServerId: (serverId) =>\n update({ queuedMessages: queuedMessages.removeByServerId(state.queuedMessages, serverId) }),\n consumeQueuedMessage: (id, content) =>\n update({ queuedMessages: queuedMessages.consume(state.queuedMessages, id, content) }),\n clearQueuedMessages: (id) =>\n update({ queuedMessages: queuedMessages.clear(state.queuedMessages, id) }),\n moveQueuedMessages: (from, to) =>\n update({ queuedMessages: queuedMessages.move(state.queuedMessages, from, to) }),\n setAgentControlState: (id, control) => update(agentControl.setState(state, id, control)),\n setAgentProbeAnswer: (id, probe) => update(agentControl.setProbeAnswer(state, id, probe)),\n setAgentProbePending: (id, pending) => update(agentControl.setProbePending(state, id, pending)),\n clearAgentControl: (id) => update(agentControl.clear(state, id)),\n setDraft: (text) => setDraftOf(conversationKey(state), text),\n setChatModel: (chatModel) => {\n if (state.chatModel !== chatModel) update({ chatModel })\n },\n openThreadTab: (conversationId) => {\n const id = conversationId ?? 'new'\n const others = state.threadTabs.filter((tab) => threadTabId(tab) !== id)\n const threadTabs = [...others, { conversationId }].slice(-MAX_THREAD_TABS)\n // Starting a new chat starts it unbound, whatever document is open.\n update({\n threadTabs,\n activeThreadTabId: id,\n ...(conversationId === null ? { newChatDocumentId: null } : {}),\n })\n if (state.conversationId !== conversationId)\n update({ conversationId, cursor: null, editingMessageId: null })\n return id\n },\n closeThreadTab: (tabId) => {\n const threadTabs = state.threadTabs.filter((tab) => threadTabId(tab) !== tabId)\n if (threadTabs.length === state.threadTabs.length) return\n if (state.activeThreadTabId !== tabId) return update({ threadTabs })\n const next = threadTabs.at(-1)\n update({ threadTabs, activeThreadTabId: next ? threadTabId(next) : null })\n if (next && state.conversationId !== next.conversationId)\n update({ conversationId: next.conversationId, cursor: null, editingMessageId: null })\n },\n selectThreadTab: (tabId) => {\n if (tabId === null) {\n if (state.activeThreadTabId !== null) update({ activeThreadTabId: null })\n return\n }\n const tab = state.threadTabs.find((t) => threadTabId(t) === tabId)\n if (!tab) return\n update({ activeThreadTabId: tabId })\n if (state.conversationId !== tab.conversationId)\n update({ conversationId: tab.conversationId, cursor: null, editingMessageId: null })\n },\n setChatModelName: (chatModelName) => {\n if (state.chatModelName !== chatModelName) update({ chatModelName })\n },\n setNewConversationAssistantMode: (newConversationAssistantMode) => {\n if (state.newConversationAssistantMode !== newConversationAssistantMode)\n update({ newConversationAssistantMode })\n },\n setNewAgentChat: (newAgentChat) => {\n const current = state.newAgentChat\n if (\n current?.agentId !== newAgentChat?.agentId ||\n current?.workspaceId !== newAgentChat?.workspaceId\n )\n update({ newAgentChat })\n },\n setNewChatDocumentId: (newChatDocumentId) => {\n if (state.newChatDocumentId !== newChatDocumentId) update({ newChatDocumentId })\n },\n startEditing: (messageId, content) => {\n preEdit = { draft: selectDraft(state), cursor: state.cursor }\n update({ editingMessageId: messageId })\n setDraftOf(conversationKey(state), content)\n },\n cancelEditing: () => {\n if (!state.editingMessageId) return\n update({ editingMessageId: null, cursor: preEdit.cursor })\n setDraftOf(conversationKey(state), preEdit.draft)\n preEdit = { draft: '', cursor: null }\n },\n completeEditing: () => {\n preEdit = { draft: '', cursor: null }\n if (state.editingMessageId) update({ editingMessageId: null })\n },\n setDeepLinkMessageId: (deepLinkMessageId) => {\n if (state.deepLinkMessageId !== deepLinkMessageId) update({ deepLinkMessageId })\n },\n setActiveCitationKey: (activeCitationKey) => {\n if (state.activeCitationKey !== activeCitationKey) update({ activeCitationKey })\n },\n setPendingTools: (pendingTools) => update({ pendingTools }),\n setAutoSendDraft: (autoSendDraft) => {\n if (state.autoSendDraft !== autoSendDraft) update({ autoSendDraft })\n },\n setAgentChatOwner: (conversationId, agentId) =>\n update({ agentChatOwners: { ...state.agentChatOwners, [conversationId]: agentId } }),\n setMessageTimer: (key, timer) =>\n update({ messageTimers: { ...state.messageTimers, [key]: timer } }),\n clearMessageTimer: (key) => {\n if (!(key in state.messageTimers)) return\n const messageTimers = { ...state.messageTimers }\n delete messageTimers[key]\n update({ messageTimers })\n },\n setConversationError: (conversationId, error, lastFailedMessage) => {\n const current = state.generating[conversationId]\n update({\n generating: {\n ...state.generating,\n [conversationId]: {\n ...current,\n isGenerating: false,\n error,\n startTime: current?.startTime ?? null,\n lastFailedMessage: lastFailedMessage ?? current?.lastFailedMessage ?? null,\n },\n },\n })\n },\n clearConversationError: (conversationId) => {\n const current = state.generating[conversationId]\n update({\n generating: {\n ...state.generating,\n [conversationId]: {\n ...(current ?? { isGenerating: false, startTime: null }),\n error: null,\n lastFailedMessage: null,\n },\n },\n })\n },\n abortConversationGeneration: (conversationId) => {\n const current = state.generating[conversationId]\n current?.abortController?.abort()\n update({\n generating: {\n ...state.generating,\n [conversationId]: {\n ...(current ?? { error: null, startTime: null }),\n isGenerating: false,\n abortController: null,\n },\n },\n })\n },\n startNewConversation: () =>\n update({\n conversationId: null,\n cursor: null,\n editingMessageId: null,\n newChatDocumentId: null,\n }),\n setPaMode: (paMode) => {\n if (state.paMode !== paMode) update({ paMode })\n },\n setConversationDocuments: (conversationId, documents, autoAdd = false) =>\n update({\n conversationDocuments: { ...state.conversationDocuments, [conversationId]: documents },\n conversationDocumentAutoAdd: {\n ...state.conversationDocumentAutoAdd,\n [conversationId]: autoAdd,\n },\n }),\n }\n}\n","/**\n * The composers' drafts kept across reloads: stored locally and encrypted, sealed to the signed-in\n * person's own key like the other data kept on the device, so nothing typed is readable at rest.\n *\n * Bound to the person: a record is kept under the user it belongs to and opened only while that\n * user is signed in (`owner`), never by whoever's key happens to be on the device, so a signed-out\n * page, a demo session or another account never sees it. Like the offline mail, the drafts never\n * outlive the session: a sign-out clears them (`clearSealedDrafts`).\n */\n\nimport { getUserEncryptionKeypair, sealedBoxDecrypt, sealedBoxEncrypt } from '@arbidocs/client'\n\n/** Where a session store keeps its drafts (see `createArbiSessionStore`). */\nexport interface ArbiDraftStorage {\n /** The saved drafts, or null while they cannot be opened yet (no one is signed in). */\n load(): Promise<Record<string, string> | null>\n /** Save the drafts (all of them: the record replaces what was saved). */\n save(drafts: Readonly<Record<string, string>>): void\n /** Who the drafts belong to now: the signed-in user, `null` signed out. */\n owner(): string | null\n /** Forget the saved drafts and any write still pending (the session ended). */\n clear(): void\n /** Be told when the drafts were cleared (the session store drops its copy). */\n onClear(listener: () => void): () => void\n}\n\n/** A key-value store the drafts are written to (`localStorage` by default). */\nexport interface DraftKeyValueStore {\n getItem(key: string): string | null\n setItem(key: string, value: string): void\n removeItem(key: string): void\n}\n\n/** How long typing settles before the drafts are written. */\nconst SAVE_DELAY_MS = 500\n\nconst encoder = new TextEncoder()\nconst decoder = new TextDecoder()\n\n/** What is stored: the drafts sealed to the owner's key, and who the owner is. */\ninterface StoredDrafts {\n owner: string\n sealed: string\n}\n\nfunction parseStored(raw: string | null): StoredDrafts | null {\n if (!raw) return null\n try {\n const parsed = JSON.parse(raw) as Partial<StoredDrafts> | null\n return parsed && typeof parsed.owner === 'string' && typeof parsed.sealed === 'string'\n ? { owner: parsed.owner, sealed: parsed.sealed }\n : null\n } catch {\n return null\n }\n}\n\n/** Every sealed draft storage made on this page, so a sign-out clears them all. */\nconst storages = new Set<ArbiDraftStorage>()\n\n/** The session ended (sign-out, or it could not be recovered): clear every saved draft. */\nexport function clearSealedDrafts(): void {\n for (const storage of [...storages]) storage.clear()\n}\n\nexport interface SealedDraftStorageOptions {\n /** The record's key in `storage`. */\n key?: string\n storage?: DraftKeyValueStore\n /**\n * The signed-in user (a stable id, e.g. the user's external id), `null` when no one is: the\n * drafts are opened and written only for them.\n */\n owner: () => string | null\n}\n\n/**\n * Drafts sealed to the signed-in person's key, in `storage` under `key`, for `owner` only. A record\n * of another user is removed unread; one that cannot be opened (damaged) reads as no drafts.\n */\nexport function createSealedDraftStorage({\n key = 'arbi-drafts',\n storage = typeof localStorage === 'undefined' ? undefined : localStorage,\n owner,\n}: SealedDraftStorageOptions): ArbiDraftStorage {\n let timer: ReturnType<typeof setTimeout> | undefined\n // Bumped by clear(): a write that started before it never lands after it.\n let generation = 0\n const listeners = new Set<() => void>()\n\n const remove = () => {\n try {\n storage?.removeItem(key)\n } catch {\n // Storage blocked: nothing was kept either.\n }\n }\n\n const write = async (drafts: Readonly<Record<string, string>>, written: number) => {\n if (!storage) return\n try {\n const user = owner()\n if (!user) return\n if (Object.keys(drafts).length === 0) {\n if (parseStored(storage.getItem(key))?.owner === user) storage.removeItem(key)\n return\n }\n const keypair = await getUserEncryptionKeypair()\n if (!keypair || written !== generation || owner() !== user) return\n // A plain Uint8Array of this realm, which is what the sealing accepts.\n const plain = Uint8Array.from(encoder.encode(JSON.stringify(drafts)))\n const record: StoredDrafts = {\n owner: user,\n sealed: sealedBoxEncrypt(plain, keypair.publicKey),\n }\n storage.setItem(key, JSON.stringify(record))\n } catch {\n // Storage full or blocked: the drafts stay in memory for this visit.\n }\n }\n\n const draftStorage: ArbiDraftStorage = {\n owner,\n load: async () => {\n const user = owner()\n if (!user) return null\n const keypair = await getUserEncryptionKeypair()\n if (!keypair || owner() !== user) return null\n try {\n const raw = storage?.getItem(key) ?? null\n if (!raw) return {}\n const stored = parseStored(raw)\n if (!stored || stored.owner !== user) {\n // Another user's (or an unreadable) record is not this person's to keep or open.\n remove()\n return {}\n }\n const plain = sealedBoxDecrypt(stored.sealed, keypair.secretKey)\n const drafts = JSON.parse(decoder.decode(plain)) as unknown\n if (!drafts || typeof drafts !== 'object') return {}\n return Object.fromEntries(\n Object.entries(drafts).filter((entry): entry is [string, string] => {\n return typeof entry[1] === 'string'\n })\n )\n } catch {\n return {}\n }\n },\n save: (drafts) => {\n clearTimeout(timer)\n const written = generation\n timer = setTimeout(() => void write(drafts, written), SAVE_DELAY_MS)\n },\n clear: () => {\n clearTimeout(timer)\n timer = undefined\n generation++\n remove()\n for (const listener of [...listeners]) listener()\n },\n onClear: (listener) => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n }\n storages.add(draftStorage)\n return draftStorage\n}\n","/**\n * The session state the blocks share (see `./store`). A host passes its own {@link ArbiSessionStore}\n * as the host configuration's `session` (ARBI-frontend backs it with its zustand store). Without\n * one, each top-level `<ArbiHost>` keeps an in-memory one, and blocks rendered with no host share a\n * module default, so a standalone block still coordinates with its siblings. A host's own store\n * keeps the composers' drafts across reloads, sealed to the person signed in on the host's `Arbi`\n * and only for them; the module default (no host, so no one signed in) keeps them in memory.\n */\n\nimport { useSyncExternalStore } from 'react'\nimport { useArbiHost, type ArbiHostConfig } from '../host/config'\nimport { OWN_SESSION_SLOT } from '../host/merge'\nimport { createArbiSessionStore, type ArbiSessionState, type ArbiSessionStore } from './store'\nimport { createSealedDraftStorage } from './drafts'\n\n/** Who is signed in on the host's `Arbi` (its session), `null` when no one is. */\nfunction signedInUser(host: ArbiHostConfig): string | null {\n const state = host.arbi?.session?.getState()\n return state?.signedIn && state.userExtId ? state.userExtId : null\n}\n\n/** A host's own session: in memory, with its drafts kept sealed for the signed-in person. */\nconst createOwnStore = (host: ArbiHostConfig) =>\n createArbiSessionStore(\n {},\n { draftStorage: createSealedDraftStorage({ owner: () => signedInUser(host) }) }\n )\n\nlet moduleDefault: ArbiSessionStore | null = null\nconst defaultStore = () => (moduleDefault ??= createArbiSessionStore())\n\n/** The session store: its setters, and `getState()` for the state as of now (in callbacks). */\nexport function useArbiSessionStore(): ArbiSessionStore {\n const host = useArbiHost()\n if (host.session) return host.session\n const own = (host as Record<string, unknown>)[OWN_SESSION_SLOT] as\n { current: ArbiSessionStore | null } | undefined\n if (own) return (own.current ??= createOwnStore(host))\n return defaultStore()\n}\n\n/**\n * A slice of the session state; re-renders when it changes. The selector returns a value from the\n * state or a primitive (a new object each call would never settle).\n */\nexport function useArbiSessionState<T>(selector: (state: ArbiSessionState) => T): T {\n const store = useArbiSessionStore()\n const select = () => selector(store.getState())\n return useSyncExternalStore(store.subscribe, select, select)\n}\n","/**\n * Who is signed in: the host `Arbi`'s session (`arbi.session`, the client's session state), the\n * one source for the user, the sign-in status and the SSO mode. Re-renders when it changes.\n */\n\nimport { useMemo, useSyncExternalStore } from 'react'\nimport type { SessionManager, SessionState, SessionUser } from '@arbidocs/client'\nimport { useArbiHost } from '../host/config'\n\nexport type ArbiSessionStatus = 'signed-out' | 'signed-in'\n\nexport interface ArbiSignedInSession {\n /** `signed-in` once a login finished on this device (also before this tab has a token). */\n status: ArbiSessionStatus\n /** The signed-in user; `null` signed out. */\n user: SessionUser | null\n /** The account signs in through SSO. */\n isSso: boolean\n /** This tab holds a server session (a token). A new tab or an offline unlock does not, yet. */\n hasToken: boolean\n /** The server session key workspace keys are sealed to; `null` until known. */\n serverSessionKey: Uint8Array | null\n}\n\nconst SIGNED_OUT: ArbiSignedInSession = {\n status: 'signed-out',\n user: null,\n isSso: false,\n hasToken: false,\n serverSessionKey: null,\n}\n\nconst noSubscription = () => () => {}\n\n/** The signed-in session of the host's `Arbi`; signed out without one. */\nexport function useArbiSession(): ArbiSignedInSession {\n return useSignedInSession(useArbiHost().arbi?.session ?? null)\n}\n\n/** The same for a session the caller holds (the host building its `Arbi` on it). */\nexport function useSignedInSession(session: SessionManager | null): ArbiSignedInSession {\n const state = useSyncExternalStore<SessionState | null>(\n session ? session.subscribe : noSubscription,\n () => session?.getState() ?? null,\n () => session?.getState() ?? null\n )\n return useMemo(\n () =>\n state?.signedIn\n ? {\n status: 'signed-in',\n user: state.user,\n isSso: state.isSsoMode,\n hasToken: !!state.accessToken,\n serverSessionKey: state.serverSessionKey,\n }\n : { ...SIGNED_OUT, isSso: state?.isSsoMode ?? false },\n [state]\n )\n}\n","/**\n * AI usage is reported in pounds (ex VAT).\n *\n * The usage endpoints (`/v1/user/projects/{id}/usage`, `/me/usage/today`) convert the metered\n * LiteLLM USD spend into £ at the API boundary (fractional, rounded to 2 decimals). The fields are\n * still named `spend` / `total_spend` in the schema, but they hold £, never dollars. Format them\n * with `formatGbp` (re-exported from `@arbidocs/sdk`).\n */\n\n/** The slice of a usage response that tells whether anything was recorded. */\nexport interface UsageTotals {\n total_spend: number\n total_tokens: number\n total_requests: number\n}\n\n/**\n * Was this usage actually metered? A `dev`-plan project with an all-zero response (no spend, no\n * tokens, no requests) is treated as \"not metered\", so the UI shows a note instead of silent\n * zeros. Any recorded tokens or requests mean usage was metered, even when the spend rounds to 0\n * (the backend records usage when billing is off, and a tiny spend can be £0.00).\n */\nexport function isUsageMetered(\n usage: UsageTotals,\n subscription: string | null | undefined\n): boolean {\n const empty = usage.total_spend === 0 && usage.total_tokens === 0 && usage.total_requests === 0\n return !(empty && subscription === 'dev')\n}\n","/**\n * React Query hooks that use the Arbi instance from context.\n */\n\nimport { useEffect, useMemo, useRef } from 'react'\nimport {\n useInfiniteQuery,\n useQuery,\n useQueries,\n useMutation,\n useQueryClient,\n} from '@tanstack/react-query'\nimport {\n ArbiApiError,\n type AskHandlers,\n type AskRequest,\n type SSEStreamResult,\n type TagListQuery,\n type ThreadsResponse,\n} from '@arbidocs/sdk/browser'\nimport { useArbi } from './useArbi'\nimport { useArbiSessionStore } from './session'\nimport type { ParsedDocument } from './documents/parsed-types'\nimport { isUsageMetered } from './usage-metered'\nimport { parseVersionRef } from './artifacts/versions'\n\n// ── Query keys ──────────────────────────────────────────────────────────────\n\n// The one key factory (every query and mutation key of the packages and the app): ./query-keys.\nexport { arbiQueryKeys, arbiMutationKeys } from './query-keys'\nimport { arbiQueryKeys } from './query-keys'\n\n// ── Hooks ───────────────────────────────────────────────────────────────────\n\n/** List the logged-in user's workspaces. */\nexport function useWorkspaces(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.workspaces(),\n queryFn: () => arbi.workspaces.list(),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n })\n}\n\n/** Every version of the document `docId`, oldest first (`is_current` marks the current one). */\nexport function useDocumentVersionList(\n docId: string | null | undefined,\n options?: { enabled?: boolean }\n) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.documentVersions(docId ?? ''),\n queryFn: () => arbi.documents.versions(docId as string),\n enabled: (options?.enabled ?? true) && !!docId && arbi.hasWorkspace,\n })\n}\n\n/**\n * A workspace's conversations (threads and tasks). The list is kept current by its writers and the\n * workspace's events (`conversation-list`), so it is not re-read on every mount; `live` re-reads it\n * on a timer instead, faster while something is generating, for a view that follows runs by itself.\n */\nexport function useConversations(\n workspaceId: string | undefined,\n options?: { enabled?: boolean; live?: boolean }\n) {\n const arbi = useArbi()\n const live = options?.live === true\n return useQuery({\n queryKey: arbiQueryKeys.conversations(workspaceId ?? ''),\n queryFn: () => arbi.readInWorkspace(workspaceId as string, () => arbi.conversations.list()),\n enabled: (options?.enabled ?? true) && !!workspaceId && arbi.hasWorkspace,\n placeholderData: (previous) => previous,\n ...(live\n ? {\n refetchInterval: (query: { state: { data?: Array<{ status?: string | null }> } }) =>\n query.state.data?.some((conversation) => conversation.status === 'generating')\n ? 3000\n : 15000,\n }\n : { staleTime: Infinity, refetchOnMount: false, refetchOnReconnect: false }),\n })\n}\n\n/** The backend's built-in slash commands (`/compact`, `/goal`, …), for a slash menu. */\nexport function useBuiltinCommands() {\n const arbi = useArbi()\n const query = useQuery({\n queryKey: arbiQueryKeys.assistantCommands(),\n queryFn: () => arbi.assistant.commands(),\n staleTime: 30 * 1000,\n enabled: arbi.isLoggedIn,\n })\n // Stable identity so a menu's merge and filter memos do not rerun every render.\n const commands = useMemo(() => query.data ?? [], [query.data])\n return { commands, isLoading: query.isLoading }\n}\n\n/** One stored message with everything the server keeps on it (its trace and metadata). */\nexport function useMessageDetails(\n messageId: string | null | undefined,\n options?: { enabled?: boolean }\n) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.messageDetails(messageId ?? ''),\n queryFn: () => arbi.conversations.getMessage(messageId as string),\n enabled: (options?.enabled ?? true) && !!messageId && arbi.isLoggedIn,\n })\n}\n\n/**\n * A conversation's stored threads (each with its message history, citations data included). The\n * chat engine and the conversation's events keep the cache current, so it is re-read only when\n * stale (2 minutes) or when the page is shown again while this tab is not streaming the\n * conversation (a turn sent from another tab never reaches this one's socket). A conversation with\n * no messages yet (a new to-do, a workflow's task before its run) has no threads: the server's 404\n * is an empty conversation to write into. `live` re-reads it every few seconds.\n */\nexport function useConversationThreads(\n conversationId: string | undefined,\n options?: { enabled?: boolean; live?: boolean }\n) {\n const arbi = useArbi()\n const session = useArbiSessionStore()\n return useQuery({\n queryKey: arbiQueryKeys.conversationThreads(conversationId ?? ''),\n queryFn: async (): Promise<ThreadsResponse> => {\n try {\n return await arbi.conversations.getThreads(conversationId as string)\n } catch (error) {\n if (error instanceof ArbiApiError && error.status === 404) {\n return { conversation_ext_id: conversationId, threads: [] } as unknown as ThreadsResponse\n }\n throw error\n }\n },\n enabled: (options?.enabled ?? true) && !!conversationId && arbi.hasWorkspace,\n staleTime: 2 * 60 * 1000,\n refetchOnWindowFocus: () =>\n session.getState().generating[conversationId ?? '']?.isGenerating ? false : 'always',\n refetchInterval: options?.live ? 3000 : false,\n })\n}\n\n/** A tag list query as a stable cache key ('' for every tag). */\nconst tagListKey = (query: TagListQuery): string =>\n [\n query.kind ? `kind:${query.kind}` : '',\n query.parentId ? `parent:${query.parentId}` : '',\n query.ids?.length ? `ids:${query.ids.join(',')}` : '',\n query.include?.length ? `include:${query.include.join(',')}` : '',\n query.linksLimit !== undefined ? `links:${query.linksLimit}` : '',\n ]\n .filter(Boolean)\n .join('|')\n\n/**\n * List tags in a workspace (default: the open one) — all of them, or filtered: `{ kind: 'issue',\n * include: ['links'] }` is every issue with its documents, facts and threads (a table's rows; its\n * columns come from `useTagKindSchema`). `ids: []` asks for nothing.\n *\n * The whole list is read once and then kept current in place: the tag writes patch it\n * (`patchWorkspaceTags`), and an invalidation of the workspace's tags (a WebSocket event, a host\n * refresh) re-reads it. It is never re-read just for being mounted or the window being focused.\n */\nexport function useTags(\n workspaceId?: string | null,\n options?: TagListQuery & { enabled?: boolean }\n) {\n const arbi = useArbi()\n const { enabled, ...query } = options ?? {}\n const workspace = workspaceId ?? (arbi.hasWorkspace ? arbi.getWorkspaceId() : '')\n const key = tagListKey(query)\n return useQuery({\n queryKey: key ? arbiQueryKeys.tagList(workspace, key) : arbiQueryKeys.tags(workspace),\n queryFn: () => arbi.readInWorkspace(workspace, () => arbi.tags.list(key ? query : undefined)),\n enabled:\n (enabled ?? true) &&\n !!workspace &&\n arbi.hasWorkspace &&\n (query.ids === undefined || query.ids.length > 0),\n ...(key ? {} : { staleTime: Infinity }),\n })\n}\n\n/**\n * Batch-fetch first-page thumbnails for a set of documents. Returns a map of\n * doc external id → `data:image/webp` URI (or `null` when no thumbnail exists).\n * Cached for a few minutes since thumbnails are effectively immutable per doc.\n */\nexport function useThumbnails(docIds: string[], options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.thumbnails(docIds),\n queryFn: () => arbi.documents.getThumbnails(docIds),\n enabled: (options?.enabled ?? true) && docIds.length > 0 && arbi.hasWorkspace,\n staleTime: 5 * 60_000,\n })\n}\n\n/**\n * Fetch a document's parsed content (chunks grouped by page) for the review\n * viewer. `stage` defaults to `final` (fully processed); `marker`/`subchunk`\n * expose earlier pipeline stages. `docId` may be a version reference (`doc-…@v2`).\n */\nexport function useParsedDocument(\n docId: string | undefined,\n stage: string = 'final',\n options?: { enabled?: boolean }\n) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.parsedDoc(docId ?? '', stage),\n queryFn: () => {\n // A version reference (`doc-…@v2`) reads that version's parse.\n const { docId: id, version } = parseVersionRef(docId as string)\n return arbi.documents.getParsedContent(\n id,\n stage,\n version ?? undefined\n ) as unknown as Promise<ParsedDocument>\n },\n enabled: (options?.enabled ?? true) && !!docId && arbi.hasWorkspace,\n })\n}\n\n/**\n * Ask the assistant (`arbi.assistant.ask`) as a mutation: one streaming turn, its frames to\n * `handlers`, resolving with the accumulated result.\n */\nexport function useAssistantQuery() {\n const arbi = useArbi()\n return useMutation<SSEStreamResult, Error, { request: AskRequest; handlers?: AskHandlers }>({\n mutationFn: ({ request, handlers }) => arbi.assistant.ask(request, handlers),\n })\n}\n\n/** List agents owned by the current user. */\nexport function useAgents(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.agents(),\n queryFn: () => arbi.agents.list(),\n enabled: (options?.enabled ?? true) && arbi.isLoggedIn,\n })\n}\n\n/**\n * Delete agents. Returns a mutation. Refreshes the agent list, the workflow list and the conversation list\n * (a deleted agent's workflows and work go with it), and drops the deleted agents' own config and workspace queries.\n */\nexport function useDeleteAgents() {\n const arbi = useArbi()\n const qc = useQueryClient()\n return useMutation<unknown, Error, { agentExtIds: string[] }>({\n mutationFn: ({ agentExtIds }) => arbi.agents.delete(agentExtIds),\n onSuccess: (_result, { agentExtIds }) => {\n for (const id of agentExtIds) {\n qc.removeQueries({ queryKey: arbiQueryKeys.agentConfig(id) })\n qc.removeQueries({ queryKey: arbiQueryKeys.agentWorkspaces(id) })\n }\n return Promise.all([\n qc.invalidateQueries({ queryKey: arbiQueryKeys.agents() }),\n qc.invalidateQueries({ queryKey: arbiQueryKeys.workflows() }),\n qc.invalidateQueries({ queryKey: arbiQueryKeys.allConversations() }),\n qc.invalidateQueries({ queryKey: arbiQueryKeys.configs() }),\n ])\n },\n })\n}\n\n/** Authorize a delegated session (generates claim code). Returns a mutation. */\n\n/** Check backend health. */\nexport function useHealth(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.health(),\n queryFn: () => arbi.health.check(),\n enabled: options?.enabled,\n })\n}\n\n/**\n * The deployment's models with their tags (`Standard`, `Premium`), providers and per-token costs,\n * and the default premium model. Static per deployment: read once.\n */\nexport function useAvailableModels(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.availableModels(),\n queryFn: () => arbi.health.models(),\n staleTime: Infinity,\n enabled: (options?.enabled ?? true) && arbi.isLoggedIn,\n })\n}\n\n// ── Behaviour-template configs ───────────────────────────────────────────────\n\n/** List the caller's saved agent configurations (behaviour templates). */\nexport function useConfigs(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.configVersions(),\n queryFn: () => arbi.agentConfig.list(),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n })\n}\n\n/** One saved agent configuration (its models, its tools). Configs change only on a save. */\nexport function useConfig(configId: string | null | undefined, options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.config(configId ?? ''),\n queryFn: () => arbi.agentConfig.get(configId as string),\n staleTime: 10 * 60 * 1000,\n enabled: (options?.enabled ?? true) && !!configId && arbi.isLoggedIn,\n })\n}\n\n// ── Activity feed ─────────────────────────────────────────────────────────────\n\n/**\n * List the caller's durable activity feed, newest first.\n *\n * Activity entries are backend-originated, to-self log lines that are always\n * read — they are deliberately kept out of the normal notifications/DM feed and\n * never affect the unread badge, so this is a separate, opt-in query.\n */\nexport function useActivity(options?: { enabled?: boolean; limit?: number; offset?: number }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.activity(),\n queryFn: () => arbi.dm.listActivity({ limit: options?.limit, offset: options?.offset }),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n })\n}\n\n/**\n * A workspace's activity feed, newest first, a page at a time: thread history, people posting,\n * uploads, new versions and signatures, workflow runs. Only what the caller can see. The pages\n * are `data.pages`; `fetchNextPage` reads the next one while `hasNextPage`.\n */\nexport function useWorkspaceActivity(\n workspaceId: string | null | undefined,\n options?: {\n enabled?: boolean\n limit?: number\n /** Runs before each page, e.g. to (re)open the workspace so titles and names decrypt. */\n beforeFetch?: () => Promise<unknown>\n }\n) {\n const arbi = useArbi()\n return useInfiniteQuery({\n queryKey: arbiQueryKeys.workspaceActivity(workspaceId ?? ''),\n queryFn: async ({ pageParam }) => {\n await options?.beforeFetch?.()\n return arbi.workspaces.activity(workspaceId as string, {\n cursor: pageParam,\n limit: options?.limit,\n })\n },\n initialPageParam: null as string | null,\n getNextPageParam: (page) => page.next_cursor ?? undefined,\n enabled: (options?.enabled ?? true) && !!workspaceId && arbi.isLoggedIn,\n })\n}\n\n// ── Projects, usage & spend ───────────────────────────────────────────────────\n\n/** List the logged-in user's projects (billing accounts). */\nexport function useProjects(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.projects(),\n queryFn: () => arbi.projects.list(),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n })\n}\n\n/**\n * AI usage breakdown for a project's billing period. `monthsBack` selects the period (0 =\n * current, 1 = previous month, …).\n *\n * The response's `total_spend` / `spend` fields are £ of AI usage (format with `formatGbp`).\n * `metered` is `false` when the deployment does not record usage (a `dev`-plan project with all\n * zeros): show \"usage is not metered here\" instead of zeros. It is `undefined` until the usage\n * has loaded.\n */\nexport function useProjectUsage(\n projectExtId: string | undefined,\n monthsBack: number = 0,\n options?: { enabled?: boolean }\n) {\n const arbi = useArbi()\n const usage = useQuery({\n queryKey: arbiQueryKeys.projectUsage(projectExtId ?? '', monthsBack),\n queryFn: () => arbi.projects.usage(projectExtId as string, monthsBack),\n enabled: (options?.enabled ?? true) && !!projectExtId && arbi.isLoggedIn,\n })\n const projects = useProjects({ enabled: !!projectExtId && (options?.enabled ?? true) })\n const subscription = projects.data?.find((p) => p.external_id === projectExtId)?.subscription\n const metered = usage.data ? isUsageMetered(usage.data, subscription) : undefined\n return { ...usage, metered }\n}\n\n/** One day of aggregated usage across projects (for a spend/token trend). */\nexport interface AggregatedDailyUsage {\n date: string\n /** £ of AI usage that day. */\n gbp: number\n totalTokens: number\n apiRequests: number\n}\n\n/** One model group's aggregated usage across projects (for a breakdown). */\nexport interface AggregatedModelGroupUsage {\n model: string\n /** £ of AI usage by this model group. */\n gbp: number\n totalTokens: number\n promptTokens: number\n completionTokens: number\n successfulRequests: number\n}\n\n/** Aggregated AI usage + spend across several projects. */\nexport interface ProjectsUsageAggregate {\n /** Summed usage across the projects, in £ (ex VAT). */\n totalGbp: number\n /** Summed token count across the projects. */\n totalTokens: number\n /** Summed API request count across the projects. */\n totalRequests: number\n /** Per-day totals merged across every project, oldest first. */\n daily: AggregatedDailyUsage[]\n /** Per-model-group totals merged across every project, most £ first. */\n modelGroups: AggregatedModelGroupUsage[]\n /**\n * False when none of the loaded projects records usage (billing is off on this deployment), so\n * zeros mean \"not metered\". True while anything real was recorded, or before data arrived.\n */\n metered: boolean\n /** True while any per-project query is still loading. */\n isLoading: boolean\n /** True if any per-project query errored. */\n isError: boolean\n}\n\n/**\n * Firm-wide AI usage + spend: aggregates {@link useProjectUsage} across several\n * projects (e.g. all of a firm's matters) in parallel and merges the real totals,\n * the daily trend, and the per-model breakdown. Shares the per-project query\n * cache, so it costs nothing extra where a project's usage is already loaded.\n * Numbers are genuine — zero projects (or zero billed work) yields zero totals;\n * callers render that honestly.\n */\nexport function useProjectsUsage(\n projectExtIds: string[],\n monthsBack: number = 0,\n options?: { enabled?: boolean }\n): ProjectsUsageAggregate {\n const arbi = useArbi()\n const enabled = (options?.enabled ?? true) && arbi.isLoggedIn\n const projects = useProjects({ enabled: enabled && projectExtIds.length > 0 })\n const results = useQueries({\n queries: projectExtIds.map((id) => ({\n queryKey: arbiQueryKeys.projectUsage(id, monthsBack),\n queryFn: () => arbi.projects.usage(id, monthsBack),\n enabled: enabled && !!id,\n })),\n })\n\n // Recompute only when a query's data actually changes (not on every parent\n // render — the dashboard re-renders often while a digest streams).\n const signature =\n results.map((r) => `${r.status}:${r.dataUpdatedAt ?? 0}`).join('|') +\n `#${projects.dataUpdatedAt}`\n\n return useMemo(() => {\n const dailyMap = new Map<string, AggregatedDailyUsage>()\n const modelMap = new Map<string, AggregatedModelGroupUsage>()\n let totalGbp = 0\n let anyData = false\n let anyMetered = false\n let totalTokens = 0\n let totalRequests = 0\n\n results.forEach((r, i) => {\n const d = r.data\n if (!d) return\n anyData = true\n const subscription = projects.data?.find(\n (p) => p.external_id === projectExtIds[i]\n )?.subscription\n if (isUsageMetered(d, subscription)) anyMetered = true\n totalGbp += d.total_spend ?? 0\n totalTokens += d.total_tokens ?? 0\n totalRequests += d.total_requests ?? 0\n\n for (const day of d.daily ?? []) {\n const cur = dailyMap.get(day.date) ?? {\n date: day.date,\n gbp: 0,\n totalTokens: 0,\n apiRequests: 0,\n }\n cur.gbp += day.spend ?? 0\n cur.totalTokens += day.total_tokens ?? 0\n cur.apiRequests += day.api_requests ?? 0\n dailyMap.set(day.date, cur)\n }\n\n for (const [model, mg] of Object.entries(d.model_groups ?? {})) {\n const cur = modelMap.get(model) ?? {\n model,\n gbp: 0,\n totalTokens: 0,\n promptTokens: 0,\n completionTokens: 0,\n successfulRequests: 0,\n }\n cur.gbp += mg.spend ?? 0\n cur.totalTokens += mg.total_tokens ?? 0\n cur.promptTokens += mg.prompt_tokens ?? 0\n cur.completionTokens += mg.completion_tokens ?? 0\n cur.successfulRequests += mg.successful_requests ?? 0\n modelMap.set(model, cur)\n }\n })\n\n return {\n totalGbp,\n totalTokens,\n totalRequests,\n daily: [...dailyMap.values()].sort((a, b) => a.date.localeCompare(b.date)),\n modelGroups: [...modelMap.values()].sort(\n (a, b) => b.gbp - a.gbp || b.totalTokens - a.totalTokens\n ),\n metered: !anyData || anyMetered,\n isLoading: results.some((r) => r.isLoading),\n isError: results.some((r) => r.isError),\n }\n }, [signature])\n}\n\n/** List the Stripe invoices for a project's subscription. */\nexport function useProjectInvoices(\n projectExtId: string | undefined,\n options?: { enabled?: boolean }\n) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.projectInvoices(projectExtId ?? ''),\n queryFn: () => arbi.projects.invoices(projectExtId as string),\n enabled: (options?.enabled ?? true) && !!projectExtId && arbi.isLoggedIn,\n })\n}\n\n/**\n * The signed-in user from `GET /v1/user/me`. Refetched on window focus, so a role granted or\n * removed elsewhere shows up without a reload; invalidate `arbiQueryKeys.currentUser()` after a\n * change you made yourself.\n */\nexport function useCurrentUser(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.currentUser(),\n queryFn: () => arbi.user.me(),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n refetchOnWindowFocus: true,\n staleTime: 30_000,\n })\n}\n\n/**\n * The firm's pooled monthly £ of AI usage (Box deployments). A 403 (the caller is not a firm member\n * or Box admin) is not retried: treat an error like `has_pool: false` and show nothing.\n */\nexport function useFirmPool(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.firmPool(),\n queryFn: () => arbi.firm.pool(),\n enabled: options?.enabled ?? arbi.isLoggedIn,\n retry: false,\n refetchOnWindowFocus: true,\n staleTime: 60_000,\n })\n}\n\n/** Buy add-ons for the firm (Box admins). Refreshes the pool; the result may carry an invoice URL. */\nexport function useTopUpFirmPool() {\n const arbi = useArbi()\n const queryClient = useQueryClient()\n return useMutation({\n mutationFn: (aiAddons: number) => arbi.firm.topUp(aiAddons),\n onSuccess: (result) => {\n queryClient.setQueryData(arbiQueryKeys.firmPool(), result.pool)\n },\n })\n}\n\n/** Why \"New project\" / \"New workspace\" is unavailable to someone who may not create them. */\nexport const PROJECT_CREATION_DENIED_REASON =\n 'Only members of your firm can create projects and workspaces.'\n\n/**\n * Whether the signed-in user may create projects and workspaces. `undefined` while the user is\n * loading: callers should neither offer nor refuse creation until it is known.\n */\nexport function useCanCreateProjects(): boolean | undefined {\n const user = useCurrentUser()\n // A role granted or removed in a workspace can change it: re-read when the memberships do.\n const { data: workspaces } = useWorkspaces({ enabled: user.isSuccess })\n const membership = workspaces?.map((w) => w.external_id).join(',')\n const { refetch } = user\n const seen = useRef<string | undefined>(undefined)\n useEffect(() => {\n if (membership === undefined || membership === seen.current) return\n const first = seen.current === undefined\n seen.current = membership\n if (!first) void refetch()\n }, [membership, refetch])\n return user.data?.can_create_projects\n}\n\n/**\n * Today's deployment-wide AI usage (£, `used_gbp`) for the signed-in user: pair it with a project's\n * `daily_cap_per_user` for a \"£ used today\" indicator. Re-read on mount and window focus, and when\n * the host invalidates it after the user's own generation; never polled.\n */\nexport function useUserUsageToday(options?: { enabled?: boolean }) {\n const arbi = useArbi()\n return useQuery({\n queryKey: arbiQueryKeys.userUsageToday(),\n queryFn: () => arbi.user.usageToday(),\n enabled: (options?.enabled ?? true) && arbi.isLoggedIn,\n refetchOnWindowFocus: true,\n refetchOnMount: 'always',\n staleTime: 15_000,\n })\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { clearSealedDrafts, useWorkspaces } from './chunk-5DI27KJG.js';
1
+ import { clearSealedDrafts, useWorkspaces } from './chunk-X2OC2LCD.js';
2
2
  import { arbiQueryKeys, callQueryKeys } from './chunk-NVAIVJID.js';
3
3
  import { notify } from './chunk-5HDC43MF.js';
4
4
  import { getUserDisplayName, DEFAULT_SEGMENTER_CONFIG, INITIAL_SEGMENTER_STATE, flushSegmenter, stepSegmenter, levelFromRms } from './chunk-APZZQZ6P.js';
@@ -2358,5 +2358,5 @@ function useOpenCallMeetingChat() {
2358
2358
  }
2359
2359
 
2360
2360
  export { AUDIENCE_CHOICES, ArbiWsContext, CALL_CAPTION_TOPIC, CALL_CHAT_MAX_CHARS, CALL_CHAT_TOPIC, CALL_MODERATION_TOPIC, CALL_RECORDING_TOPIC, CALL_TRANSCRIPTION_TOPIC, CALL_WEBINAR_TOPIC, CAPTION_MAX_CHARS, COMPOSITE_AUDIO_BITS_PER_SECOND, COMPOSITE_VIDEO_BITS_PER_SECOND, DEFAULT_JOIN_CHOICES, EMPTY_CALL_SESSION, EXPORT_SAMPLE_RATE, HISTORY_LIMIT, LIVE_SEGMENTER, MAX_AVATAR_FILE_BYTES, MUTED_DEDUPE_MS, PLAYBACK_LOOKAHEAD_MS, READ_ONLY_MEETING_TEXT, RECORDING_CHUNK_MS, RECORDING_SEGMENTER, SEGMENT_FRAME_MS, SEGMENT_ID_PATTERN, SEGMENT_PRE_ROLL_MS, SHORT_PIECE_MERGE_GAP_MS, SPEAKER_AUDIO_BITS_PER_SECOND, TrackUploader, UPLOAD_ATTEMPTS, UPLOAD_BACKOFF_MS, acceptRing, addConversationToList, appendToThread, applyAgentDmStatus, applyCallEvent, applyChatEvent, applyChatMessage, applyChatRead, applyChatUpdated, arbiAccountClient, buildMeetingChatBody, cachedChat, cachedChats, callLink, callMemberKeys, callSession, chatByExtId, chatHasLiveCall, chatLiveCallId, chatTranscriptRef, clearMeetingChatCache, clearTrackUploaders, clockTime, compositeFiles, compositeTrack, conversationKeyForCall, createMutedNotifier, createTrackCutter, cutAtPauses, declineRing, decodeCallChatPacket, decodeCaptionPacket, decodeMono16k, decryptPart, deleteChatMessage, dropFromThread, encodeCallChatPacket, encodeCaptionPacket, encodeWav, encryptPart, ensureMeetingChat, entitlementRefusal, extensionFor, fetchPart, fileSafe, findConversation, floatToWav, formatTranscriptMarkdown, getOpenChat, hasRecordingTranscript, invalidateCall, invalidateConversationDetails, invalidateConversationLists, isConversationListKey, isConversationShared, isKnownSoloConversation, isRecordingOver, isRecordingSegmentId, isRetryable, isWorkspaceGuestOf, joinFromPreJoin, knownMeetingChat, loadMeetingHistory, markRejoining, meetingChatRefFrom, meetingRefForCall, mergeChatLines, mutedNoticeFromEvent, mutedNoticeFromPacket, mutedNoticeText, myChatId, newPacketId, newSegmentId, newTrackKey, nextSeqAfter, onCallEvent, openCall, openQuestion, openRecording, parseWebinarPacket, partKey, partOffsetMs, partsDue, patchConversation, patchConversationList, persistMeetingMessage, persistTranscriptSegment, playheadAt, postRecordingDocsToThread, postTranscriptToThread, recordingFiles, recordingWindowsOf, rejoinAsAudience, removeChat, removeConversationFromLists, resetCallSession, resolveMeetingChat, saveRecordingFilesToThread, schedulePart, sealQuestionText, setOpenChat, sortTranscriptMessages, sortedParts, speakerTracks, speakerWav, splitIntoFiles, standalone, startChatCall, startContactsCall, startDmCall, startThreadCall, startsMediaFile, storeTranscriptSegment, stripSpeakerPrefix, supersedeLiveTranscript, supersededTranscriptLines, threadHasLiveCall, threadLiveCallId, threadTranscriptLines, threadTranscriptRef, threadTranscriptText, timelineDurationMs, timelineOf, toProfileView, trackUploaderFor, transcribeRecording, transcriptPersistRole, transcriptSegmentOf, unwrapTrackKey, upsertChat, useAccountClient, useArbiWsContext, useAvatarCrop, useCall, useCallInviteLinks, useCallLiveUpdates, useCallRecording, useCallRecordings, useCallSession, useCallTranscriptionAvailable, useCallsConfig, useCallsEnabled, useCanHostCalls, useEntitlements, useIsEntitled, useMeetingReadOnly, useNameEditor, useOpenCallMeetingChat, useProfile, useRecordingActions, useRecordingWindows, useRevokeCallInviteLink, useSaveToThread, useServerCallsEnabled, useUpdateProfile, wrapTrackKey, writeSamples };
2361
- //# sourceMappingURL=chunk-BF5ASP3L.js.map
2362
- //# sourceMappingURL=chunk-BF5ASP3L.js.map
2361
+ //# sourceMappingURL=chunk-Y3LBWRXS.js.map
2362
+ //# sourceMappingURL=chunk-Y3LBWRXS.js.map