@arbidocs/react 0.4.146 → 0.4.150

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 (48) hide show
  1. package/dist/artifacts/index.cjs +17 -7
  2. package/dist/artifacts/index.cjs.map +1 -1
  3. package/dist/artifacts/index.d.cts +7 -1
  4. package/dist/artifacts/index.d.ts +7 -1
  5. package/dist/artifacts/index.js +11 -2
  6. package/dist/artifacts/index.js.map +1 -1
  7. package/dist/{chunk-MFMJHBJR.js → chunk-3XYIQZTH.js} +52 -3
  8. package/dist/chunk-3XYIQZTH.js.map +1 -0
  9. package/dist/{chunk-YIFUMQGA.cjs → chunk-IQIDM3KM.cjs} +10 -16
  10. package/dist/chunk-IQIDM3KM.cjs.map +1 -0
  11. package/dist/{chunk-KLPY2HUC.cjs → chunk-JFKWH6EP.cjs} +57 -2
  12. package/dist/chunk-JFKWH6EP.cjs.map +1 -0
  13. package/dist/{chunk-7AFGROHZ.js → chunk-JQ7Y723H.js} +11 -16
  14. package/dist/{chunk-7AFGROHZ.js.map → chunk-JQ7Y723H.js.map} +1 -1
  15. package/dist/{chunk-J3BYHBKW.js → chunk-KD7CKXWQ.js} +1721 -1427
  16. package/dist/chunk-KD7CKXWQ.js.map +1 -0
  17. package/dist/{chunk-65WT5PHA.cjs → chunk-L66ZJ2UI.cjs} +1733 -1425
  18. package/dist/chunk-L66ZJ2UI.cjs.map +1 -0
  19. package/dist/document-tools/index.cjs +31 -0
  20. package/dist/document-tools/index.cjs.map +1 -1
  21. package/dist/document-tools/index.d.cts +19 -1
  22. package/dist/document-tools/index.d.ts +19 -1
  23. package/dist/document-tools/index.js +30 -1
  24. package/dist/document-tools/index.js.map +1 -1
  25. package/dist/{index-2Y2MVegs.d.ts → index-BV7pBlgY.d.cts} +119 -6
  26. package/dist/{index-2Y2MVegs.d.cts → index-BV7pBlgY.d.ts} +119 -6
  27. package/dist/{index-3E0neHf_.d.cts → index-DyFzmDZ2.d.cts} +46 -1
  28. package/dist/{index-3E0neHf_.d.ts → index-DyFzmDZ2.d.ts} +46 -1
  29. package/dist/index.cjs +1705 -1218
  30. package/dist/index.cjs.map +1 -1
  31. package/dist/index.d.cts +1531 -304
  32. package/dist/index.d.ts +1531 -304
  33. package/dist/index.js +897 -573
  34. package/dist/index.js.map +1 -1
  35. package/dist/shell/index.cjs +33 -9
  36. package/dist/shell/index.d.cts +3 -1
  37. package/dist/shell/index.d.ts +3 -1
  38. package/dist/shell/index.js +1 -1
  39. package/dist/ui/index.cjs +174 -118
  40. package/dist/ui/index.d.cts +1 -1
  41. package/dist/ui/index.d.ts +1 -1
  42. package/dist/ui/index.js +1 -1
  43. package/package.json +3 -3
  44. package/dist/chunk-65WT5PHA.cjs.map +0 -1
  45. package/dist/chunk-J3BYHBKW.js.map +0 -1
  46. package/dist/chunk-KLPY2HUC.cjs.map +0 -1
  47. package/dist/chunk-MFMJHBJR.js.map +0 -1
  48. package/dist/chunk-YIFUMQGA.cjs.map +0 -1
package/dist/index.js CHANGED
@@ -1,13 +1,13 @@
1
- import { arbiMutationKeys, replayableTagMutations, patchDocuments, setCachedDocument, adjustTagCounts, arbiQueryKeys, patchCachedDocument, useDocuments, useConversations, useAssistantQuery, useConversationThreads, refreshDocuments, FINISHED_DOCUMENT_STATUSES, useWorkspaces, forgetDocuments, getCachedDocuments, useParsedDocument, useTags, useActivity, useThumbnails } from './chunk-7AFGROHZ.js';
2
- export { DOCUMENTS_FIRST_PAGE_MEASURE, DOCUMENTS_FIRST_PAGE_SIZE, DOCUMENTS_PAGE_SIZE, FINISHED_DOCUMENT_STATUSES, PROJECT_CREATION_DENIED_REASON, SIMILARITY_THRESHOLD, adjustTagCounts, arbiMutationKeys, arbiQueryKeys, forgetDocuments, getCachedDocuments, invalidateTagData, invalidateTagTables, isDocumentsLoading, isUsageMetered, patchCachedDocument, patchDocuments, patchWorkspaceTags, refreshDocuments, setCachedDocument, stopDocumentsLoading, subscribeDocumentRows, upsertDocuments, useActivity, useAgents, useAssistantQuery, useAvailableModels, useCanCreateProjects, useConfigs, useConversationThreads, useConversations, useCreateTag, useCurrentUser, useDeleteAgents, useDeleteTag, useDocument, useDocumentVersionList, useDocuments, useDocumentsById, useDocumentsLoading, useExtractEntities, useFirmPool, useHealth, useInvalidateTagData, useParsedDocument, useProjectInvoices, useProjectUsage, useProjects, useProjectsUsage, useSetTagValues, useSimilarDocuments, useTagKindSchema, useTags, useThumbnails, useTopUpFirmPool, useUpdateTag, useUpdateTagKindSchema, useUserUsageToday, useWorkspaceActivity, useWorkspaceUsers, useWorkspaces } from './chunk-7AFGROHZ.js';
1
+ import { arbiMutationKeys, replayableTagMutations, patchDocuments, setCachedDocument, adjustTagCounts, arbiQueryKeys, patchCachedDocument, useDocuments, useConversations, useAssistantQuery, useConversationThreads, refreshDocuments, FINISHED_DOCUMENT_STATUSES, useWorkspaces, forgetDocuments, getCachedDocuments, useActivity, useTags, useThumbnails, useParsedDocument } from './chunk-JQ7Y723H.js';
2
+ export { DOCUMENTS_FIRST_PAGE_MEASURE, DOCUMENTS_FIRST_PAGE_SIZE, DOCUMENTS_PAGE_SIZE, FINISHED_DOCUMENT_STATUSES, PROJECT_CREATION_DENIED_REASON, SIMILARITY_THRESHOLD, adjustTagCounts, arbiMutationKeys, arbiQueryKeys, forgetDocuments, getCachedDocuments, invalidateTagData, invalidateTagTables, isDocumentsLoading, isUsageMetered, patchCachedDocument, patchDocuments, patchWorkspaceTags, refreshDocuments, setCachedDocument, stopDocumentsLoading, subscribeDocumentRows, upsertDocuments, useActivity, useAgents, useAssistantQuery, useAvailableModels, useCanCreateProjects, useConfigs, useConversationThreads, useConversations, useCreateTag, useCurrentUser, useDeleteAgents, useDeleteTag, useDocument, useDocumentVersionList, useDocuments, useDocumentsById, useDocumentsLoading, useExtractEntities, useFirmPool, useHealth, useInvalidateTagData, useParsedDocument, useProjectInvoices, useProjectUsage, useProjects, useProjectsUsage, useSetTagValues, useSimilarDocuments, useTagKindSchema, useTags, useThumbnails, useTopUpFirmPool, useUpdateTag, useUpdateTagKindSchema, useUserUsageToday, useWorkspaceActivity, useWorkspaces } from './chunk-JQ7Y723H.js';
3
3
  import { downloadBlob } from './chunk-YYTX3W6C.js';
4
4
  import { parseVersionRef } from './chunk-NNWMHMEC.js';
5
5
  export { cleanDraftMarkdown, cleanDraftWithReport, promoteBoldTitle, repairParsedStructure, repairParsedTitle, stripAgentPreamble, unescapeMarkdown, unwrapCitationLinks } from './chunk-NNWMHMEC.js';
6
6
  import './chunk-WUTL62MC.js';
7
- import { formatRelativeTime } from './chunk-MFMJHBJR.js';
8
- export { DEFAULT_NOTIFY_TONE, MAX_SESSION_NOTIFICATIONS, NotificationBell, Toaster, configureNotify, formatRelativeTime, notify, persistNotifyHistory, seedNotifications, selectUnread, toast, useNotify } from './chunk-MFMJHBJR.js';
9
- import { returnFocusToMark, MarkMenu, AiMarkdown, Card, Badge, TagEntity, Input, FILE_TYPE_COLORS, getEntityIcon, UserEntity, getEntityColorStyles, AgentBadge, Textarea, Label, Slider, DocumentEntity, DocumentCard, useAudioRecorder, MicWaveformIndicator, IconToggle, classifyMediaError, formatElapsed, PassageCard } from './chunk-J3BYHBKW.js';
10
- export { AUDIO_MIME_PREFERENCE, AgentBadge, AiMarkdown, ArbiBotHeadIcon, ArbiIcon, AudIcon, Avatar, AvatarFallback, AvatarImage, BASE_COLORS, Badge, Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, Checkbox, Collapsible, CollapsibleContent, CollapsibleTrigger, Command, CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator, CommandShortcut, DEFAULT_SEGMENTER_CONFIG, DebouncedInput, DictateProvider, DocIcon, DocumentCard, DocumentEntity, ENTITY_MAPPINGS, EmlIcon, EntityIcon, EntityPill, FILE_TYPE_COLORS, HoverCard, HoverCardContent, HoverCardTrigger, HtmlIcon, INITIAL_SEGMENTER_STATE, IconToggle, ImgIcon, InlineMicButton, Input, Label, MarkMenu, MicRecordingOverlay, MicWaveformIndicator, NEUTRAL_GRAY, PLACEHOLDER_COLOR, PassageCard, PdfIcon, Popover, PopoverAnchor, PopoverClose, PopoverContent, PopoverTrigger, PresenceLabel, Progress, ProjectEntity, RadioGroup, RadioGroupItem, RagDot, RelevanceDot, Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectScrollDownButton, SelectScrollUpButton, SelectSeparator, SelectTrigger, SelectValue, Separator, ShieldIcon, Slider, StatusPill, Switch, TAG_TYPE_ICONS, TAG_TYPE_LABELS, Table, TableBody, TableCaption, TableCell, TableFooter, TableHead, TableHeader, TableRow, Tabs, TabsContent, TabsList, TabsTrigger, TagEntity, Textarea, ThreadVisibilityIcon, Toggle, ToggleGroup, ToggleGroupItem, Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, TxtIcon, UserEntity, UserMenu, VIDEO_MIME_PREFERENCE, VISIBILITY_ICONS, VerifiedBadge, VidIcon, VisibilityIcon, VisibilityToggle, XlsIcon, agentAvatarColors, badgeVariants, cardVariants, classifyMediaError, configureEntityRegistry, configureRagLabels, configureStatusRegistry, createChunkedRecorder, flushSegmenter, formatElapsed, getDocIcon, getEntityColor, getEntityColorStyles, getEntityIcon, getEntityLabel, getStatusVariant, getTagTypeIcon, getTagTypeLabel, getWorkspaceColor, levelFromRms, pickRecorderMimeType, stepSegmenter, toggleVariants, useAudioRecorder } from './chunk-J3BYHBKW.js';
7
+ import { createSearchSession, clearSearchSession, formatRelativeTime } from './chunk-3XYIQZTH.js';
8
+ export { DEFAULT_NOTIFY_TONE, MAX_SESSION_NOTIFICATIONS, NotificationBell, Toaster, clearSearchSession, configureNotify, createSearchSession, formatRelativeTime, notify, persistNotifyHistory, persistSearchSession, requestSearch, seedNotifications, selectUnread, sharedSearchSession, takePendingSearch, toast, useNotify } from './chunk-3XYIQZTH.js';
9
+ import { returnFocusToMark, MarkMenu, AiMarkdown, Card, Badge, Input, FILE_TYPE_COLORS, getEntityIcon, UserEntity, getEntityColorStyles, AgentBadge, Textarea, Label, Slider, DocumentEntity, TagEntity, DocumentCard, useAudioRecorder, MicWaveformIndicator, IconToggle, classifyMediaError, formatElapsed } from './chunk-KD7CKXWQ.js';
10
+ export { AUDIO_MIME_PREFERENCE, AgentBadge, AiMarkdown, ArbiBotHeadIcon, ArbiIcon, AudIcon, Avatar, AvatarFallback, AvatarImage, BASE_COLORS, Badge, Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, Checkbox, Collapsible, CollapsibleContent, CollapsibleTrigger, Command, CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator, CommandShortcut, DEFAULT_SEGMENTER_CONFIG, DebouncedInput, DictateProvider, DocIcon, DocumentCard, DocumentEntity, ENTITY_MAPPINGS, EmlIcon, EntityIcon, EntityPill, FILE_TYPE_COLORS, HoverCard, HoverCardContent, HoverCardTrigger, HtmlIcon, INITIAL_SEGMENTER_STATE, IconToggle, ImgIcon, InlineMicButton, Input, Label, MarkMenu, MicRecordingOverlay, MicWaveformIndicator, NEUTRAL_GRAY, PLACEHOLDER_COLOR, PassageCard, PdfIcon, Popover, PopoverAnchor, PopoverClose, PopoverContent, PopoverTrigger, PresenceLabel, Progress, ProjectEntity, RadioGroup, RadioGroupItem, RagDot, RelevanceDot, Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectScrollDownButton, SelectScrollUpButton, SelectSeparator, SelectTrigger, SelectValue, Separator, ShieldIcon, Slider, StatusPill, Switch, TAG_TYPE_ICONS, TAG_TYPE_LABELS, Table, TableBody, TableCaption, TableCell, TableFooter, TableHead, TableHeader, TableRow, Tabs, TabsContent, TabsList, TabsTrigger, TagEntity, Textarea, ThreadVisibilityIcon, Toggle, ToggleGroup, ToggleGroupItem, Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, TxtIcon, UserEntity, UserMenu, VIDEO_MIME_PREFERENCE, VISIBILITY_ICONS, VerifiedBadge, VerifiedToggle, VidIcon, VisibilityIcon, VisibilityToggle, XlsIcon, agentAvatarColors, badgeVariants, cardVariants, classifyMediaError, configureEntityRegistry, configureRagLabels, configureStatusRegistry, createChunkedRecorder, flushSegmenter, formatElapsed, formatFriendlyDate, friendlyFileType, getDocIcon, getDocumentTitle, getEntityColor, getEntityColorStyles, getEntityIcon, getEntityLabel, getStatusVariant, getTagTypeIcon, getTagTypeLabel, getWorkspaceColor, isAudioFile, isDownloadOnlyFile, isImageDocument, isImageFile, isMediaFile, isVideoFile, levelFromRms, pickRecorderMimeType, stepSegmenter, tagKindNouns, tagKindTitle, toggleVariants, useAudioRecorder, useDictateContext, usesOriginalBytesForViewer } from './chunk-KD7CKXWQ.js';
11
11
  import { MarkdownRenderer } from './chunk-C44GO33B.js';
