@arbidocs/react 0.5.121 → 0.5.123
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/MarkdownRenderer.js +6 -3
- package/dist/ai/MarkdownRenderer.js.map +2 -2
- package/dist/ai/MessageArtifactCard.js +9 -1
- package/dist/ai/MessageArtifactCard.js.map +2 -2
- package/dist/ai/remark-ai-caption.js +60 -0
- package/dist/ai/remark-ai-caption.js.map +7 -0
- package/dist/artifacts/index.cjs +2 -2
- package/dist/calls/livekit/index.cjs +50 -50
- package/dist/chat/chat-artifacts.js +0 -1
- package/dist/chat/chat-artifacts.js.map +2 -2
- package/dist/chat/open-document.js +3 -1
- package/dist/chat/open-document.js.map +2 -2
- package/dist/{chunk-DLEHM4IA.cjs → chunk-AB2A6F6T.cjs} +4 -4
- package/dist/{chunk-DLEHM4IA.cjs.map → chunk-AB2A6F6T.cjs.map} +1 -1
- package/dist/{chunk-MXP4O4DI.cjs → chunk-EM6DP62E.cjs} +63 -5
- package/dist/chunk-EM6DP62E.cjs.map +1 -0
- package/dist/{chunk-X5OZRLFZ.cjs → chunk-FAJLJDWS.cjs} +9 -9
- package/dist/{chunk-X5OZRLFZ.cjs.map → chunk-FAJLJDWS.cjs.map} +1 -1
- package/dist/{chunk-RLSBRZ6Z.cjs → chunk-IX4HOS5Z.cjs} +2 -3
- package/dist/chunk-IX4HOS5Z.cjs.map +1 -0
- package/dist/{chunk-Z3W4XFWB.cjs → chunk-WUYSVTKE.cjs} +13 -11
- package/dist/chunk-WUYSVTKE.cjs.map +1 -0
- package/dist/index.cjs +723 -711
- package/dist/index.cjs.map +1 -1
- package/dist/{index.d-D2puqWeN.d.ts → index.d-CXjQ1akb.d.ts} +1 -1
- package/dist/{index.d-oR5FKZpJ.d.ts → index.d-KbsNPTEN.d.ts} +7 -5
- package/dist/index.d.ts +21 -29
- package/dist/shell/index.cjs +53 -49
- package/dist/shell/index.d.ts +1 -1
- package/dist/ui/index.cjs +159 -159
- package/dist/ui/index.d.ts +1 -1
- package/package.json +3 -3
- package/dist/chunk-MXP4O4DI.cjs.map +0 -1
- package/dist/chunk-RLSBRZ6Z.cjs.map +0 -1
- package/dist/chunk-Z3W4XFWB.cjs.map +0 -1
package/dist/ui/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { A as ARBI_MARK_SRC, a as AgentBadge, b as AiMarkdown, c as ArbiIcon, d as Avatar, e as AvatarFallback, f as AvatarImage, B as BASE_COLORS, g as Badge, h as BadgeProps, i as Button, j as ButtonProps, C as COLUMN_LABEL_FALLBACKS, k as Card, l as CardContent, m as CardDescription, n as CardFooter, o as CardHeader, p as CardProps, q as CardTitle, r as Checkbox, s as Collapsible, t as CollapsibleContent, u as CollapsibleTrigger, v as Command, w as CommandDialog, x as CommandEmpty, y as CommandGroup, z as CommandInput, D as CommandItem, E as CommandList, F as CommandSeparator, G as CommandShortcut, H as DEFAULT_METADATA_TAGS, I as DebouncedInput, J as DebouncedInputProps, K as Dialog, L as DialogClose, M as DialogContent, N as DialogDescription, O as DialogFooter, P as DialogHeader, Q as DialogOverlay, R as DialogPortal, S as DialogPresentation, T as DialogTitle, U as DialogTrigger, V as DictateContextValue, W as DocumentEntity, X as DocumentEntityProps, Y as DocumentLike, Z as DropdownMenu, _ as DropdownMenuCheckboxItem, $ as DropdownMenuContent, a0 as DropdownMenuGroup, a1 as DropdownMenuItem, a2 as DropdownMenuLabel, a3 as DropdownMenuPortal, a4 as DropdownMenuRadioGroup, a5 as DropdownMenuRadioItem, a6 as DropdownMenuSeparator, a7 as DropdownMenuShortcut, a8 as DropdownMenuSub, a9 as DropdownMenuSubContent, aa as DropdownMenuSubTrigger, ab as DropdownMenuTrigger, ac as ENTITY_MAPPINGS, ad as EntityIcon, ae as EntityIconComponent, af as EntityLabelForm, ag as EntityNoun, ah as EntityPill, ai as EntityRegistryOverride, aj as EntitySize, ak as EntityType, al as EntityVocabulary, am as FileTypeIcon, an as FolderTreeNode, ao as FormatRelativeTimeOptions, ap as HoverCard, aq as HoverCardContent, ar as HoverCardTrigger, as as IconToggle, at as IconToggleProps, au as IdentityBusy, av as IdentityProblem, aw as IdentityPurchase, ax as IdentityState, ay as IdentityStatus, az as IdentityStep, aA as IdentityVerificationFlow, aB as Input, aC as InputProps, aD as Label, aE as MarkMenu, aF as MarkMenuItem, aG as MarkMenuProps, aH as MarkdownCode, aI as MarkdownLink, aJ as MarkdownRenderer, aK as MarkdownRendererProps, aL as MarkdownStreamingContext, aM as NEUTRAL_GRAY, aN as PLACEHOLDER_COLOR, aO as PRESENTATIONS_FOLDER, aP as PRESENTATION_TEMPLATES_FOLDER, aQ as PassageCard, aR as PassageCardProps, aS as Popover, aT as PopoverAnchor, aU as PopoverClose, aV as PopoverContent, aW as PopoverTrigger, aX as PortalContainerProvider, aY as PresenceDisplayStatus, aZ as PresenceLabel, a_ as Progress, a$ as ProjectEntity, b0 as ProjectEntityProps, b1 as ProjectRelation, b2 as ProviderIcon, b3 as RadioGroup, b4 as RadioGroupItem, b5 as Rag, b6 as SHARING_LABELS, b7 as ScrollArea, b8 as ScrollBar, b9 as Select, ba as SelectContent, bb as SelectGroup, bc as SelectItem, bd as SelectLabel, be as SelectScrollDownButton, bf as SelectScrollUpButton, bg as SelectSeparator, bh as SelectTrigger, bi as SelectValue, bj as Separator, bk as SharingEntity, bl as SharingEntityProps, bm as ShieldIcon, bn as ShieldIconProps, bo as Slider, bp as StatusBadgeComponent, bq as StatusBadgeProps, br as StatusPill, bs as StatusPillProps, bt as StatusVariant, bu as Switch, bv as TAG_TYPE_ICONS, bw as TAG_TYPE_LABELS, bx as Table, by as TableBody, bz as TableCaption, bA as TableCell, bB as TableFooter, bC as TableHead, bD as TableHeader, bE as TableRow, bF as Tabs, bG as TabsContent, bH as TabsList, bI as TabsTrigger, bJ as TagEntity, bK as TagEntityProps, bL as TagLike, bM as Textarea, bN as TextareaProps, bO as ThreadVisibilityIcon, bP as Toggle, bQ as ToggleGroup, bR as ToggleGroupItem, bS as Tooltip, bT as TooltipContent, bU as TooltipProvider, bV as TooltipTrigger, bW as UserEntity, bX as UserEntityProps, bY as UserMenu, bZ as UserMenuItem, b_ as UserMenuProps, b$ as UserMenuStatus, c0 as VISIBILITY_ICONS, c1 as VerifiedBadge, c2 as VerifiedBadgeProps, c3 as VerifiedToggle, c4 as VisibilityIcon, c5 as VisibilityToggle, c6 as VisibilityToggleProps, c7 as agentAvatarColors, c8 as badgeVariants, c9 as buildFolderTree, ca as buttonVariants, cb as canonicalFolderPath, cc as cardVariants, cd as closeOpenEmphasis, ce as cn, cf as configureEntityRegistry, cg as configureEntityVocabulary, ch as configureRagLabels, ci as configureSharingMembers, cj as configureStatusRegistry, ck as createUserAvatarIcon, cl as entityNoun, cm as extensionFromMime, cn as formatCompactLastSeen, co as formatDocDate, cp as formatFolderLabel, cq as formatFriendlyDate, cr as formatRelativeTime, cs as friendlyFileType, ct as getDocIcon, cu as getDocumentAuthor, cv as getDocumentDate, cw as getDocumentNature, cx as getDocumentSubject, cy as getDocumentTitle, cz as getEntityColor, cA as getEntityColorStyles, cB as getEntityIcon, cC as getEntityLabel, cD as getFileExtension, cE as getFileTypeIcon, cF as getStatusVariant, cG as getTagTypeIcon, cH as getTagTypeLabel, cI as getUserAvatarColor, cJ as getUserDisplayName, cK as getUserInitials, cL as getWorkspaceColor, cM as isAgent, cN as isAudioFile, cO as isDocumentAddableToConversation, cP as isDownloadOnlyFile, cQ as isImageDocument, cR as isImageFile, cS as isMediaFile, cT as isPresentationFileName, cU as isVideoFile, cV as markdownBaseComponents, cW as markdownSanitizeSchema, cX as markdownToPlainText, cY as markdownToPlainTextBlocks, c_ as splitMarkdownBlocks, c$ as tagKindNouns, d0 as tagKindTitle, d1 as toggleVariants, d2 as trimOpenCitation, d3 as useDictateContext, d4 as usePortalContainer, d5 as usesOriginalBytesForViewer } from '../index.d-
|
|
1
|
+
export { A as ARBI_MARK_SRC, a as AgentBadge, b as AiMarkdown, c as ArbiIcon, d as Avatar, e as AvatarFallback, f as AvatarImage, B as BASE_COLORS, g as Badge, h as BadgeProps, i as Button, j as ButtonProps, C as COLUMN_LABEL_FALLBACKS, k as Card, l as CardContent, m as CardDescription, n as CardFooter, o as CardHeader, p as CardProps, q as CardTitle, r as Checkbox, s as Collapsible, t as CollapsibleContent, u as CollapsibleTrigger, v as Command, w as CommandDialog, x as CommandEmpty, y as CommandGroup, z as CommandInput, D as CommandItem, E as CommandList, F as CommandSeparator, G as CommandShortcut, H as DEFAULT_METADATA_TAGS, I as DebouncedInput, J as DebouncedInputProps, K as Dialog, L as DialogClose, M as DialogContent, N as DialogDescription, O as DialogFooter, P as DialogHeader, Q as DialogOverlay, R as DialogPortal, S as DialogPresentation, T as DialogTitle, U as DialogTrigger, V as DictateContextValue, W as DocumentEntity, X as DocumentEntityProps, Y as DocumentLike, Z as DropdownMenu, _ as DropdownMenuCheckboxItem, $ as DropdownMenuContent, a0 as DropdownMenuGroup, a1 as DropdownMenuItem, a2 as DropdownMenuLabel, a3 as DropdownMenuPortal, a4 as DropdownMenuRadioGroup, a5 as DropdownMenuRadioItem, a6 as DropdownMenuSeparator, a7 as DropdownMenuShortcut, a8 as DropdownMenuSub, a9 as DropdownMenuSubContent, aa as DropdownMenuSubTrigger, ab as DropdownMenuTrigger, ac as ENTITY_MAPPINGS, ad as EntityIcon, ae as EntityIconComponent, af as EntityLabelForm, ag as EntityNoun, ah as EntityPill, ai as EntityRegistryOverride, aj as EntitySize, ak as EntityType, al as EntityVocabulary, am as FileTypeIcon, an as FolderTreeNode, ao as FormatRelativeTimeOptions, ap as HoverCard, aq as HoverCardContent, ar as HoverCardTrigger, as as IconToggle, at as IconToggleProps, au as IdentityBusy, av as IdentityProblem, aw as IdentityPurchase, ax as IdentityState, ay as IdentityStatus, az as IdentityStep, aA as IdentityVerificationFlow, aB as Input, aC as InputProps, aD as Label, aE as MarkMenu, aF as MarkMenuItem, aG as MarkMenuProps, aH as MarkdownCode, aI as MarkdownLink, aJ as MarkdownRenderer, aK as MarkdownRendererProps, aL as MarkdownStreamingContext, aM as NEUTRAL_GRAY, aN as PLACEHOLDER_COLOR, aO as PRESENTATIONS_FOLDER, aP as PRESENTATION_TEMPLATES_FOLDER, aQ as PassageCard, aR as PassageCardProps, aS as Popover, aT as PopoverAnchor, aU as PopoverClose, aV as PopoverContent, aW as PopoverTrigger, aX as PortalContainerProvider, aY as PresenceDisplayStatus, aZ as PresenceLabel, a_ as Progress, a$ as ProjectEntity, b0 as ProjectEntityProps, b1 as ProjectRelation, b2 as ProviderIcon, b3 as RadioGroup, b4 as RadioGroupItem, b5 as Rag, b6 as SHARING_LABELS, b7 as ScrollArea, b8 as ScrollBar, b9 as Select, ba as SelectContent, bb as SelectGroup, bc as SelectItem, bd as SelectLabel, be as SelectScrollDownButton, bf as SelectScrollUpButton, bg as SelectSeparator, bh as SelectTrigger, bi as SelectValue, bj as Separator, bk as SharingEntity, bl as SharingEntityProps, bm as ShieldIcon, bn as ShieldIconProps, bo as Slider, bp as StatusBadgeComponent, bq as StatusBadgeProps, br as StatusPill, bs as StatusPillProps, bt as StatusVariant, bu as Switch, bv as TAG_TYPE_ICONS, bw as TAG_TYPE_LABELS, bx as Table, by as TableBody, bz as TableCaption, bA as TableCell, bB as TableFooter, bC as TableHead, bD as TableHeader, bE as TableRow, bF as Tabs, bG as TabsContent, bH as TabsList, bI as TabsTrigger, bJ as TagEntity, bK as TagEntityProps, bL as TagLike, bM as Textarea, bN as TextareaProps, bO as ThreadVisibilityIcon, bP as Toggle, bQ as ToggleGroup, bR as ToggleGroupItem, bS as Tooltip, bT as TooltipContent, bU as TooltipProvider, bV as TooltipTrigger, bW as UserEntity, bX as UserEntityProps, bY as UserMenu, bZ as UserMenuItem, b_ as UserMenuProps, b$ as UserMenuStatus, c0 as VISIBILITY_ICONS, c1 as VerifiedBadge, c2 as VerifiedBadgeProps, c3 as VerifiedToggle, c4 as VisibilityIcon, c5 as VisibilityToggle, c6 as VisibilityToggleProps, c7 as agentAvatarColors, c8 as badgeVariants, c9 as buildFolderTree, ca as buttonVariants, cb as canonicalFolderPath, cc as cardVariants, cd as closeOpenEmphasis, ce as cn, cf as configureEntityRegistry, cg as configureEntityVocabulary, ch as configureRagLabels, ci as configureSharingMembers, cj as configureStatusRegistry, ck as createUserAvatarIcon, cl as entityNoun, cm as extensionFromMime, cn as formatCompactLastSeen, co as formatDocDate, cp as formatFolderLabel, cq as formatFriendlyDate, cr as formatRelativeTime, cs as friendlyFileType, ct as getDocIcon, cu as getDocumentAuthor, cv as getDocumentDate, cw as getDocumentNature, cx as getDocumentSubject, cy as getDocumentTitle, cz as getEntityColor, cA as getEntityColorStyles, cB as getEntityIcon, cC as getEntityLabel, cD as getFileExtension, cE as getFileTypeIcon, cF as getStatusVariant, cG as getTagTypeIcon, cH as getTagTypeLabel, cI as getUserAvatarColor, cJ as getUserDisplayName, cK as getUserInitials, cL as getWorkspaceColor, cM as isAgent, cN as isAudioFile, cO as isDocumentAddableToConversation, cP as isDownloadOnlyFile, cQ as isImageDocument, cR as isImageFile, cS as isMediaFile, cT as isPresentationFileName, cU as isVideoFile, cV as markdownBaseComponents, cW as markdownSanitizeSchema, cX as markdownToPlainText, cY as markdownToPlainTextBlocks, c_ as splitMarkdownBlocks, c$ as tagKindNouns, d0 as tagKindTitle, d1 as toggleVariants, d2 as trimOpenCitation, d3 as useDictateContext, d4 as usePortalContainer, d5 as usesOriginalBytesForViewer } from '../index.d-CXjQ1akb.js';
|
|
2
2
|
export { L as LazyChunk, l as lazyChunk, a as lazyComponent, p as preloadChunks } from '../lazy-chunk.d-B6YDLMKI.js';
|
|
3
3
|
import 'clsx';
|
|
4
4
|
import 'react';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@arbidocs/react",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.123",
|
|
4
4
|
"description": "React hooks and provider for the ARBI SDK",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -117,8 +117,8 @@
|
|
|
117
117
|
"build-storybook": "storybook build"
|
|
118
118
|
},
|
|
119
119
|
"dependencies": {
|
|
120
|
-
"@arbidocs/client": "0.5.
|
|
121
|
-
"@arbidocs/sdk": "0.5.
|
|
120
|
+
"@arbidocs/client": "0.5.123",
|
|
121
|
+
"@arbidocs/sdk": "0.5.123",
|
|
122
122
|
"@didit-protocol/sdk-web": "0.4.0",
|
|
123
123
|
"@livekit/components-react": "2.9.24",
|
|
124
124
|
"@radix-ui/react-avatar": "^1.2.0",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/ai/markdown-base-components.tsx","../src/ai/markdown-streaming-context.ts","../src/ai/split-markdown-blocks.ts","../src/ai/MarkdownRenderer.tsx"],"names":["jsx","createContext","useRef","useState","useCallback","useEffect","jsxs","Check","Copy","cn","Fragment","defaultSchema","useMemo","useReducer","remarkGfm","rehypeRaw","rehypeSanitize","rehypeSlug","React","Markdown","normalizeCitationMarkup","closeOpenEmphasis","trimOpenCitation"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAeO,IAAM,sBAAA,GAA8C;AAAA,EACzD,EAAA,EAAI,CAAC,EAAE,QAAA,EAAU,GAAG,KAAA,EAAM,qBACxBA,cAAA,CAAC,IAAA,EAAA,EAAG,WAAU,uBAAA,EAAwB,aAAA,EAAY,oBAAA,EAAsB,GAAG,OACxE,QAAA,EACH,CAAA;AAAA,EAEF,EAAA,EAAI,CAAC,EAAE,QAAA,EAAU,GAAG,KAAA,EAAM,qBACxBA,cAAA,CAAC,IAAA,EAAA,EAAG,WAAU,yBAAA,EAA0B,aAAA,EAAY,oBAAA,EAAsB,GAAG,OAC1E,QAAA,EACH,CAAA;AAAA,EAEF,EAAA,EAAI,CAAC,EAAE,QAAA,EAAU,GAAG,KAAA,EAAM,qBACxBA,cAAA,CAAC,IAAA,EAAA,EAAG,WAAU,yBAAA,EAA0B,aAAA,EA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G,CAAC,IAAI,CAAC,CAAA;AAC9D,EAAA,MAAM,SAAA,GAAY,aAAa,IAAI,CAAA;AACnC,EAAA,MAAM,EAAE,aAAA,EAAe,aAAA,KAAkB,UAAA,CAAW,SAAA,EAAW,WAAW,kBAAkB,CAAA;AAE5F,EAAA,uBACEZ,cAAAA;AAAA,IAAC,qBAAA;AAAA,IAAA;AAAA,MACC,QAAA,kBAAUA,cAAAA,CAAC,KAAA,EAAA,EAAI,WAAWS,oBAAA,CAAG,iCAAA,EAAmC,SAAS,CAAA,EAAI,QAAA,EAAS,CAAA;AAAA,MAEtF,0BAAAT,cAAAA,CAAC,wBAAA,CAAyB,UAAzB,EAAkC,KAAA,EAAO,aACxC,QAAA,kBAAAA,cAAAA;AAAA,QAAC,KAAA;AAAA,QAAA;AAAA,UACC,SAAA,EAAWS,oBAAA,CAAG,wDAAA,EAA0D,SAAS,CAAA;AAAA,UACjF,aAAA,EAAa,MAAA;AAAA,UAEZ,QAAA,EAAA,MAAA,CAAO,GAAA,CAAI,CAAC,KAAA,EAAO,0BAClBT,cAAAA;AAAA,YAAC,aAAA;AAAA,YAAA;AAAA,cAEC,OAAA,EAAS,KAAA;AAAA,cACT,UAAA;AAAA,cACA,aAAA;AAAA,cACA;AAAA,aAAA;AAAA,YAJK;AAAA,WAMR;AAAA;AAAA,OACH,EACF;AAAA;AAAA,GACF;AAEJ;AAOO,IAAM,gBAAA,GAAmBkB,sBAAA,CAAM,IAAA,CAAK,yBAAyB","file":"chunk-MXP4O4DI.cjs","sourcesContent":["import React from 'react'\nimport type { Components } from 'react-markdown'\n\n/**\n * Brand-neutral presentational component overrides for react-markdown, shared by\n * every markdown surface in the workspace (the monolith's `MarkdownRenderer` and\n * the AI kit's `AiMarkdown`). One house style for headings, lists, tables and the\n * inline text elements — token-based, so it themes per app.\n *\n * Deliberately excluded (kept per-consumer): `a` (external-link confirm vs\n * plain), `code`/`pre` (rich CodeBlock + Mermaid vs inline), `span` (doc-entity\n * pills), and `del`/`ins`/`mark` (general emphasis vs redline tracked-changes) —\n * these differ by intent or carry heavy/coupled behaviour, so each renderer owns\n * them and spreads this base underneath.\n */\nexport const markdownBaseComponents: Partial<Components> = {\n h1: ({ children, ...props }: React.ComponentPropsWithoutRef<'h1'>) => (\n <h1 className=\"text-lg font-semibold\" data-testid=\"markdown-heading-1\" {...props}>\n {children}\n </h1>\n ),\n h2: ({ children, ...props }: React.ComponentPropsWithoutRef<'h2'>) => (\n <h2 className=\"font-semibold text-base\" data-testid=\"markdown-heading-2\" {...props}>\n {children}\n </h2>\n ),\n h3: ({ children, ...props }: React.ComponentPropsWithoutRef<'h3'>) => (\n <h3 className=\"font-semibold text-base\" data-testid=\"markdown-heading-3\" {...props}>\n {children}\n </h3>\n ),\n h4: ({ children, ...props }: React.ComponentPropsWithoutRef<'h4'>) => (\n <h4 className=\"font-semibold text-base\" {...props}>\n {children}\n </h4>\n ),\n h5: ({ children, ...props }: React.ComponentPropsWithoutRef<'h5'>) => (\n <h5 className=\"font-medium\" {...props}>\n {children}\n </h5>\n ),\n strong: ({ children, ...props }: React.ComponentPropsWithoutRef<'strong'>) => (\n <strong className=\"font-semibold\" {...props}>\n {children}\n </strong>\n ),\n blockquote: ({ children, ...props }: React.ComponentPropsWithoutRef<'blockquote'>) => (\n <blockquote className=\"border-l-2 border-primary pl-4\" {...props}>\n {children}\n </blockquote>\n ),\n ol: ({ children, ...props }: React.ComponentPropsWithoutRef<'ol'>) => (\n <ol className=\"list-decimal space-y-2 pl-6\" data-testid=\"markdown-ordered-list\" {...props}>\n {children}\n </ol>\n ),\n ul: ({ children, ...props }: React.ComponentPropsWithoutRef<'ul'>) => (\n <ul className=\"list-none space-y-2 pl-6\" data-testid=\"markdown-unordered-list\" {...props}>\n {children}\n </ul>\n ),\n li: ({ children, ...props }: React.ComponentPropsWithoutRef<'li'>) => (\n <li className=\"my-1.5\" {...props}>\n {children}\n </li>\n ),\n table: ({ children, ...props }: React.ComponentPropsWithoutRef<'table'>) => (\n <table data-testid=\"markdown-table\" {...props}>\n {children}\n </table>\n ),\n th: ({ children, ...props }: React.ComponentPropsWithoutRef<'th'>) => (\n <th {...props}>{children}</th>\n ),\n td: ({ children, ...props }: React.ComponentPropsWithoutRef<'td'>) => (\n <td {...props}>{children}</td>\n ),\n tr: ({ children, ...props }: React.ComponentPropsWithoutRef<'tr'>) => (\n <tr {...props}>{children}</tr>\n ),\n p: ({ children, ...props }: React.ComponentPropsWithoutRef<'p'>) => (\n <p className=\"whitespace-pre-wrap\" {...props}>\n {children}\n </p>\n ),\n hr: (props: React.ComponentPropsWithoutRef<'hr'>) => (\n <hr className=\"border-foreground/20\" {...props} />\n ),\n sup: ({ children, ...props }: React.ComponentPropsWithoutRef<'sup'>) => (\n <sup className=\"text-xs\" {...props}>\n {children}\n </sup>\n ),\n sub: ({ children, ...props }: React.ComponentPropsWithoutRef<'sub'>) => (\n <sub className=\"text-xs\" {...props}>\n {children}\n </sub>\n ),\n div: ({ children, className, ...props }: React.ComponentPropsWithoutRef<'div'>) => (\n <div className={className} {...props}>\n {children}\n </div>\n ),\n br: (props: React.ComponentPropsWithoutRef<'br'>) => <br {...props} />,\n kbd: ({ children, ...props }: React.ComponentPropsWithoutRef<'kbd'>) => (\n <kbd\n className=\"px-1.5 py-0.5 text-xs font-mono bg-muted border border-border rounded\"\n {...props}\n >\n {children}\n </kbd>\n ),\n abbr: ({ children, title, ...props }: React.ComponentPropsWithoutRef<'abbr'>) => (\n <abbr title={title} className=\"underline decoration-dotted cursor-help\" {...props}>\n {children}\n </abbr>\n ),\n cite: ({ children, ...props }: React.ComponentPropsWithoutRef<'cite'>) => (\n <cite className=\"italic\" {...props}>\n {children}\n </cite>\n ),\n}\n","import { createContext } from 'react'\n\n/**\n * Signals to `MarkdownRenderer`'s component overrides that the surrounding\n * message is still streaming tokens. Heavy renderers can defer their work while\n * this is true to avoid burning CPU on partially complete fences and to keep the\n * UI responsive during long generations.\n *\n * Default `false` means non-streaming usages (parsed documents, static answers,\n * DM bubbles) get the full rendering with no behaviour change.\n */\nexport const MarkdownStreamingContext = createContext(false)\n","/**\n * Splits a markdown string into top-level blocks at `\\n\\n` boundaries.\n *\n * Streaming AI responses arrive token-by-token; passing the full string to\n * react-markdown re-parses the entire AST on every flush. By splitting into\n * blocks and memoizing each, only the trailing (still-growing) block re-parses\n * — completed blocks stay frozen in the DOM.\n *\n * The split avoids three correctness pitfalls:\n * - never splits inside an open ``` code fence (would corrupt the language)\n * - never splits between two adjacent list items (would render as two lists)\n * - never splits between two blockquote lines (would render as two quotes)\n */\nconst LIST_ITEM_RE = /^\\s*([-*+]|\\d+[.)])\\s/\nconst BLOCKQUOTE_RE = /^\\s*>/\n\nexport function splitMarkdownBlocks(content: string): string[] {\n if (!content) return []\n const blocks: string[] = []\n let start = 0\n let inFence = false\n let i = 0\n while (i < content.length) {\n if (content.startsWith('```', i)) {\n inFence = !inFence\n i += 3\n continue\n }\n if (!inFence && content[i] === '\\n' && content[i + 1] === '\\n') {\n const before = content.slice(start, i)\n const lastLine = before.slice(before.lastIndexOf('\\n') + 1)\n const afterStart = i + 2\n const nextNewline = content.indexOf('\\n', afterStart)\n const nextLine = content.slice(afterStart, nextNewline === -1 ? undefined : nextNewline)\n const bothListItems = LIST_ITEM_RE.test(lastLine) && LIST_ITEM_RE.test(nextLine)\n const bothBlockquotes = BLOCKQUOTE_RE.test(lastLine) && BLOCKQUOTE_RE.test(nextLine)\n if (bothListItems || bothBlockquotes) {\n i += 2\n continue\n }\n blocks.push(content.slice(start, afterStart))\n start = afterStart\n i = afterStart\n continue\n }\n i++\n }\n if (start < content.length) blocks.push(content.slice(start))\n return blocks\n}\n","import React, { useCallback, useEffect, useMemo, useReducer, useRef, useState } from 'react'\nimport Markdown, { type Components, type Options as MarkdownOptions } from 'react-markdown'\nimport remarkGfm from 'remark-gfm'\nimport rehypeRaw from 'rehype-raw'\nimport rehypeSanitize, { defaultSchema, type Options as SanitizeSchema } from 'rehype-sanitize'\nimport rehypeSlug from 'rehype-slug'\nimport { Copy, Check } from 'lucide-react'\nimport { cn } from '../lib/utils'\nimport { markdownBaseComponents } from './markdown-base-components'\nimport { MarkdownStreamingContext } from './markdown-streaming-context'\nimport { splitMarkdownBlocks } from './split-markdown-blocks'\nimport { closeOpenEmphasis, normalizeCitationMarkup, trimOpenCitation } from './normalize-citations'\n\n/** remark/rehype plugin lists, as react-markdown takes them. */\ntype PluggableList = NonNullable<MarkdownOptions['rehypePlugins']>\n\n/**\n * MarkdownRenderer — the single, full-featured markdown surface for the kit.\n *\n * Renders AI answers, chat/DM messages and parsed-document panes with one house\n * style: headings, paragraphs, bold/italic, ordered/unordered lists, GFM tables,\n * fenced code blocks (monospace + copy button), inline code, blockquotes, safe\n * links (`rel=\"noopener\"`, new tab) and horizontal rules.\n *\n * Styling is 100% semantic Tailwind tokens (`text-foreground`,\n * `text-muted-foreground`, `border-border`, `bg-muted`, `text-primary`) so it\n * themes per firm — no hardcoded brand colours. It sizes to its container, so it\n * looks right in a compact chat bubble and in a full-width document pane alike.\n *\n * Streaming: the content is split into block-level chunks (see\n * `splitMarkdownBlocks`) and each chunk is memoised, so streaming token updates\n * only re-parse the trailing block instead of the whole message. Pass\n * `isStreaming` to let heavy custom components defer via `MarkdownStreamingContext`.\n *\n * Safety: inline HTML (redlines, `<mark>` highlights, parser tables) is parsed and then sanitised\n * (`markdownSanitizeSchema`), so a model or a document cannot inject scripts, handlers or styles.\n * Headings get slug ids, so `#section` links and bookmarks land.\n *\n * Math: `$…$` and `$$…$$` are typeset with KaTeX. remark-math, rehype-katex and KaTeX's CSS\n * (~90 kB gzip) load only once some content actually contains math. A `$` before a digit is a\n * currency sign, never a formula delimiter.\n *\n * Extending: pass `components` to override any element (the kit's `AiMarkdown`\n * and `CitationRenderer` layer their accent links / citation popovers on top; a host composes\n * `MarkdownLink` / `MarkdownCode` into its own overrides), and `rehypePlugins` for trusted\n * transforms that run after sanitising (e.g. turning entity ids into pills).\n */\n\nconst EDGE_FADE = '1.5rem'\n\n/**\n * A GFM table in its own horizontal scroller. The table keeps a minimum width per column\n * (`min-w-[7rem]` cells, words never broken mid-word), so on a narrow screen it scrolls sideways\n * inside this wrapper instead of squeezing cells to a letter per line. The edge(s) with more\n * content to scroll to fade out, which is the scroll hint. Wide containers are unchanged: the\n * table is `w-full` and nothing overflows.\n */\nfunction MarkdownTable({ children, ...props }: React.ComponentPropsWithoutRef<'table'>) {\n const ref = useRef<HTMLDivElement>(null)\n const [edges, setEdges] = useState({ start: false, end: false })\n const measure = useCallback(() => {\n const el = ref.current\n if (!el) return\n const start = el.scrollLeft > 1\n const end = el.scrollLeft + el.clientWidth < el.scrollWidth - 1\n setEdges((prev) => (prev.start === start && prev.end === end ? prev : { start, end }))\n }, [])\n useEffect(() => {\n const el = ref.current\n if (!el) return\n measure()\n if (typeof ResizeObserver === 'undefined') return\n const observer = new ResizeObserver(measure)\n observer.observe(el)\n if (el.firstElementChild) observer.observe(el.firstElementChild)\n return () => observer.disconnect()\n }, [measure])\n const mask =\n edges.start || edges.end\n ? `linear-gradient(to right, ${edges.start ? 'transparent' : '#000'}, #000 ${EDGE_FADE}, #000 calc(100% - ${EDGE_FADE}), ${edges.end ? 'transparent' : '#000'})`\n : undefined\n return (\n <div\n ref={ref}\n onScroll={measure}\n data-testid=\"markdown-table-scroller\"\n data-scroll-start={edges.start || undefined}\n data-scroll-end={edges.end || undefined}\n className=\"my-3 overflow-x-auto rounded-lg border border-border\"\n style={mask ? { maskImage: mask, WebkitMaskImage: mask } : undefined}\n >\n <table\n data-testid=\"markdown-table\"\n className=\"w-full border-collapse text-sm [overflow-wrap:normal] [word-break:normal]\"\n {...props}\n >\n {children}\n </table>\n </div>\n )\n}\n\n/** Fenced code block with a language label and copy-to-clipboard button. */\nfunction CodeBlock({ language, code }: { language: string; code: string }) {\n const [copied, setCopied] = useState(false)\n\n const handleCopy = async () => {\n try {\n await navigator.clipboard.writeText(code)\n setCopied(true)\n setTimeout(() => setCopied(false), 2000)\n } catch {\n // Clipboard unavailable (insecure context / permissions) — no-op.\n }\n }\n\n return (\n <div\n className=\"code-block relative my-3 overflow-hidden rounded-md border border-current/20 bg-current/5\"\n data-testid=\"markdown-code-block\"\n >\n <div className=\"flex items-center justify-between border-b border-current/20 px-3 py-1.5\">\n <span className=\"font-mono text-xs text-muted-foreground\">{language || 'code'}</span>\n <button\n type=\"button\"\n onClick={handleCopy}\n className=\"flex items-center gap-1 text-xs text-muted-foreground transition-colors hover:text-foreground\"\n title={copied ? 'Copied!' : 'Copy code'}\n >\n {copied ? <Check size={12} /> : <Copy size={12} />}\n <span>{copied ? 'Copied' : 'Copy'}</span>\n </button>\n </div>\n <pre className=\"overflow-x-auto p-3 text-sm leading-relaxed\">\n <code className={cn('font-mono', language && `language-${language}`)}>{code}</code>\n </pre>\n </div>\n )\n}\n\n/**\n * Links. Internal hash/anchor links stay in-page; everything else opens safely in a new tab\n * (`rel=\"noopener noreferrer\"` prevents reverse-tabnabbing). A backend citation marker\n * (`#cite-N`) has no popover here: the cited words stay in the surface's own colour with a quiet\n * superscript number after them (no underline, so a cited sentence does not read as a link).\n * Pass `renderCitation` to `MarkdownRenderer` to swap in a real source popover.\n */\nexport function MarkdownLink({ href, children, ...props }: React.ComponentPropsWithoutRef<'a'>) {\n if (href?.startsWith('#cite-')) {\n return (\n <span\n className=\"cited-text after:ml-px after:align-super after:text-[max(0.8em,var(--text-xs))] after:font-semibold after:text-muted-foreground after:content-[attr(data-cite)]\"\n data-cite={href.slice(6)}\n >\n {children}\n </span>\n )\n }\n const isInternal = !href || href.startsWith('#') || href.startsWith('cite:')\n return (\n <a\n className=\"text-primary underline underline-offset-2\"\n href={href}\n // A `cite:` reference is not a place to go: the click must not navigate.\n onClick={href?.startsWith('cite:') ? (e) => e.preventDefault() : undefined}\n {...(isInternal ? {} : { target: '_blank', rel: 'noopener noreferrer' })}\n {...props}\n >\n {children}\n </a>\n )\n}\n\n/**\n * Inline code, and fenced code as a `CodeBlock` (language label + copy). Exported so a host's own\n * `code` override can handle its special cases (a diagram language, an id shown as a pill) and\n * hand everything else back here.\n */\nexport function MarkdownCode({\n className,\n children,\n ...props\n}: React.ComponentPropsWithoutRef<'code'>) {\n const match = /language-(\\w+)/.exec(className || '')\n if (!match) {\n return (\n <code\n className=\"rounded bg-current/10 px-1 py-0.5 font-mono text-[0.9em]\"\n data-testid=\"markdown-inline-code\"\n {...props}\n >\n {children}\n </code>\n )\n }\n return <CodeBlock language={match[1]} code={String(children).replace(/\\n$/, '')} />\n}\n\n/**\n * Default component overrides. Spreads the shared brand-neutral base\n * (`markdownBaseComponents`: headings, lists, paragraphs, emphasis, hr…) and adds\n * the elements that carry behaviour or need self-contained styling: safe links,\n * code (inline + fenced), bordered tables and blockquotes. Module-scoped so the\n * reference is stable across renders and react-markdown can skip re-parsing.\n */\nconst defaultComponents: Partial<Components> = {\n ...markdownBaseComponents,\n a: MarkdownLink,\n em: ({ children, ...props }: React.ComponentPropsWithoutRef<'em'>) => (\n <em className=\"italic\" {...props}>\n {children}\n </em>\n ),\n code: MarkdownCode,\n // The CodeBlock renders its own <pre>; unwrap react-markdown's wrapper so we\n // don't nest <pre><pre>.\n pre: ({ children }: React.ComponentPropsWithoutRef<'pre'>) => <>{children}</>,\n blockquote: ({ children, ...props }: React.ComponentPropsWithoutRef<'blockquote'>) => (\n <blockquote className=\"border-l-2 border-border pl-4 italic text-muted-foreground\" {...props}>\n {children}\n </blockquote>\n ),\n table: MarkdownTable,\n thead: ({ children, ...props }: React.ComponentPropsWithoutRef<'thead'>) => (\n <thead className=\"bg-current/10\" {...props}>\n {children}\n </thead>\n ),\n th: ({ children, ...props }: React.ComponentPropsWithoutRef<'th'>) => (\n <th\n className=\"min-w-[7rem] border-b border-border px-3 py-2 text-left font-semibold\"\n {...props}\n >\n {children}\n </th>\n ),\n td: ({ children, ...props }: React.ComponentPropsWithoutRef<'td'>) => (\n <td className=\"min-w-[7rem] border-b border-border px-3 py-2 align-top\" {...props}>\n {children}\n </td>\n ),\n // General emphasis marks (GFM `~~strikethrough~~` → <del>, raw <ins>/<mark>).\n del: ({ children, ...props }: React.ComponentPropsWithoutRef<'del'>) => (\n <del className=\"text-muted-foreground line-through\" {...props}>\n {children}\n </del>\n ),\n ins: ({ children, ...props }: React.ComponentPropsWithoutRef<'ins'>) => (\n <ins className=\"underline decoration-primary/60\" {...props}>\n {children}\n </ins>\n ),\n mark: ({ children, ...props }: React.ComponentPropsWithoutRef<'mark'>) => (\n <mark className=\"rounded bg-primary/15 px-0.5 text-inherit\" {...props}>\n {children}\n </mark>\n ),\n}\n\n/**\n * What survives sanitising inline HTML: GitHub's schema, plus the classes the downstream steps and\n * renderers read (KaTeX's `math-*` placeholders, `language-*` on code), `<mark>` for search\n * highlights, and `data-cid` on `<ins>`/`<del>` (the redline's per-change id, minted from diff\n * positions, never from content). Scripts, event handlers, inline styles and `javascript:` URLs\n * stay out.\n */\nexport const markdownSanitizeSchema: SanitizeSchema = {\n ...defaultSchema,\n tagNames: [...(defaultSchema.tagNames ?? []), 'mark'],\n attributes: {\n ...defaultSchema.attributes,\n span: [...(defaultSchema.attributes?.span ?? []), 'className'],\n div: [...(defaultSchema.attributes?.div ?? []), 'className'],\n code: [...(defaultSchema.attributes?.code ?? []), 'className'],\n pre: [...(defaultSchema.attributes?.pre ?? []), 'className'],\n ins: [...(defaultSchema.attributes?.ins ?? []), 'dataCid'],\n del: [...(defaultSchema.attributes?.del ?? []), 'dataCid'],\n },\n}\n\n// ── Lazy KaTeX (math) ──────────────────────────────────────────────────────\n// Loaded once, module-wide, the first time content with math renders; mounted renderers that\n// were waiting re-render when it lands.\ntype MathPlugins = { remarkMath: PluggableList[number]; rehypeKatex: PluggableList[number] }\nlet loadedMath: MathPlugins | null = null\nlet mathLoadStarted = false\nconst mathSubscribers = new Set<() => void>()\n\nfunction loadMath() {\n if (mathLoadStarted) return\n mathLoadStarted = true\n void Promise.all([\n import('remark-math'),\n import('rehype-katex'),\n import('katex/dist/katex.min.css'),\n ])\n .then(([remarkMath, rehypeKatex]) => {\n loadedMath = { remarkMath: remarkMath.default, rehypeKatex: rehypeKatex.default }\n mathSubscribers.forEach((notify) => notify())\n })\n .catch(() => {\n // Retry on the next math-bearing render if the chunk failed to load.\n mathLoadStarted = false\n })\n}\n\n// remark-math's inline rule: `$…$` with no whitespace just inside, or a `$$…$$` block. A lone\n// price (\"$5,000\") never matches.\nconst MATH_RE = /\\$\\$[\\s\\S]+?\\$\\$|(?<!\\\\)\\$(?![\\s$])(?:\\\\\\$|[^$\\n])+?(?<![\\s\\\\])\\$/\n\n/**\n * A `$` straight before a digit is a currency sign (\"$2,000\", \"≈$50,000\"), not the start of inline\n * math: two in one paragraph would otherwise pair up and typeset everything between as a formula.\n * Escape them (outside code, where a backslash would show) so they stay text.\n */\nfunction escapeCurrencyDollars(markdown: string): string {\n return markdown\n .split(/(```[\\s\\S]*?```|`[^`\\n]*`)/)\n .map((part, i) => (i % 2 === 1 ? part : part.replace(/(?<!\\\\)\\$(?=\\d)/g, '\\\\$')))\n .join('')\n}\n\n/** True once the math plugins are loaded for content that contains math. */\nfunction useMathReady(content: string): boolean {\n const hasMath = useMemo(() => MATH_RE.test(content), [content])\n const [, rerender] = useReducer((n: number) => n + 1, 0)\n useEffect(() => {\n if (!hasMath || loadedMath) return\n mathSubscribers.add(rerender)\n loadMath()\n return () => {\n mathSubscribers.delete(rerender)\n }\n }, [hasMath])\n return hasMath && loadedMath !== null\n}\n\nconst NO_PLUGINS: PluggableList = []\n\n/**\n * The remark/rehype pipelines. Raw HTML (when allowed) is parsed and sanitised before the trusted\n * steps (KaTeX, slugs, the host's plugins), so their output is not stripped again. Memoised on\n * its inputs so react-markdown sees stable arrays and memoised blocks do not re-parse.\n */\nfunction usePlugins(allowHtml: boolean, mathReady: boolean, extra: PluggableList) {\n return useMemo(() => {\n const math = mathReady && loadedMath ? loadedMath : null\n const remarkPlugins: PluggableList = math ? [remarkGfm, math.remarkMath] : [remarkGfm]\n const rehypePlugins: PluggableList = [\n // Text someone else wrote (a Word comment from any .docx): raw HTML stays text.\n ...(allowHtml ? [rehypeRaw, [rehypeSanitize, markdownSanitizeSchema]] : []),\n ...(math ? [math.rehypeKatex] : []),\n rehypeSlug,\n ...extra,\n ] as PluggableList\n return { remarkPlugins, rehypePlugins }\n }, [allowHtml, mathReady, extra])\n}\n\n/**\n * One parsed markdown block, memoised on (content, components) so already-rendered\n * blocks don't re-parse when a later block streams new tokens. This is the core\n * of the streaming-rendering optimisation.\n */\nconst MemoizedBlock = React.memo(function MarkdownBlock({\n content,\n components,\n remarkPlugins,\n rehypePlugins,\n}: {\n content: string\n components: Partial<Components>\n remarkPlugins: PluggableList\n rehypePlugins: PluggableList\n}) {\n return (\n <Markdown remarkPlugins={remarkPlugins} rehypePlugins={rehypePlugins} components={components}>\n {content}\n </Markdown>\n )\n})\n\n/** Prevents a malformed-markdown render error from crashing the whole surface. */\nclass MarkdownErrorBoundary extends React.Component<\n { fallback: React.ReactNode; children: React.ReactNode },\n { hasError: boolean }\n> {\n state = { hasError: false }\n static getDerivedStateFromError() {\n return { hasError: true }\n }\n render() {\n return this.state.hasError ? this.props.fallback : this.props.children\n }\n}\n\nexport interface MarkdownRendererProps {\n /** Markdown content to render. */\n children: string\n /** Custom component overrides merged on top of the defaults. */\n components?: Partial<Components>\n /**\n * When true, signals heavy custom components (via `MarkdownStreamingContext`)\n * to defer their work while tokens are still arriving. Defaults to false.\n */\n isStreaming?: boolean\n /**\n * Renders a citation marker `[words](#cite-N)`: `children` are the cited words, `num` the N.\n * Keep it referentially stable (`useCallback`/`useMemo`), or every block re-parses.\n */\n renderCitation?: (citation: { num: string; children: React.ReactNode }) => React.ReactNode\n /** Extra classes on the wrapper (font-size, prose width, etc.). */\n className?: string\n /** Overrides the `data-testid` on the wrapper (default `markdown-renderer`). */\n testId?: string\n /**\n * Inline HTML in the markdown becomes elements, sanitised (default). False keeps it as text: for\n * content from outside the app, such as a comment in a Word file anyone could have written.\n */\n allowHtml?: boolean\n /**\n * Trusted rehype plugins run after sanitising, KaTeX and heading slugs (e.g. a pass that turns\n * entity ids into elements the host's `components` render). Keep the array referentially\n * stable (module scope), or every block re-parses.\n */\n rehypePlugins?: PluggableList\n}\n\nfunction MarkdownRendererComponent({\n children,\n components: customComponents,\n renderCitation,\n isStreaming = false,\n className,\n testId = 'markdown-renderer',\n allowHtml = true,\n rehypePlugins: extraRehypePlugins = NO_PLUGINS,\n}: MarkdownRendererProps) {\n const components = useMemo(() => {\n const base = customComponents\n ? { ...defaultComponents, ...customComponents }\n : defaultComponents\n if (!renderCitation) return base\n const Link = base.a ?? MarkdownLink\n return {\n ...base,\n a: (props: React.ComponentPropsWithoutRef<'a'>) =>\n props.href?.startsWith('#cite-')\n ? renderCitation({ num: props.href.slice(6), children: props.children })\n : React.createElement(Link as React.ElementType, props),\n }\n }, [customComponents, renderCitation])\n\n const text = useMemo(() => {\n const escaped = escapeCurrencyDollars(children)\n return normalizeCitationMarkup(\n isStreaming ? closeOpenEmphasis(trimOpenCitation(escaped)) : escaped\n )\n }, [children, isStreaming])\n const blocks = useMemo(() => splitMarkdownBlocks(text), [text])\n const mathReady = useMathReady(text)\n const { remarkPlugins, rehypePlugins } = usePlugins(allowHtml, mathReady, extraRehypePlugins)\n\n return (\n <MarkdownErrorBoundary\n fallback={<div className={cn('whitespace-pre-wrap break-words', className)}>{children}</div>}\n >\n <MarkdownStreamingContext.Provider value={isStreaming}>\n <div\n className={cn('markdown-content space-y-3 break-words leading-relaxed', className)}\n data-testid={testId}\n >\n {blocks.map((block, index) => (\n <MemoizedBlock\n key={index}\n content={block}\n components={components}\n remarkPlugins={remarkPlugins}\n rehypePlugins={rehypePlugins}\n />\n ))}\n </div>\n </MarkdownStreamingContext.Provider>\n </MarkdownErrorBoundary>\n )\n}\n\n/**\n * Memoised so a stable message in a long thread doesn't re-parse when unrelated\n * tokens arrive elsewhere; a streaming message gets a fresh `children` each flush\n * and re-renders (only its trailing block re-parses, thanks to `MemoizedBlock`).\n */\nexport const MarkdownRenderer = React.memo(MarkdownRendererComponent)\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/notifications/notify-store.ts","../src/chat/chat-artifacts.ts"],"names":["create","renderToStaticMarkup","toast","saved","useSyncExternalStore"],"mappings":";;;;;;;;AAsFO,IAAM,yBAAA,GAA4B;AAuBzC,IAAI,GAAA,GAAM,CAAA;AACV,IAAM,GAAA,GAAM,MAAM,CAAA,CAAA,EAAI,IAAA,CAAK,GAAA,EAAI,CAAE,QAAA,CAAS,EAAE,CAAC,CAAA,EAAA,CAAI,GAAA,EAAA,EAAO,QAAA,CAAS,EAAE,CAAC,CAAA,CAAA;AAGpE,SAAS,WAAW,KAAA,EAA6C;AAC/D,EAAA,IAAI,OAAA,GAAU,CAAA;AACd,EAAA,OAAO,KAAA,CAAM,OAAO,CAAC,CAAA,KAAM,EAAE,MAAA,IAAU,EAAE,WAAW,yBAAyB,CAAA;AAC/E;AAEO,IAAM,SAAA,GAAYA,cAAA,CAAoB,CAAC,GAAA,MAAS;AAAA,EACrD,eAAe,EAAC;AAAA,EAChB,KAAA,EAAO,KAAA;AAAA,EACP,UAAU,CAAC,KAAA,KAAU,GAAA,CAAI,EAAE,OAAO,CAAA;AAAA,EAClC,QAAA,EAAU,CAAC,EAAA,KACT,GAAA,CAAI,CAAC,CAAA,MAAO;AAAA,IACV,aAAA,EAAe,CAAA,CAAE,aAAA,CAAc,GAAA,CAAI,CAAC,CAAA,KAAO,CAAA,CAAE,EAAA,KAAO,EAAA,GAAK,EAAE,GAAG,CAAA,EAAG,IAAA,EAAM,IAAA,KAAS,CAAE;AAAA,GACpF,CAAE,CAAA;AAAA,EACJ,aAAa,MACX,GAAA,CAAI,CAAC,CAAA,MAAO,EAAE,eAAe,CAAA,CAAE,aAAA,CAAc,IAAI,CAAC,CAAA,MAAO,EAAE,GAAG,CAAA,EAAG,MAAM,IAAA,EAAK,CAAE,GAAE,CAAE,CAAA;AAAA,EACpF,oBAAoB,CAAC,EAAA,KACnB,GA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SAAS,CAAA,GAC/E,MAAA;AAAA,IACN,MAAM;AAAA,GACR;AACF","file":"chunk-RLSBRZ6Z.cjs","sourcesContent":["/**\n * The one notification history: every `notify.*` call pops a transient toast (rendered by\n * <Toaster/>, on sonner) and, unless `{ record: false }`, records an entry. The same entries feed\n * the topbar bell (<NotificationBell/>), its unread badge and a host's notification page; backend\n * bridges reconcile their own slices into it with {@link syncSource}.\n *\n * notify.success('Saved') // toast + entry\n * notify.error('Upload failed', { record: false }) // toast only\n * notify.info('Opening workspace…', { ambient: true }) // a log line: never badges\n *\n * sonner owns the transient toast lifecycle (stacking, timing, dismissal); this store owns the\n * history, the mute switch and what a host configures once (workspace glyph and link, see\n * {@link configureNotify}; persistence, see {@link persistNotifyHistory}). Brand-neutral: no seed\n * data, no app imports. For full sonner power the raw `toast` is re-exported.\n */\nimport { type ReactNode } from 'react'\nimport { renderToStaticMarkup } from 'react-dom/server'\n// This module IS the sanctioned toast engine home — the app-level rule that\n// steers callers to notify() doesn't apply here.\n// eslint-disable-next-line no-restricted-imports\nimport { toast } from 'sonner'\nimport { create } from 'zustand'\n\nexport { toast }\n\nexport type NotifyVariant = 'success' | 'error' | 'info' | 'warning'\n\nexport interface AppNotification {\n id: string\n title: string\n description?: string\n variant: NotifyVariant\n /** Epoch ms the entry was recorded. */\n ts: number\n read: boolean\n /** Optional in-app link the entry deep-links to (passed to the bell's onNavigate). */\n href?: string\n /** Optional click action — wins over `href` when both are present. Session\n * history only: never persisted, so a closure is safe here. */\n onSelect?: () => void\n /** The label of the action `onSelect` runs (\"Reply\", \"View\"). */\n actionLabel?: string\n /** Workspace the entry belongs to. */\n workspaceId?: string\n /** Markup of a rich (non-string) toast message, for a log that shows it as it was toasted. */\n html?: string\n /** Routine session activity (\"Opening workspace…\", \"Saved\") — kept for the\n * log but not something that demands attention: excluded from the unread\n * badge and from the bell's list. */\n ambient?: boolean\n /** Where the entry comes from. Session entries (`notify.*`) have none; a\n * backend bridge stamps its own (e.g. 'server') so {@link syncSource} can\n * replace exactly its slice on every refetch without touching the rest. */\n source?: string\n}\n\nexport interface NotifyOptions {\n /** Shown under the title in the toast; a string description is also recorded. */\n description?: ReactNode\n /** Record an entry in the history (default true). False pops the toast only — for an event\n * whose entry arrives another way (a server-persisted notification synced by a bridge). */\n record?: boolean\n /** Pop the transient toast (default true unless muted). False records the entry only. */\n toast?: boolean\n /** Recorded title for a rich (non-string) toast title. Default: the string title, else the\n * rich title's text. */\n recordTitle?: string\n /** Recorded markup for a rich toast title (default: the title rendered to static markup). */\n html?: string\n href?: string\n /** Workspace the notification belongs to: its glyph shows in the toast and its link is the\n * entry's default `href` (both as configured with {@link configureNotify}). */\n workspaceId?: string\n duration?: number\n /** A toast action button (sonner). Clicking the entry runs it too. */\n action?: { label: ReactNode; onClick: () => void }\n /** Override the toast glyph (sonner). */\n icon?: ReactNode\n /** Extra class on the toast (sonner). */\n className?: string\n /** Record as routine session activity (see {@link AppNotification.ambient}): born read. */\n ambient?: boolean\n}\n\n/** Session entries kept (oldest dropped first) — a safety net against pathological growth; a\n * large upload can log many entries, so it is generous. Source slices are bounded by their source. */\nexport const MAX_SESSION_NOTIFICATIONS = 5000\n\ninterface NotifyState {\n notifications: AppNotification[]\n /** Toasts are muted: entries are still recorded — the history is what the user comes back to. */\n muted: boolean\n setMuted: (muted: boolean) => void\n markRead: (id: string) => void\n markAllRead: () => void\n removeNotification: (id: string) => void\n removeNotifications: (ids: readonly string[]) => void\n clearNotifications: () => void\n /** Replace the history (e.g. seed a demo/initial set). */\n seed: (items: AppNotification[]) => void\n /** Record an entry (used by `notify.*`; sonner renders the toast). */\n record: (note: AppNotification) => void\n /** Reconcile one source's slice with fresh truth (e.g. a backend list on\n * every refetch): entries stamped with `source` are replaced wholesale —\n * including their read state, which the source owns — while entries from\n * other sources (session activity) stay untouched. Newest first. */\n syncSource: (source: string, items: AppNotification[]) => void\n}\n\nlet seq = 0\nconst uid = () => `n${Date.now().toString(36)}${(seq++).toString(36)}`\n\n/** Keep at most {@link MAX_SESSION_NOTIFICATIONS} session entries (newest first). */\nfunction capSession(items: AppNotification[]): AppNotification[] {\n let session = 0\n return items.filter((n) => n.source || ++session <= MAX_SESSION_NOTIFICATIONS)\n}\n\nexport const useNotify = create<NotifyState>((set) => ({\n notifications: [],\n muted: false,\n setMuted: (muted) => set({ muted }),\n markRead: (id) =>\n set((s) => ({\n notifications: s.notifications.map((n) => (n.id === id ? { ...n, read: true } : n)),\n })),\n markAllRead: () =>\n set((s) => ({ notifications: s.notifications.map((n) => ({ ...n, read: true })) })),\n removeNotification: (id) =>\n set((s) => ({ notifications: s.notifications.filter((n) => n.id !== id) })),\n removeNotifications: (ids) => {\n const drop = new Set(ids)\n set((s) => ({ notifications: s.notifications.filter((n) => !drop.has(n.id)) }))\n },\n clearNotifications: () => set({ notifications: [] }),\n seed: (items) => set({ notifications: items }),\n record: (note) => set((s) => ({ notifications: capSession([note, ...s.notifications]) })),\n syncSource: (source, items) =>\n set((s) => ({\n notifications: [\n ...items.map((n) => ({ ...n, source })),\n ...s.notifications.filter((n) => n.source !== source),\n ].sort((a, b) => b.ts - a.ts),\n })),\n}))\n\n/** What a host configures once for every `notify.*` call. */\nexport interface NotifyConfig {\n /** The toast glyph of a notification that names a workspace. */\n workspaceIcon?: (workspaceId: string) => ReactNode\n /** The default link of an entry that names a workspace. */\n workspaceHref?: (workspaceId: string) => string | undefined\n /** The default of {@link NotifyOptions.ambient} for calls that do not say: a host whose own\n * toasts are mostly confirmations (\"Saved\") records them as log lines, and passes\n * `ambient: false` for what should claim attention. Default false. */\n ambient?: boolean\n}\n\nlet config: NotifyConfig = {}\n\n/** Set the host's workspace glyph and link (merged into what is configured). */\nexport function configureNotify(next: NotifyConfig): void {\n config = { ...config, ...next }\n}\n\nfunction richMarkup(title: ReactNode): string | undefined {\n try {\n return renderToStaticMarkup(title)\n } catch {\n return undefined\n }\n}\n\nconst textOf = (html: string | undefined) =>\n (html ?? '')\n .replace(/<[^>]+>/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim()\n\n/** Ergonomic helper — `notify.success('Saved')` — toast (sonner) + optional entry. */\nfunction make(variant: NotifyVariant) {\n return (title: ReactNode, opts: NotifyOptions = {}): string => {\n const { workspaceId } = opts\n const ambient = opts.ambient ?? config.ambient ?? false\n if (opts.toast !== false && !useNotify.getState().muted) {\n toast[variant](title, {\n description: opts.description,\n duration: opts.duration,\n action: opts.action,\n icon: opts.icon ?? (workspaceId ? config.workspaceIcon?.(workspaceId) : undefined),\n className: opts.className,\n })\n }\n const id = uid()\n if (opts.record !== false) {\n const html =\n opts.html ?? (typeof title === 'string' || title == null ? undefined : richMarkup(title))\n useNotify.getState().record({\n id,\n // A rich toast still needs a READABLE title — \"Passage copied: gamma-services p.1\",\n // not \"Notification\" — so it comes from the rendered markup, tags stripped.\n title:\n opts.recordTitle ?? (typeof title === 'string' ? title : textOf(html) || 'Notification'),\n description: typeof opts.description === 'string' ? opts.description : undefined,\n variant,\n ts: Date.now(),\n // Ambient activity is a log line, not a claim on attention: it never wears an unread dot.\n read: ambient,\n // Clicking the entry goes where the notification points: its action (when it has one),\n // an explicit link, or the workspace it happened in.\n href: opts.href ?? (workspaceId ? config.workspaceHref?.(workspaceId) : undefined),\n onSelect: opts.action?.onClick,\n actionLabel: opts.action ? String(opts.action.label) : undefined,\n workspaceId,\n html,\n ambient,\n })\n }\n return id\n }\n}\nexport const notify = {\n success: make('success'),\n error: make('error'),\n info: make('info'),\n warning: make('warning'),\n}\n\n/** Replace the history — inject a seed/initial set. */\nexport function seedNotifications(items: AppNotification[]): void {\n useNotify.getState().seed(items)\n}\n\ninterface SavedHistory {\n muted?: boolean\n notifications?: AppNotification[]\n}\n\n/**\n * Keep the session history and the mute switch across reloads in `storage` under `key`: restores\n * them now and saves every change. Source slices are not saved (their source re-syncs them), and\n * neither are actions — a closure does not survive a reload. Returns the unsubscribe.\n */\nexport function persistNotifyHistory(\n key: string,\n storage: Pick<Storage, 'getItem' | 'setItem'> | undefined = globalThis.localStorage\n): () => void {\n if (!storage) return () => {}\n try {\n const saved = JSON.parse(storage.getItem(key) ?? 'null') as SavedHistory | null\n if (saved) {\n const known = new Set(useNotify.getState().notifications.map((n) => n.id))\n useNotify.setState((s) => ({\n muted: saved.muted ?? s.muted,\n notifications: capSession(\n [\n ...s.notifications,\n ...(saved.notifications ?? []).filter((n) => !n.source && !known.has(n.id)),\n ].sort((a, b) => b.ts - a.ts)\n ),\n }))\n }\n } catch {\n // Unreadable or blocked storage: start empty.\n }\n let saved: AppNotification[] = []\n let savedMuted: boolean | undefined\n return useNotify.subscribe((s) => {\n const session = s.notifications.filter((n) => !n.source)\n // A backend re-sync or a read change elsewhere leaves the session slice as it was.\n if (\n s.muted === savedMuted &&\n session.length === saved.length &&\n session.every((n, i) => n === saved[i])\n )\n return\n saved = session\n savedMuted = s.muted\n // JSON drops the undefined fields: an action's closure cannot be saved, nor its label alone.\n const notifications = session.map((n) => ({\n ...n,\n onSelect: undefined,\n actionLabel: undefined,\n }))\n try {\n storage.setItem(key, JSON.stringify({ muted: s.muted, notifications }))\n } catch {\n // Full or blocked storage: the in-memory history still works.\n }\n })\n}\n\n/** Unread count selector for the topbar bell — ambient session activity never\n * demands attention, so it never counts. */\nexport const selectUnread = (s: NotifyState): number =>\n s.notifications.filter((n) => !n.read && !n.ambient).length\n\n/** Default glyph colour per variant (raw palette, override via `toneClassNames`). */\nexport const DEFAULT_NOTIFY_TONE: Record<NotifyVariant, string> = {\n success: 'text-green-600',\n error: 'text-destructive',\n warning: 'text-amber-500',\n info: 'text-blue-500',\n}\n","import { useSyncExternalStore } from 'react'\nimport type { ArtifactEvent } from '@arbidocs/sdk/browser'\n\n/**\n * The documents the assistant is writing (or wrote) in this tab's chats, as their artifact events\n * stream in: the chat engine records every one (`recordChatArtifact`), before the host's\n * `chat.onArtifact` shows it. One store for every surface that shows a draft as it is written: the\n * answer's artifact card, the document viewer, and a drafting chat's document pane.\n *\n * A module-level store, like the open-document registry: a chat and a viewer agree wherever they\n * sit in the tree. It holds what streamed in this tab only; a saved draft is read from the\n * documents list. Cleared on sign-out (`clearChatArtifacts`).\n */\n\n/** An artifact as it streams: what the events said so far. */\nexport interface ChatArtifact {\n /** The document it is written into (`doc-…`). */\n docExtId: string\n title: string\n /** The content so far (Markdown, or the html/react source of a live artifact). */\n content: string\n /**\n * `markdown` / `text` are document drafts (stored by the server as Word documents); `html` /\n * `react` are live artifacts; `image` is a generated image.\n */\n mode: 'markdown' | 'html' | 'text' | 'react' | 'image'\n isComplete: boolean\n version?: number | null\n /** The answer that writes it. */\n messageExtId?: string\n /** The conversation it is written in (`new` until the server named it). */\n conversationId: string\n createdAt: string\n}\n\nlet artifacts: Record<string, ChatArtifact> = {}\n/** Document ids, most recently started last. */\nlet order: string[] = []\nconst listeners = new Set<() => void>()\n\nfunction subscribe(listener: () => void): () => void {\n listeners.add(listener)\n return () => listeners.delete(listener)\n}\n\nfunction emit() {\n listeners.forEach((listener) => listener())\n}\n\n/** Record an artifact event of a chat turn in `conversationId`. */\nexport function recordChatArtifact(event: ArtifactEvent, conversationId: string): void {\n const previous = artifacts[event.doc_ext_id]\n const artifact: ChatArtifact = {\n docExtId: event.doc_ext_id,\n title: event.title,\n content: event.content,\n // The backend schema lags the 'react' mode it also sends; the value passes through unchanged.\n mode: event.mode as ChatArtifact['mode'],\n isComplete: event.is_complete,\n version: event.version,\n createdAt: new Date().toISOString(),\n messageExtId: event.message_ext_id ?? undefined,\n conversationId,\n }\n artifacts = { ...artifacts, [artifact.docExtId]: artifact }\n if (!previous) order = [...order, artifact.docExtId]\n emit()\n}\n\n/** Forget every streamed artifact (sign-out). */\nexport function clearChatArtifacts(): void {\n if (order.length === 0) return\n artifacts = {}\n order = []\n emit()\n}\n\n/** Every artifact streamed in this tab, by document id. */\nexport function getChatArtifacts(): Readonly<Record<string, ChatArtifact>> {\n return artifacts\n}\n\n/** The artifact streaming (or streamed) into this document, if one did in this tab. */\nexport function getChatArtifact(documentId: string | null | undefined) {\n return documentId ? artifacts[documentId] : undefined\n}\n\n/** The artifact streaming into this document, if one is. Re-renders as it streams. */\nexport function useChatArtifact(documentId: string | null | undefined) {\n return useSyncExternalStore(\n subscribe,\n () => getChatArtifact(documentId),\n () => undefined\n )\n}\n\n/** The artifact this answer writes (or wrote), if it did in this tab. */\nexport function useMessageChatArtifact(messageId: string | null | undefined) {\n return useSyncExternalStore(\n subscribe,\n () =>\n messageId\n ? Object.values(artifacts).find((artifact) => artifact.messageExtId === messageId)\n : undefined,\n () => undefined\n )\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/search/session.ts","../src/notifications/Toaster.tsx","../src/notifications/NotificationBell.tsx","../src/host/ArbiHost.tsx","../src/host/assistant-copy.ts","../src/chat/mentions.ts","../src/chat/open-document.ts","../src/chat/thread-document.ts"],"names":["createStore","storage","jsx","Sonner","CheckCircle2","XCircle","AlertTriangle","Info","useState","useNotify","selectUnread","DEFAULT_NOTIFY_TONE","jsxs","DropdownMenu","DropdownMenuTrigger","Bell","DropdownMenuContent","CheckCheck","cn","BellOff","DropdownMenuItem","X","ScrollArea","formatRelativeTime","useContext","ArbiHostContext","useMemo","mergeHostConfig","OWN_SESSION_SLOT","useHostConfigRecord","useRef","useEffect","useSyncExternalStore","parseVersionRef"],"mappings":";;;;;;;;;;;;;;;AA8BA,IAAM,KAAA,GAAyD;AAAA,EAC7D,KAAA,EAAO,EAAA;AAAA,EACP,SAAS,EAAC;AAAA,EACV,QAAA,EAAU,KAAA;AAAA,EACV,MAAA,EAAQ,MAAA;AAAA,EACR,KAAA,EAAO,IAAA;AAAA,EACP,OAAA,EAAS;AACX,CAAA;AAEO,SAAS,mBAAA,GAAqC;AACnD,EAAA,OAAOA,mBAAA,CAAgC,OAAO,EAAE,GAAG,OAAO,WAAA,EAAa,IAAA,EAAM,GAAA,EAAK,CAAA,EAAE,CAAE,CAAA;AACxF;AAGO,IAAM,sBAAqC,mBAAA;AAG3C,SAAS,kBAAA,CACd,WAA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AA,EAAA;AAC9B,MAAA,KAAA,MAAW,CAAC,cAAA,EAAgB,UAAU,CAAA,IAAK,MAAA,CAAO,QAAQ,MAAM,CAAA;AAC9D,QAAA,IAAI,OAAO,UAAA,KAAe,QAAA,EAAU,GAAA,CAAI,cAAc,CAAA,GAAI,UAAA;AAAA,IAAA;AAAA,EAChE,CAAA,CAAA,MAAQ;AAAA,EAER;AACA,EAAA,OAAO,GAAA;AACT;AAGO,SAAS,4BAA4B,eAAA,EAA0C;AACpF,EAAA,IAAI,eAAA,CAAgB,WAAW,CAAA,EAAG;AAClC,EAAA,MAAM,OAAO,yBAAA,EAA0B;AACvC,EAAA,eAAA,CAAgB,QAAQ,CAAC,EAAA,KAAO,OAAO,IAAA,CAAK,EAAE,CAAC,CAAA;AAC/C,EAAA,IAAI;AACF,IAAA,IAAI,MAAA,CAAO,KAAK,IAAI,CAAA,CAAE,WAAW,CAAA,EAAG,OAAA,EAAQ,EAAG,UAAA,CAAW,2BAA2B,CAAA;AAAA,kBACxE,EAAG,OAAA,CAAQ,6BAA6B,IAAA,CAAK,SAAA,CAAU,IAAI,CAAC,CAAA;AAAA,EAC3E,CAAA,CAAA,MAAQ;AAAA,EAER;AACF","file":"chunk-Z3W4XFWB.cjs","sourcesContent":["/**\n * A search's state outside any component: the query last searched, its passages, and whether it\n * is running. A page that shows the shared session (`sharedSearchSession`) keeps its results when\n * it is left and opened again, another surface can hand it a query to run on arrival\n * ({@link requestSearch}), and {@link persistSearchSession} keeps the last query across reloads.\n */\nimport { createStore, type StoreApi } from 'zustand/vanilla'\nimport type { SearchChunk } from '@arbidocs/sdk/browser'\n\nexport type SearchStatus = 'idle' | 'running' | 'done' | 'error'\n\nexport interface SearchSessionState {\n /** The workspace the query and results belong to. */\n workspaceId: string | null\n /** The query last searched, or handed over to run. */\n query: string\n /** The last search's passages, best first. */\n results: SearchChunk[]\n /** A search has finished with results to show (cleared by {@link clearSearchSession}). */\n searched: boolean\n status: SearchStatus\n error: string | null\n /** A query handed over by {@link requestSearch}, run once by the page that shows the session. */\n pending: string | null\n /** Counts searches, so the reply to an older one never overwrites a newer one. */\n run: number\n}\n\nexport type SearchSession = StoreApi<SearchSessionState>\n\nconst EMPTY: Omit<SearchSessionState, 'workspaceId' | 'run'> = {\n query: '',\n results: [],\n searched: false,\n status: 'idle',\n error: null,\n pending: null,\n}\n\nexport function createSearchSession(): SearchSession {\n return createStore<SearchSessionState>(() => ({ ...EMPTY, workspaceId: null, run: 0 }))\n}\n\n/** The session a host's search page shows. */\nexport const sharedSearchSession: SearchSession = createSearchSession()\n\n/** Back to nothing searched (in `workspaceId` when given); a running search's reply is dropped. */\nexport function clearSearchSession(\n workspaceId?: string | null,\n session: SearchSession = sharedSearchSession\n): void {\n session.setState((s) => ({\n ...EMPTY,\n workspaceId: workspaceId === undefined ? s.workspaceId : workspaceId,\n run: s.run + 1,\n }))\n}\n\n/**\n * Hand a query to the search page, which runs it when it shows the session (the user already\n * asked once; the page must not wait for a second Enter).\n */\nexport function requestSearch(\n query: string,\n workspaceId: string | null,\n session: SearchSession = sharedSearchSession\n): void {\n clearSearchSession(workspaceId, session)\n session.setState({ query, pending: query })\n}\n\n/** The handed-over query, once: the next call returns null. */\nexport function takePendingSearch(session: SearchSession = sharedSearchSession): string | null {\n const { pending } = session.getState()\n if (pending !== null) session.setState({ pending: null })\n return pending\n}\n\ninterface SavedSearch {\n query?: string\n workspaceId?: string | null\n}\n\n/**\n * Keep the last query (and its workspace) in `storage` under `key`, so the search box shows it\n * after a reload. Results are not kept. Returns the unsubscribe.\n */\nexport function persistSearchSession(\n key: string,\n storage: Pick<Storage, 'getItem' | 'setItem'> | undefined = globalThis.localStorage,\n session: SearchSession = sharedSearchSession\n): () => void {\n if (!storage) return () => {}\n try {\n const saved = JSON.parse(storage.getItem(key) ?? 'null') as SavedSearch | null\n if (saved && typeof saved.query === 'string' && !session.getState().query)\n session.setState({ query: saved.query, workspaceId: saved.workspaceId ?? null })\n } catch {\n // Unreadable: start empty.\n }\n let last = ''\n return session.subscribe(({ query, workspaceId }) => {\n const next = JSON.stringify({ query, workspaceId })\n if (next === last) return\n last = next\n try {\n storage.setItem(key, next)\n } catch {\n // Storage full or blocked: the query is simply not kept.\n }\n })\n}\n","/**\n * Toaster — the one shared toast surface, built on sonner (the mature engine:\n * stacking, swipe-to-dismiss, a11y, timing). Mount once near the app root; any\n * code then calls `notify.*(...)` (or the re-exported `toast`) from anywhere.\n *\n * Firm-agnostic: every sonner `ToasterProps` passes through, so a consumer sets\n * its own `position` / `theme` / `toastOptions`. The defaults give a neutral\n * shadcn-token card that both apps can override.\n */\nimport { Toaster as Sonner, type ToasterProps } from 'sonner'\n\nexport type { ToasterProps }\n\nconst DEFAULT_TOAST_OPTIONS: ToasterProps['toastOptions'] = {\n classNames: {\n toast:\n 'group toast group-[.toaster]:bg-card group-[.toaster]:text-foreground group-[.toaster]:border group-[.toaster]:border-border group-[.toaster]:shadow-lg group-[.toaster]:rounded-lg',\n description: 'group-[.toast]:text-muted-foreground',\n actionButton: 'group-[.toast]:bg-primary group-[.toast]:text-primary-foreground',\n cancelButton: 'group-[.toast]:bg-muted group-[.toast]:text-muted-foreground',\n },\n}\n\nexport function Toaster({ toastOptions, ...props }: ToasterProps) {\n return (\n <Sonner\n className=\"toaster group\"\n toastOptions={toastOptions ?? DEFAULT_TOAST_OPTIONS}\n {...props}\n />\n )\n}\n","/**\n * NotificationBell — the topbar notification centre: a bell with an unread badge\n * that opens a dropdown of recorded entries (newest first) with an unread dot,\n * relative time and optional deep-link. \"Mark all read\" clears the badge. Backed\n * by the shared {@link useNotify} store (the same one the <Toaster/> renders).\n *\n * Firm-agnostic: navigation is a callback (`onNavigate`), styling tracks semantic\n * tokens, and per-variant glyph colours are overridable via `toneClassNames`.\n */\nimport { useState, type ReactElement } from 'react'\nimport {\n Bell,\n BellOff,\n CheckCheck,\n CheckCircle2,\n AlertTriangle,\n XCircle,\n Info,\n X,\n} from 'lucide-react'\nimport {\n DropdownMenu,\n DropdownMenuTrigger,\n DropdownMenuContent,\n DropdownMenuItem,\n} from '../ui/dropdown-menu'\nimport { ScrollArea } from '../ui/scroll-area'\nimport { cn } from '../lib/utils'\nimport { formatRelativeTime } from '../lib/format-relative-time'\nimport {\n useNotify,\n selectUnread,\n DEFAULT_NOTIFY_TONE,\n type NotifyVariant,\n type AppNotification,\n} from './notify-store'\n\nconst GLYPH: Record<NotifyVariant, typeof Info> = {\n success: CheckCircle2,\n error: XCircle,\n warning: AlertTriangle,\n info: Info,\n}\n\n/** Entries the panel lists, newest first. */\nconst BELL_LIMIT = 100\n\n/** What a custom bell trigger needs to render itself. */\nexport interface NotificationBellTriggerState {\n /** Unread count (0 when none). */\n unread: number\n /** Accessible name, including the count: \"Notifications, 2 unread\". */\n ariaLabel: string\n testId: string\n}\n\nexport interface NotificationBellProps {\n /**\n * Replaces the default icon button with the host's own trigger (for example a labelled sidebar\n * row). It must forward its ref and rest props: it is mounted as the dropdown trigger.\n */\n renderTrigger?: (state: NotificationBellTriggerState) => ReactElement\n /** Called with an entry's `href` when it's clicked (e.g. router navigate). */\n onNavigate?: (href: string) => void\n /** Open this entry in the host notification centre instead of following its link. */\n onSelectNotification?: (notification: AppNotification) => void\n /** Called after an entry is locally marked read — the hook for a backend\n * bridge to propagate read state upstream (filter by the ids it owns). */\n onMarkRead?: (id: string) => void\n /** Called after \"Mark all read\" — same upstream-propagation hook. */\n onMarkAllRead?: () => void\n /** Show the store's toast mute switch in the header — the bell is where notification\n * behaviour is controlled. */\n showMuteToggle?: boolean\n /** Override per-variant glyph colours (e.g. brand emerald for success). */\n toneClassNames?: Partial<Record<NotifyVariant, string>>\n emptyText?: string\n /** Footer link to the app's full notification surface. Omit to hide. */\n onViewAll?: () => void\n viewAllLabel?: string\n testId?: string\n /** Where the panel opens relative to the bell (a sidebar-footer bell opens upward). */\n side?: 'top' | 'right' | 'bottom' | 'left'\n align?: 'start' | 'center' | 'end'\n}\n\nexport function NotificationBell({\n renderTrigger,\n onNavigate,\n onSelectNotification,\n onMarkRead,\n onMarkAllRead,\n showMuteToggle = false,\n toneClassNames,\n emptyText = \"You're all caught up.\",\n onViewAll,\n viewAllLabel = 'View all',\n testId = 'notifications',\n side = 'bottom',\n align = 'end',\n}: NotificationBellProps) {\n const [open, setOpen] = useState(false)\n const notifications = useNotify((s) => s.notifications)\n const unread = useNotify(selectUnread)\n const markAllRead = useNotify((s) => s.markAllRead)\n const markRead = useNotify((s) => s.markRead)\n const muted = useNotify((s) => s.muted)\n const setMuted = useNotify((s) => s.setMuted)\n const tone = (v: NotifyVariant) => toneClassNames?.[v] ?? DEFAULT_NOTIFY_TONE[v]\n\n // Ambient entries (routine session activity — \"Opening workspace…\") are kept\n // for the log but never surfaced in the bell panel: they never badge and are\n // always filtered out here. The panel is the recent history; a host's\n // notification page (`onViewAll`) holds the rest.\n const visible = notifications.filter((n) => !n.ambient).slice(0, BELL_LIMIT)\n\n return (\n <DropdownMenu open={open} onOpenChange={setOpen}>\n <DropdownMenuTrigger asChild>\n {renderTrigger ? (\n renderTrigger({\n unread,\n ariaLabel: `Notifications${unread ? `, ${unread} unread` : ''}`,\n testId,\n })\n ) : (\n <button\n className=\"relative flex size-9 pointer-coarse:size-11 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground\"\n data-testid={testId}\n aria-label={`Notifications${unread ? `, ${unread} unread` : ''}`}\n title=\"Notifications\"\n >\n <Bell className=\"size-5\" />\n {unread > 0 && (\n <span\n className=\"absolute -right-0.5 -top-0.5 flex min-w-4 items-center justify-center rounded-full bg-primary px-1 text-xs font-semibold leading-4 text-primary-foreground\"\n data-testid={`${testId}-badge`}\n >\n {unread > 9 ? '9+' : unread}\n </span>\n )}\n </button>\n )}\n </DropdownMenuTrigger>\n <DropdownMenuContent\n align={align}\n side={side}\n sideOffset={8}\n collisionPadding={12}\n className=\"w-60 rounded-lg border-border/60 p-0 shadow-lg pointer-coarse:w-88\"\n data-testid={`${testId}-panel`}\n data-topbar-popover=\"\"\n >\n <div className=\"flex items-center justify-between gap-3 border-b border-border px-3.5 py-2.5 pointer-coarse:py-0\">\n <p className=\"text-sm font-semibold text-foreground\">Notifications</p>\n <div className=\"flex items-center gap-3 pointer-coarse:gap-1\">\n {unread > 0 && (\n <button\n onClick={() => {\n markAllRead()\n onMarkAllRead?.()\n }}\n className=\"flex items-center gap-1 text-xs font-medium text-primary transition-colors hover:opacity-80 pointer-coarse:min-h-11 pointer-coarse:px-2\"\n data-testid={`${testId}-mark-all`}\n >\n <CheckCheck className=\"size-3.5\" /> Mark all read\n </button>\n )}\n {showMuteToggle && (\n <button\n onClick={() => setMuted(!muted)}\n aria-pressed={muted}\n title={muted ? 'Unmute notifications' : 'Mute notifications'}\n aria-label={muted ? 'Unmute notifications' : 'Mute notifications'}\n className={cn(\n 'flex size-6 shrink-0 items-center justify-center rounded-md transition-colors hover:bg-accent pointer-coarse:size-11',\n muted ? 'text-foreground' : 'text-muted-foreground hover:text-foreground'\n )}\n data-testid={`${testId}-mute`}\n >\n <BellOff className=\"size-3.5\" />\n </button>\n )}\n {/* Explicit close — the dropdown otherwise only dismisses via\n tap-outside/Escape, which isn't discoverable on touch and (at\n mobile width, see blocks.css) the panel covers most\n of the screen so there's nothing to tap outside of. Radix\n closes a DropdownMenu on any item select by default, so a\n plain item with no other effect doubles as a close button. */}\n <DropdownMenuItem\n className=\"flex size-6 shrink-0 items-center justify-center rounded-md p-0 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus:bg-accent pointer-coarse:size-11\"\n aria-label=\"Close notifications\"\n data-testid={`${testId}-close`}\n >\n <X className=\"size-3.5\" />\n </DropdownMenuItem>\n </div>\n </div>\n {muted && (\n <p\n className=\"border-b border-border/60 bg-amber-500/10 px-3.5 py-1.5 text-xs text-muted-foreground\"\n data-testid={`${testId}-muted-note`}\n >\n Toasts are muted — everything still lands here.\n </p>\n )}\n\n {visible.length === 0 ? (\n <div className=\"px-3.5 py-10 text-center text-sm text-muted-foreground\">{emptyText}</div>\n ) : (\n <ScrollArea className=\"max-h-[380px]\">\n <ul data-testid={`${testId}-list`}>\n {visible.map((n) => {\n const Glyph = GLYPH[n.variant]\n return (\n <li key={n.id}>\n <button\n onClick={() => {\n markRead(n.id)\n if (!n.read) onMarkRead?.(n.id)\n setOpen(false)\n if (onSelectNotification) {\n onSelectNotification(n)\n return\n }\n // The specific action wins over the generic deep link.\n if (n.onSelect) n.onSelect()\n else if (n.href) onNavigate?.(n.href)\n }}\n className={cn(\n 'flex w-full items-start gap-3 border-b border-border/60 px-3.5 py-3 text-left transition-colors hover:bg-accent',\n !n.read && 'bg-accent/40'\n )}\n data-testid={`${testId}-item`}\n data-notification-id={n.id}\n >\n <Glyph className={cn('mt-0.5 size-4 shrink-0', tone(n.variant))} />\n <div className=\"min-w-0 flex-1\">\n <p className=\"text-sm font-medium leading-snug text-foreground\">\n {n.title}\n </p>\n {n.description && (\n <p className=\"mt-0.5 line-clamp-2 text-xs leading-relaxed text-muted-foreground\">\n {n.description}\n </p>\n )}\n <p className=\"mt-1 text-xs text-muted-foreground/80\">\n {formatRelativeTime(new Date(n.ts).toISOString())}\n </p>\n </div>\n {(n.onSelect || n.href) && (\n <span className=\"shrink-0 self-center rounded-md bg-primary/10 px-2 py-1 text-xs font-medium text-primary\">\n {n.actionLabel ?? 'Open'}\n </span>\n )}\n {!n.read && (\n <span className=\"mt-1.5 size-2 shrink-0 rounded-full bg-primary\" />\n )}\n </button>\n </li>\n )\n })}\n </ul>\n </ScrollArea>\n )}\n {onViewAll && (\n // A real menu item, not a bare button: selecting it must CLOSE the\n // dropdown on its way to the full surface.\n <DropdownMenuItem\n onClick={onViewAll}\n className=\"justify-center rounded-none border-t border-border px-3.5 py-2.5 text-xs font-medium text-primary focus:text-primary pointer-coarse:min-h-11\"\n data-testid={`${testId}-view-all`}\n >\n {viewAllLabel}\n </DropdownMenuItem>\n )}\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n","/**\n * `<ArbiHost config>`: the one place a host app hands its configuration to every hook and kit.\n *\n * <ArbiHost config={{ arbi, session, documents, calendar, mail, account, … }}>\n * <App />\n * </ArbiHost>\n *\n * Every field is optional and has a default (see `ArbiHostConfig`); a kit reads its domain from\n * the config (`useArbiHost().documents`, `useHost().billing` in blocks). A nested `<ArbiHost>`\n * overrides only the fields it gives and inherits the rest (`environment` field by field), for a\n * subtree that opens projects in its own tabs, say. There is no other host provider: a new domain\n * is a new optional field, never a new provider.\n *\n * SDK-free (this module, ./context, ./merge and the entity vocabulary are all it reaches), so a\n * marketing site that only sets the blocks environment does not bundle the SDK.\n */\n\nimport { useContext, useMemo, useState, type ComponentType, type ReactNode } from 'react'\nimport { ArbiHostContext } from './context'\nimport { mergeHostConfig, OWN_SESSION_SLOT } from './merge'\nimport { configureEntityVocabulary, type EntityVocabulary } from '../entities/vocabulary'\n\n/** A sign-in layer mounted inside the host (`defaultHost` in `@arbidocs/blocks/connect`). */\nexport interface ArbiHostConnection {\n Provider: ComponentType<{ children: ReactNode }>\n}\n\nexport interface ArbiHostProps<Config extends object> {\n config: Config\n children?: ReactNode\n}\n\n/**\n * Provide the host configuration. Typed by the package it is imported from: `@arbidocs/react`'s\n * takes the react domains, `@arbidocs/blocks`' the blocks domains as well.\n */\nexport function ArbiHost<Config extends object>({\n config,\n children,\n}: ArbiHostProps<Config>): React.ReactElement {\n const parent = useContext(ArbiHostContext)\n // A top-level host without a session store gets its own, made on first use (useArbiSessionStore).\n const [ownSession] = useState(() => ({ current: null as unknown }))\n const value = useMemo(() => {\n const merged = mergeHostConfig(parent, config)\n return merged[OWN_SESSION_SLOT] ? merged : { ...merged, [OWN_SESSION_SLOT]: ownSession }\n }, [parent, config, ownSession])\n // The site's nouns are in place before any kit below renders a label.\n const { vocabulary } = config as { vocabulary?: EntityVocabulary }\n if (vocabulary) configureEntityVocabulary(vocabulary)\n const Connection = (config as { connection?: ArbiHostConnection }).connection?.Provider\n return (\n <ArbiHostContext.Provider value={value}>\n {Connection ? <Connection>{children}</Connection> : children}\n </ArbiHostContext.Provider>\n )\n}\n","/**\n * What the kits call the assistant in their own words, from the host's name for it\n * (`ArbiHostConfig.assistantName`, also what people @mention). One label source: every kit phrase\n * that names the assistant is here, written once around the name, so a custom site's name shows\n * everywhere and ARBI's own text is unchanged (\"ARBI\" when the host names it nothing else).\n *\n * const copy = useAssistantCopy()\n * <Button>{copy.ask}</Button> // \"Ask ARBI\", or \"Ask Acme Assistant\"\n *\n * SDK-free: exported from `@arbidocs/react/shell` too, for presentational parts.\n */\nimport { useMemo } from 'react'\n// The record, not `useArbiHost` (`./config` names the SDK's types): this module stays SDK-free.\nimport { useHostConfigRecord } from './context'\n\n/** The assistant's name when the host names it nothing else. */\nexport const DEFAULT_ASSISTANT_NAME = 'ARBI'\n\n/** Every kit phrase that names the assistant. */\nexport interface AssistantCopy {\n /** The name itself. */\n name: string\n /** \"Ask ARBI\": a button or tab that starts a question. */\n ask: string\n /** \"Ask ARBI anything\": an empty list's call to ask. */\n askAnything: string\n /** \"Ask ARBI anything…\": the chat composer's placeholder. */\n askAnythingPlaceholder: string\n /** \"Ask ARBI...\": a compact composer's placeholder. */\n askPlaceholder: string\n /** \"Ask ARBI about your documents\": the empty chat's heading. */\n askAboutDocuments: string\n /** The files bulk bar's chat tooltip. */\n askAboutSelection: string\n /** \"ARBI is asking\": the heading over a question the assistant asks. */\n isAsking: string\n /** The composer's placeholder while the assistant waits for an answer. */\n answerPlaceholder: string\n /** The empty threads list, with the composer below it. */\n emptyThreadsComposer: string\n /** The empty threads list, with a New Task button. */\n emptyThreadsNewTask: string\n /** The drafting chip's hint while the thread drafts in a document. */\n draftingHint: string\n /** The drafting chip's hint before the document is attached. */\n draftingAttachHint: string\n /** The chat's facts tab note. */\n factsInContext: (facts: string) => string\n /** \"Ask one question — ARBI answers it for each of …\": the AI review's ask step. */\n reviewEach: (count: number, scope: string) => string\n /** The facts bar's note on the chat's facts budget. */\n factsBudgetHint: string\n /** An AI review cell left without an answer. */\n noAnswerHint: string\n /** The new-thread dialog's button that hands the thread to the assistant. */\n startWith: string\n /** The mail action bar's \"Reply with ARBI\". */\n replyWith: string\n /** The Word editor's comment button that @mentions the assistant. */\n include: string\n /** A reply to an email asked for outside a workspace. */\n replyNeedsWorkspace: string\n /** After an upload. */\n uploadedIndexing: string\n /** Before an upload completes. */\n afterUpload: string\n /** The built-in Deep research workflow's description and details. */\n deepResearch: { description: string; details: string }\n /** The built-in AI annotation operation's details. */\n annotate: { details: string; placeholder: string }\n}\n\nconst plural = (n: number) => (n === 1 ? '' : 's')\n\n/** The phrases for one name. `assistantCopy()` is ARBI's own text. */\nexport function assistantCopy(name: string = DEFAULT_ASSISTANT_NAME): AssistantCopy {\n return {\n name,\n ask: `Ask ${name}`,\n askAnything: `Ask ${name} anything`,\n askAnythingPlaceholder: `Ask ${name} anything…`,\n askPlaceholder: `Ask ${name}...`,\n askAboutDocuments: `Ask ${name} about your documents`,\n askAboutSelection: `Ask ${name} about the selected document(s) in a new thread`,\n isAsking: `${name} is asking`,\n answerPlaceholder: `Type your answer to ${name} — or pick an option above`,\n emptyThreadsComposer: `Type below to ask ${name}, bring in people, or both.`,\n emptyThreadsNewTask: `Use New Task to ask ${name}, bring in people, or both.`,\n draftingHint: `This thread works in the document: ${name} reads what it needs and makes its edits as tracked changes you accept or reject.`,\n draftingAttachHint: `Attach the open document to this thread: its questions then edit the document as tracked changes. Until then, ${name} only answers.`,\n factsInContext: (facts) =>\n `${facts} added to this chat are always in ${name}'s context for this chat.`,\n reviewEach: (count, scope) =>\n `Ask one question — ${name} answers it for each of the ${count} ${scope} document${plural(count)}.`,\n factsBudgetHint: `Facts added to this chat are always in ${name}'s context for this chat, so they share one budget. This estimates the tokens they add (≈4 characters per token), capped at ~2,000.`,\n noAnswerHint: `${name} finished this document without an answer for this field. The document may not say, or the request failed. Run it again to retry.`,\n startWith: `Start with ${name}`,\n replyWith: `Reply with ${name}`,\n include: `Include ${name}`,\n replyNeedsWorkspace: `Open a workspace to chat with ${name} about this email`,\n uploadedIndexing: `Files uploaded successfully. ${name} is now indexing them in the background.`,\n afterUpload: `After upload completes, ${name} will index files in the background.`,\n deepResearch: {\n description: `Send ${name} through your files and the web, and get an answer with sources`,\n details: `${name} searches your files and the web, then answers with the sources it used. You’ll see the research unfold in the chat.`,\n },\n annotate: {\n details: `Ask one question — ${name} answers it for every selected file and fills a new column with the answers.`,\n placeholder: `What should ${name} read out? e.g. What currency is the penalty clause denominated in?`,\n },\n }\n}\n\n/** The host's name for its assistant (`ArbiHostConfig.assistantName`), else \"ARBI\". */\nexport function useAssistantName(): string {\n const name = useHostConfigRecord().assistantName\n return (typeof name === 'string' && name.trim()) || DEFAULT_ASSISTANT_NAME\n}\n\n/** The kit phrases for the host's assistant name. */\nexport function useAssistantCopy(): AssistantCopy {\n const name = useAssistantName()\n return useMemo(() => assistantCopy(name), [name])\n}\n","/**\n * @mentions in chat text: pure helpers shared by the composer (autocomplete, extraction) and\n * the message renderer (chips). No React, no SDK.\n *\n * A mention lives in two places: the readable `@Label` text in the message content, and a\n * structured entry on the message (`{ type, user_ext_id, label }`) that the server reads to share\n * the conversation and notify. The composer only ever inserts `@<label>` for a known candidate,\n * so the structured list can be recovered from the text at send time ({@link extractMentions});\n * the renderer turns each stored mention back into a chip ({@link linkMentions}).\n */\n\n/** Who can be mentioned: a workspace member, or the assistant. */\nexport type MentionKind = 'user' | 'assistant'\n\n/** One entry of the mention autocomplete. */\nexport interface MentionCandidate {\n /** User external id (`usr-…`) for a person; any stable key (e.g. `assistant`) for the assistant. */\n id: string\n kind: MentionKind\n /** Inserted as `@<label>`. For people this must be the server's display name (given + family). */\n label: string\n /** Secondary line in the menu (email, role, …). */\n description?: string\n}\n\n/** The structured mention a message carries (the API's `MessageMention`). */\nexport interface MessageMentionRef {\n type: MentionKind\n user_ext_id?: string | null\n label?: string | null\n}\n\n/** Longest text after `@` that still counts as a query in progress. */\nconst MAX_QUERY_LENGTH = 40\n\n/**\n * The `@query` the caret is in, if any: the `@` must start the text or follow whitespace, and the\n * query may contain spaces (names do) but no newline. Returns the index of the `@` and the query.\n */\nexport function findMentionQuery(\n text: string,\n caret: number\n): { start: number; query: string } | null {\n const before = text.slice(0, caret)\n const at = before.lastIndexOf('@')\n if (at < 0) return null\n if (at > 0 && !/\\s/.test(before[at - 1])) return null\n const query = before.slice(at + 1)\n if (query.length > MAX_QUERY_LENGTH || query.includes('\\n') || query.startsWith(' ')) return null\n return { start: at, query }\n}\n\n/** Candidates matching a query: label prefix (or word-prefix) matches, prefix matches first. */\nexport function filterMentionCandidates(\n candidates: ReadonlyArray<MentionCandidate>,\n query: string\n): MentionCandidate[] {\n const q = query.trim().toLowerCase()\n if (!q) return candidates.slice()\n const scored: Array<{ c: MentionCandidate; score: number }> = []\n for (const c of candidates) {\n const label = c.label.toLowerCase()\n if (label.startsWith(q)) scored.push({ c, score: 0 })\n else if (label.split(/\\s+/).some((word) => word.startsWith(q))) scored.push({ c, score: 1 })\n else if (c.description?.toLowerCase().startsWith(q)) scored.push({ c, score: 2 })\n }\n return scored.sort((a, b) => a.score - b.score).map((s) => s.c)\n}\n\n/** Replace the `@query` at `start…caret` with `@<label> `; returns the new text and caret. */\nexport function insertMention(\n text: string,\n start: number,\n caret: number,\n label: string\n): { text: string; caret: number } {\n const inserted = `@${label} `\n return {\n text: text.slice(0, start) + inserted + text.slice(caret),\n caret: start + inserted.length,\n }\n}\n\n/** Every `[from, to)` range where `@<label>` occurs as a whole token. */\nfunction tokenRanges(text: string, label: string): Array<[number, number]> {\n const needle = `@${label}`\n const ranges: Array<[number, number]> = []\n let from = 0\n for (;;) {\n const i = text.indexOf(needle, from)\n if (i < 0) break\n const end = i + needle.length\n const startsToken = i === 0 || /\\s|\\(|\\[/.test(text[i - 1])\n const endsToken = end === text.length || !/[\\p{L}\\p{N}_]/u.test(text[end])\n if (startsToken && endsToken) ranges.push([i, end])\n from = end\n }\n return ranges\n}\n\n/**\n * The candidates mentioned in `text`, in order of first appearance. Longer labels win overlaps,\n * so `@Bob Smith` is Bob Smith, not a separate `@Bob`.\n */\nexport function extractMentions(\n text: string,\n candidates: ReadonlyArray<MentionCandidate>\n): MentionCandidate[] {\n const taken: Array<[number, number]> = []\n const found: Array<{ c: MentionCandidate; at: number }> = []\n const byLength = [...candidates].sort((a, b) => b.label.length - a.label.length)\n for (const c of byLength) {\n if (!c.label) continue\n for (const [from, to] of tokenRanges(text, c.label)) {\n if (taken.some(([a, b]) => from < b && to > a)) continue\n taken.push([from, to])\n if (!found.some((f) => f.c.id === c.id)) found.push({ c, at: from })\n }\n }\n return found.sort((a, b) => a.at - b.at).map((f) => f.c)\n}\n\n/** The API payload for mentioned candidates. */\nexport function toMessageMentions(mentioned: ReadonlyArray<MentionCandidate>): MessageMentionRef[] {\n return mentioned.map((c) =>\n c.kind === 'assistant' ? { type: 'assistant' } : { type: 'user', user_ext_id: c.id }\n )\n}\n\n/** Fragment prefix of the links {@link linkMentions} writes. */\nexport const MENTION_HREF_PREFIX = '#mention-'\n\n/** Escape the characters that would end a markdown link text early. */\nfunction escapeLinkText(label: string): string {\n return label.replace(/[[\\]\\\\]/g, (ch) => `\\\\${ch}`)\n}\n\n/**\n * Turn each stored mention's `@<label>` in `content` into a markdown link\n * `[@<label>](#mention-<id>)`, so a markdown renderer can draw it as a chip (see\n * {@link mentionFromHref}). Text that no longer matches (a renamed user) stays plain text.\n * `assistantLabels` lists other names the assistant may have been mentioned by.\n */\nexport function linkMentions(\n content: string,\n mentions: ReadonlyArray<MessageMentionRef> | null | undefined,\n assistantLabels: ReadonlyArray<string> = []\n): string {\n if (!mentions || mentions.length === 0 || !content) return content\n const targets: Array<{ label: string; id: string }> = []\n for (const m of mentions) {\n const id = m.type === 'assistant' ? 'assistant' : m.user_ext_id\n if (!id) continue\n const labels = m.type === 'assistant' ? [m.label ?? '', ...assistantLabels] : [m.label ?? '']\n for (const label of labels) if (label) targets.push({ label, id })\n }\n targets.sort((a, b) => b.label.length - a.label.length)\n const replacements: Array<{ from: number; to: number; text: string }> = []\n for (const { label, id } of targets) {\n for (const [from, to] of tokenRanges(content, label)) {\n if (replacements.some((r) => from < r.to && to > r.from)) continue\n replacements.push({\n from,\n to,\n text: `[@${escapeLinkText(label)}](${MENTION_HREF_PREFIX}${id})`,\n })\n }\n }\n replacements.sort((a, b) => b.from - a.from)\n let out = content\n for (const r of replacements) out = out.slice(0, r.from) + r.text + out.slice(r.to)\n return out\n}\n\n/** The mention a `#mention-…` href points at, or null for any other href. */\nexport function mentionFromHref(\n href: string | null | undefined\n): { kind: MentionKind; id: string } | null {\n if (!href?.startsWith(MENTION_HREF_PREFIX)) return null\n const id = href.slice(MENTION_HREF_PREFIX.length)\n if (!id) return null\n return { kind: id === 'assistant' ? 'assistant' : 'user', id }\n}\n\n/** A recipient alone (by any of its labels) is not a message. */\nexport function hasMessageBody(\n value: string,\n recipientLabel: string | ReadonlyArray<string> = 'ARBI'\n): boolean {\n const text = value.trim().toLowerCase()\n const labels = typeof recipientLabel === 'string' ? [recipientLabel] : recipientLabel\n return !!text && !labels.some((label) => text === `@${label}`.toLowerCase())\n}\n","import { useEffect, useRef, useSyncExternalStore } from 'react'\nimport { parseVersionRef } from '../artifacts/versions'\n\n/**\n * Drafting mode: the documents open beside the chat, and which one a chat turn drafts in.\n *\n * A viewer registers the document it shows (`useRegisterOpenDocument`). Being open binds nothing:\n * a turn names a document (`active_artifact_ext_id`, read with `takeDocumentForTurn` as the\n * question is sent) only when its thread is bound to it (`./thread-document`: started from the\n * document, or attached in that thread), when the document was made in that thread, or when the\n * open document is ambient (an email draft open in the composer). The server then binds the live\n * document to the turn: a Word document is read on demand and edited as tracked changes in the\n * open editor, and what the assistant saves becomes a child version of it. The request carries a\n * reference, never the content.\n *\n * The named document is always the subject, also while one of its earlier versions is on screen\n * read-only: a version still names its document. Sending a turn then returns the viewer to the live\n * document (`showLive`), where the assistant's edits appear as they are made. (Pinning a specific\n * version as a source is a separate feature: it does not go through here.)\n *\n * A module-level registry (not React context), like `useChatSurface`, so a viewer and a chat agree\n * wherever they sit in the tree; the most recently opened document is on top and closing it hands\n * back to the one before. It is not the session state's viewing document (`useArbiSessionState`):\n * it holds what mounted viewers can draft in (saved documents only, with the callback that shows\n * the live one again), and a turn reads it outside React. A viewer on the session's viewing\n * document passes that as `shownId` (it may be a version reference, resolved here the same way as\n * `selectViewingDocumentId` does).\n */\n\n/** What a viewer knows about the document it shows. */\nexport interface SavedDocumentInput {\n /** The document (`doc-…`), never a version reference. */\n documentId: string | null | undefined\n /** An unsaved draft (client-minted id, no backend record). */\n isDraft: boolean\n /** Still streaming: nothing is persisted yet. */\n isStreaming: boolean\n /** An image, audio or video artifact: there is no text to draft in. */\n isBlobArtifact: boolean\n /** The loaded document record. */\n documentData:\n | { external_id?: string | null; wp_type?: string | null; file_name?: string | null }\n | null\n | undefined\n}\n\n/** The fields that decide where a document opens. */\nexport interface WordDocumentKind {\n file_name?: string | null\n wp_type?: string | null\n}\n\n/**\n * A document edited in the Word editor: a `.docx`, or a document the assistant wrote (an\n * artifact). The one rule for where a document opens (`openWordEditor` or `openDocument`) and\n * which documents a chat drafts in.\n */\nexport function opensInWord(doc: WordDocumentKind | null | undefined): boolean {\n return !!doc && (doc.wp_type === 'artifact' || !!doc.file_name?.toLowerCase().endsWith('.docx'))\n}\n\n/**\n * The saved, content-backed document a chat can draft in, or null. Only a saved artifact or Word\n * document counts: drafts, an artifact still streaming and blob artifacts do not.\n */\nexport function savedDocumentIdFor(input: SavedDocumentInput): string | null {\n const { documentId, isDraft, isStreaming, isBlobArtifact, documentData } = input\n if (!documentId || isDraft || isStreaming || isBlobArtifact) return null\n if (!documentData || !opensInWord(documentData)) return null\n // A stale record of the previously viewed document is not this one.\n if (documentData.external_id !== documentId) return null\n return documentId\n}\n\nexport interface OpenDocumentRegistration {\n /** The saved document the viewer shows (`doc-…`); null or empty registers nothing. */\n documentId: string | null | undefined\n /** What is on screen: the document itself, or one of its earlier versions (`doc-…@v2`). */\n shownId?: string | null\n /** Show the live document again. Called when a turn starts while an earlier version is shown. */\n showLive?: () => void\n /** The workspace the document belongs to; a chat in another workspace does not draft in it. */\n workspaceId?: string | null\n /** The thread the document was made in: that thread drafts in it without being bound to it. */\n conversationId?: string | null\n /**\n * Drafted in by whichever chat is beside it, bound or not (an email draft open in the composer:\n * the composer is a drafting surface of its own).\n */\n ambient?: boolean\n}\n\ninterface Entry {\n documentId: string\n current: () => OpenDocumentRegistration\n}\n\nlet entries: Entry[] = []\nconst listeners = new Set<() => void>()\n\nfunction subscribe(listener: () => void): () => void {\n listeners.add(listener)\n return () => listeners.delete(listener)\n}\n\nfunction emit() {\n listeners.forEach((l) => l())\n}\n\nconst top = (): Entry | undefined => entries[entries.length - 1]\n\n/**\n * Registers the document a viewer shows as the open document while the caller is mounted and\n * `documentId` is set. Pass `savedDocumentIdFor(...)`, or the id of a document known to be saved.\n */\nexport function useRegisterOpenDocument(registration: OpenDocumentRegistration): void {\n const latest = useRef(registration)\n const { documentId, workspaceId, conversationId, ambient } = registration\n useEffect(() => {\n latest.current = registration\n })\n // What decides which chat drafts in it changed (its record loaded): readers re-render.\n useEffect(() => {\n if (documentId) emit()\n }, [documentId, workspaceId, conversationId, ambient])\n useEffect(() => {\n if (!documentId) return\n const entry: Entry = { documentId, current: () => latest.current }\n entries = [...entries, entry]\n emit()\n return () => {\n entries = entries.filter((e) => e !== entry)\n emit()\n }\n }, [documentId])\n}\n\n/** The open document's id (the most recently opened), or null. Re-renders when it changes. */\nexport function useOpenDocumentId(options?: { workspaceId?: string | null }): string | null {\n const workspaceId = options?.workspaceId ?? null\n return useSyncExternalStore(\n subscribe,\n () => openDocumentId({ workspaceId }),\n () => null\n )\n}\n\n/** The open document's id (the most recently opened); with `workspaceId`, only one of it. */\nexport function openDocumentId(options?: { workspaceId?: string | null }): string | null {\n const entry = top()\n if (!entry || !inWorkspace(entry, options?.workspaceId)) return null\n return entry.documentId\n}\n\nfunction inWorkspace(entry: Entry, workspaceId: string | null | undefined): boolean {\n const own = entry.current().workspaceId\n return !workspaceId || !own || own === workspaceId\n}\n\n/** What a turn is about to be sent in: its conversation and the document its thread is bound to. */\nexport interface TurnDocumentInput {\n /** The thread's bound document (`threadDocumentId` / the session's `newChatDocumentId`). */\n boundDocumentId: string | null | undefined\n /** The conversation (null: a new chat). */\n conversationId: string | null | undefined\n /** The chat's workspace: an open document of another workspace is never picked up. */\n workspaceId?: string | null\n}\n\n/** The document a turn drafts in, and the open viewer showing it (if one is). */\nfunction pickTurnDocument({\n boundDocumentId,\n conversationId,\n workspaceId,\n}: TurnDocumentInput): { documentId: string; entry: Entry | undefined } | null {\n // A bound thread names its document on every turn, open or not.\n if (boundDocumentId) {\n const entry = [...entries].reverse().find((e) => e.documentId === boundDocumentId)\n return { documentId: boundDocumentId, entry }\n }\n // Unbound: only a document made in this thread, or an ambient one (an email draft).\n for (let i = entries.length - 1; i >= 0; i--) {\n const entry = entries[i]\n if (!inWorkspace(entry, workspaceId)) continue\n const { ambient, conversationId: madeIn } = entry.current()\n if (ambient || (conversationId && madeIn === conversationId))\n return { documentId: entry.documentId, entry }\n }\n return null\n}\n\n/** The document a turn sent now would draft in, or null. Re-renders as documents open and close. */\nexport function useTurnDocumentId(input: TurnDocumentInput): string | null {\n const { boundDocumentId = null, conversationId = null, workspaceId = null } = input\n return useSyncExternalStore(\n subscribe,\n () => pickTurnDocument({ boundDocumentId, conversationId, workspaceId })?.documentId ?? null,\n () => null\n )\n}\n\n/**\n * The document an assistant turn about to be sent drafts in, or null. Call it once per turn as the\n * question is sent: when an earlier version of the document is on screen, the viewer returns to the\n * live document, where the assistant's edits appear.\n */\nexport function takeDocumentForTurn(input: TurnDocumentInput): string | null {\n const picked = pickTurnDocument(input)\n if (!picked) return null\n const { documentId, entry } = picked\n if (entry) {\n const { shownId, showLive } = entry.current()\n if (shownId && shownId !== documentId && parseVersionRef(shownId).docId === documentId)\n showLive?.()\n }\n return documentId\n}\n","/**\n * A thread's document: the one document a conversation drafts in, part of the conversation.\n *\n * A thread is bound to a document only when it was started from it (\"Chat about this document\" in\n * the viewer) or the person attached it in that thread. Only that thread names it on its turns\n * (`active_artifact_ext_id`), on every turn and after a reload. A document merely open or docked\n * beside the chat binds nothing: a new chat (the ask bar, the new-chat button, the thread\n * launcher, home) starts unbound, so a question there never becomes an edit of whatever is open.\n *\n * The binding is the server's: the conversation's `bound_document_ext_id`, set by the first turn\n * (`bound_document_ext_id` on the turn that starts it) or by a PATCH, and read under each reader's\n * access (`bound_document_unavailable`: bound to a document this reader cannot open). It follows\n * the person to every device, and a shared thread's members all see it. The query cache holds it\n * (`./thread-binding`); a new chat's binding is the session's `newChatDocumentId` until its first\n * turn creates the conversation.\n *\n * This module is the light half (no query client, no SDK), so the shell entry can carry it.\n */\n\n/** What a conversation row says about its binding. */\nexport interface ThreadBindingRow {\n external_id: string\n bound_document_ext_id?: string | null\n bound_document_unavailable?: boolean | null\n updated_at?: string | null\n}\n\n/** A conversation's binding as this reader sees it. */\nexport interface ThreadBinding {\n /** The bound document, or null (unbound, or bound to one this reader cannot open). */\n documentId: string | null\n /** Bound to a document this reader cannot open (another member's private document, or deleted). */\n unavailable: boolean\n}\n\nexport const UNBOUND: ThreadBinding = { documentId: null, unavailable: false }\n\n/** A row's binding. */\nexport function bindingOfRow(row: ThreadBindingRow | null | undefined): ThreadBinding {\n if (!row) return UNBOUND\n const documentId = row.bound_document_ext_id ?? null\n return { documentId, unavailable: !documentId && row.bound_document_unavailable === true }\n}\n\n/** The most recently active conversation bound to a document, among `conversations`, or null. */\nexport function latestThreadOfDocument(\n conversations: readonly ThreadBindingRow[] | null | undefined,\n documentId: string\n): string | null {\n let latest: ThreadBindingRow | null = null\n for (const row of conversations ?? []) {\n if (row.bound_document_ext_id !== documentId) continue\n if (!latest || (row.updated_at ?? '') > (latest.updated_at ?? '')) latest = row\n }\n return latest?.external_id ?? null\n}\n\n// --------------------------------------------------------------------------------------------- //\n// Bindings this browser kept before the server held them (`localStorage`), moved to the server\n// once (`migrateLegacyThreadDocuments` in `./thread-binding`) and then forgotten.\n// --------------------------------------------------------------------------------------------- //\n\nexport const LEGACY_THREAD_DOCUMENTS_KEY = 'arbi-thread-documents'\n\nfunction storage(): Storage | undefined {\n try {\n return typeof localStorage === 'undefined' ? undefined : localStorage\n } catch {\n return undefined\n }\n}\n\n/** The bindings this browser kept locally (conversation id → document id); empty when none. */\nexport function readLegacyThreadDocuments(): Record<string, string> {\n const out: Record<string, string> = {}\n try {\n const parsed = JSON.parse(storage()?.getItem(LEGACY_THREAD_DOCUMENTS_KEY) ?? 'null') as unknown\n if (parsed && typeof parsed === 'object')\n for (const [conversationId, documentId] of Object.entries(parsed))\n if (typeof documentId === 'string') out[conversationId] = documentId\n } catch {\n // Damaged or blocked: nothing to move.\n }\n return out\n}\n\n/** Forget locally kept bindings (moved to the server); the key goes with the last of them. */\nexport function forgetLegacyThreadDocuments(conversationIds: readonly string[]): void {\n if (conversationIds.length === 0) return\n const rest = readLegacyThreadDocuments()\n conversationIds.forEach((id) => delete rest[id])\n try {\n if (Object.keys(rest).length === 0) storage()?.removeItem(LEGACY_THREAD_DOCUMENTS_KEY)\n else storage()?.setItem(LEGACY_THREAD_DOCUMENTS_KEY, JSON.stringify(rest))\n } catch {\n // Blocked: nothing more to do.\n }\n}\n"]}
|