12
12
  export { MarkdownCode, MarkdownLink, MarkdownRenderer, MarkdownStreamingContext, markdownBaseComponents, markdownSanitizeSchema, splitMarkdownBlocks } from './chunk-C44GO33B.js';
13
13
  import { Button, Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from './chunk-YNNAJJ5Z.js';
@@ -23,11 +23,11 @@ export { cn } from './chunk-SN5YV6FF.js';
23
23
  import { AudioViewer, ImageViewer, VideoViewer } from './chunk-HDCRPPBW.js';
24
24
  import { useArbi, ArbiContext } from './chunk-CPPBN2JB.js';
25
25
  export { ArbiProvider, useArbi, useDeploymentDomain } from './chunk-CPPBN2JB.js';
26
- import React, { memo, useState, createContext, useMemo, useCallback, useEffect, useRef, useLayoutEffect, useContext, useId, useSyncExternalStore, Fragment as Fragment$1 } from 'react';
27
- import { useQueryClient, useMutation, useQuery, onlineManager, partialMatchKey } from '@tanstack/react-query';
28
- import { documents, doctags, houseTemplates, resolveCitations, summarizeCitations, settings, ArbiApiError, ACCOUNT_VENDOR, formatFileSize, connectWithReconnect, chats, identityErrorCode } from '@arbidocs/sdk/browser';
29
- export { ACCOUNT_VENDOR, Arbi, ArbiError, DEFAULT_AI_USD_PER_GBP, PublicBookingError, bookPublicSlot, cancelPublicBooking, formatGbp, formatGbpPerMillionTokens, getPublicBookingPage, splitAppPasswords, usdToGbp } from '@arbidocs/sdk/browser';
30
- import { Link, Trash2, CheckCheck, Check, Loader2, AlertTriangle, ShieldCheck, Copy, Sparkles, FileText, GitCompareArrows, Download, Search, CornerDownLeft, X, ArrowLeft, Send, Tags, Crown, Info, Activity, HardDrive, Gauge, Gift, PartyPopper, UserPlus, UserCheck, Reply, PenLine, AtSign, MessageCircleMore, FileX2, FileCheck2, Pencil, FolderPlus, SquareArrowOutUpRight, MessagesSquare, Paperclip, ArrowRight, MoreHorizontal, SquarePen, Mic, Pause, Play, Square, RotateCcw, Camera, Circle, Image as Image$1, AppWindow } from 'lucide-react';
26
+ import React3, { memo, useState, createContext, useMemo, useCallback, useEffect, useRef, useLayoutEffect, useContext, useId, useSyncExternalStore, Fragment as Fragment$1 } from 'react';
27
+ import { useQueryClient, useMutation, useQuery, useQueries, onlineManager, partialMatchKey } from '@tanstack/react-query';
28
+ import { documents, doctags, houseTemplates, resolveCitations, summarizeCitations, settings, isConnectorVendorVisible, ArbiApiError, ACCOUNT_VENDOR, searchChunks, formatFileSize, connectWithReconnect, chats, identityErrorCode } from '@arbidocs/sdk/browser';
29
+ export { ACCOUNT_VENDOR, Arbi, ArbiError, DEFAULT_AI_USD_PER_GBP, DRIVE_SYNC_VENDORS, GOOGLE_VENDORS, IMANAGE_VENDORS, MAILBOX_SYNC_VENDORS, MAX_RETRIEVE_DOC_IDS, MICROSOFT_VENDORS, PublicBookingError, SHAREPOINT_VENDORS, bookPublicSlot, cancelPublicBooking, connectErrorMessage, formatGbp, formatGbpPerMillionTokens, getPublicBookingPage, isConnectorVendorVisible, isDriveSyncVendor, isMailboxSyncVendor, isSharePointVendor, usdToGbp } from '@arbidocs/sdk/browser';
30
+ import { Link, Trash2, CheckCheck, Check, Loader2, AlertTriangle, ShieldCheck, Copy, Sparkles, FileText, GitCompareArrows, Download, Search, CornerDownLeft, Send, Tags, Crown, Info, Activity, HardDrive, Gauge, Gift, PartyPopper, UserPlus, UserCheck, Reply, PenLine, AtSign, MessageCircleMore, FileX2, FileCheck2, Pencil, FolderPlus, SquareArrowOutUpRight, MessagesSquare, Paperclip, X, ArrowRight, MoreHorizontal, SquarePen, Mic, Pause, Play, Square, RotateCcw, Camera, Circle, Image as Image$1, AppWindow } from 'lucide-react';
31
31
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
32
32
  import { isMessageType, passwordChangeErrorMessage, createRecoveryFile } from '@arbidocs/client';
33
33
  export { isMessageType } from '@arbidocs/client';
@@ -1562,15 +1562,6 @@ function useArbiShellWorkspaces(options = {}) {
1562
1562
  select: select ?? defaultSelect
1563
1563
  });
1564
1564
  }
1565
- function useInvalidateMembership() {
1566
- const qc = useQueryClient();
1567
- return () => Promise.all([
1568
- qc.invalidateQueries({ queryKey: arbiQueryKeys.workspaces() }),
1569
- qc.invalidateQueries({ queryKey: ["arbi", "workspaceUsers"] }),
1570
- qc.invalidateQueries({ queryKey: arbiQueryKeys.projects() }),
1571
- qc.invalidateQueries({ queryKey: arbiQueryKeys.contacts() })
1572
- ]);
1573
- }
1574
1565
  function useUpdateWorkspace() {
1575
1566
  const arbi = useArbi();
1576
1567
  const qc = useQueryClient();
@@ -1579,22 +1570,60 @@ function useUpdateWorkspace() {
1579
1570
  onSuccess: () => qc.invalidateQueries({ queryKey: arbiQueryKeys.workspaces() })
1580
1571
  });
1581
1572
  }
1573
+ var MEMBERS_STALE_MS = 15 * 60 * 1e3;
1574
+ function useWorkspaceUsers(workspaceId, options) {
1575
+ const arbi = useArbi();
1576
+ const workspace = workspaceId ?? (arbi.hasWorkspace ? arbi.getWorkspaceId() : "");
1577
+ return useQuery({
1578
+ queryKey: arbiQueryKeys.workspaceUsers(workspace),
1579
+ enabled: !!workspace && (options?.enabled ?? arbi.hasWorkspace),
1580
+ queryFn: async () => {
1581
+ await options?.beforeFetch?.();
1582
+ if (arbi.getWorkspaceId() !== workspace) throw new Error("The selected workspace changed.");
1583
+ return arbi.workspaces.listUsers();
1584
+ },
1585
+ staleTime: MEMBERS_STALE_MS
1586
+ });
1587
+ }
1588
+ function settleMembership(qc) {
1589
+ return Promise.all([
1590
+ qc.invalidateQueries({ queryKey: arbiQueryKeys.allWorkspaceUsers() }),
1591
+ qc.invalidateQueries({ queryKey: arbiQueryKeys.workspaces() }),
1592
+ // A project's collaborator quota counts workspace members.
1593
+ qc.invalidateQueries({ queryKey: arbiQueryKeys.projects() })
1594
+ ]);
1595
+ }
1582
1596
  function useAddWorkspaceMembers() {
1583
1597
  const arbi = useArbi();
1584
- const invalidate = useInvalidateMembership();
1598
+ const qc = useQueryClient();
1585
1599
  return useMutation({
1586
1600
  mutationKey: arbiMutationKeys.workspaceMembership(),
1587
- mutationFn: ({ emails, role, confirmInvite }) => arbi.workspaces.addUsers(emails, role, { confirmInvite }),
1588
- onSuccess: () => invalidate()
1601
+ mutationFn: (request) => arbi.workspaces.addMembers(request),
1602
+ onSuccess: () => Promise.all([
1603
+ settleMembership(qc),
1604
+ qc.invalidateQueries({ queryKey: arbiQueryKeys.contacts() })
1605
+ ])
1589
1606
  });
1590
1607
  }
1591
1608
  function useRemoveWorkspaceMembers() {
1592
1609
  const arbi = useArbi();
1593
- const invalidate = useInvalidateMembership();
1610
+ const qc = useQueryClient();
1594
1611
  return useMutation({
1595
1612
  mutationKey: arbiMutationKeys.workspaceMembership(),
1596
1613
  mutationFn: (userIds) => arbi.workspaces.removeUsers(userIds),
1597
- onSuccess: () => invalidate()
1614
+ onSuccess: () => settleMembership(qc)
1615
+ });
1616
+ }
1617
+ function useSetWorkspaceMemberRoles() {
1618
+ const arbi = useArbi();
1619
+ const qc = useQueryClient();
1620
+ return useMutation({
1621
+ mutationKey: arbiMutationKeys.setWorkspaceMemberRoles(),
1622
+ mutationFn: ({ userIds, role }) => arbi.workspaces.setUserRole(userIds, role),
1623
+ onSuccess: () => Promise.all([
1624
+ qc.invalidateQueries({ queryKey: arbiQueryKeys.allWorkspaceUsers() }),
1625
+ qc.invalidateQueries({ queryKey: arbiQueryKeys.workspaces() })
1626
+ ])
1598
1627
  });
1599
1628
  }
1600
1629
  function useFacts(workspaceId, options) {
@@ -1650,6 +1679,35 @@ function useSearchFacts() {
1650
1679
  mutationFn: (body) => arbi.facts.search(body)
1651
1680
  });
1652
1681
  }
1682
+ var PARSED_STALE_TIME = 5 * 60 * 1e3;
1683
+ function indexPassages(results) {
1684
+ const index = /* @__PURE__ */ new Map();
1685
+ for (const r of results)
1686
+ (r.data?.chunks ?? []).forEach((chunk, order) => {
1687
+ const id = chunk.metadata?.chunk_ext_id;
1688
+ if (id && !index.has(id)) index.set(id, { text: (chunk.content ?? "").trim(), order });
1689
+ });
1690
+ return index;
1691
+ }
1692
+ function usePassageQuotes(docIds) {
1693
+ const arbi = useArbi();
1694
+ const passages = useQueries({
1695
+ queries: [...new Set(docIds ?? [])].map((docId) => ({
1696
+ queryKey: arbiQueryKeys.parsedDoc(docId, "final"),
1697
+ queryFn: () => arbi.documents.getParsedContent(docId, "final"),
1698
+ enabled: arbi.hasWorkspace,
1699
+ staleTime: PARSED_STALE_TIME
1700
+ })),
1701
+ combine: indexPassages
1702
+ });
1703
+ return useMemo(
1704
+ () => ({
1705
+ quoteFor: (chunkId) => passages.get(chunkId)?.text || void 0,
1706
+ orderOf: (chunkId) => passages.get(chunkId)?.order ?? Number.POSITIVE_INFINITY
1707
+ }),
1708
+ [passages]
1709
+ );
1710
+ }
1653
1711
  var DocumentsSupportContext = createContext({});
1654
1712
  function DocumentsSupportProvider({
1655
1713
  support,
@@ -1981,7 +2039,10 @@ function useUpdateProjectFields() {
1981
2039
  projectExtId,
1982
2040
  patch
1983
2041
  }) => arbi.projects.update(projectExtId, patch),
1984
- onSuccess: () => qc.invalidateQueries({ queryKey: arbiQueryKeys.projects() })
2042
+ onSuccess: () => {
2043
+ void qc.invalidateQueries({ queryKey: arbiQueryKeys.projects() });
2044
+ void qc.invalidateQueries({ queryKey: arbiQueryKeys.workspaces() });
2045
+ }
1985
2046
  });
1986
2047
  }
1987
2048
  function useProjectEvents(projectExtId, options) {
@@ -2013,6 +2074,207 @@ function useProjectConversationUsage(projectExtId, monthsBack = 0, options) {
2013
2074
  enabled: (options?.enabled ?? true) && !!projectExtId && arbi.isLoggedIn
2014
2075
  });
2015
2076
  }
2077
+ var SLOW_AFTER_MS = 5e3;
2078
+ var POLL_EVERY_MS = 3e3;
2079
+ var STILL_WORKING = "Still working \u2014 confirm in your bank's tab if it opened. We'll update here.";
2080
+ function useIsSlow(isPending, ms = SLOW_AFTER_MS) {
2081
+ const [isSlow, setIsSlow] = useState(false);
2082
+ useEffect(() => {
2083
+ if (!isPending) {
2084
+ setIsSlow(false);
2085
+ return;
2086
+ }
2087
+ const timer = setTimeout(() => setIsSlow(true), ms);
2088
+ return () => clearTimeout(timer);
2089
+ }, [isPending, ms]);
2090
+ return isSlow;
2091
+ }
2092
+ function useChargeWatch(project, isPending) {
2093
+ const queryClient = useQueryClient();
2094
+ const isSlow = useIsSlow(isPending);
2095
+ const watchRef = useRef(null);
2096
+ useEffect(() => {
2097
+ if (!isSlow) return;
2098
+ const timer = setInterval(
2099
+ () => queryClient.invalidateQueries({ queryKey: arbiQueryKeys.projects(), exact: true }),
2100
+ POLL_EVERY_MS
2101
+ );
2102
+ return () => clearInterval(timer);
2103
+ }, [isSlow, queryClient]);
2104
+ const settle = useCallback((ok, onNotLanded) => {
2105
+ const watch2 = watchRef.current;
2106
+ if (!watch2 || watch2.settled) return;
2107
+ watch2.settled = true;
2108
+ if (ok) watch2.onLanded();
2109
+ else onNotLanded?.();
2110
+ }, []);
2111
+ useEffect(() => {
2112
+ const watch2 = watchRef.current;
2113
+ if (watch2 && !watch2.settled && watch2.landed(project)) settle(true);
2114
+ }, [project, settle]);
2115
+ const watch = useCallback((landed, onLanded) => {
2116
+ watchRef.current = { landed, onLanded, settled: false };
2117
+ }, []);
2118
+ const succeeded = useCallback(() => settle(true), [settle]);
2119
+ const refused = useCallback(() => settle(false), [settle]);
2120
+ const settleFailure = useCallback(
2121
+ async (onNotLanded) => {
2122
+ const watch2 = watchRef.current;
2123
+ if (!watch2 || watch2.settled) return;
2124
+ let fresh;
2125
+ try {
2126
+ await queryClient.refetchQueries({ queryKey: arbiQueryKeys.projects(), exact: true });
2127
+ fresh = queryClient.getQueryData(arbiQueryKeys.projects())?.find((p) => p.external_id === project.external_id);
2128
+ } catch {
2129
+ fresh = void 0;
2130
+ }
2131
+ settle(!!fresh && watch2.landed(fresh), onNotLanded);
2132
+ },
2133
+ [queryClient, project.external_id, settle]
2134
+ );
2135
+ return { isSlow, watch, succeeded, refused, settleFailure };
2136
+ }
2137
+
2138
+ // src/billing.ts
2139
+ function refreshProjects(qc, wide = false) {
2140
+ void qc.invalidateQueries({ queryKey: arbiQueryKeys.projects() });
2141
+ if (wide) {
2142
+ void qc.invalidateQueries({ queryKey: arbiQueryKeys.userSettings() });
2143
+ void qc.invalidateQueries({ queryKey: arbiQueryKeys.workspaces() });
2144
+ }
2145
+ }
2146
+ var retryAbortOnly = (failureCount, error) => failureCount < 1 && error?.name === "AbortError";
2147
+ function useInvalidateProjects() {
2148
+ const qc = useQueryClient();
2149
+ return () => qc.invalidateQueries({ queryKey: arbiQueryKeys.projects() });
2150
+ }
2151
+ function useProducts(options) {
2152
+ const arbi = useArbi();
2153
+ return useQuery({
2154
+ queryKey: arbiQueryKeys.products(),
2155
+ queryFn: () => arbi.projects.products(),
2156
+ staleTime: 5 * 6e4,
2157
+ enabled: (options?.enabled ?? true) && arbi.isLoggedIn
2158
+ });
2159
+ }
2160
+ function useCreateProject() {
2161
+ const arbi = useArbi();
2162
+ const qc = useQueryClient();
2163
+ return useMutation({
2164
+ mutationFn: ({ name, plan, ...details }) => arbi.projects.create(name, plan, details),
2165
+ onSuccess: () => refreshProjects(qc, true)
2166
+ });
2167
+ }
2168
+ function useDeleteProject() {
2169
+ const arbi = useArbi();
2170
+ const qc = useQueryClient();
2171
+ return useMutation({
2172
+ mutationFn: (projectExtId) => arbi.projects.delete(projectExtId),
2173
+ onSuccess: () => refreshProjects(qc, true)
2174
+ });
2175
+ }
2176
+ function useRefreshProject() {
2177
+ const arbi = useArbi();
2178
+ const qc = useQueryClient();
2179
+ return useMutation({
2180
+ mutationFn: (projectExtId) => arbi.projects.refresh(projectExtId),
2181
+ onSuccess: () => refreshProjects(qc, true)
2182
+ });
2183
+ }
2184
+ function useCreateProjectCheckout() {
2185
+ const arbi = useArbi();
2186
+ return useMutation({
2187
+ mutationFn: ({ projectExtId, body }) => arbi.projects.checkout(projectExtId, body)
2188
+ });
2189
+ }
2190
+ function useChangeProjectPlan() {
2191
+ const arbi = useArbi();
2192
+ const qc = useQueryClient();
2193
+ return useMutation({
2194
+ mutationFn: ({
2195
+ projectExtId,
2196
+ body
2197
+ }) => arbi.projects.changePlan(projectExtId, body),
2198
+ onSuccess: () => refreshProjects(qc, true)
2199
+ });
2200
+ }
2201
+ function useCancelProjectSubscription() {
2202
+ const arbi = useArbi();
2203
+ const qc = useQueryClient();
2204
+ return useMutation({
2205
+ mutationFn: (projectExtId) => arbi.projects.cancelSubscription(projectExtId),
2206
+ onSuccess: () => {
2207
+ void qc.invalidateQueries({ queryKey: arbiQueryKeys.projects() });
2208
+ void qc.invalidateQueries({ queryKey: arbiQueryKeys.userSettings() });
2209
+ }
2210
+ });
2211
+ }
2212
+ function usePreviewProjectPlanChange(projectExtId, change) {
2213
+ const arbi = useArbi();
2214
+ return useQuery({
2215
+ queryKey: [...arbiQueryKeys.billingQuotes(), "preview", projectExtId, change],
2216
+ queryFn: () => arbi.projects.previewPlanChange(projectExtId, change),
2217
+ enabled: !!change && arbi.isLoggedIn,
2218
+ staleTime: 6e4,
2219
+ retry: retryAbortOnly
2220
+ });
2221
+ }
2222
+ function usePlanQuote(projectExtId, body) {
2223
+ const arbi = useArbi();
2224
+ return useQuery({
2225
+ queryKey: [...arbiQueryKeys.billingQuotes(), "plan", projectExtId ?? null, body],
2226
+ queryFn: () => arbi.projects.quotePlan(projectExtId ?? null, body),
2227
+ enabled: !!body && arbi.isLoggedIn,
2228
+ staleTime: 5 * 6e4,
2229
+ retry: retryAbortOnly
2230
+ });
2231
+ }
2232
+ function useAddonQuote(projectExtId, kind, enabled = true) {
2233
+ const arbi = useArbi();
2234
+ return useQuery({
2235
+ queryKey: [...arbiQueryKeys.billingQuotes(), "addon", projectExtId, kind],
2236
+ queryFn: () => arbi.projects.quoteAddon(projectExtId, kind),
2237
+ enabled: enabled && arbi.isLoggedIn,
2238
+ staleTime: 6e4,
2239
+ retry: retryAbortOnly
2240
+ });
2241
+ }
2242
+ function useProjectBillingPortal() {
2243
+ const arbi = useArbi();
2244
+ return useMutation({
2245
+ mutationFn: (projectExtId) => arbi.projects.billingPortal(projectExtId)
2246
+ });
2247
+ }
2248
+ function useAddProjectAddonBlock() {
2249
+ const arbi = useArbi();
2250
+ const qc = useQueryClient();
2251
+ return useMutation({
2252
+ mutationFn: ({ projectExtId, kind }) => arbi.projects.addAddonBlock(projectExtId, kind),
2253
+ onSuccess: () => refreshProjects(qc)
2254
+ });
2255
+ }
2256
+ function useUpdateProjectNextPeriodAddons() {
2257
+ const arbi = useArbi();
2258
+ const qc = useQueryClient();
2259
+ return useMutation({
2260
+ mutationFn: ({
2261
+ projectExtId,
2262
+ body
2263
+ }) => arbi.projects.setNextPeriodAddons(projectExtId, body),
2264
+ onSuccess: () => refreshProjects(qc)
2265
+ });
2266
+ }
2267
+ function useUpdateProjectAddonSettings() {
2268
+ const arbi = useArbi();
2269
+ const qc = useQueryClient();
2270
+ return useMutation({
2271
+ mutationFn: ({
2272
+ projectExtId,
2273
+ body
2274
+ }) => arbi.projects.updateAddonSettings(projectExtId, body),
2275
+ onSuccess: () => refreshProjects(qc)
2276
+ });
2277
+ }
2016
2278
  function useContacts(options) {
2017
2279
  const arbi = useArbi();
2018
2280
  return useQuery({
@@ -3453,11 +3715,241 @@ var calendarQueryKeys = {
3453
3715
  ],
3454
3716
  accounts: () => ["arbi", "calendar", "accounts"],
3455
3717
  caldavProfiles: () => ["arbi", "calendar", "caldav-profiles"],
3456
- appPasswords: () => ["arbi", "calendar", "app-passwords"],
3457
3718
  bookingPages: () => ["arbi", "calendar", "booking-pages"],
3458
3719
  /** The offline outbox (writes made offline, not yet sent). */
3459
3720
  outbox: () => ["arbi", "calendar", "outbox"]
3460
3721
  };
3722
+ var connectorQueryKeys = {
3723
+ all: () => ["arbi", "connectors"],
3724
+ catalog: () => ["arbi", "connectors", "catalog"],
3725
+ mine: () => ["arbi", "connectors", "mine"],
3726
+ mailboxFolders: (vendor) => ["arbi", "connectors", "folders", vendor],
3727
+ mailboxSyncProgress: (vendor, workspaceExtId) => ["arbi", "connectors", "sync-progress", vendor, workspaceExtId],
3728
+ allMailboxSyncProgress: () => ["arbi", "connectors", "sync-progress"],
3729
+ driveFolders: (vendor) => ["arbi", "connectors", "drive-folders", vendor],
3730
+ driveFolderChildren: (vendor, itemId) => ["arbi", "connectors", "drive-folder-children", vendor, itemId],
3731
+ driveFolderDocCount: (vendor, itemId) => ["arbi", "connectors", "drive-folder-doc-count", vendor, itemId],
3732
+ driveSyncEstimate: (vendor) => ["arbi", "connectors", "drive-sync-estimate", vendor],
3733
+ driveSyncProgress: (vendor) => ["arbi", "connectors", "drive-sync-progress", vendor],
3734
+ allDriveSyncProgress: () => ["arbi", "connectors", "drive-sync-progress"],
3735
+ slack: () => ["arbi", "connectors", "slack"]
3736
+ };
3737
+ function useConnectorMutation(mutationFn) {
3738
+ const qc = useQueryClient();
3739
+ return useMutation({
3740
+ mutationFn,
3741
+ onSuccess: () => qc.invalidateQueries({ queryKey: connectorQueryKeys.all() })
3742
+ });
3743
+ }
3744
+ function useConnectorCatalog() {
3745
+ const arbi = useArbi();
3746
+ return useQuery({
3747
+ queryKey: connectorQueryKeys.catalog(),
3748
+ queryFn: () => arbi.connectors.catalog(),
3749
+ staleTime: 5 * 6e4,
3750
+ enabled: arbi.isLoggedIn
3751
+ });
3752
+ }
3753
+ function useMyConnectors() {
3754
+ const arbi = useArbi();
3755
+ return useQuery({
3756
+ queryKey: connectorQueryKeys.mine(),
3757
+ queryFn: () => arbi.connectors.mine(),
3758
+ staleTime: 3e4,
3759
+ enabled: arbi.isLoggedIn
3760
+ });
3761
+ }
3762
+ function useDisconnectConnector() {
3763
+ const arbi = useArbi();
3764
+ return useConnectorMutation(
3765
+ ({ vendorKey }) => arbi.connectors.disconnect(vendorKey)
3766
+ );
3767
+ }
3768
+ function useConnectorVendorVisibility() {
3769
+ const { data: settings } = useUserSettings();
3770
+ return (vendorKey) => isConnectorVendorVisible(settings, vendorKey);
3771
+ }
3772
+ function connectorReturnTo(reopen) {
3773
+ const params = new URLSearchParams(window.location.search);
3774
+ params.delete("connected");
3775
+ params.delete("connect_error");
3776
+ params.set("stay", "1");
3777
+ if (reopen) params.set("reopen", reopen);
3778
+ else params.delete("reopen");
3779
+ return `${window.location.pathname}?${params.toString()}`;
3780
+ }
3781
+ function useMailboxFolders(vendorKey, enabled) {
3782
+ const arbi = useArbi();
3783
+ return useQuery({
3784
+ queryKey: connectorQueryKeys.mailboxFolders(vendorKey),
3785
+ queryFn: () => arbi.connectors.mailboxFolders(vendorKey),
3786
+ enabled: enabled && arbi.isLoggedIn,
3787
+ staleTime: 6e4
3788
+ });
3789
+ }
3790
+ function useEnableMailboxSync() {
3791
+ const arbi = useArbi();
3792
+ return useConnectorMutation(
3793
+ (v) => arbi.connectors.enableMailboxSync(v.vendorKey, {
3794
+ workspace_ext_id: v.workspaceExtId,
3795
+ backfill_window: v.backfillWindow,
3796
+ backfill_since: v.backfillSince ?? null,
3797
+ folders: v.folders,
3798
+ skip_duplicates: v.skipDuplicates,
3799
+ auto_rename: v.autoRename ?? false,
3800
+ shared: v.shared ?? false,
3801
+ auto_sync: v.autoSync
3802
+ })
3803
+ );
3804
+ }
3805
+ function useTriggerMailboxSync() {
3806
+ const arbi = useArbi();
3807
+ return useConnectorMutation(
3808
+ ({ vendorKey, workspaceExtId }) => arbi.connectors.syncMailbox(vendorKey, workspaceExtId)
3809
+ );
3810
+ }
3811
+ function useMailboxSyncProgress(vendorKey, workspaceExtId, enabled) {
3812
+ const arbi = useArbi();
3813
+ return useQuery({
3814
+ queryKey: connectorQueryKeys.mailboxSyncProgress(vendorKey, workspaceExtId),
3815
+ queryFn: () => arbi.connectors.mailboxSyncProgress(vendorKey, workspaceExtId),
3816
+ enabled: enabled && !!workspaceExtId && arbi.isLoggedIn,
3817
+ refetchInterval: (query) => query.state.data?.running ? 1500 : false,
3818
+ staleTime: 0
3819
+ });
3820
+ }
3821
+ function useCancelMailboxSync() {
3822
+ const arbi = useArbi();
3823
+ return useMutation({
3824
+ mutationFn: ({ vendorKey, workspaceExtId }) => arbi.connectors.cancelMailboxSync(vendorKey, workspaceExtId)
3825
+ });
3826
+ }
3827
+ function useDriveFolders(vendorKey, enabled) {
3828
+ const arbi = useArbi();
3829
+ return useQuery({
3830
+ queryKey: connectorQueryKeys.driveFolders(vendorKey),
3831
+ queryFn: () => arbi.connectors.driveFolders(vendorKey),
3832
+ enabled: enabled && arbi.isLoggedIn,
3833
+ retry: false,
3834
+ staleTime: 6e4
3835
+ });
3836
+ }
3837
+ function useDriveFolderChildren(vendorKey, itemId, enabled) {
3838
+ const arbi = useArbi();
3839
+ return useQuery({
3840
+ queryKey: connectorQueryKeys.driveFolderChildren(vendorKey, itemId),
3841
+ queryFn: () => arbi.connectors.driveFolderChildren(vendorKey, itemId),
3842
+ enabled: enabled && arbi.isLoggedIn,
3843
+ staleTime: 3e4
3844
+ });
3845
+ }
3846
+ function useDriveFolderDocCount(vendorKey, itemId, enabled) {
3847
+ const arbi = useArbi();
3848
+ return useQuery({
3849
+ queryKey: connectorQueryKeys.driveFolderDocCount(vendorKey, itemId),
3850
+ queryFn: () => arbi.connectors.driveFolderDocCount(vendorKey, itemId),
3851
+ enabled: enabled && arbi.isLoggedIn,
3852
+ staleTime: 5 * 6e4
3853
+ });
3854
+ }
3855
+ function useEnableDriveSync() {
3856
+ const arbi = useArbi();
3857
+ return useConnectorMutation(
3858
+ (v) => arbi.connectors.enableDriveSync(v.vendorKey, {
3859
+ workspace_ext_id: v.workspaceExtId,
3860
+ folders: v.folders,
3861
+ skip_duplicates: v.skipDuplicates,
3862
+ auto_rename: v.autoRename,
3863
+ shared: v.shared,
3864
+ auto_sync: v.autoSync
3865
+ })
3866
+ );
3867
+ }
3868
+ function useTriggerDriveSync() {
3869
+ const arbi = useArbi();
3870
+ return useConnectorMutation(
3871
+ ({ vendorKey }) => arbi.connectors.syncDrive(vendorKey)
3872
+ );
3873
+ }
3874
+ function useDriveSyncEstimate(vendorKey, enabled) {
3875
+ const arbi = useArbi();
3876
+ return useQuery({
3877
+ queryKey: connectorQueryKeys.driveSyncEstimate(vendorKey),
3878
+ queryFn: () => arbi.connectors.driveSyncEstimate(vendorKey),
3879
+ enabled: enabled && arbi.isLoggedIn,
3880
+ staleTime: 3e4
3881
+ });
3882
+ }
3883
+ function useDriveSyncProgress(vendorKey, enabled) {
3884
+ const arbi = useArbi();
3885
+ return useQuery({
3886
+ queryKey: connectorQueryKeys.driveSyncProgress(vendorKey),
3887
+ queryFn: () => arbi.connectors.driveSyncProgress(vendorKey),
3888
+ enabled: enabled && arbi.isLoggedIn,
3889
+ refetchInterval: (query) => query.state.data?.running ? 1500 : false,
3890
+ staleTime: 0
3891
+ });
3892
+ }
3893
+ function useCancelDriveSync() {
3894
+ const arbi = useArbi();
3895
+ return useMutation({
3896
+ mutationFn: ({ vendorKey }) => arbi.connectors.cancelDriveSync(vendorKey)
3897
+ });
3898
+ }
3899
+ function useSlackConnection() {
3900
+ const arbi = useArbi();
3901
+ return useQuery({
3902
+ queryKey: connectorQueryKeys.slack(),
3903
+ queryFn: () => arbi.connectors.slack.status(),
3904
+ enabled: arbi.isLoggedIn,
3905
+ // Fresh on every visit: the OAuth return lands here before the status changed server-side.
3906
+ staleTime: 0,
3907
+ refetchOnMount: "always",
3908
+ refetchOnWindowFocus: true
3909
+ });
3910
+ }
3911
+ function useDisconnectSlack() {
3912
+ const arbi = useArbi();
3913
+ return useConnectorMutation(() => arbi.connectors.slack.disconnect());
3914
+ }
3915
+ function useRefreshConnectorsOnRunEnd(running) {
3916
+ const qc = useQueryClient();
3917
+ const wasRunning = useRef(running);
3918
+ useEffect(() => {
3919
+ if (wasRunning.current && !running) {
3920
+ void qc.invalidateQueries({ queryKey: connectorQueryKeys.mine() });
3921
+ }
3922
+ wasRunning.current = running;
3923
+ }, [running, qc]);
3924
+ }
3925
+ var FOCUS_RECHECK_MS = 6e4;
3926
+ function useConnectorAutoSync(workspaceExtId, opened) {
3927
+ const arbi = useArbi();
3928
+ const qc = useQueryClient();
3929
+ const lastCheck = useRef(0);
3930
+ useEffect(() => {
3931
+ if (!opened || !workspaceExtId || !arbi.isLoggedIn) return;
3932
+ const check = () => {
3933
+ lastCheck.current = Date.now();
3934
+ void arbi.connectors.bridgeTokens({ autoSyncWorkspaceExtId: workspaceExtId }).then(() => {
3935
+ void qc.invalidateQueries({ queryKey: connectorQueryKeys.mine() });
3936
+ void qc.invalidateQueries({ queryKey: connectorQueryKeys.allMailboxSyncProgress() });
3937
+ void qc.invalidateQueries({ queryKey: connectorQueryKeys.allDriveSyncProgress() });
3938
+ });
3939
+ };
3940
+ check();
3941
+ const onVisible = () => {
3942
+ if (document.visibilityState !== "visible") return;
3943
+ if (Date.now() - lastCheck.current < FOCUS_RECHECK_MS) return;
3944
+ check();
3945
+ };
3946
+ document.addEventListener("visibilitychange", onVisible);
3947
+ return () => document.removeEventListener("visibilitychange", onVisible);
3948
+ }, [opened, workspaceExtId, arbi, qc]);
3949
+ }
3950
+ function connectorErrorStatus(err) {
3951
+ return err instanceof ArbiApiError ? err.status : void 0;
3952
+ }
3461
3953
  function isQueuedCalendarWrite(value) {
3462
3954
  return !!value && typeof value === "object" && value.queued === true;
3463
3955
  }
@@ -3469,7 +3961,24 @@ function CalendarSupportProvider({
3469
3961
  return /* @__PURE__ */ jsx(CalendarSupportContext.Provider, { value, children });
3470
3962
  }
3471
3963
  function useCalendarSupport() {
3472
- return useContext(CalendarSupportContext);
3964
+ const support = useContext(CalendarSupportContext);
3965
+ const arbi = useArbi();
3966
+ const qc = useQueryClient();
3967
+ return useMemo(
3968
+ () => ({
3969
+ ...support,
3970
+ connectors: support.connectors ?? {
3971
+ authorize: (vendor, returnPath) => arbi.connectors.authorize(vendor, returnPath),
3972
+ bridge: (vendor) => arbi.connectors.bridgeTokens({ vendor }),
3973
+ connectedVendors: async () => (await qc.fetchQuery({
3974
+ queryKey: connectorQueryKeys.mine(),
3975
+ queryFn: () => arbi.connectors.mine(),
3976
+ staleTime: 3e4
3977
+ })).map((c) => c.vendor_key)
3978
+ }
3979
+ }),
3980
+ [support, arbi, qc]
3981
+ );
3473
3982
  }
3474
3983
  function invalidateCalendarEvents(qc) {
3475
3984
  return Promise.all([
@@ -3980,56 +4489,18 @@ function useSyncAccountsOnOpen(enabled = true) {
3980
4489
  }, [enabled, accounts, arbi, qc]);
3981
4490
  return { syncing };
3982
4491
  }
3983
- function useAppPasswords(enabled = true) {
4492
+ function useBookingPages(enabled = true) {
3984
4493
  const arbi = useArbi();
3985
4494
  return useQuery({
3986
- queryKey: calendarQueryKeys.appPasswords(),
3987
- queryFn: () => arbi.calendar.listAppPasswords(),
4495
+ queryKey: calendarQueryKeys.bookingPages(),
4496
+ queryFn: () => arbi.calendar.listBookingPages(),
3988
4497
  enabled: enabled && arbi.isLoggedIn,
3989
4498
  staleTime: 3e4,
3990
4499
  retry: false
3991
4500
  });
3992
4501
  }
3993
- function useInvalidateAppPasswords() {
3994
- const qc = useQueryClient();
3995
- return () => qc.invalidateQueries({ queryKey: calendarQueryKeys.appPasswords() });
3996
- }
3997
- function useCreateAppPassword() {
3998
- const arbi = useArbi();
3999
- const invalidate = useInvalidateAppPasswords();
4000
- return useMutation({
4001
- mutationFn: (body) => arbi.calendar.createAppPassword(body),
4002
- onSuccess: () => invalidate()
4003
- });
4004
- }
4005
- function useCreateFeed() {
4006
- const arbi = useArbi();
4007
- const invalidate = useInvalidateAppPasswords();
4008
- return useMutation({
4009
- mutationFn: (body) => arbi.calendar.createFeed(body),
4010
- onSuccess: () => invalidate()
4011
- });
4012
- }
4013
- function useRevokeAppPassword() {
4014
- const arbi = useArbi();
4015
- const invalidate = useInvalidateAppPasswords();
4016
- return useMutation({
4017
- mutationFn: (id) => arbi.calendar.revokeAppPassword(id),
4018
- onSuccess: () => invalidate()
4019
- });
4020
- }
4021
- function useBookingPages(enabled = true) {
4022
- const arbi = useArbi();
4023
- return useQuery({
4024
- queryKey: calendarQueryKeys.bookingPages(),
4025
- queryFn: () => arbi.calendar.listBookingPages(),
4026
- enabled: enabled && arbi.isLoggedIn,
4027
- staleTime: 3e4,
4028
- retry: false
4029
- });
4030
- }
4031
- function useSaveBookingPage() {
4032
- const arbi = useArbi();
4502
+ function useSaveBookingPage() {
4503
+ const arbi = useArbi();
4033
4504
  const qc = useQueryClient();
4034
4505
  return useMutation({
4035
4506
  mutationFn: (body) => arbi.calendar.putBookingPage(body),
@@ -4142,51 +4613,6 @@ function useAiTask() {
4142
4613
  isDone: status === "done"
4143
4614
  };
4144
4615
  }
4145
- function useSemanticSearch(docIds) {
4146
- const arbi = useArbi();
4147
- const [query, setQuery] = useState("");
4148
- const mutation = useMutation({
4149
- mutationFn: async ({ query: q, mode }) => {
4150
- const res = await arbi.assistant.retrieve(q, docIds, { searchMode: mode });
4151
- const byTool = res.retrieval_chunk?.tool_responses ?? {};
4152
- return Object.values(byTool).flat().map(
4153
- (c) => ({
4154
- chunkExtId: c.metadata.chunk_ext_id,
4155
- docId: c.metadata.doc_ext_id,
4156
- docTitle: c.metadata.doc_title,
4157
- page: c.metadata.page_number,
4158
- score: c.metadata.rerank_score ?? c.metadata.score,
4159
- content: c.content
4160
- })
4161
- ).sort((a, b) => (b.score ?? 0) - (a.score ?? 0));
4162
- }
4163
- });
4164
- const { mutateAsync, reset } = mutation;
4165
- const search = useCallback(
4166
- async (q, mode = "hybrid") => {
4167
- const trimmed = q.trim();
4168
- setQuery(trimmed);
4169
- if (!trimmed || docIds.length === 0) {
4170
- reset();
4171
- return;
4172
- }
4173
- try {
4174
- await mutateAsync({ query: trimmed, mode });
4175
- } catch {
4176
- }
4177
- },
4178
- [mutateAsync, reset, docIds]
4179
- );
4180
- const status = mutation.isPending ? "running" : mutation.isError ? "error" : mutation.isSuccess ? "done" : "idle";
4181
- return {
4182
- query,
4183
- results: mutation.data ?? [],
4184
- status,
4185
- error: mutation.error ? mutation.error.message ?? "Search failed." : null,
4186
- search,
4187
- isRunning: mutation.isPending
4188
- };
4189
- }
4190
4616
  function toRedlineMarkdown(original, revised) {
4191
4617
  const parts = diffWords(original ?? "", revised ?? "");
4192
4618
  return parts.map((p) => {
@@ -4590,6 +5016,75 @@ function MessageArtifactCard({
4590
5016
  }
4591
5017
  );
4592
5018
  }
5019
+ var IDLE = {
5020
+ query: "",
5021
+ results: [],
5022
+ searched: false,
5023
+ status: "idle",
5024
+ error: null
5025
+ };
5026
+ function useSemanticSearch(docIds = [], options = {}) {
5027
+ const arbi = useArbi();
5028
+ const [ownSession] = useState(createSearchSession);
5029
+ const session = options.session ?? ownSession;
5030
+ const { model, workspaceId } = options;
5031
+ const state = useSyncExternalStore(session.subscribe, session.getState, session.getState);
5032
+ const foreign = !!workspaceId && !!state.workspaceId && state.workspaceId !== workspaceId;
5033
+ useEffect(() => {
5034
+ if (!workspaceId) return;
5035
+ const current = session.getState().workspaceId;
5036
+ if (current !== workspaceId) {
5037
+ if (current) clearSearchSession(workspaceId, session);
5038
+ else session.setState({ workspaceId });
5039
+ }
5040
+ }, [session, workspaceId]);
5041
+ const search = useCallback(
5042
+ async (query, mode = "hybrid") => {
5043
+ const trimmed = query.trim();
5044
+ if (!trimmed) {
5045
+ clearSearchSession(void 0, session);
5046
+ return;
5047
+ }
5048
+ const run = session.getState().run + 1;
5049
+ session.setState((s) => ({
5050
+ query: trimmed,
5051
+ status: "running",
5052
+ error: null,
5053
+ run,
5054
+ workspaceId: workspaceId ?? s.workspaceId
5055
+ }));
5056
+ try {
5057
+ const result = await arbi.assistant.retrieve(trimmed, docIds, {
5058
+ searchMode: mode,
5059
+ store: false,
5060
+ ...model ? { model } : {}
5061
+ });
5062
+ if (session.getState().run !== run) return;
5063
+ session.setState({ results: searchChunks(result), searched: true, status: "done" });
5064
+ } catch (error) {
5065
+ if (session.getState().run !== run) return;
5066
+ session.setState({
5067
+ status: "error",
5068
+ error: error instanceof Error ? error.message : "Search failed"
5069
+ });
5070
+ }
5071
+ },
5072
+ [arbi, docIds, model, session, workspaceId]
5073
+ );
5074
+ const clear = useCallback(() => clearSearchSession(void 0, session), [session]);
5075
+ const shown = foreign ? IDLE : state;
5076
+ return {
5077
+ query: shown.query,
5078
+ results: shown.results,
5079
+ searched: shown.searched,
5080
+ status: shown.status,
5081
+ error: shown.error,
5082
+ isRunning: shown.status === "running",
5083
+ search,
5084
+ clear,
5085
+ session
5086
+ };
5087
+ }
4593
5088
  function DocSearch({
4594
5089
  docIds,
4595
5090
  onOpenDoc,
@@ -4597,437 +5092,71 @@ function DocSearch({
4597
5092
  className
4598
5093
  }) {
4599
5094
  const { results, status, error, search, isRunning, query } = useSemanticSearch(docIds);
4600
- const [value, setValue] = useState("");
4601
- const submit = () => {
4602
- if (value.trim()) void search(value, "hybrid");
4603
- };
4604
- return /* @__PURE__ */ jsxs("div", { className: cn("space-y-3", className), "data-testid": "doc-search", children: [
4605
- /* @__PURE__ */ jsxs("div", { className: "relative", children: [
4606
- /* @__PURE__ */ jsx(Search, { className: "pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" }),
4607
- isRunning && /* @__PURE__ */ jsx(Loader2, { className: "absolute right-3 top-1/2 size-4 -translate-y-1/2 animate-spin text-ai-accent" }),
4608
- /* @__PURE__ */ jsx(
4609
- "input",
4610
- {
4611
- value,
4612
- onChange: (e) => setValue(e.target.value),
4613
- onKeyDown: (e) => e.key === "Enter" && (e.preventDefault(), submit()),
4614
- placeholder,
4615
- className: "h-11 w-full rounded-lg border border-input bg-background pl-9 pr-24 text-sm outline-none focus:border-ai-accent/50 focus:ring-2 focus:ring-ai-accent/15",
4616
- "data-testid": "doc-search-input"
4617
- }
4618
- ),
4619
- /* @__PURE__ */ jsxs(
4620
- "button",
4621
- {
4622
- type: "button",
4623
- onClick: submit,
4624
- className: "absolute right-2 top-1/2 flex -translate-y-1/2 items-center gap-1 rounded-md bg-ai-accent px-2.5 py-1 text-xs font-medium text-ai-accent-foreground",
4625
- "data-testid": "doc-search-submit",
4626
- children: [
4627
- "Search ",
4628
- /* @__PURE__ */ jsx(CornerDownLeft, { className: "size-3" })
4629
- ]
4630
- }
4631
- )
4632
- ] }),
4633
- status === "error" && /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", "data-testid": "doc-search-error", children: error }),
4634
- status === "done" && /* @__PURE__ */ jsxs("div", { className: "space-y-2", "data-testid": "doc-search-results", children: [
4635
- /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: results.length === 0 ? `No passages matched \u201C${query}\u201D.` : `${results.length} passage${results.length === 1 ? "" : "s"} for \u201C${query}\u201D` }),
4636
- results.slice(0, 8).map((r, i) => /* @__PURE__ */ jsxs(
4637
- Card,
4638
- {
4639
- variant: "elevated",
4640
- className: cn(
4641
- "rounded-xl p-3",
4642
- onOpenDoc && r.docId && "cursor-pointer transition-colors hover:border-ai-accent/40"
4643
- ),
4644
- onClick: () => r.docId && onOpenDoc?.(r.docId),
4645
- "data-testid": `doc-search-hit-${i}`,
4646
- children: [
4647
- /* @__PURE__ */ jsxs("div", { className: "mb-1 flex items-center gap-2", children: [
4648
- /* @__PURE__ */ jsx(FileText, { className: "size-3.5 text-ai-accent" }),
4649
- /* @__PURE__ */ jsx("span", { className: "truncate text-xs font-medium text-foreground", children: r.docTitle ?? "Document" }),
4650
- r.page != null && /* @__PURE__ */ jsxs(Badge, { variant: "secondary", children: [
4651
- "p.",
4652
- r.page
4653
- ] }),
4654
- r.score != null && /* @__PURE__ */ jsxs("span", { className: "ml-auto text-xs text-muted-foreground", children: [
4655
- "score ",
4656
- r.score.toFixed(2)
4657
- ] })
4658
- ] }),
4659
- /* @__PURE__ */ jsx("p", { className: "line-clamp-3 text-xs leading-relaxed text-muted-foreground", children: r.content })
4660
- ]
4661
- },
4662
- `${r.docId}-${r.page}-${i}`
4663
- ))
4664
- ] })
4665
- ] });
4666
- }
4667
- function DocumentReview({
4668
- docId,
4669
- doc,
4670
- workspaceId,
4671
- stage = "final",
4672
- activeChunkId,
4673
- onClose,
4674
- className
4675
- }) {
4676
- const parsedQuery = useParsedDocument(docId, stage);
4677
- const tagsQuery = useTags(workspaceId);
4678
- const tagNameById = React.useMemo(() => {
4679
- const map = /* @__PURE__ */ new Map();
4680
- for (const t of tagsQuery.data ?? []) {
4681
- if (t.external_id) map.set(t.external_id, t.name ?? t.external_id.slice(0, 8));
4682
- }
4683
- return map;
4684
- }, [tagsQuery.data]);
4685
- const title = doc?.doc_metadata?.title || doc?.file_name || "Document";
4686
- const { findings, chunkToTag } = React.useMemo(() => {
4687
- const list = [];
4688
- const chunkTag = /* @__PURE__ */ new Map();
4689
- for (const dt of doc?.doctags ?? []) {
4690
- const chunkIds = (dt.citations ?? []).flatMap((d) => (d.chunks ?? []).map((c) => c.chunk_id));
4691
- if (chunkIds.length === 0) continue;
4692
- list.push({
4693
- key: dt.tag_ext_id,
4694
- tagExtId: dt.tag_ext_id,
4695
- statement: dt.note ?? "",
4696
- chunkIds
4697
- });
4698
- for (const cid of chunkIds) if (!chunkTag.has(cid)) chunkTag.set(cid, dt.tag_ext_id);
4699
- }
4700
- return { findings: list, chunkToTag: chunkTag };
4701
- }, [doc?.doctags]);
4702
- const pages = React.useMemo(() => {
4703
- const chunks = parsedQuery.data?.chunks ?? [];
4704
- const byPage = /* @__PURE__ */ new Map();
4705
- for (const c of chunks) {
4706
- const p = c.metadata?.page_number ?? 0;
4707
- if (!byPage.has(p)) byPage.set(p, []);
4708
- byPage.get(p).push(c);
4709
- }
4710
- return [...byPage.entries()].sort((a, b) => a[0] - b[0]);
4711
- }, [parsedQuery.data]);
4712
- const scrollRef = React.useRef(null);
4713
- const [flash, setFlash] = React.useState(null);
4714
- const jumpToChunk = React.useCallback((chunkId) => {
4715
- const el = scrollRef.current?.querySelector(`[data-chunk-id="${chunkId}"]`);
4716
- if (!el) return;
4717
- el.scrollIntoView({ behavior: "smooth", block: "center" });
4718
- setFlash(chunkId);
4719
- window.setTimeout(() => setFlash((c) => c === chunkId ? null : c), 1600);
4720
- }, []);
4721
- const parsedReady = !parsedQuery.isLoading && !!parsedQuery.data;
4722
- React.useEffect(() => {
4723
- if (!activeChunkId || !parsedReady) return;
4724
- const raf = window.requestAnimationFrame(() => jumpToChunk(activeChunkId));
4725
- return () => window.cancelAnimationFrame(raf);
4726
- }, [activeChunkId, parsedReady, jumpToChunk]);
4727
- return /* @__PURE__ */ jsxs(
4728
- "div",
4729
- {
4730
- "data-testid": "document-review",
4731
- className: cn(
4732
- "flex h-full min-h-0 flex-col overflow-hidden rounded-lg border bg-card",
4733
- className
4734
- ),
4735
- children: [
4736
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3 border-b px-4 py-3", children: [
4737
- /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
4738
- /* @__PURE__ */ jsx("div", { className: "truncate text-sm font-semibold", title, children: title }),
4739
- /* @__PURE__ */ jsxs("div", { className: "text-xs text-muted-foreground", children: [
4740
- parsedQuery.data?.metadata?.total_number_of_pages ? `${parsedQuery.data.metadata.total_number_of_pages} pages` : `${pages.length} pages`,
4741
- findings.length ? ` \xB7 ${findings.length} findings` : ""
4742
- ] })
4743
- ] }),
4744
- doc?.status ? /* @__PURE__ */ jsx(Badge, { variant: "secondary", children: doc.status }) : null,
4745
- onClose ? /* @__PURE__ */ jsx(
4746
- "button",
4747
- {
4748
- type: "button",
4749
- "aria-label": "Close review",
4750
- "data-testid": "document-review-close",
4751
- onClick: onClose,
4752
- className: "rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground",
4753
- children: /* @__PURE__ */ jsx(X, { className: "size-4" })
4754
- }
4755
- ) : null
4756
- ] }),
4757
- /* @__PURE__ */ jsxs("div", { className: "flex min-h-0 flex-1", children: [
4758
- findings.length > 0 ? /* @__PURE__ */ jsxs(
4759
- "aside",
4760
- {
4761
- className: "hidden w-64 shrink-0 overflow-y-auto border-r p-3 md:block",
4762
- "data-testid": "document-review-findings",
4763
- children: [
4764
- /* @__PURE__ */ jsx("div", { className: "mb-2 text-xs font-medium uppercase tracking-wide text-muted-foreground", children: "AI findings" }),
4765
- /* @__PURE__ */ jsx("ul", { className: "space-y-2", children: findings.map((f) => /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsxs(
4766
- "div",
4767
- {
4768
- role: "button",
4769
- tabIndex: 0,
4770
- "data-testid": "review-finding",
4771
- onClick: () => jumpToChunk(f.chunkIds[0]),
4772
- onKeyDown: (e) => {
4773
- if (e.key === "Enter" || e.key === " ") {
4774
- e.preventDefault();
4775
- jumpToChunk(f.chunkIds[0]);
4776
- }
4777
- },
4778
- className: "w-full cursor-pointer rounded-md border p-2 text-left text-xs transition hover:border-ring hover:bg-muted/50 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring",
4779
- children: [
4780
- /* @__PURE__ */ jsx(
4781
- TagEntity,
4782
- {
4783
- size: "sm",
4784
- tag: {
4785
- external_id: f.tagExtId,
4786
- name: tagNameById.get(f.tagExtId) ?? f.tagExtId.slice(0, 8)
4787
- }
4788
- }
4789
- ),
4790
- /* @__PURE__ */ jsx("p", { className: "mt-1 line-clamp-3 text-muted-foreground", children: f.statement })
4791
- ]
4792
- }
4793
- ) }, f.key)) })
4794
- ]
4795
- }
4796
- ) : null,
4797
- /* @__PURE__ */ jsx("div", { ref: scrollRef, className: "min-w-0 flex-1 overflow-y-auto px-6 py-4", children: parsedQuery.isLoading ? /* @__PURE__ */ jsx("div", { className: "flex h-full items-center justify-center text-sm text-muted-foreground", children: "Loading document\u2026" }) : parsedQuery.isError ? /* @__PURE__ */ jsx("div", { className: "flex h-full items-center justify-center text-sm text-muted-foreground", children: "Could not load this document\u2019s content." }) : pages.length === 0 ? /* @__PURE__ */ jsx("div", { className: "flex h-full items-center justify-center text-sm text-muted-foreground", children: "No readable content." }) : /* @__PURE__ */ jsx("div", { className: "mx-auto max-w-3xl space-y-8", children: pages.map(([pageNum, chunks]) => /* @__PURE__ */ jsxs("section", { children: [
4798
- /* @__PURE__ */ jsxs("div", { className: "mb-3 flex items-center gap-3", children: [
4799
- /* @__PURE__ */ jsxs("span", { className: "text-xs font-medium uppercase tracking-wide text-muted-foreground", children: [
4800
- "Page ",
4801
- pageNum
4802
- ] }),
4803
- /* @__PURE__ */ jsx("div", { className: "h-px flex-1 bg-border" })
4804
- ] }),
4805
- /* @__PURE__ */ jsx("div", { className: "space-y-3", children: chunks.map((c, i) => {
4806
- const cid = c.metadata?.chunk_ext_id;
4807
- const tagExtId = cid ? chunkToTag.get(cid) : void 0;
4808
- const highlighted = !!tagExtId;
4809
- const isActive = !!cid && cid === activeChunkId;
4810
- return /* @__PURE__ */ jsxs(
4811
- "div",
4812
- {
4813
- "data-chunk-id": cid,
4814
- "data-testid": isActive ? "review-chunk-active" : highlighted ? "review-chunk-cited" : "review-chunk",
4815
- className: cn(
4816
- "scroll-mt-4 rounded-md px-2 py-1 transition-colors",
4817
- highlighted && "bg-[var(--color-ai-accent-soft,theme(colors.amber.100))] ring-1 ring-inset ring-border",
4818
- // The externally-selected search passage wins the
4819
- // styling: a stronger accent ring so the matched
4820
- // hit stands out from any AI-finding highlights.
4821
- isActive && "bg-[var(--color-ai-accent-soft,theme(colors.amber.100))] ring-2 ring-inset ring-ai-accent",
4822
- flash === cid && "ring-2 ring-ring"
4823
- ),
4824
- children: [
4825
- highlighted ? /* @__PURE__ */ jsx("div", { className: "mb-1", children: /* @__PURE__ */ jsx(
4826
- TagEntity,
4827
- {
4828
- size: "sm",
4829
- tag: {
4830
- external_id: tagExtId,
4831
- name: tagNameById.get(tagExtId) ?? tagExtId.slice(0, 8)
4832
- }
4833
- }
4834
- ) }) : null,
4835
- /* @__PURE__ */ jsx(MarkdownRenderer, { className: "prose prose-sm max-w-none dark:prose-invert", children: c.content })
4836
- ]
4837
- },
4838
- cid ?? i
4839
- );
4840
- }) })
4841
- ] }, pageNum)) }) })
4842
- ] })
4843
- ]
4844
- }
4845
- );
4846
- }
4847
- function queryTerms(query) {
4848
- const terms = /* @__PURE__ */ new Set();
4849
- for (const phrase of query.match(/"([^"]+)"/g) ?? []) {
4850
- const inner = phrase.slice(1, -1).trim();
4851
- if (inner) terms.add(inner);
4852
- }
4853
- for (const word of query.replace(/"/g, " ").split(/\s+/)) {
4854
- if (word.length > 2) terms.add(word);
4855
- }
4856
- return [...terms];
4857
- }
4858
- function HighlightedSnippet({ text, terms }) {
4859
- const nodes = useMemo(() => {
4860
- if (terms.length === 0) return [text];
4861
- const escaped = terms.map((t) => t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
4862
- const re = new RegExp(`(${escaped.join("|")})`, "gi");
4863
- return text.split(re).map((part, i) => i % 2 === 1 ? /* @__PURE__ */ jsx("mark", { children: part }, i) : part);
4864
- }, [text, terms]);
4865
- return /* @__PURE__ */ jsx(Fragment, { children: nodes });
4866
- }
4867
- function ResultRow({
4868
- result,
4869
- index,
4870
- terms,
4871
- isActive,
4872
- onSelect
4873
- }) {
4874
- return /* @__PURE__ */ jsx(
4875
- PassageCard,
4876
- {
4877
- onClick: onSelect,
4878
- active: isActive,
4879
- score: result.score,
4880
- "data-testid": `arbi-semantic-search-result-${index}`,
4881
- header: /* @__PURE__ */ jsxs(Fragment, { children: [
4882
- /* @__PURE__ */ jsx(FileText, { className: "size-3.5 shrink-0 text-ai-accent" }),
4883
- /* @__PURE__ */ jsx("span", { className: "truncate text-xs font-medium text-foreground", children: result.docTitle ?? "Document" }),
4884
- result.page != null && /* @__PURE__ */ jsxs(Badge, { variant: "secondary", children: [
4885
- "p.",
4886
- result.page
4887
- ] })
4888
- ] }),
4889
- children: /* @__PURE__ */ jsxs("p", { className: "line-clamp-3 text-xs leading-relaxed text-muted-foreground", children: [
4890
- /* @__PURE__ */ jsx("span", { className: "text-muted-foreground/60", children: "\u2026 " }),
4891
- /* @__PURE__ */ jsx(HighlightedSnippet, { text: result.content, terms }),
4892
- /* @__PURE__ */ jsx("span", { className: "text-muted-foreground/60", children: " \u2026" })
4893
- ] })
4894
- }
4895
- );
4896
- }
4897
- function SemanticSearch({
4898
- docIds,
4899
- workspaceId,
4900
- searchMode = "hybrid",
4901
- placeholder = "Search your documents by meaning\u2026",
4902
- className,
4903
- "data-testid": testId = "arbi-semantic-search"
4904
- }) {
4905
- const { results, status, error, search, isRunning, query } = useSemanticSearch(docIds);
4906
- const [value, setValue] = useState("");
4907
- const [selected, setSelected] = useState(null);
4908
- const { data: docs = [] } = useDocuments(workspaceId, { enabled: !!workspaceId });
4909
- const docMap = useMemo(() => {
4910
- const map = /* @__PURE__ */ new Map();
4911
- for (const d of docs) if (d.external_id) map.set(d.external_id, d);
4912
- return map;
4913
- }, [docs]);
4914
- const terms = useMemo(() => queryTerms(query), [query]);
4915
- const submit = useCallback(() => {
4916
- const q = value.trim();
4917
- if (!q) return;
4918
- setSelected(null);
4919
- void search(q, searchMode);
4920
- }, [value, search, searchMode]);
4921
- const selectedDoc = selected?.docId ? docMap.get(selected.docId) : void 0;
4922
- const hasResults = status === "done" && results.length > 0;
4923
- return /* @__PURE__ */ jsxs("div", { "data-testid": testId, className: cn("flex min-h-0 flex-col gap-4 md:flex-row", className), children: [
4924
- /* @__PURE__ */ jsxs(
4925
- "div",
4926
- {
4927
- className: cn(
4928
- "flex min-h-0 flex-col gap-3 md:w-[22rem] md:shrink-0",
4929
- selected && "hidden md:flex"
4930
- ),
4931
- children: [
4932
- /* @__PURE__ */ jsxs("div", { className: "relative", children: [
4933
- /* @__PURE__ */ jsx(Search, { className: "pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" }),
4934
- isRunning && /* @__PURE__ */ jsx(Loader2, { className: "absolute right-3 top-1/2 size-4 -translate-y-1/2 animate-spin text-ai-accent" }),
4935
- /* @__PURE__ */ jsx(
4936
- "input",
4937
- {
4938
- value,
4939
- onChange: (e) => setValue(e.target.value),
4940
- onKeyDown: (e) => e.key === "Enter" && (e.preventDefault(), submit()),
4941
- placeholder,
4942
- "aria-label": "Semantic search query",
4943
- className: "h-11 w-full rounded-lg border border-input bg-background pl-9 pr-24 text-sm outline-none focus:border-ai-accent/50 focus:ring-2 focus:ring-ai-accent/15",
4944
- "data-testid": "arbi-semantic-search-input"
4945
- }
4946
- ),
4947
- /* @__PURE__ */ jsxs(
4948
- "button",
4949
- {
4950
- type: "button",
4951
- onClick: submit,
4952
- disabled: !value.trim() || isRunning,
4953
- className: "absolute right-2 top-1/2 flex -translate-y-1/2 items-center gap-1 rounded-md bg-ai-accent px-2.5 py-1 text-xs font-medium text-ai-accent-foreground disabled:opacity-50",
4954
- "data-testid": "arbi-semantic-search-submit",
4955
- children: [
4956
- "Search ",
4957
- /* @__PURE__ */ jsx(CornerDownLeft, { className: "size-3" })
4958
- ]
4959
- }
4960
- )
4961
- ] }),
4962
- status === "error" && /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", "data-testid": "arbi-semantic-search-error", children: error }),
4963
- status === "done" && /* @__PURE__ */ jsxs(
4964
- "div",
4965
- {
4966
- className: "flex min-h-0 flex-col gap-2 overflow-y-auto",
4967
- "data-testid": "arbi-semantic-search-results",
4968
- children: [
4969
- /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: results.length === 0 ? `No passages matched \u201C${query}\u201D.` : `${results.length} passage${results.length === 1 ? "" : "s"} for \u201C${query}\u201D` }),
4970
- results.map((r, i) => /* @__PURE__ */ jsx(
4971
- ResultRow,
4972
- {
4973
- result: r,
4974
- index: i,
4975
- terms,
4976
- isActive: selected?.chunkExtId != null && selected.chunkExtId === r.chunkExtId,
4977
- onSelect: () => setSelected(r)
4978
- },
4979
- r.chunkExtId ?? `${r.docId}-${r.page}-${i}`
4980
- ))
4981
- ]
4982
- }
4983
- )
4984
- ]
4985
- }
4986
- ),
4987
- /* @__PURE__ */ jsx(
4988
- "div",
4989
- {
4990
- className: cn("min-h-0 min-w-0 flex-1", !selected && "hidden md:block"),
4991
- "data-testid": "arbi-semantic-search-viewer",
4992
- children: selected && selected.docId ? /* @__PURE__ */ jsxs("div", { className: "flex h-full min-h-0 flex-col gap-2", children: [
4993
- /* @__PURE__ */ jsxs(
4994
- Button,
4995
- {
4996
- variant: "ghost",
4997
- size: "sm",
4998
- className: "self-start md:hidden",
4999
- onClick: () => setSelected(null),
5000
- "data-testid": "arbi-semantic-search-back",
5001
- children: [
5002
- /* @__PURE__ */ jsx(ArrowLeft, { className: "size-4" }),
5003
- " Back to results"
5004
- ]
5005
- }
5095
+ const [value, setValue] = useState("");
5096
+ const submit = () => {
5097
+ if (value.trim()) void search(value, "hybrid");
5098
+ };
5099
+ return /* @__PURE__ */ jsxs("div", { className: cn("space-y-3", className), "data-testid": "doc-search", children: [
5100
+ /* @__PURE__ */ jsxs("div", { className: "relative", children: [
5101
+ /* @__PURE__ */ jsx(Search, { className: "pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" }),
5102
+ isRunning && /* @__PURE__ */ jsx(Loader2, { className: "absolute right-3 top-1/2 size-4 -translate-y-1/2 animate-spin text-ai-accent" }),
5103
+ /* @__PURE__ */ jsx(
5104
+ "input",
5105
+ {
5106
+ value,
5107
+ onChange: (e) => setValue(e.target.value),
5108
+ onKeyDown: (e) => e.key === "Enter" && (e.preventDefault(), submit()),
5109
+ placeholder,
5110
+ className: "h-11 w-full rounded-lg border border-input bg-background pl-9 pr-24 text-sm outline-none focus:border-ai-accent/50 focus:ring-2 focus:ring-ai-accent/15",
5111
+ "data-testid": "doc-search-input"
5112
+ }
5113
+ ),
5114
+ /* @__PURE__ */ jsxs(
5115
+ "button",
5116
+ {
5117
+ type: "button",
5118
+ onClick: submit,
5119
+ className: "absolute right-2 top-1/2 flex -translate-y-1/2 items-center gap-1 rounded-md bg-ai-accent px-2.5 py-1 text-xs font-medium text-ai-accent-foreground",
5120
+ "data-testid": "doc-search-submit",
5121
+ children: [
5122
+ "Search ",
5123
+ /* @__PURE__ */ jsx(CornerDownLeft, { className: "size-3" })
5124
+ ]
5125
+ }
5126
+ )
5127
+ ] }),
5128
+ status === "error" && /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", "data-testid": "doc-search-error", children: error }),
5129
+ status === "done" && /* @__PURE__ */ jsxs("div", { className: "space-y-2", "data-testid": "doc-search-results", children: [
5130
+ /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: results.length === 0 ? `No passages matched \u201C${query}\u201D.` : `${results.length} passage${results.length === 1 ? "" : "s"} for \u201C${query}\u201D` }),
5131
+ results.slice(0, 8).map((r, i) => /* @__PURE__ */ jsxs(
5132
+ Card,
5133
+ {
5134
+ variant: "elevated",
5135
+ className: cn(
5136
+ "rounded-xl p-3",
5137
+ onOpenDoc && r.docId && "cursor-pointer transition-colors hover:border-ai-accent/40"
5006
5138
  ),
5007
- /* @__PURE__ */ jsx(
5008
- DocumentReview,
5009
- {
5010
- docId: selected.docId,
5011
- doc: selectedDoc,
5012
- workspaceId,
5013
- activeChunkId: selected.chunkExtId ?? void 0,
5014
- className: "min-h-0 flex-1"
5015
- },
5016
- selected.docId
5017
- )
5018
- ] }) : /* @__PURE__ */ jsx(
5019
- "div",
5020
- {
5021
- className: "flex h-full min-h-[16rem] items-center justify-center rounded-lg border border-dashed border-border bg-muted/20 p-8 text-center",
5022
- "data-testid": "arbi-semantic-search-empty",
5023
- children: /* @__PURE__ */ jsxs("div", { className: "max-w-xs", children: [
5024
- /* @__PURE__ */ jsx(Search, { className: "mx-auto mb-3 size-6 text-muted-foreground/50" }),
5025
- /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: hasResults ? "Select a passage to open the document alongside, scrolled to the match." : "Search across the record \u2014 every hit is a real, cited passage you can open in place." })
5026
- ] })
5027
- }
5028
- )
5029
- }
5030
- )
5139
+ onClick: () => r.docId && onOpenDoc?.(r.docId),
5140
+ "data-testid": `doc-search-hit-${i}`,
5141
+ children: [
5142
+ /* @__PURE__ */ jsxs("div", { className: "mb-1 flex items-center gap-2", children: [
5143
+ /* @__PURE__ */ jsx(FileText, { className: "size-3.5 text-ai-accent" }),
5144
+ /* @__PURE__ */ jsx("span", { className: "truncate text-xs font-medium text-foreground", children: r.docTitle || "Document" }),
5145
+ r.page != null && /* @__PURE__ */ jsxs(Badge, { variant: "secondary", children: [
5146
+ "p.",
5147
+ r.page
5148
+ ] }),
5149
+ r.score > 0 && /* @__PURE__ */ jsxs("span", { className: "ml-auto text-xs text-muted-foreground", children: [
5150
+ "score ",
5151
+ r.score.toFixed(2)
5152
+ ] })
5153
+ ] }),
5154
+ /* @__PURE__ */ jsx("p", { className: "line-clamp-3 text-xs leading-relaxed text-muted-foreground", children: r.content })
5155
+ ]
5156
+ },
5157
+ `${r.docId}-${r.page}-${i}`
5158
+ ))
5159
+ ] })
5031
5160
  ] });
5032
5161
  }
5033
5162
  function DocQaPanel({ docId, docName }) {
@@ -5478,7 +5607,7 @@ var CitationLink = ({
5478
5607
  ]
5479
5608
  }
5480
5609
  );
5481
- var CitationRenderer = React.memo(CitationRendererComponent);
5610
+ var CitationRenderer = React3.memo(CitationRendererComponent);
5482
5611
  var FileIcon = ({ size = 16, className = "" }) => {
5483
5612
  return /* @__PURE__ */ jsxs(
5484
5613
  "svg",
@@ -6116,6 +6245,7 @@ function notificationUserName(user) {
6116
6245
  return [user.given_name, user.family_name].filter(Boolean).join(" ") || user.email;
6117
6246
  }
6118
6247
  var CONVERSATION_ID = /^con-[a-zA-Z0-9]+$/;
6248
+ var WORKFLOW_ID = /^wfl-[a-zA-Z0-9]+$/;
6119
6249
  var DOCUMENT_ID = /^doc-[a-zA-Z0-9]+$/;
6120
6250
  function parse(content) {
6121
6251
  try {
@@ -6244,6 +6374,14 @@ function conversationTarget(n) {
6244
6374
  ...n.message_ext_id ? { messageId: n.message_ext_id } : {}
6245
6375
  };
6246
6376
  }
6377
+ function workflowTarget(n) {
6378
+ const workflowId = parse(n.content)?.workflow_ext_id;
6379
+ return {
6380
+ kind: "workflows",
6381
+ ...typeof workflowId === "string" && WORKFLOW_ID.test(workflowId) ? { workflowId } : {},
6382
+ ...n.workspace_ext_id ? { workspaceId: n.workspace_ext_id } : {}
6383
+ };
6384
+ }
6247
6385
  function signatureTitle(n, senderName, documentName) {
6248
6386
  const type = n.type;
6249
6387
  const { documentId } = signatureRequestMeta(n.content);
@@ -6409,22 +6547,14 @@ function describeServerNotification(n, options = {}) {
6409
6547
  variant: "success",
6410
6548
  target: conversationTarget(n)
6411
6549
  };
6412
- case "workflow_completed": {
6413
- const workflowId = parse(n.content)?.workflow_ext_id;
6414
- return {
6415
- title: "A workflow completed",
6416
- variant: "success",
6417
- target: {
6418
- kind: "workflows",
6419
- ...typeof workflowId === "string" ? { workflowId } : {}
6420
- }
6421
- };
6422
- }
6550
+ case "workflow_completed":
6551
+ return { title: "A workflow completed", variant: "success", target: workflowTarget(n) };
6552
+ // The failed run's thread when it has one (its error is there), else the workflow.
6423
6553
  case "workflow_failed":
6424
6554
  return {
6425
6555
  title: "A workflow failed to start",
6426
6556
  variant: "error",
6427
- target: { kind: "workflows" }
6557
+ target: conversationTarget(n) ?? workflowTarget(n)
6428
6558
  };
6429
6559
  case "deployment_user_invited":
6430
6560
  case "deployment_user_registered": {
@@ -7715,10 +7845,18 @@ function CommandPaletteProvider({
7715
7845
  }
7716
7846
 
7717
7847
  // src/session/store.ts
7848
+ var DEFAULT_DOCUMENT_VIEWER_STATE = {
7849
+ tab: "pdf",
7850
+ compareId: null,
7851
+ tabRequest: null,
7852
+ textScale: 1,
7853
+ phonePdfChosen: false
7854
+ };
7718
7855
  var EMPTY_SESSION_STATE = {
7719
7856
  workspaceId: null,
7720
7857
  conversationId: null,
7721
7858
  viewingDocument: null,
7859
+ documentViewer: DEFAULT_DOCUMENT_VIEWER_STATE,
7722
7860
  selectedDocumentIds: [],
7723
7861
  generating: {},
7724
7862
  paMode: false,
@@ -7755,6 +7893,12 @@ function createArbiSessionStore(initial = {}) {
7755
7893
  if (state.conversationId !== conversationId) update({ conversationId });
7756
7894
  },
7757
7895
  setViewingDocument: (input) => update({ viewingDocument: nextViewingDocument(state.viewingDocument, input) }),
7896
+ setDocumentViewer: (change) => {
7897
+ const next = { ...state.documentViewer, ...change };
7898
+ const keys = Object.keys(change);
7899
+ if (keys.some((key) => next[key] !== state.documentViewer[key]))
7900
+ update({ documentViewer: next });
7901
+ },
7758
7902
  setSelectedDocumentIds: (ids) => update({ selectedDocumentIds: ids }),
7759
7903
  setConversationGenerating: (conversationId, isGenerating) => {
7760
7904
  const current = state.generating[conversationId];
@@ -7833,7 +7977,7 @@ function DocumentTable({
7833
7977
  const rows = documents ?? query.data ?? [];
7834
7978
  const isLoading = !documents && query.isLoading;
7835
7979
  const tagsQuery = useTags(workspaceId);
7836
- const tagNameById = React.useMemo(() => {
7980
+ const tagNameById = React3.useMemo(() => {
7837
7981
  const map = /* @__PURE__ */ new Map();
7838
7982
  for (const t of tagsQuery.data ?? []) {
7839
7983
  if (t.external_id) map.set(t.external_id, t.name ?? t.external_id.slice(0, 8));
@@ -7846,15 +7990,15 @@ function DocumentTable({
7846
7990
  const viewingDocId = useArbiSessionState(selectViewingDocumentId);
7847
7991
  const effectiveSelected = selectedIds ?? storeSelected;
7848
7992
  const emitSelection = onSelectionChange ?? storeSetSelected;
7849
- const gridApiRef = React.useRef(null);
7850
- const openDocument = React.useCallback(
7993
+ const gridApiRef = React3.useRef(null);
7994
+ const openDocument = React3.useCallback(
7851
7995
  (id) => {
7852
7996
  session.setViewingDocument({ id });
7853
7997
  onOpenDocument?.(id);
7854
7998
  },
7855
7999
  [onOpenDocument, session]
7856
8000
  );
7857
- const applySelection = React.useCallback(() => {
8001
+ const applySelection = React3.useCallback(() => {
7858
8002
  const api = gridApiRef.current;
7859
8003
  if (!api) return;
7860
8004
  const wanted = new Set(effectiveSelected);
@@ -7864,10 +8008,10 @@ function DocumentTable({
7864
8008
  if (node.isSelected() !== shouldSelect) node.setSelected(shouldSelect);
7865
8009
  });
7866
8010
  }, [effectiveSelected]);
7867
- React.useEffect(() => {
8011
+ React3.useEffect(() => {
7868
8012
  applySelection();
7869
8013
  }, [applySelection]);
7870
- const columnDefs = React.useMemo(
8014
+ const columnDefs = React3.useMemo(
7871
8015
  () => [
7872
8016
  {
7873
8017
  colId: "select",
@@ -7975,7 +8119,7 @@ function DocumentTable({
7975
8119
  const id = e.data?.external_id;
7976
8120
  if (id) openDocument(id);
7977
8121
  };
7978
- const getRowId = React.useCallback((params) => params.data.external_id, []);
8122
+ const getRowId = React3.useCallback((params) => params.data.external_id, []);
7979
8123
  const autoHeight = height === "auto";
7980
8124
  const style = autoHeight ? {} : { height: typeof height === "number" ? `${height}px` : height, width: "100%" };
7981
8125
  if (isLoading) {
@@ -8106,14 +8250,14 @@ function DocumentGallery({
8106
8250
  const rows = documents ?? query.data ?? [];
8107
8251
  const isLoading = !documents && query.isLoading;
8108
8252
  const tagsQuery = useTags(workspaceId);
8109
- const tagNameById = React.useMemo(() => {
8253
+ const tagNameById = React3.useMemo(() => {
8110
8254
  const map = /* @__PURE__ */ new Map();
8111
8255
  for (const t of tagsQuery.data ?? []) {
8112
8256
  if (t.external_id) map.set(t.external_id, t.name ?? t.external_id.slice(0, 8));
8113
8257
  }
8114
8258
  return map;
8115
8259
  }, [tagsQuery.data]);
8116
- const docIds = React.useMemo(
8260
+ const docIds = React3.useMemo(
8117
8261
  () => rows.map((d) => d.external_id).filter((id) => !!id),
8118
8262
  [rows]
8119
8263
  );
@@ -8125,8 +8269,8 @@ function DocumentGallery({
8125
8269
  const viewingDocId = useArbiSessionState(selectViewingDocumentId);
8126
8270
  const effectiveSelected = selectedIds ?? storeSelected;
8127
8271
  const emitSelection = onSelectionChange ?? storeSetSelected;
8128
- const selectedSet = React.useMemo(() => new Set(effectiveSelected), [effectiveSelected]);
8129
- const toggleSelected = React.useCallback(
8272
+ const selectedSet = React3.useMemo(() => new Set(effectiveSelected), [effectiveSelected]);
8273
+ const toggleSelected = React3.useCallback(
8130
8274
  (id) => {
8131
8275
  const next = new Set(effectiveSelected);
8132
8276
  if (next.has(id)) next.delete(id);
@@ -8135,14 +8279,14 @@ function DocumentGallery({
8135
8279
  },
8136
8280
  [effectiveSelected, emitSelection]
8137
8281
  );
8138
- const openDocument = React.useCallback(
8282
+ const openDocument = React3.useCallback(
8139
8283
  (id) => {
8140
8284
  session.setViewingDocument({ id });
8141
8285
  onOpenDocument?.(id);
8142
8286
  },
8143
8287
  [onOpenDocument, session]
8144
8288
  );
8145
- const [renamingId, setRenamingId] = React.useState(null);
8289
+ const [renamingId, setRenamingId] = React3.useState(null);
8146
8290
  const update = useUpdateDocuments();
8147
8291
  const rename = (doc, title) => update.mutate(
8148
8292
  {
@@ -8217,6 +8361,186 @@ function DocumentGallery({
8217
8361
  }
8218
8362
  );
8219
8363
  }
8364
+ function DocumentReview({
8365
+ docId,
8366
+ doc,
8367
+ workspaceId,
8368
+ stage = "final",
8369
+ activeChunkId,
8370
+ onClose,
8371
+ className
8372
+ }) {
8373
+ const parsedQuery = useParsedDocument(docId, stage);
8374
+ const tagsQuery = useTags(workspaceId);
8375
+ const tagNameById = React3.useMemo(() => {
8376
+ const map = /* @__PURE__ */ new Map();
8377
+ for (const t of tagsQuery.data ?? []) {
8378
+ if (t.external_id) map.set(t.external_id, t.name ?? t.external_id.slice(0, 8));
8379
+ }
8380
+ return map;
8381
+ }, [tagsQuery.data]);
8382
+ const title = doc?.doc_metadata?.title || doc?.file_name || "Document";
8383
+ const { findings, chunkToTag } = React3.useMemo(() => {
8384
+ const list = [];
8385
+ const chunkTag = /* @__PURE__ */ new Map();
8386
+ for (const dt of doc?.doctags ?? []) {
8387
+ const chunkIds = (dt.citations ?? []).flatMap((d) => (d.chunks ?? []).map((c) => c.chunk_id));
8388
+ if (chunkIds.length === 0) continue;
8389
+ list.push({
8390
+ key: dt.tag_ext_id,
8391
+ tagExtId: dt.tag_ext_id,
8392
+ statement: dt.note ?? "",
8393
+ chunkIds
8394
+ });
8395
+ for (const cid of chunkIds) if (!chunkTag.has(cid)) chunkTag.set(cid, dt.tag_ext_id);
8396
+ }
8397
+ return { findings: list, chunkToTag: chunkTag };
8398
+ }, [doc?.doctags]);
8399
+ const pages = React3.useMemo(() => {
8400
+ const chunks = parsedQuery.data?.chunks ?? [];
8401
+ const byPage = /* @__PURE__ */ new Map();
8402
+ for (const c of chunks) {
8403
+ const p = c.metadata?.page_number ?? 0;
8404
+ if (!byPage.has(p)) byPage.set(p, []);
8405
+ byPage.get(p).push(c);
8406
+ }
8407
+ return [...byPage.entries()].sort((a, b) => a[0] - b[0]);
8408
+ }, [parsedQuery.data]);
8409
+ const scrollRef = React3.useRef(null);
8410
+ const [flash, setFlash] = React3.useState(null);
8411
+ const jumpToChunk = React3.useCallback((chunkId) => {
8412
+ const el = scrollRef.current?.querySelector(`[data-chunk-id="${chunkId}"]`);
8413
+ if (!el) return;
8414
+ el.scrollIntoView({ behavior: "smooth", block: "center" });
8415
+ setFlash(chunkId);
8416
+ window.setTimeout(() => setFlash((c) => c === chunkId ? null : c), 1600);
8417
+ }, []);
8418
+ const parsedReady = !parsedQuery.isLoading && !!parsedQuery.data;
8419
+ React3.useEffect(() => {
8420
+ if (!activeChunkId || !parsedReady) return;
8421
+ const raf = window.requestAnimationFrame(() => jumpToChunk(activeChunkId));
8422
+ return () => window.cancelAnimationFrame(raf);
8423
+ }, [activeChunkId, parsedReady, jumpToChunk]);
8424
+ return /* @__PURE__ */ jsxs(
8425
+ "div",
8426
+ {
8427
+ "data-testid": "document-review",
8428
+ className: cn(
8429
+ "flex h-full min-h-0 flex-col overflow-hidden rounded-lg border bg-card",
8430
+ className
8431
+ ),
8432
+ children: [
8433
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3 border-b px-4 py-3", children: [
8434
+ /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
8435
+ /* @__PURE__ */ jsx("div", { className: "truncate text-sm font-semibold", title, children: title }),
8436
+ /* @__PURE__ */ jsxs("div", { className: "text-xs text-muted-foreground", children: [
8437
+ parsedQuery.data?.metadata?.total_number_of_pages ? `${parsedQuery.data.metadata.total_number_of_pages} pages` : `${pages.length} pages`,
8438
+ findings.length ? ` \xB7 ${findings.length} findings` : ""
8439
+ ] })
8440
+ ] }),
8441
+ doc?.status ? /* @__PURE__ */ jsx(Badge, { variant: "secondary", children: doc.status }) : null,
8442
+ onClose ? /* @__PURE__ */ jsx(
8443
+ "button",
8444
+ {
8445
+ type: "button",
8446
+ "aria-label": "Close review",
8447
+ "data-testid": "document-review-close",
8448
+ onClick: onClose,
8449
+ className: "rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground",
8450
+ children: /* @__PURE__ */ jsx(X, { className: "size-4" })
8451
+ }
8452
+ ) : null
8453
+ ] }),
8454
+ /* @__PURE__ */ jsxs("div", { className: "flex min-h-0 flex-1", children: [
8455
+ findings.length > 0 ? /* @__PURE__ */ jsxs(
8456
+ "aside",
8457
+ {
8458
+ className: "hidden w-64 shrink-0 overflow-y-auto border-r p-3 md:block",
8459
+ "data-testid": "document-review-findings",
8460
+ children: [
8461
+ /* @__PURE__ */ jsx("div", { className: "mb-2 text-xs font-medium uppercase tracking-wide text-muted-foreground", children: "AI findings" }),
8462
+ /* @__PURE__ */ jsx("ul", { className: "space-y-2", children: findings.map((f) => /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsxs(
8463
+ "div",
8464
+ {
8465
+ role: "button",
8466
+ tabIndex: 0,
8467
+ "data-testid": "review-finding",
8468
+ onClick: () => jumpToChunk(f.chunkIds[0]),
8469
+ onKeyDown: (e) => {
8470
+ if (e.key === "Enter" || e.key === " ") {
8471
+ e.preventDefault();
8472
+ jumpToChunk(f.chunkIds[0]);
8473
+ }
8474
+ },
8475
+ className: "w-full cursor-pointer rounded-md border p-2 text-left text-xs transition hover:border-ring hover:bg-muted/50 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring",
8476
+ children: [
8477
+ /* @__PURE__ */ jsx(
8478
+ TagEntity,
8479
+ {
8480
+ size: "sm",
8481
+ tag: {
8482
+ external_id: f.tagExtId,
8483
+ name: tagNameById.get(f.tagExtId) ?? f.tagExtId.slice(0, 8)
8484
+ }
8485
+ }
8486
+ ),
8487
+ /* @__PURE__ */ jsx("p", { className: "mt-1 line-clamp-3 text-muted-foreground", children: f.statement })
8488
+ ]
8489
+ }
8490
+ ) }, f.key)) })
8491
+ ]
8492
+ }
8493
+ ) : null,
8494
+ /* @__PURE__ */ jsx("div", { ref: scrollRef, className: "min-w-0 flex-1 overflow-y-auto px-6 py-4", children: parsedQuery.isLoading ? /* @__PURE__ */ jsx("div", { className: "flex h-full items-center justify-center text-sm text-muted-foreground", children: "Loading document\u2026" }) : parsedQuery.isError ? /* @__PURE__ */ jsx("div", { className: "flex h-full items-center justify-center text-sm text-muted-foreground", children: "Could not load this document\u2019s content." }) : pages.length === 0 ? /* @__PURE__ */ jsx("div", { className: "flex h-full items-center justify-center text-sm text-muted-foreground", children: "No readable content." }) : /* @__PURE__ */ jsx("div", { className: "mx-auto max-w-3xl space-y-8", children: pages.map(([pageNum, chunks]) => /* @__PURE__ */ jsxs("section", { children: [
8495
+ /* @__PURE__ */ jsxs("div", { className: "mb-3 flex items-center gap-3", children: [
8496
+ /* @__PURE__ */ jsxs("span", { className: "text-xs font-medium uppercase tracking-wide text-muted-foreground", children: [
8497
+ "Page ",
8498
+ pageNum
8499
+ ] }),
8500
+ /* @__PURE__ */ jsx("div", { className: "h-px flex-1 bg-border" })
8501
+ ] }),
8502
+ /* @__PURE__ */ jsx("div", { className: "space-y-3", children: chunks.map((c, i) => {
8503
+ const cid = c.metadata?.chunk_ext_id;
8504
+ const tagExtId = cid ? chunkToTag.get(cid) : void 0;
8505
+ const highlighted = !!tagExtId;
8506
+ const isActive = !!cid && cid === activeChunkId;
8507
+ return /* @__PURE__ */ jsxs(
8508
+ "div",
8509
+ {
8510
+ "data-chunk-id": cid,
8511
+ "data-testid": isActive ? "review-chunk-active" : highlighted ? "review-chunk-cited" : "review-chunk",
8512
+ className: cn(
8513
+ "scroll-mt-4 rounded-md px-2 py-1 transition-colors",
8514
+ highlighted && "bg-[var(--color-ai-accent-soft,theme(colors.amber.100))] ring-1 ring-inset ring-border",
8515
+ // The externally-selected search passage wins the
8516
+ // styling: a stronger accent ring so the matched
8517
+ // hit stands out from any AI-finding highlights.
8518
+ isActive && "bg-[var(--color-ai-accent-soft,theme(colors.amber.100))] ring-2 ring-inset ring-ai-accent",
8519
+ flash === cid && "ring-2 ring-ring"
8520
+ ),
8521
+ children: [
8522
+ highlighted ? /* @__PURE__ */ jsx("div", { className: "mb-1", children: /* @__PURE__ */ jsx(
8523
+ TagEntity,
8524
+ {
8525
+ size: "sm",
8526
+ tag: {
8527
+ external_id: tagExtId,
8528
+ name: tagNameById.get(tagExtId) ?? tagExtId.slice(0, 8)
8529
+ }
8530
+ }
8531
+ ) }) : null,
8532
+ /* @__PURE__ */ jsx(MarkdownRenderer, { className: "prose prose-sm max-w-none dark:prose-invert", children: c.content })
8533
+ ]
8534
+ },
8535
+ cid ?? i
8536
+ );
8537
+ }) })
8538
+ ] }, pageNum)) }) })
8539
+ ] })
8540
+ ]
8541
+ }
8542
+ );
8543
+ }
8220
8544
  function VoiceNoteRecorder({
8221
8545
  onSave,
8222
8546
  onDiscard,
@@ -8762,6 +9086,6 @@ function hasVideoTrack(blob) {
8762
9086
  });
8763
9087
  }
8764
9088
 
8765
- export { ALLOWED_PORTAL_ORIGINS, AccountClientProvider, ActivityFeed, AiActionCard, AiAnswer, AppleIcon, ArbiBotIcon, ArbiSessionStateProvider, ArbiWebSocketProvider, ArtifactCanvas, BOX_SEAT_REFUSED, BOX_SEAT_REFUSED_ACTION, BOX_SEAT_REFUSED_TITLE, CalendarSupportProvider, ChatBubble, CitationRenderer, ClaudeIcon, CommandPalette, CommandPaletteProvider, ConversationList, DEFAULT_ASPECT_OPTIONS, DEFAULT_PASSWORD_CHANGE_FORM_MESSAGES, DEFAULT_START_BY_EMAIL_LABELS, DateSeparator, DirectMessages, DmAvatar, DmComposer, DocQaPanel, DocSearch, DocumentCardMenu, DocumentGallery, DocumentReview, DocumentTable, DocumentsSupportProvider, DraftTitleControls, EMPTY_SESSION_STATE, FileIcon, FireworksIcon, GeminiIcon, GitHubIcon, GoogleIcon, ImageCropModal, ImageCropper, LinkedInIcon, MAIL_DRAFT_REPLACED_EVENT, MAX_AVATAR_FILE_BYTES, MailClientProvider, MailOfflineUnavailableError, MessageArtifactCard, MessageBubble, MessageThread, OpenAIIcon, PhotoCapture, ProviderIcon, RUN_WINDOW_MS, SIGNATURE_NOTIFICATION_TYPES, SemanticSearch, StartByEmail, TypingIndicator, VideoCapture, VoiceNoteRecorder, WORK_NOTIFICATION_LABELS, accountPath, aliasTakenMessage, annotateThread, announceMailDraftReplaced, applyOptimisticDocumentEdit, arbiAccountClient, arbiMailClient, calendarQueryKeys, callNotificationMeta, captureFrameAsBlob, connectOAuthCalendarAccount, createArbiSessionStore, createMailClient, cropImage, dayKey, defaultMailAlias, deploymentUserMeta, describeActivity, describeServerNotification, documentActivityMeta, documentActivityPhrase, documentDisplayName, docxMentionMeta, downloadRecoveryFile, fileAttachment, formatIdentityPrice, getNotificationTypeMeta, getWorkspaceActionText, getWorkspaceKind, getWorkspaceSentPhrase, hasVideoTrack, identityStepFor, inputRequestTitle, invalidateCalendarEvents, invalidateCalendars, isAliasTakenError, isDeploymentAdmin, isDeploymentUserNotification, isOfflineReadableArbiQuery, isQueuedCalendarWrite, isReplayableArbiMutation, isRestorableArbiQueryOnline, isSignatureNotificationType, isWorkspaceNotificationType, mailDraftIdFromContent, mailJson, mailQueryKeys, mountDiditVerification, nextAliasSuggestion, nextViewingDocument, notificationUserName, parseActivityContent, parseDeleteAccountBlockers, pickRecentWorkspaces, redlineStats, registerArbiMutationDefaults, resetCalendarAccountSyncState, resolveActiveWorkspace, rollbackOptimisticDocumentEdit, safePortalUrl, selectIsGenerating, selectViewingDocumentId, signatureNotificationPhrase, signatureRequestMeta, supportsHouseTemplates, textToArtifact, titleFromQuestion, toChatCitations, toNotificationPreferences, toProfileView, toRedlineMarkdown, toShellWorkspace, useAccountClient, useActOnStep, useAddHolidayCalendar, useAddWorkspaceMembers, useAgentChats, useAgentConfig, useAgentModels, useAgentSession, useAgentWorkspaces, useAiTask, useAppPasswords, useArbiChat, useArbiConnected, useArbiDocumentSync, useArbiSessionState, useArbiSessionStore, useArbiShellWorkspaces, useArbiWebSocket, useArbiWsContext, useArbiWsMessage, useArbiWsStatus, useArbiWsStore, useArbiWsTask, useArbiWsTasks, useAssignDocTags, useAuthorizeLimits, useAvatarCrop, useBookingPages, useCalDavProfiles, useCalendarAccounts, useCalendarEvent, useCalendarEventByUid, useCalendarEvents, useCalendarInvitations, useCalendarOutbox, useCalendarOverlays, useCalendarSettings, useCalendarShares, useCalendarSupport, useCalendars, useCameraStream, useClaimNativeAlias, useCloseAgentSession, useCommandPalette, useConfirmEmailChange, useConnectCalDavAccount, useConnectMailAccount, useConnectOAuthAccount, useContacts, useConversationActivity, useConversationPendingAuth, useConversationUsage, useCreateAgent, useCreateAppPassword, useCreateCalendar, useCreateContact, useCreateEvent, useCreateFact, useCreateFacts, useCreateFeed, useCreateRoom, useCreateWork, useCreateWorkflow, useCurrentSessionId, useDecideCounter, useDeleteAccount, useDeleteAccountFlow, useDeleteBookingPage, useDeleteCalendar, useDeleteContact, useDeleteDocuments, useDeleteEvent, useDeleteFact, useDeleteNotifications, useDeleteSkill, useDeleteWorkflow, useDirectMessages, useDisconnectCalendarAccount, useDisconnectMailAccount, useDocumentsSupport, useEmailChange, useFacts, useFetchCalendarEvent, useFilteredProjects, useFinaliseTranslation, useFindTime, useFollowThread, useFreeBusy, useGenerateAgentAvatar, useGenerateDocTags, useGrantAgentAccess, useHolidayCountries, useHouseTemplateCandidates, useIdentityVerification, useIdentityVerificationFlow, useImportCalendar, useInviteContacts, useMailAccounts, useMailAttachmentText, useMailCache, useMailClient, useMailDraftCompose, useMailDraftEditor, useMailDraftReplaced, useMailFolders, useMailMessage, useMailMessages, useMailOnline, useMailPolicy, useMailProjects, useMailUnlock, useMarkNotificationsRead, useMcpTools, useMoveEvent, useNameEditor, useNotificationPreferences, useNotifications, usePasswordChange, usePasswordChangeForm, usePendingContacts, usePlanWork, useProfile, useProjectConversationUsage, useProjectEvents, usePublishCalendar, useRefreshCalendar, useRemoveDocTags, useRemoveWorkspaceMembers, useRequestEmailChange, useRespondToEvent, useResumeCalendarAccountConnect, useRevokeAgentAccess, useRevokeAppPassword, useRooms, useRunConversation, useRunWorkflow, useSaveAgentConfig, useSaveBookingPage, useSaveCalendarSettings, useSaveMailDraft, useSearchContacts, useSearchFacts, useSemanticSearch, useSendBackStep, useSendMail, useSessions, useSetSkillVisibility, useSetWorkspaceHouseTemplate, useShareCalendar, useShellWorkspaces, useSignOut, useSkillSource, useSkills, useStartAgentSession, useStartCalendarAccountOAuth, useStartWorkQuery, useSubscribeCalendar, useSyncAccountsOnOpen, useSyncCalendarAccount, useTerminateSession, useUnshareCalendar, useUpdateCalendar, useUpdateCalendarAccount, useUpdateContact, useUpdateConversation, useUpdateDocTag, useUpdateDocuments, useUpdateEvent, useUpdateFact, useUpdateMailMessage, useUpdateProfile, useUpdateProjectFields, useUpdateUserSettings, useUpdateWorkflow, useUpdateWorkspace, useUploadDocuments, useUploadSkillFiles, useUploadUrls, useUserSettings, useVideoRecorder, useWorkNotifications, useWorkflowRuns, useWorkflows, useWorkspaceDocs, useWorkspaceNotificationLevel, userDisplayName, userInitials, workflowStepOf, workspaceHouseTemplateId };
9089
+ export { ALLOWED_PORTAL_ORIGINS, AccountClientProvider, ActivityFeed, AiActionCard, AiAnswer, AppleIcon, ArbiBotIcon, ArbiSessionStateProvider, ArbiWebSocketProvider, ArtifactCanvas, BOX_SEAT_REFUSED, BOX_SEAT_REFUSED_ACTION, BOX_SEAT_REFUSED_TITLE, CalendarSupportProvider, ChatBubble, CitationRenderer, ClaudeIcon, CommandPalette, CommandPaletteProvider, ConversationList, DEFAULT_ASPECT_OPTIONS, DEFAULT_DOCUMENT_VIEWER_STATE, DEFAULT_PASSWORD_CHANGE_FORM_MESSAGES, DEFAULT_START_BY_EMAIL_LABELS, DateSeparator, DirectMessages, DmAvatar, DmComposer, DocQaPanel, DocSearch, DocumentCardMenu, DocumentGallery, DocumentReview, DocumentTable, DocumentsSupportProvider, DraftTitleControls, EMPTY_SESSION_STATE, FileIcon, FireworksIcon, GeminiIcon, GitHubIcon, GoogleIcon, ImageCropModal, ImageCropper, LinkedInIcon, MAIL_DRAFT_REPLACED_EVENT, MAX_AVATAR_FILE_BYTES, MailClientProvider, MailOfflineUnavailableError, MessageArtifactCard, MessageBubble, MessageThread, OpenAIIcon, POLL_EVERY_MS, PhotoCapture, ProviderIcon, RUN_WINDOW_MS, SIGNATURE_NOTIFICATION_TYPES, SLOW_AFTER_MS, STILL_WORKING, StartByEmail, TypingIndicator, VideoCapture, VoiceNoteRecorder, WORK_NOTIFICATION_LABELS, accountPath, aliasTakenMessage, annotateThread, announceMailDraftReplaced, applyOptimisticDocumentEdit, arbiAccountClient, arbiMailClient, calendarQueryKeys, callNotificationMeta, captureFrameAsBlob, connectOAuthCalendarAccount, connectorErrorStatus, connectorQueryKeys, connectorReturnTo, createArbiSessionStore, createMailClient, cropImage, dayKey, defaultMailAlias, deploymentUserMeta, describeActivity, describeServerNotification, documentActivityMeta, documentActivityPhrase, documentDisplayName, docxMentionMeta, downloadRecoveryFile, fileAttachment, formatIdentityPrice, getNotificationTypeMeta, getWorkspaceActionText, getWorkspaceKind, getWorkspaceSentPhrase, hasVideoTrack, identityStepFor, inputRequestTitle, invalidateCalendarEvents, invalidateCalendars, isAliasTakenError, isDeploymentAdmin, isDeploymentUserNotification, isOfflineReadableArbiQuery, isQueuedCalendarWrite, isReplayableArbiMutation, isRestorableArbiQueryOnline, isSignatureNotificationType, isWorkspaceNotificationType, mailDraftIdFromContent, mailJson, mailQueryKeys, mountDiditVerification, nextAliasSuggestion, nextViewingDocument, notificationUserName, parseActivityContent, parseDeleteAccountBlockers, pickRecentWorkspaces, redlineStats, registerArbiMutationDefaults, resetCalendarAccountSyncState, resolveActiveWorkspace, rollbackOptimisticDocumentEdit, safePortalUrl, selectIsGenerating, selectViewingDocumentId, signatureNotificationPhrase, signatureRequestMeta, supportsHouseTemplates, textToArtifact, titleFromQuestion, toChatCitations, toNotificationPreferences, toProfileView, toRedlineMarkdown, toShellWorkspace, useAccountClient, useActOnStep, useAddHolidayCalendar, useAddProjectAddonBlock, useAddWorkspaceMembers, useAddonQuote, useAgentChats, useAgentConfig, useAgentModels, useAgentSession, useAgentWorkspaces, useAiTask, useArbiChat, useArbiConnected, useArbiDocumentSync, useArbiSessionState, useArbiSessionStore, useArbiShellWorkspaces, useArbiWebSocket, useArbiWsContext, useArbiWsMessage, useArbiWsStatus, useArbiWsStore, useArbiWsTask, useArbiWsTasks, useAssignDocTags, useAuthorizeLimits, useAvatarCrop, useBookingPages, useCalDavProfiles, useCalendarAccounts, useCalendarEvent, useCalendarEventByUid, useCalendarEvents, useCalendarInvitations, useCalendarOutbox, useCalendarOverlays, useCalendarSettings, useCalendarShares, useCalendarSupport, useCalendars, useCameraStream, useCancelDriveSync, useCancelMailboxSync, useCancelProjectSubscription, useChangeProjectPlan, useChargeWatch, useClaimNativeAlias, useCloseAgentSession, useCommandPalette, useConfirmEmailChange, useConnectCalDavAccount, useConnectMailAccount, useConnectOAuthAccount, useConnectorAutoSync, useConnectorCatalog, useConnectorVendorVisibility, useContacts, useConversationActivity, useConversationPendingAuth, useConversationUsage, useCreateAgent, useCreateCalendar, useCreateContact, useCreateEvent, useCreateFact, useCreateFacts, useCreateProject, useCreateProjectCheckout, useCreateRoom, useCreateWork, useCreateWorkflow, useCurrentSessionId, useDecideCounter, useDeleteAccount, useDeleteAccountFlow, useDeleteBookingPage, useDeleteCalendar, useDeleteContact, useDeleteDocuments, useDeleteEvent, useDeleteFact, useDeleteNotifications, useDeleteProject, useDeleteSkill, useDeleteWorkflow, useDirectMessages, useDisconnectCalendarAccount, useDisconnectConnector, useDisconnectMailAccount, useDisconnectSlack, useDocumentsSupport, useDriveFolderChildren, useDriveFolderDocCount, useDriveFolders, useDriveSyncEstimate, useDriveSyncProgress, useEmailChange, useEnableDriveSync, useEnableMailboxSync, useFacts, useFetchCalendarEvent, useFilteredProjects, useFinaliseTranslation, useFindTime, useFollowThread, useFreeBusy, useGenerateAgentAvatar, useGenerateDocTags, useGrantAgentAccess, useHolidayCountries, useHouseTemplateCandidates, useIdentityVerification, useIdentityVerificationFlow, useImportCalendar, useInvalidateProjects, useInviteContacts, useIsSlow, useMailAccounts, useMailAttachmentText, useMailCache, useMailClient, useMailDraftCompose, useMailDraftEditor, useMailDraftReplaced, useMailFolders, useMailMessage, useMailMessages, useMailOnline, useMailPolicy, useMailProjects, useMailUnlock, useMailboxFolders, useMailboxSyncProgress, useMarkNotificationsRead, useMcpTools, useMoveEvent, useMyConnectors, useNameEditor, useNotificationPreferences, useNotifications, usePassageQuotes, usePasswordChange, usePasswordChangeForm, usePendingContacts, usePlanQuote, usePlanWork, usePreviewProjectPlanChange, useProducts, useProfile, useProjectBillingPortal, useProjectConversationUsage, useProjectEvents, usePublishCalendar, useRefreshCalendar, useRefreshConnectorsOnRunEnd, useRefreshProject, useRemoveDocTags, useRemoveWorkspaceMembers, useRequestEmailChange, useRespondToEvent, useResumeCalendarAccountConnect, useRevokeAgentAccess, useRooms, useRunConversation, useRunWorkflow, useSaveAgentConfig, useSaveBookingPage, useSaveCalendarSettings, useSaveMailDraft, useSearchContacts, useSearchFacts, useSemanticSearch, useSendBackStep, useSendMail, useSessions, useSetSkillVisibility, useSetWorkspaceHouseTemplate, useSetWorkspaceMemberRoles, useShareCalendar, useShellWorkspaces, useSignOut, useSkillSource, useSkills, useSlackConnection, useStartAgentSession, useStartCalendarAccountOAuth, useStartWorkQuery, useSubscribeCalendar, useSyncAccountsOnOpen, useSyncCalendarAccount, useTerminateSession, useTriggerDriveSync, useTriggerMailboxSync, useUnshareCalendar, useUpdateCalendar, useUpdateCalendarAccount, useUpdateContact, useUpdateConversation, useUpdateDocTag, useUpdateDocuments, useUpdateEvent, useUpdateFact, useUpdateMailMessage, useUpdateProfile, useUpdateProjectAddonSettings, useUpdateProjectFields, useUpdateProjectNextPeriodAddons, useUpdateUserSettings, useUpdateWorkflow, useUpdateWorkspace, useUploadDocuments, useUploadSkillFiles, useUploadUrls, useUserSettings, useVideoRecorder, useWorkNotifications, useWorkflowRuns, useWorkflows, useWorkspaceDocs, useWorkspaceNotificationLevel, useWorkspaceUsers, userDisplayName, userInitials, workflowStepOf, workspaceHouseTemplateId };
8766
9090
  //# sourceMappingURL=index.js.map
8767
9091
  //# sourceMappingURL=index.js.map