@vertesia/ui 1.4.0 → 1.4.1
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/lib/core/components/SidePanel.js +1 -1
- package/lib/core/components/SidePanel.js.map +1 -1
- package/lib/core/components/shadcn/button.d.ts +10 -3
- package/lib/core/components/shadcn/button.d.ts.map +1 -1
- package/lib/core/components/shadcn/button.js +41 -9
- package/lib/core/components/shadcn/button.js.map +1 -1
- package/lib/core/components/shadcn/modal/dialog.js +1 -1
- package/lib/core/components/shadcn/modal/dialog.js.map +1 -1
- package/lib/core/components/shadcn/resizeable.d.ts +1 -1
- package/lib/core/components/shadcn/resizeable.d.ts.map +1 -1
- package/lib/core/components/shadcn/resizeable.js +12 -2
- package/lib/core/components/shadcn/resizeable.js.map +1 -1
- package/lib/core/components/shadcn/tabs.d.ts +12 -1
- package/lib/core/components/shadcn/tabs.d.ts.map +1 -1
- package/lib/core/components/shadcn/tabs.js +12 -4
- package/lib/core/components/shadcn/tabs.js.map +1 -1
- package/lib/core/components/shadcn/theme/ThemeSwitcher.js +1 -1
- package/lib/core/components/shadcn/theme/ThemeSwitcher.js.map +1 -1
- package/lib/core/hooks/useIntersectionObserver.d.ts.map +1 -1
- package/lib/core/hooks/useIntersectionObserver.js +3 -1
- package/lib/core/hooks/useIntersectionObserver.js.map +1 -1
- package/lib/features/agent/chat/AgentChatPlaybackControls.d.ts.map +1 -1
- package/lib/features/agent/chat/AgentChatPlaybackControls.js +2 -2
- package/lib/features/agent/chat/AgentChatPlaybackControls.js.map +1 -1
- package/lib/features/agent/chat/AgentRequestInputOverlay.d.ts.map +1 -1
- package/lib/features/agent/chat/AgentRequestInputOverlay.js +2 -2
- package/lib/features/agent/chat/AgentRequestInputOverlay.js.map +1 -1
- package/lib/features/agent/chat/AgentRightPanel.js +1 -1
- package/lib/features/agent/chat/AgentRightPanel.js.map +1 -1
- package/lib/features/agent/chat/AskUserWidget.d.ts.map +1 -1
- package/lib/features/agent/chat/AskUserWidget.js +4 -3
- package/lib/features/agent/chat/AskUserWidget.js.map +1 -1
- package/lib/features/agent/chat/ImageLightbox.d.ts.map +1 -1
- package/lib/features/agent/chat/ImageLightbox.js +1 -1
- package/lib/features/agent/chat/ImageLightbox.js.map +1 -1
- package/lib/features/agent/chat/ModernAgentConversation.d.ts.map +1 -1
- package/lib/features/agent/chat/ModernAgentConversation.js +57 -12
- package/lib/features/agent/chat/ModernAgentConversation.js.map +1 -1
- package/lib/features/agent/chat/ModernAgentOutput/AllMessagesMixed.d.ts +8 -1
- package/lib/features/agent/chat/ModernAgentOutput/AllMessagesMixed.d.ts.map +1 -1
- package/lib/features/agent/chat/ModernAgentOutput/AllMessagesMixed.js +45 -36
- package/lib/features/agent/chat/ModernAgentOutput/AllMessagesMixed.js.map +1 -1
- package/lib/features/agent/chat/ModernAgentOutput/Header.d.ts.map +1 -1
- package/lib/features/agent/chat/ModernAgentOutput/Header.js +4 -2
- package/lib/features/agent/chat/ModernAgentOutput/Header.js.map +1 -1
- package/lib/features/agent/chat/ModernAgentOutput/MessageInput.d.ts.map +1 -1
- package/lib/features/agent/chat/ModernAgentOutput/MessageInput.js +7 -3
- package/lib/features/agent/chat/ModernAgentOutput/MessageInput.js.map +1 -1
- package/lib/features/agent/chat/ModernAgentOutput/MessageItem.d.ts.map +1 -1
- package/lib/features/agent/chat/ModernAgentOutput/MessageItem.js +2 -1
- package/lib/features/agent/chat/ModernAgentOutput/MessageItem.js.map +1 -1
- package/lib/features/agent/chat/ModernAgentOutput/WorkstreamTabs.d.ts.map +1 -1
- package/lib/features/agent/chat/ModernAgentOutput/WorkstreamTabs.js +158 -8
- package/lib/features/agent/chat/ModernAgentOutput/WorkstreamTabs.js.map +1 -1
- package/lib/features/agent/chat/ModernAgentOutput/requestInputMessages.d.ts +6 -0
- package/lib/features/agent/chat/ModernAgentOutput/requestInputMessages.d.ts.map +1 -1
- package/lib/features/agent/chat/ModernAgentOutput/requestInputMessages.js +15 -1
- package/lib/features/agent/chat/ModernAgentOutput/requestInputMessages.js.map +1 -1
- package/lib/features/agent/chat/hooks/useFileProcessing.d.ts +1 -0
- package/lib/features/agent/chat/hooks/useFileProcessing.d.ts.map +1 -1
- package/lib/features/agent/chat/hooks/useFileProcessing.js +37 -3
- package/lib/features/agent/chat/hooks/useFileProcessing.js.map +1 -1
- package/lib/features/magic-pdf/AnnotatedImageSlider.js +13 -13
- package/lib/features/magic-pdf/AnnotatedImageSlider.js.map +1 -1
- package/lib/features/magic-pdf/DownloadPopover.js +2 -2
- package/lib/features/magic-pdf/DownloadPopover.js.map +1 -1
- package/lib/features/magic-pdf/MagicPdfView.js +3 -3
- package/lib/features/magic-pdf/MagicPdfView.js.map +1 -1
- package/lib/features/oauth/McpConnectionsButton.d.ts.map +1 -1
- package/lib/features/oauth/McpConnectionsButton.js +2 -2
- package/lib/features/oauth/McpConnectionsButton.js.map +1 -1
- package/lib/features/oauth/McpConnectionsDialog.d.ts.map +1 -1
- package/lib/features/oauth/McpConnectionsDialog.js +1 -1
- package/lib/features/oauth/McpConnectionsDialog.js.map +1 -1
- package/lib/features/oauth/RemoteMcpConnectionButton.d.ts.map +1 -1
- package/lib/features/oauth/RemoteMcpConnectionButton.js +1 -1
- package/lib/features/oauth/RemoteMcpConnectionButton.js.map +1 -1
- package/lib/features/pdf-viewer/PdfPageSlider.js +2 -2
- package/lib/features/pdf-viewer/PdfPageSlider.js.map +1 -1
- package/lib/features/pdf-viewer/SimplePdfViewer.d.ts.map +1 -1
- package/lib/features/pdf-viewer/SimplePdfViewer.js +3 -3
- package/lib/features/pdf-viewer/SimplePdfViewer.js.map +1 -1
- package/lib/features/store/objects/DocumentQuickFilter.d.ts.map +1 -1
- package/lib/features/store/objects/DocumentQuickFilter.js +5 -5
- package/lib/features/store/objects/DocumentQuickFilter.js.map +1 -1
- package/lib/features/store/objects/DocumentSearchResults.d.ts.map +1 -1
- package/lib/features/store/objects/DocumentSearchResults.js +2 -2
- package/lib/features/store/objects/DocumentSearchResults.js.map +1 -1
- package/lib/features/store/objects/components/ContentDispositionButton.d.ts.map +1 -1
- package/lib/features/store/objects/components/ContentDispositionButton.js +1 -1
- package/lib/features/store/objects/components/ContentDispositionButton.js.map +1 -1
- package/lib/features/store/objects/components/ContentOverview.js +3 -3
- package/lib/features/store/objects/components/ContentOverview.js.map +1 -1
- package/lib/features/store/objects/components/DocumentIcon.js +1 -1
- package/lib/features/store/objects/components/VectorSearchWidget.js +1 -1
- package/lib/features/store/objects/components/VectorSearchWidget.js.map +1 -1
- package/lib/features/store/objects/layout/renderers.d.ts.map +1 -1
- package/lib/features/store/objects/layout/renderers.js +2 -2
- package/lib/features/store/objects/layout/renderers.js.map +1 -1
- package/lib/features/store/objects/selection/SelectionActions.js +1 -1
- package/lib/features/store/objects/selection/SelectionActions.js.map +1 -1
- package/lib/features/store/objects/selection/actions/StartWorkflowComponent.js +4 -4
- package/lib/features/store/objects/selection/actions/StartWorkflowComponent.js.map +1 -1
- package/lib/features/store/types/ContentObjectTypesTable.d.ts.map +1 -1
- package/lib/features/store/types/ContentObjectTypesTable.js +4 -4
- package/lib/features/store/types/ContentObjectTypesTable.js.map +1 -1
- package/lib/features/store/types/SelectContentTypeModal.js +1 -1
- package/lib/features/store/types/SelectContentTypeModal.js.map +1 -1
- package/lib/features/user/UserInfo.js +7 -3
- package/lib/features/user/UserInfo.js.map +1 -1
- package/lib/router/HistoryNavigator.d.ts.map +1 -1
- package/lib/router/HistoryNavigator.js +5 -0
- package/lib/router/HistoryNavigator.js.map +1 -1
- package/lib/router/Nav.d.ts.map +1 -1
- package/lib/router/Nav.js +9 -1
- package/lib/router/Nav.js.map +1 -1
- package/lib/vertesia-ui-core.js +1 -1
- package/lib/vertesia-ui-core.js.map +1 -1
- package/lib/vertesia-ui-features.js +1 -1
- package/lib/vertesia-ui-features.js.map +1 -1
- package/lib/vertesia-ui-router.js +1 -1
- package/lib/vertesia-ui-router.js.map +1 -1
- package/lib/vertesia-ui-widgets.js +1 -1
- package/lib/vertesia-ui-widgets.js.map +1 -1
- package/lib/widgets/form/Form.js +1 -1
- package/lib/widgets/form/Form.js.map +1 -1
- package/lib/widgets/json-view/JSONSwitcher.js +1 -1
- package/lib/widgets/json-view/JSONSwitcher.js.map +1 -1
- package/lib/widgets/json-view/JSONView.js +6 -6
- package/lib/widgets/json-view/JSONView.js.map +1 -1
- package/lib/widgets/monacoEditor/MonacoEditor.d.ts.map +1 -1
- package/lib/widgets/monacoEditor/MonacoEditor.js +29 -0
- package/lib/widgets/monacoEditor/MonacoEditor.js.map +1 -1
- package/lib/widgets/xml-viewer/hooks/useXMLViewer.d.ts +9 -0
- package/lib/widgets/xml-viewer/hooks/useXMLViewer.d.ts.map +1 -1
- package/lib/widgets/xml-viewer/hooks/useXMLViewer.js +20 -17
- package/lib/widgets/xml-viewer/hooks/useXMLViewer.js.map +1 -1
- package/package.json +29 -30
- package/src/__tests__/a11y.test.tsx +73 -0
- package/src/core/components/SidePanel.tsx +1 -1
- package/src/core/components/shadcn/button.tsx +67 -12
- package/src/core/components/shadcn/modal/dialog.tsx +1 -1
- package/src/core/components/shadcn/resizeable.test.tsx +77 -0
- package/src/core/components/shadcn/resizeable.tsx +28 -2
- package/src/core/components/shadcn/tabs.test.tsx +65 -0
- package/src/core/components/shadcn/tabs.tsx +25 -3
- package/src/core/components/shadcn/theme/ThemeSwitcher.tsx +1 -1
- package/src/core/hooks/useIntersectionObserver.tsx +3 -1
- package/src/features/agent/chat/AgentChatPlaybackControls.tsx +0 -5
- package/src/features/agent/chat/AgentRequestInputOverlay.test.tsx +31 -0
- package/src/features/agent/chat/AgentRequestInputOverlay.tsx +6 -2
- package/src/features/agent/chat/AgentRightPanel.tsx +1 -1
- package/src/features/agent/chat/AskUserWidget.test.tsx +49 -0
- package/src/features/agent/chat/AskUserWidget.tsx +32 -22
- package/src/features/agent/chat/ImageLightbox.tsx +0 -1
- package/src/features/agent/chat/ModernAgentConversation.test.tsx +246 -1
- package/src/features/agent/chat/ModernAgentConversation.tsx +62 -17
- package/src/features/agent/chat/ModernAgentOutput/AllMessagesMixed.test.tsx +6 -1
- package/src/features/agent/chat/ModernAgentOutput/AllMessagesMixed.tsx +81 -49
- package/src/features/agent/chat/ModernAgentOutput/Header.tsx +3 -3
- package/src/features/agent/chat/ModernAgentOutput/MessageInput.test.tsx +25 -0
- package/src/features/agent/chat/ModernAgentOutput/MessageInput.tsx +5 -3
- package/src/features/agent/chat/ModernAgentOutput/MessageItem.tsx +4 -1
- package/src/features/agent/chat/ModernAgentOutput/WorkstreamTabs.tsx +328 -42
- package/src/features/agent/chat/ModernAgentOutput/requestInputMessages.test.ts +80 -0
- package/src/features/agent/chat/ModernAgentOutput/requestInputMessages.ts +21 -1
- package/src/features/agent/chat/hooks/useFileProcessing.test.tsx +70 -0
- package/src/features/agent/chat/hooks/useFileProcessing.ts +37 -6
- package/src/features/magic-pdf/AnnotatedImageSlider.tsx +62 -66
- package/src/features/magic-pdf/DownloadPopover.tsx +2 -2
- package/src/features/magic-pdf/MagicPdfView.tsx +3 -3
- package/src/features/oauth/McpConnectionsButton.tsx +0 -2
- package/src/features/oauth/McpConnectionsDialog.tsx +0 -1
- package/src/features/oauth/RemoteMcpConnectionButton.tsx +0 -1
- package/src/features/pdf-viewer/PdfPageSlider.tsx +5 -5
- package/src/features/pdf-viewer/SimplePdfViewer.tsx +11 -12
- package/src/features/store/objects/DocumentQuickFilter.tsx +13 -15
- package/src/features/store/objects/DocumentSearchResults.tsx +3 -6
- package/src/features/store/objects/components/ContentDispositionButton.tsx +5 -1
- package/src/features/store/objects/components/ContentOverview.tsx +11 -11
- package/src/features/store/objects/components/DocumentIcon.tsx +1 -1
- package/src/features/store/objects/components/VectorSearchWidget.tsx +2 -2
- package/src/features/store/objects/layout/renderers.tsx +1 -2
- package/src/features/store/objects/selection/SelectionActions.tsx +1 -1
- package/src/features/store/objects/selection/actions/StartWorkflowComponent.tsx +6 -5
- package/src/features/store/types/ContentObjectTypesTable.tsx +12 -14
- package/src/features/store/types/SelectContentTypeModal.tsx +2 -2
- package/src/features/user/UserInfo.tsx +7 -7
- package/src/router/HistoryNavigator.ts +5 -0
- package/src/router/Nav.tsx +12 -3
- package/src/widgets/form/Form.tsx +1 -1
- package/src/widgets/json-view/JSONSwitcher.tsx +2 -2
- package/src/widgets/json-view/JSONView.tsx +7 -7
- package/src/widgets/monacoEditor/MonacoEditor.tsx +29 -0
- package/src/widgets/xml-viewer/hooks/useXMLViewer.test.ts +26 -0
- package/src/widgets/xml-viewer/hooks/useXMLViewer.ts +23 -18
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{jsx as e,jsxs as t,Fragment as n}from"react/jsx-runtime";import{Button as r,DropdownMenu as a,DropdownMenuTrigger as s,cn as i,DropdownMenuContent as o,DropdownMenuRadioGroup as l,DropdownMenuRadioItem as c,Input as d,Slider as u,onActivateKey as m,useToast as p,VTooltip as h,Badge as f,Dropdown as g,MenuItem as v,ErrorBox as b,Center as x,Tabs as y,TabsPanel as w,DropdownMenuItem as N,MenuGroup as k,Avatar as C,Table as _,useFetch as S,errorMessage as T,Popover as I,PopoverTrigger as z,PopoverContent as R,FilterProvider as j,FilterBtn as P,FilterBar as A,FilterClear as D,useIsInModal as E,SelectBox as $,InputList as L,CopyButton as F,Card as M,Separator as O,CardContent as U,THead as W,TBody as B,SharedState as V,useWatchSharedState as q,Modal as H,ModalTitle as G,ModalBody as J,Spinner as K,MessageBox as Q,ModalFooter as Y,useIntersectionObserver as Z,Textarea as X,insertNewlineAtCursor as ee,Breadcrumbs as te,ResizablePanelGroup as ne,ResizablePanel as re,ResizableHandle as ae,RadioGroup as se,FormItem as ie,RadioGroupAdapter as oe,useTheme as le,Portal as ce,Checkbox as de,Label as ue,NumberInput as me,SidePanel as pe,Divider as he,Switch as fe,TR as ge,EmptyCollection as ve,ConfirmModal as be,useDebounce as xe,Panel as ye,TagsInput as we,Styles as Ne,Command as ke,CommandInput as Ce,CommandEmpty as _e,CommandGroup as Se,CommandItem as Te,useFlag as Ie,DialogDescription as ze,Heading as Re,TabsBar as je,SelectList as Pe}from"@vertesia/ui/core";import Ae,{clsx as De}from"clsx";import{AnimatePresence as Ee,motion as $e}from"motion/react";import*as Le from"react";import Fe,{useMemo as Me,useState as Oe,createContext as Ue,useContext as We,useRef as Be,useCallback as Ve,memo as qe,useEffect as He,forwardRef as Ge,useId as Je,Component as Ke,useLayoutEffect as Qe,useSyncExternalStore as Ye}from"react";import{useUITranslation as Ze,i18nInstance as Xe,NAMESPACE as et}from"@vertesia/ui/i18n";import{HandIcon as tt,ShieldCheckIcon as nt,ShieldAlertIcon as rt,ChevronDownIcon as at,Loader2 as st,Check as it,Copy as ot,Download as lt,Minimize2 as ct,Maximize2 as dt,X as ut,ChevronsLeft as mt,ChevronLeft as pt,ChevronRight as ht,ChevronsRight as ft,Radio as gt,CopyIcon as vt,Search as bt,CheckCircle2 as xt,Unlink2 as yt,Link2 as wt,Code as Nt,FileText as kt,Table as Ct,Link as _t,Image as St,MessageSquare as Tt,GitBranch as It,BarChart3 as zt,CheckCircle as Rt,AlertCircle as jt,HelpCircle as Pt,Send as At,XCircle as Dt,XIcon as Et,ExternalLink as $t,ImageIcon as Lt,FileTextIcon as Ft,ChevronDown as Mt,Layers as Ot,CheckCheck as Ut,Clock as Wt,Bot as Bt,RefreshCcw as Vt,Info as qt,User as Ht,AlertTriangle as Gt,ArrowLeft as Jt,Terminal as Kt,Wrench as Qt,Brain as Yt,Pencil as Zt,DownloadCloudIcon as Xt,Pause as en,Play as tn,Link2Off as nn,PackageIcon as rn,Loader2Icon as an,RefreshCwIcon as sn,ChevronRightIcon as on,FolderOpenIcon as ln,FolderIcon as cn,FileIcon as dn,MonitorIcon as un,ExternalLinkIcon as mn,ClipboardList as pn,Circle as hn,LayoutListIcon as fn,ClipboardCopyIcon as gn,XCircleIcon as vn,CheckCircleIcon as bn,Rows3 as xn,MessageSquareText as yn,Rewind as wn,InfoIcon as Nn,GitFork as kn,MoreVertical as Cn,Users2 as _n,Users as Sn,RefreshCw as Tn,Filter as In,Eye as zn,CheckIcon as Rn,UploadIcon as jn,AlertCircleIcon as Pn,TableProperties as An,LayoutGrid as Dn,PaperclipIcon as En,PlusIcon as $n,Activity as Ln,SquareIcon as Fn,ArrowUpIcon as Mn,Cpu as On,ChevronsUp as Un,ChevronsDown as Wn,Minus as Bn,Plus as Vn,Maximize as qn,ScanSearch as Hn,SquarePen as Gn,FileSearch as Jn,Settings as Kn,FolderClosed as Qn,Trash2 as Yn,ChevronsUpDown as Zn,EllipsisVertical as Xn}from"lucide-react";import*as er from"@radix-ui/react-dialog";import{useUserSession as tr,UserSessionContext as nr}from"@vertesia/ui/session";import rr from"papaparse";import{VegaEmbed as ar}from"react-vega";import{twMerge as sr}from"tailwind-merge";import{AgentMessageType as ir,MarkdownRenditionFormat as or,normalizeToolCollection as lr,FileProcessingStatus as cr,AgentSearchScope as dr,mergeInCodePromptSchemas as ur,supportsToolUse as mr,InteractionStatus as pr,PrincipalType as hr,ImageRenditionFormat as fr,WorkflowExecutionStatus as gr,normalizeAgentToolApprovalMode as vr,PDF_RENDITION_NAME as br,AUDIO_RENDITION_NAME as xr,ContentNature as yr,POSTER_RENDITION_NAME as wr,ContentObjectStatus as Nr,Permission as kr,SearchTypes as Cr,SupportedEmbeddingTypes as _r,getContentTypeRefId as Sr,SecurityLevelLabels as Tr}from"@vertesia/common";import"react-dom";import{Slot as Ir}from"@radix-ui/react-slot";import{cva as zr}from"class-variance-authority";import*as Rr from"@radix-ui/react-tooltip";import"@vertesia/ui/env";import"framer-motion";import*as jr from"@radix-ui/react-checkbox";import"@radix-ui/react-collapsible";import{Command as Pr}from"cmdk";import*as Ar from"@radix-ui/react-dropdown-menu";import Dr from"dayjs";import"react-calendar";import*as Er from"@radix-ui/react-popover";import{capitalize as $r}from"lodash-es";import*as Lr from"@radix-ui/react-label";import"@radix-ui/react-radio-group";import"react-resizable-panels";import*as Fr from"@radix-ui/react-separator";import*as Mr from"@radix-ui/react-slider";import*as Or from"@radix-ui/react-switch";import*as Ur from"@radix-ui/react-tabs";import Wr,{defaultUrlTransform as Br}from"react-markdown";import Vr from"rehype-katex";import{remarkDefinitionList as qr,defListHastHandlers as Hr}from"remark-definition-list";import Gr from"remark-directive";import Jr from"remark-gfm";import Kr from"remark-github-blockquote-alert";import Qr from"remark-math";import Yr from"remark-supersub";import{visit as Zr,SKIP as Xr}from"unist-util-visit";import{FusionFragmentProvider as ea,FusionFragmentHandler as ta}from"@vertesia/fusion-ux";import na from"dompurify";import ra from"mermaid";import{useRouterContext as aa,NavLink as sa,useNavigate as ia}from"@vertesia/ui/router";import{MarkdownRenderer as oa,DropZone as la,UploadSummary as ca,useCodeBlockContext as da,isIncompleteJson as ua,CodeBlockPlaceholder as ma,CodeBlockErrorBoundary as pa,CodeBlockRendererProvider as ha,XMLViewer as fa,JSONCode as ga,MonacoEditor as va,JSONDisplay as ba,Progress as xa,useSchema as ya,SchemaEditor as wa,ManagedObject as Na,GeneratedForm as ka}from"@vertesia/ui/widgets";import Ca,{Ajv as _a}from"ajv";import Sa from"dayjs/plugin/localizedFormat";import Ta from"dayjs/plugin/relativeTime";import{Md5 as Ia}from"ts-md5";import{ErrorBoundary as za}from"react-error-boundary";import{pdfjs as Ra,Document as ja,Page as Pa}from"react-pdf";import{SidebarItem as Aa}from"@vertesia/ui/layout";function Da({children:t,secondary:n=!1}){return e("span",{className:n?"bg-secondary text-primary":"text-foreground bg-muted",children:t})}function Ea(e){return e?"array"===e.name?Ea(e.innerType):e:void 0}function $a({property:n}){return t("div",{className:"flex items-center gap-x-2",children:[e("div",{className:"font-semibold text-gray-600",children:n.name}),n.optional&&e(Da,{children:"optional"}),e(Da,{children:n.type.value})]})}function La({activities:t}){return e("div",{className:"flex flex-col gap-y-4 divide-y divide-gray-200",children:t.map(t=>e(Ma,{activity:t},t.name))})}function Fa({code:n,children:r}){return t("div",{className:"flex gap-2 items-center border-b border-b-gray-200 mb-2",children:[e("div",{className:"text-lg font-medium text-gray-900 py-2 ",children:r}),n&&e("div",{children:e(Da,{children:n})})]})}function Ma({activity:n,headingClass:r,headingRef:a}){return t("div",{className:r,id:n.name,ref:a,children:[e("div",{className:"text-xl font-semibold pt-8",children:n.title}),e("div",{className:"pb-4",children:e(Da,{children:n.name})}),n.doc&&e("div",{className:"text-gray-700 pb-2",children:n.doc}),t("div",{className:"pb-4",children:[e(Fa,{code:n.paramsType,children:"Parameters"}),e("div",{className:"divide-y divide-gray-100",children:n.params.map(t=>e(Oa,{property:t},t.name))})]}),t("div",{className:"pb-4",children:[e(Fa,{children:"Returns"}),e("div",{children:n.returnType?n.returnType.value:"void"})]})]})}function Oa({property:n,className:r}){const a=Me(()=>{const t=Ea(n.type.innerType)??n.type;return"object"===t.name&&t.members?e(Wa,{members:t.members}):"enum"===t.name&&t.enum?e(Ua,{values:t.enum}):null},[n.type]);return t("div",{className:Ae("py-2",r),children:[e($a,{property:n}),n.doc&&e("div",{className:"text-gray-700 text-sm pt-2",children:n.doc}),a&&e("div",{className:"my-2 overflow-hidden",children:a})]})}function Ua({values:t}){return e("div",{className:"flex flex-wrap items-center gap-2",children:t.map(t=>e(Da,{secondary:!0,children:t},t))})}function Wa({members:n}){return e(Va,{className:"rounded-md border border-gray-200",button:n=>t("div",{className:"px-4 py-2 flex items-center gap-x-2 text-sm font-medium hover:text-blue-600",children:[e(qa,{isOpen:n}),e("div",n?{children:"Hide child properties"}:{children:"Show child properties"})]}),body:e(Ba,{properties:n})})}function Ba({properties:t}){return e("div",{className:"border-s-2 border-s-blue-200 flex flex-col divide-y divide-gray-100 border-t border-t-gray-200",children:t.map(t=>e(Oa,{property:t,className:"px-4 py-2"},t.name))})}function Va({button:n,body:a,className:s,isInitiallyOpen:i}){const[o,l]=Oe(i||!1);return t("div",{className:Ae(o?"block":"inline-block",s),children:[e(r,{variant:"unstyled",className:"p-0 m-0 bg-transparent",onClick:()=>l(!o),children:e(Ee,{children:n(o)})}),e(Ee,{children:o&&e($e.div,{className:"overflow-hidden",initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.3,ease:"easeOut"},children:a})})]})}function qa({isOpen:t}){return e(Ee,{propagate:!0,mode:"wait",children:e($e.div,{className:"font-mono font-semibold text-gray-400 text-lg",initial:{rotate:0},animate:{rotate:t?45:0},transition:{duration:.2},children:"+"},"closeIcon")})}function Ha(e){return"full_control"===e?"text-attention":"auto_review"===e?"text-info":"text-muted"}function Ga(t){return e("full_control"===t?rt:"ask"===t?tt:nt,{className:"size-4"})}function Ja({mode:n,onChange:d,disabled:u=!1,className:m}){const{t:p}=Ze(),h=Me(()=>[{mode:"ask",label:p("agent.approvalMode.ask"),description:p("agent.approvalMode.askDescription"),icon:e(tt,{className:"size-4"})},{mode:"auto_review",label:p("agent.approvalMode.autoReview"),description:p("agent.approvalMode.autoReviewDescription"),icon:e(nt,{className:"size-4"})},{mode:"full_control",label:p("agent.approvalMode.fullControl"),description:p("agent.approvalMode.fullControlDescription"),icon:e(rt,{className:"size-4"})}],[p]),f=h.find(e=>e.mode===n)??h[2];return t(a,{children:[e(s,{asChild:!0,children:t(r,{type:"button",variant:"ghost",size:"sm",disabled:u,className:i("h-8 max-w-[13rem] rounded-full px-2.5 font-medium","bg-mixer-muted/15 text-muted hover:bg-muted hover:text-foreground disabled:opacity-60",m),"aria-label":p("agent.approvalMode.selectorLabel"),children:[e("span",{className:i("shrink-0",Ha(n)),children:Ga(n)}),e("span",{className:"min-w-0 truncate",children:f.label}),e(at,{className:"size-4 shrink-0 opacity-70"})]})}),t(o,{align:"start",className:"z-[1000000] w-[min(28rem,calc(100vw-1rem))] p-2",children:[e("div",{className:"px-2 pb-1.5 pt-1 text-sm font-medium text-foreground",children:p("agent.approvalMode.dropdownTitle")}),e(l,{value:n,onValueChange:e=>{var t;(t=e)!==n&&d(t)},children:h.map(n=>t(c,{value:n.mode,className:"min-h-14 items-start gap-3 rounded-md py-2 pe-8 ps-2 text-start",children:[e("span",{className:i("mt-0.5 shrink-0",Ha(n.mode)),children:n.icon}),t("span",{className:"min-w-0 flex-1",children:[e("span",{className:"block text-sm font-medium text-foreground",children:n.label}),e("span",{className:"mt-0.5 block whitespace-normal text-sm leading-5 text-muted",children:n.description})]})]},n.mode))})]})]})}function Ka(...e){return sr(De(e))}const Qa=Ue(null);function Ya({children:t}){const n=Be(new Map),r=Be(new Map),a=Ve(e=>n.current.get(e),[]),s=Ve((e,t)=>{n.current.set(e,t)},[]),i=Ve(async(e,t)=>{const a=n.current.get(e);if(a)return a;const s=r.current.get(e);if(s)return s;const i=t().then(t=>(n.current.set(e,t),r.current.delete(e),t)).catch(t=>{throw r.current.delete(e),t});return r.current.set(e,i),i},[]),o=Fe.useMemo(()=>({getUrl:a,setUrl:s,getOrFetch:i}),[a,s,i]);return e(Qa.Provider,{value:o,children:t})}function Za(){return We(Qa)}function Xa(e){return e.startsWith("agents/")||e.startsWith("documents/")}function es(e,t,n="inline"){return`artifact:${e}:${t}:${n}`}function ts(e){return`file:${e}`}function ns({error:n,chartTitle:r}){return e("div",{className:"flex items-center justify-center h-full bg-red-50 dark:bg-red-950 rounded-md p-4",children:t("div",{className:"text-center",children:[t("p",{className:"text-sm font-medium text-red-600 dark:text-red-400",children:["Cannot render ",r||"Vega-Lite"," chart"]}),e("p",{className:"text-xs text-red-500 dark:text-red-500 mt-1 max-w-xs truncate",children:n})]})})}function rs({isOpen:n,onClose:a,title:s,description:i,children:o}){const{t:l}=Ze();return e(er.Root,{open:n,onOpenChange:e=>!e&&a(),children:t(er.Portal,{children:[e(er.Overlay,{className:"fixed inset-0 z-50 bg-black/80 backdrop-blur-sm transition-all duration-300 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0"}),t(er.Content,{className:"fixed inset-2 sm:inset-4 z-50 flex flex-col bg-white dark:bg-gray-900 rounded-xl shadow-2xl transition-all duration-300 ease-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-98 data-[state=open]:zoom-in-98 data-[state=closed]:slide-out-to-bottom-2 data-[state=open]:slide-in-from-bottom-2",onEscapeKeyDown:a,children:[e(er.Close,{asChild:!0,children:e(r,{variant:"unstyled",onClick:a,className:"absolute top-3 end-3 z-10 p-2 rounded-lg bg-white/80 dark:bg-gray-800/80 backdrop-blur-sm hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors duration-150 shadow-sm","aria-label":l("agent.closeFullscreen"),children:e(ut,{className:"w-5 h-5 text-gray-600 dark:text-gray-300"})})}),e("div",{className:"flex-1 overflow-auto p-4 sm:p-6 animate-in fade-in-0 duration-500 delay-150",children:o}),e("div",{className:"flex items-center justify-between px-4 sm:px-6 py-3 border-t border-gray-200 dark:border-gray-800 bg-gray-50/50 dark:bg-gray-800/50 rounded-b-xl",children:t("div",{className:"flex flex-col",children:[e(er.Title,{className:"text-base font-semibold text-gray-900 dark:text-gray-100",children:s||l("agent.dashboard")}),i&&e(er.Description,{className:"text-sm text-gray-500 dark:text-gray-400 mt-0.5",children:i})]})})]})]})})}const as={categorical:["#6366f1","#8b5cf6","#ec4899","#f43f5e","#f97316","#eab308","#22c55e","#14b8a6","#06b6d4","#3b82f6"],blues:["#dbeafe","#93c5fd","#3b82f6","#1d4ed8","#1e3a8a"],purples:["#f3e8ff","#c4b5fd","#8b5cf6","#6d28d9","#4c1d95"],diverging:["#ef4444","#fca5a5","#fef3c7","#86efac","#22c55e"]};function ss(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function is(e){return ss(e)}function os(e,t){if(!e?.encoding)return!1;for(const n of t)for(const t of Object.values(e.encoding))if(t.field===n)return!0;if(Array.isArray(e.layer))for(const n of e.layer)if(os(n,t))return!0;return!1}function ls(e,t){if(!e)return!1;const n=e=>{if(!e)return!1;const n=e.color?.field;return!!n&&t.includes(n)};if(n(e.encoding))return!0;if(Array.isArray(e.layer))for(const t of e.layer)if(n(t.encoding))return!0;return!1}function cs(e,t=[]){const n=[];if(!e||"object"!=typeof e)return n;if(e.data&&"object"==typeof e.data){const r=e.data.url;"string"==typeof r&&r.startsWith("artifact:")&&n.push({path:[...t,"data"],artifactPath:r.replace(/^artifact:/,"").trim()})}const r=["layer","vconcat","hconcat","concat","spec","repeat","facet"];for(const a of r)if(a in e){const r=e[a];Array.isArray(r)?r.forEach((e,r)=>{is(e)&&n.push(...cs(e,[...t,a,String(r)]))}):is(r)&&n.push(...cs(r,[...t,a]))}return n}const ds=qe(function({spec:a,artifactRunId:s}){const{t:i}=Ze(),{title:o,description:l,options:c}=a,d=a.spec,[u,m]=Oe(!1),[p,h]=Oe(!1),[f,g]=Oe(null),[v,b]=Oe(!1),x=Be(null),y=Be(null),w=Be(null),{client:N}=tr(),k=Za(),C=Be(N);C.current=N;const _=Be(k);_.current=k;const[S,T]=Oe(null),[I,z]=Oe(!1),[R,j]=Oe(null),P=c?.mode||"chart",A="dashboard"===P,D=c?.enableFullscreen??A,E=c?.height||function(e,t){if("chart"===t)return 280;let n=1;if(e.vconcat)n=Array.isArray(e.vconcat)?e.vconcat.length:1;else if(e.concat){const t=e.columns||2,r=Array.isArray(e.concat)?e.concat.length:1;n=Math.ceil(r/t)}else e.facet&&(n=2);return Math.max(500,280*n+40)}(d,P);He(()=>{const e=cs(d);if(0===e.length)return T(d),z(!1),void j(null);s?console.info("[VegaLiteChart] resolving artifacts with runId:",s,e.map(e=>e.artifactPath)):console.warn("[VegaLiteChart] artifact references found but artifactRunId is missing!",{references:e.map(e=>e.artifactPath),artifactRunId:s});let t=!1;z(!0),j(null);return(async()=>{const n=new Map,r=C.current,a=_.current;for(const i of e)try{const e=i.path.join(".");let t;if(s&&!Xa(i.artifactPath)){const e=es(s,i.artifactPath,"inline");if(a)t=await a.getOrFetch(e,async()=>(await r.files.getArtifactDownloadUrl(s,i.artifactPath,"inline")).url);else{t=(await r.files.getArtifactDownloadUrl(s,i.artifactPath,"inline")).url}}else{const e=ts(i.artifactPath);if(a)t=await a.getOrFetch(e,async()=>(await r.files.getDownloadUrl(i.artifactPath)).url);else{t=(await r.files.getDownloadUrl(i.artifactPath)).url}}const o=await fetch(t);if(!o.ok)throw new Error(`Failed to fetch artifact data: ${o.statusText}`);let l;if(i.artifactPath.toLowerCase().endsWith(".csv")){const e=await o.text();l=rr.parse(e,{header:!0,skipEmptyLines:!0,dynamicTyping:!0}).data}else{const e=await o.json();l=Array.isArray(e)?e:[e]}n.set(e,l)}catch(e){return console.error(`Failed to resolve artifact: ${i.artifactPath}`,e),void(t||j(`Failed to load data from artifact: ${i.artifactPath}`))}if(!t){const e=function(e,t){const n=JSON.parse(JSON.stringify(e));for(const[e,r]of t){const t=e.split(".");let a=n;for(let e=0;e<t.length-1;e++){const n=a[t[e]];if(!ss(n))break;a=n}const s=a[t[t.length-1]];ss(s)&&(delete s.url,s.values=r)}return n}(d,n);T(e),z(!1)}})(),()=>{t=!0}},[d,s]);const[$,L]=Oe(!1),F=Be(!1);He(()=>{const e=()=>{const e=document.documentElement.classList.contains("dark");e!==F.current&&(F.current=e,L(e))};e();const t=new MutationObserver(e);return t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),()=>t.disconnect()},[]);const[M,O]=Oe(0),U=Be(0);He(()=>{if(!w.current)return;let e;const t=new ResizeObserver(t=>{clearTimeout(e),e=setTimeout(()=>{const e=t[0]?.contentRect.width;e&&e!==U.current&&(U.current=e,O(e))},100)});t.observe(w.current);const n=w.current.clientWidth;return U.current=n,O(n),()=>{clearTimeout(e),t.disconnect()}},[]);const W=Me(()=>cs(d).length>0,[d]),B=Me(()=>{if(W&&!S)return null;let e=S||d;return e?(c?.parameterValues&&(e=function(e,t){if(!t||0===Object.keys(t).length)return e;const n=JSON.parse(JSON.stringify(e)),r=e=>{for(const n of e)n.name&&n.name in t&&(n.value=t[n.name])};Array.isArray(n.params)&&r(n.params);const a=e=>{if(Array.isArray(e))for(const t of e)if(Array.isArray(t.params)&&r(t.params),t.vconcat&&a(t.vconcat),t.hconcat&&a(t.hconcat),t.concat&&a(t.concat),Array.isArray(t.layer))for(const e of t.layer)Array.isArray(e.params)&&r(e.params)};if(n.vconcat&&a(n.vconcat),n.hconcat&&a(n.hconcat),n.concat&&a(n.concat),Array.isArray(n.layer))for(const e of n.layer)e&&Array.isArray(e.params)&&r(e.params);return n}(e,c.parameterValues)),function(e){const t=JSON.parse(JSON.stringify(e)),n=["vconcat","hconcat","concat"];if(!n.some(e=>Array.isArray(t[e])))return t;const r=[];if(Array.isArray(t.params))for(const e of t.params)e&&"object"==typeof e&&e.name&&e.select&&r.push({name:e.name,param:e});if(0===r.length)return t;for(const{name:e,param:a}of r){const r=a.select?.fields||[],s="legend"===a.select?.bind;let i=null;for(const e of n)if(Array.isArray(t[e])){i=t[e];break}if(!i||0===i.length)continue;let o=0;for(let e=0;e<i.length;e++){const t=i[e];if(os(t,r)||s&&ls(t,r)){o=e;break}}const l=i[o];l.params||(l.params=[]),l.params.push(a);const c=t.params??[];t.params=c.filter(t=>t.name!==e)}return Array.isArray(t.params)&&0===t.params.length&&delete t.params,t}(e)):null},[S,d,W,c?.parameterValues]),V=Ve((e,t)=>{if(!e||"object"!=typeof e)return e;if(e.hconcat&&Array.isArray(e.hconcat)){const n=e.hconcat.length,r=(e.spacing??10)*(n-1),a=Math.floor((t-r)/n);return{...e,hconcat:e.hconcat.map(e=>V(e,a))}}if(e.vconcat&&Array.isArray(e.vconcat))return{...e,vconcat:e.vconcat.map(e=>V(e,t))};if(e.concat&&Array.isArray(e.concat)){const n=e.columns??e.concat.length,r=(e.spacing??10)*(n-1),a=Math.floor((t-r)/n);return{...e,concat:e.concat.map(e=>V(e,a))}}const n=e.width;return"container"===n||"number"==typeof n&&n>t?{...e,width:t}:e},[]),q=Ve((e,t=!1)=>{if(!B)return null;const n=function(e){const t={background:"transparent",view:{stroke:"transparent"},range:{category:as.categorical,diverging:as.diverging,heatmap:as.purples,ramp:as.blues},mark:{tooltip:!0},bar:{tooltip:!0,cornerRadiusTopLeft:4,cornerRadiusTopRight:4},line:{tooltip:!0,strokeWidth:2.5,strokeCap:"round"},point:{tooltip:!0,size:60,filled:!0},area:{tooltip:!0,fillOpacity:.7,line:!0},rect:{tooltip:!0,cornerRadius:2},arc:{tooltip:!0,cornerRadius:4},circle:{tooltip:!0,size:80}};return e?{...t,axis:{labelColor:"#a1a1aa",titleColor:"#e4e4e7",gridColor:"#3f3f46",domainColor:"#52525b",tickColor:"#52525b",labelFont:"Inter, system-ui, sans-serif",titleFont:"Inter, system-ui, sans-serif",labelFontSize:11,titleFontSize:12,titleFontWeight:500},legend:{labelColor:"#a1a1aa",titleColor:"#e4e4e7",labelFont:"Inter, system-ui, sans-serif",titleFont:"Inter, system-ui, sans-serif",labelFontSize:11,titleFontSize:12,symbolSize:100},title:{color:"#fafafa",font:"Inter, system-ui, sans-serif",fontSize:14,fontWeight:600}}:{...t,axis:{labelColor:"#71717a",titleColor:"#3f3f46",gridColor:"#e4e4e7",domainColor:"#d4d4d8",tickColor:"#d4d4d8",labelFont:"Inter, system-ui, sans-serif",titleFont:"Inter, system-ui, sans-serif",labelFontSize:11,titleFontSize:12,titleFontWeight:500},legend:{labelColor:"#71717a",titleColor:"#3f3f46",labelFont:"Inter, system-ui, sans-serif",titleFont:"Inter, system-ui, sans-serif",labelFontSize:11,titleFontSize:12,symbolSize:100},title:{color:"#18181b",font:"Inter, system-ui, sans-serif",fontSize:14,fontWeight:600}}}($),r=t?"undefined"!=typeof window?Math.min(window.innerWidth-80,1400):1200:M>0?M-24:500,a="vconcat"in B||"hconcat"in B||"concat"in B,s=a?{type:"pad",contains:"padding"}:{type:"fit",contains:"padding"};let i=B;a&&r&&(i=V(B,r));const l=i.width,c=a?void 0:"container"===l?r:l??r,{width:d,...u}=i;return{$schema:"https://vega.github.io/schema/vega-lite/v6.json",...!a&&c?{width:c}:{},height:t?void 0:e,autosize:s,...a?i:u,...o&&!B.title?{title:o}:{},config:{...n,...B.config}}},[B,o,$,M,V]),H=Ve(async()=>{const e=v?y.current:x.current;if(e&&!p)try{(await e.toCanvas(2)).toBlob(async e=>{e&&(await navigator.clipboard.write([new ClipboardItem({"image/png":e})]),h(!0),setTimeout(()=>h(!1),2e3))},"image/png")}catch(e){console.error("Failed to copy chart:",e)}},[p,v]),G=Ve(async()=>{const e=v?y.current:x.current;if(e&&!u){m(!0);try{const t=await e.toImageURL("png",2),n=document.createElement("a");n.download=`${o||"chart"}.png`,n.href=t,n.click()}catch(e){console.error("Failed to export chart:",e)}finally{m(!1)}}},[o,u,v]),J=Ve(e=>{x.current=e,g(null)},[]),K=Ve(e=>{y.current=e},[]),Q=Ve(e=>{console.error("Vega-Lite rendering error:",e),g(e instanceof Error?e.message:"Unknown error")},[]),Y=Ve(()=>{b(e=>!e)},[]);He(()=>{g(null)},[d]);const Z=({className:n})=>t("div",{className:Ka("flex items-center gap-2",n),children:[t(r,{variant:"unstyled",onClick:H,disabled:p,className:"text-xs px-2 py-1 rounded border border-gray-300 dark:border-gray-700 bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700 cursor-pointer transition-colors disabled:opacity-50 flex items-center gap-1",title:i("agent.copyToClipboard"),children:[e(p?it:ot,{className:"w-3 h-3"}),i(p?"agent.copied":"agent.copy")]}),t(r,{variant:"unstyled",onClick:G,disabled:u,className:"text-xs px-2 py-1 rounded border border-gray-300 dark:border-gray-700 bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700 cursor-pointer transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1",title:i("agent.exportAsPng"),children:[e(lt,{className:"w-3 h-3"}),i(u?"agent.exporting":"agent.export")]}),D&&t(r,{variant:"unstyled",onClick:Y,className:"text-xs px-2 py-1 rounded border border-gray-300 dark:border-gray-700 bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700 cursor-pointer transition-colors flex items-center gap-1",title:i(v?"agent.exitFullscreen":"agent.fullscreen"),children:[e(v?ct:dt,{className:"w-3 h-3"}),i(v?"agent.exit":"agent.fullscreen")]})]});if(I||W&&!S)return e("div",{className:"bg-white dark:bg-gray-900 rounded-lg border border-gray-200 dark:border-gray-800 shadow-sm",children:t("div",{className:"flex flex-col gap-2 p-3",children:[e("div",{className:"flex items-center justify-between",children:e("span",{className:"font-medium text-sm text-gray-900 dark:text-gray-100",children:o||"Chart"})}),e("div",{className:"flex items-center justify-center bg-gray-50 dark:bg-gray-800 rounded",style:{width:"100%",height:E},children:t("div",{className:"flex items-center gap-2 text-gray-500 dark:text-gray-400",children:[e(st,{className:"w-5 h-5 animate-spin"}),e("span",{className:"text-sm",children:"Loading data from artifacts..."})]})})]})});if(R)return e("div",{className:"bg-white dark:bg-gray-900 rounded-lg border border-gray-200 dark:border-gray-800 shadow-sm",children:t("div",{className:"flex flex-col gap-2 p-3",children:[e("div",{className:"flex items-center justify-between",children:e("span",{className:"font-medium text-sm text-gray-900 dark:text-gray-100",children:o||"Chart"})}),e("div",{style:{width:"100%",height:E},children:e(ns,{error:R,chartTitle:o})})]})});if(f)return e("div",{className:"bg-white dark:bg-gray-900 rounded-lg border border-gray-200 dark:border-gray-800 shadow-sm",children:t("div",{className:"flex flex-col gap-2 p-3",children:[e("div",{className:"flex items-center justify-between",children:e("span",{className:"font-medium text-sm text-gray-900 dark:text-gray-100",children:o||"Chart"})}),e("div",{style:{width:"100%",height:E},children:e(ns,{error:f,chartTitle:o})})]})});const X=q(E),ee=q(0,!0);return X?("undefined"!=typeof window&&localStorage.getItem("DEBUG_VEGA_RENDERS")&&console.log("VegaLite rendering with spec:",{title:o,hasData:!!X.data?.values,dataLength:X.data?.values?.length}),t(n,{children:[e("div",{className:Ka("bg-white dark:bg-gray-900 rounded-lg border border-gray-200 dark:border-gray-800 shadow-sm",A&&"border-2"),children:t("div",{className:"flex flex-col gap-2 p-3",children:[t("div",{className:"flex items-center justify-between",children:[t("div",{className:"flex items-center gap-2",children:[e("span",{className:"font-medium text-sm text-gray-900 dark:text-gray-100",children:o||(A?"Dashboard":"Chart")}),A&&e("span",{className:"text-xs px-2 py-0.5 rounded-full bg-indigo-100 dark:bg-indigo-900 text-indigo-700 dark:text-indigo-300",children:"Interactive"})]}),e(Z,{})]}),l&&e("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:l}),e("div",{ref:w,className:"bg-white dark:bg-gray-900 rounded overflow-hidden",style:{width:"100%",height:E,minWidth:0},children:e(ar,{spec:X,onEmbed:e=>J(e.view),onError:Q,options:{renderer:c?.renderer||"canvas",actions:!1}})})]})}),t(rs,{isOpen:v,onClose:()=>b(!1),title:o||(A?"Dashboard":"Chart"),description:l,children:[e("div",{className:"w-full h-full min-h-[calc(100vh-200px)]",children:ee&&e(ar,{spec:ee,onEmbed:e=>K(e.view),onError:Q,options:{renderer:c?.renderer||"canvas",actions:!1}})}),e("div",{className:"absolute bottom-6 end-6",children:e(Z,{className:"bg-white dark:bg-gray-800 rounded-lg shadow-lg p-2 border border-gray-200 dark:border-gray-700"})})]})]})):null},(e,t)=>JSON.stringify(e.spec)===JSON.stringify(t.spec)&&e.artifactRunId===t.artifactRunId);function us(e){return"vega-lite"===e.library&&"object"==typeof e.spec}function ms(e){return"recharts"===e.library||void 0===e.library}const ps=qe(function({spec:n,artifactRunId:r}){return us(n)?e(ds,{spec:n,artifactRunId:r}):function(e){return"string"==typeof e.$schema&&e.$schema.includes("vega")}(n)?e(ds,{spec:{library:"vega-lite",spec:n},artifactRunId:r}):t("div",{className:"my-5 rounded-lg border border-amber-200 bg-amber-50 p-4 text-sm text-amber-900 dark:border-amber-900 dark:bg-amber-950 dark:text-amber-200",children:["Recharts chart rendering has been retired. Use a Vega-Lite chart spec (",e("code",{children:'library: "vega-lite"'})," with ",e("code",{children:"spec"}),")."]})},(e,t)=>JSON.stringify(e.spec)===JSON.stringify(t.spec)&&e.artifactRunId===t.artifactRunId);function hs(e,t){return"live"===e?e:0===t?"live":Math.min(Math.max(e,0),t-1)}function fs(e,t){return 0===t?-1:"live"===e?t-1:Math.min(Math.max(e,0),t-1)}function gs(e,t){if(0===e.length)return null;const n="live"===t?e.length:fs(t,e.length);for(let t=Math.min(n-1,e.length-1);t>=0;t--)if(e[t].type===ir.QUESTION)return t;return null}function vs(e,t){if(0===e.length||"live"===t)return null;for(let n=fs(t,e.length)+1;n<e.length;n++)if(e[n].type===ir.QUESTION)return n;return"live"}function bs(e,t,n){const r=n?hs(t,e.length):"live",a=fs(r,e.length),s=!n||"live"===r,i=s?e:e.slice(0,a+1);return{cursor:r,cursorIndex:a,isLive:s,renderedMessageCount:i.length,displayedMessages:i}}function xs(){return"undefined"!=typeof window}function ys(){if(!xs())return!1;const e=new URLSearchParams(window.location.search),t=function(e){const t=e.indexOf("?");return-1===t?new URLSearchParams:new URLSearchParams(e.slice(t+1))}(window.location.hash),n=e.get("agentChatPlayback")??t.get("agentChatPlayback");return"1"===n||"true"===n}const ws=xs,Ns=ys;function ks({cursor:n,messages:a,onChangeCursor:s,className:o}){const{t:l}=Ze(),c=a.length,m="live"===n,p=fs(n,c),h=c>0&&(m||p>0),f=!m&&c>0,g=c>0&&(m||p>0),v=!m&&c>0&&p<c-1,b=0===c?0:p+1,[x,y]=Oe(String(b));He(()=>{y(String(b))},[b]);const w=(e,t=!1)=>{if(0===c)return void y("0");const n=Number.parseInt(e,10);if(!Number.isFinite(n))return void(t&&y(String(b)));const r=Math.min(Math.max(n,1),c);y(String(r)),s(r-1)},N=c>1,k=N?1:0,C=Math.max(1,c),_="size-7 rounded-lg text-muted hover:text-foreground disabled:opacity-35",S=`${Math.max(3,String(c).length+1)}ch`;return t("div",{className:i("inline-flex max-w-full flex-col gap-1 rounded-xl border border-border/70 bg-background/95 px-2 py-1 text-sm leading-none text-muted shadow-lg shadow-black/10 backdrop-blur",o),"data-testid":"agent-test-playback-controls","data-playback-cursor":n,"data-live-message-count":c,"data-rendered-message-count":m?c:p+1,children:[t("div",{className:"flex max-w-full items-center gap-1",children:[e("span",{className:"ms-2 me-1 font-medium leading-none text-foreground/80",children:l("agent.rewind.label")}),e(r,{type:"button",variant:"ghost",size:"icon","aria-label":l("agent.rewind.jumpToStart"),title:l("agent.rewind.jumpToStart"),disabled:!g,onClick:()=>{0!==c&&s(0)},className:_,children:e(mt,{className:"size-4"})}),e(r,{type:"button",variant:"ghost",size:"icon","aria-label":l("agent.rewind.previousMessage"),title:l("agent.rewind.previousMessage"),disabled:!h,onClick:()=>{0!==c&&s("live"!==n?Math.max(0,p-1):c-1)},className:_,children:e(pt,{className:"size-4"})}),t("span",{className:"inline-flex min-w-16 items-center justify-center gap-0.5 px-1 font-medium leading-none tabular-nums text-foreground/80","data-testid":"agent-test-playback-position",children:[e(d,{type:"text",variant:"unstyled",size:"sm",clearable:!1,inputMode:"numeric",pattern:"[0-9]*",value:x,"aria-label":l("agent.rewind.positionInput"),disabled:0===c,onChange:e=>{const t=e.replace(/\D/g,"");y(t)},onBlur:e=>w(e.currentTarget.value,!0),onKeyDown:e=>{"Enter"===e.key&&(w(e.currentTarget.value,!0),e.currentTarget.blur())},style:{width:S},className:"h-7 w-auto rounded-md border border-transparent bg-transparent px-1 text-center text-sm font-medium leading-none tabular-nums text-foreground outline-none transition-colors hover:border-border focus:border-ring focus:bg-muted/30 disabled:opacity-50"}),e("span",{"aria-hidden":"true",className:"text-muted",children:"/"}),e("span",{className:"text-muted",children:c})]}),e(r,{type:"button",variant:"ghost",size:"icon","aria-label":l("agent.rewind.nextMessage"),title:l("agent.rewind.nextMessage"),disabled:!f,onClick:()=>{0!==c&&"live"!==n&&s(p>=c-1?"live":p+1)},className:_,children:e(ht,{className:"size-4"})}),e(r,{type:"button",variant:"ghost",size:"icon","aria-label":l("agent.rewind.jumpToLatest"),title:l("agent.rewind.jumpToLatest"),disabled:!v,onClick:()=>{0!==c&&s(c-1)},className:_,children:e(ft,{className:"size-4"})}),e(r,{type:"button",variant:m?"secondary":"ghost",size:"icon","aria-label":l("agent.rewind.jumpToLive"),title:l("agent.rewind.jumpToLive"),disabled:m,onClick:()=>s("live"),className:i(_,m&&"bg-muted text-foreground"),children:e(gt,{className:"size-4"})})]}),e("div",{className:"px-2 pb-1",children:e(u,{min:k,max:C,step:1,value:[b],"aria-label":l("agent.rewind.positionInput"),disabled:!N,onValueChange:([e])=>(e=>{0!==c&&w(e)})(String(e)),className:"h-2"})})]})}Ue(void 0);class Cs{filter(e,t){const n=t.toLowerCase();return e.filter(e=>this.valueOf(e).toLowerCase().includes(n))}renderOption(e){return this.valueOf(e)}findById(e,t){return e.find(e=>this.idOf(e)===t)}createItem(e){return null}}class _s extends Cs{valueOf(e){return String(e)}idOf(e){return String(e)}static instance=new _s}class Ss extends _s{createItem(e){return e}static instance=new Ss}const Ts=Fe.createContext(void 0);function Is(){return Fe.useContext(Ts)}const zs=Rr.Provider,Rs=Rr.Root,js=Rr.Trigger,Ps=Le.forwardRef(({className:t,sideOffset:n=4,side:r="top",...a},s)=>{const i=Is();return e(Rr.Portal,{container:i,children:e(Rr.Content,{ref:s,sideOffset:n,side:r,style:{zIndex:100},className:Ka("max-w-[90vw]","z-50 overflow-hidden rounded-md bg-tooltips border border-border px-3 py-1.5 text-xs animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...a})})});function As({description:n,children:r,size:a="sm",placement:s="top",className:i,asChild:o}){const[l,c]=Le.useState(!1),d=Le.useRef(!1);return Le.useEffect(()=>{const e=()=>{c(!1),d.current=!0,requestAnimationFrame(()=>{d.current=!1})};return window.addEventListener("blur",e),document.addEventListener("visibilitychange",e),()=>{window.removeEventListener("blur",e),document.removeEventListener("visibilitychange",e)}},[]),e(zs,{delayDuration:0,children:t(Rs,{open:l,onOpenChange:e=>{d.current||c(e)},children:[e(js,{className:"cursor-pointer",asChild:o,children:r}),e(Ps,{side:s,className:`px-3 py-1.5 max-w-${a} text-${a} px-3 ${i}`,children:n})]})})}Ps.displayName=Rr.Content.displayName;const Ds=new Set;function Es(e,t,n){He(()=>{t&&!Ds.has(e)&&(Ds.add(e),console.warn(`[@vertesia/ui] ${e} is deprecated: ${n}`))},[t,n,e])}const $s=zr("hover:cursor-pointer inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{destructive:"bg-destructive dark:bg-destructive/10 text-destructive ring-1 ring-inset ring-destructive-muted/50 dark:ring-destructive-muted/50 shadow-xs hover:bg-destructive/50",outline:"border border-input bg-background shadow-xs hover:bg-muted ring-inset",secondary:"bg-primary/5 dark:bg-primary/10 text-primary shadow-xs hover:bg-primary/10 dark:hover:bg-primary/20 ring-inset",ghost:"hover:bg-muted/50 dark:hover:bg-muted/20 ring-inset",link:"text-foreground underline-offset-4 hover:underline ring-inset",primary:"bg-primary text-white shadow-xs hover:bg-primary/90 ring-inset",unstyled:""},size:{xs:"h-7 rounded px-2 py-1 text-xs gap-x-1",sm:"h-8 rounded px-3 text-xs",md:"h-9 rounded-md px-4 py-2",lg:"h-10 rounded-md px-3",xl:"rounded-md px-3.5 py-2.5 text-sm gap-x-2",icon:"p-0 m-0 rounded-full",none:""}},defaultVariants:{variant:"primary",size:"md"}}),Ls=Le.forwardRef(({className:r,variant:a,size:s,asChild:i=!1,alt:o,isDisabled:l,isLoading:c,title:d,onClick:u,type:m,...p},h)=>{Es("Button.alt",void 0!==o,"use aria-label for the accessible name and wrap in <VTooltip> for a visual tooltip. `alt` is forwarded to both for one release.");const f=i?Ir:"button",g=i?m:m??"button",v=p["aria-label"]??o,b=i?p.children:t(n,{children:[c&&e(st,{className:"animate-spin"}),p.children]}),x=e(f,{className:Ae(Ka($s({variant:a,size:s})),r),disabled:l||c||p.disabled,ref:h,onClick:u,type:g,autoFocus:!1,...p,"aria-label":v,children:b});return o||d?e(As,{description:o||d,asChild:!0,className:"cursor-pointer",size:"xs",placement:"top",children:x}):x});Ls.displayName="Button";const Fs=Le.forwardRef(({size:t,content:n,toast:r,className:a,alt:s,"aria-label":i,...o},l)=>{const[c,d]=Oe(!1),{t:u}=Ze();Es("CopyButton.alt",void 0!==s,"use aria-label for the accessible name. `alt` is forwarded for one release.");const m=i??s??u("misc.copy");return e(Ls,{ref:l,className:Ka(a),variant:"unstyled",size:t||"sm",onClick:e=>{e.stopPropagation(),navigator.clipboard.writeText(n).then(()=>{d(!0),setTimeout(()=>d(!1),2e3),r?.toast&&r.toast({status:"success",title:r.message||u("misc.copiedToClipboard"),duration:2e3})}).catch(e=>{console.error("Failed to copy text: ",e),r?.toast&&r.toast({status:"error",title:u("misc.failedToCopy"),duration:2e3})})},...o,"aria-label":m,title:m,children:c?e(it,{className:"text-success"}):e(vt,{className:"size-4"})})});Fs.displayName="CopyButton";const Ms=zr("inline-flex items-center rounded-md px-2 py-1 text-xs font-medium",{variants:{variant:{default:"text-foreground bg-muted",secondary:"bg-secondary text-primary",destructive:"bg-destructive text-destructive",attention:"bg-attention text-attention",success:"bg-success text-success",info:"bg-info text-info",done:"bg-done text-done"}},defaultVariants:{variant:"default"}});function Os({className:t,variant:n,children:r,onClick:a,...s}){const i=a?{role:"button",tabIndex:0,onClick:a,onKeyDown:(o=a,e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),o(e))})}:{};var o;return e("span",{className:Ka(Ms({variant:n}),t),...i,...s,children:r})}zr("inline-flex items-center gap-x-1.5 rounded-md px-2 py-1 text-xs font-medium ring-1 ring-inset ring-border",{variants:{variant:{default:"",success:"",destructive:"",attention:"",done:"",info:""}},defaultVariants:{variant:"default"}}),zr("h-1.5 w-1.5",{variants:{variant:{default:"fill-foreground",success:"fill-success",destructive:"fill-destructive",attention:"fill-attention",done:"fill-done",info:"fill-info"}},defaultVariants:{variant:"default"}});const Us=zr("",{variants:{size:{xs:"rounded py-1 text-xs rounded-xs",sm:"rounded text-xs rounded-sm",md:"rounded-md py-2 text-sm",lg:"rounded-md text-base",xl:"rounded-md py-2.5 text-lg"},variant:{default:"flex w-full rounded-md border border-input bg-background ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 ring-inset focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",unstyled:"block m-0 p-0 w-full border-0 focus:outline-hidden focus:ring-0 bg-transparent",noPadding:"block rounded-md border-0 bg-background shadow-2xs ring-1 ring-inset ring-ring placeholder:text-muted-foreground focus:ring-2 focus:ring-inset focus:ring-ring ring-offset-background",legacy:"py-1.5 block rounded-md border-0 bg-background shadow-2xs ring-1 ring-inset ring-ring placeholder:text-muted-foreground focus:ring-2 focus:ring-inset focus:ring-ring ring-offset-background"}},defaultVariants:{size:"md",variant:"default"}});Le.forwardRef(({className:n,type:r,size:a="md",variant:s="default",clearable:i=!0,onChange:o,value:l,invalid:c,...d},u)=>{const m=d["aria-invalid"]??(!!c||void 0);return t("div",{className:"w-full relative inline-block [&:hover_.clear-button]:opacity-100",children:[e("input",{type:r,className:Ka(Us({size:a,variant:s}),n,i&&l?"pe-8":""),ref:u,value:null==l?"":l,onChange:e=>{o?.(e.target.value)},...d,"aria-invalid":m}),i&&l&&!d.readOnly&&!d.disabled&&e(Ls,{variant:"link",size:"icon",type:"button",onClick:()=>{o?.("")},className:"clear-button opacity-0 transition-opacity duration-200\n absolute top-1/2 -translate-y-1/2 text-muted !hover:text-destructive cursor-pointer\n flex items-center justify-center size-6 rounded end-2","aria-label":"Clear input",children:e(ut,{size:16})})]})}).displayName="Input",Ge(function(t,n){const{current:r,children:a,className:s,href:i="#",onClick:o,...l}=t;return e("li",{className:Ae(s,r?"bg-muted":"","w-full p-2 ps-3 text-sm leading-6 font-semibold hover:bg-muted"),children:e("a",{ref:n,href:i,onClick:e=>{o?(e.preventDefault(),o(e)):"#"===i&&e.preventDefault()},className:"w-full flex items-center gap-x-3",...l,children:a})})});const Ws={INPUT:"rounded-md text-sm flex w-full rounded-md border border-input bg-background ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 ring-inset focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 py-1.5"};function Bs(e){return null==e||Number.isNaN(e)?"":e.toString()}Fe.forwardRef(({value:t,onChange:n,className:r,noScroll:a=!1,noSpinners:s=!1,...i},o)=>{const[l,c]=Fe.useState(Bs(t));return He(()=>{if(null==t||!Number.isNaN(t)){const e=Bs(t);c(e)}},[t]),e("input",{onWheel:a?e=>{e.currentTarget.blur()}:i.onWheel,type:"number",value:l,onChange:e=>{const t=e.target.value;if(c(t),""===t)n?.(void 0,t);else{const e=parseFloat(t);n?.(e,t)}},className:Ae(r,Ws.INPUT,{"no-spinners":s},s&&"[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"),ref:o,...i})});Le.forwardRef(({...t},n)=>e("nav",{ref:n,"aria-label":"breadcrumb",...t})).displayName="Breadcrumb";Le.forwardRef(({className:t,...n},r)=>e("ol",{ref:r,className:Ka("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted sm:gap-2.5",t),...n})).displayName="BreadcrumbList";Le.forwardRef(({className:t,...n},r)=>e("li",{ref:r,className:Ka("inline-flex items-center gap-1.5 text-muted",t),...n})).displayName="BreadcrumbItem";Le.forwardRef(({asChild:t,className:n,...r},a)=>e("a",{ref:a,className:Ka("transition-colors hover:text-muted",n),...r})).displayName="BreadcrumbLink";Le.forwardRef(({className:t,href:n,onClick:r,...a},s)=>e(Ls,{variant:"ghost",size:"md",ref:s,className:Ka("p-0! hover:underline! hover:bg-background!",t),onClick:e=>{e.preventDefault(),r&&r(e)},...a})).displayName="BreadcrumbButton";Le.forwardRef(({className:t,...n},r)=>e("span",{ref:r,"aria-current":"page",className:Ka("font-normal text-foreground",t),...n})).displayName="BreadcrumbPage";Le.forwardRef(({className:t,...n},r)=>e("div",{ref:r,className:Ka("rounded-xl border bg-card text-card-foreground shadow",t),...n})).displayName="Card";Le.forwardRef(({className:t,...n},r)=>e("div",{ref:r,className:Ka("flex flex-col p-6",t),...n})).displayName="CardHeader";Le.forwardRef(({className:t,...n},r)=>e("div",{ref:r,className:Ka("font-semibold leading-none tracking-tight",t),...n})).displayName="CardTitle";Le.forwardRef(({className:t,...n},r)=>e("div",{ref:r,className:Ka("text-sm text-muted-foreground",t),...n})).displayName="CardDescription";Le.forwardRef(({className:t,...n},r)=>e("div",{ref:r,className:Ka("p-6 pt-0",t),...n})).displayName="CardContent";Le.forwardRef(({className:t,...n},r)=>e("div",{ref:r,className:Ka("flex items-center p-6 pt-0",t),...n})).displayName="CardFooter";function Vs({children:t}){return e("span",{style:{border:0,clip:"rect(0 0 0 0)",height:"1px",margin:"-1px",overflow:"hidden",padding:0,position:"absolute",width:"1px",whiteSpace:"nowrap",wordWrap:"normal"},children:t})}Le.forwardRef(({className:t,...n},r)=>e(jr.Root,{ref:r,className:Ka("peer size-4 shrink-0 rounded-sm border border-1 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-white",t),...n,children:e(jr.Indicator,{className:Ka("flex items-center justify-center text-current"),children:e(it,{className:"size-4"})})})).displayName=jr.Root.displayName;const qs=Ue(!1);function Hs({children:t}){return e(qs.Provider,{value:!0,children:t})}function Gs({className:n,children:r,isOpen:a,onClose:s,description:i="Modal Description",noCloseButton:o=!1,allowOverflow:l=!1,disableCloseOnClickOutside:c=!1,size:d="md",action:u}){const m=e=>{e||s()};return t(Qs,{open:a,onOpenChange:e=>{c&&!e||m(e)},children:[l&&e(Xs,{className:"z-50 fixed inset-0 bg-black/80"}),e(Vs,{children:e(ti,{children:i})}),t(ei,{className:Ka("min-h-20 p-4","fixed left-[50%] top-[50%] z-50 grid w-full translate-x-[-50%] translate-y-[-50%] border bg-background shadow-lg duration-200 sm:rounded-lg",function(){switch(d){case"sm":return"max-w-[20vw]";case"md":default:return"max-w-[60vw] lg:max-w-[40vw]";case"lg":return"max-w-[80vw] md:max-w-[60vw]";case"xl":return"max-w-[95vw] lg:max-w-[80vw]"}}(),n),children:[e("div",{className:"top-4 end-4 absolute",children:t("div",{className:"flex gap-2",children:[u&&u,!o&&e(Zs,{onClick:()=>m(!1),asChild:!0,autoFocus:!1,children:e(Ls,{variant:"outline",alt:"Close",className:"data-[state=open]:bg-accent opacity-70 hover:opacity-100 rounded-sm focus:outline-none focus:ring-2 focus:ring-ring ring-offset-background focus:ring-offset-2 data-[state=open]:text-muted-foreground transition-opacity disabled:pointer-events-none",children:e(ut,{className:"size-4"})})})]})}),e(Hs,{children:r})]})]})}const Js=({children:n,show:r=!0,className:a,description:s,showDivider:i=!1,...o})=>r?t(ni,{className:Ka(i?"border-b-solid border-b border-b-1 pb-2 mb-4":"","text-lg font-semibold leading-6 tracking-tight",{"py-2":!s},a),...o,children:[n,s&&e(ti,{className:"text-sm !font-normal text-muted-foreground pb-2",children:s})]}):t(Vs,{children:[e(ni,{children:n}),s&&e(ti,{children:s})]}),Ks=({children:t,className:n,...r})=>e("div",{className:Ka("text-sm max-h-[80vh] overflow-y-auto",n),...r,children:t}),Qs=er.Root,Ys=er.Portal,Zs=er.Close,Xs=Le.forwardRef(({className:t,...n},r)=>e(er.Overlay,{ref:r,className:Ka("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...n}));Xs.displayName=er.Overlay.displayName;const ei=Le.forwardRef(({className:n,children:r,...a},s)=>{const i=Is();return t(Ys,{container:i,children:[e(Xs,{}),e(er.Content,{ref:s,autoFocus:!1,onOpenAutoFocus:e=>{e.preventDefault()},className:Ka("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] border bg-background shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",n),...a,children:r})]})});ei.displayName=er.Content.displayName;const ti=Le.forwardRef(({className:t,...n},r)=>e(er.Description,{ref:r,className:Ka("text-sm text-muted",t),...n}));ti.displayName=er.Description.displayName;const ni=Le.forwardRef(({className:t,...n},r)=>e(er.Title,{ref:r,className:Ka("text-lg font-semibold leading-none tracking-tight",t),...n}));ni.displayName=er.Title.displayName;Le.forwardRef(({className:t,...n},r)=>e(Pr,{ref:r,className:Ka("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",t),...n})).displayName=Pr.displayName;Le.forwardRef(({className:n,...r},a)=>t("div",{className:"flex items-center px-3 border-b","cmdk-input-wrapper":"",children:[e(bt,{className:"opacity-50 size-4 shrink-0"}),e(Pr.Input,{ref:a,className:Ka("focus:ring-0","border-0 flex h-8 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",n),...r})]})).displayName=Pr.Input.displayName;Le.forwardRef(({className:t,...n},r)=>e(Pr.List,{ref:r,className:Ka("overflow-y-auto overflow-x-hidden",t),...n})).displayName=Pr.List.displayName;Le.forwardRef((t,n)=>e(Pr.Empty,{ref:n,className:"py-2 text-sm text-center",...t})).displayName=Pr.Empty.displayName;Le.forwardRef(({className:t,...n},r)=>e(Pr.Group,{ref:r,className:Ka("overflow-y-auto overflow-x-hidden p-1 text-foreground","[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",t),...n})).displayName=Pr.Group.displayName;Le.forwardRef(({className:t,...n},r)=>e(Pr.Separator,{ref:r,className:Ka("-mx-1 h-px bg-border",t),...n})).displayName=Pr.Separator.displayName;Le.forwardRef(({className:t,...n},r)=>e(Pr.Item,{ref:r,className:Ka("hover:bg-muted cursor-pointer relative flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",t),...n})).displayName=Pr.Item.displayName;const ri=Le.createContext(!1);function ai({...t}){return e(Ar.Root,{"data-slot":"dropdown-menu",...t})}function si({...t}){return e(Ar.Trigger,{"data-slot":"dropdown-menu-trigger",...t})}function ii({className:t,align:n="start",sideOffset:r=4,...a}){return e(Ar.Portal,{children:e(Ar.Content,{"data-slot":"dropdown-menu-content",sideOffset:r,align:n,className:Ka("data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 ring-foreground/10 bg-popover text-popover-foreground min-w-32 rounded-lg p-1 shadow-md ring-1 duration-100 z-50 max-h-(--radix-dropdown-menu-content-available-height) w-(--radix-dropdown-menu-trigger-width) origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto data-[state=closed]:overflow-hidden",t),...a})})}function oi({className:t,inset:n,variant:r="default",...a}){return e(Ar.Item,{"data-slot":"dropdown-menu-item","data-inset":n,"data-variant":r,className:Ka("hover:bg-muted focus:bg-muted data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:text-destructive gap-2 rounded-md px-1.5 py-1 text-sm data-inset:ps-7 [&_svg:not([class*='size-'])]:size-4 group/dropdown-menu-item relative flex cursor-default items-center outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0",t),...a})}const li={left:"start",center:"center",right:"end"};function ci({trigger:n,children:r,align:a="right",hover:s}){const[i,o]=Le.useState(!1),l=Le.useRef(null);if(s){return t("div",{className:"relative inline-flex",onMouseEnter:()=>{l.current&&clearTimeout(l.current),o(!0)},onMouseLeave:()=>{l.current=setTimeout(()=>o(!1),80)},children:[n,i&&e("div",{className:Ka("absolute top-full pt-1 z-50","right"===a?"end-0":"center"===a?"left-1/2 -translate-x-1/2":"start-0"),children:e("div",{className:"min-w-32 rounded-lg p-1 shadow-md ring-1 ring-foreground/10 bg-popover text-popover-foreground",children:e(ri.Provider,{value:!0,children:r})})})]})}return t(ai,{children:[e(si,{asChild:!0,children:e("span",{className:"-m-1.5 flex items-center p-1.5",children:n})}),e(ii,{align:li[a],className:"w-max",children:r})]})}function di({children:t,href:n,onClick:r,isDisabled:a=!1,variant:s="default",className:i}){const o=Le.useContext(ri),l=Ka("w-full gap-2 rounded-md px-1.5 py-1 text-sm text-nowrap [&_svg:not([class*='size-'])]:size-4 flex cursor-default items-center select-none [&_svg]:pointer-events-none [&_svg]:shrink-0","destructive"===s?"text-destructive":"",a?"pointer-events-none opacity-50":"hover:bg-muted focus:bg-muted",i);if(o){const s=e=>{e.stopPropagation(),r?.(e)};return n?e("a",{href:n,className:l,children:t}):e("button",{type:"button",className:l,disabled:a,onClick:s,children:t})}return e(oi,{className:Ka("data-[disabled]:pointer-events-none data-[disabled]:opacity-50 text-nowrap",i),disabled:a,variant:s,onClick:e=>{e.stopPropagation(),r?.(e)},asChild:!!n,children:n?e("a",{href:n,children:t}):t})}const ui=Le.createContext(null);function mi(e=!1,t=()=>{},n){e&&t("enter"===n)}Le.forwardRef(({children:t,...n},r)=>{const a=Le.useContext(ui);if(!a)throw new Error("PopoverTrigger must be used within a Popover");const{setOpen:s,hover:i,click:o}=a;return e(Er.Trigger,{ref:r,asChild:!0,onMouseEnter:()=>mi(i,s,"enter"),onMouseLeave:()=>mi(i,s,"leave"),onClick:()=>{o&&s(e=>!e)},...n,children:t})}).displayName=Er.Trigger.displayName;Le.forwardRef(({className:t,align:n="center",side:r="bottom",...a},s)=>{const i=Le.useContext(ui);if(!i)throw new Error("PopoverContent must be used within a Popover");const{setOpen:o,hover:l}=i,c=Is();return e(Er.Portal,{container:c,children:e(Er.Content,{ref:s,align:n,side:r,onMouseEnter:()=>mi(l,o,"enter"),onMouseLeave:()=>mi(l,o,"leave"),className:Ka("z-50 w-72 rounded-md border-popover bg-popover text-popover-foreground ring-1 ring-gray-200 dark:ring-slate-700 shadow-md focus:outline-none animate-in","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...a})})}).displayName=Er.Content.displayName;var pi;Er.Close.displayName=Er.Close.displayName,Fe.createContext({filters:[],setFilters:()=>{},filterGroups:[]}),function(e){e.IS="is",e.IS_NOT="is_not",e.CONTAINS="contains",e.BEFORE="before",e.AFTER="after",e.IS_ANY_OF="is_any_of"}(pi||(pi={}));Ge(({className:t,level:n=3,...r},a)=>e(`h${n}`,{ref:a,className:Ka({h1:"text-2xl font-medium tracking-tight",h2:"text-xl font-medium tracking-tight",h3:"text-lg font-medium",h4:"text-base font-medium",h5:"text-sm font-medium",h6:"text-xs font-medium"}[`h${n}`],"mb-2",t),...r})).displayName="Heading";const hi=zr("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70");Le.forwardRef(({className:n,required:r,...a},s)=>t(Lr.Root,{ref:s,className:Ka(hi(),n),...a,children:[a.children,r&&e("span",{className:"text-destructive-foreground ms-1",children:"*"})]})).displayName=Lr.Root.displayName,Ue(()=>{});Le.forwardRef(({className:t,orientation:n="horizontal",decorative:r=!0,...a},s)=>e(Fr.Root,{ref:s,decorative:r,orientation:n,className:Ka("shrink-0 bg-border","horizontal"===n?"h-[1px] w-full":"h-full w-[1px]",t),...a})).displayName=Fr.Root.displayName;Le.forwardRef(({className:n,trackClassName:r,rangeClassName:a,thumbClassName:s,value:i,defaultValue:o,min:l=0,max:c=100,"aria-label":d,...u},m)=>{const p=Le.useId(),h=Array.isArray(i)?i.length:Array.isArray(o)?o.length:1,f=Le.useMemo(()=>Array.from({length:Math.max(1,h)},(e,t)=>`${p}-thumb-${t}`),[p,h]);return t(Mr.Root,{ref:m,"data-slot":"slider",value:i,defaultValue:o,min:l,max:c,...u,className:Ka("relative flex w-full touch-none select-none items-center data-[disabled]:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",n),children:[e(Mr.Track,{"data-slot":"slider-track",className:Ka("relative h-1.5 w-full grow overflow-hidden rounded-full bg-muted data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5",r),children:e(Mr.Range,{"data-slot":"slider-range",className:Ka("absolute h-full bg-primary data-[orientation=vertical]:w-full",a)})}),f.map(t=>e(Mr.Thumb,{"data-slot":"slider-thumb","aria-label":d,className:Ka("block size-3.5 rounded-full border border-primary bg-background shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",s)},t))]})}).displayName=Mr.Root.displayName;const fi={sm:["h-5 w-8","size-3","translate-x-4 rtl:-translate-x-4"],md:["h-6 w-11","size-4","translate-x-6 rtl:-translate-x-6"],lg:["h-8 w-16","size-6","translate-x-9 rtl:-translate-x-9"]};function gi({className:n,size:r="md",value:a,onChange:s,children:i,disabled:o,...l}){const[c,d,u]=fi[r],m=e(Or.Root,{"data-slot":"switch",checked:a,onCheckedChange:s,disabled:o,...l,className:Ka("data-[state=checked]:bg-primary data-[state=unchecked]:bg-muted focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:aria-invalid:border-destructive/50 shrink-0 rounded-full border focus-visible:ring-3 aria-invalid:ring-3 peer group/switch relative inline-flex items-center transition-all outline-none after:absolute after:-inset-x-3 after:-inset-y-2 data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",c,!i&&n),children:e(Or.Thumb,{"data-slot":"switch-thumb",className:Ka("bg-white rounded-full pointer-events-none block ring-0 transition-transform",d,a?u:"translate-x-1 rtl:-translate-x-1")})});return i?t("div",{className:Ka("flex items-center",n),children:[m,e("span",{className:"px-2",children:i})]}):m}const vi=Le.createContext({size:void 0,tabs:void 0,current:void 0,setTab:void 0,responsive:!1,variant:"tabs",updateHash:!0});Le.forwardRef(({className:t,size:n,variant:r="tabs",...a},s)=>e(vi.Provider,{value:{size:n,variant:r},children:e(Ur.List,{ref:s,className:Ka("tabs"===r?"border-b -mb-px flex gap-4":"flex gap-2 p-1 rounded-md",t),...a})})).displayName=Ur.List.displayName;Le.forwardRef(({className:t,href:n,variant:r="tabs",...a},s)=>{const{size:i}=Le.useContext(vi),o=Le.useCallback(e=>{if(n){e.preventDefault();const t=window.history.state;window.history.pushState(t,"",n)}a.onClick&&a.onClick(e)},[n,a.onClick]);return e(Ur.Trigger,{ref:s,className:Ka("tabs"===r?Ka("border-b-2 px-2 py-1.5 text-sm font-medium whitespace-nowrap cursor-pointer","border-transparent text-muted-foreground hover:border-border hover:text-foreground","data-[state=active]:border-primary data-[state=active]:text-primary","disabled:pointer-events-none disabled:opacity-50"):Ka("px-3 py-1.5 text-sm font-medium whitespace-nowrap cursor-pointer rounded-sm transition-colors","tborder border-input bg-muted shadow-xs hover:bg-muted ring-inset","data-[state=active]:bg-primary data-[state=active]:text-white data-[state=active]:shadow-sm","disabled:pointer-events-none disabled:opacity-50"),t,i?`w-1/${i}`:""),onClick:o,...a})}).displayName=Ur.Trigger.displayName;Le.forwardRef(({className:t,...n},r)=>e(Ur.Content,{ref:r,className:Ka("focus-visible:outline-none","flex-1 overflow-y-auto min-h-0 pt-2 pb-4",t),...n})).displayName=Ur.Content.displayName;const bi=zr("text-foreground",{variants:{size:{xl:"text-base md:text-lg leading-relaxed",lg:"text-base leading-relaxed",default:"text-sm leading-normal",sm:"text-sm leading-normal",xs:"text-xs leading-normal"},weight:{normal:"font-normal",medium:"font-medium",semibold:"font-semibold"}},defaultVariants:{size:"default",weight:"normal"}});Ge(({className:t,size:n,weight:r,...a},s)=>e("p",{ref:s,className:Ka(bi({size:n,weight:r,className:t})),...a})).displayName="Text";function xi({size:n,className:r}){const a=function(e){switch(e){case"xs":return"size-2";case"sm":return"size-3";case"md":return"size-4";case"lg":return"size-5";case"xl":return"size-7";case"2xl":return"size-10";default:throw new Error(`Unexpected size: ${e}`)}}(n||"md");return t("svg",{className:Ae("animate-[spin_0.8s_linear_infinite] text-indigo-500",a,r),xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",role:"img","aria-label":"Loading",children:[e("title",{children:"Loading"}),e("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]})}function yi({onComplete:e,onError:t}){const n=Be(null),r=Be(e),a=Be(t);He(()=>{r.current=e,a.current=t},[e,t]),He(()=>()=>{n.current&&(n.current(),n.current=null)},[]);return{openOAuthPopup:e=>{n.current&&(n.current(),n.current=null);const t=window.screenX+(window.outerWidth-600)/2,s=window.screenY+(window.outerHeight-700)/2,i=window.open(e,"oauth_popup",`width=600,height=700,left=${t},top=${s},popup=yes`);let o=!1,l=null;const c=new BroadcastChannel("oauth-callback");c.addEventListener("message",e=>{var t;"object"==typeof(t=e.data)&&null!==t&&"type"in t&&"oauth-complete"===t.type&&"success"in t&&"boolean"==typeof t.success&&(o=!0,c.close(),l&&clearInterval(l),r.current(),!e.data.success&&e.data.error&&a.current?.(e.data.error),n.current=null)}),i&&(l=setInterval(()=>{i.closed&&(l&&clearInterval(l),c.close(),o||r.current(),n.current=null)},1e3)),n.current=()=>{c.close(),l&&clearInterval(l)}}}}function wi({appId:r,collectionId:a,collectionName:s,authenticated:i,onAuthChange:o,onError:l,variant:c="default",showLabel:d=!1,showDisconnect:u=!1,readOnly:m=!1}){const{client:p}=tr(),{t:h}=Ze(),[f,g]=Oe(null),[v,b]=Oe(void 0===i&&!m),[x,y]=Oe(!1),[w,N]=Oe(!1),k=i??f?.authenticated??!1,C=s??a,_="h-6 w-32 justify-center px-2 text-xs",S=Ve(async()=>{if(void 0===i)if(m)b(!1);else try{b(!0);const e=await p.remoteMcpConnections.getCollectionStatus(r,a);g(e)}catch(e){console.error("[RemoteMcpConnectionButton] Failed to load OAuth status:",e)}finally{b(!1)}else b(!1)},[p,r,a,i,m]);He(()=>{S()},[S]);const{openOAuthPopup:T}=yi({onComplete:()=>{y(!1),S(),o?.()},onError:e=>{console.error("OAuth failed:",e),y(!1)}}),I=async()=>{try{y(!0),l?.(null);const e=await p.remoteMcpConnections.authorize(r,a);e.connected?(y(!1),await S(),o?.()):e.authorization_url?T(e.authorization_url):(l?.(`${C}: Authorization URL not provided by server`),y(!1))}catch(e){console.error("Failed to authorize:",e);const t=(e instanceof Error?e.original_message??e.message:"Failed to connect").replace(/^[A-Za-z\s]+:\s/,"");l?.(`${C}: ${t}`),y(!1)}},z=async()=>{try{N(!0),await p.remoteMcpConnections.disconnect(r,a),await S(),o?.()}catch(e){console.error("Failed to disconnect:",e)}finally{N(!1)}};return v?"compact"===c?e(Ls,{variant:"outline",size:"sm",disabled:!0,className:_,"aria-label":h("mcpConnections.checkingStatus"),title:h("mcpConnections.checkingStatus"),children:e(xi,{className:"size-3"})}):e("div",{className:"flex items-center gap-2 text-sm",children:e(xi,{className:"size-4"})}):"full"===c?t("div",k?{className:"flex items-center gap-2",children:[d&&t("span",{className:"font-medium text-sm text-foreground",children:[C,":"]}),t("div",{className:"flex items-center gap-1 text-success text-sm",children:[e(xt,{className:"size-4"}),e("span",{children:h("mcpOAuth.connected")})]}),u&&e(Ls,{variant:"ghost",size:"sm",onClick:z,disabled:w,children:w?e(xi,{className:"size-4"}):h("mcpOAuth.disconnect")})]}:{className:"flex items-center gap-2 text-sm",children:[d&&t("span",{className:"font-medium text-foreground",children:[C,":"]}),e(Ls,{variant:"ghost",size:"sm",onClick:I,disabled:x,children:t(n,x?{children:[e(xi,{className:"size-4"}),e("span",{children:h("mcpOAuth.authenticating")})]}:{children:[e(rt,{className:"size-4"}),e("span",{children:h("mcpOAuth.authenticate")})]})})]}):k?t("div","compact"===c?{className:"flex items-center gap-2",children:[d&&t("span",{className:"font-medium text-xs text-foreground",children:[C,":"]}),!m&&u&&e(Ls,{variant:"outline",size:"sm",onClick:z,disabled:w,className:_,children:w?e(xi,{className:"size-3"}):t(n,{children:[e(yt,{className:"size-3"}),e("span",{children:h("mcpOAuth.disconnect")})]})})]}:{className:"flex items-center gap-1 text-success",children:[e(xt,{className:"size-4"}),e("span",{className:"text-sm",children:h("mcpOAuth.connected")})]}):"compact"===c?t("div",m?{className:"flex items-center gap-2",children:[d&&t("span",{className:"font-medium text-xs text-foreground",children:[s,":"]}),e("div",{className:"flex items-center gap-1 text-muted",children:e("span",{className:"text-xs",children:h("mcpOAuth.notConnected")})})]}:{className:"flex items-center gap-2",children:[d&&t("span",{className:"font-medium text-xs text-foreground",children:[C,":"]}),e(Ls,{variant:"outline",size:"sm",onClick:I,disabled:x,className:_,children:t(n,x?{children:[e(xi,{className:"size-3"}),e("span",{children:h("mcpOAuth.connecting")})]}:{children:[e(wt,{className:"size-3"}),e("span",{children:h("mcpOAuth.connect")})]})})]}):e(Ls,{variant:"outline",size:"sm",onClick:I,disabled:m||x,children:t(n,x?{children:[e(xi,{className:"size-4"}),e("span",{children:h("mcpOAuth.connecting")})]}:{children:[e(wt,{className:"size-4 me-1"}),e("span",{children:h("mcpOAuth.connect")})]})})}Ue({theme:"system",setTheme:()=>null});const Ni=Fe.createContext({});function ki({children:t,artifactRunId:n,onProposalSelect:r,onProposalSubmit:a,MarkdownRenderer:s}){const i=Me(()=>({artifactRunId:n,onProposalSelect:r,onProposalSubmit:a,MarkdownRenderer:s}),[n,r,a,s]);return e(Ni.Provider,{value:i,children:t})}function Ci(){return Fe.useContext(Ni)}const _i=Ue(null);const Si={chart:{icon:zt,label:"chart",defaultHeight:200},mermaid:{icon:It,label:"diagram",defaultHeight:150},proposal:{icon:Tt,label:"options",defaultHeight:100},code:{icon:Nt,label:"code",defaultHeight:80},image:{icon:St,label:"image",defaultHeight:150},link:{icon:_t,label:"link",defaultHeight:24},expand:{icon:lt,label:"content",defaultHeight:100},table:{icon:Ct,label:"table",defaultHeight:150},markdown:{icon:kt,label:"content",defaultHeight:100},"fusion-fragment":{icon:Nt,label:"fragment",defaultHeight:150}};function Ti({type:n,error:a,onRetry:s,message:i,height:o}){const l=Si[n],c=o??l.defaultHeight,d="link"===n;if(a)return t("div",{className:"flex items-center gap-2 rounded border border-destructive/30 bg-destructive/5 text-destructive "+(d?"inline-flex px-2 py-1 text-sm":"p-4"),style:d?void 0:{minHeight:c},children:[t("span",{className:"text-destructive",children:["Failed to load ",l.label]}),s&&e(r,{variant:"unstyled",onClick:s,className:"ms-2 rounded bg-destructive/10 px-2 py-1 text-xs hover:bg-destructive/20 transition-colors text-destructive",children:"Retry"})]});const u=l.icon;return d?t("span",{className:"inline-flex items-center gap-1 text-muted animate-pulse",children:[e(u,{className:"h-3 w-3"}),e("span",{children:i||`Loading ${l.label}...`})]}):t("div",{className:"flex flex-col items-center justify-center gap-3 rounded border border-border bg-muted/30 animate-pulse",style:{minHeight:c},children:[e(u,{className:"h-8 w-8 text-muted"}),e("span",{className:"text-sm text-muted",children:i||`Loading ${l.label}...`}),e("div",{className:"flex gap-1",children:[...Array(3)].map((t,n)=>e("div",{className:"h-2 w-2 rounded-full bg-muted animate-bounce",style:{animationDelay:150*n+"ms"}},n))})]})}class Ii extends Fe.Component{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){console.error(`CodeBlock rendering error (${this.props.type}):`,e,t),this.props.onError?.(e)}handleRetry=()=>{this.setState({hasError:!1,error:void 0})};render(){if(this.state.hasError){const{type:n,fallbackCode:r}=this.props;return t("div",{className:"space-y-2",children:[e(Ti,{type:n,error:this.state.error?.message||"Rendering failed",onRetry:this.handleRetry}),r&&t("details",{className:"text-sm",children:[e("summary",{className:"cursor-pointer text-muted hover:text-foreground",children:"Show raw content"}),e("pre",{className:"mt-2 overflow-x-auto rounded bg-muted/50 p-2 text-xs",children:e("code",{children:r})})]})]})}return this.props.children}}function zi(e){if("object"!=typeof e||null===e)return null;const t=e;return"vega-lite"===t.library&&"spec"in t&&"object"==typeof t.spec&&null!==t.spec?t:"string"==typeof t.$schema&&t.$schema.includes("vega")?{library:"vega-lite",spec:t}:null}function Ri({content:n}){const{headers:r,rows:a}=Me(()=>{if(!Array.isArray(n)||0===n.length)return{headers:[],rows:[]};const e=n[0];if("object"!=typeof e||null===e)return{headers:[],rows:[]};const t=Object.keys(e),r=n.map(e=>t.map(t=>{const n=e[t];return null==n?"":"object"==typeof n?JSON.stringify(n):String(n)}));return{headers:t,rows:r}},[n]);return 0===r.length?e(Ti,{type:"table",error:"No table data found"}):t("div",{className:"overflow-x-auto",children:[t("table",{className:"min-w-full text-sm border-collapse",children:[e("thead",{children:e("tr",{className:"border-b",children:r.map((t,n)=>e("th",{className:"px-3 py-2 text-start font-medium text-muted",children:t},n))})}),e("tbody",{children:a.slice(0,100).map((t,n)=>e("tr",{className:"border-b border-muted/20",children:t.map((t,n)=>e("td",{className:"px-3 py-2",children:t},n))},n))})]}),a.length>100&&t("div",{className:"text-sm text-muted py-2",children:["Showing 100 of ",a.length," rows"]})]})}function ji({content:t,path:n}){const r=n.split(".").pop()?.toLowerCase()||"",a="string"==typeof t?t:JSON.stringify(t,null,2);return e("pre",{className:"overflow-x-auto p-3 bg-muted/10 rounded text-sm",children:e("code",{className:`language-${r}`,children:a})})}function Pi(e){return na.sanitize(e,{USE_PROFILES:{svg:!0,svgFilters:!0},ADD_TAGS:["use"],FORBID_TAGS:["foreignObject"]})}function Ai(e){return e.replace(/<svg([^>]*)>/i,(e,t)=>{let n=t;if(!/viewBox/i.test(n)){const e=/\swidth\s*=\s*["']?(\d+(?:\.\d+)?)/i.exec(n),t=/\sheight\s*=\s*["']?(\d+(?:\.\d+)?)/i.exec(n);e&&t&&(n+=` viewBox="0 0 ${e[1]} ${t[1]}"`)}return n=n.replace(/\swidth\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/i,"").replace(/\sheight\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/i,""),/style="/i.test(n)?n=n.replace(/style="([^"]*)"/i,(e,t)=>`style="${t};width:100%;height:auto;display:block;max-width:100%;"`):n+=' style="width:100%;height:auto;display:block;max-width:100%;"',/preserveAspectRatio=/i.test(n)||(n+=' preserveAspectRatio="xMidYMid meet"'),`<svg${n}>`})}function Di({content:t}){const n=Me(()=>{const e="string"==typeof t?t.trim():"";return e?Ai(Pi(e)):null},[t]);return n?e("div",{style:{margin:"16px 0",width:"100%",overflowX:"auto"},dangerouslySetInnerHTML:{__html:n}}):e(Ti,{type:"expand",error:"Empty mockup"})}function Ei({content:t,path:n}){const r="string"==typeof t?t:"",a=n.split("/").pop()||"Artifact image";return e("img",{src:r,alt:a,className:"max-w-full h-auto rounded",loading:"lazy"})}function $i({content:t,renderType:n,path:r,runId:a,contentType:s}){const{MarkdownRenderer:i}=Ci(),o=Me(()=>"auto"!==n?n:function(e,t,n){const r=t.split(".").pop()?.toLowerCase();if("svg"===r)return"mockup";if(["png","jpg","jpeg","gif","webp"].includes(r||""))return"image";if("md"===r)return"markdown";if("csv"===r)return"table";if("json"===n&&"object"==typeof e&&null!==e){const t=e;if("string"==typeof t.$schema&&t.$schema.includes("vega"))return"vega-lite";if("vega-lite"===t.library&&"spec"in t)return"vega-lite";if("template"in t&&"data"in t)return"fusion-fragment";if(Array.isArray(e)&&e.length>0&&"object"==typeof e[0])return"table"}return"code"}(t,r,s),[t,r,s,n]);switch(o){case"chart":{const n=zi(t);return n?e(Ii,{type:"chart",fallbackCode:JSON.stringify(t,null,2),children:e(ds,{spec:n,artifactRunId:a})}):e(Ti,{type:"chart",error:"Only Vega-Lite charts are supported. Recharts rendering has been retired."})}case"vega-lite":{const n=zi(t);return n?e(Ii,{type:"chart",fallbackCode:JSON.stringify(t,null,2),children:e(ds,{spec:n,artifactRunId:a})}):e(Ti,{type:"chart",error:"Invalid Vega-Lite specification"})}case"fusion-fragment":{const n=t;return console.log("[ArtifactContentRenderer] fusion-fragment:",{hasTemplate:!!n.template,hasData:!!n.data,runId:a,hasVegaLiteChart:!!ds}),n.template&&n.data?e(Ii,{type:"fusion-fragment",fallbackCode:JSON.stringify(t,null,2),children:e(ea,{data:n.data,ChartComponent:ds,artifactRunId:a,children:e(ta,{code:JSON.stringify(n.template),data:n.data})})}):e(Ii,{type:"fusion-fragment",fallbackCode:JSON.stringify(t,null,2),children:e(ta,{code:JSON.stringify(t)})})}case"table":return e(Ii,{type:"table",fallbackCode:JSON.stringify(t,null,2),children:e(Ri,{content:t})});case"markdown":{const n="string"==typeof t?t:String(t);return e(Ii,{type:"markdown",fallbackCode:n,children:i?e(i,{artifactRunId:a,children:n}):e("pre",{className:"overflow-x-auto p-3 bg-muted/10 rounded text-sm",children:e("code",{children:n})})})}case"mockup":return e(Ii,{type:"expand",fallbackCode:"string"==typeof t?t:r,children:e(Di,{content:t})});case"image":return e(Ii,{type:"image",fallbackCode:r,children:e(Ei,{content:t,path:r})});default:return e(ji,{content:t,path:r})}}const Li='Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif';function Fi({code:t,className:n}){const r=Be(null),[a,s]=Oe(null),[i,o]=Oe(null),l=Je().replace(/:/g,"_");return He(()=>{let e=!1;return(async()=>{if(!t.trim())return s(null),void o(null);try{o(null);const n=`mermaid-${l}-${Date.now()}`,r=function(e){const t=e.trim();let n="",r=!1,a=!1;for(let e=0;e<t.length;e++){const s=t[e],i=e>0?t[e-1]:"";if('"'!==s||a||"\\"===i)if("'"!==s||r||"\\"===i){if((r||a)&&"\\"===s){let r=e;for(;"\\"===t[r];)r++;if("n"===t[r]){n+="<br/>",e=r;continue}}n+=s}else a=!a,n+=s;else r=!r,n+=s}return n}(t),{svg:a}=await ra.render(n,r),i=function(e){return e.replace(/<svg([^<>]*)>/i,(e,t)=>{let n=t.replace(/\swidth="[^"]*"/i,"").replace(/\sheight="[^"]*"/i,"");return/style="/i.test(n)?n=n.replace(/style="([^"]*)"/i,(e,t)=>`style="${t};width:100%;height:auto;display:block;max-width:100%;"`):n+=' style="width:100%;height:auto;display:block;max-width:100%;"',/preserveAspectRatio=/i.test(n)||(n+=' preserveAspectRatio="xMidYMid meet"'),`<svg${n}>`})}(a);e||s(i)}catch(t){if(!e){const e=t instanceof Error?t.message:"Failed to render mermaid diagram";o(e),s(null)}}})(),()=>{e=!0}},[t,l]),i?null:e("div",a?{ref:r,className:`my-4 w-full overflow-x-auto [&_svg]:mx-auto [&_svg]:w-full [&_svg]:h-auto [&_svg]:max-w-full ${n||""}`,dangerouslySetInnerHTML:{__html:a}}:{className:`my-4 p-4 bg-gray-50 dark:bg-gray-800 rounded-lg animate-pulse ${n||""}`,children:e("div",{className:"h-32 bg-gray-200 dark:bg-gray-700 rounded"})})}function Mi(e){const t=e.trim();if(t.length<2)return!0;if(!t.startsWith("{"))return!1;try{return JSON.parse(t),!1}catch(e){const n=["unexpected end","unterminated string","expected","unexpected token"],r=(e instanceof Error?e.message:"").toLowerCase();if(n.some(e=>r.includes(e))){let e=0,n=0,r=!1,a=!1;for(const s of t)a?a=!1:"\\"!==s?'"'!==s?r||("{"===s?e++:"}"===s?e--:"["===s?n++:"]"===s&&n--):r=!r:a=!0;return e>0||n>0||r}return!1}}function Oi(e){try{let t=e.trim();const n=t.indexOf("{"),r=t.lastIndexOf("}");return-1!==n&&r>n&&(t=t.slice(n,r+1)),JSON.parse(t)}catch{return null}}function Ui({code:t}){const{artifactRunId:n}=Ci();n||console.warn("[VegaLiteCodeBlockHandler] artifactRunId is missing from CodeBlockContext");const r=Me(()=>Mi(t),[t]),a=Me(()=>{if(r)return null;const e=Oi(t);return e?{library:"vega-lite",spec:e}:null},[t,r]);return r?e(Ti,{type:"chart",message:"Loading chart..."}):a?e(Ii,{type:"chart",fallbackCode:t,children:e(ds,{spec:a,artifactRunId:n})}):e(Ti,{type:"chart",error:"Invalid Vega-Lite specification"})}function Wi({code:t}){const{artifactRunId:n}=Ci();n||console.warn("[ChartCodeBlockHandler] artifactRunId is missing from CodeBlockContext");const r=Me(()=>Mi(t),[t]),a=Me(()=>{if(r)return null;const e=Oi(t);if(!e)return null;const n=function(e){const t="string"==typeof e.$schema&&e.$schema.includes("vega"),n="vega-lite"===e.library&&"spec"in e;return t||n?"vega-lite":null}(e);return n?"vega-lite"===e.library&&"spec"in e&&"object"==typeof e.spec?e:{library:"vega-lite",spec:e}:null},[t,r]);return r?e(Ti,{type:"chart",message:"Loading chart..."}):a?e(Ii,{type:"chart",fallbackCode:t,children:e(ds,{spec:a,artifactRunId:n})}):e(Ti,{type:"chart",error:"Invalid Vega-Lite chart specification"})}function Bi({code:t}){const n=t.trim();return n?e(Ii,{type:"mermaid",fallbackCode:t,children:e(Fi,{code:n})}):e(Ti,{type:"mermaid",error:"Empty diagram"})}function Vi({code:t}){const n=Me(()=>{const e=t.trim();return e?Ai(Pi(e)):null},[t]);return n?e(Ii,{type:"code",fallbackCode:t,children:e("div",{style:{margin:"16px 0",width:"100%",overflowX:"auto"},dangerouslySetInnerHTML:{__html:n}})}):e(Ti,{type:"code",error:"Empty mockup"})}function qi({code:t,language:n}){const{artifactRunId:r}=Ci(),a=t.trim(),s=Me(()=>{if(!n?.includes(":"))return"auto";const e=n.split(":")[1];return["chart","vega-lite","table","markdown","fusion-fragment","mockup","code","image","auto"].includes(e)?e:"auto"},[n]),{data:i,isLoading:o,error:l,contentType:c}=function({runId:e,path:t,parseJson:n=!0}){const{client:r}=tr(),a=Za(),s=Be(r);s.current=r;const i=Be(a);i.current=a;const[o,l]=Oe({data:void 0,rawContent:void 0,isLoading:!0,error:void 0,contentType:void 0}),c=Ve(async()=>{if(!e)return void l({data:void 0,rawContent:void 0,isLoading:!1,error:"No run ID provided",contentType:void 0});if(!t)return void l({data:void 0,rawContent:void 0,isLoading:!1,error:"No artifact path provided",contentType:void 0});l(e=>({...e,isLoading:!0,error:void 0}));const r=s.current,a=i.current,o=function(e){const t=e.split(".").pop()?.toLowerCase();switch(t){case"json":return"json";case"md":case"txt":case"csv":case"yaml":case"yml":default:return"text";case"png":case"jpg":case"jpeg":case"gif":case"webp":case"pdf":return"binary"}}(t);try{const s=es(e,t,"inline");let i;i=a?await a.getOrFetch(s,async()=>(await r.files.getArtifactDownloadUrl(e,t,"inline")).url):(await r.files.getArtifactDownloadUrl(e,t,"inline")).url;const c=await fetch(i);if(!c.ok)throw new Error(`Failed to fetch artifact: ${c.status} ${c.statusText}`);if("binary"===o)return void l({data:i,rawContent:void 0,isLoading:!1,error:void 0,contentType:o});const d=await c.text();let u;if(n&&"json"===o)try{u=JSON.parse(d)}catch{u=d}else u=d;l({data:u,rawContent:d,isLoading:!1,error:void 0,contentType:o})}catch(e){const n=e instanceof Error?e.message:"Failed to fetch artifact";console.error("Failed to fetch artifact content:",t,e),l({data:void 0,rawContent:void 0,isLoading:!1,error:n,contentType:o})}},[e,t,n]);He(()=>{c()},[c]);const d=Ve(()=>{l({data:void 0,rawContent:void 0,isLoading:!0,error:void 0,contentType:void 0}),c()},[c]);return{data:o.data,rawContent:o.rawContent,isLoading:o.isLoading,error:o.error,contentType:o.contentType,retry:d}}({runId:r,path:a});return r?o?e(Ti,{type:"expand",message:`Loading ${a}...`}):l?e(Ti,{type:"expand",error:`Failed to load artifact: ${l}`}):void 0===i?e(Ti,{type:"expand",error:"No content found in artifact"}):e($i,{content:i,renderType:s,path:a,runId:r,contentType:c}):e(Ti,{type:"expand",error:"No artifact run ID available"})}function Hi(e){return e.trim().replace(/^\/+/,"")}function Gi(e){return e.startsWith("artifact:")?{scheme:"artifact",path:e.slice(9).trim()}:e.startsWith("image:")?{scheme:"image",path:e.slice(6).trim()}:e.startsWith("store:")?{scheme:"store",path:Hi(e.slice(6))}:e.startsWith("document:")?{scheme:"document",path:Hi(e.slice(9))}:e.startsWith("collection:")?{scheme:"collection",path:Hi(e.slice(11))}:{scheme:"standard",path:e}}function Ji(e,t){switch(e){case"store":case"document":return t?`/store/objects/${t}`:null;case"collection":return t?`/store/collections/${t}`:null;default:return null}}function Ki({rawUrl:e,artifactRunId:t,disposition:n="inline"}){const{client:r}=tr(),a=Za(),s=Be(r);s.current=r;const i=Be(a);i.current=a;const{scheme:o,path:l}=Gi(e),c=Ji(o,l),[d,u]=Oe(()=>{if(c)return{url:c,isLoading:!1,error:void 0};if("standard"===o)return{url:e,isLoading:!1,error:void 0};if(a&&("artifact"===o||"image"===o)){let e;e="artifact"===o&&t&&!Xa(l)?es(t,l,n):ts(l);const r=a.getUrl(e);if(r)return{url:r,isLoading:!1,error:void 0}}return{url:void 0,isLoading:!0,error:void 0}}),m=Ve(async()=>{if(c||"standard"===o)return;if("artifact"!==o&&"image"!==o)return void u({url:void 0,isLoading:!1,error:`Unknown scheme: ${o}`});u(e=>({...e,isLoading:!0,error:void 0}));const e=s.current,r=i.current;try{let a;if("artifact"===o)if(t&&!Xa(l)){const s=es(t,l,n);if(r)a=await r.getOrFetch(s,async()=>(await e.files.getArtifactDownloadUrl(t,l,n)).url);else{a=(await e.files.getArtifactDownloadUrl(t,l,n)).url}}else{const t=ts(l);if(r)a=await r.getOrFetch(t,async()=>(await e.files.getDownloadUrl(l)).url);else{a=(await e.files.getDownloadUrl(l)).url}}else{const t=ts(l);if(r)a=await r.getOrFetch(t,async()=>(await e.files.getDownloadUrl(l)).url);else{a=(await e.files.getDownloadUrl(l)).url}}u({url:a,isLoading:!1,error:void 0})}catch(e){const t=e instanceof Error?e.message:"Failed to resolve URL";console.error("Failed to resolve URL:",l,e),u({url:void 0,isLoading:!1,error:t})}},[o,l,t,n,c]);He(()=>{if(d.url&&!d.error)return;let e=!1;return e||(async()=>{await m()})(),()=>{e=!0}},[m,d.url,d.error]);const p=Ve(()=>{u({url:void 0,isLoading:!0,error:void 0}),m()},[m]);return{url:d.url,isLoading:d.isLoading,error:d.error,scheme:o,retry:p}}function Qi({src:n,alt:r,caption:a,className:s,artifactRunId:i}){const o=n||"",{scheme:l}=Gi(o);return"standard"===l?t("figure",{className:"my-4",children:[e("img",{src:n,alt:r,className:s}),e("figcaption",{className:"mt-2 text-sm text-muted text-center italic",children:a})]}):e(Yi,{rawSrc:o,alt:r,caption:a,artifactRunId:i,className:s})}function Yi({rawSrc:n,alt:r,caption:a,artifactRunId:s,className:i}){const{url:o,isLoading:l,error:c,retry:d}=Ki({rawUrl:n,artifactRunId:s,disposition:"inline"});return l?e(Ti,{type:"image",message:r?`Loading ${r}...`:void 0}):c?e(Ti,{type:"image",error:c,onRetry:d}):o?t("figure",{className:"my-4",children:[e("img",{src:o,alt:r,className:i}),e("figcaption",{className:"mt-2 text-sm text-muted text-center italic",children:a})]}):null}function Zi({node:t,src:n,alt:r,className:a,artifactRunId:s,ExistingImg:i,...o}){const l=n||"",{scheme:c}=Gi(l);return"standard"===c?"function"==typeof i?e(i,{node:t,src:n,alt:r,...o}):e("img",{src:n,alt:r,className:a,...o}):e(Xi,{rawSrc:l,alt:r,artifactRunId:s,className:a,rest:o})}function Xi({rawSrc:t,alt:n,artifactRunId:r,className:a,rest:s}){const{url:i,isLoading:o,error:l,retry:c}=Ki({rawUrl:t,artifactRunId:r,disposition:"inline"});return o?e(Ti,{type:"image",message:n?`Loading ${n}...`:void 0}):l?e(Ti,{type:"image",error:l,onRetry:c}):i?e("img",{src:i,alt:n,className:a,...s}):null}function eo({node:t,href:n,children:r,className:a,artifactRunId:s,ExistingLink:i,...o}){const l=n||"",{scheme:c,path:d}=Gi(l),u=Ji(c,d);return u?"function"==typeof i?e(i,{node:t,href:u,...o,children:r}):e("a",{href:u,...o,className:a,target:"_blank",rel:"noopener noreferrer",children:r}):"standard"===c?"function"==typeof i?e(i,{node:t,href:n,...o,children:r}):e("a",{href:n,...o,className:a,target:"_blank",rel:"noopener noreferrer",children:r}):e(to,{rawHref:l,artifactRunId:s,className:a,rest:o,children:r})}function to({rawHref:t,artifactRunId:n,className:r,children:a,rest:s}){const{url:i,isLoading:o,error:l,retry:c}=Ki({rawUrl:t,artifactRunId:n,disposition:"attachment"});return o?e("span",{className:"inline-flex items-center gap-1 text-muted",children:e(Ti,{type:"link"})}):l?e("span",{className:"inline-flex items-center gap-1",children:e(Ti,{type:"link",error:l,onRetry:c})}):e("a",{href:i||"#",...s,className:r,target:"_blank",rel:"noopener noreferrer",children:a})}ra.initialize({startOnLoad:!1,theme:"default",securityLevel:"loose",fontFamily:Li,suppressErrorRendering:!0,flowchart:{htmlLabels:!0,useMaxWidth:!0,nodeSpacing:40,rankSpacing:50,padding:12},sequence:{useMaxWidth:!0},themeVariables:{fontFamily:Li}});const no=["artifact:","image:","store:","document://","collection:"],ro=/(!?\[[^[\]\n]*\]\()((?:artifact:|image:|store:|document:\/\/|collection:)[^)[\n]+)(\))/g,ao=/`[^`\n]*`/g,so=/(^|\n)(`{3,}|~{3,})[^\n]*\n[\s\S]*?\n\2(?=\n|$)/g,io=/\s+("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|\([^)]*\))\s*$/;function oo(e){return no.some(t=>e.startsWith(t))}function lo(e){return e.replace(ro,(e,t,n,r)=>`${t}${function(e){const t=e.trim();if(t.startsWith("<")){const n=t.indexOf(">");if(n>0&&oo(t.slice(1,n).trim()))return e}const n=t.match(io),r=n?.index??-1,a=(r>=0?t.slice(0,r):t).trim(),s=r>=0?t.slice(r):"";return oo(a)?`<${a}>${s}`:e}(n)}${r}`)}function co(e){let t="",n=0;for(const r of e.matchAll(ao))t+=lo(e.slice(n,r.index)),t+=r[0],n=r.index+r[0].length;return t+=lo(e.slice(n)),t}const uo=/^([ \t]*):::([^\n]*?):::[ \t]*$/gm,mo=/^\w+/;const po=/(^|\n)(`{3,}|~{3,})[^\n]*\n[\s\S]*?\n\2(?=\n|$)/g,ho=/`[^`\n]*`/g,fo=/\\\$/g,go=/\\[^\s]/,vo=/[{}]/,bo=/[_^][\w{]/,xo=/^[a-zA-Z]$/,yo=/^[a-zA-Z]\s*=/,wo=/^\s/,No=/\s$/,ko=/[+*/-]$/,Co=/\^[+-]$/;function _o(e){return go.test(e)||vo.test(e)||bo.test(e)||xo.test(e)||yo.test(e)}function So(e){return!!wo.test(e)||(!!No.test(e)||!(!ko.test(e)||Co.test(e)))}function To(e,t,n){const r=e.slice(t+1,n);return 0===r.length||r.includes("\n")?null:r}function Io(e){const t=function(e){const t=[];for(let n=0;n<e.length;n++)"$"===e[n]&&(n>0&&"\\"===e[n-1]||(n+1<e.length&&"$"===e[n+1]?n++:n>0&&"$"===e[n-1]&&(n<2||"\\"!==e[n-2])||t.push(n)));return t}(e);if(t.length<2)return e;const n=new Set,r=new Set,a=new Array(t.length-1);for(let n=0;n<t.length-1;n++)a[n]=To(e,t[n],t[n+1]);const s=[];for(let e=0;e<t.length-1;e++){if(n.has(e))continue;const r=a[e];null!==r&&_o(r)&&(n.add(e),n.add(e+1),s.push([t[e],t[e+1]]))}let i=0;for(;i<t.length;){if(n.has(i)){i++;continue}let e=i+1;for(;e<t.length&&n.has(e);)e++;if(e>=t.length)break;if(e>i+1){r.add(t[i]),i++;continue}const s=a[i];null!==s?(So(s)&&(r.add(t[i]),r.add(t[e])),n.add(i),n.add(e),i=e+1):i++}for(let e=0;e<t.length;e++)n.has(e)||e+1<t.length&&n.has(e+1)&&r.add(t[e]);if(0===r.size&&0===s.length)return e;const o=[];let l=0;const c=Array.from(r).sort((e,t)=>e-t);let d=0,u=0;for(;d<c.length||u<s.length;){const t=d<c.length?c[d]:1/0;if(t<(u<s.length?s[u][0]:1/0))t>l&&o.push(e.slice(l,t)),o.push("\\$"),l=t+1,d++;else{const[t,n]=s[u];t>l&&o.push(e.slice(l,t));const r=e.slice(t,n+1);for(o.push(r.replace(fo,"\\text{\\textdollar}")),l=n+1;d<c.length&&c[d]<=n;)d++;u++}}return l<e.length&&o.push(e.slice(l)),o.join("")}function zo(e){const t=[];let n=0;for(const r of e.matchAll(ho))t.push(Io(e.slice(n,r.index))),t.push(r[0]),n=r.index+r[0].length;return t.push(Io(e.slice(n))),t.join("")}const Ro={note:"md-callout-info",tip:"md-callout-info",warning:"md-callout-attention",important:"md-callout-attention",caution:"md-callout-destructive"},jo={note:"Note",tip:"Tip",warning:"Warning",important:"Important",caution:"Caution"};function Po(){return e=>{Zr(e,e=>{if("containerDirective"!==e.type&&"leafDirective"!==e.type&&"textDirective"!==e.type)return;const t=e;t.data||(t.data={});const n=t.data,r=t.attributes||{},a=t.name;if("pagebreak"===a)return n.hName="hr",void(n.hProperties={className:"md-pagebreak"});if("columns"===a)return n.hName="div",void(n.hProperties={className:"md-columns"});if("column"===a){n.hName="div";const e={className:"md-column"};return r.width&&(e.style=`flex-basis:${r.width};flex-grow:0;flex-shrink:0`),void(n.hProperties=e)}if(a in Ro){n.hName="div",n.hProperties={className:`md-callout ${Ro[a]}`,"data-callout-type":a};const e=jo[a];if(e&&t.children){const n={type:"paragraph",data:{hName:"p",hProperties:{className:"md-callout-title"}},children:[{type:"text",value:e}]};t.children.unshift(n)}return}n.hName="div",n.hProperties={className:`md-${a}`,...Object.fromEntries(Object.entries(r).filter(([e])=>"class"!==e))},r.class&&(n.hProperties.className+=` ${r.class}`)})}}const Ao=["artifact:","image:","store:","document:","document://","collection:"];function Do(e){return Ao.some(t=>e.startsWith(t))?e:Br(e)}function Eo(){return e=>{Zr(e,"html",(e,t,n)=>{const r=e,a=n;if("string"==typeof r.value&&/<!--[\s\S]*?-->/.test(r.value)&&a?.children&&"number"==typeof t)return a.children.splice(t,1),[Xr,t]})}}const $o={chart:Wi,"vega-lite":Ui,vegalite:Ui,mermaid:Bi,mockup:Vi,svg:Vi};function Lo({children:t,components:n,remarkPlugins:r=[],removeComments:a=!0,artifactRunId:s,className:i,codeClassName:o,inlineCodeClassName:l,linkClassName:c,imageClassName:d,onProposalSelect:u,onProposalSubmit:m}){const p=We(_i),h=Fe.useMemo(()=>{return e=function(e){if(!e||!no.some(t=>e.includes(t)))return e;let t="",n=0;for(const r of e.matchAll(so))t+=co(e.slice(n,r.index)),t+=r[0],n=r.index+r[0].length;return t+=co(e.slice(n)),t}(function(e){if(!e?.includes("$"))return e;const t=[];let n=0;for(const r of e.matchAll(po))t.push(zo(e.slice(n,r.index))),t.push(r[0]),n=r.index+r[0].length;return t.push(zo(e.slice(n))),t.join("")}(t)),e?.includes(":::")?e.replace(uo,(e,t,n)=>{const r=n.trim(),a=mo.exec(r);if(!a)return e;const s=a[0],i=r.slice(s.length).trim();return i?`${t}:::${s}\n${t}${i}\n${t}:::`:`${t}::${s}`}):e;var e},[t]),f=Fe.useMemo(()=>{const e=[Jr,Gr,Po,Kr,qr,Yr,Qr,...r];return a&&e.push(Eo),e},[r,a]),g=Fe.useMemo(()=>[Vr],[]),v=Fe.useMemo(()=>({handlers:{...Hr}}),[]),b=Fe.useMemo(()=>{const t=n||{},r=t.code,a=t.a,i=t.img;return{...t,code:({node:t,className:n,children:a,...s})=>{const i=/language-([\w-]+)/.exec(n||""),c=!i,d=i?i[1]:"";if(!c&&d){if(p){const t=p.getComponent(d);if(t){const n=String(a||"").trim();return e(t,{code:n,language:d})}}if(function(e){return e?.startsWith("expand")??!1}(d)){const t=String(a||"").trim();return e(qi,{code:t,language:d})}const t=$o[d];if(t){const n=String(a||"").trim();return e(t,{code:n,language:d})}}if("function"==typeof r)return e(r,{node:t,className:n,...s,children:a});return e("code",{...s,className:c?`px-1.5 py-0.5 rounded ${l||""}`:` ${o||""}`,children:a})},a:t=>{const{node:n,href:r,children:i,...o}=t;return e(eo,{node:n,href:r,className:c,artifactRunId:s,ExistingLink:"function"==typeof a?a:void 0,...o,children:i})},img:t=>{const{node:n,src:r,alt:a,title:o,...l}=t;return o?e(Qi,{src:r,alt:a,caption:o,className:d,artifactRunId:s}):e(Zi,{node:n,src:r,alt:a,className:d,artifactRunId:s,ExistingImg:"function"==typeof i?i:void 0,...l})}}},[n,s,p,o,l,c,d]),x=e(ki,{artifactRunId:s,onProposalSelect:u,onProposalSubmit:m,MarkdownRenderer:Lo,children:e(Wr,{remarkPlugins:f,rehypePlugins:g,remarkRehypeOptions:v,components:b,urlTransform:Do,children:h})});return e("div",i?{className:`md-content ${i}`,children:x}:{className:"md-content",children:x})}const Fo={default:{border:"border-s-attention",bg:"bg-amber-50 dark:bg-amber-900/20",icon:"text-attention"},warning:{border:"border-s-destructive",bg:"bg-red-50 dark:bg-red-900/20",icon:"text-destructive"},info:{border:"border-s-info",bg:"bg-blue-50 dark:bg-blue-900/20",icon:"text-info"},success:{border:"border-s-success",bg:"bg-green-50 dark:bg-green-900/20",icon:"text-success"}},Mo={default:Pt,warning:jt,info:Tt,success:Rt};function Oo({question:a,description:s,options:o,onSelect:l,onMultiSelect:c,onSubmit:d,allowFreeResponse:u=!1,multiSelect:m=!1,placeholder:p,submitLabel:h,isLoading:f=!1,icon:g,variant:v="default",hideIcon:b=!1,hideBorder:x=!1,compact:y=!1,answered:w=!1,className:N,cardClassName:k,headerClassName:C,iconClassName:_,questionClassName:S,descriptionClassName:T,optionsClassName:I,buttonClassName:z,inputContainerClassName:R,inputClassName:j,submitButtonClassName:P}){const{t:A}=Ze(),D=p??A("agent.typeYourResponse"),E=h??A("agent.send"),[$,L]=Fe.useState(""),[F,M]=Fe.useState(new Set),O=Fe.useRef(null),U=Fo[v],W=Mo[v],B=e=>{M(t=>{const n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},V=()=>{F.size>0&&c&&(c(Array.from(F)),M(new Set))},q=()=>{$.trim()&&d&&(d($.trim()),L(""))},H=e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),q())},G=x?"":`border-s-4 ${U.border}`;if(y){const c=g||e(W,{className:"size-4"}),d=e("div",{className:i("agent-ask-question text-sm leading-6 text-foreground/85",S),children:e(Lo,{children:a})});return w?t("div",{className:i("my-1.5 font-sans",N),children:[d,s&&e("p",{className:i("mt-1 text-xs leading-5 text-muted",T),children:s})]}):e("div",{className:i("my-2 font-sans",N),children:t("div",{className:i("rounded-lg border border-border bg-background/60 shadow-none",k),children:[e("div",{className:i("px-3 py-2",C),children:t("div",{className:"flex items-start gap-2.5",children:[!b&&e("div",{className:i("mt-1 flex-shrink-0 text-attention",_),children:c}),t("div",{className:"min-w-0 flex-1",children:[d,s&&e("p",{className:i("mt-1 text-xs leading-5 text-muted",T),children:s})]})]})}),o&&o.length>0&&e("div",{className:i("flex flex-col gap-1.5 px-3 pb-3 pt-0",I),children:m?t(n,{children:[o.map(n=>{const r=F.has(n.id);return t("label",{className:i("flex cursor-pointer items-start gap-2.5 rounded-md border px-3 py-2 text-start transition-colors",r?"border-info/60 bg-info/10":"border-border bg-background/70 hover:bg-mixer-muted/15",f&&"cursor-not-allowed opacity-50",z),children:[e("input",{type:"checkbox",checked:r,onChange:()=>B(n.id),disabled:f,className:"mt-1 size-4 rounded border-border bg-background text-info focus:ring-info"}),t("span",{className:"min-w-0 flex-1",children:[t("span",{className:"flex items-center gap-2 text-sm font-medium leading-5 text-foreground",children:[n.icon,e("span",{className:"break-words",children:n.label})]}),n.description&&e("span",{className:"mt-0.5 block break-words text-xs leading-5 text-muted",children:n.description})]})]},n.id)}),e("div",{className:"pt-1",children:t(r,{size:"sm",onClick:V,disabled:f||0===F.size,className:"inline-flex items-center gap-2",children:[e(At,{className:"size-4"}),F.size>0?A("agent.submitSelectionCount",{count:F.size}):A("agent.submitSelection")]})})]}):o.map(n=>t("button",{type:"button",onClick:()=>l?.(n.id),disabled:f,className:i("flex w-full cursor-pointer items-start gap-2.5 rounded-md border border-border bg-background/70 px-3 py-2 text-start transition-colors","hover:bg-mixer-muted/15 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",f&&"cursor-not-allowed opacity-50",z),children:[e("span",{className:"mt-1 size-4 flex-shrink-0 rounded-full border border-border","aria-hidden":"true"}),t("span",{className:"min-w-0 flex-1",children:[t("span",{className:"flex items-center gap-2 text-sm font-medium leading-5 text-foreground",children:[n.icon,e("span",{className:"break-words",children:n.label})]}),n.description&&e("span",{className:"mt-0.5 block break-words text-xs leading-5 text-muted",children:n.description})]})]},n.id))}),u&&e("div",{className:i("px-3 pb-3 pt-0",R),children:t("div",{className:"flex gap-2",children:[e("input",{ref:O,type:"text",value:$,onChange:e=>L(e.target.value),onKeyDown:H,placeholder:D,disabled:f,className:i("min-w-0 flex-1 rounded-md border border-border bg-background/70 px-3 py-2 text-sm text-foreground focus:border-transparent focus:ring-2 focus:ring-ring",j)}),e(r,{size:"sm",onClick:q,disabled:f||!$.trim(),className:P,children:f?"...":E})]})})]})})}return e("div",{className:`my-4 font-sans ${N||""}`,children:t("div",{className:`${G} ${U.bg} rounded-e-lg shadow-sm ${k||""}`,children:[e("div",{className:`px-4 py-3 ${C||""}`,children:t("div",{className:"flex items-start gap-3",children:[!b&&e("div",{className:`flex-shrink-0 mt-0.5 ${U.icon} ${_||""}`,children:g||e(W,{className:"size-5"})}),t("div",{className:"flex-1 min-w-0",children:[e("div",{className:`prose prose-sm dark:prose-invert max-w-none text-gray-900 dark:text-gray-100 ${S||""}`,children:e(Lo,{children:a})}),s&&e("p",{className:`mt-1 text-sm text-gray-600 dark:text-gray-400 ${T||""}`,children:s})]})]})}),o&&o.length>0&&e("div",{className:`px-4 pb-3 pt-1 ${I||""}`,children:m?t("div",{className:"space-y-2",children:[o.map(n=>t("label",{className:`flex items-start gap-3 px-4 py-3 rounded-lg cursor-pointer transition-colors\n ${F.has(n.id)?"bg-blue-50 dark:bg-blue-900/30 border border-blue-300 dark:border-blue-700":"bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700"}\n ${f?"opacity-50 cursor-not-allowed":""}`,children:[e("input",{type:"checkbox",checked:F.has(n.id),onChange:()=>B(n.id),disabled:f,className:"mt-0.5 w-4 h-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500 dark:border-gray-600 dark:bg-gray-700"}),t("div",{className:"flex-1 overflow-hidden",children:[t("div",{className:"flex items-center gap-2 text-sm font-medium text-gray-900 dark:text-gray-100 break-words",children:[n.icon,e("span",{className:"break-words",children:n.label})]}),n.description&&e("div",{className:"mt-1 text-sm text-gray-500 dark:text-gray-400 break-words whitespace-pre-wrap",children:n.description})]})]},n.id)),e("div",{className:"pt-2",children:t(r,{size:"sm",onClick:V,disabled:f||0===F.size,className:"flex items-center gap-2",children:[e(At,{className:"size-4"}),F.size>0?A("agent.submitSelectionCount",{count:F.size}):A("agent.submitSelection")]})})]}):e("div",{className:"flex flex-col gap-2 w-full",children:o.map(n=>e(r,{variant:"unstyled",onClick:()=>l?.(n.id),disabled:f,className:`w-full h-auto whitespace-normal text-start px-4 py-3 rounded-lg border border-gray-200 dark:border-gray-700\n bg-white dark:bg-gray-800\n hover:bg-gray-50 dark:hover:bg-gray-700 hover:border-gray-300 dark:hover:border-gray-600\n focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-1\n transition-colors\n ${f?"opacity-50 cursor-not-allowed":"cursor-pointer"}\n ${z||""}`,children:t("div",{className:"flex items-start gap-3",children:[n.icon&&e("span",{className:"flex-shrink-0 mt-0.5 text-gray-500 dark:text-gray-400",children:n.icon}),t("div",{className:"flex-1 overflow-hidden",children:[e("div",{className:"font-medium text-sm text-gray-900 dark:text-gray-100 break-words text-center",children:n.label}),n.description&&e("div",{className:"mt-1 text-sm text-gray-500 dark:text-gray-400 break-words whitespace-pre-wrap",children:n.description})]})]})},n.id))})}),u&&e("div",{className:`px-4 pb-3 pt-1 ${R||""}`,children:t("div",{className:"flex gap-2",children:[e("input",{ref:O,type:"text",value:$,onChange:e=>L(e.target.value),onKeyDown:H,placeholder:D,disabled:f,className:`flex-1 px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-800 focus:ring-2 focus:ring-blue-500 focus:border-transparent ${j||""}`}),e(r,{size:"sm",onClick:q,disabled:f||!$.trim(),className:P,children:f?"...":E})]})})]})})}function Uo({question:t,description:n,onConfirm:r,onCancel:a,confirmLabel:s,cancelLabel:i,isLoading:o=!1,variant:l="default",className:c}){const{t:d}=Ze(),u=s??d("agent.yes"),m=i??d("agent.no");return e(Oo,{question:t,description:n,variant:l,isLoading:o,className:c,options:[{id:"confirm",label:u,icon:e(Rt,{className:"size-4"})},{id:"cancel",label:m,icon:e(Dt,{className:"size-4"})}],onSelect:e=>{"confirm"===e?r():a()}})}function Wo(e){const t=e.replace(/^workstream[:_-]?/i,"").replace(/^sys:/i,"").replace(/[-_:]?[0-9a-f]{8}-[0-9a-f-]{12,}$/i,"").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").replace(/[:_-]+/g," ").trim();return t?t.split(/\s+/).map(e=>{const t=e.toLowerCase();return"qa"===t?"QA":"ui"===t?"UI":"api"===t?"API":"url"===t?"URL":t.charAt(0).toUpperCase()+t.slice(1)}).join(" "):e}function Bo(e,t){const n=t?Wo(t):"",r=Wo(e);if(!n)return r;if(function(e){return/[0-9a-f]{8}-[0-9a-f-]{12,}/i.test(e)}(e))return n;const a=n.toLowerCase().replace(/\s+/g,"");return r.toLowerCase().replace(/\s+/g,"").startsWith(a)?n:r}function Vo(e){if("string"!=typeof e)return!1;const t=e.trim().toLowerCase();return Boolean(t&&"main"!==t&&"all"!==t)}function qo(e,t){return Vo(t)&&function(e){const t=e.trim();if(!t||!/^[{[]/.test(t))return!1;try{return JSON.parse(t),!0}catch{return!1}}(e)}function Ho(e){if(!qo(function(e){return e.message?"object"==typeof e.message?JSON.stringify(e.message,null,2):String(e.message).trim():""}(e),e.workstream_id))return!1;if(e.type!==ir.ANSWER&&e.type!==ir.COMPLETE)return!1;const t=e.details?.event_class;return"user_content"===t||!0===e.details?.streamed}function Go(e){switch(e){case"running":return"bg-info";case"canceling":return"bg-attention";case"completed":return"bg-success";case"canceled":case"failed":case"timeout":return"bg-destructive"}}function Jo(e){const t=e.details;if("launched"!==t?.workstream_event)return null;const n="string"==typeof t.workstream_id?t.workstream_id:"string"==typeof e.workstream_id?e.workstream_id:"";return n&&"main"!==n&&"all"!==n?{workstreamId:n,launchId:"string"==typeof t.launch_id?t.launch_id:void 0,kind:"string"==typeof t.kind?t.kind:void 0,interaction:"string"==typeof t.interaction?t.interaction:void 0,childWorkflowId:"string"==typeof t.child_workflow_id?t.child_workflow_id:void 0,childWorkflowRunId:"string"==typeof t.child_workflow_run_id?t.child_workflow_run_id:void 0}:null}function Ko(e){const t=e.details;if("activity"!==t?.event_class)return null;if(void 0!==t.workstream_event)return null;if(e.type===ir.ERROR)return null;const n="string"==typeof t.child_workflow_id?t.child_workflow_id:void 0,r="string"==typeof t.child_workflow_run_id?t.child_workflow_run_id:void 0;if(!n&&!r)return null;const a="string"==typeof t.workstream_id&&t.workstream_id.trim()?t.workstream_id:"string"==typeof e.workstream_id?e.workstream_id:"";return Vo(a)?{workstreamId:a,launchId:"string"==typeof t.launch_id?t.launch_id:void 0,kind:"string"==typeof t.kind?t.kind:void 0,interaction:"string"==typeof t.interaction?t.interaction:void 0,childWorkflowId:n,childWorkflowRunId:r}:null}function Qo(){if("undefined"==typeof window)return!1;const e=new URLSearchParams(window.location.search).get("agentChatDebug"),t=function(e){const t=e.indexOf("?");return-1===t?null:new URLSearchParams(e.slice(t+1)).get("agentChatDebug")}(window.location.hash),n=e??t;if(null!==n)return"1"===n||"true"===n;try{const e=window.localStorage.getItem("agentChatDebug");return"1"===e||"true"===e}catch{return!1}}function Yo(e,t){Qo()&&console.debug(`[agent-chat] ${e}`,t??{})}function Zo(e,t){const n="number"==typeof t.timestamp?t.timestamp:new Date(t.timestamp).getTime(),r=e.findIndex(e=>("number"==typeof e.timestamp?e.timestamp:new Date(e.timestamp).getTime())>n);-1===r?e.push(t):e.splice(r,0,t)}const Xo=[ir.COMPLETE,ir.IDLE,ir.REQUEST_INPUT,ir.TERMINATED];function el(e){if(!e.length)return!0;const t=e.filter(e=>{return t=e,!(t.details?._optimistic&&"failed"===t.details?._deliveryStatus&&Xo.includes(t.type));var t}),n=t.filter(e=>"main"===rl(e));if(0===n.length){const e=t[t.length-1];return!e||!Xo.includes(e.type)}const r=n[n.length-1];return!Xo.includes(r.type)}function tl(e){if(e.type!==ir.IDLE)return!1;const t=e.details?.status_reason,n=e.details?.display_role;return"user_stopped"===t||"user_stopped"===n||String(e.message??"").trim().toLowerCase().startsWith("stopped.")}function nl(e){return"number"==typeof e?e:new Date(e).getTime()}function rl(e){return e.workstream_id?e.workstream_id:"main"}function al(e){if("main"===rl(e))return!0;if(Jo(e)||Ko(e))return!0;const t=function(e){const t=e.details;return!t||"object"!=typeof t||Array.isArray(t)?{}:t}(e),n="string"==typeof t.child_workflow_id||"string"==typeof t.child_workflow_run_id,r="string"==typeof t.tool||"string"==typeof t.tool_run_id;return!("activity"!==t.event_class||e.type!==ir.ERROR&&e.type!==ir.WARNING||n||r)}function sl(e,t){return"all"===t?e.filter(al):e.filter(e=>{const n=Jo(e)??Ko(e);return n?.workstreamId!==t&&rl(e)===t})}async function il(e,t){return e.agents.getArtifactUrl(t,"conversation.json").then(e=>e.url)}function ol(e){if("string"!=typeof e)return;return e.replace(/\r\n/g,"\n").trim()||void 0}function ll(e){return ol(e.message)}function cl(e,t){const n=ol(e.text);if(!n)return!1;const r=e.workstreamId||"main";return t.some(t=>{if(nl(t.timestamp)<e.startTimestamp)return!1;if(rl(t)!==r)return!1;const a="string"==typeof t.details?.streaming_id?t.details.streaming_id:void 0;return e.streamingId&&a?a===e.streamingId&&("thinking"!==t.details?.display_role&&(!ul(t)&&!t.details?.tool_status)):e.activityId&&t.details?.activity_id===e.activityId?"thinking"!==t.details?.display_role&&(!ul(t)&&!t.details?.tool_status):(t.type===ir.THOUGHT||t.type===ir.ANSWER||t.type===ir.COMPLETE||t.type===ir.IDLE)&&(!!t.details?.streamed&&ll(t)===n)})}function dl(e,t){if(rl(e)!==rl(t))return!1;const n=ll(e),r=ll(t);if(!n||n!==r)return!1;const a=nl(e.timestamp);return!(nl(t.timestamp)-a>1e4)&&(e.type===ir.ANSWER&&(t.type===ir.COMPLETE||t.type===ir.IDLE)||(!(e.type!==ir.THOUGHT||t.type!==ir.ANSWER&&t.type!==ir.COMPLETE&&t.type!==ir.IDLE||!e.details?.streamed&&!t.details?.streamed)||!(e.type!==t.type||!e.details?.streamed&&!t.details?.streamed||t.type!==ir.THOUGHT&&t.type!==ir.ANSWER&&t.type!==ir.COMPLETE&&t.type!==ir.IDLE)))}function ul(e){return e.type===ir.THOUGHT&&!!e.details?.tool}function ml(e){const t=e.details;return e.type===ir.THOUGHT&&("tool_preamble"===t?.display_role||"think"===t?.tool)}function pl(e){if(ml(e))return!1;if(ul(e))return!0;if(e.type!==ir.THOUGHT)return!1;const t=e.details;return!!(Array.isArray(t?.tools)&&t.tools.length>0)}function hl(e){return e.details?.tool_run_id}function fl(e){return e.details?.tool_iteration}function gl(e){return e.details?.tool_status}function vl(e){const t=e.details?.activity_group_id;if("string"==typeof t&&""!==t.trim())return t}function bl(e,t){return t??e}function xl(e){return e.message?"object"==typeof e.message?JSON.stringify(e.message,null,2):String(e.message).trim():""}function yl(e){const t=wl(e.details?.tool_approval);if(!t)return xl(e);const n=Nl(t.tool_title)??Nl(t.tool_name),r=function(e){if(!e)return;const t=e.indexOf(":");if(t<0)return e;const n=e.slice(0,t),r=e.slice(t+1).trim();if(!r)return e;switch(n){case"document_id":return`document ${r}`;case"object_id":return`object ${r}`;case"collection_id":return`collection ${r}`;case"process_id":return`process ${r}`;case"process_definition_id":return`process definition ${r}`;case"interaction_id":return`interaction ${r}`;case"prompt_id":return`prompt ${r}`;case"dashboard_id":return`dashboard ${r}`;case"database_id":return`database ${r}`;case"table_id":return`table ${r}`;default:return r}}(Nl(t.target));if(n&&r)return`Approve ${n}: ${r}?`;const a=Nl(t.action_summary);return a?`Approve ${function(e){return e.replace(/:\s*name(?::|\s+)/i,": ")}(a)}?`:xl(e)}function wl(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:void 0}function Nl(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function kl(e){const t=e.details;return e.type===ir.REQUEST_INPUT&&!!t?.ux}function Cl(e){const t=e.details;return[t?.request_id,t?.requestId,t?.activity_id,t?.activityId,t?.tool_run_id,t?.toolRunId,e.timestamp,xl(e)].filter(e=>"string"==typeof e||"number"==typeof e).map(String).join("|")}function _l(e){const t=e.details;return[t?.ack,t?._messageId,t?._deliveryStatus,e.timestamp,rl(e),xl(e)].filter(e=>"string"==typeof e||"number"==typeof e).map(String).join("|")}function Sl(e){const t=new Set;return e.forEach((n,r)=>{if(n.type!==ir.REQUEST_INPUT)return;const a=rl(n);for(let s=r+1;s<e.length;s+=1){const r=e[s];if(rl(r)===a){if(r.type===ir.REQUEST_INPUT)break;if(r.type===ir.QUESTION){t.add(Cl(n));break}}}}),t}function Tl(e){const t=new Set;for(const n of e){const e=wl(n.details),r=wl(e?.approval_request),a=r?.approval_key,s=e?.approval_decision;"string"!=typeof a||"denied"!==s&&"denied_with_feedback"!==s&&"timeout"!==s&&"reviewer_denied"!==s&&"cancelled_after_denial"!==s||t.add(a)}return t}function Il(e){const t=wl(e.details),n=wl(t?.tool_approval),r=n?.approval_key;return"string"==typeof r?r:void 0}function zl(e){return e.type===ir.REQUEST_INPUT&&void 0!==Il(e)}function Rl(e){if(e.type!==ir.QUESTION)return!1;const t=xl(e).trim().toLowerCase();return"allow_once"===t||"allow_for_run"===t||"deny"===t}function jl(e){return Rl(e)||function(e){if(e.type!==ir.QUESTION)return!1;const t=wl(e.details),n=wl(t?.metadata),r=wl(t?.tool_approval_response)??wl(n?.tool_approval_response);return"deny_with_feedback"===r?.decision}(e)}function Pl(e,t){if(e.type!==ir.REQUEST_INPUT)return!1;const n=Il(e);return!!n&&t.has(n)}function Al(e,t,n){return zl(e)&&(t.has(Cl(e))||Pl(e,n))}function Dl(e,t){return e.type===ir.QUESTION&&t.has(_l(e))}function El(e,t){return e.type===ir.REQUEST_INPUT&&t.has(Cl(e))}function $l(e,t="main"){const n=Sl(e),r=Tl(e);for(let a=e.length-1;a>=0;a-=1){const s=e[a];if(kl(s)&&(rl(s)===t&&!El(s,n)&&!Pl(s,r)))return s}}function Ll({mcpConnect:n,onMcpConnected:a,onDecline:s,disabled:i}){const{client:o}=tr(),{t:l}=Ze();return t("div",{className:"flex shrink-0 items-center justify-end gap-2",children:[e(wi,{appId:n.app_install_id,collectionId:n.collection_id,collectionName:n.name,variant:"default",onAuthChange:()=>{o.remoteMcpConnections.getCollectionStatus(n.app_install_id,n.collection_id).then(e=>{e.authenticated&&a?.(n)}).catch(()=>{})},readOnly:i}),t(r,{variant:"ghost",size:"sm",onClick:s,disabled:i,children:[e(Et,{className:"size-4"}),e("span",{children:l("mcpOAuth.decline")})]})]})}function Fl({message:n,onSendMessage:r,onMcpConnected:a,isLoading:s=!1,disabled:o=!1,className:l}){const{t:c}=Ze();if(!n)return null;const d=n.details.ux,u=d.options??[],m=d.mcp_connect,p=d.free_response,h=o||s||!r,f=yl(n),g=(e,t)=>{h||(t?r?.(e,t):r?.(e))},v=i("flex-shrink-0 border-t border-border/70 bg-background/95 backdrop-blur","fixed bottom-0 end-0 start-0 z-20 lg:sticky lg:start-auto lg:end-auto","pb-safe-area",l);return e("div",m?{className:v,"data-agent-request-input-overlay":!0,children:t("div",{className:"mx-auto flex w-full max-w-3xl flex-col gap-3 px-3 py-3 sm:flex-row sm:items-center sm:justify-between",children:[e("div",{className:"min-w-0 text-sm leading-6 text-foreground/85",children:f}),e(Ll,{mcpConnect:m,onMcpConnected:a,onDecline:()=>g(c("agent.mcpDeclinedMessage",{name:m.name})),disabled:h})]})}:{className:v,"data-agent-request-input-overlay":!0,children:e("div",{className:"mx-auto w-full max-w-3xl px-3 py-3",children:e(Oo,{question:f,options:u,variant:d.variant,multiSelect:d.multiSelect,allowFreeResponse:0===u.length||!!p,placeholder:p?.placeholder,submitLabel:p?.submit_label,onSelect:g,onMultiSelect:e=>g(e.join(", ")),onSubmit:e=>g(e,p?.metadata),hideBorder:!0,compact:!0,isLoading:h,className:"my-0",cardClassName:"bg-background/80 shadow-lg shadow-black/5 dark:shadow-none"})})})}function Ml({className:n,inline:r=!1,color:a="blue"}){const s={blue:"from-blue-400 to-indigo-500 dark:from-blue-500 dark:to-indigo-400",purple:"from-purple-400 to-violet-500 dark:from-purple-500 dark:to-violet-400",teal:"from-teal-400 to-emerald-500 dark:from-teal-500 dark:to-emerald-400",green:"from-green-400 to-emerald-500 dark:from-green-500 dark:to-emerald-400",amber:"from-amber-400 to-orange-500 dark:from-amber-500 dark:to-orange-400"}[a];return t("div",{className:i("flex items-center gap-1.5",r?"inline-flex":"",n),children:[e("div",{className:`w-2 h-2 bg-gradient-to-r ${s} rounded-full animate-[bounce_1.2s_ease-in-out_infinite]`}),e("div",{className:`w-2 h-2 bg-gradient-to-r ${s} rounded-full animate-[bounce_1.2s_ease-in-out_0.2s_infinite]`}),e("div",{className:`w-2 h-2 bg-gradient-to-r ${s} rounded-full animate-[bounce_1.2s_ease-in-out_0.4s_infinite]`})]})}function Ol({className:n,size:r="md",color:a="blue"}){const s={blue:"bg-blue-500 dark:bg-blue-400",purple:"bg-purple-500 dark:bg-purple-400",teal:"bg-teal-500 dark:bg-teal-400",green:"bg-green-500 dark:bg-green-400",amber:"bg-amber-500 dark:bg-amber-400"};return t("span",{className:i("relative flex",n),children:[e("span",{className:i("animate-ping absolute inline-flex h-full w-full rounded-full opacity-60",s[a])}),e("span",{className:i("animate-pulse absolute inline-flex h-[80%] w-[80%] rounded-full opacity-80",s[a]),style:{left:"10%",top:"10%",animationDuration:"2s"}}),e("span",{className:i("relative inline-flex rounded-full",s[a],{sm:"w-3 h-3",md:"w-5 h-5",lg:"w-7 h-7"}[r])})]})}function Ul({className:t,color:n="blue"}){const[r,a]=Oe(".");return He(()=>{const e=setInterval(()=>{a(e=>"."===e?"..":".."===e?"...":".")},500);return()=>clearInterval(e)},[]),e("span",{className:i({blue:"text-blue-600 dark:text-blue-400",purple:"text-purple-600 dark:text-purple-400",teal:"text-teal-600 dark:text-teal-400",green:"text-green-600 dark:text-green-400",amber:"text-amber-600 dark:text-amber-400"}[n],"font-bold",t),children:r})}function Wl({message:n,className:r,color:a="blue"}){const s={blue:{dot:"bg-blue-500 dark:bg-blue-400",text:"text-blue-700 dark:text-blue-300"},purple:{dot:"bg-purple-500 dark:bg-purple-400",text:"text-purple-700 dark:text-purple-300"},teal:{dot:"bg-teal-500 dark:bg-teal-400",text:"text-teal-700 dark:text-teal-300"},green:{dot:"bg-green-500 dark:bg-green-400",text:"text-green-700 dark:text-green-300"},amber:{dot:"bg-amber-500 dark:bg-amber-400",text:"text-amber-700 dark:text-amber-300"}};return t("div",{className:i("flex items-center gap-2 py-1",r),children:[t("div",{className:"flex gap-1",children:[e("div",{className:`w-1.5 h-1.5 ${s[a].dot} rounded-full animate-bounce`}),e("div",{className:`w-1.5 h-1.5 ${s[a].dot} rounded-full animate-bounce`,style:{animationDelay:"0.2s"}}),e("div",{className:`w-1.5 h-1.5 ${s[a].dot} rounded-full animate-bounce`,style:{animationDelay:"0.4s"}})]}),e("div",{className:`${s[a].text} font-medium text-xs`,children:n})]})}function Bl({className:n,color:r="blue",width:a="md",message:s}){const[o,l]=Oe(15),[c,d]=Oe("increasing"),[u,m]=Oe(.4),p=Be(null),h=Be(!0);He(()=>{const e=p.current;if(!e)return;const t=new IntersectionObserver(([e])=>{h.current=e.isIntersecting},{threshold:0});return t.observe(e),()=>t.disconnect()},[]);return He(()=>{let e,t=Date.now();const n=()=>{if(!h.current)return void(e=requestAnimationFrame(n));const r=Date.now(),a=r-t;t=r,l(e=>{const t=u*(a/16),n="increasing"===c?e+t:e-t;return n>=85?(d("decreasing"),m(.3+.2*Math.random()),85):n<=15?(d("increasing"),m(.3+.2*Math.random()),15):(Math.random()>.99&&m(e=>Math.max(.2,Math.min(.5,e+(.1*Math.random()-.05)))),n)}),e=requestAnimationFrame(n)};return e=requestAnimationFrame(n),()=>{cancelAnimationFrame(e)}},[c,u]),t("div",{ref:p,className:i("flex flex-col gap-1",n),children:[s&&e("div",{className:`text-xs font-medium ${{blue:"text-blue-700 dark:text-blue-300",purple:"text-purple-700 dark:text-purple-300",teal:"text-teal-700 dark:text-teal-300",green:"text-green-700 dark:text-green-300",amber:"text-amber-700 dark:text-amber-300"}[r]} mb-1`,children:s}),e("div",{className:i("h-1.5 rounded-full overflow-hidden shadow-inner",{blue:"bg-blue-200 dark:bg-blue-900/30",purple:"bg-purple-200 dark:bg-purple-900/30",teal:"bg-teal-200 dark:bg-teal-900/30",green:"bg-green-200 dark:bg-green-900/30",amber:"bg-amber-200 dark:bg-amber-900/30"}[r],{sm:"w-24",md:"w-32",lg:"w-48",xl:"w-64",full:"w-full"}[a]),children:e("div",{className:i("h-full rounded-full",{blue:"bg-gradient-to-r from-blue-400 to-blue-500 dark:from-blue-500 dark:to-blue-400",purple:"bg-gradient-to-r from-purple-400 to-purple-500 dark:from-purple-500 dark:to-purple-400",teal:"bg-gradient-to-r from-teal-400 to-teal-500 dark:from-teal-500 dark:to-teal-400",green:"bg-gradient-to-r from-green-400 to-green-500 dark:from-green-500 dark:to-green-400",amber:"bg-gradient-to-r from-amber-400 to-amber-500 dark:from-amber-500 dark:to-amber-400"}[r]),style:{width:`${o}%`,transition:"width 150ms cubic-bezier(0.4, 0.0, 0.2, 1)"}})})]})}function Vl({className:t,color:n="blue",size:r="md"}){const[a,s]=Oe(Array(7).fill(50)),o=Be(null),l=Be(!0);He(()=>{const e=o.current;if(!e)return;const t=new IntersectionObserver(([e])=>{l.current=e.isIntersecting},{threshold:0});return t.observe(e),()=>t.disconnect()},[]);const c={sm:{width:"w-16",height:"h-4",barWidth:"w-0.5",gap:"gap-[2px]"},md:{width:"w-20",height:"h-5",barWidth:"w-1",gap:"gap-[3px]"},lg:{width:"w-24",height:"h-6",barWidth:"w-1.5",gap:"gap-1"}},d={blue:"bg-gradient-to-b from-blue-400 to-blue-500 dark:from-blue-400 dark:to-blue-500",purple:"bg-gradient-to-b from-purple-400 to-purple-500 dark:from-purple-400 dark:to-purple-500",teal:"bg-gradient-to-b from-teal-400 to-teal-500 dark:from-teal-400 dark:to-teal-500",green:"bg-gradient-to-b from-green-400 to-green-500 dark:from-green-400 dark:to-green-500",amber:"bg-gradient-to-b from-amber-400 to-amber-500 dark:from-amber-400 dark:to-amber-500"};return He(()=>{let e;const t=[1.2,1,1.5,.8,1.3,.9,1.1],n=[0,.5,1,1.5,2,2.5,3];let r=0;const a=()=>{if(!l.current)return void(e=requestAnimationFrame(a));r+=.02;const i=Array(7).fill(0).map((e,a)=>10+40*(Math.sin(r*t[a]+n[a])+1));s(i),e=requestAnimationFrame(a)};return e=requestAnimationFrame(a),()=>{cancelAnimationFrame(e)}},[]),e("div",{ref:o,className:i("flex items-end justify-center",c[r].width,c[r].height,c[r].gap,t),children:a.map((t,a)=>e("div",{className:i(c[r].barWidth,"rounded-full transform-gpu",d[n]),style:{height:`${t}%`,transition:"height 100ms cubic-bezier(0.4, 0.0, 0.2, 1)",opacity:.9}},a))})}const ql=["Brewing some code magic...","Doing the robot dance...","Cooking up something good...","Working my gears...","Parsing the possibilities...","Crunching the numbers...","Connecting the digital dots...","Processing at maximum capacity...","Searching through my circuits...","Running advanced algorithms...","Computing optimal solutions...","Loading brilliance.exe...","Scanning the knowledge base...","Optimizing response protocols...","Having a quick brainstorm...","Thinking cap firmly on...","Pondering the digital universe...","Consulting my silicon wisdom...","Untangling the logic knots...","Assembling clever responses...","Mixing thoughtful ingredients...","Polishing the perfect answer...","Taking a momentary mind sprint...","Connecting virtual synapses...","Baking fresh ideas...","Stirring the thought pot...","Simmering solutions slowly...","Whipping up a smart response...","Adding a dash of intelligence...","Preparing a gourmet answer...","Growing brilliant ideas...","Cultivating the perfect response...","Gathering digital nectar...","Planting seeds of solutions...","Exploring the data landscape...","Mapping the solution path...","Navigating through possibilities...","Charting the course to answers...","Embarking on a thought expedition...","Sketching out concepts...","Painting with digital brushstrokes...","Composing my response symphony...","Crafting precision answers...","Weaving threads of information...","Just a moment of processing...","Taking a quick thinking break...","Almost there, final touches...","Putting the pieces together...","Making progress, hold tight..."],Hl=Ue(null);function Gl(){const e=We(Hl);return e||{openImage:e=>window.open(e,"_blank"),closeImage:()=>{}}}function Jl({children:n}){const[a,s]=Oe(null),i=Ve((e,t)=>{s({src:e,alt:t})},[]),o=Ve(()=>{s(null)},[]),{t:l}=Ze();return t(Hl.Provider,{value:{openImage:i,closeImage:o},children:[n,a&&e("div",{role:"button",tabIndex:-1,"aria-label":l("agent.close"),className:"fixed inset-0 z-[100] flex items-center justify-center bg-black/80 backdrop-blur-sm",onClick:o,onKeyDown:m(o),children:t("div",{className:"relative max-w-[90vw] max-h-[90vh]",children:[e("img",{src:a.src,alt:a.alt||l("agent.enlargedView"),className:"max-w-full max-h-[90vh] object-contain rounded-lg shadow-2xl"}),e(r,{variant:"unstyled",className:"absolute top-2 end-2 text-white bg-black/50 rounded-full p-2 hover:bg-black/70 transition-colors",onClick:o,title:l("agent.close"),"aria-label":l("agent.close"),children:e(ut,{className:"size-6"})}),e("a",{href:a.src,target:"_blank",rel:"noopener noreferrer",className:"absolute bottom-2 end-2 text-white bg-black/50 rounded-full p-2 hover:bg-black/70 transition-colors",onClick:e=>e.stopPropagation(),title:l("agent.openInNewTab"),children:e($t,{className:"size-5"})})]})})]})}const Kl=new Set(["png","jpg","jpeg","gif","webp","bmp","svg"]),Ql=new Set(["css","csv","html","js","json","jsx","log","md","mjs","sql","ts","tsx","txt","xml","yaml","yml"]);function Yl(e){const t=e?.split(/[?#]/)[0]??"";return t.includes(".")?(t.split(".").pop()??"").toLowerCase():""}function Zl({item:t,children:r,StoreLinkComponent:a,CollectionLinkComponent:s}){const i=t.href;if(!i)return e(n,{children:r});if(function(e){return Boolean(e?.includes("/store/objects/")||e?.startsWith("store:")||e?.startsWith("document:"))}(i)){const t=function(e){const t=e.split("/store/objects/")[1];return t?t.split(/[?#]/)[0]:e.replace(/^store:/,"").replace(/^document:(?:\/\/)?/,"").split(/[?#]/)[0]}(i);return a?e(a,{href:i,documentId:t,children:r}):e("a",{href:i.startsWith("store:")||i.startsWith("document:")?`/store/objects/${t}`:i,children:r})}if(function(e){return Boolean(e?.includes("/store/collections/")||e?.startsWith("collection:"))}(i)){const t=function(e){return e.split("/store/collections/")[1]||e.replace(/^collection:/,"")}(i);return s?e(s,{href:i,collectionId:t,children:r}):e("a",{href:i.startsWith("collection:")?`/store/collections/${t}`:i,children:r})}return/^https?:\/\//.test(i)||i.startsWith("/")?e("a",{href:i,target:i.startsWith("/")?void 0:"_blank",rel:"noopener noreferrer",children:r}):e(n,{children:r})}function Xl({item:n,artifactRunId:a,variant:s,onRemove:o,StoreLinkComponent:l,CollectionLinkComponent:c}){const{t:d}=Ze(),u=We(nr),m=Za(),{openImage:p}=Gl(),h=function(e){return e.artifactPath?e.artifactPath:e.href?.startsWith("artifact:")?e.href.slice(9):void 0}(n),f=function(e){return!!e.contentType?.toLowerCase().startsWith("image/")||Kl.has(Yl(e.artifactPath||e.href||e.name))}(n),g=f&&!function(e){const t=e.contentType?.toLowerCase()??"";return!!t.startsWith("text/")||!("application/json"!==t&&!t.includes("xml"))||Ql.has(Yl(e.artifactPath||e.href||e.name))}(n),[v,b]=Oe(n.previewUrl);He(()=>{b(n.previewUrl)},[n.previewUrl]),He(()=>{if(!g||n.previewUrl||!a||!h||!u?.client)return;let e=!1;const t=es(a,h,"inline");return(async()=>{const n=m?await m.getOrFetch(t,async()=>(await u.client.files.getArtifactDownloadUrl(a,h,"inline")).url):(await u.client.files.getArtifactDownloadUrl(a,h,"inline")).url;e||b(n)})().catch(()=>{e||b(void 0)}),()=>{e=!0}},[h,a,n.previewUrl,u?.client,g,m]);const x={attention:"bg-attention/15 text-attention",destructive:"bg-destructive/15 text-destructive",info:"bg-info/15 text-info",muted:"bg-muted text-muted",success:"bg-success/15 text-success"}[n.statusTone??"muted"],y=Boolean(o&&!1!==n.removable),w=e=>{e.stopPropagation(),e.preventDefault(),o?.(n.id)},N=y?e(r,{variant:"unstyled",size:"none","aria-label":d("agent.removeFile",{name:n.name}),onClick:w,className:i("absolute -end-1.5 -top-1.5 inline-flex size-5 items-center justify-center rounded-full","border border-border bg-background text-muted shadow-sm transition-colors hover:text-foreground"),children:e(Et,{className:"size-3","aria-hidden":"true"})}):null,k=y?e(r,{variant:"unstyled",size:"none","aria-label":d("agent.removeFile",{name:n.name}),onClick:w,className:i("-me-1 inline-flex size-6 shrink-0 items-center justify-center rounded-md text-muted","transition-colors hover:bg-mixer-muted/30 hover:text-foreground"),children:e(Et,{className:"size-3.5","aria-hidden":"true"})}):null,C=g&&v?e(r,{type:"button",variant:"unstyled",size:"none",onClick:e=>{e.stopPropagation(),e.preventDefault(),p(v,n.name)},"aria-label":n.name,title:d("agent.enlargedView"),className:i("group shrink-0 overflow-hidden rounded border border-border/60 p-0","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","composer"===s?"size-6":"size-24"),children:e("img",{src:v,alt:n.name,className:"h-full w-full object-cover transition-transform group-hover:scale-[1.05]"})}):e(f?Lt:Ft,{className:"size-3.5 shrink-0 text-muted","aria-hidden":"true"}),_=t("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1.5",children:[C,e("span",{className:i("truncate","composer"===s?"max-w-[14rem]":"max-w-[16rem]"),children:n.name}),n.statusLabel?e("span",{className:i("shrink-0 rounded px-1.5 py-0.5 text-[10px] font-medium",x),children:n.statusLabel}):null]});if("composer"===s)return t("span",{title:n.name,className:i("inline-flex min-h-8 max-w-full items-center gap-1 rounded-xl border border-border/60","bg-mixer-muted/15 px-2.5 py-1 text-sm text-foreground/80 transition-colors",n.href&&"hover:bg-mixer-muted/25"),children:[e(Zl,{item:n,StoreLinkComponent:l,CollectionLinkComponent:c,children:_}),k]});const S=e("span",{title:n.name,className:i("inline-flex max-w-full items-center gap-1.5 rounded-md border border-border/60 bg-mixer-muted/15","px-2.5 py-1.5 text-xs text-foreground/80 transition-colors",n.href&&"hover:bg-mixer-muted/25"),children:_});return t("span",{className:"relative inline-flex max-w-full",children:[e(Zl,{item:n,StoreLinkComponent:l,CollectionLinkComponent:c,children:S}),N]})}function ec({items:t,artifactRunId:n,className:r,align:a="start",variant:s="message",onRemove:o,StoreLinkComponent:l,CollectionLinkComponent:c}){return 0===t.length?null:e("div",{className:i("flex flex-wrap gap-2","end"===a&&"justify-end",r),children:t.map(t=>e(Xl,{item:t,artifactRunId:n,variant:s,onRemove:o,StoreLinkComponent:l,CollectionLinkComponent:c},t.id))})}const tc=/^\s*(?:\*\*)?(attachments|uploaded artifacts):(?:\*\*)?\s*$/i,nc=/^\s*(?:[-*]\s*)?\[([^\]]+)]\(([^)]+)\)(?:\s+\((.*)\))?\s*$/;function rc(e){const t=e.split(/\r?\n/),n=[],r=[];let a=!1;for(const e of t){const t=e.trim();if(tc.test(t)){a=!0;continue}if(!a){n.push(e);continue}if(!t)continue;const s=nc.exec(t);if(!s){a=!1,n.push(e);continue}const[,i,o,l]=s,c=o.startsWith("artifact:")?o.slice(9):void 0;r.push({id:`${o}-${r.length}`,name:i,href:o,artifactPath:c,contentType:l?.toLowerCase().includes("image")?"image/*":void 0})}return{body:n.join("\n").trim(),attachments:r}}const ac=qe(function({message:n,batchData:a,isRunning:s=!1,className:o,headerClassName:l,senderClassName:c,progressBarClassName:d,itemListClassName:u,itemClassName:h,summaryClassName:f}){const[g,v]=Oe(!1),b=p(),{t:x}=Ze(),{tool_name:y,total:w,completed:N,succeeded:k,failed:C,items:_,started_at:S,completed_at:T}=a,I=w>0?N/w*100:0,z=C>0,R=N===w&&!s,j=s||!R?"running":C===w?"error":C>0?"warning":"completed",P=((T?T-S:Date.now()-S)/1e3).toFixed(1);return t("div",{className:i("border-s-4 shadow-md overflow-hidden bg-white dark:bg-gray-900 mb-5","completed"===j?"border-s-success":"error"===j?"border-s-destructive":"warning"===j?"border-s-attention":"border-s-blue-500",o),children:[t("div",{role:"button",tabIndex:0,"aria-expanded":g,className:i("flex items-center justify-between px-4 py-2 border-b border-gray-100/80 dark:border-gray-800/80 bg-blue-50/50 dark:bg-blue-900/10 cursor-pointer",l),onClick:()=>v(!g),onKeyDown:m(()=>v(!g)),children:[t("div",{className:"flex items-center gap-2",children:[s||!R?e(Ol,{size:"sm",color:"blue"}):"completed"===j?e(Rt,{className:"size-4 text-success"}):"error"===j||"warning"===j?e(jt,{className:"size-4 text-destructive"}):e(Ot,{className:"size-4 text-purple-600"}),e("span",{className:i("text-xs font-medium text-muted",c),children:x("agent.batch")}),e("span",{className:"text-xs text-blue-600 dark:text-blue-400 font-medium",children:y}),t("span",{className:"text-xs text-muted",children:[N,"/",w]}),g?e(Mt,{className:"size-3 text-muted"}):e(ht,{className:"size-3 text-muted cn-rtl-flip"})]}),t("div",{className:"flex items-center gap-2",children:[t("span",{className:"text-xs text-muted",children:[P,"s"]}),e("span",{className:"text-xs text-muted",children:Dr(S).format("HH:mm:ss")}),e(r,{variant:"ghost",size:"xs",onClick:e=>{e.stopPropagation(),(()=>{const e=JSON.stringify(a,null,2);navigator.clipboard.writeText(e).then(()=>{b({status:"success",title:x("agent.copiedBatchDetails"),duration:2e3})})})()},className:"text-muted",title:x("agent.copyBatchDetails"),children:e(vt,{className:"size-3"})})]})]}),e("div",{className:i("px-4 py-2 bg-gray-50/50 dark:bg-gray-800/30",d),children:t("div",{className:"flex items-center gap-3",children:[e("div",{className:"flex-1 h-2 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden",children:e("div",{className:`h-full ${z?"bg-attention":R?"bg-success":"bg-blue-500"} transition-all duration-300 ease-out`,style:{width:`${I}%`}})}),t("div",{className:"flex items-center gap-2 text-xs",children:[k>0&&t("span",{className:"text-success flex items-center gap-1",children:[e(Rt,{className:"size-3"}),k]}),C>0&&t("span",{className:"text-destructive flex items-center gap-1",children:[e(jt,{className:"size-3"}),C]}),s&&N<w&&t("span",{className:"text-blue-500 flex items-center gap-1",children:[e(st,{className:"size-3 animate-spin"}),w-N]})]})]})}),g&&_.length>0&&e("div",{className:i("max-h-64 overflow-y-auto",u),children:_.map(n=>t("div",{className:i("flex items-center gap-2 px-4 py-1.5 text-xs border-b border-gray-100 dark:border-gray-800 last:border-b-0 hover:bg-gray-50 dark:hover:bg-gray-800/50",h),children:[t("div",{className:"w-4 flex-shrink-0",children:["success"===n.status&&e(Rt,{className:"size-3 text-success"}),"error"===n.status&&e(jt,{className:"size-3 text-destructive"}),"running"===n.status&&e(st,{className:"size-3 text-blue-500 animate-spin"}),"pending"===n.status&&e("div",{className:"size-3 rounded-full border border-gray-300 dark:border-gray-600"})]}),e("span",{className:"font-mono text-muted w-24 truncate flex-shrink-0",title:n.id,children:n.id}),e("span",{className:"text-muted truncate flex-1",title:n.message,children:n.message||("pending"===n.status?x("agent.waiting"):"")}),void 0!==n.duration_ms&&t("span",{className:"text-muted flex-shrink-0",children:[(n.duration_ms/1e3).toFixed(1),"s"]})]},n.id))}),!g&&n.message&&e("div",{className:i("px-4 py-2 text-xs text-muted",f),children:n.message})]})},(e,t)=>e.isRunning===t.isRunning&&(e.batchData.completed===t.batchData.completed&&(e.batchData.succeeded===t.batchData.succeeded&&e.batchData.failed===t.batchData.failed))),sc={sending:{icon:Wt,className:"text-muted/70"},received:{icon:it,className:"text-info"},consumed:{icon:Ut,className:"text-success"},failed:{icon:jt,className:"text-destructive"}};function ic(e){if(e.type!==ir.QUESTION&&!tl(e))return;const t=e.details?._deliveryStatus;return"sending"===(n=t)||"received"===n||"consumed"===n||"failed"===n?t:e.details?.ack?"consumed":void 0;var n}function oc({message:t,className:n}){const{t:r}=Ze(),a=ic(t);if(!a)return null;const s=sc[a],o=s.icon,l=function(e,t){switch(t){case"sending":return e("agent.messageSending");case"received":return e("agent.messageReceived");case"consumed":return e("agent.messageConsumed");case"failed":return e("agent.messageFailed")}return t}(r,a);return e(h,{description:l,asChild:!0,children:e("span",{"aria-label":l,className:i("inline-flex h-5 w-5 items-center justify-center",s.className,n),role:"img",children:e(o,{className:"size-3.5","aria-hidden":"true"})})})}function lc({client:e,toast:t}){const n=Xe.getFixedT(null,et),[r,a]=Oe(!1),s=Ve(async(r,s)=>{if(r){a(!0);try{cc((await e.files.getDownloadUrlWithOptions({file:r,name:s})).url,s)}catch(e){t({status:"error",title:n("store.downloadFailed"),description:e instanceof Error?e.message:n("store.failedToGetDownloadUrl"),duration:5e3})}finally{a(!1)}}},[e,t,n]),i=Ve((e,t)=>{e&&cc(e,t)},[]),o=Ve(async(t,n)=>{const r="store"in e?e.store:e,a=await r.rendering.render(t);if(a.download_url)cc(a.download_url,n);else{if(!a.file_uri)throw new Error("No download URL or file URI in response");cc((await e.files.getDownloadUrlWithOptions({file:a.file_uri,name:n})).url,n)}},[e]);return{downloadFromContentSource:s,downloadFromUrl:i,renderDocument:Ve(async(e,r)=>{a(!0);try{const a=`${r.title||"document"}.${r.format}`;await o({object_id:e,format:r.format,title:r.title,pandoc_options:r.pandocOptions,use_default_template:r.useDefaultTemplate,template_path:r.templateObjectId?`store:${r.templateObjectId}`:void 0},a),t({status:"success",title:n("store.documentExported"),description:n("store.successfullyExportedTo",{format:r.format.toUpperCase()}),duration:2e3})}catch(e){t({status:"error",title:n("store.exportFailed"),description:e instanceof Error?e.message:n("store.failedToExportDocument"),duration:5e3})}finally{a(!1)}},[o,t,n]),renderContent:Ve(async(e,r)=>{a(!0);try{const a=`${r.title||"export"}.${r.format}`;await o({content:e,format:r.format,title:r.title,artifact_run_id:r.artifactRunId,pandoc_options:r.pandocOptions},a),t({status:"success",title:n("store.contentExported"),description:n("store.successfullyExportedTo",{format:r.format.toUpperCase()}),duration:2e3})}catch(e){t({status:"error",title:n("store.exportFailed"),description:e instanceof Error?e.message:n("store.failedToExportContent"),duration:5e3})}finally{a(!1)}},[o,t,n]),isDownloading:r}}function cc(e,t){fetch(e).then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}`);return e.blob()}).then(n=>{const r=URL.createObjectURL(n),a=document.createElement("a");a.href=r,a.download=t||dc(e),a.style.display="none",document.body.appendChild(a),a.click(),setTimeout(()=>{document.body.removeChild(a),URL.revokeObjectURL(r)},100)}).catch(()=>{const n=document.createElement("a");n.href=e,n.download=t||dc(e),n.target="_blank",n.rel="noopener noreferrer",n.style.display="none",document.body.appendChild(n),n.click(),setTimeout(()=>{document.body.removeChild(n)},100)})}function dc(e){try{const t=new URL(e).pathname.split("/");return t[t.length-1]||"download"}catch{return"download"}}function uc(e){return void 0!==e&&e>="0"&&e<="9"}function mc(e){return" "===e||"\t"===e}function pc(e,t){if(t>0&&uc(e[t-1]))return;let n=t;for(;uc(e[n]);)n++;if(n===t||"."!==e[n])return;n++;const r=n;for(;mc(e[n]);)n++;return n>r&&(void 0!==(a=e[n])&&" "!==a&&"\t"!==a&&"\n"!==a&&"\r"!==a)?n:void 0;var a}function hc(e,t){for(let n=t;n<e.length;n++)if(void 0!==pc(e,n))return n;return-1}function fc(e){const t=hc(e,0);if(-1===t)return e;let n=e.slice(0,t),r=t;for(;-1!==r;){const t=hc(e,pc(e,r)??r+1);if(-1===t){n+=e.slice(r),n+="\n\n";break}let a=t;for(;a>r&&mc(e[a-1]);)a--;n+=e.slice(r,a),n+="\n\n",r=t}return n}function gc(e){if(!e.includes("\n"))return e;const t=e.split("\n");let n=!1;return t.map(e=>{const t=n&&e.length>=2&&!uc(e[0])&&":"!==e[1]?` ${e}`:e;return n=function(e){let t=0;for(;mc(e[t]);)t++;return void 0!==pc(e,t)}(e),t}).join("\n")}const vc=["className","cardClassName","headerClassName","contentClassName","timestampClassName","senderClassName","iconClassName","detailsClassName","artifactsClassName","proseClassName"];function bc(e,t,...n){const r={};for(const a of vc)r[a]=i(e[a],t[a],...n.map(e=>e?.[a]));return r}const xc={Ready:"agent.ready",Error:"agent.error"},yc={[ir.ANSWER]:{borderColor:"border-s-info",iconColor:"text-info",sender:"Agent",Icon:Bt},[ir.COMPLETE]:{borderColor:"border-s-success",iconColor:"text-success",sender:"Completed",Icon:Rt},[ir.IDLE]:{borderColor:"border-s-info",iconColor:"text-info",sender:"Ready",Icon:Wt},[ir.REQUEST_INPUT]:{borderColor:"border-s-attention",iconColor:"text-attention",sender:"Input",Icon:Ht},[ir.QUESTION]:{borderColor:"border-s-muted",iconColor:"text-muted",sender:"User",Icon:Ht},[ir.THOUGHT]:{borderColor:"border-s-purple-500",iconColor:"text-purple-600 dark:text-purple-400",sender:"Agent",Icon:Bt},[ir.ERROR]:{borderColor:"border-s-destructive",iconColor:"text-destructive",sender:"Error",Icon:jt},[ir.UPDATE]:{borderColor:"border-s-success",iconColor:"text-success",sender:"Update",Icon:qt},[ir.PLAN]:{borderColor:"border-s-attention",iconColor:"text-attention",sender:"Plan",Icon:Tt},[ir.TERMINATED]:{borderColor:"border-s-muted",iconColor:"text-muted",sender:"Terminated",Icon:Rt},[ir.WARNING]:{borderColor:"border-s-attention",iconColor:"text-attention",sender:"Warning",Icon:jt},[ir.SYSTEM]:{borderColor:"border-s-muted",iconColor:"text-muted",sender:"System",Icon:qt},[ir.STREAMING_CHUNK]:{borderColor:"border-s-info",iconColor:"text-info",sender:"Agent",Icon:Bt},[ir.BATCH_PROGRESS]:{borderColor:"border-s-blue-500",iconColor:"text-blue-600 dark:text-blue-400",sender:"Batch",Icon:Ot},[ir.RESTARTING]:{borderColor:"border-s-attention",iconColor:"text-attention",sender:"Restarting",Icon:Vt},default:{borderColor:"border-s-muted",iconColor:"text-muted",sender:"Agent",Icon:Bt}};const wc=qe(function({message:n,showPulsatingCircle:a=!1,onSendMessage:s,requestInputAnswered:o=!1,className:l,cardClassName:c,headerClassName:d,contentClassName:u,timestampClassName:m,senderClassName:h,iconClassName:b,detailsClassName:x,artifactsClassName:y,proseClassName:w,messageStyleOverrides:N,StoreLinkComponent:k,CollectionLinkComponent:C}){const[_,S]=Oe(!1),{t:T}=Ze(),{client:I}=tr(),z=p(),R=Za(),{openImage:j}=Gl(),{router:P}=aa(),A=Be(I);A.current=I;const D=Be(R);D.current=R;const{renderContent:E,isDownloading:$}=lc({client:I,toast:z}),L=Me(()=>{const e=yc[n.type]||yc.default,t=N?.default,r=N?.[n.type];return{...e,...t,...r,...bc(e,{className:l,cardClassName:c,headerClassName:d,contentClassName:u,timestampClassName:m,senderClassName:h,iconClassName:b,detailsClassName:x,artifactsClassName:y,proseClassName:w},t,r)}},[n.type,N,l,c,d,u,m,h,b,x,y,w]),F=Me(()=>{let e="";if(n.message&&(e="object"==typeof n.message?JSON.stringify(n.message,null,2):n.message.trim?n.message.trim():String(n.message)),"string"==typeof e&&e.includes("%thinking_message%")){const t=Math.floor(Math.random()*ql.length);e=e.replace(/%thinking_message%/g,ql[t])}return e},[n.message]),M=Me(()=>n.type===ir.QUESTION?rc(F):null,[F,n.type]),O=M?.body??F,U=M?.attachments??[],W=Me(()=>O?function(e,t,n){if("string"!=typeof e)return e;if(t===ir.THOUGHT||"string"==typeof n&&(n.toLowerCase().includes("thinking about")||n.toLowerCase().includes("i'm thinking")||n.toLowerCase().includes("💭"))){let t=e;return t=gc(fc(t)),t.includes(":")&&!t.includes("\n\n")&&(t=t.replace(/\b(First|Next|Then|Finally|Lastly|Additionally|Step \d+):\s+/gi,"\n\n$&")),t.includes(" - ")&&(t=t.replace(/(^|\S)\s+-\s+/g,"$1\n- ")),t}return e.includes("\n\n")?e:fc(e)}(O,n.type,"string"==typeof n.message?n.message:void 0):"",[O,n.type,n.message]),B=async e=>{const t="string"==typeof F?F:"";if(!t.trim())return void z({status:"error",title:T("agent.noContentToExport"),duration:2e3});const r=`Message ${Dr(n.timestamp).format("YYYY-MM-DD HH-mm-ss")}`;await E(t,{format:e,title:r,artifactRunId:K})},V="string"==typeof F&&F.trim().length>0,q=Me(()=>({a:({node:t,ref:n,...r})=>{const a=r.href||"",s=a.startsWith("/")?P.getTopRouter().navigator.addStickyParams(a):a;if(a.includes("/store/objects")){if(k){const t=a.split("/store/objects/")[1]||"";return e(k,{href:s,documentId:t,children:r.children})}return e(sa,{href:s,topLevelNav:!0,children:r.children})}if(a.includes("/store/collections")){if(C){const t=a.split("/store/collections/")[1]||"";return e(C,{href:s,collectionId:t,children:r.children})}return e(sa,{href:s,topLevelNav:!0,children:r.children})}return e("a",{...r,target:"_blank",rel:"noopener noreferrer"})},img:({node:t,ref:n,...a})=>e(r,{variant:"unstyled",className:"block p-0",onClick:()=>a.src&&j(a.src,a.alt),"aria-label":a.alt||a.src||"image",children:e("img",{...a,alt:a.alt??"",className:"max-w-full h-auto rounded-lg shadow-md my-3 cursor-pointer hover:shadow-lg transition-shadow",loading:"lazy"})})}),[j,k,C,P]),H=t=>{if("object"==typeof t)return e("pre",{className:"text-xs font-mono whitespace-pre-wrap overflow-x-auto bg-gray-100 dark:bg-gray-800 p-2 rounded text-gray-700",children:JSON.stringify(t,null,2)});const r=n.workflow_run_id;return!r&&"string"==typeof t&&t.includes("artifact:")&&console.warn("[MessageItem] message contains artifact references but workflow_run_id is missing!",{type:n.type,workflow_run_id:n.workflow_run_id,hasArtifact:t.includes("artifact:")}),e("div",{className:i("vprose prose prose-slate dark:prose-invert prose-p:leading-relaxed prose-p:my-3 prose-headings:font-semibold prose-headings:tracking-normal prose-headings:mt-6 prose-headings:mb-3 prose-h1:text-xl prose-h2:text-lg prose-h3:text-base prose-li:my-1 prose-ul:my-3 prose-ol:my-3 prose-table:my-5 prose-pre:my-4 prose-hr:my-6 max-w-none text-[15px] break-words",L.proseClassName),style:{overflowWrap:"anywhere"},children:e(oa,{artifactRunId:r,onProposalSelect:e=>s?.(e),onProposalSubmit:e=>s?.(e),components:q,children:t})})},[G,J]=Oe([]),K=n.workflow_run_id,Q=n.details,Y=Q?.outputFiles??Q?.files;He(()=>{(async()=>{if(!K||!Array.isArray(Y)||0===Y.length)return void J([]);const e=A.current,t=D.current;try{const n=await Promise.all(Y.map(async n=>{if("string"!=typeof n||!n.trim())return null;const r=n.trim(),a=r.startsWith("artifact:")?r.slice(9):r,s=a.split(".").pop()?.toLowerCase()||"",i=new Set(["png","jpg","jpeg","gif","webp","bmp","svg"]).has(s),o=i?"inline":"attachment";try{const n=es(K,a,o);let s;if(t)s=await t.getOrFetch(n,async()=>(await e.files.getArtifactDownloadUrl(K,a,o)).url);else{s=(await e.files.getArtifactDownloadUrl(K,a,o)).url}return{displayName:r,artifactPath:a,url:s,isImage:i}}catch(e){return console.error(`Failed to resolve artifact URL for ${a}`,e),null}}));J(n.filter(e=>!!e))}catch(e){console.error("Error loading artifact URLs from message details",e),J([])}})()},[K,Y]);const Z=rl(n),{Icon:X}=L;return e("div",{className:i("w-full max-w-full",L.className),children:t("div",{className:i("border-s-4 bg-white dark:bg-gray-900 mb-4 w-full max-w-full overflow-hidden",L.borderColor,L.cardClassName),"data-workstream-id":Z,children:[t("div",{className:i("flex items-center justify-between px-4 py-1.5",L.headerClassName),children:[t("div",{className:"flex items-center gap-1.5",children:[e("div",{className:i(a?"animate-fadeIn":"",L.iconClassName),children:a?e(Ol,{size:"sm",color:"blue"}):e(X,{className:`size-4 ${L.iconColor}`})}),e("span",{className:i("text-xs font-medium text-muted",L.senderClassName),children:xc[L.sender]?T(xc[L.sender]):L.sender}),"main"!==Z&&"all"!==Z&&e(f,{variant:"default",className:"text-xs text-muted ms-1",children:Z})]}),t("div",{className:"flex items-center gap-1.5 print:hidden",children:[e(oc,{message:n}),e("span",{className:i("text-[11px] text-muted/70",L.timestampClassName),children:Dr(n.timestamp).format("HH:mm:ss")}),e(r,{variant:"ghost",size:"xs",onClick:()=>{const e=F||"",t="string"==typeof n.details?n.details:n.details?JSON.stringify(n.details,null,2):"",r=[e,t?`\n\nDetails:\n${t}`:""].join("").trim();navigator.clipboard.writeText(r).then(()=>{z({status:"success",title:T("agent.copiedToClipboard"),duration:2e3})})},className:"text-muted/50 hover:text-muted h-5 w-5 p-0",title:T("agent.copyMessage"),children:e(vt,{className:"size-3"})}),V&&t(g,{trigger:e(r,{variant:"ghost",size:"xs",className:"text-muted/50 hover:text-muted h-5 w-5 p-0",title:T("agent.exportMessage"),disabled:$,children:e(lt,{className:"size-3 "+($?"animate-pulse":"")})}),children:[e(v,{onClick:()=>B(or.pdf),children:T("agent.exportAsPdf")}),e(v,{onClick:()=>B(or.docx),children:T("agent.exportAsWord")})]})]})]}),t("div",{className:i("px-4 pb-3 bg-white dark:bg-gray-900 overflow-hidden",L.contentClassName),children:[n.type===ir.REQUEST_INPUT&&n.details?.ux?(()=>{const t=n.details.ux;return e(Oo,{question:"string"==typeof F?F:"",options:t.options,variant:t.variant,multiSelect:t.multiSelect,onSelect:e=>s?.(e),onMultiSelect:e=>s?.(e.join(", ")),allowFreeResponse:!t.options?.length||!!t.free_response,placeholder:t.free_response?.placeholder,submitLabel:t.free_response?.submit_label,onSubmit:e=>s?.(e,t.free_response?.metadata),hideBorder:!0,compact:!0,answered:o})})():O&&e("div",{className:"message-content break-words w-full",style:{overflowWrap:"anywhere",wordBreak:"break-word"},children:H(W||O)}),U.length>0&&e(ec,{items:U,artifactRunId:K,variant:"message",className:i(O&&"mt-3"),StoreLinkComponent:k,CollectionLinkComponent:C}),G.length>0&&t("div",{className:i("mt-3 text-xs",L.artifactsClassName),children:[e("div",{className:"font-medium text-muted mb-1",children:"Artifacts"}),G.some(e=>e.isImage)&&e("div",{className:"mb-2 flex flex-wrap gap-3",children:G.filter(e=>e.isImage).map(({displayName:n,artifactPath:a,url:s})=>t(r,{variant:"unstyled",className:"max-w-xs cursor-pointer text-start p-0",onClick:()=>j(s,n),"aria-label":n,children:[e("img",{src:s,alt:n,className:"max-w-full h-auto rounded-lg shadow-sm hover:shadow-md transition-shadow"}),e("div",{className:"mt-1 text-[11px] text-muted truncate",children:n})]},`${a}-preview`))}),e("div",{className:"flex flex-wrap gap-2 print:hidden",children:G.map(({displayName:t,artifactPath:n,url:a})=>e(r,{variant:"outline",size:"xs",className:"px-2 py-1 text-xs",onClick:()=>window.open(a,"_blank"),title:n,children:t},n+a))})]}),n.details&&t("div",{className:i("mt-2 print:hidden",L.detailsClassName),children:[t(r,{variant:"unstyled",onClick:()=>S(!_),className:"text-[11px] text-muted flex items-center",children:[T(_?"agent.hideDetails":"agent.showDetails"),e("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-3 w-3 ms-1 transition-transform "+(_?"rotate-180":""),fill:"none",viewBox:"0 0 24 24",stroke:"currentColor","aria-hidden":"true",children:e("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),_&&e("div",{className:"mt-1 p-1.5 bg-muted border border-mixer-muted/40 rounded text-sm",children:"string"==typeof n.details?H(n.details):e("pre",{className:"text-xs font-mono whitespace-pre-wrap overflow-x-auto bg-muted p-2 rounded text-muted",children:JSON.stringify(n.details,null,2)})})]})]})]})})},(e,t)=>e.message.timestamp===t.message.timestamp&&e.message.type===t.message.type&&e.message.message===t.message.message&&e.message.details===t.message.details&&e.message.workstream_id===t.message.workstream_id&&e.message.workflow_run_id===t.message.workflow_run_id&&e.showPulsatingCircle===t.showPulsatingCircle&&e.onSendMessage===t.onSendMessage&&e.requestInputAnswered===t.requestInputAnswered&&e.messageStyleOverrides===t.messageStyleOverrides&&vc.every(n=>e[n]===t[n]));const Nc=Fe.memo(function({text:n,workstreamId:a,artifactRunId:s,revealSpeed:o=300,isComplete:l=!1,timestamp:c,className:d,cardClassName:u,headerClassName:m,contentClassName:h,proseClassName:f,senderClassName:g,iconClassName:v}){const{t:b}=Ze(),[x,y]=Oe(0),[w,N]=Oe(""),k=Be(null),C=Be(n.length),_=Be(0),S=Be(c||Date.now()),T=Be(n),I=Be(0),z=Be(performance.now()),R=Be(o),j=Be(0);He(()=>{const e=performance.now(),t=n.length-I.current,r=e-z.current;if(t>0&&r>30){const e=t/r*1e3,n=.2;R.current=R.current*(1-n)+e*n,R.current=Math.max(50,Math.min(2e3,R.current))}I.current=n.length,z.current=e},[n.length]),C.current=n.length,T.current=n;const P=Ve(()=>{let e=performance.now();const t=n=>{const r=n-e;e=n;const a=C.current-_.current;if(a<=0)return j.current=0,void(k.current=null);let s;if(l)s=Math.max(500,2*R.current);else if(a<20)s=.85*R.current;else if(a<100)s=R.current;else if(a<500){const e=(a-100)/400;s=R.current*(1+.5*e)}else s=2*R.current;const i=s*r/1e3+j.current,o=Math.floor(i);j.current=i-o,o>0&&(_.current=Math.min(_.current+o,C.current),y(_.current)),k.current=requestAnimationFrame(t)};k.current=requestAnimationFrame(t)},[l]);He(()=>(n.length>_.current&&!k.current&&P(),()=>{k.current&&(cancelAnimationFrame(k.current),k.current=null)}),[n.length,P]),He(()=>{l&&_.current<n.length&&(k.current&&(cancelAnimationFrame(k.current),k.current=null),P())},[l,n.length,P]);const A=Be(null),D=Be(0);He(()=>{(x>=C.current||l)&&(N(T.current.slice(0,x)),D.current=x)},[x,l]);const E=x<n.length&&!l;He(()=>{if(E)return A.current||(A.current=window.setInterval(()=>{const e=_.current;e>D.current&&(N(T.current.slice(0,e)),D.current=e)},33)),()=>{A.current&&(clearInterval(A.current),A.current=null)};A.current&&(clearInterval(A.current),A.current=null)},[E]);const $=p(),L=Me(()=>Dr(S.current).format("HH:mm:ss"),[]),F=x<n.length,M=Me(()=>{const e=w||n.slice(0,x);return F?e+"│":e},[w,n,x,F]);return n?e("div",{className:i("w-full max-w-full",d),children:t("div",{className:i("border-s-4 bg-white dark:bg-gray-900 mb-4 border-s-purple-500 w-full max-w-full overflow-hidden",u),"data-workstream-id":a,children:[t("div",{className:i("flex items-center justify-between px-4 py-1.5",m),children:[t("div",{className:"flex items-center gap-1.5",children:[e("div",{className:i("animate-fadeIn",v),children:F?e("span",{className:"size-2 rounded-full bg-blue-500 animate-pulse inline-block"}):e(Bt,{className:"size-4 text-purple-600 dark:text-purple-400"})}),e("span",{className:i("text-xs font-medium text-muted",g),children:"Agent"}),a&&"main"!==a&&t("span",{className:"text-xs text-muted",children:["• Task ",a]})]}),t("div",{className:"flex items-center gap-2 text-muted",children:[e("span",{className:"text-[11px]",children:L}),e(r,{variant:"ghost",size:"xs",onClick:()=>{navigator.clipboard.writeText(n).then(()=>{$({status:"success",title:b("agent.copiedToClipboard"),duration:2e3})})},className:"size-6 p-0 hover:bg-gray-100 dark:hover:bg-gray-800",title:b("agent.copyMessage"),children:e(vt,{className:"size-3"})})]})]}),t("div",{className:i("px-3 pb-2 streaming-content",F&&"streaming-active",h),children:[e("div",{className:i("vprose prose prose-slate dark:prose-invert prose-p:leading-relaxed prose-p:my-3 prose-headings:font-semibold prose-headings:tracking-normal prose-headings:mt-6 prose-headings:mb-3 prose-h1:text-xl prose-h2:text-lg prose-h3:text-base prose-li:my-1 prose-ul:my-3 prose-ol:my-3 prose-table:my-5 prose-pre:my-4 prose-hr:my-6 max-w-none text-[15px] break-words",f),style:{overflowWrap:"anywhere"},children:e(oa,{artifactRunId:s,children:M})}),e("style",{children:"\n /* Ensure inline elements flow properly */\n .streaming-content p:last-child,\n .streaming-content li:last-child {\n display: inline;\n }\n /* Soft fade at reveal edge */\n .streaming-active .vprose {\n mask-image: linear-gradient(to right, black 97%, transparent 100%);\n -webkit-mask-image: linear-gradient(to right, black 97%, transparent 100%);\n }\n "})]})]})}):null});function kc(e){return e.message?"object"==typeof e.message?JSON.stringify(e.message,null,2):String(e.message).trim():""}function Cc(e){return e.type===ir.THOUGHT&&"thinking"===e.details?.display_role}function _c(e){if(Cc(e))return!0;if(e.type!==ir.WARNING)return!1;const t=e.details,n=kc(e).replace(/^[^A-Za-z0-9]+/,"").toLowerCase();return"number"==typeof t?.attempt&&"number"==typeof t?.maxAttempts&&"number"==typeof t?.estimatedBackoffSeconds&&"string"==typeof t?.activityId&&(n.startsWith("retrying operation")||n.startsWith("retrying checkpoint operation"))}function Sc(e){if("number"==typeof e)return e;if(!e)return-1/0;const t=new Date(e).getTime();return Number.isFinite(t)?t:-1/0}function Tc(e,t){const n=e.details?.[t];if("string"!=typeof n)return;const r=n.trim();return r||void 0}function Ic(e){if(Ho(e))return!1;const t=kc(e);return!(!t||function(e){const t=e.replace(/\s+/g," ").trim().toLowerCase();return"thinking"===t||"thinking..."===t||"working"===t||"working..."===t||"waiting"===t||"waiting..."===t}(t))&&(e.type===ir.ANSWER||!ml(e)&&(e.type===ir.THOUGHT&&Boolean(e.details?.streamed)))}function zc(e){if(e.type!==ir.ERROR&&e.type!==ir.WARNING)return!1;const t=e.details;return Boolean(t?.tool||t?.tool_status||t?.tool_run_id||t?.activity_group_id||t?.tool_event)}function Rc(e){if(e.type!==ir.ERROR||zc(e))return!1;const t=e.details;return kc(e).startsWith("Error analyzing conversation:")&&"string"==typeof t?.error}function jc(e){if(e.type!==ir.ERROR)return!1;const t=e.details;return"activity"===t?.event_class&&(!t.workstream_event&&!(t.tool||t.tool_status||t.tool_run_id||t.activity_group_id||t.tool_event))}function Pc(e){return!Ho(e)&&(!jc(e)&&(e.type===ir.QUESTION||Boolean(Jo(e))||Ic(e)||e.type===ir.REQUEST_INPUT&&!zl(e)||e.type===ir.TERMINATED||(e.type===ir.ERROR||e.type===ir.WARNING)&&!zc(e)&&!_c(e)))}function Ac(e){const t=e.details?.tool_status;return"running"===t||"completed"===t||"error"===t||"warning"===t?t:e.type===ir.ERROR?"error":e.type===ir.WARNING?"warning":void 0}function Dc(e,t){return pl(e)&&!Cc(e)&&t.length>0&&t.every(Cc)}function Ec(e){return!Ho(e)&&(!Ic(e)&&(!Jo(e)&&(!!jc(e)||(!!_c(e)||(!!zl(e)||(!!zc(e)||(!!ml(e)||(!!pl(e)||(e.type===ir.UPDATE||e.type===ir.PLAN||e.type===ir.THOUGHT&&!e.details?.streamed)))))))))}function $c(e,t,n=function(e){return e.reduce((e,t)=>Math.max(e,Sc(t.timestamp)),-1/0)}(e)){const r=[];let a=[];const s=new Set,i=(e,t)=>{if(0===a.length)return;const s=function(e,t,n){if(!e.some(_c))return e;if(!t)return e.filter(e=>!_c(e));let r=-1,a=-1;return e.forEach((e,t)=>{_c(e)?a=t:r=t}),e.filter((e,t)=>!_c(e)||t===a&&t>r&&Sc(e.timestamp)>=n)}(a,e,n);if(0===s.length)return void(a=[]);const i=s[0],o=s[s.length-1],l=function(e,t){for(let n=e.length-1;n>=0;n--){const r=Ac(e[n]);if("error"===r||"warning"===r)return r;if(r)return t?"running":"completed"}return t?"running":"completed"}(s,e);r.push({type:"work",id:e?`${i.timestamp}-active`:`${i.timestamp}-${o.timestamp}-${s.length}`,messages:s,isActive:e,status:l,startTimestamp:i.timestamp,endTimestamp:t?.timestamp??o.timestamp}),a=[]};for(const t of e){const e=Jo(t),n=e?null:Ko(t),o=e??n;if(o){const n=s.has(o.workstreamId);if(s.add(o.workstreamId),e||!n){i(!1,t),r.push({type:"message",message:t});continue}}if(t.type!==ir.COMPLETE&&t.type!==ir.IDLE)if(Ec(t)||a.length>0&&Rc(t)){if(Dc(t,a)){const e=r[r.length-1];if("work"===e?.type&&!e.isActive){r.pop(),a=[...e.messages,t];continue}}a.push(t)}else Pc(t)&&(i(!1,t),r.push({type:"message",message:t}));else{if(tl(t)){const e=a[0]?.timestamp;i(!1,t);const n=r[r.length-1];r.push({type:"stopped",message:t,startTimestamp:void 0!==e&&"work"===n?.type?n.startTimestamp:e??t.timestamp,endTimestamp:t.timestamp});continue}i(!1,t)}}return i(!t),r}function Lc(e,t){if(0===t.size)return e;const n=e.find(e=>e.workflow_run_id)?.workflow_run_id??"",r=[];return t.forEach((t,a)=>{const s=t.text.trim();if(!s||cl(t,e))return;if(qo(s,t.workstreamId))return;const i=function(e,t){if(e.activityId){const n=t.find(t=>pl(t)&&(Tc(t,"activity_id")===e.activityId||Tc(t,"activity_group_id")===e.activityId));if(n)return n;const r=t.find(t=>Tc(t,"activity_id")===e.activityId&&Tc(t,"activity_group_id"))?.details?.activity_group_id;if("string"==typeof r){const e=t.find(e=>pl(e)&&Tc(e,"activity_group_id")===r);if(e)return e}}if(e.isComplete)return;const n=Sc(e.startTimestamp);if(!Number.isFinite(n))return;const r=[...t].filter(e=>Sc(e.timestamp)>=n).sort((e,t)=>Sc(e.timestamp)-Sc(t.timestamp));for(const e of r){if(Sc(e.timestamp)-n>6e4)return;if(pl(e))return e;if(Pc(e))return}}(t,e),o=i?Tc(i,"activity_group_id"):void 0;r.push({timestamp:t.startTimestamp,workflow_run_id:n,type:i?ir.THOUGHT:ir.ANSWER,message:s,workstream_id:t.workstreamId,details:{activity_id:t.activityId,activity_group_id:o,display_role:i?"tool_preamble":void 0,source:"streaming_summary",streamed:!0,streaming_id:a,tools:i?.details?.tool?[i.details.tool]:void 0}})}),0===r.length?e:[...e,...r].sort((e,t)=>Sc(e.timestamp)-Sc(t.timestamp))}const Fc=new Set(["tool","tool_event","tool_run_id","tool_use_id","activity_group_id","event_class","tool_iteration","tool_status","message_to_human","tools","streamed","files","outputFiles","display_role","observation","progress_messages","browseruse","browser_use"]);function Mc(e){return e?Object.entries(e).filter(([e,t])=>!Fc.has(e)&&null!=t&&""!==t):[]}function Oc(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/^./,e=>e.toUpperCase())}function Uc(e){const t=e?.progress_messages;return Array.isArray(t)?t.flatMap(e=>{if(!e||"object"!=typeof e)return[];const t=e,n="string"==typeof t.message?t.message.trim():"";if(!n)return[];return[{message:n,status:"string"==typeof t.status?t.status:void 0,timestamp:"number"==typeof t.timestamp||"string"==typeof t.timestamp?t.timestamp:void 0}]}):[]}function Wc(e){return["progress",e.timestamp??"no-time",e.status??"status",e.message].join(":")}function Bc(e){const t=e.details,n="string"==typeof t?.tool_run_id?t.tool_run_id:void 0;if(n)return`tool-run:${n}`;const r="string"==typeof t?.activity_group_id?t.activity_group_id:void 0,a="string"==typeof t?.tool_use_id?t.tool_use_id:void 0;return r||a?`tool:${r??"no-activity"}:${a??"no-use"}`:["message",e.workstream_id??"main",e.type,e.timestamp,Kc(e)].join(":")}function Vc(e){switch(e){case"completed":return"bg-green-50 dark:bg-green-900/30 text-green-700 dark:text-green-300 border-green-200 dark:border-green-800";case"running":return"bg-blue-50 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 border-blue-200 dark:border-blue-800";case"error":return"bg-red-50 dark:bg-red-900/30 text-red-700 dark:text-red-300 border-red-200 dark:border-red-800";case"warning":return"bg-yellow-50 dark:bg-yellow-900/30 text-yellow-700 dark:text-yellow-300 border-yellow-200 dark:border-yellow-800";default:return""}}const qc=e=>/\.(png|jpg|jpeg|gif|webp|svg)(\?|$)/i.test(e);function Hc({files:n,className:a}){const{t:s}=Ze(),{openImage:o}=Gl();return n&&0!==n.length?e("div",{className:i("mt-2 flex flex-wrap gap-2",a),children:n.map((n,a)=>{const i=n.split("/").pop()?.split("?")[0]||"file";return qc(n)?e(r,{variant:"unstyled",className:"cursor-pointer p-0",onClick:()=>o(n,i),title:s("agent.clickToEnlarge"),"aria-label":i,children:e("img",{src:n,alt:i,className:"max-w-[300px] max-h-[200px] rounded border hover:opacity-80 transition-opacity hover:shadow-lg"})},a):t("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 px-2 py-1 bg-muted rounded text-xs hover:bg-muted/80",children:["📎 ",i]},a)})}):null}const Gc=e=>{if(!e)return;const t=e.files??e.outputFiles;return Array.isArray(t)?t:void 0},Jc=e=>{const t=e.details;return e.type===ir.THOUGHT&&"tool_preamble"===t?.display_role},Kc=e=>{const t=e.details;if(Jc(e))return"assistant";if(t?.tool)return t.tool;switch(e.type){case ir.UPDATE:return"update";case ir.WARNING:return"warning";case ir.ERROR:return"error";case ir.SYSTEM:return"system";default:return"activity"}},Qc=e=>Jc(e)?"text-[10px] px-1.5 py-0.5 rounded-md bg-gray-50 dark:bg-gray-800 text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-gray-700 font-medium":"text-[10px] px-1.5 py-0.5 rounded-md bg-purple-50 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300 border border-purple-200 dark:border-purple-800 font-medium";function Yc({message:n,isExpanded:a,onToggle:s,artifactRunId:o,classNames:l={}}){const{t:c}=Ze(),[d,u]=Oe([]),h=p(),{client:f}=tr(),g=Za(),v=Be(f);v.current=f;const b=Be(g);b.current=g;const x=n.details,y=Kc(n),w=Qc(n),N=Gc(x),k="string"==typeof n.message?n.message:"";He(()=>{if(!N||0===N.length||!o)return void u([]);let e=!1;return(async()=>{const t=v.current,n=b.current,r=await Promise.all(N.map(async e=>{if(!e||"string"!=typeof e)return null;if(e.startsWith("http://")||e.startsWith("https://"))return e;const r=e.startsWith("artifact:")?e.slice(9):e,a=r.split(".").pop()?.toLowerCase()||"",s=new Set(["png","jpg","jpeg","gif","webp","bmp","svg"]).has(a)?"inline":"attachment";try{const e=es(o,r,s);if(n)return await n.getOrFetch(e,async()=>(await t.files.getArtifactDownloadUrl(o,r,s)).url);return(await t.files.getArtifactDownloadUrl(o,r,s)).url}catch(e){return console.error(`Failed to resolve artifact URL for ${r}`,e),null}}));e||u(r.filter(e=>!!e))})(),()=>{e=!0}},[N,o]);const C=d.filter(e=>qc(e)),_=d.filter(e=>!qc(e));return t("div",{className:i("border-b border-gray-100 dark:border-gray-800 last:border-b-0",l.itemClassName),children:[t("div",{role:"button",tabIndex:0,className:i("flex items-start justify-between px-3 py-2 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors",l.itemHeaderClassName),onClick:s,onKeyDown:m(s),children:[t("div",{className:"flex items-start gap-2 flex-1 min-w-0",children:[e("div",{className:"flex-shrink-0 pt-0.5",children:a?e(Mt,{className:"size-3 text-muted"}):e(ht,{className:"size-3 text-muted cn-rtl-flip"})}),e("div",{className:"flex-1 min-w-0",children:k?e("span",{className:"text-xs text-foreground line-clamp-2",children:k}):t("span",{className:"text-xs text-muted italic",children:["Activity: ",y]})})]}),t("div",{className:"flex items-center gap-2 flex-shrink-0",children:[!a&&e("span",{className:i(w,l.toolBadgeClassName),children:y}),e(r,{variant:"ghost",size:"xs",onClick:e=>{e.stopPropagation(),(()=>{const e=[k,x?`\n\nDetails:\n${JSON.stringify(x,null,2)}`:""].join("").trim();navigator.clipboard.writeText(e).then(()=>{h({status:"success",title:c("agent.copiedToClipboard"),duration:2e3})})})()},className:"text-muted opacity-0 group-hover:opacity-100 transition-opacity",title:c("agent.copyMessage"),children:e(vt,{className:"size-3"})})]})]}),C.length>0&&e("div",{className:"px-3 pb-1.5",children:e(Hc,{files:C})}),a&&(()=>{const r=x?.tool_status,a=Mc(x),s=Uc(x);return t("div",{className:i("px-4 py-2 bg-gray-50/50 dark:bg-gray-800/30",l.itemContentClassName),children:[t("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[e("span",{className:i(w,l.toolBadgeClassName),children:y}),r&&e("span",{className:i("text-[10px] px-1.5 py-0.5 rounded-md border font-medium",Vc(r)),children:r}),e("span",{className:"text-[10px] text-muted/70",children:Dr(n.timestamp).format("HH:mm:ss")})]}),a.length>0&&e("div",{className:"mb-2 space-y-0.5",children:a.map(([n,r])=>t("div",{className:"flex gap-1.5 text-xs",children:[t("span",{className:"text-muted font-medium flex-shrink-0",children:[Oc(n),":"]}),e("span",{className:"text-foreground break-all",children:"object"==typeof r?JSON.stringify(r):String(r)})]},n))}),s.length>0&&t("div",{className:"mb-2 space-y-1",children:[e("div",{className:"text-[10px] uppercase tracking-wide text-muted/70 font-medium",children:c("agent.progress")}),s.map(n=>t("div",{className:"text-xs text-muted",children:[n.timestamp&&e("span",{className:"me-1 text-muted/60",children:Dr(n.timestamp).format("HH:mm:ss")}),e("span",{children:n.message})]},Wc(n)))]}),(()=>{const t="string"==typeof x?.observation?x.observation:void 0;return t&&t!==k?e("div",{className:"vprose prose prose-slate dark:prose-invert prose-p:leading-relaxed prose-p:my-1.5 max-w-none text-sm",children:e(oa,{artifactRunId:o,children:t})}):null})(),_.length>0&&e(Hc,{files:_})]})})()]})}function Zc({files:t,artifactRunId:n}){const[r,a]=Oe([]),{client:s}=tr(),i=Za(),o=Be(s);o.current=s;const l=Be(i);return l.current=i,He(()=>{if(!t||0===t.length||!n)return void a([]);let e=!1;return(async()=>{const r=o.current,s=l.current,i=await Promise.all(t.map(async e=>{if(!e||"string"!=typeof e)return null;const t=e.startsWith("artifact:")?e.slice(9):e,a=t.split(".").pop()?.toLowerCase()||"";if(new Set(["png","jpg","jpeg","gif","webp","bmp","svg"]).has(a))return null;if(t.startsWith("http://")||t.startsWith("https://"))return t;try{const e=es(n,t,"attachment");if(s)return await s.getOrFetch(e,async()=>(await r.files.getArtifactDownloadUrl(n,t,"attachment")).url);return(await r.files.getArtifactDownloadUrl(n,t,"attachment")).url}catch(e){return console.error(`Failed to resolve artifact URL for ${t}`,e),null}}));e||a(i.filter(e=>!!e))})(),()=>{e=!0}},[t,n]),0===r.length?null:e("div",{className:"ps-4 pe-2 pb-1.5",children:e(Hc,{files:r})})}function Xc({messages:t,artifactRunId:n}){const[r,a]=Oe([]),{client:s}=tr(),i=Za(),o=Be(s);o.current=s;const l=Be(i);return l.current=i,He(()=>{if(!n||0===t.length)return void a([]);const e=t[t.length-1].details,r=Gc(e);if(!r||0===r.length)return void a([]);let s=!1;return(async()=>{const e=o.current,t=l.current,i=await Promise.all(r.map(async r=>{if(!r||"string"!=typeof r)return null;const a=r.startsWith("artifact:")?r.slice(9):r,s=a.split(".").pop()?.toLowerCase()||"";if(!new Set(["png","jpg","jpeg","gif","webp","bmp","svg"]).has(s))return null;if(a.startsWith("http://")||a.startsWith("https://"))return a;try{const r=es(n,a,"inline");if(t)return await t.getOrFetch(r,async()=>(await e.files.getArtifactDownloadUrl(n,a,"inline")).url);return(await e.files.getArtifactDownloadUrl(n,a,"inline")).url}catch(e){return console.error(`Failed to resolve artifact URL for ${a}`,e),null}}));s||a(i.filter(e=>!!e))})(),()=>{s=!0}},[t,n]),0===r.length?null:e("div",{className:"px-3 py-1.5 border-b border-gray-100 dark:border-gray-800",children:e(Hc,{files:r})})}const ed=qe(function({messages:a,showPulsatingCircle:s=!1,toolRunId:o,toolStatus:l,preambleText:c,preambleMessage:d,rootClassName:u,headerClassName:h,senderClassName:f,toolSummaryClassName:g,toolBadgeClassName:v,itemClassName:b,itemHeaderClassName:x,itemContentClassName:y}){const w=Me(()=>function(e){const t=new Map,n=[];for(const r of e){const e=r.details?.tool_run_id;e?(t.has(e)||t.set(e,[]),t.get(e)?.push(r)):n.push(r)}for(const[e,r]of t){if(r.length<=1){n.push(...r);continue}r.sort((e,t)=>("number"==typeof e.timestamp?e.timestamp:new Date(e.timestamp).getTime())-("number"==typeof t.timestamp?t.timestamp:new Date(t.timestamp).getTime()));const e=r[r.length-1],t=r.find(e=>"started"===e.details?.tool_event),a=r.find(e=>"running"===e.details?.tool_status),s=t??a??r.find(e=>e.message?.trim()),i=("string"==typeof s?.details?.message_to_human?s.details.message_to_human:void 0)||s?.message||e.message,o=r.filter(e=>"progress"===e.details?.tool_event&&e.message?.trim()).map(e=>({message:e.message.trim(),status:e.details?.tool_status,timestamp:e.timestamp})),l={};for(const e of r)Object.assign(l,e.details);o.length>0&&(l.progress_messages=o),n.push({...e,message:i,details:l})}return n.sort((e,t)=>("number"==typeof e.timestamp?e.timestamp:new Date(e.timestamp).getTime())-("number"==typeof t.timestamp?t.timestamp:new Date(t.timestamp).getTime())),n}(a),[a]),N=Me(()=>w.map(Bc),[w]),[k,C]=Oe(!0),[_,S]=Oe(new Set),[T,I]=Oe(new Set),z=Be(N),{t:R}=Ze(),j=p(),P=w.find(e=>e.workflow_run_id)?.workflow_run_id??w[0]?.workflow_run_id;He(()=>{const e=z.current,t=new Set(e),n=N.filter(e=>!t.has(e));if(n.length>0){I(new Set(n));const e=setTimeout(()=>{I(new Set)},500);return z.current=N,()=>clearTimeout(e)}z.current=N},[N]);const A=w[0],D=w[w.length-1],E=A.timestamp,$=D.timestamp,L=w.map(e=>Kc(e)),F=1===new Set(L).size?`${w.length}× ${L[0]}`:`${w.length} activity updates`,M=e=>{S(t=>{const n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})};return t("div",{className:i("border-s-4 overflow-hidden bg-white dark:bg-gray-900 mb-4","completed"===l?"border-s-success":"error"===l?"border-s-destructive":"warning"===l?"border-s-attention":"border-s-purple-500",u),children:[t("div",{role:"button",tabIndex:0,"aria-expanded":!k,className:i("flex items-center justify-between px-4 py-1.5 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors",h),onClick:()=>C(!k),onKeyDown:m(()=>C(!k)),children:[t("div",{className:"flex items-center gap-1 flex-1 min-w-0",children:[s?e(Ol,{size:"sm",color:"blue"}):"running"===l?e("span",{className:"size-2 rounded-full bg-blue-500 inline-block"}):"completed"===l?e(Rt,{className:"size-4 text-success"}):"error"===l?e(jt,{className:"size-4 text-destructive"}):"warning"===l?e(Gt,{className:"size-4 text-attention"}):e(Bt,{className:"size-4 text-purple-600 dark:text-purple-400"}),c?e("span",{className:i("text-xs text-foreground line-clamp-2 flex-1 min-w-0",g),children:c}):t(n,{children:[e("span",{className:i("text-xs font-medium text-muted",f),children:"Agent"}),e("span",{className:i("text-xs text-purple-600 dark:text-purple-400 font-medium",g),children:F})]}),k?e(ht,{className:"size-3 text-muted flex-shrink-0 cn-rtl-flip"}):e(Mt,{className:"size-3 text-muted flex-shrink-0"})]}),t("div",{className:"flex items-center gap-1 flex-shrink-0",children:[c&&e("span",{className:i("text-[10px] text-purple-600 dark:text-purple-400 font-medium",g),children:F}),t("span",{className:"text-[11px] text-muted/70",children:[Dr(E).format("HH:mm:ss"),w.length>1&&` - ${Dr($).format("HH:mm:ss")}`]}),e(r,{variant:"ghost",size:"xs",onClick:e=>{e.stopPropagation(),(()=>{const e=w.map(e=>{const t=e.details;return`[${Kc(e)}] ${e.message||""}\n${t?JSON.stringify(t,null,2):""}`}).join("\n\n---\n\n");navigator.clipboard.writeText(e).then(()=>{j({status:"success",title:R("agent.copiedAllToolCalls"),duration:2e3})})})()},className:"text-muted/50 hover:text-muted h-5 w-5 p-0",title:R("agent.copyAllToolCalls"),children:e(vt,{className:"size-3"})})]})]}),e(Xc,{messages:w,artifactRunId:P}),k&&e("div",{className:"px-3 py-0.5 space-y-0",children:w.map((n,r)=>{const a=N[r]??Bc(n),s=n.details,o=Kc(n),l=Qc(n),c="string"==typeof n.message?n.message:"",d=T.has(a),u=_.has(a),p=Gc(s);return t("div",{className:i("border-b border-gray-100 dark:border-gray-800 last:border-b-0",b),style:{opacity:d?0:1,transform:d?"translateX(-10px)":"translateX(0)",transition:"opacity 0.3s ease-out, transform 0.3s ease-out",transitionDelay:100*(r-(w.length-T.size))+"ms",animation:d?"slideInFade 0.4s ease-out forwards":"none",animationDelay:100*(r-(w.length-T.size))+"ms"},children:[t("div",{role:"button",tabIndex:0,"aria-expanded":u,className:i("flex items-start gap-2 py-1.5 text-xs cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800/50",x),onClick:()=>M(a),onKeyDown:m(()=>M(a)),title:c,children:[e("div",{className:"flex-shrink-0 pt-0.5",children:u?e(Mt,{className:"size-3 text-muted"}):e(ht,{className:"size-3 text-muted cn-rtl-flip"})}),e("div",{className:"flex-1 min-w-0",children:c?e("span",{className:"text-foreground line-clamp-2",children:c}):t("span",{className:"text-muted italic",children:["Activity: ",o]})}),!u&&e("span",{className:i(l,"flex-shrink-0",v),children:o})]}),e(Zc,{files:p,artifactRunId:P}),u&&(()=>{const r=s?.tool_status,a=Mc(s),d=Uc(s);return t("div",{className:i("ps-5 pe-3 pb-2 text-sm",y),children:[t("div",{className:"flex items-center gap-2 mb-1.5 flex-wrap",children:[e("span",{className:i(l,v),children:o}),r&&e("span",{className:i("text-[10px] px-1.5 py-0.5 rounded-md border font-medium",Vc(r)),children:r}),e("span",{className:"text-[10px] text-muted/70",children:Dr(n.timestamp).format("HH:mm:ss")})]}),a.length>0&&e("div",{className:"mb-1.5 space-y-0.5",children:a.map(([n,r])=>t("div",{className:"flex gap-1.5 text-xs",children:[t("span",{className:"text-muted font-medium flex-shrink-0",children:[Oc(n),":"]}),e("span",{className:"text-foreground break-all",children:"object"==typeof r?JSON.stringify(r):String(r)})]},n))}),d.length>0&&t("div",{className:"mb-1.5 space-y-1",children:[e("div",{className:"text-[10px] uppercase tracking-wide text-muted/70 font-medium",children:R("agent.progress")}),d.map(n=>t("div",{className:"text-xs text-muted",children:[n.timestamp&&e("span",{className:"me-1 text-muted/60",children:Dr(n.timestamp).format("HH:mm:ss")}),e("span",{children:n.message})]},Wc(n)))]}),(()=>{const t="string"==typeof s?.observation?s.observation:void 0;return t&&t!==c?e("div",{className:"vprose prose prose-slate dark:prose-invert prose-p:leading-relaxed prose-p:my-1.5 max-w-none text-sm",children:e(oa,{artifactRunId:P,children:t})}):null})()]})})()]},a)})}),e("style",{children:"\n @keyframes slideInFade {\n from {\n opacity: 0;\n transform: translateX(-10px);\n }\n to {\n opacity: 1;\n transform: translateX(0);\n }\n }\n "}),!k&&e("div",{className:"group",children:w.map((t,n)=>{const r=N[n]??Bc(t);return e(Yc,{message:t,isExpanded:_.has(r),onToggle:()=>M(r),artifactRunId:P,classNames:{toolBadgeClassName:v,itemClassName:b,itemHeaderClassName:x,itemContentClassName:y}},r)})})]})},(e,t)=>e.messages.length===t.messages.length&&(e.showPulsatingCircle===t.showPulsatingCircle&&(e.toolRunId===t.toolRunId&&(e.toolStatus===t.toolStatus&&(e.preambleText===t.preambleText&&(e.rootClassName===t.rootClassName&&(e.headerClassName===t.headerClassName&&(e.senderClassName===t.senderClassName&&(e.toolSummaryClassName===t.toolSummaryClassName&&(e.toolBadgeClassName===t.toolBadgeClassName&&(e.itemClassName===t.itemClassName&&(e.itemHeaderClassName===t.itemHeaderClassName&&(e.itemContentClassName===t.itemContentClassName&&e.messages.every((e,n)=>{return r=e,a=t.messages[n],r.timestamp===a.timestamp&&r.type===a.type&&r.message===a.message&&r.details===a.details&&r.workstream_id===a.workstream_id&&r.workflow_run_id===a.workflow_run_id;var r,a}))))))))))))));function td({workstreams:n,activeWorkstream:a,onSelectWorkstream:s,count:o,completionStatus:l}){const{t:c}=Ze(),d=new Map;d.set("all",c("agent.allMessages")),d.set("main",c("agent.main")),n.forEach((e,t)=>{"all"!==t&&"main"!==t&&"research_france"!==t&&"statistics"!==t&&d.set(t,e)}),n=d;const u=Array.from(n.entries()).sort(([e],[t])=>"all"===e?-1:"all"===t?1:"main"===e?-1:"main"===t?1:e.localeCompare(t)),m=u.length>2;return e("div",m?{className:"flex overflow-x-auto gap-1 mb-1 bg-muted border-b border-muted/20 sticky top-0 z-10",children:u.map(([n,c])=>t(r,{variant:"unstyled",className:i("px-2 py-1 text-xs font-medium whitespace-nowrap transition-colors flex items-center gap-1.5",a===n?"bg-info text-info border-b-2 border-info":"text-muted hover:bg-muted border-b-2 border-transparent"),onClick:()=>s(n),title:c.length>20?c:void 0,children:[c.length>20?`${c.substring(0,18)}...`:c,o?.has(n)&&o.get(n)>0&&t("div",{className:"flex items-center gap-1",children:[e("span",{className:i("inline-flex items-center justify-center p-1 text-xs rounded-full",a===n?"bg-info text-info":"bg-muted text-muted"),children:o.get(n)}),l&&"all"!==n&&(l.get(n)?e(Rt,{className:"size-3 text-success"}):e(Wt,{className:"size-3 text-attention"}))]})]},n))}:{className:"py-0.5"})}const nd=e=>e.type===ir.BATCH_PROGRESS&&!!e.details?.batch_id;function rd(e){if(null==e||""===e)return Date.now();const t="number"==typeof e?e:new Date(e).getTime();return Number.isFinite(t)?t:Date.now()}function ad(e){const t=Date.now()-rd(e);return Math.max(0,Math.round(t/1e3))}function sd(e,t){const n=rd(t)-rd(e);return Math.max(0,Math.round(n/1e3))}function id(e){if(e<60)return`${e}s`;const t=Math.floor(e/60),n=e%60;return n>0?`${t}m ${n}s`:`${t}m`}function od(e){if(null==e||""===e)return;const t="number"==typeof e?e:new Date(e).getTime();return Number.isFinite(t)?t:void 0}function ld(e){const t=od(e);if(void 0!==t)return new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"}).format(new Date(t))}function cd(e){const t=e.filter(e=>"main"===rl(e)),n=t[t.length-1]??e[e.length-1];return n?.type===ir.QUESTION}function dd(e){return e.map((t,n)=>{const r=function(e){if(e.type!==ir.UPDATE)return;const t=Ed(e);if(void 0!==t.tool||void 0!==t.activity_group_id)return;const n="string"==typeof t.path&&t.path.trim()?t.path.trim():void 0;return n&&ud(e)===`Prepared and saved artifact to ${n}`?n:void 0}(t);if(!r)return t;const a=function(e,t){const n=rl(e[t]);for(let r=t-1;r>=0;r-=1){const t=e[r];if(rl(t)!==n)continue;const a=Ed(t);if("write_artifact"===a.tool&&"string"==typeof a.activity_group_id)return t;if(t.type!==ir.REQUEST_INPUT&&!Vd(t)&&"thinking"!==a.display_role){if("string"==typeof a.tool&&"write_artifact"!==a.tool)return;if(t.type===ir.ANSWER||t.type===ir.COMPLETE||t.type===ir.IDLE||t.type===ir.TERMINATED)return}}}(e,n),s=a?Ed(a):void 0;if(!s)return t;const i="string"==typeof s.activity_group_id?s.activity_group_id:void 0,o="string"==typeof s.tool_run_id?s.tool_run_id:void 0,l="string"==typeof s.tool_use_id?s.tool_use_id:void 0,c="number"==typeof s.tool_iteration?s.tool_iteration:void 0;return i?{...t,details:{...t.details,event_class:"activity",tool:"write_artifact",tool_run_id:o??"write_artifact",tool_use_id:l??o??"write_artifact",tool_iteration:c,tool_status:"completed",tool_event:"progress",activity_group_id:i,output:ud(t),path:r}}:t})}function ud(e){return e.message?"object"==typeof e.message?JSON.stringify(e.message,null,2):String(e.message).trim():""}function md({message:n,details:r,onSelectWorkstream:a}){const{t:s}=Ze(),o=Bo(r.workstreamId,r.interaction),l=r.interaction?Wo(r.interaction):"",c=l&&l!==o?l:void 0;return e("div",{className:"mx-auto w-full max-w-3xl px-1","data-workstream-id":r.workstreamId,children:t("button",{type:"button",className:i("group flex w-full items-start gap-3 border-b border-border/70 py-2 text-start text-sm text-muted","transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2","focus-visible:ring-focus focus-visible:ring-offset-2 focus-visible:ring-offset-background"),onClick:()=>a?.(r.workstreamId),children:[e(Bt,{className:"mt-0.5 size-4 shrink-0 text-muted","aria-hidden":"true"}),t("div",{className:"min-w-0 flex-1",children:[t("div",{className:"flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1",children:[e("span",{className:"font-medium text-muted",children:s("agent.workstreams")}),e("span",{className:"min-w-0 truncate text-foreground/85",children:o})]}),c&&e("div",{className:"mt-0.5 truncate text-xs text-muted/75",children:c}),e("span",{className:"sr-only",children:ud(n)})]}),e(ht,{className:"mt-0.5 size-4 shrink-0 text-muted transition-transform group-hover:translate-x-0.5 rtl:rotate-180 rtl:group-hover:-translate-x-0.5"})]})})}const pd=["agent-markdown vprose prose max-w-none break-words text-sm leading-6 text-foreground/80","prose-p:my-2 prose-p:leading-6 prose-li:my-0.5 prose-pre:my-3 prose-headings:tracking-normal","prose-headings:text-foreground prose-strong:text-foreground prose-code:text-foreground","prose-a:text-foreground prose-a:underline prose-a:decoration-muted prose-a:underline-offset-4","[&_p]:text-foreground/80 [&_li]:text-foreground/80 [&_li::marker]:text-muted"].join(" "),hd=/\[[^\]]+\]\((?:\/store\/(?:objects|collections)\/|store:|document:|document:\/\/|collection:)[^)]+\)/,fd={table:function({node:n,className:r,children:a,...s}){const i=function(e){const t=bd(e),n=Math.max(0,...t.map(e=>e.length));if(n<=1)return[];const r=function(e){const t=bd(e),n=function(e){return vd(e,"tbody").flatMap(e=>vd(e,"tr").map(e=>vd(e,"td").map(e=>gd(e).replace(/\s+/g," ").trim())))}(e),r=Math.max(0,...t.map(e=>e.length));if(r<=1)return new Set;const a=new Set;for(let e=0;e<r;e+=1){const t=n.map(t=>t[e]||"").map(e=>e.trim()).filter(Boolean);if(0===t.length)continue;const r=t.map(e=>e.length),s=Math.max(...r),i=r.reduce((e,t)=>e+t,0)/r.length,o=t.some(e=>/\S{12,}/.test(e));s<=16&&i<=10&&!o&&a.add(e)}if(a.size>=r)return new Set;return a}(e),a=Array.from({length:n},(e,n)=>{if(r.has(n))return 8;const a=t.map(e=>e[n]||"").map(e=>e.trim()).filter(Boolean);if(0===a.length)return 18;const s=a.map(e=>e.length),i=Math.max(...s),o=s.reduce((e,t)=>e+t,0)/s.length,l=function(e){return e.reduce((e,t)=>{const n=t.match(/\S+/g)||[];return Math.max(e,...n.map(e=>e.length))},0)}(a);return c=.7*o+.25*i+.45*l,d=18,u=90,Math.min(u,Math.max(d,c));var c,d,u}),s=a.reduce((e,t)=>e+t,0);return s<=0?[]:a.map((e,t)=>{const n=`${(e/s*100).toFixed(3)}%`;return{key:`agent-markdown-table-column-${t}`,compact:r.has(t),width:n}})}(n);return t("table",{...s,className:r,children:[i.length>0?e("colgroup",{children:i.map(t=>e("col",{className:t.compact?"agent-markdown-table-compact-col":void 0,style:{"--agent-markdown-table-column-width":t.width}},t.key))}):null,a]})}};function gd(e){if(!e||"object"!=typeof e)return"";const t=e;return"string"==typeof t.value?t.value:Array.isArray(t.children)?t.children.map(gd).join(""):""}function vd(e,t){if(!e||"object"!=typeof e)return[];const n=e.children;return Array.isArray(n)?n.filter(e=>{if(!e||"object"!=typeof e)return!1;const n=e;return t?n.tagName===t:"string"==typeof n.tagName}):[]}function bd(e){return vd(e).filter(e=>"thead"===e.tagName||"tbody"===e.tagName).flatMap(e=>vd(e,"tr").map(e=>vd(e).filter(e=>"th"===e.tagName||"td"===e.tagName).map(e=>gd(e).replace(/\s+/g," ").trim())))}function xd(e){if(null==e||"boolean"==typeof e)return 0;if("string"==typeof e||"number"==typeof e)return String(e).length;if(Array.isArray(e))return e.reduce((e,t)=>e+xd(t),0);if(Fe.isValidElement(e)){return xd(e.props.children)}return 0}function yd(e,t){const[n,r]=Oe(()=>ad(e));return He(()=>{if(!t)return void r(ad(e));const n=()=>r(ad(e));n();const a=window.setInterval(n,1e3);return()=>window.clearInterval(a)},[t,e]),n}function wd({children:n,message:r,workstreamId:a,className:s,artifactRunId:o,markdownComponents:l}){const{t:c}=Ze(),[d,u]=Oe(!1),m=Me(()=>xd(n),[n])>520,p="string"==typeof n||"number"==typeof n,h=p?String(n):"",f="string"==typeof n&&hd.test(n),g=r?ic(r):void 0;return He(()=>{!m&&d&&u(!1)},[d,m]),e("div",{className:"mx-auto flex w-full max-w-3xl justify-end px-1",children:t("div",{className:i("max-w-[min(44rem,82%)] rounded-[1.35rem] bg-mixer-muted/35 px-4 py-2.5","text-sm font-normal leading-6 text-foreground/90 shadow-sm shadow-black/5 dark:bg-mixer-muted/15 dark:text-foreground/88 dark:shadow-none","break-words [overflow-wrap:anywhere]",s),"data-workstream-id":a,children:[e("div",{className:i(p&&!f&&"whitespace-pre-wrap",m&&!d&&"max-h-72 overflow-hidden [mask-image:linear-gradient(to_bottom,black_76%,transparent_100%)]"),children:f?e(oa,{artifactRunId:o,components:l,className:i("agent-markdown vprose prose max-w-none break-words text-sm leading-6 text-foreground/90","prose-p:my-0 prose-p:leading-6 prose-a:text-foreground prose-a:underline prose-a:decoration-muted prose-a:underline-offset-4","[&_p+_p]:mt-2"),children:h}):n}),m&&t("button",{type:"button","aria-expanded":d,className:"mt-2 inline-flex items-center gap-1 text-sm font-medium text-muted transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",onClick:()=>u(e=>!e),children:[c(d?"agent.showLess":"agent.showMore"),e(Mt,{className:i("size-4 transition-transform",d&&"rotate-180"),"aria-hidden":"true"})]}),r&&g?e("div",{className:"mt-1.5 flex justify-end",children:e(oc,{message:r,className:"h-4 w-4"})}):null]})})}function Nd({message:r,onSendMessage:a,onSelectWorkstream:s,requestInputAnswered:o=!1,StoreLinkComponent:l,CollectionLinkComponent:c}){const d=r.type===ir.REQUEST_INPUT?yl(r):ud(r),u=Jo(r)??Ko(r),m=rl(r),p=r.workflow_run_id,h=Me(()=>r.type===ir.QUESTION?rc(d):null,[d,r.type]),f=Me(()=>({...fd,a:({node:t,ref:n,...r})=>{const a=r.href||"";if(a.includes("/store/objects")){const t=a.split("/store/objects/")[1]||"";return l?e(l,{href:a,documentId:t,children:r.children}):e(sa,{href:a,topLevelNav:!0,children:r.children})}if(a.includes("/store/collections")){const t=a.split("/store/collections/")[1]||"";return c?e(c,{href:a,collectionId:t,children:r.children}):e(sa,{href:a,topLevelNav:!0,children:r.children})}return e("a",{...r,target:"_blank",rel:"noopener noreferrer"})}}),[l,c]);if(u)return e(md,{message:r,details:u,onSelectWorkstream:s});if(r.type===ir.QUESTION){const a=h?.body??d,s=h?.attachments??[];return t(n,{children:[s.length>0&&e("div",{className:"mx-auto flex w-full max-w-3xl justify-end px-1",children:e(ec,{items:s,artifactRunId:p,align:"end",variant:"message",StoreLinkComponent:l,CollectionLinkComponent:c})}),a&&e(wd,{message:r,workstreamId:m,artifactRunId:p,markdownComponents:f,children:a})]})}const g=r.details;if(r.type===ir.REQUEST_INPUT&&g?.ux){const t=g.ux;return e("div",{className:"mx-auto w-full max-w-3xl px-1",children:e(Oo,{question:d,options:t.options,variant:t.variant,multiSelect:t.multiSelect,onSelect:e=>a?.(e),onMultiSelect:e=>a?.(e.join(", ")),allowFreeResponse:!t.options?.length||!!t.free_response,placeholder:t.free_response?.placeholder,submitLabel:t.free_response?.submit_label,onSubmit:e=>a?.(e,t.free_response?.metadata),hideBorder:!0,compact:!0,answered:o})})}const v=r.type===ir.ERROR||r.type===ir.WARNING;return t("div",{className:"mx-auto w-full max-w-3xl px-1","data-workstream-id":m,children:[v&&e("div",{className:"mb-2 text-xs font-medium text-destructive",children:r.type===ir.WARNING?"Warning":"Error"}),d&&e("div",{className:i(pd,v&&"rounded-lg border border-destructive/20 bg-destructive/5 px-3 py-2"),style:{overflowWrap:"anywhere"},children:e(oa,{artifactRunId:p,onProposalSelect:e=>a?.(e),onProposalSubmit:e=>a?.(e),components:f,children:d})})]})}function kd(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function Cd(e){return null!=e&&("string"==typeof e?e.trim().length>0:Array.isArray(e)?e.length>0:"object"!=typeof e||Object.keys(e).length>0)}function _d(e){return null!=e&&!1!==e&&("string"!=typeof e||e.trim().length>0)}function Sd(e,t){const n=e&&kd(e)?e.title:void 0;return"string"==typeof n&&n.trim()?n:t.replace(/[_-]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/\b\w/g,e=>e.toUpperCase())}function Td(e){if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e)return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Id(t){return null==t||""===t?e("span",{className:"text-muted",children:"Not provided"}):"boolean"==typeof t?t?"Yes":"No":"number"==typeof t?String(t):"string"==typeof t?e("span",{className:"whitespace-pre-wrap",children:t}):Array.isArray(t)&&t.every(e=>"object"!=typeof e||null===e)?t.map(e=>Td(e)).join(", "):e("pre",{className:"max-h-40 overflow-auto whitespace-pre-wrap rounded-md bg-background/55 px-2 py-1.5 font-mono text-[12px] leading-relaxed text-foreground/80",children:Td(t)})}function zd(n,r,a){if(!Cd(n))return null;if(!kd(n))return Id(n);const s=function(e){if(!e||!kd(e))return{};const t=e.properties;return kd(t)?t:{}}(r),i=[...Object.keys(s),...Object.keys(n).filter(e=>!(e in s))].map(e=>({key:e,label:Sd(s[e],e),value:n[e]})).filter(e=>Cd(e.value));return 0===i.length?null:t("div",{className:"space-y-2 text-start",children:[a?e("div",{className:"text-xs font-medium uppercase tracking-normal text-muted",children:a}):null,e("dl",{className:"space-y-2",children:i.map(n=>t("div",{className:"grid gap-1 sm:grid-cols-[minmax(7rem,32%)_1fr] sm:gap-3",children:[e("dt",{className:"text-xs font-medium text-muted",children:n.label}),e("dd",{className:"min-w-0 break-words text-sm text-foreground",children:Id(n.value)})]},n.key))})]})}function Rd({data:t,schema:n,title:r,template:a,prependFriendlyMessage:s,timestamp:i,isSummaryView:o,messageItemClassNames:l,messageStyleOverrides:c,StoreLinkComponent:d,CollectionLinkComponent:u}){const m=s?.trim()||("string"==typeof t?t.trim():""),p=a?.({data:t??s,schema:n,title:r});if(!_d(p)&&m){const t={type:ir.QUESTION,message:m,timestamp:rd(i),workflow_run_id:"",workstream_id:"main"};return o?e(Nd,{message:t,StoreLinkComponent:d,CollectionLinkComponent:u}):e(wc,{...l,messageStyleOverrides:c,message:t})}const h=_d(p)?p:zd(t,n,r);return _d(h)?e(wd,{className:"py-3",children:h}):null}function jd({label:n,timestamp:r,className:a}){const s=function(e=!0){const[t,n]=Oe(0);return He(()=>{if(!e)return;const t=window.setInterval(()=>{n(()=>Math.floor(Math.random()*ql.length))},4e3);return()=>window.clearInterval(t)},[e]),t}(),o=yd(r,!0);return e("div",{className:i("mx-auto w-full max-w-3xl px-1",a),children:t("div",{className:"border-b border-border/70 pb-4 text-sm text-muted",children:[t("div",{className:"flex items-center gap-3",children:[e(Ol,{size:"sm",color:"blue"}),t("div",{className:"min-w-0",children:[t("div",{children:[e("span",{className:"font-medium",children:n}),t("span",{className:"ms-2 text-muted/75",children:["for ",id(o)]})]}),e("div",{className:"mt-1 truncate text-muted/80",children:ql[s]})]})]}),e("div",{className:"mt-3 ps-6",children:e(Ml,{color:"blue"})})]})})}const Pd="_summary_started_at",Ad="_summary_finished_at",Dd=new Set(["account_id","activity_group_id","activity_id","channel_id","collection_id","document_id","display_role","event_class","id","object_id","project_id","run_id","streamed","tenant_id","thread_id","tool","tool_event","tool_iteration","tool_run_id","tool_use_id","tool_status","tools","message_to_human","progress_messages","source","token_usage","checkpoint_at","checkpoint_threshold","approval_decision","approval_request","cancellation_reason",Pd,Ad,"workflow_run_id"]);function Ed(e){return kd(e.details)?e.details:{}}function $d(e){return e.replace(/[_-]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,e=>e.toUpperCase())}function Ld(e){const t=[];if("string"==typeof e.tool&&e.tool.trim()&&t.push(e.tool.trim()),Array.isArray(e.tools))for(const n of e.tools)if("string"==typeof n&&n.trim())t.push(n.trim());else if(kd(n)){const e="string"==typeof n.name?n.name:n.tool;"string"==typeof e&&e.trim()&&t.push(e.trim())}return t}function Fd(e){const t=Array.from(new Set(Ld(e)));return t.length>0?t.join(", "):void 0}function Md(e){return"number"==typeof e||"string"==typeof e?e:void 0}const Od=["query","path","file","file_name","fileName","filename","name","title","artifact","artifact_path","url","command"];function Ud(e){for(const t of Od){const n=e[t];if("string"==typeof n&&n.trim())return{key:t,value:n.trim()};if("number"==typeof n||"boolean"==typeof n)return{key:t,value:String(n)}}}function Wd(e){switch(e){case"search":return"Search";case"read":return"Read";case"edit":return"Edit";case"command":return"Bash";case"skill":return"Skill";case"discover":default:return"Tool";case"think":return"Thought"}}function Bd(e,t){switch(e){case"denied":case"denied_with_feedback":return`User declined to use ${t}.`;case"timeout":return`Approval timed out for ${t}.`;case"reviewer_denied":return`Approval reviewer denied ${t}.`;case"cancelled_after_denial":return`Cancelled ${t} after another tool was denied.`;default:return}}function Vd(e){if(e.type!==ir.QUESTION)return;const t=ud(e).trim().toLowerCase();return"allow_once"===t||"allow_for_run"===t||"deny"===t?t:void 0}function qd(e,t){const n=[];return e.forEach((r,a)=>{if(r.type!==ir.REQUEST_INPUT)return;const s=function(e){const t=Ed(e).tool_approval;return kd(t)?t:void 0}(r),i=function(e){const t=e?.approval_key;return"string"==typeof t&&t.trim()?t.trim():void 0}(s);if(!s||!i||t.has(i))return;const o=rl(r);let l;for(let t=a+1;t<e.length;t+=1){const n=e[t];if(rl(n)===o){if(n.type===ir.REQUEST_INPUT)break;if(n.type===ir.QUESTION){l=n;break}}}if(!l||"deny"!==Vd(l))return;const c="string"==typeof s.tool_name&&s.tool_name.trim()?s.tool_name.trim():"tool_action",d=function(e){const t=e.tool_title;if("string"==typeof t&&t.trim())return t.trim();const n=e.tool_name;return"string"==typeof n&&n.trim()?$d(n.trim()):"tool action"}(s),u="string"==typeof s.target&&s.target.trim()?s.target:"",m={tool_name:c,tool_title:s.tool_title,action_summary:s.action_summary,target:s.target,approval_key:i};n.push({timestamp:l.timestamp??r.timestamp,workflow_run_id:l.workflow_run_id||r.workflow_run_id,type:ir.THOUGHT,message:Bd("denied",d)??`User declined to use ${d}.`,workstream_id:o,details:{event_class:"activity",tool:c,tool_run_id:`approval:${i}`,tool_use_id:`approval:${i}`,tool_status:"error",tool_event:"failed",activity_group_id:`approval:${i}`,approval_decision:"denied",approval_request:m,input:s.input,target:u,observation:"The user declined this tool action.",source:"synthetic_tool_approval_decision"}})}),0===n.length?e:[...e,...n].sort((e,t)=>rd(e.timestamp)-rd(t.timestamp))}function Hd(e,t=160){const n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}...`:n}const Gd=["batch_id","activity_group_id","activity_id","tool_run_id","tool_use_id","streaming_id","chunk_index","tool_iteration","tool_event"];function Jd(e,t="message"){const n=function(e){for(const t of Gd){const n=e[t];if("string"==typeof n&&n.trim())return`${t}:${n.trim()}`;if("number"==typeof n||"boolean"==typeof n)return`${t}:${n}`}}(Ed(e)),r=Hd(ud(e),96);return[t,e.workstream_id||"main",e.workflow_run_id,e.timestamp,e.type,n??r].filter(Boolean).join(":")}function Kd(e){if("single"===e.type)return Jd(e.message);if("streaming"===e.type)return`streaming:${e.streamingId}:${e.startTimestamp}:${e.workstreamId||"main"}`;const t=e.messages[0],n=e.messages[e.messages.length-1],r=t?Jd(t,"first"):e.firstTimestamp,a=n?Jd(n,"last"):e.firstTimestamp;return["group",e.toolRunId,e.firstTimestamp,r,a].filter(Boolean).join(":")}function Qd(e,t){for(let n=t-1;n>=0;n--){const t=e[n];if("single"===t.type)return t.message.timestamp;if("tool_group"===t.type)return t.firstTimestamp;if("streaming"===t.type)return t.startTimestamp}}function Yd(e){const t=Td(e).trim();return t.length>2400?`${t.slice(0,2400)}\n...`:t}function Zd(e,t,n,r){if(null!=n&&""!==n&&!(Array.isArray(n)&&0===n.length||kd(n)&&0===Object.keys(n).length))return{key:e,label:t,value:n,tone:r}}function Xd(e){const t=Ed(e),n=new Set,r=[],a=Ud(t),s=(e,a,s)=>{for(const i of a){const a=Zd(i,e,t[i],s);if(a)return n.add(i),void r.push(a)}};s("Query",["query"]),s("Input",["input","params","arguments","args"]),s("Output",["output","stdout","result","results","content","result_summary","observation","display_message"],"string"==typeof t.approval_decision?"error":void 0),s("Files",["files","outputFiles"]),s("Error",["error","stderr"],"error"),a&&n.add(a.key);const i=function(e,t){const n=Object.entries(e).reduce((e,[n,r])=>(Dd.has(n)||t.has(n)||null==r||""===r||(e[n]=r),e),{});return Object.keys(n).length>0?n:void 0}(t,n);return 0===r.length&&i&&r.push({key:"details",label:"Details",value:i}),r}function eu(e,t){if(e.type===ir.REQUEST_INPUT)return;const n=ud(e),r=Ed(e),a=ml(e),s=function(e){const t=Ed(e),n=Ld(t).join(" ").toLowerCase(),r="string"==typeof t.tool?t.tool.toLowerCase():"",a=r||n;return ml(e)?"think":r.startsWith("learn_")||n.includes("learn_")?"skill":"discover_tools"===r?"discover":e.type!==ir.THOUGHT||r?a.includes("search")||a.includes("web")||a.includes("fetch")?"search":a.includes("read")||a.includes("document")||a.includes("file")?"read":a.includes("edit")||a.includes("write")||a.includes("patch")||a.includes("create")?"edit":a.includes("bash")||a.includes("shell")||a.includes("command")||a.includes("terminal")?"command":e.type===ir.THOUGHT&&0===n.length?"think":"tool":"think"}(e),i=Ld(r),o=function(e){const t=Ud(e);if(t)return t.value;const n=e.files??e.outputFiles;return Array.isArray(n)&&n.length>0?n.map(e=>Td(e)).join(", "):void 0}(r),l="string"==typeof r.command&&r.command.trim()?r.command.trim():void 0,c=i[0]?$d(i[0]):function(e){const t=e.details,n=t?.tool||"",r=Array.isArray(t?.tools)?t.tools.map(e=>"string"==typeof e?e:e.name||e.tool||"").filter(Boolean):[],a=[n,...r].join(" ").toLowerCase(),s=n.toLowerCase(),i="string"==typeof e.message?e.message.trim():"";return"tool_preamble"===t?.display_role?a.includes("search")||a.includes("web")||a.includes("fetch")?"Preparing search":r.length>0?"Preparing tools":"Thinking":s.includes("search")?"Searching":s.includes("fetch")||s.includes("web")?"Searching the web":s.includes("read")||s.includes("document")?"Reading":s.includes("edit")||s.includes("write")||s.includes("create")?"Editing":s.includes("bash")||s.includes("shell")||s.includes("command")?"Running command":i||"Using tool"}(e),d=Bd(r.approval_decision,c),u=function(e){switch(e){case"denied":case"denied_with_feedback":return"Declined by user";case"timeout":return"Approval timed out";case"reviewer_denied":return"Denied by reviewer";case"cancelled_after_denial":return"Cancelled after denial";default:return}}(r.approval_decision),m="string"==typeof r.message_to_human&&r.message_to_human.trim()?r.message_to_human.trim():void 0,p="think"===s?n||c:Hd("command"===s?m||(d?"":n)||l||c:m||o||(d?"":n)||c),h=n?"think"===s?n:Hd(n,420):void 0,f=h&&h!==p&&!d;return p||f?{key:`${e.timestamp}-${r.activity_id||r.tool_run_id||t}`,kind:s,label:Wd(s),title:p,isPreamble:a,command:l,text:f?h:void 0,toolName:Fd(r),startedAt:Md(r[Pd])??e.timestamp,finishedAt:Md(r[Ad])??e.timestamp,status:d?"error":r.tool_status,decisionText:u,sections:Xd(e)}:void 0}function tu(e){return"string"==typeof e.activity_group_id&&e.activity_group_id.trim()?e.activity_group_id.trim():void 0}function nu(e){return"string"==typeof e.tool_use_id&&e.tool_use_id.trim()?e.tool_use_id.trim():"string"==typeof e.tool_run_id&&e.tool_run_id.trim()?e.tool_run_id.trim():"string"==typeof e.tool&&e.tool.trim()?e.tool.trim():void 0}function ru(e){const t=new Map,n=[];let r;const a=function(e){const t=new Map,n=new Map,r=(e,t,n)=>{if(!t||!n)return;const r=e.get(t)??new Set;r.add(n),e.set(t,r)};for(const a of e){const e=Ed(a),s=tu(e),i=nu(e);"started"===e.tool_event&&r(t,s,i),"string"==typeof e.approval_decision&&r(n,s,i)}return new Set([...t.entries(),...n.entries()].filter(([,e])=>e.size>1).map(([e])=>e))}(e);e.forEach((e,s)=>{const i=Ed(e);if(ml(e))return n.push({index:s,message:e}),void(r=void 0);const o=function(e,t){const n=tu(e),r=nu(e);return n?r&&t.has(n)?`activity:${n}:tool:${r}`:`activity:${n}`:"string"==typeof e.tool_use_id&&e.tool_use_id.trim()?`tool-use:${e.tool_use_id.trim()}`:"string"==typeof e.tool_run_id&&e.tool_run_id.trim()?`run:${e.tool_run_id.trim()}`:void 0}(i,a),l=!o&&function(e){const t=Ed(e);return!(e.type!==ir.UPDATE||!Array.isArray(t.updates))||e.type===ir.PLAN&&Array.isArray(t.plan)}(e)?r:void 0,c=o??l;if(!c)return void n.push({index:s,message:e});const d=t.get(c);d?d.messages.push(e):t.set(c,{index:s,messages:[e]}),!function(e){const t=Ed(e);return"plan"===t.tool||"update_plan"===t.tool}(e)?e.type===ir.PLAN&&(r=void 0):r=c});const s=Array.from(t.values()).map(({index:e,messages:t})=>{const n=[...t].sort((e,t)=>rd(e.timestamp)-rd(t.timestamp)),r=n[n.length-1],a=n.find(e=>"started"===Ed(e).tool_event),s=n.find(e=>ud(e)),i=n.findLast(e=>"string"==typeof Ed(e).approval_decision&&Boolean(ud(e))),o=n.findLast(e=>ud(e).startsWith("$ ")),l=n.findLast(e=>(e.type===ir.ERROR||e.type===ir.WARNING)&&ud(e)),c={};for(const e of n)Object.assign(c,Ed(e));l&&void 0===c.error&&void 0===c.stderr&&(c.error=ud(l)),!l&&n.some(e=>e.type===ir.PLAN&&Array.isArray(e.details?.plan))&&(c.tool_status="completed"),o&&void 0===c.command&&(c.command=ud(o)),c[Pd]=n[0]?.timestamp,c[Ad]=n[n.length-1]?.timestamp;const d="string"==typeof a?.details?.message_to_human?a.details.message_to_human:"";return{index:e,message:{...r,message:i?.message||d||(s?s.message:r.message),details:c}}});return[...n,...s].sort((e,t)=>e.index-t.index).map(({message:e})=>e)}function au({kind:t,status:n}){if("error"===n||"warning"===n)return e(Gt,{className:"size-3.5"});switch(t){case"search":return e(bt,{className:"size-3.5"});case"read":return e(kt,{className:"size-3.5"});case"edit":return e(Zt,{className:"size-3.5"});case"command":return e(Kt,{className:"size-3.5"});case"skill":case"think":return e(Yt,{className:"size-3.5"});default:return e(Qt,{className:"size-3.5"})}}function su(e){const t=[],n=od(e.startedAt),r=od(e.finishedAt),a=ld(e.startedAt),s=ld(e.finishedAt);return e.toolName&&t.push({label:"Tool",value:e.toolName}),a&&s&&void 0!==n&&void 0!==r&&n!==r?(t.push({label:"Started",value:a}),t.push({label:"Ended",value:s}),t.push({label:"Duration",value:id(sd(e.startedAt,e.finishedAt))})):(a||s)&&t.push({label:"Time",value:a??s??""}),t}function iu({hasDetailContent:n,item:r}){const a=su(r);return 0===a.length?null:e("dl",{className:i("flex flex-wrap gap-x-4 gap-y-1 text-xs",n&&"mb-3 border-b border-border/60 pb-2"),children:a.map(n=>t("div",{className:"flex min-w-0 items-baseline gap-1.5",children:[e("dt",{className:"shrink-0 text-muted",children:n.label}),e("dd",{className:"min-w-0 wrap-break-word font-medium text-foreground/80",children:n.value})]},n.label))})}function ou({section:n}){const r=n.value,a="string"==typeof r||"number"==typeof r||"boolean"==typeof r,s="Files"===n.label&&Array.isArray(r),o="Output"===n.label;if(s){const t=Array.from(new Set(r.map(e=>Td(e))));return e("div",{className:"mt-2 flex flex-wrap items-center gap-1.5",children:t.map(t=>e("span",{className:"rounded-md bg-mixer-muted/15 px-1.5 py-0.5 font-mono text-[11px] text-muted",children:Hd(t,64)},t))})}const l=i("text-xs font-medium","error"===n.tone?"text-destructive":"text-muted"),c=a&&!String(r).includes("\n")&&String(r).length<180?e("div",{className:i("break-words text-xs","error"===n.tone?"text-destructive":"text-foreground/75"),children:String(r)}):e("pre",{className:i("max-h-52 overflow-auto whitespace-pre-wrap rounded-lg px-3 py-2 font-mono text-[11px] leading-relaxed","error"===n.tone?"bg-destructive/5 text-destructive":"bg-mixer-muted/10 text-foreground/75"),children:Yd(r)});return t("div",{className:"mt-2",children:[o?null:e("div",{className:i("mb-1",l),children:n.label}),c]})}function lu(e){return"command"===e.kind?"Shell":e.label}function cu(e){if("command"!==e.kind)return e.title;const t=e.command||e.title;return t.trim().startsWith("$")?t:`$ ${t}`}function du({item:n}){const r="command"===n.kind&&n.command?cu(n):void 0,a=r||0!==n.sections.length?void 0:n.text,s=Boolean(r||a||n.sections.length),o=function(e){const t=[lu(e),cu(e)],n=su(e).map(e=>`${e.label}: ${e.value}`);n.length>0&&t.push(n.join("\n")),e.text&&t.push(e.text);for(const n of e.sections)t.push(`${n.label}\n${Yd(n.value)}`);return t.filter(Boolean).join("\n\n")}(n),[l,c]=Oe("idle"),d=Be(void 0);He(()=>()=>{void 0!==d.current&&window.clearTimeout(d.current)},[]);return t("div",{className:"relative mt-2 rounded-lg border border-border/70 bg-mixer-muted/10 p-3 shadow-sm",children:[s?e("div",{className:"absolute end-2 top-2",children:e("button",{type:"button",className:i("inline-flex size-7 shrink-0 items-center justify-center rounded-md text-muted opacity-70 transition","hover:bg-mixer-muted/20 hover:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","copied"===l&&"text-success opacity-100","failed"===l&&"text-destructive opacity-100"),onClick:()=>{(async function(e){try{if(navigator.clipboard?.writeText)return await navigator.clipboard.writeText(e),!0}catch{}if("undefined"==typeof document)return!1;const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly",""),t.style.position="fixed",t.style.insetInlineStart="-9999px",t.style.top="0",document.body.appendChild(t);try{return t.focus(),t.select(),document.execCommand("copy")}catch{return!1}finally{t.remove()}})(o).then(e=>{c(e?"copied":"failed"),void 0!==d.current&&window.clearTimeout(d.current),d.current=window.setTimeout(()=>c("idle"),2e3)})},"aria-label":"Copy tool details",title:"Copy tool details",children:e("copied"===l?Rt:vt,{className:"size-4"})})}):null,t("div",{className:i(s&&"pe-7"),children:[e(iu,{item:n,hasDetailContent:s}),r?e("pre",{className:"mb-3 whitespace-pre-wrap break-words font-mono text-sm leading-6 text-foreground/85",children:r}):null,a?e("div",{className:"mb-3 break-words text-sm leading-6 text-foreground/75",children:a}):null,n.sections.length>0?e("div",{className:"space-y-3",children:n.sections.map(t=>e(ou,{section:t},t.key))}):null]}),"failed"===l&&s?e("div",{className:"mt-3 text-xs text-destructive",children:"Copy failed"}):null]})}function uu({item:n}){const r=Boolean(n.decisionText),a=!r&&("error"===n.status||"warning"===n.status),s=su(n).length>0,o=Boolean(n.command||n.text||n.sections.length||s),[l,c]=Oe(!1),d=r?void 0:n.status;return t("div",{className:"min-w-0",children:[t("button",{type:"button",className:i("grid w-full grid-cols-[1.5rem_1fr_auto] gap-2 text-start outline-none transition-colors","focus-visible:text-foreground focus-visible:underline focus-visible:underline-offset-4",o?"cursor-pointer hover:text-foreground":"cursor-default"),onClick:()=>o&&c(e=>!e),"aria-expanded":o?l:void 0,disabled:!o,children:[e("span",{className:i("flex size-5 items-center justify-center pt-0.5",a?"text-attention":"text-muted"),children:e(au,{kind:n.kind,status:d})}),t("span",{className:"min-w-0 text-sm text-muted",children:[e("span",{className:"break-words",children:n.title}),n.decisionText?e(f,{variant:"destructive",className:"ms-2 rounded-full shadow-sm shadow-destructive/10",children:n.decisionText}):null]}),o?e(Mt,{className:i("mt-0.5 size-4 shrink-0 text-muted opacity-50 transition-transform",!l&&"-rotate-90"),"aria-hidden":"true"}):null]}),o&&l?e("div",{className:"mt-1",children:e(du,{item:n})}):null]})}function mu({item:n,artifactRunId:r,disableCollapse:a}){const{t:s}=Ze(),o=n.text??n.title,l=o.trim(),[c,d]=Oe(!1),u=l?l.split(/\r?\n/).length:0,m=l.length>520||u>6,p=s(c?"agent.showLess":"agent.showMore");return t("div",{className:"min-w-0 py-1",children:[e("div",{"data-testid":"summary-thought-prose",className:i(pd,m&&!a&&!c&&"[display:-webkit-box] overflow-hidden [-webkit-box-orient:vertical] [-webkit-line-clamp:6]"),style:{overflowWrap:"anywhere"},children:e(oa,{artifactRunId:r,components:fd,children:o})}),m&&!a?e("div",{className:"mt-1.5 flex justify-end",children:t("button",{type:"button","aria-expanded":c,className:i("inline-flex items-center gap-1 text-sm font-medium text-muted transition-colors","[text-decoration:none] hover:text-foreground hover:[text-decoration:none]","focus-visible:text-foreground focus-visible:[text-decoration:none]","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),onClick:()=>d(e=>!e),children:[p,e(Mt,{className:i("size-4 transition-transform",c&&"rotate-180"),"aria-hidden":"true"})]})}):null]})}function pu({items:t,artifactRunId:n,disablePreambleCollapse:r}){return e("div",{className:"mt-3",children:e("div",{className:"space-y-3",children:t.map(t=>t.isPreamble||"think"===t.kind?e(mu,{item:t,artifactRunId:n,disableCollapse:r},t.key):e(uu,{item:t},t.key))})})}function hu({text:t,artifactRunId:n,workstreamId:r}){return e("div",{className:"mx-auto w-full max-w-3xl px-1","data-workstream-id":r,children:e("div",{className:pd,style:{overflowWrap:"anywhere"},children:e(oa,{artifactRunId:n,components:fd,children:t})})})}function fu({message:n,startTimestamp:r,endTimestamp:a,className:s}){const{t:o}=Ze(),l=id(sd(r??n.timestamp,a??n.timestamp));return t("div",{className:i("mx-auto w-full max-w-3xl px-1",s),"data-testid":"summary-stopped-message",children:[t("div",{className:"flex items-center justify-end gap-2 text-lg font-medium text-muted sm:text-xl",children:[e("span",{children:o("agent.youStoppedAfter",{duration:l})}),e(oc,{message:n,className:"h-5 w-5"})]}),e("div",{className:"mt-5 border-b border-border/70"})]})}function gu({label:r,timestamp:a,durationSeconds:s,showElapsed:o,details:l,emptyDetailsLabel:c,defaultExpanded:d=!1,disablePreambleCollapse:u=!1,className:m,artifactRunId:p,onSendMessage:h,answeredToolApprovalRequestInputKeys:f,resolvedToolApprovalKeys:g}){const[v,b]=Oe(d),x=yd(a,o&&void 0===s),y=s??x,w=o&&void 0!==a,N=Me(()=>function(e){const t=new Set,n=[];return ru(e).forEach((e,r)=>{const a=eu(e,r);if(!a)return;const s=`${a.kind}:${a.label}:${a.title}:${a.text??""}`;t.has(s)||(t.add(s),n.push(a))}),n}(l??[]),[l]),k=Me(()=>(l??[]).filter(e=>kl(e)&&!Al(e,f??new Set,g??new Set)),[f,l,g]),C=N.length>0||k.length>0||Boolean(c);return e("div",{className:i("mx-auto w-full max-w-3xl px-1",m),children:t("div",{className:"border-b border-border/70 pb-3 text-sm text-muted",children:[t("button",{type:"button",className:i("inline-flex max-w-full items-center gap-2 text-start outline-none","focus-visible:text-foreground focus-visible:underline focus-visible:underline-offset-4",C?"cursor-pointer hover:text-foreground":"cursor-default"),onClick:()=>C&&b(e=>!e),"aria-expanded":C?v:void 0,disabled:!C,children:[e("span",{className:"min-w-0 truncate font-medium",children:r}),w?t("span",{className:"shrink-0 text-muted/75",children:["for ",id(y)]}):null,C?e(v?Mt:ht,{className:"size-4 shrink-0 opacity-50"}):null]}),C&&v?N.length>0||k.length>0?t(n,{children:[N.length>0?e(pu,{items:N,artifactRunId:p,disablePreambleCollapse:u}):null,k.length>0?e("div",{className:"mt-3 space-y-3",children:k.map(t=>{const n=t.details.ux;return e(Oo,{question:yl(t),options:n.options,variant:n.variant,multiSelect:n.multiSelect,onSelect:e=>h?.(e),onMultiSelect:e=>h?.(e.join(", ")),allowFreeResponse:!n.options?.length||!!n.free_response,placeholder:n.free_response?.placeholder,submitLabel:n.free_response?.submit_label,onSubmit:e=>h?.(e,n.free_response?.metadata),hideBorder:!0,compact:!0,className:"my-0",cardClassName:"bg-background/60 shadow-none"},Jd(t,"work-request-input"))})}):null]}):t("div",{className:"mt-3 flex items-center gap-2 text-sm text-muted",children:[e(Kt,{className:"size-4 opacity-70","aria-hidden":"true"}),e("span",{children:c})]}):null]})})}function vu({children:n,status:r}){const a="error"===r?"bg-destructive":"warning"===r?"bg-attention":"completed"===r?"bg-success":"bg-muted";return t("div",{className:"relative ps-7",children:[e("div",{className:"absolute start-2 top-0 bottom-0 w-px bg-border"}),e("div",{className:i("absolute start-[5px] top-4 size-2.5 rounded-full ring-4 ring-background",a)}),n]})}class bu extends Ke{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(e){return console.error("Message render error:",e),{hasError:!0,error:e}}componentDidUpdate(e){this.state.hasError&&e.children!==this.props.children&&this.setState({hasError:!1,error:void 0})}render(){return this.state.hasError?t("div",{className:"border-s-4 border-s-destructive bg-destructive/10 px-4 py-2 my-2 rounded-e",children:[e("p",{className:"text-sm text-destructive font-medium",children:Xe.getFixedT(null,et)("agent.failedToRenderMessage")}),e("p",{className:"text-xs text-muted mt-1 truncate",children:this.state.error?.message||"Unknown error"})]}):this.props.children}}const xu=(e,t)=>{if(e.type!==t.type)return!1;if(e.message!==t.message)return!1;const n=e.details,r=t.details;if("completed"!==n?.tool_status||"completed"!==r?.tool_status)return!1;const a="number"==typeof e.timestamp?e.timestamp:new Date(e.timestamp).getTime();return("number"==typeof t.timestamp?t.timestamp:new Date(t.timestamp).getTime())-a<2e3},yu=Fe.memo(function({messages:a,bottomRef:s,viewMode:o="stacked",isCompleted:l=!1,streamingMessages:c=new Map,onSendMessage:d,messageItemClassNames:u,messageStyleOverrides:m,toolCallGroupClassNames:p,hideToolCallsInViewMode:f,streamingMessageClassNames:g,batchProgressPanelClassNames:v,artifactRunId:b,hideWorkstreamTabs:x,workingIndicatorClassName:y,messageListClassName:w,StoreLinkComponent:N,CollectionLinkComponent:k,prependFriendlyMessage:C,initialRequestData:_,initialRequestSchema:S,initialRequestTitle:T,initialRequestTemplate:I,showInitialRequest:z,hiddenMessageTypes:R,disableAutoScroll:j=!1,renderRequestInputControls:P=!0,activeWorkstream:A,onActiveWorkstreamChange:D}){b||console.warn("[AllMessagesMixed] artifactRunId prop is missing!");const{t:E}=Ze(),$=Be(null),[L,F]=Oe("all"),M=A??L,O=Ve(e=>{void 0===A&&F(e),D?.(e)},[A,D]),U=Be(0),W=Be(null),B=Be(!1),V=Be(!1),q=c.size>0,H="sliding"===o;He(()=>{const e=$.current;if(!e)return;const t=()=>{if(V.current)return;const{scrollTop:t,scrollHeight:n,clientHeight:r}=e,a=n-t-r;B.current=a>80};return e.addEventListener("scroll",t,{passive:!0}),()=>e.removeEventListener("scroll",t)},[]);const G=Me(()=>{let e=0;return c.forEach(t=>{e+=t.text?.length||0}),Math.floor(e/200)},[c]),J=Ve(()=>{s.current&&(V.current=!0,s.current.scrollIntoView({behavior:q?"instant":"smooth"}),U.current=Date.now(),requestAnimationFrame(()=>{V.current=!1})),W.current=null},[s,q]);He(()=>{if(a.length,c.size,j)return;if(B.current)return;const e=Date.now()-U.current;if(e>=100)J();else if(null===W.current){const t=100-e;W.current=window.setTimeout(J,t)}return()=>{null!==W.current&&(clearTimeout(W.current),W.current=null)}},[a.length,c.size,G,J,j]);const K=Fe.useMemo(()=>{const e=[...a.filter(e=>!function(e){if(e.type!==ir.UPDATE)return!1;const t=Ed(e).event_class;return"document_created"===t||"document_updated"===t}(e)&&!R?.includes(e.type))].sort((e,t)=>("number"==typeof e.timestamp?e.timestamp:new Date(e.timestamp).getTime())-("number"==typeof t.timestamp?t.timestamp:new Date(t.timestamp).getTime())),t=[];for(const n of e){const e=t[t.length-1];e&&dl(e,n)||(e&&xu(e,n)||t.push(n))}return t},[a,R]),Q=Fe.useMemo(()=>{const e=function(e){const t=new Map,n=Xe.getFixedT(null,et);return t.set("all",n("agent.allMessages")),t.set("main",n("agent.main")),e.forEach(e=>{e.workstream_id&&"main"!==e.workstream_id&&"all"!==e.workstream_id&&!t.has(e.workstream_id)&&t.set(e.workstream_id,e.workstream_id)}),t}(K);return K.forEach(t=>{const n=Jo(t)??Ko(t);n&&e.set(n.workstreamId,Bo(n.workstreamId,n.interaction))}),e},[K]),Y=Fe.useMemo(()=>{if("all"!==M)return Q.get(M)??Wo(M)},[M,Q]),Z=Ve(()=>{const e=$.current;e&&(V.current=!0,"function"==typeof e.scrollTo?e.scrollTo({top:0,behavior:"smooth"}):e.scrollTop=0,requestAnimationFrame(()=>{V.current=!1}))},[]),X=Ve(e=>{O(e),requestAnimationFrame(Z)},[Z,O]),ee=Ve(()=>{O("all"),requestAnimationFrame(Z)},[Z,O]);He(()=>{"all"===M||Q.has(M)||O("all")},[M,Q,O]);const te=Fe.useMemo(()=>{const e=new Map;e.set("all",K.length);const t=function(e){return e.filter(e=>"main"===rl(e))}(K);return e.set("main",t.length),K.forEach(t=>{const n=rl(t);"main"!==n&&e.set(n,(e.get(n)||0)+1)}),e},[K]),ne=Fe.useMemo(()=>dd(sl(K,M)),[K,M]),re=Fe.useMemo(()=>Sl(ne),[ne]),ae=Fe.useMemo(()=>Tl(ne),[ne]),se=Fe.useMemo(()=>function(e){const t=new Set;return e.forEach((n,r)=>{if(!zl(n))return;const a=rl(n);for(let s=r+1;s<e.length;s+=1){const r=e[s];if(rl(r)===a){if(r.type===ir.REQUEST_INPUT)break;if(r.type===ir.QUESTION){jl(r)&&t.add(Cl(n));break}}}}),t}(ne),[ne]),ie=Fe.useMemo(()=>function(e,t){const n=new Set;return e.forEach((r,a)=>{if(!zl(r)||t)return;const s=rl(r);for(let t=a+1;t<e.length;t+=1){const r=e[t];if(rl(r)===s){if(r.type===ir.REQUEST_INPUT)break;if(r.type===ir.QUESTION){Rl(r)&&n.add(_l(r));break}}}}),n}(ne),[ne]),oe=Fe.useMemo(()=>{if(P)return;const e=$l(ne);return e?Cl(e):void 0},[ne,P]),le=Fe.useCallback(e=>e.type===ir.REQUEST_INPUT&&(oe===Cl(e)||Al(e,se,ae)),[se,oe,ae]),ce=Fe.useCallback(e=>Dl(e,ie),[ie]),de=Fe.useMemo(()=>ne.filter(e=>!ce(e)),[ne,ce]),ue=Be(Date.now()),me=(Boolean(C?.trim())||Cd(_)||void 0!==I)&&(z??!0),pe=Me(()=>ne.some(e=>e.type===ir.QUESTION),[ne]),he="all"===M&&me&&!pe,fe=Me(()=>ne.reduce((e,t)=>Math.max(e,rd(t.timestamp)),-1/0),[ne]),ge=Me(()=>ne.reduce((e,t)=>Cc(t)?e:Math.max(e,rd(t.timestamp)),-1/0),[ne]),ve=Me(()=>ne.some(e=>zl(e)&&!Al(e,se,ae)),[se,ne,ae]),be=Me(()=>function(e,t){const n=e.filter(e=>"main"===rl(e)),r=n[n.length-1]??e[e.length-1];if(!r||!Dl(r,t))return!1;const a=Vd(r);return"allow_once"===a||"allow_for_run"===a}(ne,ie),[ne,ie]),xe=Me(()=>!ve&&(!be&&(!cd(de)&&(l||!el(de)))),[de,be,ve,l]),{completeStreaming:ye,incompleteStreaming:we}=Fe.useMemo(()=>{const e=new Map,t=[];return c.forEach((n,r)=>{if(M&&"all"!==M){const e=n.workstreamId||"main";if(M!==e)return}n.startTimestamp<=ge?e.set(r,n):n.text&&t.push({id:r,data:n})}),{completeStreaming:e,incompleteStreaming:t}},[c,M,ge]),Ne=Fe.useMemo(()=>qd(Lc(ne,ye),ae),[ne,ye,ae]),ke=Fe.useMemo(()=>Ne.filter(e=>!le(e)&&!ce(e)),[Ne,le,ce]),Ce=Me(()=>{if(we.some(({data:e})=>e.text.trim().length>0))return Number.POSITIVE_INFINITY;const e=we.reduce((e,{data:t})=>Math.max(e,t.startTimestamp),-1/0);return Math.max(fe,e)},[we,fe]),_e=Fe.useMemo(()=>$c(ke,xe,Ce),[ke,xe,Ce]),Se=Fe.useMemo(()=>function(e){const t=[];let n=null;const r=()=>{n&&(t.push({type:"tool_group",messages:n.messages,firstTimestamp:n.firstTimestamp,toolRunId:n.toolRunId,toolStatus:n.toolStatus,preambleText:n.preambleText,preambleMessage:n.preambleMessage}),n=null)};for(const a of e)"tool_group"===a.type?n?(n.messages=[...n.messages,...a.messages],n.toolStatus=bl(n.toolStatus,a.toolStatus),!n.toolRunId&&a.toolRunId&&(n.toolRunId=a.toolRunId),!n.preambleMessage&&a.preambleMessage&&(n.preambleMessage=a.preambleMessage,n.preambleText=a.preambleText)):n={messages:[...a.messages],firstTimestamp:a.firstTimestamp,toolRunId:a.toolRunId,toolStatus:a.toolStatus,preambleText:a.preambleText,preambleMessage:a.preambleMessage}:(r(),t.push(a));return r(),t}(function(e,t,n){const r=new Map,a=new Map,s=new Map,i=[];for(const t of e){const e=vl(t);if(t.type===ir.REQUEST_INPUT||t.type===ir.BATCH_PROGRESS)i.push(t);else if(ml(t))i.push(t);else if(e)r.has(e)||r.set(e,{messages:[],firstTimestamp:nl(t.timestamp)}),r.get(e)?.messages.push(t);else if(pl(t)){const e=fl(t),n=hl(t);void 0!==e?(a.has(e)||a.set(e,{messages:[],firstTimestamp:nl(t.timestamp)}),a.get(e)?.messages.push(t)):n?(s.has(n)||s.set(n,{messages:[],firstTimestamp:nl(t.timestamp)}),s.get(n)?.messages.push(t)):i.push(t)}else i.push(t)}const o=[];r.forEach((e,t)=>{o.push({kind:"activity_group",activityGroupId:t,messages:e.messages,timestamp:e.firstTimestamp})}),a.forEach((e,t)=>{o.push({kind:"iteration_group",iteration:t,messages:e.messages,timestamp:e.firstTimestamp})}),s.forEach((e,t)=>{o.push({kind:"tool_run",toolRunId:t,messages:e.messages,timestamp:e.firstTimestamp})});for(const e of i)o.push({kind:"message",message:e,timestamp:nl(e.timestamp)});t.forEach((t,r)=>{if(t.text&&!cl(t,e)){if(n&&"all"!==n){const e=t.workstreamId||"main";if(n!==e)return}o.push({kind:"streaming",streamingId:r,data:t,timestamp:t.startTimestamp})}}),o.sort((e,t)=>{const n="streaming"===e.kind&&!e.data.isComplete,r="streaming"===t.kind&&!t.data.isComplete;return n&&!r?1:r&&!n?-1:e.timestamp-t.timestamp});const l=[];let c=[];const d=()=>{c.length>0&&(1!==c.length||ml(c[0])?l.push({type:"tool_group",messages:c,firstTimestamp:nl(c[0].timestamp)}):l.push({type:"single",message:c[0]}),c=[])};for(const e of o)if("streaming"===e.kind)d(),l.push({type:"streaming",streamingId:e.streamingId,text:e.data.text,workstreamId:e.data.workstreamId,startTimestamp:e.data.startTimestamp,isComplete:e.data.isComplete});else if("activity_group"===e.kind){d();const t=[...e.messages].sort((e,t)=>nl(e.timestamp)-nl(t.timestamp)),n=t.reduce((e,t)=>gl(t)||e,void 0);l.push({type:"tool_group",messages:t,firstTimestamp:e.timestamp,toolRunId:e.activityGroupId,toolStatus:n})}else if("iteration_group"===e.kind){d();const t=[...e.messages].sort((e,t)=>nl(e.timestamp)-nl(t.timestamp)),n=t.reduce((e,t)=>gl(t)||e,void 0);l.push({type:"tool_group",messages:t,firstTimestamp:e.timestamp,toolStatus:n})}else if("tool_run"===e.kind){d();const t=[...e.messages].sort((e,t)=>nl(e.timestamp)-nl(t.timestamp)),n=t.reduce((e,t)=>gl(t)||e,void 0);l.push({type:"tool_group",messages:t,firstTimestamp:e.timestamp,toolRunId:e.toolRunId,toolStatus:n})}else pl(e.message)?c.push(e.message):(d(),l.push({type:"single",message:e.message}));return d(),l}(ne,ye,M)),[ne,ye,M]),Te=Me(()=>!xe||cd(de),[de,xe]),Ie=function(e,t,n){if(!t||n)return!1;if(e.some(e=>"work"===e.type&&e.isActive))return!1;const r=e[e.length-1];return!!r&&("work"===r.type||r.message.type===ir.QUESTION)}(_e,Te,we.length>0),ze=function(e){const t=e[e.length-1];return!!t&&"message"===t.type&&t.message.type===ir.QUESTION&&1===e.length}(_e)?E("agent.preparing"):E("agent.working"),Re=0===ne.length&&me&&Te&&0===we.length,je=Me(()=>function(e,t,n){const r=e[e.length-1];return r?"work"===r.type?r.endTimestamp??r.startTimestamp:r.message.timestamp??n:t.reduce((e,t)=>{const n=Sc(t.timestamp);return!Number.isFinite(n)||n>=e.ms?e:{timestamp:t.timestamp,ms:n}},{ms:Number.POSITIVE_INFINITY}).timestamp??n}(_e,ke,ue.current),[_e,ke]),Pe=Be(je),Ae=Be(!1),De=Me(()=>{if(!Ie)return je;const e=rd(je),t=rd(Pe.current);return!Ae.current||e<t?je:Pe.current},[je,Ie]);He(()=>{Pe.current=De,Ae.current=Ie},[De,Ie]);const Ee=Me(()=>{const e=new Map,t=new Map;K.forEach(e=>{const n=rl(e);t.has(n)||t.set(n,[]),t.get(n)?.push(e)});for(const[n,r]of t.entries())if(r.length>0){const t=r.some(e=>{if([ir.COMPLETE,ir.IDLE,ir.REQUEST_INPUT,ir.TERMINATED].includes(e.type))return!0;if(e.type===ir.UPDATE&&e.details){const t=e.details;return"completed"===t.workstream_event||"completed"===t.status||"canceled"===t.status}return!1});e.set(n,t)}return e},[K]);return t("div",{ref:$,tabIndex:0,className:"flex-1 min-h-0 h-full w-full max-w-full overflow-y-auto overflow-x-hidden px-1.5 sm:px-2.5 lg:px-3 flex flex-col relative focus:outline-none","data-testid":"all-messages-mixed","data-message-count":a.length,"data-streaming-count":c.size,"data-view-mode":o,children:[e("style",{children:"\n /* Better vertical rhythm for markdown */\n .vprose > * + * {\n margin-top: 0.625rem;\n }\n .vprose > h1 + *,\n .vprose > h2 + *,\n .vprose > h3 + * {\n margin-top: 0.375rem;\n }\n /* Tables should read like part of the conversation, not a separate app grid. */\n .vprose table {\n margin-top: 0.875rem;\n margin-bottom: 0.875rem;\n border-collapse: collapse;\n width: 100%;\n background: transparent;\n }\n .vprose th,\n .vprose td {\n padding: 0.5rem 0.625rem;\n border: 0;\n border-bottom: 1px solid color-mix(in oklch, var(--border) 70%, transparent);\n background: transparent;\n text-align: left;\n }\n .vprose thead th {\n background: transparent;\n font-weight: 600;\n color: var(--muted);\n font-size: 0.75rem;\n text-transform: none;\n letter-spacing: 0;\n }\n .vprose tbody tr:hover {\n background: transparent;\n }\n /* Dark mode table styles */\n .dark .vprose th,\n .dark .vprose td {\n border-color: color-mix(in oklch, var(--border) 70%, transparent);\n }\n .dark .vprose thead th {\n background: transparent;\n color: var(--muted);\n }\n .dark .vprose tbody tr:hover {\n background: transparent;\n }\n /* Horizontal rules as section dividers */\n .vprose hr {\n margin-top: 1rem;\n margin-bottom: 1rem;\n border-color: var(--gray-5, #d1d5db);\n }\n /* Better blockquote styling */\n .vprose blockquote {\n margin-top: 0.875rem;\n margin-bottom: 0.875rem;\n padding-left: 1rem;\n border-left-width: 3px;\n border-left-color: var(--gray-6, #d1d5db);\n color: var(--gray-11, #6b7280);\n }\n /* Code blocks */\n .vprose pre {\n margin-top: 0.75rem;\n margin-bottom: 0.75rem;\n padding: 0.75rem;\n border-radius: 0.5rem;\n overflow-x: auto;\n background-color: var(--color-muted-background, #f3f4f6);\n color: var(--color-foreground, #1f2937);\n }\n .vprose pre code {\n color: inherit;\n }\n .dark .vprose pre {\n color: var(--color-foreground, #f9fafb);\n }\n\n /* Summary chat markdown: keep structure, but match the app's quieter conversation surface. */\n .agent-markdown {\n color: color-mix(in oklch, var(--foreground) 78%, transparent);\n font-size: 0.875rem;\n line-height: 1.625;\n overflow-x: auto;\n }\n .agent-markdown > * + * {\n margin-top: 0.65rem;\n }\n .agent-markdown p {\n margin-top: 0.5rem;\n margin-bottom: 0.5rem;\n }\n .agent-markdown h1,\n .agent-markdown h2,\n .agent-markdown h3,\n .agent-markdown h4 {\n margin-top: 1.2rem;\n margin-bottom: 0.45rem;\n color: var(--foreground);\n font-weight: 650;\n letter-spacing: 0;\n line-height: 1.3;\n }\n .agent-markdown h1 {\n font-size: 1.2rem;\n }\n .agent-markdown h2 {\n font-size: 1.05rem;\n }\n .agent-markdown h3,\n .agent-markdown h4 {\n font-size: 0.95rem;\n }\n .agent-markdown h1:first-child,\n .agent-markdown h2:first-child,\n .agent-markdown h3:first-child,\n .agent-markdown h4:first-child {\n margin-top: 0;\n }\n .agent-markdown hr {\n margin: 1.15rem 0;\n border: 0;\n border-top: 1px solid var(--border);\n opacity: 0.65;\n }\n .agent-markdown ul,\n .agent-markdown ol {\n margin-top: 0.55rem;\n margin-bottom: 0.55rem;\n padding-left: 1.25rem;\n }\n .agent-markdown li {\n margin-top: 0.2rem;\n margin-bottom: 0.2rem;\n padding-left: 0.1rem;\n color: inherit;\n }\n .agent-markdown li::marker {\n color: var(--muted);\n }\n .agent-markdown strong {\n color: var(--foreground);\n font-weight: 600;\n }\n .agent-markdown em {\n color: color-mix(in oklch, var(--foreground) 72%, transparent);\n }\n .agent-markdown a {\n color: var(--foreground);\n text-decoration-color: var(--muted);\n text-underline-offset: 3px;\n }\n .agent-markdown blockquote {\n margin-top: 0.85rem;\n margin-bottom: 0.85rem;\n padding-left: 0.875rem;\n border-left: 2px solid var(--border);\n color: var(--muted);\n font-style: normal;\n }\n .agent-markdown :not(pre) > code {\n border: 1px solid var(--border);\n border-radius: 0.375rem;\n background: var(--muted-background);\n color: var(--foreground);\n padding: 0.1rem 0.35rem;\n font-size: 0.8125em;\n font-weight: 500;\n }\n .agent-markdown pre {\n margin-top: 0.85rem;\n margin-bottom: 0.85rem;\n max-height: 32rem;\n overflow: auto;\n border: 1px solid var(--border);\n border-radius: 0.75rem;\n background: var(--muted-background);\n color: var(--foreground);\n padding: 0.875rem;\n font-size: 0.8125rem;\n line-height: 1.55;\n }\n .agent-markdown pre code {\n border: 0;\n background: transparent;\n color: inherit;\n padding: 0;\n font-size: inherit;\n }\n .agent-markdown table {\n display: table;\n width: 100%;\n max-width: 100%;\n margin: 0.9rem 0 1rem;\n border: 0;\n border-collapse: collapse;\n border-spacing: 0;\n font-size: 0.8125rem;\n table-layout: fixed;\n background: transparent;\n }\n .agent-markdown thead {\n background: transparent;\n }\n .agent-markdown th,\n .agent-markdown td {\n border: 0;\n border-bottom: 1px solid color-mix(in oklch, var(--border) 70%, transparent);\n background: transparent;\n padding: 0.55rem 0.75rem;\n text-align: left;\n vertical-align: top;\n overflow-wrap: anywhere;\n word-break: normal;\n white-space: normal;\n }\n .agent-markdown th {\n color: var(--muted);\n font-size: 0.75rem;\n font-weight: 600;\n letter-spacing: 0;\n text-transform: none;\n white-space: nowrap;\n }\n .agent-markdown td {\n color: inherit;\n }\n .agent-markdown th + th,\n .agent-markdown td + td {\n padding-inline-start: 1.75rem;\n }\n .agent-markdown th:first-child,\n .agent-markdown td:first-child {\n min-width: 0;\n width: auto;\n white-space: normal;\n }\n .agent-markdown col {\n width: var(--agent-markdown-table-column-width);\n }\n .agent-markdown .agent-markdown-table-compact-col {\n width: clamp(4.75rem, var(--agent-markdown-table-column-width), 7rem);\n }\n .agent-markdown tr:last-child td {\n border-bottom: 0;\n }\n .agent-markdown tbody tr:nth-child(even) {\n background: transparent;\n }\n .agent-markdown tbody tr:hover {\n background: transparent;\n }\n "}),"stacked"===o&&e("div",{className:i("sticky top-0 z-10",x&&"hidden"),children:e(td,{workstreams:Q,activeWorkstream:M,onSelectWorkstream:X,count:te,completionStatus:Ee})}),0!==ne.length||me||H&&Ie?t("div",{className:i("flex-1 flex flex-col justify-start w-full max-w-full",H?"gap-6 px-2 py-6 sm:px-4":"gap-3 pb-4",w),children:[H&&"all"!==M&&Y&&e("div",{className:"sticky top-0 z-20 -mx-2 bg-background/95 px-2 pb-2 pt-1 backdrop-blur sm:-mx-4 sm:px-4",children:t("div",{className:"mx-auto flex w-full max-w-3xl items-center gap-2 border-b border-border/70 pb-3",children:[e(h,{description:E("agent.backToMainAgent"),asChild:!0,children:e(r,{type:"button",variant:"ghost",size:"icon",className:"size-8 shrink-0 text-muted hover:text-foreground","aria-label":E("agent.backToMainAgent"),onClick:ee,children:e(Jt,{className:"size-4","aria-hidden":"true"})})}),e("div",{className:"min-w-0 flex-1 truncate text-sm font-medium text-foreground",children:Y})]})}),he&&e(Rd,{data:_,schema:S,title:T,template:I,prependFriendlyMessage:C,timestamp:ne[0]?.timestamp??Date.now(),isSummaryView:H,messageItemClassNames:u,messageStyleOverrides:m,StoreLinkComponent:N,CollectionLinkComponent:k},"initial-request"),Re&&e(jd,{label:ze,timestamp:De,className:y}),t(n,"stacked"===o?{children:[Se.map((t,n)=>{const r=n===Se.length-1;if("tool_group"===t.type){const n=t.messages[t.messages.length-1],a="completed"===t.toolStatus||"error"===t.toolStatus||"warning"===t.toolStatus,s=!l&&r&&!Xo.includes(n.type)&&!a;return f?.includes(o)?null:e(vu,{status:t.toolStatus,children:e(bu,{children:e(ed,{...p,messages:t.messages,showPulsatingCircle:s,toolRunId:t.toolRunId,toolStatus:t.toolStatus,preambleText:t.preambleText,preambleMessage:t.preambleMessage,rootClassName:i("rounded-lg border border-border bg-background/60 shadow-none",p?.rootClassName),headerClassName:i("px-3 py-2",p?.headerClassName),itemHeaderClassName:i("hover:bg-mixer-muted/20",p?.itemHeaderClassName)})})},Kd(t))}if("streaming"===t.type)return e(vu,{children:e(Nc,{...g,text:t.text,workstreamId:t.workstreamId,isComplete:t.isComplete,timestamp:t.startTimestamp,artifactRunId:b,cardClassName:i("rounded-lg border border-border bg-background/60 shadow-none",g?.cardClassName)})},Kd(t));{const a=t.message;if(le(a))return null;if(ce(a))return null;if(tl(a))return e(vu,{children:e(fu,{message:a,startTimestamp:Qd(Se,n)??a.timestamp,endTimestamp:a.timestamp})},Jd(a,"stopped"));const s=!l&&r&&!Xo.includes(a.type);return nd(a)?e(bu,{children:e(ac,{message:a,batchData:a.details,isRunning:!a.details.completed_at,...v})},`batch-${a.details.batch_id}-${a.timestamp}`):e(vu,{status:"message",children:e(bu,{children:e(wc,{...u,message:a,showPulsatingCircle:s,onSendMessage:d,requestInputAnswered:El(a,re),cardClassName:i("rounded-lg border border-border bg-background/60 shadow-none",u?.cardClassName),headerClassName:i("px-3 py-2",u?.headerClassName),contentClassName:i("bg-transparent",u?.contentClassName),messageStyleOverrides:m,StoreLinkComponent:N,CollectionLinkComponent:k})})},Jd(a))}}),we.map(({id:t,data:n})=>e(vu,{children:e(Nc,{...g,text:n.text,workstreamId:n.workstreamId,isComplete:n.isComplete,timestamp:n.startTimestamp,artifactRunId:b,cardClassName:i("rounded-lg border border-border bg-background/60 shadow-none",g?.cardClassName)})},`streaming-incomplete-${t}`)),Te&&0===we.length&&!Re&&e(vu,{children:t("div",{className:i("flex items-center gap-2 py-2 text-sm text-muted",y),children:[e(Ol,{size:"sm",color:"blue"}),e("span",{children:E("agent.working")})]})})]}:{children:[_e.map(t=>{if("work"===t.type){if(f?.includes(o))return null;const r=function(e){return e.length>0&&e.every(_c)}(t.messages);return e(gu,{label:(n=t.isActive,function(e){return e?"Working":"Worked"}(n)),status:t.status,timestamp:t.startTimestamp,durationSeconds:t.isActive?void 0:sd(t.startTimestamp,t.endTimestamp),showElapsed:!0,details:r?void 0:t.messages,defaultExpanded:t.isActive&&!r,disablePreambleCollapse:t.isActive,className:y,onSendMessage:d,answeredToolApprovalRequestInputKeys:se,resolvedToolApprovalKeys:ae},`work-${t.id}-${t.isActive?"active":"done"}-${t.status}`)}var n;if("stopped"===t.type)return e(fu,{message:t.message,startTimestamp:t.startTimestamp,endTimestamp:t.endTimestamp},Jd(t.message,"stopped-summary"));const r=t.message;return le(r)||ce(r)?null:nd(r)?e(bu,{children:e(ac,{message:r,batchData:r.details,isRunning:!r.details.completed_at,...v})},Jd(r,"batch")):e(bu,{children:e(Nd,{message:r,onSendMessage:d,onSelectWorkstream:X,requestInputAnswered:El(r,re),StoreLinkComponent:N,CollectionLinkComponent:k})},Jd(r,"summary"))}),we.map(({id:t,data:n})=>e(hu,{text:n.text,workstreamId:n.workstreamId,artifactRunId:b},`streaming-incomplete-${t}`)),Ie&&!Re&&e(gu,{label:ze,status:"running",timestamp:De,showElapsed:!0,className:y})]}),e("div",{ref:s,className:"h-2"})]}):"all"===M&&Te&&0===we.length?e("div",{className:"flex-1 px-2 py-6 sm:px-4",children:e(jd,{label:E("agent.preparing"),timestamp:ue.current,className:y})}):e("div",{className:"flex items-center justify-center h-full text-center py-8",children:e("div",{className:"flex items-center px-3 py-2 text-sm text-muted",children:E("all"===M?"agent.waitingForAgentResponse":"agent.noMessagesInWorkstream")})})]})});function wu(e,t){if(0===t)return"live";if("live"===e)return"live";const n=fs(e,t);return n>=t-1?"live":n+1}function Nu(e){return function(e){let t=0,n=e.length;for(;t<n&&"-"===e[t];)t++;for(;n>t&&"-"===e[n-1];)n--;return e.slice(t,n)}(e.trim().replace(/[^a-z0-9-_]+/gi,"-")).slice(0,80)}function ku({fixture:n,cursor:a,initialCursor:s,onCursorChange:o,autoStepMs:l,repeat:c=1,viewMode:d,className:u,title:m,showHeader:p=!0}){const{t:h}=Ze(),f=n.messages,g=s??(f.length>0?0:"live"),[v,b]=Oe(()=>hs(g,f.length)),x=a??v,y=d??"sliding",[w,N]=Oe(Boolean(l)),[k,C]=Oe(0),_=Be(null),S=Me(()=>bs(f,x,!0),[x,f]),T=S.displayedMessages,I=Me(()=>{return e=function(e,t){return e?.find(e=>e.cursor===t)}(n.streamingFrames,S.cursor),e?new Map(e.streamingMessages.map((e,t)=>[e.id??e.activityId??`stream-${t}`,e])):new Map;var e},[n.streamingFrames,S.cursor]),z=Ve(e=>{const t=hs(e,f.length);void 0===a&&b(t),o?.(t)},[a,f.length,o]);He(()=>{const e=hs(x,f.length);e!==x&&z(e)},[x,f.length,z]),He(()=>{if(!l||l<=0||!w)return;const e=window.setInterval(()=>{const e=wu(x,f.length);"live"!==e||"live"!==x?z(e):C(e=>{const t=e+1;return c>0&&t>=c?(N(!1),t):(z(f.length>0?0:"live"),t)})},l);return()=>window.clearInterval(e)},[l,x,w,f.length,c,z]);const R=T.length>0&&!el(T),j=Me(()=>$l(T),[T]),P=m??n.metadata?.title??h("agent.rewind.fixtureTitle"),A=Ve(()=>{const e={...n,metadata:{...n.metadata,title:P,exported_at:n.metadata?.exported_at??(new Date).toISOString(),message_count:f.length}},t=n.metadata?.agent_run_id??"fixture";!function(e,t){const n=new Blob([JSON.stringify(t,null,2)],{type:"application/json"}),r=URL.createObjectURL(n),a=document.createElement("a");a.href=r,a.download=e,document.body.appendChild(a),a.click(),a.remove(),URL.revokeObjectURL(r)}(`${Nu(P)||"agent-chat"}-${Nu(t)}.json`,e)},[n,f.length,P]),D=Ve(()=>{z(wu(S.cursor,f.length))},[f.length,S.cursor,z]);return t("div",{className:i("flex h-full min-h-0 w-full flex-col bg-background text-foreground",u),"data-agent-test-playback-enabled":!0,"data-agent-playback-cursor":S.cursor,"data-agent-live-message-count":f.length,"data-agent-rendered-message-count":S.renderedMessageCount,"data-agent-replay-playing":w||void 0,"data-agent-replay-loop":k,children:[p&&t("div",{className:"flex flex-wrap items-center justify-between gap-2 border-b border-border px-3 py-2",children:[t("div",{className:"min-w-0",children:[e("div",{className:"truncate text-sm font-medium",children:P}),e("div",{className:"text-xs text-muted",children:h("agent.rewind.fixtureMeta",{messageCount:f.length,loops:k})})]}),t("div",{className:"flex items-center gap-2",children:[t(r,{type:"button",variant:"secondary",size:"sm",onClick:A,children:[e(Xt,{className:"size-4"}),e("span",{className:"ms-1.5",children:h("agent.rewind.exportFixture")})]}),l&&l>0&&t(r,{type:"button",variant:"secondary",size:"sm",onClick:()=>N(e=>!e),children:[e(w?en:tn,{className:"size-4"}),e("span",{className:"ms-1.5",children:h(w?"agent.rewind.pause":"agent.rewind.resume")})]})]})]}),e("div",{className:"flex flex-shrink-0 justify-end px-2 py-1.5",children:e(ks,{cursor:S.cursor,messages:f,onChangeCursor:z})}),e(yu,{messages:T,isCompleted:R,streamingMessages:I,bottomRef:_,artifactRunId:n.metadata?.agent_run_id??"agent-chat-fixture",viewMode:y,renderRequestInputControls:!j}),j&&e(Fl,{message:j,onSendMessage:D,isLoading:!1})]})}function Cu({className:n,inline:r=!1}){return t("div",{className:i("flex items-center gap-1",r?"inline-flex":"",n),children:[e("div",{className:"w-2 h-2 bg-blue-500 rounded-full animate-[jumping_1s_infinite_ease-in-out] hover:bg-blue-600",style:{transform:"translateY(0)",animationRange:"0px -8px"}}),e("div",{className:"w-2 h-2 bg-blue-500 rounded-full animate-[jumping_1s_0.3s_infinite_ease-in-out] hover:bg-blue-600",style:{transform:"translateY(0)",animationRange:"0px -8px"}}),e("div",{className:"w-2 h-2 bg-blue-500 rounded-full animate-[jumping_1s_0.6s_infinite_ease-in-out] hover:bg-blue-600",style:{transform:"translateY(0)",animationRange:"0px -8px"}})]})}function _u(){const{client:e}=tr(),[t,n]=Oe([]),[r,a]=Oe(!0),[s,i]=Oe(!1),o=Be(0),l=Ve(async()=>{const t=o.current+1;o.current=t,a(!0),i(!1);try{const r=await e.apps.getInstalledApps("tools"),s=[];for(const e of r){const t=e,n=t.oauth_collection_ids??[],r=t.manifest.oauth_providers??{};if(!t.manifest.tool_collections)continue;const a=t.manifest.tool_collections.map(e=>lr(e)).filter(e=>"mcp"===e.type&&n.includes(e.id)),i=new Map,o=new Map,l=[];for(const e of a)if(e.oauth_provider){const t=i.get(e.oauth_provider)??[];t.push(e),i.set(e.oauth_provider,t)}else if(e.oauth_app){const t=o.get(e.oauth_app)??[];t.push(e),o.set(e.oauth_app,t)}else l.push(e);for(const[e,n]of i)s.push({key:`${t.id}:provider:${e}`,appId:t.id,appName:t.manifest.title||t.manifest.name,label:r[e]?.display_name||e,representativeId:n[0].id,memberIds:n.map(e=>e.id),memberNames:n.map(e=>e.name)});for(const[e,n]of o)s.push({key:`${t.id}:oauthapp:${e}`,appId:t.id,appName:t.manifest.title||t.manifest.name,label:e,representativeId:n[0].id,memberIds:n.map(e=>e.id),memberNames:n.map(e=>e.name)});for(const e of l)s.push({key:`${t.id}:individual:${e.id}`,appId:t.id,appName:t.manifest.title||t.manifest.name,label:e.name,representativeId:e.id,memberIds:[e.id],memberNames:[e.name]})}if(o.current!==t)return;if(n(s),a(!1),0===s.length)return;i(!0);const l=new Map,c=await Promise.all(s.map(async t=>{try{let n=l.get(t.appId);n||(n=e.remoteMcpConnections.getStatus(t.appId),l.set(t.appId,n));const r=(await n).find(e=>e.collection_id===t.representativeId);return{...t,authStatus:r}}catch{return t}}));if(o.current!==t)return;n(c)}catch(e){o.current===t&&(console.error("Failed to load MCP tool collections:",e),n([]))}finally{o.current===t&&(a(!1),i(!1))}},[e]);return He(()=>{l()},[l]),{groups:t,loading:r,statusLoading:s,reload:l}}function Su(e,t){return!!t?.length&&e.memberIds.every(e=>t.includes(e))}function Tu(e,t,n){const r=new Set(t??[]);if(n)for(const t of e.memberIds)r.delete(t);else for(const t of e.memberIds)r.add(t);return Array.from(r)}function Iu(e,t){return e.filter(e=>!0===e.authStatus?.authenticated&&!Su(e,t)).length}function zu(e,t){return e.filter(e=>!0===e.authStatus?.authenticated&&!Su(e,t)).map(e=>e.label)}function Ru({isOpen:n,onClose:r,groups:a,loading:s,statusLoading:i=!1,reload:o,disabledCollections:l,onChange:c,onConnectionChange:d,readOnly:u=!1}){const{t:m}=Ze(),p=()=>{o(),d?.()};return t(Gs,{isOpen:n,onClose:r,size:"md",className:"max-w-[92vw] sm:max-w-[620px] lg:max-w-[620px]",children:[e(Js,{children:m("mcpConnections.title")}),t(Ks,{children:[e("p",{className:"mb-4 text-sm text-muted",children:m("mcpConnections.subtitle")}),s?e("div",{className:"flex items-center justify-center py-8",children:e(xi,{className:"size-5"})}):0===a.length?e("div",{className:"py-8 text-center text-sm text-muted",children:m("mcpConnections.empty")}):e("div",{className:"space-y-1",children:a.map(n=>{const r=!Su(n,l),a=!0===n.authStatus?.authenticated;return t("div",{className:"flex items-center justify-between gap-3 py-3",children:[t("div",{className:"flex min-w-0 items-center gap-2",children:[e(a?wt:nn,{className:"size-4 shrink-0 "+(a?"text-success":"text-muted"),"aria-hidden":"true"}),e(As,{description:t("div",{className:"space-y-0.5",children:[e("div",{className:"font-medium",children:n.appName}),n.memberNames.length>1&&e("div",{className:"text-xs text-muted",children:n.memberNames.join(" · ")})]}),placement:"top",asChild:!0,children:e("span",{className:"truncate "+(r?"text-foreground":"text-muted line-through"),children:n.label})})]}),t("div",{className:"flex shrink-0 items-center gap-3",children:[i&&!n.authStatus?e(Ls,{variant:"outline",size:"sm",disabled:!0,className:"h-6 w-32 justify-center px-2 text-xs","aria-label":m("mcpConnections.checkingStatus"),title:m("mcpConnections.checkingStatus"),children:e(xi,{className:"size-3"})}):e(wi,{appId:n.appId,collectionId:n.representativeId,collectionName:n.label,authenticated:n.authStatus?.authenticated,onAuthChange:p,variant:"compact",showDisconnect:!0,readOnly:u}),c&&e(gi,{size:"sm",value:r,onChange:e=>c(Tu(n,l,e)),disabled:u,"aria-label":m(r?"mcpConnections.deactivateAria":"mcpConnections.activateAria",{name:n.label})})]})]},n.key)})})]})]})}function ju({disabledCollections:r,onChange:a,onConnectionChange:s,readOnly:i=!1,variant:o="outline",size:l="sm"}){const{t:c}=Ze(),{groups:d,loading:u,statusLoading:m,reload:p}=_u(),[h,f]=Oe(!1);if(!u&&0===d.length)return null;const g=Iu(d,r),v=zu(d,r),b=v.slice(0,2),x=v.length-b.length,y=b.length>0?`${b.join(", ")}${x>0?` +${x}`:""}`:void 0;return t(n,{children:[t("div",{className:"flex min-w-0 items-center gap-2",children:[y&&e("span",{className:"max-w-48 truncate text-muted",title:v.join(", "),children:y}),t(Ls,{variant:o,size:l,className:"shrink-0",onClick:()=>f(!0),disabled:u,"aria-label":c("mcpConnections.manage"),children:[e("span",{children:c("mcpConnections.label")}),g>0&&e(Os,{variant:"success",children:g})]})]}),e(Ru,{isOpen:h,onClose:()=>f(!1),groups:d,loading:u,reload:p,statusLoading:m,disabledCollections:r,onChange:a,onConnectionChange:s,readOnly:i})]})}function Pu({disabledCollections:n,onChange:r,onConnectionChange:a,readOnly:s=!1}){const{t:i}=Ze(),{groups:o,loading:l,statusLoading:c,reload:d}=_u();if(!l&&0===o.length)return null;const u=()=>{d(),a?.()};return l&&0===o.length?t("div",{className:"flex items-center gap-2 border-y border-border/70 py-2 text-sm text-muted",children:[e(xi,{className:"size-4"}),e("span",{children:i("mcpConnections.label")})]}):e("div",{className:"space-y-1",children:o.map(a=>{const o=!Su(a,n),l=!0===a.authStatus?.authenticated;return t("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-2 py-2 text-sm",children:[t("div",{className:"flex min-w-36 flex-1 items-center gap-2",children:[e(l?wt:nn,{className:"size-4 shrink-0 "+(l?"text-success":"text-muted"),"aria-hidden":"true"}),e(As,{description:t("div",{className:"space-y-0.5",children:[e("div",{className:"font-medium",children:a.appName}),a.memberNames.length>1&&e("div",{className:"text-xs text-muted",children:a.memberNames.join(" · ")})]}),placement:"top",asChild:!0,children:e("span",{className:"block truncate "+(o?"text-foreground":"text-muted line-through"),children:a.label})})]}),c&&!a.authStatus?e(Ls,{variant:"outline",size:"sm",disabled:!0,className:"h-6 w-32 justify-center px-2 text-xs","aria-label":i("mcpConnections.checkingStatus"),title:i("mcpConnections.checkingStatus"),children:e(xi,{className:"size-3"})}):e(wi,{appId:a.appId,collectionId:a.representativeId,collectionName:a.label,authenticated:a.authStatus?.authenticated,onAuthChange:u,variant:"compact",showDisconnect:!0,readOnly:s}),r&&t("div",{className:"flex min-w-24 items-center justify-end gap-2 text-xs",children:[e("span",{className:o?"text-muted":"text-attention",children:i(o?"mcpConnections.enabled":"mcpConnections.disabled")}),e(gi,{size:"sm",value:o,onChange:e=>r(Tu(a,n,e)),disabled:s,"aria-label":i(o?"mcpConnections.deactivateAria":"mcpConnections.activateAria",{name:a.label})})]})]},a.key)})})}function Au({disabledCollections:r,onChange:a,onConnectionChange:s,readOnly:i=!1}){const{t:o}=Ze(),{groups:l,loading:c,statusLoading:d,reload:u}=_u(),[m,p]=Oe(!1);if(!c&&0===l.length)return null;const h=Iu(l,r);return t(n,{children:[e(ci,{align:"left",trigger:e(Ls,{variant:"ghost",size:"icon",className:"size-8 rounded-md text-muted hover:bg-muted","aria-label":o("mcpConnections.settings"),title:o("mcpConnections.settings"),disabled:c,children:e("span",{className:"flex size-5 items-center justify-center rounded-[3px] border border-muted text-sm font-semibold leading-none","aria-hidden":"true",children:"/"})}),children:t(di,{onClick:()=>p(!0),isDisabled:c,children:[e("span",{children:o("mcpConnections.title")}),h>0&&e(Os,{variant:"success",children:h})]})}),e(Ru,{isOpen:m,onClose:()=>p(!1),groups:l,loading:c,reload:u,statusLoading:d,disabledCollections:r,onChange:a,onConnectionChange:s,readOnly:i})]})}const Du=[/conversation\.json$/,/-conversation\.json$/,/^tools\.json$/];function Eu(e,t,n=0){const[r,a]=Oe([]),[s,i]=Oe(!1),[o,l]=Oe(null),[c,d]=Oe(0),u=Be(0),m=Ve(async()=>{if(!t)return;const n=++u.current;i(!0),l(null);try{const r=await e.files.listArtifacts(t);if(n!==u.current)return;const s=r.map(e=>function(e,t){const n=`agents/${t}/`,r=e.indexOf(n);return-1!==r?e.slice(r+n.length):e.split("/").pop()??e}(e,t)).filter(e=>e&&!function(e){const t=e.split("/").pop()??e;return Du.some(e=>e.test(t))}(e));a(s)}catch(e){if(n!==u.current)return;l(e instanceof Error?e.message:"Failed to list artifacts"),a([])}finally{n===u.current&&i(!1)}},[e,t]);He(()=>{m()},[m,n,c]);const p=Me(()=>function(e){const t={children:[]};for(const n of e){const e=n.split("/");let r=t,a="";for(let t=0;t<e.length;t++){const n=e[t];a=a?`${a}/${n}`:n;const s=t===e.length-1;let i=r.children.find(e=>e.name===n);i||(i={name:n,path:a,isDirectory:!s,children:[]},r.children.push(i)),r=i}}const n=e=>{e.children.sort((e,t)=>e.isDirectory!==t.isDirectory?e.isDirectory?-1:1:e.name.localeCompare(t.name)),e.children.forEach(n)};return n(t),t.children}(r),[r]),h=Ve(()=>{d(e=>e+1)},[]);return{tree:p,flatFiles:r,isLoading:s,error:o,refresh:h}}function $u({node:n,depth:a,runId:s,onDownload:i,downloadingPath:o,forceExpanded:l=!1}){const[c,d]=Oe(!1),u=l||c;if(n.isDirectory)return t("div",{className:"min-w-0",children:[t(r,{variant:"unstyled",className:"flex w-full max-w-full items-center justify-start gap-1.5 rounded px-1 py-1 text-start text-sm hover:bg-muted/30",style:{paddingInlineStart:14*a+4+"px"},onClick:()=>d(e=>!e),"aria-expanded":u,children:[u?e(at,{className:"size-3.5 shrink-0 text-muted"}):e(on,{className:"size-3.5 shrink-0 text-muted cn-rtl-flip"}),e(u?ln:cn,{className:"size-4 shrink-0 text-info"}),e("span",{className:"min-w-0 truncate font-medium",title:n.path,children:(m=n.name,m.replace(/[_-]/g," ").replace(/\b\w/g,e=>e.toUpperCase()))})]}),u&&n.children.map(t=>e($u,{node:t,depth:a+1,runId:s,onDownload:i,downloadingPath:o,forceExpanded:l},`${s}:${t.path}`))]});var m;const p=o===n.path;return e("div",{className:"min-w-0",children:t(r,{variant:"unstyled",className:"flex w-full max-w-full items-center justify-start gap-1.5 rounded px-1 py-1 text-start text-sm hover:bg-muted/30",style:{paddingInlineStart:14*a+4+"px"},onClick:()=>i(n.path),disabled:p,title:n.path,children:[p?e(an,{className:"size-3.5 shrink-0 animate-spin text-info"}):e("span",{className:"size-3.5 shrink-0"}),e(dn,{className:"size-4 shrink-0 text-muted"}),e("span",{className:"min-w-0 truncate",children:n.name})]})})}function Lu(e){return e.reduce((e,t)=>t.isDirectory?e+Lu(t.children):e+1,0)}function Fu(e,t){const n=t.trim().toLocaleLowerCase();return n?e.flatMap(e=>{const t=`${e.name} ${e.path}`.toLocaleLowerCase().includes(n);if(!e.isDirectory)return t?[e]:[];const r=Fu(e.children,n);return t?[{...e}]:r.length>0?[{...e,children:r}]:[]}):e}function Mu({icon:n,children:r,action:a}){return t(x,{className:"h-full min-h-[240px] flex-col text-center text-muted",children:[n,e("span",{className:"text-sm",children:r}),a]})}const Ou=Fe.memo(function({runId:a,refreshKey:s=0}){const{t:i}=Ze(),{client:o}=tr(),{tree:l,flatFiles:c,isLoading:u,error:m,refresh:p}=Eu(o,a,s),[h,f]=Oe(null),[g,v]=Oe(""),x=g.trim(),y=Me(()=>Fu(l,x),[l,x]),w=Me(()=>Lu(y),[y]),N=Je(),k=Ve(async e=>{if(a){f(e);try{const{url:t}=await o.files.getArtifactDownloadUrl(a,e,"attachment");!function(e,t){const n=document.createElement("a");n.href=e,n.download=t,n.rel="noopener noreferrer",n.style.display="none",document.body.appendChild(n),n.click(),n.remove()}(t,e.split("/").pop()||"artifact")}catch(e){console.error("Failed to get artifact download URL:",e)}finally{f(null)}}},[o,a]);return a?u&&0===c.length?e(Mu,{icon:e(an,{className:"mb-2 size-6 animate-spin"}),children:i("agent.loadingArtifacts")}):m?e("div",{className:"flex flex-col items-center justify-center p-4 text-muted w-full",children:t(b,{title:"Fail to load Artifacts",className:"w-full",action:p,actionLabel:t(n,{children:[e(sn,{className:"size-3.5 me-1.5"}),i("agent.retry")]}),children:[e("span",{className:"break-all text-muted",children:m})," ",e("br",{})]})}):0===c.length?e(Mu,{icon:e(rn,{className:"mb-2 size-8"}),action:t(r,{variant:"ghost",size:"sm",className:"mt-2",onClick:p,children:[e(sn,{className:"size-3.5 me-1.5"}),i("agent.refresh")]}),children:i("agent.noArtifactsYet")}):t("div",{className:"flex flex-col h-full",children:[t("div",{className:"flex shrink-0 flex-col gap-2 px-3 py-2",children:[t("div",{className:"flex items-center justify-between gap-2 text-xs text-muted",children:[e("span",{children:x?`${w} of ${c.length} file${1!==c.length?"s":""}`:`${c.length} file${1!==c.length?"s":""}`}),e(r,{variant:"ghost",size:"sm",onClick:p,disabled:u,className:"h-6 w-6 p-0",children:e(sn,{className:"size-3.5 "+(u?"animate-spin":"")})})]}),e("label",{htmlFor:N,className:"sr-only",children:i("form.filter")}),e(d,{id:N,type:"text",role:"searchbox",autoComplete:"off",placeholder:i("store.searchPlaceholder"),value:g,onChange:v,clearable:!0})]}),e("div",{className:"flex-1 overflow-y-auto px-3 pb-2",children:y.length>0?e("div",{className:"min-w-0",children:y.map(t=>e($u,{node:t,depth:0,runId:a,onDownload:k,downloadingPath:h,forceExpanded:!!x},`${a}:${t.path}`))}):e("div",{className:"px-1 py-6 text-sm text-muted",children:i("agent.noContentAvailable")})})]}):e(Mu,{icon:e(rn,{className:"mb-2 size-8"}),children:"No run selected"})});function Uu(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Wu(e){if(!Uu(e))return;const t=e.browseruse??e.browser_use;if(!Uu(t))return;const n={widget:"string"==typeof t.widget?t.widget:void 0,browser_workflow_id:"string"==typeof t.browser_workflow_id?t.browser_workflow_id:void 0,workstream_id:"string"==typeof t.workstream_id?t.workstream_id:void 0,phase:"string"==typeof t.phase?t.phase:void 0,url:"string"==typeof t.url?t.url:void 0,title:"string"==typeof t.title?t.title:void 0,screenshot:"string"==typeof t.screenshot?t.screenshot:void 0,raw_screenshot:"string"==typeof t.raw_screenshot?t.raw_screenshot:void 0,prefer_raw_screenshot:"boolean"==typeof t.prefer_raw_screenshot?t.prefer_raw_screenshot:void 0,updated_at:"number"==typeof t.updated_at?t.updated_at:void 0};return n.widget&&"browseruse"!==n.widget||!(n.url||n.title||n.screenshot||n.raw_screenshot)?void 0:n}function Bu(e){return e.replace(/^artifact:\/\//,"").replace(/^artifact:/,"").replace(/^\/+/,"")}function Vu(e){return e?e.replace(/_/g," "):"browser"}function qu({state:n,runId:r,className:a,compact:s}){const{t:o}=Ze(),{client:l}=tr(),c=Za(),{openImage:d}=Gl(),[u,m]=Oe(),p=!1===n.prefer_raw_screenshot?n.screenshot||n.raw_screenshot:n.raw_screenshot||n.screenshot,h=n.title||n.url||o("agent.browserUse"),g=Me(()=>p&&Bu(p).split("/").pop()||o("agent.browserScreenshot"),[p,o]);return He(()=>{if(!p)return void m(void 0);if(p.startsWith("http://")||p.startsWith("https://"))return void m(p);if(!r)return void m(void 0);let e=!1;return(async()=>{const t=Bu(p);try{const n=es(r,t,"inline"),a=c?await c.getOrFetch(n,async()=>(await l.files.getArtifactDownloadUrl(r,t,"inline")).url):(await l.files.getArtifactDownloadUrl(r,t,"inline")).url;e||m(a)}catch(n){console.error(`Failed to resolve browser screenshot ${t}`,n),e||m(void 0)}})(),()=>{e=!0}},[l,r,p,c]),t("div",s?{className:i("overflow-hidden rounded-md border border-border/70 bg-transparent",a),children:[t("div",{className:"flex items-center gap-2 px-2 py-1.5",children:[e(un,{className:"size-3.5 shrink-0 text-info"}),t("div",{className:"min-w-0 flex-1",children:[t("div",{className:"flex min-w-0 items-center gap-1",children:[e("span",{className:"text-xs font-medium text-foreground",children:o("agent.browserPreview")}),n.phase&&t("span",{className:"truncate text-[11px] capitalize text-muted",children:["· ",Vu(n.phase)]})]}),e("div",{className:"truncate text-[11px] text-muted",title:h,children:h})]}),n.url&&e("a",{href:n.url,target:"_blank",rel:"noopener noreferrer",title:o("agent.openInNewTab"),className:i("inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-md","text-muted hover:bg-muted hover:text-foreground"),children:e(mn,{className:"size-3"})})]}),p&&(u?e("button",{type:"button",className:"block w-full bg-mixer-muted/20 text-start",onClick:()=>d(u,g),title:o("agent.clickToEnlarge"),children:e("img",{src:u,alt:g,className:"block max-h-32 w-full object-contain"})}):t("div",{className:"flex min-h-16 items-center justify-center gap-2 bg-mixer-muted/20 px-3 py-4 text-xs text-muted",children:[e(Lt,{className:"size-4"}),e("span",{children:o("agent.browserScreenshotPending")})]}))]}:{className:i("overflow-hidden rounded-md border border-muted bg-mixer-muted/10",a),children:[t("div",{className:"flex items-start justify-between gap-2 border-b border-muted px-2.5 py-2",children:[t("div",{className:"flex min-w-0 items-start gap-2",children:[e(un,{className:"mt-0.5 size-4 shrink-0 text-info"}),t("div",{className:"min-w-0",children:[e("div",{className:"text-xs font-medium text-foreground",children:o("agent.browserUse")}),e("div",{className:"truncate text-xs text-muted",title:h,children:h})]})]}),e(f,{variant:"info",className:"shrink-0 capitalize",children:Vu(n.phase)})]}),u?e("button",{type:"button",className:"block w-full bg-mixer-muted/20 text-start",onClick:()=>d(u,g),title:o("agent.clickToEnlarge"),children:e("img",{src:u,alt:g,className:"block max-h-56 w-full object-contain"})}):t("div",{className:"flex min-h-28 items-center justify-center gap-2 bg-mixer-muted/20 px-3 py-6 text-xs text-muted",children:[e(Lt,{className:"size-4"}),e("span",{children:o("agent.browserScreenshotPending")})]}),n.url&&t("div",{className:"flex items-center gap-2 border-t border-muted px-2.5 py-1.5",children:[e("a",{href:n.url,target:"_blank",rel:"noopener noreferrer",className:"min-w-0 flex-1 truncate text-xs text-info hover:underline",title:n.url,children:n.url}),e("a",{href:n.url,target:"_blank",rel:"noopener noreferrer",title:o("agent.openInNewTab"),className:i("inline-flex h-6 shrink-0 items-center justify-center rounded-md px-1.5","text-muted hover:bg-muted hover:text-foreground"),children:e(mn,{className:"size-3"})})]})]})}function Hu({documents:t,activeId:n,onSelect:a}){return 0===t.length?null:e("div",{className:"flex items-center gap-1 px-2 py-1.5",children:e(g,{align:"right",trigger:e(r,{variant:"ghost",size:"xs",title:"All opened documents",className:"flex items-center gap-1.5 max-w-[220px] text-xs h-7 px-2",children:e(at,{className:"size-3 shrink-0"})}),children:t.map(t=>e(v,{onClick:()=>a(t.id),className:t.id===n?"font-medium":"",children:e("span",{className:"truncate max-w-[200px]",children:t.title})},t.id))})})}const Gu=Fe.memo(function({isOpen:n,documents:a,activeDocumentId:s,onSelectDocument:i,onCloseDocument:o,onUpdateDocumentTitle:l,refreshKey:c,runId:d}){const{client:u}=tr(),{t:m}=Ze(),[p,f]=Oe(null),[g,v]=Oe(!1),[b,x]=Oe(null),[y,w]=Oe(null),N=Ve(async e=>{v(!0),x(null);try{const[t,n]=await Promise.all([u.store.objects.getObjectText(e),u.store.objects.retrieve(e)]);f(t.text??null);const r=n.name;w(r),r&&l?.(e,r)}catch(e){const t=e instanceof Error?e.message:m("agent.failedToLoadDocument");x(t),f(null)}finally{v(!1)}},[u,l,m]);return He(()=>{s&&n&&N(s)},[s,c,n,N]),n&&0!==a.length?t("div",{className:"h-full shadow-xl border border-muted/20 overflow-hidden flex flex-col",children:[t("div",{className:"flex items-center justify-between px-3 py-2 border-b border-muted/20 shrink-0",children:[t("div",{className:"flex items-center gap-2 min-w-0",children:[e(Ft,{className:"size-4 text-muted shrink-0"}),e("h3",{className:"font-bold text-sm truncate",children:y||m("agent.document")})]}),t("div",{className:"flex items-center gap-1",children:[e(Hu,{documents:a,activeId:s,onSelect:i}),s&&e(sa,{href:`/store/objects/${s}#overview`,topLevelNav:!0,className:"inline-flex items-center justify-center rounded-md text-sm font-medium h-8 w-8 hover:bg-muted/20 text-muted hover:text-foreground",children:e(h,{description:m("agent.openDocument"),placement:"top",size:"xs",children:e(mn,{className:"size-4"})})}),e(r,{variant:"ghost",size:"sm",onClick:()=>s&&o(s),title:m("agent.close"),children:e(ut,{className:"size-4"})})]})]}),e("div",{className:"flex-1 overflow-y-auto px-4 py-4",children:g?t("div",{className:"flex items-center justify-center py-12",children:[e(an,{className:"size-5 animate-spin text-muted"}),e("span",{className:"ms-2 text-sm text-muted",children:m("agent.loadingDocument")})]}):b?e("div",{className:"p-4 rounded-md bg-destructive/10 text-destructive text-sm",children:b}):p?e("div",{className:"prose prose-sm dark:prose-invert max-w-none",children:e(oa,{artifactRunId:d,children:p})}):t("div",{className:"flex flex-col items-center justify-center py-12 text-muted",children:[e(Ft,{className:"size-8 mb-2"}),e("span",{className:"text-sm",children:m("agent.noContentAvailable")})]})})]}):null});const Ju=Fe.memo(function({plan:n,workstreamStatus:a,isOpen:s,onClose:o,plans:l=[],activePlanIndex:c=0,onChangePlan:d=()=>{}}){const{t:u}=Ze();if(!s)return null;const m=n.plan||[],p=m.length,h=m.reduce((e,t)=>t?.id&&("completed"===a.get(t.id.toString())||"completed"===t.status)?e+1:e,0),f=p>0?Math.round(h/p*100):0,g=l.length>0?l.length-c:1,v=l[c]?.timestamp;return 0===m.length?e("div",{className:"h-full overflow-hidden",children:t(x,{className:"h-full min-h-[240px] flex-col text-center text-muted",children:[e(pn,{className:"mb-2 size-8"}),e("span",{className:"text-sm",children:u("agent.noPlanAvailable")})]})}):e("div",{className:"h-full overflow-hidden",children:t("div",{className:"flex h-full flex-col gap-4 overflow-y-auto px-2 py-3",children:[t("div",{className:"space-y-2",children:[t("div",{className:"flex items-start justify-between gap-3",children:[t("div",{className:"min-w-0",children:[e("div",{className:"text-sm font-medium text-foreground",children:u("agent.taskProgress")}),e("div",{className:"text-xs text-muted",children:u("agent.tasksCompleted",{completed:h,total:p})})]}),l.length>1&&t("div",{className:"flex shrink-0 items-center gap-1 text-xs text-muted",children:[e(r,{variant:"ghost",size:"icon",className:"size-7",onClick:()=>d(Math.min(l.length-1,c+1)),disabled:c>=l.length-1,"aria-label":u("agent.olderPlan"),title:u("agent.olderPlan"),children:e(pt,{className:"size-4","aria-hidden":"true"})}),t("div",{className:"min-w-20 text-center",children:[t("div",{className:"font-medium text-foreground",children:[g,"/",l.length]}),e("div",{className:"truncate",children:v?new Date(v).toLocaleTimeString():u("agent.unknownTime")})]}),e(r,{variant:"ghost",size:"icon",className:"size-7",onClick:()=>d(Math.max(0,c-1)),disabled:c<=0,"aria-label":u("agent.newerPlan"),title:u("agent.newerPlan"),children:e(ht,{className:"size-4","aria-hidden":"true"})})]})]}),e("div",{className:"h-2 overflow-hidden rounded-full bg-mixer-muted/20",role:"progressbar","aria-valuemin":0,"aria-valuemax":p,"aria-valuenow":h,"aria-label":u("agent.taskProgress"),children:e("div",{className:"h-full rounded-full bg-success transition-all duration-300",style:{width:`${f}%`}})})]}),e("ol",{className:"divide-y divide-border/60",children:m.map((n,r)=>{const s=n.id?n.id.toString():`task-${r}`,o=n.goal||`Task ${r+1}`,l=n.id?`task-${n.id.toString()}`:`task-${o}-${n.status||"pending"}`;let c=n.status||"pending";a.has(s)&&(c=a.get(s));let d=hn,m="text-muted";"in_progress"===c?(d=Wt,m="text-info"):"completed"===c&&(d=Rt,m="text-success");const p=u("completed"===c?"agent.completed":"in_progress"===c?"agent.inProgress":"agent.pending");return t("li",{className:"grid grid-cols-[auto_minmax(0,1fr)_auto] items-start gap-3 px-1 py-3",children:[e("span",{className:"mt-0.5 min-w-5 text-center text-xs font-medium tabular-nums text-muted/80",children:s}),e("span",{className:"min-w-0 text-sm leading-5 text-foreground/85",children:o}),t("span",{className:i("flex items-center gap-1.5 text-xs font-medium",m),children:[e(d,{className:"size-3.5 shrink-0","aria-hidden":"true"}),e("span",{children:p})]})]},l)})}),(()=>{const n=new Set(m.filter(e=>e?.id).map(e=>e.id.toString())),r=Array.from(a.entries()).filter(([e])=>"main"!==e&&!n.has(e));return r.length>0?t("div",{className:"mt-1 px-1 py-2",children:[e("div",{className:"mb-2 text-xs font-medium text-muted",children:u("agent.workstreams")}),e("div",{className:"divide-y divide-border/60",children:r.map(([n,r])=>{let a=hn,s="text-muted",o=u("agent.pending");return"in_progress"===r?(a=Wt,s="text-info",o=u("agent.inProgress")):"completed"===r&&(a=Rt,s="text-success",o=u("agent.completed")),t("div",{className:"flex items-center gap-2 py-2",children:[e(a,{className:i("size-3.5 shrink-0",s)}),e("span",{className:"min-w-0 flex-1 truncate text-xs font-medium text-foreground/80",children:n}),e("span",{className:"text-xs font-medium text-muted",children:o})]},n)})})]}):null})()]})})});function Ku({icon:n,children:r}){return t(x,{className:"h-full min-h-[240px] flex-col text-center text-muted",children:[n,e("span",{className:"text-sm",children:r})]})}function Qu({files:n}){const{t:r}=Ze(),a=Me(()=>n?Array.from(n.values()):[],[n]),s=t=>{switch(t){case cr.UPLOADING:case cr.PROCESSING:return e(an,{className:"size-4 animate-spin text-info"});case cr.READY:return e(bn,{className:"size-4 text-success"});case cr.ERROR:return e(vn,{className:"size-4 text-destructive"});default:return e(Ft,{className:"size-4 text-muted"})}},i=t=>{switch(t){case cr.UPLOADING:return e(f,{variant:"info",children:r("agent.uploading")});case cr.PROCESSING:return e(f,{variant:"info",children:r("agent.processing")});case cr.READY:return e(f,{variant:"success",children:r("agent.ready")});case cr.ERROR:return e(f,{variant:"destructive",children:r("agent.error")});default:return null}};return e("div",{className:"h-full min-h-0",children:0===a.length?e(Ku,{icon:e(Ft,{className:"mb-2 size-8"}),children:r("agent.noFilesUploadedYet")}):e("div",{className:"space-y-2 p-2",children:a.map(n=>t("div",{className:"flex items-start gap-2 p-2 border border-muted rounded-md",children:[e("div",{className:"mt-0.5",children:s(n.status)}),t("div",{className:"flex-1 min-w-0",children:[t("div",{className:"flex items-center justify-between gap-2",children:[e("span",{className:"text-sm font-medium truncate",children:n.name}),i(n.status)]}),n.error&&e("div",{className:"text-xs text-destructive mt-1",children:n.error})]})]},n.id))})})}class Yu extends Fe.Component{state={hasError:!1};static getDerivedStateFromError(e){return{hasError:!0,message:e instanceof Error?e.message:String(e)}}componentDidCatch(e,t){console.error("Agent right panel section failed to render",{error:e,componentStack:t.componentStack})}render(){return this.state.hasError?t("div",{className:i("rounded-md border border-destructive bg-mixer-destructive/10 text-destructive",this.props.compact?"p-2 text-xs":"m-3 p-3 text-sm"),children:[e("div",{className:"font-medium",children:this.props.title}),e("div",{className:"mt-1 text-xs text-muted",children:this.props.description}),this.state.message&&e("div",{className:"mt-1 break-all text-[11px] text-muted",children:this.state.message})]}):this.props.children}}function Zu({workstreams:n,messages:a,runId:s}){const{t:o}=Ze(),{client:l}=tr(),c=p(),d=Me(()=>function(e){const t=new Map;for(const n of e){const e=Wu(n.details);if(!e)continue;const r=e.workstream_id||n.workstream_id||"main",a=e.updated_at??("number"==typeof n.timestamp?n.timestamp:new Date(n.timestamp).getTime()),s=t.get(r);(!s||a>=s.timestamp)&&t.set(r,{state:{...e,workstream_id:r},timestamp:a})}return new Map(Array.from(t.entries()).map(([e,t])=>[e,t.state]))}(a),[a]),u=o("agent.panelRenderErrorDescription"),m=Ve(e=>{navigator.clipboard.writeText(e),c({status:"success",title:o("agent.runIdCopied"),duration:2e3})},[o,c]),h=Ve(async e=>{try{const t=await il(l,e);t&&window.open(t,"_blank")}catch{c({status:"error",title:o("agent.failedToDownload")})}},[l,o,c]);return 0===n.length?e(Ku,{icon:e(fn,{className:"mb-2 size-8"}),children:o("agent.noActiveParallelTasks")}):t("div",{className:"h-full min-h-0 overflow-y-auto px-2 py-2",children:[e("div",{className:"px-1 pb-2 text-xs text-muted",children:o("agent.parallelWorkDescription")}),e("div",{className:"divide-y divide-border/60",children:n.map(n=>{const a="running"===n.status||"canceling"===n.status,l=Math.round(n.elapsed_ms/1e3),c=Math.max(0,Math.round(n.remaining_ms/1e3)),p=n.deadline_ms>0?Math.min(100,Math.round(n.elapsed_ms/n.deadline_ms*100)):0,g=d.get(n.workstream_id),v=n.deadline_ms>0,b=[n.phase?Wo(n.phase):void 0,l>0?o("agent.elapsed",{seconds:l}):void 0,v&&c>0?o("agent.remaining",{seconds:c}):void 0].filter(Boolean),x=(()=>{switch(n.status){case"running":return e(f,{variant:"info",children:o("agent.running")});case"canceling":return e(f,{variant:"attention",children:o("agent.canceling")});case"completed":return e(f,{variant:"done",children:o("agent.completed")});case"failed":return e(f,{variant:"destructive",children:o("agent.failed")});case"timeout":return e(f,{variant:"destructive",children:o("agent.timeout")});case"canceled":return e(f,{variant:"destructive",children:o("agent.canceled")})}})();return e(Yu,{title:o("agent.workstreamRenderError"),description:u,compact:!0,children:e("div",{className:"py-3",children:t("div",{className:"flex items-start gap-2",children:[e("span",{className:i("mt-2 size-2 shrink-0 rounded-full",Go(n.status)),"aria-hidden":"true"}),t("div",{className:"min-w-0 flex-1",children:[t("div",{className:"flex min-w-0 items-center justify-between gap-2",children:[e("span",{className:"min-w-0 truncate text-sm font-medium text-foreground",title:n.workstream_id,children:Wo(n.workstream_id)}),x]}),b.length>0&&e("div",{className:"mt-0.5 truncate text-xs text-muted",children:b.join(" · ")}),a&&v&&e("div",{className:"mt-2 h-1 rounded-full bg-muted",role:"progressbar","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":p,"aria-valuetext":o("agent.workstreamProgress",{percent:p}),children:e("div",{className:"h-full rounded-full bg-info transition-all duration-500",style:{width:`${p}%`}})}),g&&e(Yu,{title:o("agent.browserWidgetRenderError"),description:u,compact:!0,children:e(qu,{state:g,runId:s,compact:!0,className:"mt-2"})}),n.child_workflow_run_id&&t("div",{className:"mt-2 flex flex-wrap gap-1",children:[t(r,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs text-muted hover:text-foreground",onClick:()=>m(n.child_workflow_run_id),children:[e(gn,{className:"size-3 me-1"}),o("agent.copyRunId")]}),t(r,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs text-muted hover:text-foreground",onClick:()=>h(n.child_workflow_run_id),children:[e(Xt,{className:"size-3 me-1"}),o("agent.download")]})]})]})]})})},n.launch_id)})})]})}const Xu="flex items-center border-b-2 px-2 py-1.5 text-sm font-medium whitespace-nowrap cursor-pointer shrink-0",em="border-transparent text-muted-foreground hover:border-border hover:text-foreground",tm="border-primary text-primary";function nm({tabs:n,current:r,onTabChange:l,label:c,active:d}){const[u,m]=Oe(!1),p=Be(null),h=Be(!1),f=()=>{p.current&&(clearTimeout(p.current),p.current=null)},g=()=>{f(),p.current=setTimeout(()=>m(!1),150)};return He(()=>()=>clearTimeout(p.current??void 0),[]),t(a,{modal:!1,open:u,onOpenChange:e=>{f(),e&&(h.current=!1),m(e)},children:[e(s,{asChild:!0,children:t("button",{type:"button",onMouseEnter:()=>{f(),h.current=!0,m(!0)},onMouseLeave:g,className:i(Xu,d?tm:em),children:[c,e(at,{className:"ms-1 size-4"})]})}),e(o,{align:"end",className:"w-max",onMouseEnter:f,onMouseLeave:g,onCloseAutoFocus:e=>{h.current&&e.preventDefault()},children:n.map(t=>e(N,{disabled:t.disabled,onClick:()=>l(t.name),className:i(t.name===r&&"text-primary"),children:t.label},t.name))})]})}function rm({tabs:n,current:r,onTabChange:a,className:s}){const{t:o}=Ze(),l=Be(null),c=Be([]),d=Be(null),[u,m]=Oe({count:n.length,promote:!1}),p=()=>{const e=l.current;if(!e)return;const t=e.clientWidth,a=n.map((e,t)=>c.current[t]?.offsetWidth??0),s=(e,t)=>{let r=0,s=0;for(let i=0;i<n.length;i++){if(i===t)continue;const n=r+(s>0?4:0)+a[i];if(n>e)break;r=n,s+=1}return s};let i;if(a.reduce((e,t)=>e+t,0)+4*Math.max(0,n.length-1)<=t)i={count:n.length,promote:!1};else{const e=d.current?.offsetWidth??0,o=Math.max(1,s(t-e-4,-1)),l=n.findIndex(e=>e.name===r);if(l<0||l<o)i={count:o,promote:!1};else{const n=t-e-a[l]-8;i={count:s(n,l),promote:!0}}}m(e=>e.count===i.count&&e.promote===i.promote?e:i)},h=Be(p);h.current=p,Qe(()=>{h.current()}),He(()=>{const e=l.current;if(!e||"undefined"==typeof ResizeObserver)return;const t=new ResizeObserver(()=>h.current());return t.observe(e),()=>t.disconnect()},[]);const f=n.findIndex(e=>e.name===r);let g,v;if(u.promote&&f>=0){const e=n.filter((e,t)=>t!==f);g=[...e.slice(0,u.count),n[f]],v=e.slice(u.count)}else g=n.slice(0,u.count),v=n.slice(u.count);const b=v.some(e=>e.name===r),x=o("agent.moreTabs");return t("div",{ref:l,className:i("relative",s),children:[t("div",{"aria-hidden":!0,className:"pointer-events-none invisible absolute left-0 top-0 flex w-max gap-1",children:[n.map((t,n)=>e("button",{type:"button",tabIndex:-1,ref:e=>{c.current[n]=e},className:i(Xu,em),children:t.label},t.name)),t("button",{type:"button",tabIndex:-1,ref:d,className:i(Xu,em),children:[x,e(at,{className:"ms-1 size-4"})]})]}),t("div",{className:"-mb-px flex gap-1 overflow-hidden border-b",children:[g.map(t=>{const n=t.name===r;return e("button",{type:"button","aria-current":n?"page":void 0,disabled:t.disabled,onClick:()=>a(t.name),className:i(Xu,n?tm:em,"disabled:pointer-events-none disabled:opacity-50"),children:t.label},t.name)}),v.length>0&&e(nm,{tabs:v,current:r,onTabChange:a,label:x,active:b})]})]})}const am=Fe.memo(function({plan:n,workstreamStatus:a,plans:s=[],activePlanIndex:i=0,onChangePlan:o,activeWorkstreams:l=[],messages:c=[],hideWorkstreams:d=!1,openDocuments:u=[],activeDocumentId:m,onSelectDocument:p,onCloseDocument:h,onUpdateDocumentTitle:f,docRefreshKey:g=0,runId:v,processingFiles:b,showArtifacts:x=!1,artifactRefreshKey:N=0,payloadContent:k,conversationContent:C,onClose:_,defaultTab:S,activeTab:T,onTabChange:I}){const{t:z}=Ze(),[R,j]=Oe(S||"plan"),P=T??R,A=e=>{j(e),I?.(e)},D=!d&&l.length>0,E=u.length>0,$=!!b&&b.size>0,L=Ve((t,n)=>e(Yu,{title:z("agent.panelRenderError",{name:t}),description:z("agent.panelRenderErrorDescription"),children:n}),[z]),F={name:"conversation",label:"Conversation",content:C?L("Conversation",e("div",{className:"flex flex-col h-full min-h-0",children:C})):null,is_allowed:!!C},M=[...C?[F]:[],{name:"plan",label:z("agent.plan"),content:L(z("agent.plan"),n?e(Ju,{plan:n,workstreamStatus:a||new Map,isOpen:!0,onClose:_,plans:s,activePlanIndex:i,onChangePlan:o}):e(Ku,{icon:e(fn,{className:"mb-2 size-8"}),children:z("agent.noPlanAvailable")})),is_allowed:!0},{name:"workstreams",label:D?t("span",{className:"inline-flex min-w-0 items-center gap-1 whitespace-nowrap",children:[z("agent.workstreams")," ",e("span",{className:"inline-flex shrink-0 items-center justify-center rounded-full bg-info px-1.5 py-0.5 text-[10px] text-info",children:l.length})]}):z("agent.workstreams"),content:L(z("agent.workstreams"),e(Zu,{workstreams:l,messages:c,runId:v})),is_allowed:!d},{name:"documents",label:E?t("span",{className:"inline-flex min-w-0 items-center gap-1 whitespace-nowrap",children:[z("agent.documents")," ",e("span",{className:"inline-flex shrink-0 items-center justify-center rounded-full bg-info px-1.5 py-0.5 text-[10px] text-info",children:u.length})]}):z("agent.documents"),content:L(z("agent.documents"),u.length>0&&p&&h?e(Gu,{isOpen:!0,documents:u,activeDocumentId:m??null,onSelectDocument:p,onCloseDocument:h,onUpdateDocumentTitle:f,refreshKey:g,runId:v}):e(Ku,{icon:e(Ft,{className:"mb-2 size-8"}),children:z("agent.noDocumentsOpen")})),is_allowed:!0},{name:"uploads",label:$?t("span",{className:"inline-flex min-w-0 items-center gap-1 whitespace-nowrap",children:[z("agent.uploads")," ",e("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-info"})]}):z("agent.uploads"),content:L(z("agent.uploads"),e(Qu,{files:b})),is_allowed:!0},{name:"artifacts",label:z("agent.artifacts"),content:L(z("agent.artifacts"),e(Ou,{runId:v,refreshKey:N})),is_allowed:x},{name:"payload",label:z("agent.payload"),content:k?L(z("agent.payload"),e("div",{className:"overflow-y-auto",children:k})):null,is_allowed:!!k}],O=M.filter(e=>void 0===e.is_allowed||!0===e.is_allowed);return t(y,{tabs:M,current:P,onTabChange:A,fullHeight:!0,className:"px-0",children:[t("div",{className:"flex items-end justify-between shrink-0 px-1 py-1 gap-1",children:[e(rm,{tabs:O,current:P,onTabChange:A,className:"min-w-0 flex-1"}),!C&&e(r,{variant:"ghost",size:"sm",className:"shrink-0 ms-1",onClick:_,title:"Close Right Panel",children:e(Et,{className:"size-4"})})]}),e(w,{className:"flex-1 min-h-0 pt-0 pb-0"})]})});function sm(e){if(!e)return[];const t=[];for(let n=0;n<e.length;n++){const r=e[n];if("file"!==r.kind)continue;const a=r.getAsFile();if(a)if(!r.type.startsWith("image/")||a.name&&"image.png"!==a.name)t.push(a);else{const e=r.type.split("/")[1]||"png";t.push(new File([a],`pasted-image-${Date.now()}.${e}`,{type:a.type}))}}return t}function im(e,t){return{...e,details:{...e.details??{},_deliveryStatus:t}}}function om(e){const t=e.details,n=t?._messageId;if("string"==typeof n&&n)return n;const r=t?.ack;return"string"==typeof r&&r?r:void 0}function lm(e,t){const n=e?.[t];return"string"==typeof n&&n?n:void 0}function cm(e){return"workflow_run"===e?.streaming_id_scope}function dm(e){if(e.type===ir.STREAMING_CHUNK)return!1;if(e.type===ir.SYSTEM){const t=e.details;if("file_processing"===t?.system_type&&t.files)return!1}return Boolean(e.message)||function(e){return[ir.COMPLETE,ir.IDLE,ir.TERMINATED,ir.REQUEST_INPUT].includes(e.type)}(e)}function um(e){if(e)return{type:e.type,timestamp:e.timestamp,workstream_id:e.workstream_id,text:"string"==typeof e.message?e.message.slice(0,80):e.message?"[non-string]":"",display_role:e.details?.display_role,source:e.details?.source}}function mm(e,t){if(e.find(e=>e.timestamp===t.timestamp))return e;if(!t.details?._optimistic&&(t.type===ir.QUESTION||tl(t))){const n="string"==typeof t.details?.ack?t.details.ack:void 0,r=n?im(t,"consumed"):t;if(n){const a=e.filter(e=>!((e.type===t.type||tl(e))&&e.details?._optimistic&&om(e)===n));return Zo(a,r),a}if(t.type===ir.QUESTION){const n=e.filter(e=>e.type===ir.QUESTION&&e.details?._optimistic&&e.message===t.message&&(e.workstream_id??"main")===(t.workstream_id??"main"));if(1===n.length){const r=e.filter(e=>e!==n[0]);return Zo(r,t),r}}}const n=[...e];return Zo(n,t),n}function pm(e,t){const[n,r]=Oe([]),[a,s]=Oe(!1),[i,o]=Oe("loading"),[l,c]=Oe(null),[d,u]=Oe(null),[m,p]=Oe(new Map),[h,f]=Oe(0),g=Ve(()=>f(e=>e+1),[]),v=Be(null),b=Be(0),[x,y]=Oe(new Map),w=Be(new Map),N=Be(null),[k,C]=Oe(!1),_=Be(null),S=Ve(()=>{const e=N.current;e&&("raf"===e.mode?cancelAnimationFrame(e.id):clearTimeout(e.id),N.current=null)},[]),T=Ve(()=>{w.current.size>0&&(y(new Map(w.current)),C(!0),_.current&&clearTimeout(_.current),_.current=setTimeout(()=>C(!1),50)),N.current=null},[]);He(()=>{s(!el(n))},[n]),He(()=>{Yo("stream state",{agentRunId:t,messageCount:n.length,streamingCount:x.size,initialHistoryStatus:i,isCompleted:a,lastDeliveredTs:b.current,first:um(n[0]),last:um(n[n.length-1])})},[t,i,a,n,x.size]),He(()=>{const n=v.current!==t;v.current=t,n&&(r([]),o("loading"),c(null),u(null),y(new Map),p(new Map),b.current=0);const a=new AbortController,s=n?void 0:b.current||void 0;return Yo("stream start",{agentRunId:t,isNewConversation:n,since:s,streamNonce:h}),e.agents.getInternals(t).then(e=>{a.signal.aborted||(Yo("internals loaded",{agentRunId:t,status:e.status,first_workflow_run_id:e.first_workflow_run_id}),c(e.status?.toUpperCase()??null),u(e.first_workflow_run_id??null))}).catch(e=>{a.signal.aborted||console.error("Failed to check agent run status:",e)}),e.agents.streamMessages(t,e=>{if(!a.signal.aborted){if(Yo("stream message",{agentRunId:t,type:e.type,timestamp:e.timestamp,workstream_id:e.workstream_id,hasMessage:Boolean(e.message),display_role:e.details?.display_role,source:e.details?.source}),e.timestamp&&e.timestamp>b.current&&(b.current=e.timestamp),e.type===ir.STREAMING_CHUNK){const t=e.details,n=function(e){const t=e.details,n=lm(t,"streaming_id"),r=lm(t,"activity_id");return n&&cm(t)?n:r??n}(e);if(!n)return;const r=w.current.get(n)||{text:"",workstreamId:e.workstream_id,startTimestamp:Date.now(),activityId:t?.activity_id,streamingId:t?.streaming_id},a=r.text+(e.message||"");return w.current.set(n,{text:a,workstreamId:e.workstream_id,isComplete:t.is_final,startTimestamp:r.startTimestamp,activityId:t?.activity_id,streamingId:t?.streaming_id}),void(null===N.current&&(document.hidden?N.current={mode:"timeout",id:window.setTimeout(T,16)}:N.current={mode:"raf",id:requestAnimationFrame(T)}))}if(e.type===ir.SYSTEM){const t=e.details;if("file_processing"===t?.system_type&&t.files)return void p(new Map(t.files.map(e=>[e.id,e])))}if(e.type===ir.THOUGHT||e.type===ir.ANSWER){const t=function(e){const t=e.details,n=lm(t,"streaming_id"),r=lm(t,"activity_id"),a=[];return n&&cm(t)&&a.push(n),r&&a.push(r),[...new Set(a)]}(e);if(t.length>0){for(const e of t)w.current.delete(e);y(e=>{const n=new Map(e);let r=!1;for(const e of t)r=n.delete(e)||r;return r?n:e})}}e.type!==ir.COMPLETE&&e.type!==ir.IDLE||w.current.size>0&&T(),dm(e)&&r(t=>mm(t,e))}},s,a.signal,{onHistoryLoaded:e=>{if(a.signal.aborted)return;const n=e.filter(dm);Yo("history loaded",{agentRunId:t,count:e.length,timelineCount:n.length,since:s,first:um(e[0]),last:um(e[e.length-1])}),o(e.length>0?"has_messages":"empty"),n.length>0&&r(e=>n.reduce((e,t)=>(t.timestamp&&t.timestamp>b.current&&(b.current=t.timestamp),mm(e,t)),e))},onHistoryError:e=>{a.signal.aborted||(Yo("history error",{agentRunId:t,error:e instanceof Error?e.message:String(e)}),o("error"))}}).then(()=>{if(!a.signal.aborted)return Yo("stream resolved",{agentRunId:t}),e.agents.getInternals(t).then(e=>{a.signal.aborted||(Yo("internals refreshed after stream end",{agentRunId:t,status:e.status}),c(e.status?.toUpperCase()??null))}).catch(e=>{a.signal.aborted||console.error("Failed to refresh agent run status on stream end:",e)})}).catch(e=>{a.signal.aborted||(Yo("stream failed",{agentRunId:t,error:e instanceof Error?e.message:String(e)}),console.error("Failed to stream agent messages:",e))}),()=>{Yo("stream cleanup",{agentRunId:t,streamNonce:h}),a.abort(),S(),w.current.clear(),_.current&&(clearTimeout(_.current),_.current=null)}},[t,h,e.agents,T,S]),He(()=>{const e=()=>{!document.hidden&&w.current.size>0&&(S(),T())};return document.addEventListener("visibilitychange",e),()=>{document.removeEventListener("visibilitychange",e)}},[T,S]);const I=Ve(e=>{r(t=>{const n=[...t,e];return n.sort((e,t)=>("number"==typeof e.timestamp?e.timestamp:new Date(e.timestamp).getTime())-("number"==typeof t.timestamp?t.timestamp:new Date(t.timestamp).getTime())),n})},[]),z=Ve((e,t)=>{r(n=>n.map(n=>n.details?._optimistic&&om(n)===e?im(n,t):n))},[]),R=Ve(e=>{r(t=>t.filter(t=>!e(t)))},[]);return{messages:n,streamingMessages:x,isCompleted:a,initialHistoryStatus:i,debugChunkFlash:k,addOptimisticMessage:I,updateOptimisticMessageStatus:z,removeOptimisticMessages:R,reconnect:g,agentRunStatus:l,workflowRunId:d,serverFileUpdates:m}}function hm(e){if("string"==typeof e&&e.trim().length>0)return e}function fm(e,t){const n=hm(e.revision_root_id)||hm(e.revision_root)||hm(e.root_document_id)||hm(e.root_id);if(n)return n;const r=e.revision_info;if(r&&"object"==typeof r){const e=hm(r.root);if(e)return e}return t}function gm(e,t){return e.revisionRootId&&t.revisionRootId?e.revisionRootId===t.revisionRootId:t.revisionRootId?e.id===t.revisionRootId:e.revisionRootId?e.revisionRootId===t.id:e.id===t.id}function vm(e){if(function(e){return e.type.startsWith("image/")}(e)&&"undefined"!=typeof URL&&URL.createObjectURL)return URL.createObjectURL(e)}function bm(e){"undefined"!=typeof URL&&URL.revokeObjectURL&&URL.revokeObjectURL(e)}function xm({activeWorkstreams:n,className:r}){const{t:a}=Ze(),s=Me(()=>n.filter(e=>"running"===e.status||"canceling"===e.status),[n]),o=s.slice(0,3),l=Math.max(0,s.length-o.length);return 0===s.length?null:e("div",{className:i("mx-auto mb-2 w-full max-w-3xl px-1",r),"data-agent-active-workstreams":!0,children:t("output",{className:"flex flex-col gap-1.5 rounded-2xl border border-border/70 bg-background/95 p-2 text-xs text-muted shadow-lg shadow-black/5","aria-live":"polite",children:[t("div",{className:"flex items-center gap-2 px-1 font-medium",children:[e(Bt,{className:"size-3.5 text-muted","aria-hidden":"true"}),e("span",{children:a("agent.activeWorkstreams",{count:s.length})})]}),t("div",{className:"flex flex-col gap-0.5",children:[o.map(n=>{const r=Bo(n.workstream_id,n.interaction);return t("span",{className:"flex min-w-0 items-center gap-2 rounded-lg px-1 py-1 text-sm text-foreground/80",title:r,children:[e("span",{className:i("size-1.5 shrink-0 rounded-full",Go(n.status)),"aria-hidden":"true"}),e("span",{className:"truncate font-medium",children:r}),n.phase&&e("span",{className:"truncate text-xs text-muted/75",children:Wo(n.phase)})]},n.launch_id||n.workstream_id)}),l>0&&t("span",{className:"px-1 py-1 text-xs text-muted",children:["+",l]})]})]})})}class ym{_listeners=new Set;snapshot;constructor(e){this.snapshot=new wm(e,this)}subscribe=e=>(this._listeners.add(e),()=>{this._listeners.delete(e)});getSnapshot=()=>this.snapshot;notify(){this._listeners.forEach(e=>{e()})}}class wm{vertesia;_interactive=!0;_debug_mode=!1;_non_blocking_subagents=!0;_checkpoint_tokens;_visibility;_user_channels;_collection;_disabled_mcp_collections;_start=!1;_preserveRunValues=!1;_interaction;_environment;_model="";_model_options;_tool_names=[];_data;_mode="start";_scheduledWorkflowConfig;_interactionParamsSchema;_schemaVersion=0;_inputValidator;_store;constructor(e,t){this.vertesia=e,this._store=t}onStateChanged(){const e=this.clone();this._store.snapshot=e,this._store.notify()}clone(){const e=new wm(this.vertesia,this._store);return e._interactionParamsSchema=this._interactionParamsSchema,e._schemaVersion=this._schemaVersion,e._interaction=this._interaction,e._data=this._data,e._environment=this._environment,e._model=this._model,e._model_options=this._model_options?{...this._model_options}:void 0,e._tool_names=[...this._tool_names],e._interactive=this._interactive,e._debug_mode=this._debug_mode,e._non_blocking_subagents=this._non_blocking_subagents,e._checkpoint_tokens=this._checkpoint_tokens,e._visibility=this._visibility,e._user_channels=this._user_channels?[...this._user_channels]:void 0,e._inputValidator=this._inputValidator,e._start=this._start,e._collection=this._collection,e._disabled_mcp_collections=this._disabled_mcp_collections?[...this._disabled_mcp_collections]:void 0,e._preserveRunValues=this._preserveRunValues,e._mode=this._mode,e._scheduledWorkflowConfig=this._scheduledWorkflowConfig,e}set mode(e){e!==this._mode&&(this._mode=e,"schedule"!==e||this._scheduledWorkflowConfig||(this._scheduledWorkflowConfig={name:"",description:"",cron_expression:"0 9 * * *",timezone:"UTC"}),this.onStateChanged())}get mode(){return this._mode}set scheduledWorkflowConfig(e){this._scheduledWorkflowConfig=e,this.onStateChanged()}get scheduledWorkflowConfig(){return this._scheduledWorkflowConfig}updateScheduledWorkflowConfig(e){this._scheduledWorkflowConfig={...this._scheduledWorkflowConfig,...e},this.onStateChanged()}get interactive(){return this._interactive}set interactive(e){e!==this._interactive&&(this._interactive=e,this.onStateChanged())}get debug_mode(){return this._debug_mode}set debug_mode(e){e!==this._debug_mode&&(this._debug_mode=e,this.onStateChanged())}get non_blocking_subagents(){return this._non_blocking_subagents}set non_blocking_subagents(e){e!==this._non_blocking_subagents&&(this._non_blocking_subagents=e,this.onStateChanged())}get checkpoint_tokens(){return this._checkpoint_tokens}set checkpoint_tokens(e){e!==this._checkpoint_tokens&&(this._checkpoint_tokens=e,this.onStateChanged())}get visibility(){return this._visibility}set visibility(e){e!==this._visibility&&(this._visibility=e,this.onStateChanged())}get user_channels(){return this._user_channels}set user_channels(e){this._user_channels=e,this.onStateChanged()}get collection(){return this._collection}set collection(e){e!==this._collection&&(this._collection=e,this.onStateChanged())}get disabled_mcp_collections(){return this._disabled_mcp_collections}set disabled_mcp_collections(e){this._disabled_mcp_collections=e&&e.length>0?e:void 0,this.onStateChanged()}get search_scope(){return this._collection?dr.Collection:void 0}async restoreConversation(e){let t=e.interaction;if(e.version){/^[a-fA-F0-9]{24}$/.test(t)||(t=`${t}@${e.version}`)}const n=await this.vertesia.interactions.catalog.resolve(t),r=n.runtime?.environment||e.config?.environment,a=e.config?.model,s=await(r?this.vertesia.environments.retrieve(r).catch(()=>{}):Promise.resolve(void 0));this._data=e.data,this.interaction=n,null!=e.interactionParamsSchema&&(this.interactionParamsSchema=e.interactionParamsSchema),this._tool_names=e.tool_names||[],this._interactive=e.interactive,this._debug_mode=e.debug_mode??!1,this._non_blocking_subagents=e.non_blocking_subagents??!0,this._checkpoint_tokens=e.checkpoint_tokens,this._user_channels=e.user_channels,this._disabled_mcp_collections=e.disabled_mcp_collections,this._model_options=e.config?.model_options,this.collection=e.collection_id??void 0,this._model_options=e.config?.model_options,this.environment=s,a&&(this._model=a),this.onStateChanged()}get interaction(){return this._interaction}set interaction(e){if(e?.id!==this._interaction?.id){if(this._interaction=e,this.interactionParamsSchema=e?ur(e.prompts):void 0,this._inputValidator=void 0,e&&!this._preserveRunValues&&(this._model_options=e.model_options,e.runtime?.environment)){const t=e.runtime.environment;this.vertesia.environments.retrieve(t).then(e=>this.environment=e)}this.onStateChanged()}}get environment(){return this._environment}set environment(e){if(e?.id!==this._environment?.id){if(this._environment=e,!this._preserveRunValues){const t=this.interaction?.runtime?.model;t&&e&&mr(t,e.provider)?this._model=t:this._model=e?.default_model&&mr(e.default_model,e.provider)?e.default_model:""}this.onStateChanged()}}get model(){return this._model}set model(e){e!==this._model&&(this._model=e||"",this.onStateChanged())}get model_options(){return this._model_options}set model_options(e){JSON.stringify(e)!==JSON.stringify(this._model_options)&&(this._model_options=e,this.onStateChanged())}get tool_names(){return this._tool_names}set tool_names(e){this._tool_names=e,this.onStateChanged()}get data(){return this._data}set data(e){this._data=e,this.onStateChanged()}set run(e){console.log("run",e),this.onStateChanged()}set start(e){this._start!==e&&(this._start=e,this.onStateChanged())}markStarted(){this.start=!0}setMode(e){this.mode=e}setInteraction(e){this.interaction=e}setEnvironment(e){this.environment=e}setModel(e){this.model=e}setModelOptions(e){this.model_options=e}setToolNames(e){this.tool_names=e}setCollection(e){this.collection=e}setDisabledMcpCollections(e){this.disabled_mcp_collections=e}setInteractive(e){this.interactive=e}setDebugMode(e){this.debug_mode=e}setUserChannels(e){this.user_channels=e}setCheckpointTokens(e){this.checkpoint_tokens=e}setVisibility(e){this.visibility=e}setData(e){this.data=e}setPreserveRunValues(e){this.preserveRunValues=e}get start(){return this._start}get preserveRunValues(){return this._preserveRunValues}set preserveRunValues(e){this._preserveRunValues=e}get schemaVersion(){return this._schemaVersion}get interactionParamsSchema(){return this._interactionParamsSchema}set interactionParamsSchema(e){this._interactionParamsSchema!==e&&(this._interactionParamsSchema=e,this._schemaVersion+=1,e&&(this._data=this.initializeBooleanDefaults(this._data||{},e)),this.onStateChanged())}initializeBooleanDefaults(e,t){if(!t.properties)return e;const n={...e};for(const[e,r]of Object.entries(t.properties)){const t=r;"boolean"===t.type&&void 0===n[e]?n[e]=!1:"object"===t.type&&t.properties&&(n[e]=this.initializeBooleanDefaults(n[e]||{},t))}return n}reset(){if(this._start=!1,this._interactive=!0,this._debug_mode=!1,this._non_blocking_subagents=!0,this._checkpoint_tokens=void 0,this._visibility=void 0,this._user_channels=void 0,this._collection=void 0,this._disabled_mcp_collections=void 0,this._preserveRunValues=!1,this._model="",this._model_options=void 0,this._environment=void 0,this._tool_names=[],this._interaction=void 0,this._data=void 0,this._interactionParamsSchema=null,this._inputValidator=void 0,this.model=void 0,this.environment=void 0,this.onStateChanged(),location.hash){const e=window.location.origin+window.location.pathname+window.location.search;history.replaceState(null,"",e),location.hash=""}}validateInput(){if(!this._interactionParamsSchema)return{isValid:!0};if(!this._inputValidator||this._inputValidator.schema!==this._interactionParamsSchema){const e=new Ca({strict:!1});this._inputValidator={validate:e.compile(this._interactionParamsSchema),schema:this._interactionParamsSchema}}const e=this._data||{};if(!this._inputValidator.validate(e)){return{isValid:!1,errorMessage:this._inputValidator.validate.errors?this._inputValidator.validate.errors.map(e=>`${e.instancePath}: ${e.message}`).join(", "):"Invalid payload data"}}return{isValid:!0}}}const Nm=Ue(void 0);function km({children:t}){const{client:n}=tr(),[r]=Oe(()=>new ym(n)),a=Ye(r.subscribe,r.getSnapshot);return e(Nm.Provider,{value:a,children:t})}function Cm(){const e=We(Nm);if(!e)throw new Error("usePayloadBuilder must be used within a PayloadProvider");return e}function _m({title:n,variant:a="full",isTerminal:s=!1,onClose:o,isModal:l,agentRunId:c,workflowRunId:d,viewMode:u,onViewModeChange:m,showPlanPanel:p,showPlanButton:h=!0,onTogglePlanPanel:f,showPlaybackButton:g=!1,isPlaybackEnabled:v=!1,onTogglePlayback:b,onDownload:x,onExportFixture:y,resetWorkflow:w,onExportPdf:N,onShowDetails:k,allowWorkflowControl:C=!0,onClone:_,isReceivingChunks:S=!1,className:T}){const{t:I}=Ze(),z="compact"===a,R="sliding"===u?"stacked":"sliding",j=I("agent.verbose"),P=I("agent.summary"),A="stacked"===R?j:P,D=t("div",{className:i(z?"flex flex-col items-center gap-1":"flex justify-end items-center gap-2 ms-auto"),children:[h&&e("div",{className:"relative",children:t(r,{size:"compact"===a?"icon":"sm",variant:p?"primary":"ghost",onClick:f,className:i("transition-all duration-200 rounded-md","compact"===a&&"size-8 rounded-lg"),title:I("agent.toggleRightSidebar"),children:[e(pn,{className:i("size-4","full"===a&&"me-1.5")}),e("span","full"===a?{className:"font-medium text-xs",children:I(p?"agent.hideSidebar":"agent.showSidebar")}:{className:"sr-only",children:I(p?"agent.hideSidebar":"agent.showSidebar")})]})}),z?e(r,{variant:"ghost",size:"icon",onClick:()=>m(R),className:"size-8 rounded-lg",title:A,"aria-label":A,children:e("stacked"===R?xn:yn,{className:"size-4"})}):t("div",{className:"flex items-center gap-1 bg-muted rounded p-0.5 mt-2 lg:mt-0",children:[t(r,{variant:"stacked"===u?"outline":"ghost",size:"xs",onClick:()=>m("stacked"),"aria-pressed":"stacked"===u,className:"gap-1.5",children:[e(xn,{className:"size-3.5"}),j]}),t(r,{variant:"sliding"===u?"outline":"ghost",size:"xs",onClick:()=>m("sliding"),"aria-pressed":"sliding"===u,className:"gap-1.5",children:[e(yn,{className:"size-3.5"}),P]})]}),g&&b&&t(r,{type:"button",size:"compact"===a?"icon":"sm",variant:v?"primary":"ghost",onClick:b,"aria-pressed":v,"aria-label":I("agent.rewind.label"),title:I("agent.rewind.label"),className:i("transition-all duration-200 rounded-md","compact"===a&&"size-8 rounded-lg"),children:[e(wn,{className:i("size-4","full"===a&&"me-1.5")}),e("span","full"===a?{className:"font-medium text-xs",children:I("agent.rewind.label")}:{className:"sr-only",children:I("agent.rewind.label")})]}),e(Sm,{compact:z,agentRunId:c,workflowRunId:d,isModal:l,isTerminal:s,onClose:o,onDownload:x,onExportFixture:y,resetWorkflow:w,onExportPdf:N,onShowDetails:k,allowWorkflowControl:C,onClone:_}),o&&!l&&e(r,{size:"xs",variant:"ghost",onClick:o,"aria-label":I("agent.close"),children:e(Et,{className:"size-4"})})]});return e(km,"compact"===a?{children:e("div",{className:i("inline-flex items-center rounded-xl border border-border/70 bg-background/90 p-1 shadow-lg shadow-black/10 backdrop-blur",T),children:D})}:{children:t("div",{className:i("flex flex-wrap items-end justify-between py-1.5 px-2 border-b shadow-sm flex-shrink-0",T),children:[t("div",{className:"flex flex-wrap items-center gap-2",children:[t("div",{className:"flex items-center gap-1",children:[e(Bt,{className:"size-5 text-muted"}),e("span",{className:"font-medium",children:n})]}),t("span",{className:"text-xs text-muted ms-1 flex items-center gap-1.5",children:["(Agent Run ID: ",c,")",e("span",{className:i("w-2 h-2 rounded-full transition-colors duration-200",S?"bg-purple-500 shadow-[0_0_6px_2px_rgba(168,85,247,0.6)]":"bg-gray-400")})]})]}),D]})})}function Sm({compact:n=!1,agentRunId:a,workflowRunId:s,isModal:i,isTerminal:o,onClose:l,onDownload:c,onExportFixture:d,resetWorkflow:u,onExportPdf:m,onShowDetails:h,allowWorkflowControl:f=!0,onClone:b}){const{t:x}=Ze(),y=p(),{client:w}=tr(),N=Cm(),{router:C}=aa();return e(g,{align:"right",trigger:e(r,{size:n?"icon":"xs",variant:"ghost",title:x("agent.moreActions"),"aria-label":x("agent.moreActions"),className:n?"size-8 rounded-lg":void 0,children:e(Cn,{className:"size-4"})}),children:t(k,{label:"Actions",children:[i&&t(v,{onClick:()=>(e=>{const t=e.startsWith("/")?C.getTopRouter().navigator.addStickyParams(e):e;return window.open(t,"_blank"),t})(`/store/agent-runner/${a}`),children:[e($t,{className:"size-3.5 text-muted"})," ",x("agent.openInNewTab")]}),t(v,{onClick:()=>{navigator.clipboard.writeText(a),y({status:"success",title:x("agent.agentRunIdCopied"),duration:2e3})},children:[e(vt,{className:"size-3.5 text-muted"})," ",x("agent.copyAgentRunId")]}),t(v,{onClick:()=>{navigator.clipboard.writeText(s),y({status:"success",title:x("agent.workflowRunIdCopied"),duration:2e3})},children:[e(vt,{className:"size-3.5 text-muted"})," ",x("agent.copyWorkflowRunId")]}),h&&t(v,{onClick:h,children:[e(Nn,{className:"size-3.5 text-muted"})," ",x("agent.details")]}),t(v,{onClick:()=>{c?c():il(w,a).then(e=>window.open(e,"_blank"))},children:[e(Xt,{className:"size-3.5 text-muted"})," ",x("agent.downloadConversation")]}),m&&t(v,{onClick:m,children:[e(Xt,{className:"size-3.5 text-muted"})," ",x("agent.exportAsPdf")]}),d&&t(v,{onClick:d,children:[e(Xt,{className:"size-3.5 text-muted"})," ",x("agent.rewind.exportFixture")]}),l&&i&&t(v,{onClick:l,children:[e(Et,{className:"size-3.5 text-muted"})," ",x("agent.close")]}),b&&t(v,{onClick:async()=>{try{const e=await w.agents.fork(a);y({status:"success",title:x("agent.conversationCloned"),duration:2e3}),b?.(e)}catch(e){y({status:"error",title:x("agent.failedToCloneConversation"),duration:2e3})}},children:[e(kn,{className:"size-3.5 text-muted"})," ",x("agent.cloneConversation")]}),f&&!o&&t(v,{onClick:async()=>{try{return await w.agents.terminate(a,"cancel"),y({status:"success",title:x("agent.workflowCancelled"),duration:2e3}),N.reset(),u?.(),!0}catch(e){return y({status:"error",title:x("agent.failedToCancelWorkflow"),duration:2e3}),!1}},variant:"destructive",children:[e(Et,{className:"size-3.5"})," ",x("agent.cancelWorkflow")]})]})})}function Tm(e){return function(e){return"object"==typeof e&&null!==e&&"value"in e}(e)?e.value:e}function Im(e){if("stringList"===e.type)return e.value.map(e=>"string"==typeof e?e:Tm(e));if(e.multiple)return e.value.map(Tm);const t=e.value[0];return void 0===t?void 0:Tm(t)}function zm(e,t,n){e.query[t]=n}function Rm({buckets:n,name:r,placeholder:a}){const s=n.map(e=>({label:`(${e.count})`,value:e._id}));return{name:r,placeholder:a||`${r.charAt(0).toUpperCase()+r.slice(1)}`,options:s,type:"select",labelRenderer:r=>{const a=n.find(e=>e._id===r),s=a?.name||r;let i="success";if(a?.status)switch(a.status){case pr.published:i="success";break;case pr.archived:i="destructive";break;case pr.code:i="info"}const o=a?.version&&a?.status?`v${a.version} ${a.status!==pr.unknown?a.status:""}`:a?.status||(a?.version?`v${a.version}`:"");return t("div",{className:"w-full flex items-center justify-between",children:[t("div",{className:"flex flex-row flex-wrap items-center gap-2 min-w-0 flex-1",children:[e("span",{className:"text-sm truncate",children:s}),o&&e(f,{variant:i,className:"text-xs w-fit",children:o})]}),(a?.count??0)>0&&t("span",{className:"ms-2 text-xs shrink-0",children:["(",a?.count,")"]})]})},filterBy:(e,t)=>{const r=n.find(t=>t._id===e);return(r?.name||e).toLowerCase().includes(t.toLowerCase())}}}function jm(e){return`${e._id} (${e.count})`}function Pm(e){return`${e.name} (${e.count})`}function Am({buckets:e,name:t,placeholder:n,type:r,multiple:a}){return function({buckets:e,name:t,placeholder:n,type:r="select",multiple:a=!1}){return{name:t,options:e.map(e=>({label:jm(e),value:e._id})),type:r,multiple:a,placeholder:`${n??`${t.charAt(0).toUpperCase()+t.slice(1)}`}`,allowCreate:!1}}({buckets:e,name:t,placeholder:n,type:r,multiple:a})}const Dm={},Em={},$m={};function Lm(e){return"object"==typeof e&&null!==e&&"status"in e&&404===e.status}function Fm(e,t,n){let r=e[t];return r||(r=n().catch(n=>{throw Lm(n)||delete e[t],n}),e[t]=r),r}function Mm(e){const{client:t}=tr();return S(()=>Fm(Dm,e,()=>t.users.retrieve(e)),{deps:[e],condition:()=>!!e})}function Om(e){const{client:t}=tr();return S(()=>Fm(Em,e,()=>t.iam.groups.retrieve(e)),{deps:[e],condition:()=>!!e})}function Um(e){const{client:t}=tr();return S(()=>Fm($m,e,()=>t.apikeys.retrieve(e)),{deps:[e],condition:()=>!!e})}function Wm(){return e("div",{className:"size-8"})}function Bm({showTitle:n=!1,size:r="md"}){const{t:a}=Ze();return e(tp,{title:a("user.systemUser"),description:a("user.systemUserDescription"),children:t("div",{className:"flex gap-2 items-center",children:[e(C,{src:"/icon.svg",size:r}),n&&e("div",{className:"text-sm font-semibold ps-2",children:a("user.systemUser")})]})})}function Vm({showTitle:n=!1,size:r="md"}){const{t:a}=Ze();return e(tp,{title:a("user.allProjectMembers"),description:a("user.allProjectMembersDescription"),children:t("div",{className:"flex gap-2 items-center",children:[e(_n,{className:"size-4",size:r}),n&&e("div",{className:"text-sm font-semibold ps-2",children:a("user.allProjectMembers")})]})})}function qm({accountId:r,showTitle:a=!1,size:s="md"}){const{t:i}=Ze(),o=r.split(":")[0],l=r.split(":")[1],c=t(n,{children:[e("div",{children:i("user.serviceAccountDescription")}),t("div",{className:"text-muted text-sm",children:[e("span",{className:"font-semibold",children:"Type:"})," ",o]}),t("div",{className:"text-muted text-sm",children:[e("span",{className:"font-semibold",children:"ID:"})," ",l]})]});return e(tp,{title:i("user.serviceAccount"),description:c,children:t("div",{className:"flex flex-row items-center gap-2",children:[e(C,{src:"/cloud.svg",name:"SA",color:"bg-amber-500",className:"px-[5px] text-white",size:s}),a&&t("div",{className:"text-sm font-semibold ps-2 truncate",children:[i("user.serviceAccount")," : ~",l.slice(-6)]})]})})}function Hm({email:r,showTitle:a=!1,size:s="md"}){const{t:i}=Ze(),o=t(n,{children:[e("div",{children:i("user.serviceAccountDescription")}),t("div",{className:"text-muted text-sm",children:[e("span",{className:"font-semibold",children:"Email:"})," ",r]})]});return e(tp,{title:"Email Agent",description:o,children:t("div",{className:"flex items-center gap-2",children:[t("div",{className:"flex items-center -space-x-2",children:[e(C,{src:"/cloud.svg",color:"bg-amber-500",className:"px-[5px] text-white border-2 border-white dark:border-gray-800",size:s}),e(C,{name:r,size:s,className:"border-2 border-white dark:border-gray-800"})]}),a&&t("div",{className:"text-sm font-semibold truncate",children:[i("user.agentOnBehalfOf")," : ",r]})]})})}function Gm({agentId:r,onBehalfOfType:a,onBehalfOfId:s,showTitle:i=!1,size:o="md",isScheduleAgent:l=!1}){const{t:c}=Ze(),d="user"===a&&s,u="apikey"===a&&s,m=Mm(s||""),p=Um(s||""),h=d?m.data:void 0,f=u?p.data:void 0,g=r.slice(-6),v=h?c("user.agentOnBehalfOf"):f?c("user.agentOnBehalfOfApiKey"):`${c("user.serviceAccount")}~${g}`,b=l?c("user.schedule",{title:v}):v,x=t("div",{className:"space-y-2",children:[h&&t("div",{className:"flex items-center gap-2",children:[e(C,{src:h.picture,name:h.name,size:"sm"}),t("div",{children:[e("div",{className:"font-medium",children:h.name||h.email}),h.email&&h.name&&e("div",{className:"text-xs text-muted",children:h.email})]})]}),f&&t("div",{children:[e("div",{className:"font-medium",children:f.name}),t("div",{className:"text-xs text-muted-foreground",children:["Key ID: ",f.id]})]}),!h&&!f&&t(n,{children:[e("div",{children:c("user.serviceAccountDescription")}),t("div",{className:"text-gray-800 dark:text-gray-500 text-sm",children:[e("span",{className:"font-semibold",children:"ID:"})," ",r]})]})]});return e(tp,{title:b,description:x,children:t("div",{className:"flex items-center gap-2",children:[t("div",{className:"flex items-center -space-x-2",children:[e(C,{src:"/cloud.svg",color:"bg-amber-500",className:"px-[5px] text-white border-2 border-white dark:border-gray-800",size:o}),h&&e(C,{src:h.picture,name:h.name,size:o,className:"border-2 border-white dark:border-gray-800"}),f&&e(C,{name:"API",color:"bg-gray-400",size:o,className:"border-2 border-white dark:border-gray-800"})]}),i&&e("div",{className:"text-sm font-semibold truncate",children:h?`Agent (${h.name||h.email})`:f?`Agent (${f.name})`:v})]})})}function Jm({title:t="Error",error:n,showTitle:r=!1,size:a="md"}){return e(Ym,{title:t,message:T(n),color:"bg-red-500",showTitle:r,size:a})}function Km({showTitle:t=!1,size:n="md",color:r}){const{t:a}=Ze();return e(Ym,{title:a("user.unknownUser"),message:a("user.unknownUserDescription"),color:r,showTitle:t,size:n})}function Qm({userRef:t,showTitle:n=!1,size:r="md"}){const{t:a}=Ze();if(!t)return e(Ym,{title:a("user.unknownUser"),message:a("user.unknownUserDescription"),showTitle:n,size:r});const s=t.split(":"),i=s[0];switch(i){case hr.User:return e(Xm,{userId:s[1],showTitle:n,size:r});case hr.Group:return e(Zm,{userId:s[1],showTitle:n,size:r});case"system":return e(Bm,{showTitle:n,size:r});case hr.ServiceAccount:return e(qm,{accountId:s.slice(1).join(":"),showTitle:n,size:r});case hr.Agent:{let t,a,i;return"agent"===s[1]?(t=s.slice(2,5).join(":"),a=s[5],i=s[6]):(t=s.slice(1,4).join(":"),a=s[4],i=s[5]),e(Gm,{agentId:t,onBehalfOfType:a,onBehalfOfId:i,showTitle:n,size:r})}case hr.Schedule:{const t="agent"===s[2]?s.slice(3,6).join(":"):"unknown-agent",a=s[6],i=s[7];return e(Gm,{agentId:t,onBehalfOfType:a,onBehalfOfId:i,showTitle:n,size:r,isScheduleAgent:!0})}case"email":return e(Hm,{email:s[1],showTitle:n,size:r});case hr.ApiKey:return e(ep,{keyId:s[1],size:r,showTitle:n});case"project":if("*"===s[1])return e(Vm,{showTitle:n,size:r});break;default:return e(Jm,{title:a("user.unknownUser"),error:`Invalid user ref type: ${i}`,showTitle:n,size:r})}}function Ym({title:n,message:r,color:a,size:s="md",showTitle:i=!1}){return e(tp,{title:n,description:r,children:t("div",{className:"flex flex-row items-center gap-2",children:[e(C,{color:a,size:s}),i&&e("div",{className:"text-sm font-semibold ps-1",children:n})]})})}function Zm({userId:n,showTitle:r=!1,size:a="md"}){const{t:s}=Ze(),{data:i,error:o}=Om(n);if(o)return Lm(o)?e(Km,{showTitle:r,size:a,color:"bg-indigo-500"}):e(Jm,{title:s("user.failedToFetchGroup"),error:o,showTitle:r,size:a});if(!i)return e(Wm,{});const l=t("div",{className:"space-y-1",children:[i.description&&e("div",{className:"text-sm",children:i.description}),e("div",{className:"text-xs text-muted-foreground",children:s("user.groupId",{id:i.id})}),i.tags&&i.tags.length>0&&e("div",{className:"flex flex-wrap gap-1",children:i.tags.map(t=>e("span",{className:"px-1.5 py-0.5 bg-muted rounded text-xs",children:t},t))})]});return e(tp,{title:i.name||s("user.unnamedGroup"),description:l,children:t("div",{className:"flex flex-row items-center gap-2",children:[e(Sn,{className:"size-6 text-indigo-500",size:a}),r&&e("div",{className:"text-sm font-semibold ps-2",children:i.name||s("user.unnamedGroup")})]})})}function Xm({userId:n,showTitle:r=!1,size:a="md"}){const{t:s}=Ze(),{data:i,error:o}=Mm(n);if(o)return Lm(o)?e(Km,{showTitle:r,size:a,color:"bg-indigo-500"}):e(Jm,{title:s("user.failedToFetchUser"),error:o,showTitle:r,size:a});if(!i)return e(Wm,{});const l=e("div",{className:"truncate",title:i.email,children:i.email});return e(tp,{title:i.name||i.email||i.username||s("user.unknown"),description:l,children:t("div",{className:"flex flex-row items-center gap-2",children:[e(C,{src:i.picture,name:i.name,color:"bg-indigo-500",size:a}),r&&e("div",{className:"text-sm font-semibold ps-2",children:i.name||i.email||i.username||s("user.unknown")})]})})}function ep({keyId:n,showTitle:r=!1,size:a="md"}){const{t:s}=Ze(),{data:i,error:o}=Um(n);if(o)return Lm(o)?e(Km,{showTitle:r,size:a,color:"bg-pink-500"}):e(Jm,{title:s("user.failedToFetchApiKey"),error:o,showTitle:r,size:a});if(!i)return e(Wm,{});const l=s("user.privateKey"),c=e(C,{name:"PK",color:"bg-pink-500",size:a}),d=t(_,{className:"dark:bg-gray-800 dark:text-gray-200 table-fixed w-full",children:[t("tr",{children:[e("td",{className:"font-semibold w-20",children:s("user.key")}),e("td",{className:"truncate max-w-0",children:i?.name})]}),t("tr",{children:[e("td",{className:"font-semibold w-20",children:s("user.account")}),e("td",{className:"truncate max-w-0",children:i?.account})]}),t("tr",{children:[e("td",{className:"font-semibold w-20",children:s("user.project")}),e("td",{className:"truncate max-w-0",children:i?.project.name})]})]});return e(tp,{title:l,description:d,children:t("div",{className:"flex flex-row items-center gap-2",children:[c,r&&e("div",{className:"text-sm font-semibold",children:i?.name||i?.account||i?.project.name||s("user.unknown")})]})})}function tp({title:n,description:r,children:a}){return t(I,{hover:!0,children:[e(z,{className:"cursor-pointer flex items-center inline-block",children:e("div",{children:a})}),e(R,{align:"center",sideOffset:8,side:"right",children:t("div",{className:"flex flex-col gap-1 rounded-md shadow-md p-2",children:[e("div",{className:"text-md font-semibold",children:n}),r]})})]})}function np({buckets:n,name:r,placeholder:a}){return function({buckets:n,name:r,placeholder:a}){const s=n.map(e=>({value:e._id,label:`(${e.count})`}));return{name:r,placeholder:a||`${r.charAt(0).toUpperCase()+r.slice(1)}`,options:s,labelRenderer:r=>{if("Unknown User"===r||!r){const e=n.find(e=>e._id===r);return`Unknown User (${e?.count||0})`}const a=n.find(e=>e._id===r);return t("div",{className:"flex items-center w-full gap-2",children:[e("div",{className:"flex-1 min-w-0 flex items-center truncate",children:e(Qm,{userRef:r,showTitle:!0,size:"sm"})}),t("span",{className:"text-muted-foreground flex-shrink-0",children:["(",a?.count||0,")"]})]})}}}({buckets:n,name:r,placeholder:a})}function rp(e){const t=[];return t.push({name:"id",placeholder:"Agent Run ID",type:"text",multiple:!1}),t.push(Rm({buckets:e.interactions||[],name:"interaction",placeholder:"Interaction"})),t.push(Am({buckets:e.statuses||[],name:"status",placeholder:"Status"})),t.push(np({buckets:e.initiated_by||[],name:"initiated_by",placeholder:"Initiated By"})),t.push({name:"start",placeholder:"Started After",type:"date",multiple:!1}),t.push({name:"end",placeholder:"Started Before",type:"date",multiple:!1}),t}function ap(e){return t=>{e.clearFilters(!1,!1),t.forEach(t=>{if(t.value&&t.value.length>0){const n=t.name,r=Im(t);zm(e,n,r)}}),e.search()}}function sp({facets:n,search:a,selectionCount:s,actions:i,filters:o,setFilters:l,filterGroups:c}){const[d,u]=Oe([]),m=o??d,p=l??u,h=Be(!1),f=Be("undefined"!=typeof window&&Boolean(new URLSearchParams(window.location.search).get("filters"))),g=rp(n),v=c??g,b=Me(()=>ap(a),[a]);He(()=>{h.current?f.current?f.current=!1:b(m):h.current=!0},[m,b]);return e(j,{filterGroups:v,filters:m,setFilters:p,children:t("div",{className:"gap-2 items-center w-full",children:[t("div",{className:"flex justify-between mb-1",children:[e(P,{}),t("div",{className:"flex justify-end",children:[!s&&e("div",{className:"flex items-center justify-between px-2 py-1",children:e("div",{className:"text-sm text-muted-foreground",children:a.initialized?`${a.totalCount} agent runs`:"Loading agent runs..."})}),i&&i.length>0?e("div",{className:"flex items-center gap-2 mb-1 me-2",children:i.map((t,n)=>e("div",{children:t},n))}):null,e(r,{onClick:()=>{a.search()},variant:"outline",title:"Refresh",children:e(Tn,{className:"size-5"})})]})]}),m.length>0&&t("div",{className:"flex items-center gap-2 mb-1",children:[e(A,{}),e(D,{})]})]})})}class ip{types;map={};constructor(e){this.types=e,e.sort((e,t)=>e.name.localeCompare(t.name));for(const t of e)this.map[t.id]=t}getType(e){return this.map[e]}getTypeLayout(e){const t=this.map[e];return t?t.table_layout:void 0}getTypeName(e){const t=this.map[e];return t?t.name:void 0}}const op=Ue({registry:void 0,isLoading:!1,load:()=>Promise.resolve(),reload:()=>Promise.resolve()});function lp({children:t}){const{store:n,project:r}=tr(),[a,s]=Oe(),[i,o]=Oe(!1),l=Be(!1),c=Be(r?.id),d=Ve(async()=>{if(r&&!l.current){l.current=!0,o(!0);try{const e=await n.types.catalog.list({layout:!0});s(new ip(e))}catch(e){console.error("Failed to fetch types",e)}finally{o(!1),l.current=!1}}},[n,r]),u=Ve(async()=>(l.current=!1,d()),[d]);return He(()=>{c.current!==r?.id&&(c.current=r?.id,s(void 0),l.current=!1)}),e(op.Provider,{value:{registry:a,isLoading:i,load:d,reload:u},children:t})}function cp(){const e=We(op);return He(()=>{e.registry||e.isLoading||e.load()},[e.registry,e.isLoading,e.load]),e}function dp(e){const{registry:t}=cp(),n=[];if(n.push({name:"name",placeholder:"Name",type:"text",multiple:!1}),t){const e=t.types.map(e=>({label:e.name,value:e.id})),r={name:"types",placeholder:"Type",type:"select",multiple:!0,options:e,filterBy:(t,n)=>{const r=e.find(e=>e.value===t);return r?.label?.toLowerCase().includes(n.toLowerCase())??!1}};n.push(r)}return n}function up(e){return t=>{0!==t.length?(e.clearFilters(!1),t.forEach(t=>{if(t.value&&t.value.length>0){const n=t.name,r=Im(t);zm(e,n,r)}}),e.search()):e.clearFilters(!0)}}function mp({facets:n,search:r,filters:a,setFilters:s,filterGroups:i}){const[o,l]=Oe([]),c=dp(),d=up(r),u=void 0!==a&&void 0!==s;return e(j,{filterGroups:i??c,filters:u?a:o,setFilters:e=>{if(u)return void s(e);const t="function"==typeof e?e(o):e;l(t),d(t)},children:t("div",{className:"flex gap-2 items-center",children:[e(P,{}),e(A,{}),e(D,{})]})})}function pp({buckets:n,typeRegistry:r,type:a="select",multiple:s=!1}){const i=new Map;r||console.warn("Type names cannot be resolved"),n.forEach(e=>{let t,n=e._id;null==e._id?(n="Document",t="Document"):(t=r?.getTypeName(e._id),t||(console.warn("Content Object Type not found",e._id),t=e._id)),i.set(n,{name:t,count:e.count})});return{name:"types",placeholder:"Types",type:a,multiple:s,options:n.map(e=>{const t=e._id,n=t||"Document",r=i.get(n);return{value:t,label:r?`${r.name} (${r.count})`:`Unknown (${e.count})`}}),labelRenderer:n=>{const r=i.get(n);return r?t("div",{className:"w-full flex items-center",children:[e("span",{className:"text-sm truncate",children:r.name}),t("span",{className:"ms-2 text-xs",children:["(",r.count,")"]})]}):(console.warn(`Type data not found for ${n}`),n)},filterBy:(e,t)=>{const n=i.get(e);return n?n.name.toLowerCase().includes(t.toLowerCase()):(console.warn(`Type name not found for ${e}`),!1)}}}function hp(e){return Array.isArray(e)?e:[]}function fp(e){const{registry:t}=cp(),n=[];if(n.push({placeholder:"ID",name:"id",type:"text",options:[]}),n.push({placeholder:"Name",name:"name",type:"text",options:[]}),e.type){const r=pp({buckets:hp(e.type),typeRegistry:t,type:"select",multiple:!0});n.push(r)}if(e.status){const t=Am({buckets:hp(e.status),name:"status",placeholder:"Status",type:"select",multiple:!0});n.push(t)}return e.tags&&n.push({name:"tags",placeholder:"Tags",type:"stringList",options:hp(e.tags).map(e=>({label:e._id,value:e._id}))}),n.push({name:"created_at",placeholder:"Created Date",type:"date",multiple:!0,options:[]}),n.push({name:"updated_at",placeholder:"Updated Date",type:"date",multiple:!0,options:[]}),n}function gp(e){return t=>{0!==t.length?(e.clearFilters(!1),t.forEach(t=>{if(t.value&&t.value.length>0){const n=t.name;let r;if("date"===t.type&&t.multiple){if(Array.isArray(t.value)&&t.value.length>0)if(1===t.value.length){const e=Tm(t.value[0]);r={gte:e,lte:e}}else if(2===t.value.length){r={gte:Tm(t.value[0]),lte:Tm(t.value[1])}}}else r=Im(t);zm(e,"name"===n?"name":"id"===n?"id":n,r)}}),e.search()):e.clearFilters()}}function vp({facets:n,search:r}){const[a,s]=Oe([]),i=fp(n),o=gp(r),l=E();return e(j,{filterGroups:i,filters:a,setFilters:e=>{const t="function"==typeof e?e(a):e;s(t),o(t)},inModal:l,children:t("div",{className:"flex gap-2 items-center",children:[e(P,{}),e(A,{}),e(D,{})]})})}function bp({search:t,buckets:n,placeholder:r="All Environments",className:a}){const{client:s}=tr(),[i,o]=Oe([]),l=t.getFilterValue("environment");He(()=>{if(s){const e=n.map(async e=>{let t;return await s.environments.retrieve(e._id).then(e=>{t=e.name}).catch(()=>{t=`${e._id} (deleted)`}),t||(t=e._id),{...e,name:t}});Promise.all(e).then(e=>{e.sort((e,t)=>e.name.localeCompare(t.name)),o(e)})}},[n,s]);const c=i?.find(e=>e._id===l);return e($,{filterBy:"name",className:a,isClearable:!0,optionLabel:Pm,options:i,value:c,onChange:e=>{t.setFilterValue("environment",e?._id)},by:"_id",placeholder:r})}function xp(e){const t=[];t.push({name:"name",placeholder:"Name",type:"text",multiple:!1});t.push({name:"prompt",placeholder:"Prompt Name",type:"text",multiple:!1});t.push({name:"model",placeholder:"Model",type:"text",multiple:!1});return t.push({name:"tags",placeholder:"Tags",type:"stringList",multiple:!0}),t}function yp(e){return t=>{0!==t.length?(e.clearFilters(!1,!1),t.forEach(t=>{if(t.value&&t.value.length>0){const n=t.name,r=Im(t);zm(e,n,r)}}),e.search(!0)):e.clearFilters(!0,!0)}}function wp({facets:n,search:r}){const[a,s]=Oe([]),i=xp(),o=yp(r);return e(j,{filterGroups:i,filters:a,setFilters:e=>{const t="function"==typeof e?e(a):e;s(t),o(t)},children:t("div",{className:"flex gap-2 items-center",children:[e(P,{}),e(A,{}),e(D,{})]})})}function Np(e){const t=[];return t.push(Am({buckets:e.statuses||[],name:"status",placeholder:"Status",multiple:!1})),t.push({name:"name",placeholder:"Name",type:"text",multiple:!1}),t}function kp({facets:n,filters:r,setFilters:a}){const s=Np(n);return e(j,{filterGroups:s,filters:r,setFilters:a,children:t("div",{className:"flex items-center gap-2",children:[e(P,{}),e(A,{}),e(D,{})]})})}function Cp(e){const t=[];return t.push(Am({buckets:e.statuses||[],name:"status",placeholder:"Status",multiple:!0})),t.push(np({buckets:e.started_by||[],name:"started_by",placeholder:"Started By"})),t.push(Am({buckets:e.run_type||[],name:"run_type",placeholder:"Mode",multiple:!0})),t.push(Am({buckets:e.processes||[],name:"process",placeholder:"Process",multiple:!0})),t.push({name:"start",placeholder:"Started After",type:"date",multiple:!1}),t.push({name:"end",placeholder:"Started Before",type:"date",multiple:!1}),t}function _p({facets:n,filters:r,setFilters:a}){const s=Cp(n);return e(j,{filterGroups:s,filters:r,setFilters:a,children:t("div",{className:"flex items-center gap-2",children:[e(P,{}),e(A,{}),e(D,{})]})})}function Sp(e){const t=[];if(t.push({name:"name",placeholder:"Name",type:"text",multiple:!1}),e.role&&e.role.length>0){const n={name:"role",placeholder:"Role",type:"select",options:e.role.map(e=>({label:e._id,value:e._id,count:e.count}))};t.push(n)}return t}function Tp(e){return t=>{0!==t.length?(e.clearFilters(!1,!1),t.forEach(t=>{if(t.value&&t.value.length>0){const n=t.name,r=Im(t);zm(e,n,r)}}),e.search()):e.clearFilters(!0,!1)}}function Ip({facets:n,search:r,filters:a,setFilters:s,filterGroups:i}){const[o,l]=Oe([]),c=Sp(n),d=Tp(r),u=void 0!==a&&void 0!==s;return e(j,{filterGroups:i??c,filters:u?a:o,setFilters:e=>{if(u)return void s(e);const t="function"==typeof e?e(o):e;l(t),d(t)},children:t("div",{className:"flex gap-2 items-center",children:[e(P,{}),e(A,{}),e(D,{})]})})}function zp(n){const r=[];if(r.push({name:"run_ids",placeholder:"Run ID",type:"text",multiple:!1}),n.interactions){const e=Rm({buckets:n.interactions||[],name:"interaction",placeholder:"Interactions"});r.push(e)}if(n.environments){const a=function({buckets:n,name:r}){const a=n.map(e=>({label:`(${e.count})`,value:e._id}));return{name:"environment",placeholder:r.charAt(0).toUpperCase()+r.slice(1),options:a,type:"select",labelRenderer:r=>{const a=n.find(e=>e._id===r);return t("div",{className:"w-full flex items-center",children:[e("span",{className:"text-sm truncate",children:a?.name||r}),t("span",{className:"ms-2 text-xs",children:["(",a?.count||0,")"]})]})},filterBy:(e,t)=>{const r=n.find(t=>t._id===e);return(r?.name||e).toLowerCase().includes(t.toLowerCase())}}}({buckets:n.environments||[],name:"environments"});r.push(a)}if(r.push({name:"tags",placeholder:"Tags",type:"stringList",multiple:!0}),n.models){const e=Am({buckets:n.models||[],name:"model"});r.push(e)}if(n.statuses){const e=Am({buckets:n.statuses||[],name:"status"});r.push(e)}if(n.finish_reason){const e=Am({buckets:n.finish_reason.map(e=>({...e,_id:null===e._id?"none":e._id})),name:"finish_reason",placeholder:"Finish Reason"});r.push(e)}if(n.created_by){const e=np({buckets:n.created_by||[],name:"created_by",placeholder:"Created By"});r.push(e)}r.push({name:"start",placeholder:"Date After",type:"date",multiple:!1});r.push({name:"end",placeholder:"Date Before",type:"date",multiple:!1});r.push({name:"workflow_run_ids",placeholder:"Workflow Run ID",type:"text",multiple:!1});return r.push({name:"workflow_ids",placeholder:"Workflow ID",type:"text",multiple:!1}),r}function Rp(e){return t=>{0!==t.length?(e.clearFilters(!1,!1),t.forEach(t=>{if(t.value&&t.value.length>0){const n=t.name;let r=Im(t);"run_ids"!==n&&"workflow_run_ids"!==n&&"workflow_ids"!==n||Array.isArray(r)||(r=[r]),zm(e,n,r)}}),e.search()):e.clearFilters(!0,!1)}}function jp({facets:n,search:a,actions:s,selectionCount:i,filters:o,setFilters:l,filterGroups:c}){const[d,u]=Oe([]),m=zp(n),p=Rp(a),h=void 0!==o&&void 0!==l,f=h?o:d;return e(j,{filterGroups:c??m,filters:f,setFilters:e=>{if(h)return void l(e);const t="function"==typeof e?e(d):e;u(t),p(t)},children:t("div",{className:"gap-2 items-center w-full",children:[t("div",{className:"flex justify-between mb-1",children:[e(P,{}),t("div",{className:"flex justify-end",children:[!i&&e("div",{className:"flex items-center justify-between px-2 py-1",children:e("div",{className:"text-sm text-muted",children:a.initialized?`${a.totalCount} calls`:"Loading calls..."})}),s&&s.length>0?e("div",{className:"flex items-center gap-2 mb-1 me-2",children:s.map((t,n)=>e("div",{children:t},n))}):null,e(r,{onClick:()=>{a.search()},variant:"outline",title:"Refresh",children:e(Tn,{className:"size-5"})})]})]}),f.length>0&&t("div",{className:"flex items-center gap-2 mb-1",children:[e(A,{}),e(D,{})]})]})})}function Pp({search:t,buckets:n,name:r,placeholder:a,className:s}){const i=t.getFilterValue(r),o=n?.find(e=>JSON.stringify(e._id)===JSON.stringify(i));return e($,{filterBy:"_id",className:s,isClearable:!0,optionLabel:jm,options:n,value:o,onChange:e=>{t.setFilterValue(r,e?._id)},by:"_id",placeholder:a})}function Ap({search:t,name:n,placeholder:r,className:a}){const[s,i]=Oe([]);return He(()=>{t.setFilterValue(n,s)},[n,t,s]),e(L,{className:a,value:s,onChange:i,placeholder:r})}function Dp(e){return`${e.name} (${e.count})`}function Ep({search:t,buckets:n,placeholder:r="Filter by Type",className:a}){const[s,i]=Oe([]),{registry:o}=cp(),l=t.getFilterValue("type");He(()=>{if(o){const e=n.map(e=>{let t;return null==e._id?(e._id="Document",t="Document"):(t=o.getTypeName(e._id),t||(console.warn("Content Object Type not found",e._id),t=e._id)),{...e,name:t}});e.sort((e,t)=>e.name.localeCompare(t.name)),i(e)}},[n,o]);const c=s?.find(e=>e._id===l);return e($,{filterBy:"name",className:a,isClearable:!0,optionLabel:Dp,options:s,value:c,onChange:e=>{t.setFilterValue("type",e?._id)},by:"_id",placeholder:r})}function $p(e){const t=[];return t.push(Am({buckets:e.tags||[],name:"tags",placeholder:"Tags",multiple:!0})),t.push({name:"name",placeholder:"Name",type:"text",multiple:!1}),t}function Lp({facets:n,filters:r,setFilters:a}){const s=$p(n);return e(j,{filterGroups:s,filters:r,setFilters:a,children:t("div",{className:"flex items-center gap-2",children:[e(P,{}),e(A,{}),e(D,{})]})})}function Fp(e){const t=[];if(t.push({placeholder:"Workflow Name or Workflow Run ID",name:"name",type:"text",options:[]}),e.status){const n=Am({buckets:e.status||[],name:"status",placeholder:"Status"});t.push(n)}if(e.initiated_by){const n=np({buckets:e.initiated_by||[],name:"initiated_by",placeholder:"Initiated By"});t.push(n)}t.push({name:"start",placeholder:"Date After",type:"date",multiple:!1});t.push({name:"end",placeholder:"Date Before",type:"date",multiple:!1});return t.push({name:"has_reported_errors",placeholder:"Has Reported Errors",type:"select",multiple:!1,options:[{label:"Yes",value:"true"},{label:"No",value:"false"}]}),t}function Mp(e){return t=>{0!==t.length?(e.clearFilters(!1),t.forEach(t=>{if(t.value&&t.value.length>0){const n=t.name,r=Im(t);if("name"===n)zm(e,"search_term",r),zm(e,"name",r);else if("has_reported_errors"===n){const t=Array.isArray(r)?r[0]:r;"true"!==t&&"false"!==t||zm(e,n,"true"===t)}else zm(e,n,r)}}),e.search()):e.clearFilters()}}function Op({facets:n,search:r}){const[a,s]=Oe([]),i=Fp(n),o=Mp(r);return e(j,{filterGroups:i,filters:a,setFilters:e=>{const t="function"==typeof e?e(a):e;s(t),o(t)},children:t("div",{className:"flex gap-2 items-center",children:[e(P,{}),e(A,{}),e(D,{})]})})}function Up(e){const t=[];return t.push({name:"name",placeholder:"Name",type:"text",multiple:!1}),t}function Wp({facets:n,filters:r,setFilters:a}){const s=Up();return e(j,{filterGroups:s,filters:r,setFilters:a,children:t("div",{className:"flex items-center gap-2",children:[e(P,{}),e(A,{}),e(D,{})]})})}class Bp{object;objects;setState;collectionId;singleSelection=!1;constructor(e,t,n,r){this.object=e,this.objects=n,this.setState=r,this.singleSelection=0===Object.keys(this.objects).length,this.collectionId=t}isSingleSelection(){return this.singleSelection}hasSelection(){return void 0!==this.object||0!==this.size()}size(){return Object.keys(this.objects).length}getObjectIds(){return Object.keys(this.objects)}getObjectId(){return this.object?.id}clone(){return new Bp(this.object,this.collectionId,this.objects,this.setState)}add(e){this.objects[e.id]=e,this.singleSelection=0===Object.keys(this.objects).length,this.setState(this.clone())}remove(e){delete this.objects[e],this.singleSelection=0===Object.keys(this.objects).length,this.setState(this.clone())}addAll(e){for(const t of e)this.objects[t.id]=t;this.setState(this.clone())}isSelected(e){return void 0!==this.objects[e]}removeAll(){this.objects={},this.singleSelection=!0,this.setState(this.clone())}}const Vp=Ue(void 0);function qp(){const e=We(Vp);if(!e)throw new Error("useObjectSelection must be used within a ObjectSelectionProvider");return e}function Hp(){return We(Vp)}function Gp({value:t,collectionId:n,children:r}){const[a,s]=Oe();return He(()=>{const e=new Bp(t,n,{},s);s(e)},[n,t]),a&&e(Vp.Provider,{value:a,children:r})}const Jp=Ue(void 0);function Kp({onFilter:t,children:n}){return e(Jp.Provider,{value:t,children:n})}const Qp="h-6 w-6 p-0 opacity-0 group-hover/field:opacity-100 text-muted hover:text-foreground transition-opacity shrink-0";function Yp({field:a,value:s,label:i,copyContent:o}){const l=We(Jp),c=Array.isArray(s)?s.length>0:void 0!==s&&""!==s;return t(n,{children:[void 0!==o&&""!==o&&e(F,{content:o,className:Qp}),c&&void 0!==s&&e(h,{description:`Filter by ${i}`,asChild:!0,size:"xs",children:e(r,{variant:"ghost",size:"sm","aria-label":`Filter by ${i}`,className:Qp,onClick:e=>{e.stopPropagation(),l?.(a,s)},children:e(In,{className:"size-3"})})})]})}const Zp="text/csv",Xp="image/",eh="application/pdf",th="video/",nh=["application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/msword","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.ms-powerpoint"],rh=e=>e===Zp||Zp.includes(e),ah=e=>e.startsWith(Xp)||Xp.includes(e),sh=e=>e===eh||eh.includes(e),ih=e=>e.startsWith(th)||th.includes(e),oh=e=>nh.includes(e);function lh(e,t){if("undefined"==typeof window||"undefined"==typeof document)return!1;const n=document.createElement("iframe");n.style.position="fixed",n.style.right="0",n.style.bottom="0",n.style.width="0",n.style.height="0",n.style.border="0",n.style.visibility="hidden",document.body.appendChild(n);const r=n.contentWindow;if(!r)return n.parentNode?.removeChild(n),!1;const a=r.document;a.open(),a.write("<!doctype html><html><head><title></title></head><body></body></html>"),a.close(),a.title=t;document.querySelectorAll('link[rel="stylesheet"], style').forEach(e=>{a.head.appendChild(e.cloneNode(!0))});const s=a.createElement("style");return s.textContent='\n@media print {\n body {\n margin: 24px;\n font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;\n font-size: 14px;\n line-height: 1.5;\n color: #111827;\n background-color: #ffffff;\n }\n\n .vprose {\n max-width: 800px;\n margin: 0 auto;\n }\n\n .vprose h1 {\n font-size: 24px;\n font-weight: 700;\n margin: 1.5rem 0 0.75rem;\n }\n\n .vprose h2 {\n font-size: 20px;\n font-weight: 600;\n margin: 1.25rem 0 0.75rem;\n }\n\n .vprose h3 {\n font-size: 18px;\n font-weight: 600;\n margin: 1rem 0 0.5rem;\n }\n\n .vprose p {\n margin: 0 0 0.5rem;\n }\n\n .vprose ul,\n .vprose ol {\n margin: 0.5rem 0 0.5rem 1.5rem;\n padding: 0;\n }\n\n .vprose li {\n margin: 0.25rem 0;\n }\n\n .vprose table {\n width: 100%;\n border-collapse: collapse;\n margin: 1rem 0;\n }\n\n .vprose th,\n .vprose td {\n border: 1px solid #d1d5db;\n padding: 0.5rem 0.75rem;\n vertical-align: top;\n }\n\n .vprose thead th {\n background-color: #f3f4f6;\n font-weight: 600;\n }\n\n .vprose pre,\n .vprose code {\n font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;\n font-size: 12px;\n }\n\n .vprose pre {\n padding: 0.75rem;\n border-radius: 4px;\n border: 1px solid #e5e7eb;\n background-color: #f9fafb;\n white-space: pre-wrap;\n word-break: break-word;\n }\n\n /* Hide chart action buttons when printing */\n .chart-actions {\n display: none !important;\n }\n\n /* Hide interactive elements in agent conversation when printing */\n .print-hidden,\n [class*="print:hidden"],\n button[title="Copy message"],\n button[title="Copy to clipboard"],\n button[title="Export as PNG"],\n .message-actions {\n display: none !important;\n }\n\n /* Prevent page breaks inside elements */\n .vprose table,\n .vprose pre,\n .vprose blockquote,\n .vprose figure,\n .vprose img,\n [class*="chart"],\n [class*="Chart"] {\n break-inside: avoid;\n page-break-inside: avoid;\n }\n\n /* Keep headings with following content */\n .vprose h1,\n .vprose h2,\n .vprose h3,\n .vprose h4,\n .vprose h5,\n .vprose h6 {\n break-after: avoid;\n page-break-after: avoid;\n }\n\n /* Keep list items together when possible */\n .vprose li {\n break-inside: avoid;\n page-break-inside: avoid;\n }\n}\n',a.head.appendChild(s),a.body.innerHTML=e.innerHTML,r.focus(),r.print(),setTimeout(()=>{n.parentNode?.removeChild(n)},1e3),!0}const ch=import.meta.env,dh={max_hw:ch?.VITE_RENDITION_HW||256,format:fr.jpeg,generate_if_missing:!0},uh="vertesia.content_store.renditionId";async function mh(e,t,n,r,a){if(!t?.content?.type||!(ah(t.content.type)||ih(t.content.type)||sh(t.content.type)))return void a("No preview available");a("Preparing preview...");const s=Date.now()/1e3,i=localStorage.getItem(`${uh}_${t.id}_${dh.max_hw}`),o=localStorage.getItem(`${uh}_${t.id}_${dh.max_hw}_time`);if(i?.length&&o&&Math.abs(s-parseInt(o,10))<=900)return n(i),r(`${t.name} Rendition`),a("ready"),i;a("Preparing preview..."),e.objects.getRendition(t.id,dh).then(s=>{if("generating"===s.status)a("Preparing preview..."),n(""),r(""),setTimeout(()=>mh(e,t,n,r,a),6e4);else{if("failed"===s.status)return a("No preview available"),n(""),void r("");{if(!s?.renditions?.length)return a("No preview available"),n(""),void r("");const e=s.renditions[0];localStorage.setItem(`${uh}_${t.id}_${dh.max_hw}`,e),localStorage.setItem(`${uh}_${t.id}_${dh.max_hw}_time`,(Date.now()/1e3).toString()),n(e),r(`${t.name} Rendition`),a("ready"),console.log(`Rendition for document ${t.id} retrieved successfully: ${e}`)}}}).catch(e=>{a("No preview available"),console.warn("Failed to retrieve rendition:",e),n(""),r("")})}function ph(e,t=7){return e?`~${e.slice(-t)}`:""}function hh(e,t){return e.length>t?`${e.substring(0,t)}...`:e}function fh(e){switch(e){case gr.RUNNING:return"text-info";case gr.COMPLETED:return"text-success";case gr.FAILED:return"text-destructive";case gr.TERMINATED:case gr.CANCELED:return"text-attention";default:return"text-muted"}}function gh(e){switch(e){case gr.RUNNING:return"Running";case gr.COMPLETED:return"Completed";case gr.FAILED:return"Failed";case gr.CONTINUED_AS_NEW:return"Continued As New";case gr.TERMINATED:return"Terminated";case gr.TIMED_OUT:return"Timed Out";case gr.CANCELED:return"Canceled";default:return"Unknown"}}function vh(e){return"object"==typeof e&&null!==e}function bh(e,t){if(!vh(e))return;const n=e[t];return"string"==typeof n?n:void 0}function xh(e){return"string"==typeof e?e:bh(e,"id")||""}Dr.extend(Ta),Dr.extend(Sa);const yh={string(n,r){const a=[];if(n){const e=n.get("slice");e&&a.push(t=>t.slice(parseInt(e,10)));const t=n.get("max_length");t&&a.push(e=>e.slice(0,parseInt(t,10))),n.has("upper")&&a.push(e=>e.toUpperCase()),n.has("lower")&&a.push(e=>e.toLowerCase()),n.has("capitalize")&&a.push(e=>e[0].toUpperCase()+e.substring(1)),n.has("ellipsis")&&a.push(e=>`${e}...`)}return(n,r,s)=>{let i;if(n){if(i=String(n),a.length>0)for(const e of a)i=e(i)}else i="";return e("td",{className:"group/field",children:s?t("div",{className:"flex items-center gap-2 min-w-0",children:[e("span",{className:"truncate",children:i}),s]}):i},r)}},fileSize:(t,n)=>(t,n)=>{let r="";if(t){const e=Number(t);if(Number.isNaN(e))r=String(t);else{const t=["Bytes","KB","MB","GB","TB"];if(0===e)r="0 Bytes";else{const n=Math.floor(Math.log(e)/Math.log(1024));r=`${(e/1024**n).toFixed(2)} ${t[n]}`}}}return e("td",{className:"group/field",children:r},n)},number(t,n){let r,a;t&&(r=t.get("currency")||void 0,a=t.get("decimals")||void 0);const s=a?parseInt(a,10):2;return(t,n)=>{const a=Number(t),i=new Intl.NumberFormat("en-US",{style:r?"currency":"decimal",currency:r,maximumFractionDigits:s}).format(Number.isFinite(a)?a:0);return e("td",{className:"group/field",children:i},n)}},objectId(n,a){const s=[];let i=!1;if(n){const e=n.get("slice");e&&(i=!0,s.push(t=>t.slice(parseInt(e,10))))}return(n,o,l)=>{const c=xh(n),d=s.reduce((e,t)=>t(e),c);return t("td",{className:"flex justify-start items-center gap-2 group/field",children:[e(r,{variant:"ghost","aria-label":"Preview Object",title:"Preview Object",onClick:e=>{e.stopPropagation(),a?.(c)},children:e(zn,{className:"size-4"})}),i?"~":"",d,l]},o)}},objectName(n,r){let a="title";return n&&(a=n.get("title")||"title"),(n,r,s)=>{const i=vh(n)&&vh(n.properties)?n.properties:void 0,o=i?.[a],l=function(e){return null==e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e?e:String(e)}(o),c=bh(n,"name"),d=bh(n,"id"),u=l||c||(d?ph(d):"");return e("td",{className:"group/field",children:s?t("div",{className:"flex items-center gap-2 min-w-0",children:[e("span",{className:"truncate",children:u}),s]}):u},r)}},objectLink(n,a){const s=[];return s.push(e=>e.slice(-7)),(n,i)=>{const o=xh(n),l=s.reduce((e,t)=>t(e),o);return t("td",{className:"flex justify-between items-center gap-2 max-w-48 group/field",children:["~",l,e(r,{variant:"ghost",alt:"Preview Object",onClick:e=>{e.stopPropagation(),a?.(o)},children:e(zn,{className:"size-4"})})]},i)}},typeLink:(n,r)=>(n,r,a)=>{const s=bh(n,"name")||"n/a";return e("td",{className:"group/field",children:a?t("div",{className:"flex items-center gap-2 min-w-0",children:[e("span",{className:"truncate",children:s}),a]}):s},r)},revision:(n,r)=>(n,r)=>{const a=vh(n)&&vh(n.revision)?n.revision:void 0;if(!a)return e("td",{},r);const s=bh(a,"root"),i=bh(a,"label");return e("td",{className:"group/field",children:t("div",{className:"flex flex-col gap-0.5",children:[s&&t("div",{className:"flex items-center gap-1",children:[t("span",{className:"text-xs text-muted font-mono",children:["root: ~",s.slice(-7)]}),e("a",{href:`/store/objects/${s}`,onClick:e=>e.stopPropagation(),children:e($t,{className:"size-3 text-muted"})})]}),i&&t("span",{className:"text-xs text-muted",children:["label: ",i]})]})},r)},date(n,r){let a,s="fromNow";if(n){const e=n.get("localized");if(e)s="format",a=e;else{const e=n.get("relative");e&&(s=e)}}return(n,r,i)=>{const o="string"==typeof n||"number"==typeof n||n instanceof Date?n:void 0;if(void 0===o)return e("td",{children:i},r);const l=Dr(o),c="format"===s?l.format(a):"toNow"===s?l.toNow():l.fromNow();return e("td",{className:"group/field",children:t("div",{className:"flex items-center gap-2",children:[e(h,{description:l.format("LLL"),children:c}),i]})},r)}}},wh=yh.string();function Nh(e){return"object"==typeof e&&null!==e}function kh(e,t){let n=e;if(!n)return;if(!t.length)return n;const r=t.length-1;for(let e=0;e<r;e++){if(!Nh(n))return;if(n=n[t[e]],!n)return}return Nh(n)?n[t[r]]:void 0}function Ch(e){return e&&"."!==e?e.split("."):[]}class _h{layout;renderer=wh;path;fallbackPath;previewObject;constructor(e,t){if(this.layout=e,this.path=Ch(e.field||""),this.fallbackPath=e.fallback?Ch(e.fallback):void 0,this.previewObject=t,e.render)this.renderer=(e,t)=>null;else{const t=e.type||"string",n=t.indexOf("?");if(n>0){const e=t.substring(0,n),r=new URLSearchParams(t.substring(n+1));this.renderer=yh[e](r)}else this.renderer=yh[t]()}}get name(){return this.layout.name}resolveValue(e){let t=kh(e,this.path);return void 0===t&&this.fallbackPath&&(t=kh(e,this.fallbackPath)),void 0===t&&(t=this.layout.default),t}render(t,n){if(this.layout.render)return e("td",{className:"whitespace-nowrap px-3 py-4 text-sm group",children:this.layout.render(t)},n);const r=this.layout.type||"string",a=r.indexOf("?")>0?r.substring(0,r.indexOf("?")):r,s=this.buildActions(t,a);if(("objectId"===a||"objectLink"===a)&&this.previewObject){const e=r.indexOf("?"),i=e>0?new URLSearchParams(r.substring(e+1)):void 0;return yh[a](i,e=>{this.previewObject?.(t.id)})(t,n,s)}return this.renderer(this.resolveValue(t),n,s)}buildActions(t,n){const r=this.layout.field;if("objectId"===n||"objectLink"===n||"id"===r)return e(Yp,{field:"id",value:t.id,label:t.id,copyContent:t.id});if("objectName"===n||"name"===r)return e(Yp,{field:"name",value:t.name,label:t.name??t.id});if("typeLink"===n||"type.name"===r||"type"===r){const n=t.type?.id;return e(Yp,{field:"type",value:n,label:t.type?.name??n??"type"})}return"status"===r?e(Yp,{field:"status",value:t.status,label:t.status}):void 0}}function Sh({isLoading:n=!1,counts:r=6}){return n?e("div",{className:"flex flex-wrap gap-2 justify-between",children:Array(r).fill(0).map((n,r)=>e("div",{className:"w-[15vw] animate-pulse",children:t(M,{className:"relative flex flex-col border h-fit",children:[e("div",{className:"h-48 bg-muted rounded-t-xl flex items-center justify-center text-muted",children:" "}),e(O,{className:"bg-muted h-[2px]"}),t(U,{className:"p-2 flex flex-col",children:[t("div",{className:"flex flex-col overflow-hidden",children:[e("div",{className:"h-5 bg-muted rounded w-3/4 mb-2"}),e("div",{className:"h-4 bg-muted rounded w-1/2"})]}),e("div",{className:"text-xs text-muted w-full flex justify-end mt-2",children:e("div",{className:"h-3 bg-muted rounded w-1/4"})})]})]})},r))}):null}function Th({selection:n,document:a,onSelectionChange:s,onRowClick:i,highlightRow:o,previewObject:l,selectedObject:c}){const{client:d}=tr(),[u,m]=Oe(void 0),[p,f]=Oe(void 0),[g,v]=Oe(void 0),b="string"==typeof a.properties?.title?a.properties.title:a.name;He(()=>{a?.content&&mh(d,a,m,f,v)},[d,a]);const x=o?.(a);return t(M,{className:`relative flex flex-col border h-fit w-full ${c?.id===a.id?"border-attention border-4":""} ${x?"border-blue-400 dark:border-blue-500 bg-blue-50/50 dark:bg-blue-900/20":""}`,onClick:()=>i?.(a),children:[x&&e("div",{className:"absolute top-2 end-8 z-10",children:e(Rn,{className:"size-4 text-blue-600 dark:text-blue-400"})}),n&&e("div",{className:"absolute top-2 start-2 z-10 flex flex-col items-center gap-1",children:e("input",{checked:n.isSelected(a.id),type:"checkbox",onChange:e=>{e.stopPropagation(),s(a,e)},onClick:e=>e.stopPropagation()})}),e("div",{className:"absolute top-1 end-1 z-10 flex flex-col items-center",children:e(r,{variant:"ghost",size:"sm",title:"Preivew Object",onClick:e=>{e.stopPropagation(),l?.(a.id)},children:e(zn,{className:"size-4 "+("ready"===g?"text-muted":"text-white")})})}),u&&"ready"===g?e("img",{src:u,alt:p,className:"w-auto h-48 object-cover rounded-t-xl"}):e("div",{className:"h-48 bg-gray-700 rounded-t-xl flex items-center justify-center text-muted",children:g}),e(O,{className:"bg-gray-200 h-[2px]"}),t(U,{className:"p-2 flex flex-col",children:[t("div",{className:"flex flex-col overflow-hidden",children:[e(h,{placement:"top",description:b,children:e("h3",{className:"text-start font-medium leading-none truncate",children:b})}),a?.type?.name?e(h,{placement:"bottom",size:"xs",description:a?.type?.name,children:e("p",{className:"text-start text-xs text-muted truncate",children:a?.type?.name})}):e("p",{className:"text-xs text-muted",children:" "})]}),a.score&&t("div",{className:"text-xs text-muted w-full flex justify-end",children:["Score: ",a.score.toFixed(4)??"-"]})]})]})}function Ih({objects:n,selection:r,isLoading:a,columns:s,onRowClick:i,highlightRow:o,selectedObject:l,toggleAll:c,onSelectionChange:d}){const{t:u}=Ze();return t(_,{className:"w-full",children:[e(W,{children:t("tr",{children:[r&&e("th",{children:e("input",{type:"checkbox",onChange:c})}),s.map(t=>e("th",{children:t.name},t.name))]})}),t(B,{isLoading:a,columns:s.length+1,children:[n?.map(n=>{const a=o?.(n);return t("tr",{className:`group cursor-pointer hover:bg-muted ${l?.id===n.id?"bg-muted":""} ${a?"bg-blue-50 dark:bg-blue-900/20":""}`,onClick:()=>{i?.(n)},children:[r&&e("td",{onClick:e=>e.stopPropagation(),children:e("input",{checked:r.isSelected(n.id),type:"checkbox",className:""+(r.isSelected(n.id)?"":"hidden group-hover:block"),onChange:e=>d(n,e)})}),s.map((e,t)=>e.render(n,t)),e("td",{className:"w-8 text-center",children:a&&e(Rn,{className:"size-4 text-blue-600 dark:text-blue-400 inline-block"})})]},n.id)}),0===n.length&&e("tr",{children:e("td",{colSpan:s.length+(r?1:0),className:"text-center",children:u("store.noObjectsDragAndDrop")})})]})]})}function zh({objects:r,selection:a,isLoading:s,onSelectionChange:i,onRowClick:o,highlightRow:l,previewObject:c,selectedObject:d}){return t(n,{children:[e(Sh,{isLoading:s}),e("div",{className:"w-full gap-2 grid xs:grid-cols-1 sm:grid-cols-2 md:grid-cols-4 lg:grid-cols-6 @xs:grid-cols-1 @sm:grid-cols-2 @md:grid-cols-3 @lg:grid-cols-4",children:r.map(t=>e(Th,{document:t,selection:a,onSelectionChange:i,onRowClick:o,highlightRow:l,previewObject:c,selectedObject:d},t.id))})]})}class Rh{client;limit;collectionId;facets=new V({});result=new V({objects:[],isLoading:!1});initialized=!1;facetSpecs=[];query={};constructor(e,t=100){this.client=e,this.limit=t}withFacets(e){return this.facetSpecs=e,this}get objects(){return this.result.value.objects}get error(){return this.result.value.error}get isRunning(){return this.result.value.isLoading}get hasMore(){return this.result.value.hasMore||!1}getFilterValue(e){return this.query[e]}setFilterValue(e,t){this.query[e]=t,this.search()}setDefaultKeys(e){}clearFilters(e=!0){const{parent:t,full_text:n,vector:r,weights:a,score_aggregation:s,dynamic_scaling:i,limit:o,all_revisions:l}=this.query;this.query={parent:t,...void 0!==n&&{full_text:n},...void 0!==r&&{vector:r},...void 0!==a&&{weights:a},...void 0!==s&&{score_aggregation:s},...void 0!==i&&{dynamic_scaling:i},...void 0!==o&&{limit:o},...void 0!==l&&{all_revisions:l}},e&&this.search()}getFacetBuckets(e){const t=this.facets.value[e];return Array.isArray(t)?t:[]}resetFacets(){this.query={}}reset(e=!1){this.initialized=!1,this.result.value={objects:[],isLoading:e,hasMore:!0}}_updateRunningState(e){const t=this.result.value;this.result.value={objects:t.objects,isLoading:e,error:t.error,hasMore:t.hasMore}}_searchRequest(e,t,n,r=!0){const a={limit:t,offset:n,query:e,facets:r?this.facetSpecs:void 0};return this.collectionId?this.client.collections.searchMembers(this.collectionId,a):this.client.objects.search(a)}_facetsRequest(){const e={facets:this.facetSpecs,query:this.query};return this.collectionId?this.client.collections.computeFacets(this.collectionId,e):this.client.objects.computeFacets(e)}computeFacets(e){this._facetsRequest().then(e=>{this.facets.value=e})}async _search(e=!1,t=!1){if(this.isRunning&&e)return!1;const n=this.result.value;e||(this.initialized=!0),this.result.value={isLoading:!0,objects:e?this.objects:[],hasMore:!e||this.result.value.hasMore};const r=this.limit,a=e?this.objects.length:0;try{const n=await this._searchRequest(this.query,r,a,!t),s=n.results||[],i=n.facets||{};return this.result.value={isLoading:!1,objects:e?this.objects.concat(s):s,hasMore:s.length===r},!t&&i&&Object.keys(i).length>0&&(this.facets.value=i),!0}catch(e){if("object"==typeof e&&null!==e&&"status"in e&&404===e.status)return this.result.value={isLoading:!1,objects:[],hasMore:!1},!1;const t=e instanceof Error?e:new Error(String(e));return this.result.value={error:t,isLoading:!1,objects:n.objects,hasMore:!1},!1}}search(e=!1){return this.isRunning?Promise.resolve(!1):this._search(!1,e)}loadMore(e=!1){return this.isRunning||!this.hasMore||this.query.vector?Promise.resolve(!1):(this.objects.length>0&&(e=!0),this._search(!0,e))}}const jh=Ue(void 0);function Ph(){return We(jh)}function Ah(){return q(Ph().facets)}function Dh(){const e=Ph();return{...q(e.result),search:e}}function Eh(){const e=Ph();return q(e.facets).total}const $h=Xe.getFixedT(null,et);var Lh;async function Fh(e){try{const t=await e.arrayBuffer(),n=new Ia;n.appendByteArray(new Uint8Array(t));const r=n.end();return r?.toString()}catch(e){return void console.error("Error calculating file hash:",e)}}function Mh(){const{client:e}=tr(),t=p();return{checkDocumentProcessing:Ve(async(n,r,a)=>{try{console.log(`Preparing metadata for ${n.length} files...`);const t=await async function(e,t){const n=[];for(let r=0;r<e.length;r+=5){const a=e.slice(r,r+5),s=await Promise.all(a.map(async e=>{let n=t||"/";if(e.webkitRelativePath){const r=e.webkitRelativePath.split("/");if(r.length>1){const e=r.slice(0,-1).join("/");n=t?`${t}/${e}`:e}}return{file:e,hash:await Fh(e),name:e.name,size:e.size,location:n}}));n.push(...s)}return n}(n,r),s=async()=>{const n=t.map(e=>e.hash).filter(Boolean);if(0===n.length)return;const r={"content.etag":{$in:n}};let s;if(a){const t={query:{match:r},select:"id content.etag"};s=(await e.store.collections.searchMembers(a,t)).results}else{const t={query:r,select:"id content.etag"};s=await e.store.objects.find(t)}for(const e of s){const n=t.find(t=>t.hash===e.content?.etag);n&&(n.existingId=e.id,n.action=Lh.SKIP)}},i=async()=>{const n=t.filter(e=>e.action!==Lh.SKIP),r=n.map(e=>e.location),s=Array.from(new Set(r)),i=[];for(const t of s){const r={"content.name":{$in:n.filter(e=>e.location===t).map(e=>e.name)},location:t||"/"};if(a){const t=e.store.collections.searchMembers(a,{query:{match:r},select:"id content.name location"}).then(e=>e.results);i.push(t)}else{const t=e.store.objects.find({query:r,select:"id content.name location"});i.push(t)}}const o=(await Promise.all(i)).flat();console.log(`Found ${o.length} document to update`,o);for(const e of o){const n=t.find(t=>t.name===e.content?.name&&(t.location?t.location===e.location:"/"===e.location));n&&(n.existingId=e.id,n.action=Lh.UPDATE)}console.log(`Reconciled ${t.filter(e=>e.action===Lh.UPDATE).length}`)};return await s(),await i(),t.forEach(e=>{e.action||(e.action=Lh.CREATE)}),console.log("Document processing check results:",{totalFiles:n.length,toCreate:t.filter(e=>e.action===Lh.CREATE).length,toUpdate:t.filter(e=>e.action===Lh.UPDATE).length,toSkip:t.filter(e=>e.action===Lh.SKIP).length}),t}catch(e){throw t({title:$h("store.errorInUploadProcessingCheck"),status:"error",description:T(e)}),console.log("Error in file upload processing check",e),new Error(`Error in file upload processing check: ${T(e)}`,{cause:e})}},[e,t])}}function Oh({isOpen:a,onClose:s,files:i,collectionId:o,selectedFolder:l,title:c,children:d,onUploadComplete:u,hideFileSelection:m=!1,showTypeSelectionOnly:f=!1,allowFolders:g=!0}){const{client:v}=tr(),{registry:b}=cp(),x=p(),{t:y}=Ze(),w=c??y("upload.uploadFiles"),[N,k]=Oe([]),[C,_]=Oe([]),[S,I]=Oe(!1),[z,R]=Oe(null),[j,P]=Oe([]),[A,D]=Oe(!1),[E,L]=Oe(!1),[F,M]=Oe(0),[O,U]=Oe(Date.now()),[W,B]=Oe(void 0),[V,q]=Oe(null),[Z,X]=Oe(w),[ee,te]=Oe("");He(()=>{o&&v.store.collections.retrieve(o).then(B)},[v.store.collections.retrieve,o]),He(()=>{A?(X(y("upload.uploadingFiles")),te(`${Math.round(F)}% complete`)):E?(X(y("upload.uploadComplete")),te("")):S?(X(y("upload.fileAnalysisResults")),te(`${N.length} file${1!==N.length?"s":""}`)):N.length>0?(X(w),te(y("upload.checkingForDuplicates"))):(X(w),te(""))},[A,E,S,w,F,N.length,y]);const ne=()=>W||l?t(Q,{className:"mb-4",status:"default",icon:e(cn,{className:"size-5"}),children:[e("div",{className:"flex items-center",children:e("span",{className:"font-medium",children:y("upload.uploadLocation")})}),t("div",{className:"text-sm mt-1",children:[W&&t("div",{className:"flex items-center",children:[e("span",{className:"me-1",children:y("upload.collectionLabel")}),e("span",{className:"font-medium",children:W.name})]}),l&&t("div",{className:"flex items-center mt-1",children:[e("span",{className:"me-1",children:y("upload.folderLabel")}),e("span",{className:"font-medium",children:l})]})]})]}):null,[re,ae]=Oe({toCreate:0,toUpdate:0,toSkip:0}),{checkDocumentProcessing:se}=Mh(),ie=Me(()=>b?.types||[],[b?.types]),oe=Ve(async e=>{if(e.length)try{console.log(`Processing ${e.length} files to determine required actions...`);const t=await se(e,l,o);_(t);const n=t.filter(e=>e.action===Lh.CREATE).length,r=t.filter(e=>e.action===Lh.UPDATE).length,a=t.filter(e=>e.action===Lh.SKIP).length;ae({toCreate:n,toUpdate:r,toSkip:a}),x({title:y("upload.filesAnalyzed"),description:`${e.length} file(s): ${n} new, ${r} to update, ${a} to skip`,status:"info",duration:4e3}),I(!0)}catch(e){console.error("Error processing files:",e),x({title:y("agent.error"),description:y("upload.errorAnalyzingFiles"),status:"error",duration:5e3})}},[se,o,l,y,x]);He(()=>{a&&(_([]),I(!1),R(null),P([]),D(!1),L(!1),M(0),ae({toCreate:0,toUpdate:0,toSkip:0}),q(null),X(w),te(""),i&&i.length>0?(k(i),oe(i)):k([]),U(Date.now()))},[a,i,oe,w]);const le=()=>{k([]),_([]),I(!1),R(null),P([]),D(!1),L(!1),M(0),ae({toCreate:0,toUpdate:0,toSkip:0}),q(null),X(w),te(""),U(Date.now()),s()},ce=e=>{e&&e.length>0&&(k(e),oe(e))},de=async()=>{if(!C.length)return;const e=z?.id||null,t=C.map(e=>({file:e.file,status:"pending",progress:0,action:e.action===Lh.CREATE?"create":e.action===Lh.UPDATE?"update":"skip"}));P(t),D(!0),L(!1);const n=C.filter(e=>e.action===Lh.SKIP),r=C.filter(e=>e.action===Lh.UPDATE),a=C.filter(e=>e.action===Lh.CREATE),s={success:!0,objectIds:[],uploadedFiles:[],skippedFiles:[],failedFiles:[]};for(const t of n)t.existingId&&(s.objectIds.push(t.existingId),s.skippedFiles.push({id:t.existingId,name:t.name,type:e,status:"skipped",location:t.location}),P(e=>e.map(e=>e.file===t.file?{...e,status:"success",progress:100,id:t.existingId}:e)));const i=async(t,n)=>{const r=[];for(let e=0;e<t.length;e+=50)r.push(t.slice(e,e+50));for(let a=0;a<r.length;a++){const i=r[a];if(console.log(`Processing ${n} batch ${a+1}/${r.length} (${i.length} files)`),t.length>50){const e=50*a;x({title:y("upload.processingFilesAction",{action:n}),description:y("upload.processedCount",{processed:e,total:t.length}),status:"info",duration:2e3})}let l=0;await Promise.all(i.map(async t=>{try{if(P(e=>e.map(e=>e.file===t.file?{...e,status:"uploading",progress:20}:e)),"update"===n&&t.existingId)await v.store.objects.update(t.existingId,{type:e||void 0,content:t.file,location:t.location,name:t.name},{createRevision:!0,revisionLabel:`upload on ${(new Date).toISOString()}`}),P(e=>e.map(e=>e.file===t.file?{...e,status:"success",progress:100,id:t.existingId}:e)),s.objectIds.push(t.existingId),s.uploadedFiles.push({id:t.existingId,name:t.name,type:e,status:"updated",location:t.location});else{const n=await v.store.objects.create({type:e||void 0,content:t.file,location:t.location||t.file.webkitRelativePath||t.name},{collection_id:o});P(e=>e.map(e=>e.file===t.file?{...e,status:"success",progress:100,id:n.id}:e)),s.objectIds.push(n.id),s.uploadedFiles.push({id:n.id,name:t.name,type:e,status:"created",location:t.location})}}catch(n){console.error(`Failed to process file ${t.name}:`,n),P(e=>e.map(e=>e.file===t.file?{...e,status:"error",progress:100,message:T(n,"Unknown error")}:e)),s.failedFiles.push({name:t.name,error:T(n,"Unknown error"),status:"failed",location:t.location,type:e}),s.success=!1}l++,l%5!=0&&l!==i.length||P(e=>{const t=e.filter(e=>"success"===e.status||"error"===e.status).length,n=e.length,r=n>0?Math.round(t/n*100):0;return M(r),e})}))}};r.length>0&&await i(r,"update"),a.length>0&&await i(a,"create"),P(e=>{const t=e.filter(e=>"pending"===e.status).map(e=>({...e,status:"error",progress:100,message:y("upload.uploadProcessInterrupted")}));return t.length>0?(t.forEach(e=>{s.failedFiles.push({name:e.file.name,error:y("upload.uploadProcessInterrupted"),status:"failed",type:z?.id||null})}),s.success=!1,e.map(e=>"pending"===e.status?{...e,status:"error",progress:100,message:y("upload.uploadProcessInterrupted")}:e)):e}),D(!1),L(!0);const l=s.uploadedFiles.filter(e=>"created"===e.status).length,c=s.uploadedFiles.filter(e=>"updated"===e.status).length,d=s.skippedFiles.length,u=s.failedFiles.length;let m="";l>0&&(m+=`${l} file${1!==l?"s":""} uploaded`),c>0&&(m+=m?", ":"",m+=`${c} file${1!==c?"s":""} updated`),d>0&&(m+=m?", ":"",m+=`${d} file${1!==d?"s":""} skipped`),u>0&&(m+=m?", ":"",m+=`${u} file${1!==u?"s":""} failed`),x({title:y("upload.uploadComplete"),description:m,status:u>0?"warning":"success",duration:5e3}),q(s)},ue=()=>t("div",{className:"mb-4",children:[t("div",{className:"block text-sm font-medium mb-2",children:[y("store.contentType")," ",e("span",{className:"text-muted font-normal",children:y("store.optional")}),e(h,{description:y("upload.contentTypeTooltip"),placement:"top",size:"xs",children:e(qt,{className:"size-3 ms-2"})})]}),e($,{options:ie,value:z,optionLabel:e=>e?e.name:y("store.selectContentTypeLabel"),placeholder:y("store.selectContentTypeAuto"),onChange:e=>R(void 0===e?null:e),filterBy:"name",isClearable:!0}),!z&&e("div",{className:"p-2 rounded-md",children:t("div",{className:"flex items-center text-attention",children:[e(bn,{className:"size-4 me-1"}),y("store.automaticTypeDetection"),e(h,{description:y("store.automaticTypeDetectionDescription"),placement:"top",size:"xs",children:e(qt,{className:"size-3 ms-2"})})]})})]});return t(H,{isOpen:a,onClose:le,className:"mx-auto",disableCloseOnClickOutside:!0,children:[e(G,{description:ee,children:Z}),f?t(J,{children:[d,ne(),ue()]}):0!==N.length||m?A||E?A?t(J,{children:[ne(),e("div",{className:"mb-4",children:e("div",{className:"h-2 bg-muted/20 rounded-full overflow-hidden",children:e("div",{className:"h-full bg-primary rounded-full",style:{width:`${F}%`}})})}),e("div",{className:"max-h-96 overflow-y-auto",children:j.map((n,r)=>t("div",{className:"flex items-center py-2 border-b border-border last:border-b-0",children:[t("div",{className:"me-3",children:["pending"===n.status&&e(dn,{className:"size-5 text-muted"}),"uploading"===n.status&&e(K,{size:"sm"}),"success"===n.status&&e(bn,{className:"size-5 text-success"}),"error"===n.status&&e(vn,{className:"size-5 text-destructive"})]}),t("div",{className:"flex-1 min-w-0",children:[e("div",{className:"truncate font-medium",children:n.file.name}),t("div",{className:"text-xs text-muted",children:["pending"===n.status&&y("agent.waiting"),"uploading"===n.status&&y("agent.uploading"),"success"===n.status&&("create"===n.action?y("store.created"):"update"===n.action?y("store.updated"):y("upload.skip")),"error"===n.status&&n.message]})]})]},`${n.file.name}-${n.file.size}-${n.file.lastModified}`))})]}):e(J,{children:t("div",{className:"mb-4",children:[ne(),e(ca,{files:j.map(e=>{let t;return t="success"===e.status?"create"===e.action?"success":"update"===e.action?"updated":"skipped":"failed",{name:e.file.name,status:t,error:"error"===e.status?e.message:void 0}}),location:l||void 0,collection:W?.name})]})}):e(J,{children:S?t(n,{children:[ne(),e("div",{className:"mb-4",children:e("div",{className:"p-4 rounded-md mb-4",children:t("div",{className:"grid grid-cols-3 gap-4",children:[t("div",{className:"flex flex-col items-center",children:[t("div",{className:"flex items-center gap-2",children:[e(jn,{className:"size-5 text-primary"}),e("span",{className:"font-medium",children:y("upload.new")})]}),e("div",{className:"text-2xl font-semibold",children:re.toCreate})]}),t("div",{className:"flex flex-col items-center",children:[t("div",{className:"flex items-center gap-2",children:[e(bn,{className:"size-5 text-success"}),e("span",{className:"font-medium",children:y("upload.update")})]}),e("div",{className:"text-2xl font-semibold",children:re.toUpdate})]}),t("div",{className:"flex flex-col items-center",children:[t("div",{className:"flex items-center gap-2",children:[e(Pn,{className:"size-5 text-mixer-attention/40"}),e("span",{className:"font-medium",children:y("upload.skip")})]}),e("div",{className:"text-2xl font-semibold",children:re.toSkip})]})]})})}),ue(),e(Q,{className:"mb-4",status:"info",children:re.toCreate+re.toUpdate>0?t("div",{className:"space-y-1",children:[e("p",{children:y("upload.filesReadyToProcess",{count:re.toCreate+re.toUpdate})}),e("p",{children:re.toSkip>0&&y("upload.filesToSkip",{count:re.toSkip})})]}):re.toSkip>0?e("span",{children:y("upload.allFilesExist",{count:re.toSkip})}):e("span",{children:y("upload.noFilesToProcess")})})]}):t("div",{className:"flex flex-col items-center justify-center py-4",children:[e(K,{size:"lg",className:"mb-4"}),e("div",{className:"text-lg font-medium",children:y("upload.analyzingFiles")})]})}):t(J,{className:"flex flex-col items-center justify-center p-8",children:[ne(),e(la,{onDrop:ce,message:y("upload.dragAndDrop"),buttonLabel:y("upload.selectFiles"),className:"w-full h-64",allowFolders:g}),d]}),(()=>{if(f)return t(Y,{children:[e(r,{variant:"ghost",onClick:le,children:y("modal.cancel")}),e(r,{onClick:()=>{u&&u({success:!0,objectIds:[],uploadedFiles:[{name:"type-selection",type:z?.id||null,status:"created"}],skippedFiles:[],failedFiles:[]}),le()},children:z?y("upload.useTypeName",{typeName:z.name}):y("upload.useAutoDetection")})]});if(0===N.length&&!m)return e(Y,{children:e(r,{variant:"ghost",onClick:le,children:y("modal.cancel")})});if(!A&&!E){const n=S;return t(Y,{children:[e(r,{variant:"ghost",onClick:le,children:y("modal.cancel")}),e(r,{disabled:!n,onClick:de,children:re.toCreate+re.toUpdate>0?y("agent.upload"):y("upload.continue")})]})}return A?e(Y,{children:e(r,{variant:"ghost",disabled:!0,children:y("agent.uploading")})}):t(Y,{children:[e(r,{variant:"ghost",onClick:()=>{k([]),_([]),I(!1),R(null),P([]),D(!1),L(!1),M(0),ae({toCreate:0,toUpdate:0,toSkip:0})},children:y("upload.uploadMore")}),e(r,{onClick:()=>{u&&V&&u(V),le()},children:y("agent.close")})]})})()]},O)}function Uh(e){const t="function"==typeof e?e:e.onUploadDone,{client:n,project:r,store:a}=tr(),s=Ph(),i=p(),o=Xe.getFixedT(null,et),{checkDocumentProcessing:l}=Mh();return async(e,c,d)=>{const u={success:!1,objectIds:[],uploadedFiles:[],skippedFiles:[],failedFiles:[]};if(!r)return i({status:"error",title:o("store.noProjectSelected"),duration:3e3}),u;if(!e||0===e.length)return i({status:"warning",title:o("store.noFilesSelected"),duration:3e3}),u;const m=Array.from(e).filter(e=>e.size>0);if(0===m.length)return i({status:"error",title:o("store.noValidFilesSelected"),description:o("store.pleaseSelectValidFiles"),duration:5e3}),u;const p=[],h=[],f=[];console.log(`Processing ${m.length} files with smart file processing...`);const g=await l(m,null,d),v=g.filter(e=>e.action===Lh.CREATE).length,b=g.filter(e=>e.action===Lh.UPDATE).length,x=g.filter(e=>e.action===Lh.SKIP).length;i({title:o("store.filesAnalyzedTitle"),description:`${m.length} file(s): ${v} new, ${b} to update, ${x} to skip`,status:"info",duration:4e3});for(const e of g.filter(e=>e.action===Lh.SKIP&&e.existingId))p.push({id:e.existingId,name:e.name,type:c,status:"skipped",location:e.location});const y=g.filter(e=>(e.action===Lh.CREATE||e.action===Lh.UPDATE)&&e.file);if(y.length>0){console.log(`Processing ${y.length} files (${y.filter(e=>e.action===Lh.CREATE).length} create, ${y.filter(e=>e.action===Lh.UPDATE).length} update)...`);const e=50,t=[];for(let n=0;n<y.length;n+=e)t.push(y.slice(n,n+e));for(let r=0;r<t.length;r++){const s=t[r],l=r*e;console.log(`Processing batch ${r+1}/${t.length} (${s.length} files)`),y.length>e&&i({title:o("store.processingFiles"),description:`Processed ${l}/${y.length} files...`,status:"info",duration:2e3});const m=await Promise.all(s.map(async e=>{try{if(e.action===Lh.UPDATE&&e.existingId){const t=await n.store.objects.update(e.existingId,{type:c||void 0,content:e.file,location:e.location,name:e.name},{createRevision:!0,revisionLabel:`upload on ${(new Date).toISOString()}`});return h.push({id:e.existingId,name:e.name,type:c,status:"updated",location:e.location}),u.objectIds.push(e.existingId),{success:!0,id:t.id,name:e.name,action:"update"}}{const t=d?{collection_id:d}:void 0,n=await a.objects.create({type:c||void 0,content:e.file,location:e.location||e.file.webkitRelativePath||e.name},t);h.push({id:n.id,name:e.name,type:c,status:"created",location:e.location})}}catch(t){console.error(`Failed to process file ${e.name}:`,t),f.push({name:e.name,error:T(t,"Unknown error"),status:"failed",location:e.location,type:c}),i({status:"error",title:o("store.processingFailedFor",{name:e.name}),description:T(t),duration:4e3})}})),p=h.filter(e=>"created"===e.status),g=h.filter(e=>"updated"===e.status),v=h.filter(e=>"failed"===e.status);console.log(`Batch ${r+1} results:`,{creates:p,updates:g,failures:v,total:m.length})}}const w=h.filter(e=>"created"===e.status).length,N=h.filter(e=>"updated"===e.status).length,k=h.filter(e=>"failed"===e.status).length,C=h.filter(e=>"skipped"===e.status).length;t&&(console.log("Upload complete:",{totalObjectIds:u.objectIds.length,uploadedFiles:w,updatedFiles:N,skippedFiles:C,failedFiles:k}),await t(u.objectIds));let _="";return w>0&&(_+=`${w} file${1!==w?"s":""} uploaded`),N>0&&(_+=_?", ":"",_+=`${N} file${1!==N?"s":""} updated`),C>0&&(_+=_?", ":"",_+=`${C} file${1!==C?"s":""} skipped (already existed)`),k>0&&(_+=_?", ":"",_+=`${k} file${1!==k?"s":""} failed`),_&&i({status:k>0?"warning":"success",title:_,duration:4e3}),s.search(),u}}!function(e){e.CREATE="create",e.SKIP="skip",e.UPDATE="update"}(Lh||(Lh={}));const Wh=[{name:"ID",field:"id",type:"objectId?slice=-7"},{name:"Name",field:".",type:"objectName"},{name:"Type",field:"type.name",type:"string"},{name:"Status",field:"status",type:"string"},{name:"Updated At",field:"updated_at",type:"date"}];function Bh({isGridView:t=!1,onUpload:n,collectionId:r,...a}){return n?e(Vh,{...a,onUpload:n,isGridView:t,collectionId:r}):e(qh,{...a,isGridView:t})}function Vh({isGridView:n,onUpload:r,collectionId:a,skipTypeModal:s=!1,...i}){const[o,l]=Oe(!1),[c,d]=Oe([]),[u,m]=Oe(!1),[h,f]=Oe(null),[g,v]=Oe(!1),b=Ph(),x=p(),{t:y}=Ze(),{checkDocumentProcessing:w}=Mh(),N=async(e,t)=>{console.log("Files dropped on ObjectTable:",e.length,t),l(!0);try{if(a){const t=await w(e,null,a);f(t);const n=t.filter(e=>"create"===e.action).length,r=t.filter(e=>"update"===e.action).length,s=t.filter(e=>"skip"===e.action).length;x({title:y("store.filesReadyToProcess"),description:`${e.length} file(s): ${n} new, ${r} to update, ${s} to skip`,status:"info",duration:4e3})}else f(null)}catch(e){console.error("Error processing files:",e),x({title:y("store.errorProcessingFiles"),description:y("store.errorCheckingDuplicates"),status:"error",duration:4e3}),f(null)}finally{if(l(!1),d(e),m(!1),s){console.log("Skipping type modal and calling onUpload directly",{filesLength:e.length,processedFilesLength:h?.length});const t=r(e,null,a);t&&"object"==typeof t&&(t.processedFiles=h)}else console.log("Setting typeSelectionOpen to true",{filesLength:e.length}),v(!0)}},k=e=>{const t=[...c];d([]),f(null),v(!1),t.length>0&&void 0!==e&&(l(!0),console.log("Starting upload with",{typeId:e,filesCount:t.length,hasProcessingResults:!!h,collectionId:a}),r(t,e,a).finally(()=>{l(!1),b.search()}))},C=e=>{e.preventDefault(),e.stopPropagation(),m(!0)};return t("div",{className:"min-h-[400px] relative",onDragOver:C,onDragEnter:C,onDragLeave:e=>{e.preventDefault(),e.stopPropagation(),e.currentTarget.contains(e.relatedTarget)||m(!1)},onDrop:e=>{if(e.preventDefault(),e.stopPropagation(),m(!1),e.dataTransfer.items){const t=[];for(let n=0;n<e.dataTransfer.items.length;n++){const r=e.dataTransfer.items[n];if("file"===r.kind){const e=r.getAsFile();e&&t.push(e)}}if(t.length>0){const e={count:t.length,message:`Preparing to upload ${t.length} file${1===t.length?"":"s"}...`};N(t,e)}}},children:[e("div",{className:Ae("bg-white dark:bg-gray-800 opacity-40 absolute inset-0 z-50 flex justify-center items-center",o?"block":"hidden"),children:e(K,{size:"xl"})}),e(qh,{...i,isGridView:n}),e("div",{className:Ae("absolute inset-0 pointer-events-none",u?"z-40":"-z-10"),children:e("div",{className:"w-full h-full relative",children:e(la,{onDrop:N,message:"Drop files or folders here to upload",className:Ae("absolute inset-0 bg-white/90 dark:bg-gray-800/90 pointer-events-auto",u?"flex":"hidden"),buttonLabel:"Select Files or Folders",allowFolders:!0})})}),e(Oh,{isOpen:g&&c.length>0,onClose:()=>{d([]),f(null),v(!1),k(void 0)},files:c,collectionId:a,selectedFolder:null,title:"Upload Files",onUploadComplete:e=>{if(e){if(e.failedFiles&&e.failedFiles.length>0&&x({title:y("store.uploadIssues"),description:`${e.failedFiles.length} file(s) failed to upload`,status:"warning",duration:5e3}),e.success){const t=e.uploadedFiles.filter(e=>"created"===e.status).length,n=e.uploadedFiles.filter(e=>"updated"===e.status).length,r=e.skippedFiles.length;(t>0||n>0)&&x({title:y("store.uploadComplete"),description:`${t>0?`${t} created`:""}${t>0&&n>0?", ":""}${n>0?`${n} updated`:""}${r>0?`, ${r} skipped`:""}`,status:"success",duration:5e3})}b.search()}d([]),f(null),v(!1),e?.success&&e.objectIds.length>0?k(null):k(void 0)}})]})}function qh({objects:t,layout:n=Wh,isLoading:r,onRowClick:a,onSelectionChange:s,highlightRow:i,previewObject:o,selectedObject:l,isGridView:c}){const d=Hp(),u=(e,n)=>{if(d){const r=n.nativeEvent instanceof MouseEvent&&n.nativeEvent.shiftKey;if(n.target.checked){if(d.add(e),r){const n=t.findIndex(t=>t.id===e.id),r=function(e,t,n){for(let r=t-1;r>=0;r--)if(n.isSelected(e[r].id))return r;return-1}(t,n,d);if(r>-1&&r<n-1){const e=[];for(let a=r+1;a<n;a++)e.push(t[a]);d.addAll(e)}else{const e=function(e,t,n){const r=e.length;for(let a=t+1;a<r;a++)if(n.isSelected(e[a].id))return a;return-1}(t,n,d);if(e>-1&&e>n+1){const r=[];for(let a=n+1;a<e;a++)r.push(t[a]);d.addAll(r)}}}}else d.remove(e.id);s?.(d)}},m=e=>{if(d){e.target.checked?d.addAll(t):d.removeAll()}},p=Me(()=>{const e=n.length>0?n:Wh;return console.log("Using layout with columns:",e.map(e=>e.name).join(", ")),e.map(e=>new _h(e,o))},[n,o]);return e(c?zh:Ih,{objects:t,isLoading:r,columns:p,onRowClick:a,highlightRow:i,previewObject:o,selectedObject:l,selection:d,toggleAll:m,onSelectionChange:u})}function Hh({children:t,limit:n,parent:r,typeId:a,facets:s,name:i,collectionId:o}){const{store:l}=tr(),c=Me(()=>{let e;s?e=s:(e=[{name:"status",field:"status"},{name:"location",field:"location"}],a||e.unshift({name:"type",field:"type"}));const t=new Rh(l,n).withFacets(e);return t.collectionId=o,t.query.type=a,t.query.parent=r,t.query.name=i,o&&(t.query.all_revisions=!0),t},[o,s,n,i,r,l,a]);return e(jh.Provider,{value:c,children:t})}const Gh="vertesia.content_store.lastDisplayedView";function Jh({onUpdate:t}){const{t:n}=Ze(),[a,s]=Oe("grid"===localStorage.getItem(Gh)),i=()=>{localStorage.setItem(Gh,"grid"),s(!0),t(!0)},o=()=>{localStorage.setItem(Gh,"table"),s(!1),t(!1)};return e(r,{variant:"outline",onClick:()=>{a?o():i()},alt:n(a?"misc.tableView":"misc.thumbnailView"),children:e(a?An:Dn,{})})}Jh.LAST_DISPLAYED_VIEW=Gh;const Kh=[{name:"Name",field:"properties.title",type:"string",fallback:"name"},{name:"Type",field:"type.name",type:"string"},{name:"Status",field:"status",type:"string"},{name:"Created At",field:"created_at",type:"date"}];function Qh({onChange:t,selectedIds:n}){return e(Hh,{children:e(Yh,{onRowClick:e=>{t(e||void 0)},selectedIds:n})})}function Yh({onRowClick:n,selectedIds:a}){const{t:s}=Ze(),i=Ve(e=>!!a?.has(e.id),[a]),[o,l]=Oe(!1),[c,d]=Oe("grid"===localStorage.getItem("vertesia.content_store.lastDisplayedView")),{search:u,isLoading:m,error:p,objects:h,hasMore:f}=Dh(),g=Be(null);Z(g,()=>{o&&f&&!m&&(l(!1),u.loadMore(!0).finally(()=>{l(!0)}))},{threshold:.1,deps:[o,f,m]}),He(()=>{u.search().finally(()=>{l(!0)})},[u]);const v=Ah(),x=Ph();return p?e(b,{title:s("store.searchFailed"),children:p.message}):t("div",{className:"flex flex-col gap-2 h-full w-full",children:[t("div",{className:"flex justify-between items-center flex-shrink-0",children:[e(vp,{facets:v,search:x}),t("div",{className:"flex items-center gap-2",children:[e(r,{variant:"outline",onClick:()=>{l(!1),u.search().then(()=>l(!0))},"aria-label":"Refresh",children:e(Tn,{size:16})}),e(Jh,{onUpdate:d})]})]}),t("div",{className:"@container relative flex-1 overflow-y-auto",children:[e(Bh,{objects:h||[],isLoading:!h.length&&m,layout:Kh,onRowClick:n,highlightRow:a?.size?i:void 0,isGridView:c}),e("div",{ref:g,className:"h-4 w-full"})]})]})}function Zh(e){const t=Math.max(0,e)/1e3,n=t>0&&t<10&&!Number.isInteger(t)?1:0;return`${new Intl.NumberFormat(void 0,{maximumFractionDigits:n}).format(t)}K`}function Xh({onSend:n,onStop:a,approvalModeSlot:s,mcpSlot:o,disabled:l=!1,isSending:c=!1,isStopping:d=!1,isStreaming:u=!1,isCompleted:m=!1,contextWindowUsage:p,onCompactContext:f,isCompactingContext:b=!1,activeTaskCount:x=0,activeWorkstreams:y=[],placeholder:w,onFilesSelected:N,uploadedFiles:k=[],onRemoveFile:C,onRemoveProcessingFile:_,acceptedFileTypes:S,maxFiles:T=5,processingFiles:I,artifactRunId:z,hasProcessingFiles:R=!1,renderDocumentSearch:j,selectedDocuments:P=[],onRemoveDocument:A,hideObjectLinking:D=!1,hideFileUpload:E=!1,disableDropZone:$=!1,className:L,inputClassName:F}){const{t:M}=Ze(),O=w??M("agent.typeYourMessage"),U=Be(null),W=Be(null),[B,V]=Oe(""),[q,Q]=Oe(!1),[Y,Z]=Oe(!1),[te,ne]=Oe(!1),re=Boolean(N&&!E),ae=re&&!$,se=!D||re||Boolean(j),ie=k.length>=T,oe=_??C,le=Me(()=>y.filter(e=>"running"===e.status||"canceling"===e.status),[y]),ce=le.length||x,de=p?M("agent.contextUsageCompactLabel",{percent:p.usedPercent}):void 0,ue=p?M("agent.contextTokenUsage",{used:Zh(p.usedTokens),limit:Zh(p.checkpointTokens)}):void 0,me=Me(()=>{const e=[];if(!E&&I)for(const t of I.values()){const n=t.preview_url,r=t.status===cr.UPLOADING?M("agent.uploading"):t.status===cr.PROCESSING?M("agent.processing"):t.status===cr.ERROR?M("agent.error"):t.status===cr.READY?M("agent.ready"):t.status;e.push({id:t.id,name:t.name,contentType:t.content_type,artifactPath:t.artifact_path,previewUrl:n,removable:Boolean(oe),statusLabel:r,statusTone:t.status===cr.ERROR?"destructive":t.status===cr.READY?"success":"attention"})}if(!E)for(const t of k)e.push({id:t.id,name:t.name,contentType:t.type,artifactPath:t.artifact_path,previewUrl:t.previewUrl,removable:Boolean(C),statusLabel:M("agent.ready"),statusTone:"success"});for(const t of P)e.push({id:t.id,name:t.name,href:`/store/objects/${t.id}`,removable:Boolean(A),statusTone:"info"});return e},[oe,E,A,C,I,P,M,k]);He(()=>{!l&&m&&U.current?.focus()},[l,m]);const pe=Ve(e=>{if(!re||!N)return;const t=Array.from(e),n=T-k.length,r=t.slice(0,n);r.length>0&&N(r)},[re,N,T,k.length]),he=Ve(e=>{e.preventDefault(),e.stopPropagation(),ae&&ne(!0)},[ae]),fe=Ve(e=>{e.preventDefault(),e.stopPropagation(),ne(!1)},[]),ge=Ve(e=>{e.preventDefault(),e.stopPropagation(),ne(!1),ae&&e.dataTransfer?.files&&e.dataTransfer.files.length>0&&pe(e.dataTransfer.files)},[ae,pe]),ve=Ve(e=>{if(!re)return;const t=sm(e.clipboardData?.items);t.length>0&&pe(t)},[re,pe]),be=Ve(e=>{re&&e.target.files&&e.target.files.length>0&&(pe(e.target.files),e.target.value="")},[re,pe]),xe=Ve(()=>{W.current?.click()},[]),ye=Ve(()=>Z(!1),[]),we=Ve(e=>Z(!1),[]),Ne=()=>{const e=B.trim();!e||l||c||(n(e),V(""))},ke=()=>{a&&!d&&a()},Ce=Be(0),_e=Ve(()=>{const e=U.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]);He(()=>{_e()},[B,_e]);return t("div",{className:i("px-3 py-3 flex-shrink-0 transition-all fixed lg:sticky bottom-0 start-0 end-0 lg:start-auto lg:end-auto w-full bg-background/95 backdrop-blur z-10",te&&ae&&"bg-info/10 border-info",L),onDragOver:ae?he:void 0,onDragLeave:ae?fe:void 0,onDrop:ae?ge:void 0,children:[te&&ae&&e("div",{className:"absolute inset-0 flex items-center justify-center bg-blue-100/80 dark:bg-blue-900/40 rounded-lg z-10 pointer-events-none",children:t("div",{className:"text-blue-600 dark:text-blue-400 font-medium flex items-center gap-2",children:[e(jn,{className:"size-5"}),M("agent.dropFilesToUpload")]})}),re&&e("input",{ref:W,type:"file",multiple:!0,accept:S,onChange:be,className:"hidden"}),e(xm,{activeWorkstreams:y}),t("div",{className:"mx-auto flex max-w-3xl flex-col gap-2 rounded-2xl border border-border/70 bg-mixer-muted/15 p-2.5 shadow-lg shadow-black/5",children:[me.length>0&&e(ec,{items:me,artifactRunId:z,variant:"composer",onRemove:e=>{I?.has(e)?oe?.(e):k.some(t=>t.id===e)?C?.(e):A?.(e)},className:"gap-1.5"}),e("div",{className:"flex min-w-0 flex-1",children:e(X,{ref:U,value:B,onKeyDown:e=>{if("Enter"===e.key){return e.metaKey||e.ctrlKey||e.altKey||e.shiftKey?void(e.shiftKey||(e.preventDefault(),ee(e.currentTarget,V))):(e.preventDefault(),void(B.trim().length>0&&Ne()))}if("Escape"===e.key&&u&&a){const e=Date.now();e-Ce.current<500?(ke(),Ce.current=0):Ce.current=e}},onChange:e=>V(e.target.value),onPaste:ve,disabled:l,"aria-label":O,placeholder:O,rows:1,style:{maxHeight:"160px"},className:i("min-h-[44px] resize-none border-0 bg-transparent px-0 py-0 text-sm leading-6 shadow-none focus-visible:ring-0",F)})}),t("div",{className:"flex items-center justify-between gap-3",children:[t("div",{className:"flex min-w-0 flex-wrap items-center gap-1.5",children:[se&&t(g,{align:"left",trigger:e(r,{variant:"ghost",size:"icon",className:"size-8 rounded-full text-muted hover:bg-muted","aria-label":M("agent.addAttachment"),title:M("agent.addAttachment"),children:e($n,{className:"size-4"})}),children:[!D&&t(v,{onClick:()=>Q(!0),isDisabled:!m,children:[e(En,{className:"size-4"}),M("agent.linkObject")]}),re&&t(v,{onClick:xe,isDisabled:ie,children:[e(jn,{className:"size-4"}),M("agent.upload")]}),j&&t(v,{onClick:()=>Z(!0),children:[e(Ft,{className:"size-4"}),e("span",{children:M("agent.searchDocuments")}),P.length>0&&e("span",{className:"ms-auto inline-flex items-center justify-center rounded-full bg-info/20 px-1.5 py-0.5 text-[10px] font-medium text-info",children:P.length})]})]}),s,o,p&&e(h,{asChild:!0,placement:"top",size:"md",className:"text-foreground shadow-lg",description:t("span",{className:"block max-w-56 text-start text-sm leading-6",children:[e("span",{className:"block",children:M("agent.contextRemainingUntilCompact",{percent:p.remainingPercent})}),ue&&e("span",{className:"mt-1 block text-foreground/80",children:ue})]}),children:e(r,{type:"button",variant:"ghost",size:"icon",className:i("size-8 rounded-lg text-info hover:bg-muted hover:text-info disabled:opacity-60","focus-visible:ring-2 focus-visible:ring-info/40"),"aria-label":de,onClick:f,disabled:!f||b,children:b?e(K,{size:"sm"}):t("svg",{viewBox:"0 0 24 24",className:i("size-8 -rotate-90",p.usedPercent>=90?"text-destructive":p.usedPercent>=70?"text-attention":"text-info"),"aria-hidden":"true",children:[e("circle",{cx:"12",cy:"12",r:"9.75",fill:"none",strokeWidth:"4.5",className:"stroke-current text-muted/50"}),e("circle",{cx:"12",cy:"12",r:"9.75",fill:"none",pathLength:100,strokeWidth:"4.5",strokeLinecap:"round",strokeDasharray:100,style:{strokeDashoffset:100-p.usedPercent},className:"stroke-current"})]})})}),0===le.length&&ce>0&&e("output",{className:"flex min-w-0 flex-wrap items-center gap-1.5","aria-live":"polite",children:t("span",{className:"inline-flex h-8 items-center gap-1 rounded-full px-2 text-xs text-muted",children:[e(Ln,{className:"size-3 text-attention"}),M("agent.activeWorkstreams",{count:ce})]})})]}),u&&a&&!B.trim()?e(r,{onClick:ke,disabled:d,variant:"ghost",size:"icon",className:i("size-9 rounded-full border border-border/60 bg-foreground text-background shadow-sm","hover:bg-foreground/90 hover:text-background","disabled:bg-mixer-muted/25 disabled:text-muted disabled:opacity-100","[&_svg]:text-destructive disabled:[&_svg]:text-muted"),title:M("agent.stopTooltip"),"aria-label":M("agent.stopTooltip"),children:d?e(K,{size:"sm"}):e(Fn,{className:"size-3 fill-current stroke-current"})}):e(r,{onClick:Ne,disabled:l||c||!B.trim()||R,variant:"ghost",size:"icon",className:i("size-9 rounded-full border border-border/60 bg-foreground text-background shadow-sm","hover:bg-foreground/90 hover:text-background","disabled:bg-mixer-muted/25 disabled:text-muted disabled:opacity-100"),title:M(R?"agent.waitForFiles":"agent.sendTooltip"),"aria-label":M(R?"agent.waitForFiles":"agent.send"),children:c?e(K,{size:"sm"}):e(Mn,{className:"size-4"})})]})]}),t(H,{isOpen:q,onClose:()=>Q(!1),className:"min-w-[60vw]",children:[e(G,{children:M("agent.linkObject")}),e(J,{className:"pb-6",children:e(Qh,{onChange:e=>{const t=`[${e.properties?.title||e.name||"Object"}](store:${e.id})`,n=B||"",r=U.current?.selectionStart||n.length,a=n.substring(0,r)+t+n.substring(r);V(a),Q(!1),setTimeout(()=>{if(U.current){U.current.focus();const e=r+t.length;U.current.setSelectionRange(e,e)}},100)}})})]}),j?.({isOpen:Y,onClose:ye,onSelect:we})]})}function ef({code:t}){const{onProposalSelect:n,onProposalSubmit:r}=da(),a=Me(()=>ua(t),[t]),s=Me(()=>{if(a)return null;try{const e=t.trim(),a=JSON.parse(e);if(!a.options||!a.question&&!a.title)return null;const s={question:a.question||a.title||"",description:a.description,options:Array.isArray(a.options)?a.options.map(e=>({id:e.id||e.value||"",label:e.label||"",description:e.description})):void 0,allowFreeResponse:a.allowFreeResponse??a.multiple,variant:a.variant,onSelect:n,onSubmit:r};return s.question&&s.options?.length?s:null}catch{return null}},[t,n,r,a]);return a?e(ma,{type:"proposal",message:"Loading options..."}):s?e(pa,{type:"proposal",fallbackCode:t,children:e(Oo,{...s})}):e(ma,{type:"proposal",error:"Invalid proposal specification"})}const tf=qe(function({code:t}){const n=Me(()=>{try{const e=JSON.parse(t);return"vega-lite"===e?.library&&e?.spec&&"object"==typeof e.spec?e:"string"==typeof e?.$schema&&e.$schema.includes("vega")?{library:"vega-lite",spec:e}:null}catch{return null}},[t]);return n?e(ds,{spec:n}):null}),nf=qe(function({code:t}){const n=Me(()=>{try{return{library:"vega-lite",spec:JSON.parse(t)}}catch{return null}},[t]);return n?e(ds,{spec:n}):null}),rf={chart:tf,"vega-lite":nf,vegalite:nf,"fusion-fragment":ta,proposal:ef,askuser:ef};function af({url:t,code:n}){const[r,a]=Oe(null);return He(()=>{import(t).then(e=>{a(()=>e.default)}).catch(e=>{console.error("Failed to load remote widget component from ",t,e)})},[t]),r?e(r,{code:n}):null}function sf({children:t}){const{client:n}=tr(),[r,a]=Oe(rf);return He(()=>{(async function(t){const n=await t.apps.getInstalledApps("tools"),r=new Set;for(const e of n){if(e.manifest.tool_collections&&e.manifest.tool_collections.length>0)for(const t of e.manifest.tool_collections||[]){const e=lr(t).url;if(e.startsWith("http://")||e.startsWith("https://")){const t=e.indexOf("/api/");if(t>0){const n=e.substring(0,t);r.add(`${n}/api/widgets`)}}}e.manifest.endpoint&&e.manifest.capabilities?.includes("tools")&&r.add(new URL("/api/widgets",e.manifest.endpoint).toString())}const a=await Promise.all(Array.from(r).map(t=>fetch(t).then(e=>{if(!e.ok)throw new Error(`Failed to fetch widgets: ${e.status} ${e.statusText}`);return e.json()}).then(t=>{const n=[],r=t.widgets;for(const[t,a]of Object.entries(r))n.push({name:t,component:t=>e(af,{url:a.url,code:t.code})});return n}).catch(()=>(console.error("Failed to fetch skill widgets from ",t),null)))),s={};for(const e of a.flat())e&&(s[e.name]=e.component);return s})(n).then(e=>{a({...rf,...e})})},[n]),e(ha,{components:r,children:t})}const of=new Map;function lf(e){if("number"==typeof e)return e;if(!e)return Date.now();const t=new Date(e).getTime();return Number.isFinite(t)?t:Date.now()}function cf(e){return"running"===e||"canceling"===e}function df(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function uf(e,t){return cf(e.status)||!cf(t.status)?{...e,...t}:{...e,interaction:e.interaction??t.interaction,elapsed_ms:Math.max(e.elapsed_ms,t.elapsed_ms),deadline_ms:Math.max(e.deadline_ms,t.deadline_ms),remaining_ms:0,phase:e.phase??t.phase,child_workflow_id:e.child_workflow_id??t.child_workflow_id,child_workflow_run_id:e.child_workflow_run_id??t.child_workflow_run_id}}function mf(e){const t=new Map,n=new Map;return e.forEach((e,r)=>{const a=lf(e.timestamp),s=function(e){const t=e.details,n="string"==typeof t?.workstream_id&&t.workstream_id.trim()?t.workstream_id:rl(e);return"main"===n||"all"===n?null:{workstreamId:n,launchId:"string"==typeof t?.launch_id?t.launch_id:void 0,interaction:"string"==typeof t?.interaction?t.interaction:void 0,childWorkflowId:"string"==typeof t?.child_workflow_id?t.child_workflow_id:void 0,childWorkflowRunId:"string"==typeof t?.child_workflow_run_id?t.child_workflow_run_id:void 0}}(e),i=Jo(e),o=i?.workstreamId??s?.workstreamId;if(!o)return;const l=i?.launchId??s?.launchId,c=Ho(e);if(!i&&!l&&c&&!n.has(o))return;const d=function(e,t,n,r,a,s){if(r){const s=t.get(n);if(s?.startsWith("message-derived:")){const t=e.get(s);t&&(e.delete(s),e.set(r,{...t,launch_id:r,updated_at:Math.max(t.updated_at,a)}))}t.set(n,r)}const i=r??t.get(n)??`message-derived:${n}`,o=e.get(i);if(o)return o;const l={workstream_id:n,launch_id:i,elapsed_ms:0,deadline_ms:0,remaining_ms:0,status:"running",started_at:a,updated_at:a,order:s};return e.set(i,l),t.has(n)||t.set(n,i),l}(t,n,o,l,a,r);i?(d.interaction=i.interaction??d.interaction,d.child_workflow_id=i.childWorkflowId??d.child_workflow_id,d.child_workflow_run_id=i.childWorkflowRunId??d.child_workflow_run_id,d.status="running"):(d.interaction=s?.interaction??d.interaction,d.child_workflow_id=s?.childWorkflowId??d.child_workflow_id,d.child_workflow_run_id=s?.childWorkflowRunId??d.child_workflow_run_id);const u=function(e){const t=e.details,n=t?.status;return"running"===n||"canceling"===n||"completed"===n||"canceled"===n||"failed"===n||"timeout"===n?n:"completed"===t?.workstream_event?"completed":void 0}(e);u?d.status=u:c||(!function(e){if(e.type!==ir.ERROR)return!1;const t=e.details;return"activity"===t?.event_class&&!t.workstream_event&&!(t.tool||t.tool_status||t.tool_run_id||t.activity_group_id||t.tool_event)}(e)?e.type!==ir.COMPLETE&&e.type!==ir.IDLE||(d.status="completed"):d.status="failed"),c||(d.updated_at=Math.max(d.updated_at,a),cf(d.status)?d.elapsed_ms=Math.max(d.elapsed_ms,a-d.started_at):(d.elapsed_ms=Math.max(d.elapsed_ms,a-d.started_at),d.remaining_ms=0))}),Array.from(t.values()).sort((e,t)=>{const n=Number(!cf(e.status))-Number(!cf(t.status));return 0!==n?n:cf(e.status)?e.order-t.order:t.updated_at-e.updated_at||e.order-t.order}).map(({started_at:e,updated_at:t,order:n,...r})=>r)}function pf(e){return{workstream_id:e.workstream_id,launch_id:e.launch_id,interaction:e.interaction,elapsed_ms:e.elapsed_ms,deadline_ms:e.deadline_ms,remaining_ms:Math.max(0,e.deadline_ms-e.elapsed_ms),status:e.status,phase:e.latest_progress?.phase,child_workflow_id:e.child_workflow_id,child_workflow_run_id:e.child_workflow_run_id}}function hf(e){return{workstream_id:e.workstream_id,launch_id:e.launch_id,interaction:e.interaction,elapsed_ms:e.duration_ms??0,deadline_ms:0,remaining_ms:0,status:e.status,phase:e.last_progress?.phase,child_workflow_id:e.child_workflow_id,child_workflow_run_id:e.child_workflow_run_id}}function ff(e,t){const n=e.findIndex(e=>e.launch_id===t.launch_id);if(n>=0)return void(e[n]=uf(e[n],t));const r=e.findIndex(e=>e.workstream_id===t.workstream_id&&e.launch_id.startsWith("message-derived:"));r>=0&&!t.launch_id.startsWith("message-derived:")?e[r]=uf(e[r],t):e.push(t)}function gf(e){if(e<60)return`${e}s`;const t=Math.floor(e/60),n=e%60;return n>0?`${t}m ${n}s`:`${t}m`}function vf({message:n,startedAt:r}){const{t:a}=Ze(),s=function(e,t=!0){const[n,r]=Oe(()=>Math.max(0,Math.floor((Date.now()-lf(e))/1e3)));return He(()=>{if(!t)return;const n=()=>{r(Math.max(0,Math.floor((Date.now()-lf(e))/1e3)))};n();const a=window.setInterval(n,1e3);return()=>window.clearInterval(a)},[t,e]),n}(r),o=function(e=!0){const[t,n]=Oe(0);return He(()=>{if(!e)return;const t=window.setInterval(()=>{n(()=>Math.floor(Math.random()*ql.length))},4e3);return()=>window.clearInterval(t)},[e]),t}();return t("div",{className:"mx-auto flex min-h-full w-full max-w-3xl flex-col justify-end gap-6 px-1 py-8",children:[e("div",{className:"flex w-full justify-end",children:e("div",{className:i("max-w-[min(44rem,82%)] rounded-[1.35rem] bg-mixer-muted/35 px-4 py-2.5","break-words text-sm font-normal leading-6 text-foreground/90 shadow-sm shadow-black/5","dark:bg-mixer-muted/15 dark:text-foreground/88 dark:shadow-none [overflow-wrap:anywhere]"),children:e("div",{className:"whitespace-pre-wrap",children:n})})}),t("div",{className:"border-b border-border/70 pb-4 text-sm text-muted",children:[t("div",{className:"flex items-center gap-3",children:[e(Ol,{size:"sm",color:"blue"}),t("div",{className:"min-w-0",children:[t("div",{children:[e("span",{className:"font-medium",children:a("agent.preparing")}),t("span",{className:"ms-2 text-muted/75",children:["for ",gf(s)]})]}),e("div",{className:"mt-1 truncate text-muted/80",children:ql[o]})]})]}),e("div",{className:"mt-3 ps-6",children:e(Ml,{color:"blue"})})]})]})}function bf(e){return function(e){let t=0,n=e.length;for(;t<n&&"-"===e[t];)t++;for(;n>t&&"-"===e[n-1];)n--;return e.slice(t,n)}(e.trim().replace(/[^a-z0-9-_]+/gi,"-")).slice(0,80)}function xf(t){const{agentRunId:n,startWorkflow:r}=t;return n?e(sf,{children:e(Nf,{...t,agentRunId:n})}):r?e(wf,{...t}):e(yf,{})}function yf(){const{t:n}=Ze();return t(Q,{status:"info",icon:e(Bt,{className:"size-16 text-muted mb-4"}),children:[e("div",{className:"text-base font-medium text-muted",children:n("agent.noAgentRunning")}),e("div",{className:"mt-3 text-sm text-muted",children:n("agent.selectInteraction")})]})}function wf({initialMessage:n,interactive:a=!0,startWorkflow:s,onClose:o,isModal:l=!1,fullWidth:c=!1,placeholder:d,startButtonText:u,title:m,getAttachedDocs:h,onAttachmentsSent:f,acceptedFileTypes:g,maxFiles:v=5,hideHeader:b=!1,hideFileUpload:x=!1,hideObjectLinking:y,headerVariant:w,inputContainerClassName:N,inputClassName:k,className:C,allowWorkflowControl:_,initialToolApprovalMode:S}){const{t:T}=Ze(),I=!x,z=d??T("agent.typeYourMessage"),R=u??T("agent.startAgent"),j=m??T("agent.startNewConversation"),{client:P}=tr(),[A,D]=Oe(""),[E,$]=Oe(!1),[L,F]=Oe(null),[M,O]=Oe(null),[U,W]=Oe(null),[B,V]=Oe(()=>vr(S,a)),q=p(),H=Be(null),G=Be(null),[J,Q]=Oe([]),[Y,Z]=Oe(!1),te=Be(0),ne=Ve(e=>{I&&(e.preventDefault(),e.stopPropagation(),te.current++,e.dataTransfer?.types?.includes("Files")&&Z(!0))},[I]),re=Ve(e=>{I&&(e.preventDefault(),e.stopPropagation())},[I]),ae=Ve(e=>{I&&(e.preventDefault(),e.stopPropagation(),te.current--,0===te.current&&Z(!1))},[I]),se=Ve(e=>{if(I&&(e.preventDefault(),e.stopPropagation(),te.current=0,Z(!1),e.dataTransfer?.files&&e.dataTransfer.files.length>0)){const t=Array.from(e.dataTransfer.files);Q(e=>[...e,...t].slice(0,v))}},[v,I]),ie=Ve(e=>{if(!I)return;const t=sm(e.clipboardData?.items);t.length>0&&Q(e=>[...e,...t].slice(0,v))},[I,v]),oe=Ve(e=>{if(e.target.files&&e.target.files.length>0){const t=Array.from(e.target.files);Q(e=>[...e,...t].slice(0,v))}e.target.value=""},[v]),le=Ve(e=>{Q(t=>t.filter((t,n)=>n!==e))},[]);He(()=>{H.current&&H.current.focus()},[]);const ce=async()=>{if(!s)return;const e=A.trim();if(e&&!E){$(!0);try{sessionStorage.removeItem("plan-panel-shown"),q({title:I&&J.length>0?T("agent.startingAgentUploading"):T("agent.startingAgent"),status:"info",duration:3e3});const t=h?.()||[];let n=e;if(t.length>0&&!/store:\S+/.test(e)){n=[e,"","Attachments:",...t.map(e=>`[${e.name}](/store/objects/${e.id})`)].join("\n")}if(I&&J.length>0){const e=J.map(e=>e.name).join(", ");n=[n,"",`[System: ${J.length} file(s) are being uploaded: ${e}. Please wait for the "Files Ready" notification before processing them.]`].join("\n")}O(n),W(Date.now());const r=await s(n,{tool_approval_mode:B});if(r){const e=r.agent_run_id,t=[];if(I&&J.length>0){for(const n of J)try{const r=`files/${n.name}`;await P.agents.uploadArtifact(e,r,n),await P.agents.sendSignal(e,"FileUploaded",{id:`file-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,name:n.name,content_type:n.type||"application/octet-stream",reference:`artifact:${r}`,artifact_path:r}),t.push(n.name)}catch(e){console.error(`Failed to upload staged file ${n.name}:`,e)}if(t.length>0)try{await P.agents.sendSignal(e,"UserInput",{message:`[Files Ready] All ${t.length} file(s) have been uploaded and are now available: ${t.join(", ")}. You can now process them.`,metadata:{type:"files_ready",files:t}})}catch(e){console.error("Failed to send files ready signal:",e)}Q([])}f?.(),F(e),D(""),q({title:T("agent.agentStarted"),status:"success",duration:3e3})}}catch(e){O(null),W(null),q({title:T("agent.errorStarting"),status:"error",duration:3e3,description:e instanceof Error?e.message:T("agent.unknownError")})}finally{$(!1)}}},de=Ve(()=>{const e=H.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]);return He(()=>{de()},[A,de]),L?e(Nf,{onClose:o,isModal:l,initialMessage:n,placeholder:d,fullWidth:c,hideHeader:b,headerVariant:w,hideFileUpload:x,hideObjectLinking:y,inputContainerClassName:N,inputClassName:k,className:C,allowWorkflowControl:_,agentRunId:L,title:m,pendingStartMessage:M??void 0,pendingStartTimestamp:U??void 0,initialToolApprovalMode:B}):e("div",{className:i("flex h-full flex-col items-center bg-background",C),children:t("div",{className:i("relative flex h-full w-full flex-col overflow-hidden border-0",c?"":"max-w-4xl"),onDragEnter:I?ne:void 0,onDragOver:I?re:void 0,onDragLeave:I?ae:void 0,onDrop:I?se:void 0,children:[I&&Y&&e("div",{className:"absolute inset-0 flex items-center justify-center bg-info-background z-50 pointer-events-none rounded-lg",children:t("div",{className:"text-info font-medium flex items-center gap-2 text-lg",children:[e(jn,{className:"size-6"}),"Drop files to stage for upload"]})}),I&&e("input",{ref:G,type:"file",multiple:!0,accept:g,onChange:oe,className:"hidden"}),!b&&t("div",{className:"flex items-center justify-between border-b border-border/60 bg-background px-3 py-2",children:[t("div",{className:"flex items-center gap-2",children:[e("div",{className:"p-1",children:e(On,{className:"size-3.5 text-muted"})}),e("span",{className:"text-sm font-medium text-foreground",children:j})]}),o&&!l&&e(r,{size:"xs",variant:"ghost",onClick:o,"aria-label":T("agent.close"),title:T("agent.close"),className:"text-muted hover:text-foreground",children:e(Et,{className:"size-4"})})]}),e("div",{className:"flex flex-1 flex-col items-center justify-end overflow-y-auto bg-background px-4",children:M&&U?e(vf,{message:M,startedAt:U}):e("div",{className:"mx-auto flex min-h-full w-full max-w-3xl flex-col justify-end py-8",children:n&&e("div",{className:"text-[15px] leading-relaxed text-foreground/80",children:n})})}),e("div",{className:"shrink-0 bg-background px-4 pb-safe-area-4 pt-2",children:t("div",{className:i("mx-auto flex max-w-3xl flex-col gap-3 rounded-2xl border border-border/70 bg-mixer-muted/15 p-3 shadow-lg shadow-black/5",N),children:[I&&J.length>0&&e("div",{className:"flex flex-wrap gap-2",children:J.map((n,a)=>t("div",{className:"flex items-center gap-1.5 rounded-md bg-attention/10 px-2 py-1 text-sm text-attention",title:T("agent.fileStagedTooltip"),children:[e(Ft,{className:"size-3.5"}),e("span",{className:"max-w-[120px] truncate",children:n.name}),e("span",{className:"text-xs opacity-70",children:T("agent.staged")}),e(r,{variant:"unstyled","aria-label":`Remove staged file ${n.name}`,onClick:()=>le(a),className:"ms-1 rounded p-0.5 hover:bg-attention/20",children:e(Et,{className:"size-3"})})]},`${n.name}-${n.size}-${n.lastModified}`))}),e(X,{ref:H,value:A,onChange:e=>D(e.target.value),onKeyDown:e=>{if("Enter"!==e.key)return;if(!(e.metaKey||e.ctrlKey||e.altKey||e.shiftKey))return e.preventDefault(),void ce();e.shiftKey||(e.preventDefault(),ee(e.currentTarget,D))},onPaste:ie,placeholder:z,disabled:E,rows:2,className:i("min-h-[72px] resize-none overflow-hidden border-0 bg-transparent px-0 py-0 text-sm leading-6 shadow-none focus-visible:ring-0",k),style:{minHeight:"72px",maxHeight:"200px"}}),t("div",{className:"flex items-center justify-between gap-3",children:[t("div",{className:"flex min-w-0 items-center gap-2",children:[I&&e(r,{variant:"ghost",size:"icon",onClick:()=>G.current?.click(),disabled:E||J.length>=v,"aria-label":T("agent.upload"),className:"rounded-full text-muted",title:T("agent.upload"),children:e(jn,{className:"size-4"})}),a&&e(Ja,{mode:B,onChange:V,disabled:E})]}),e(r,{onClick:ce,disabled:!A.trim()||E,variant:"ghost",size:"icon",className:i("size-9 rounded-full border border-border/60 bg-foreground text-background shadow-sm","hover:bg-foreground/90 hover:text-background","disabled:bg-mixer-muted/25 disabled:text-muted disabled:opacity-100"),title:R,"aria-label":R,children:E?e(K,{size:"sm"}):e(Mn,{className:"size-4"})})]})]})})]})})}function Nf({agentRunId:a,title:s,interactive:o=!0,onClose:l,isModal:c=!1,fullWidth:d=!1,placeholder:u,resetWorkflow:m,onRestart:h,onClone:f,onShowDetails:g,allowWorkflowControl:v=!0,uploadedFiles:b,onRemoveFile:x,acceptedFileTypes:y,maxFiles:w,renderDocumentSearch:N,selectedDocuments:k,onRemoveDocument:C,hideObjectLinking:_,hideHeader:S,headerVariant:T="full",hideMessageInput:I,failedAction:z,hidePlanPanel:R,hideWorkstreamTabs:j,showRightPanel:P=!0,hideFileUpload:A,showArtifacts:D=!1,hideDocumentPanel:E,hiddenMessageTypes:$,getAttachedDocs:L,onAttachmentsSent:F,isUploading:M=!1,getMessageContext:O,className:U,inputContainerClassName:W,inputClassName:B,fusionData:V,fileUploadRef:q,onProcessingFilesChange:K,processingFiles:Z,onPlansChange:X,onWorkstreamStatusChange:ee,viewMode:te,onViewModeChange:ne,onShowInputChange:re,stopRef:ae,onStoppingChange:se,messageItemClassNames:ie,messageStyleOverrides:oe,toolCallGroupClassNames:le,hideToolCallsInViewMode:ce,streamingMessageClassNames:de,batchProgressPanelClassNames:ue,workingIndicatorClassName:me,messageListClassName:pe,StoreLinkComponent:he,CollectionLinkComponent:fe,prependFriendlyMessage:ge,initialRequestData:ve,initialRequestSchema:be,initialRequestTitle:xe,initialRequestTemplate:ye,payloadContent:we,conversationContent:Ne,conversationTab:ke=!1,pendingStartMessage:Ce,pendingStartTimestamp:_e,initialToolApprovalMode:Se,enablePlayback:Te,showPlaybackToggle:Ie=!0}){const{t:ze}=Ze(),{client:Re}=tr(),je=p(),{messages:Pe,streamingMessages:Ae,isCompleted:De,initialHistoryStatus:Ee,debugChunkFlash:$e,addOptimisticMessage:Le,updateOptimisticMessageStatus:Fe,reconnect:Ue,agentRunStatus:We,workflowRunId:qe,serverFileUpdates:Ge}=pm(Re,a),{plans:Je,activePlanIndex:Ke,setActivePlanIndex:Qe,workstreamStatusMap:Ye,showInput:tt,showSlidingPanel:nt,setShowSlidingPanel:rt}=function(e,t,n=!1){const[r,a]=Oe([]),[s,i]=Oe(0),[o,l]=Oe(new Map),[c,d]=Oe(t),[u,m]=Oe(!n),p=Be(-1),h=Be(new Set);He(()=>{0===e.length&&(a([]),i(0),l(new Map),m(!n),p.current=-1,h.current.clear())},[e.length,n]);const f=Ve(e=>{const n=e[e.length-1];n&&(n.type===ir.TERMINATED?d(!1):d(!!t||n.type===ir.REQUEST_INPUT))},[t]);return He(()=>{if(0===e.length)return;const t=p.current+1;if(t>=e.length)return void f(e);let n=!1;const r=[],s=[];for(let a=t;a<e.length;a++){const t=e[a];if(t.type===ir.PLAN)try{let e=null;if(t.details&&"object"==typeof t.details&&t.details.plan&&Array.isArray(t.details.plan)&&(e={plan:t.details.plan}),e){const a="number"==typeof t.timestamp?t.timestamp:new Date(t.timestamp).getTime();if(!h.current.has(a)){h.current.add(a),n=!0,r.push({plan:e,timestamp:a});const t=new Map;t.set("main","in_progress"),Array.isArray(e.plan)&&e.plan.forEach(e=>{if(e&&"object"==typeof e&&e.id){const n=e.id.toString();t.set(n,e.status||"pending")}}),s.push({timestamp:a,statusMap:t})}}}catch(e){console.error("Failed to parse plan from message:",e)}}p.current=e.length-1,n&&r.length>0&&(a(e=>[...[...r].reverse(),...e]),i(0),m(!0),s.length>0&&l(e=>{const t=new Map(e);for(const e of s)t.set(e.timestamp,e.statusMap);return t})),f(e)},[e,f]),He(()=>{if(1===r.length&&!u&&!sessionStorage.getItem("plan-panel-shown")){const e=setTimeout(()=>{m(!0),sessionStorage.setItem("plan-panel-shown","true")},500);return()=>clearTimeout(e)}},[r.length,u]),{plans:r,activePlanIndex:s,setActivePlanIndex:i,workstreamStatusMap:o,showInput:c,showSlidingPanel:u,setShowSlidingPanel:m}}(Pe,o,c),{openDocuments:at,activeDocumentId:st,isDocPanelOpen:it,docRefreshKey:ot,closeDocPanel:lt,closeDocument:ct,selectDocument:dt,openDocInPanel:ut,updateDocumentTitle:mt}=function(e){const[t,n]=Oe([]),[r,a]=Oe(null),[s,i]=Oe(!1),[o,l]=Oe(0),c=Be(-1);return He(()=>{0===e.length&&(n([]),a(null),i(!1),l(0),c.current=-1)},[e.length]),He(()=>{const t=c.current+1;if(!(t>=e.length)){for(let r=t;r<e.length;r++){const t=e[r];if(t.type===ir.UPDATE&&t.details){const e=t.details;if("document_created"===e.event_class||"document_updated"===e.event_class){const t=hm(e.document_id),r=hm(e.updated_document_id)||t,s=e.title;if(r){const o={id:r,title:s||"Document",revisionRootId:fm(e,t||r)};n(e=>{const t=e.findIndex(e=>gm(e,o));if(t<0)return[...e,o];const n=e[t];if(n.id===o.id&&n.title===o.title&&n.revisionRootId===o.revisionRootId)return e;const r=[...e];return r[t]=o,r}),a(o.id),i(!0),"document_updated"===e.event_class&&l(e=>e+1)}}}}c.current=e.length-1}},[e]),{openDocuments:t,activeDocumentId:r,isDocPanelOpen:s,docRefreshKey:o,closeDocPanel:Ve(()=>{i(!1)},[]),closeDocument:Ve(e=>{n(t=>{const n=t.filter(t=>t.id!==e);return 0===n.length?(i(!1),a(null)):a(t=>t===e?n[0].id:t),n})},[]),selectDocument:Ve(e=>{a(e)},[]),openDocInPanel:Ve(e=>{n(t=>t.some(t=>t.id===e)?t:[...t,{id:e,title:"Document",revisionRootId:e}]),a(e),i(!0)},[]),updateDocumentTitle:Ve((e,t)=>{n(n=>n.map(n=>n.id===e?{...n,title:t}:n))},[])}}(Pe),{processingFiles:pt,hasProcessingFiles:ht,handleFileUpload:ft,removeProcessingFile:gt}=function(e,t,n,r){const a=Xe.getFixedT(null,et),[s,i]=Oe(new Map),[o,l]=Oe(new Set),c=Be(new Set),d=Be(new Map),u=Be(t),m=Ve(e=>{const t=d.current.get(e);t&&(bm(t),d.current.delete(e))},[]);He(()=>{if(u.current!==t){u.current=t,d.current.forEach(bm),d.current.clear(),i(new Map);const e=new Set;c.current=e,l(e)}},[t]),He(()=>()=>{d.current.forEach(bm),d.current.clear()},[]);const p=Me(()=>{const e=new Map;return s.forEach((t,n)=>{o.has(n)||e.set(n,t)}),n.forEach((t,n)=>{if(!o.has(n)){const r=s.get(n)?.preview_url;e.set(n,r?{...t,preview_url:r}:t)}}),e},[s,o,n]),h=Me(()=>Array.from(p.values()).some(e=>e.status===cr.UPLOADING||e.status===cr.PROCESSING),[p]),f=Ve(async n=>{for(const s of n){const n=`file-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,o=`files/${s.name}`,l=vm(s);l&&d.current.set(n,l);const u={id:n,name:s.name,content_type:s.type||"application/octet-stream",size:s.size,status:cr.UPLOADING,started_at:Date.now(),preview_url:l};i(e=>new Map(e).set(n,u));try{if(await e.agents.uploadArtifact(t,o,s),i(e=>{const t=new Map(e),r=t.get(n);return r&&(r.status=cr.PROCESSING,r.artifact_path=o,r.reference=`artifact:${o}`),t}),c.current.has(n))continue;await e.agents.sendSignal(t,"FileUploaded",{id:n,name:s.name,content_type:s.type||"application/octet-stream",reference:`artifact:${o}`,artifact_path:o})}catch(e){if(c.current.has(n))continue;i(t=>{const r=new Map(t),a=r.get(n);return a&&(a.status=cr.ERROR,a.error=e instanceof Error?e.message:"Upload failed",a.completed_at=Date.now()),r}),r({status:"error",title:a("agent.uploadFailed"),description:e instanceof Error?e.message:"Failed to upload file",duration:3e3})}}},[e,t,r,a]),g=Ve(async n=>{l(e=>{if(e.has(n))return e;const t=new Set(e);return t.add(n),c.current=t,t}),i(e=>{if(!e.has(n))return e;const t=new Map(e);return t.delete(n),t}),m(n);try{await e.agents.sendSignal(t,"FileRemoved",{id:n})}catch(e){r({status:"error",title:a("agent.removeFileFailed"),description:e instanceof Error?e.message:"Failed to remove file",duration:3e3})}},[t,e,m,a,r]);return{processingFiles:p,hasProcessingFiles:h,handleFileUpload:f,removeProcessingFile:g}}(Re,a,Ge,je),vt=o&&!A,bt=Ve(e=>{gt(e)},[gt]),xt=Be(null),yt=Be(null),wt=Be(null),[Nt,kt]=Oe(!1),[Ct,_t]=Oe(!1),[St,Tt]=Oe("sliding"),It=te??St,zt=Ve(e=>{ne?ne(e):Tt(e)},[ne]),[jt,Pt]=Oe(!1),[At,Dt]=Oe(!1),[Et,$t]=Oe("all"),[Lt,Ft]=Oe("live"),[Mt,Ot]=Oe(!1),[Ut,Wt]=Oe(0),[Bt,Vt]=Oe([]),[qt,Ht]=Oe([]),[Gt,Jt]=Oe(!1),Kt=Me(()=>void 0===Se&&o?void 0:vr(Se,o),[Se,o]),[Qt,Yt]=Oe(Kt),Zt=Be(!1),Xt=Be(0),en=Be(!1);He(()=>{Yt(Kt)},[Kt]);const tn=Be(Nt);tn.current=Nt;const nn=Be(ht);nn.current=ht;const rn=Me(()=>{const e=Pe.filter(e=>"main"===(e.workstream_id||"main"));return e[e.length-1]},[Pe]),an=Me(()=>rn?.type===ir.TERMINATED?"TERMINATED":rn?.type!==ir.COMPLETE||We&&"RUNNING"!==We?We:"COMPLETED",[rn,We]),sn=Me(()=>{const e=an?.toUpperCase();return"COMPLETED"===e||"FAILED"===e||"CANCELED"===e||"CANCELLED"===e||"TERMINATED"===e||"TIMED_OUT"===e},[an]),on=Me(()=>sn&&"FAILED"!==an?.toUpperCase()&&!!h,[sn,an,h]),ln=!I||on,cn=Me(()=>"FAILED"===an?.toUpperCase()||"FAILED"===We?.toUpperCase(),[an,We]),dn=Be(sn);dn.current=sn;const un=Be(on);un.current=on;const mn=Me(()=>{const e=Je[Ke]||{plan:{plan:[]},timestamp:0},t=Ye.get(e.timestamp)||new Map;return{plan:e.plan,workstreamStatus:t}},[Je,Ke,Ye]),pn=Me(()=>mf(Pe),[Pe]),hn=Me(()=>{const e=[...pn];for(const t of qt)ff(e,hf(t));for(const t of Bt)ff(e,pf(t));return e.map((e,t)=>({workstream:e,index:t})).sort((e,t)=>Number(!cf(e.workstream.status))-Number(!cf(t.workstream.status))||e.index-t.index).map(({workstream:e})=>e)},[pn,Bt,qt]),fn=Me(()=>hn.filter(e=>cf(e.status)),[hn]),gn=Me(()=>fn.filter(e=>"running"===e.status).length,[fn]),vn=Me(()=>{if("all"===Et)return;const e=hn.find(e=>e.workstream_id===Et||e.launch_id===Et);return e?Bo(e.workstream_id,e.interaction):Bo(Et)},[Et,hn]),bn=Me(()=>u||(vn?ze("agent.messageMainAgentWhileViewingWorkstream",{workstream:vn}):void 0),[vn,u,ze]),xn=Ie&&void 0===Te&&xs(),yn=Te??(ys()||Mt),wn=Me(()=>sl($?.length?Pe.filter(e=>!$.includes(e.type)):Pe,Et),[Et,$,Pe]),Nn=Me(()=>bs(wn,Lt,yn),[yn,Lt,wn]),kn=Nn.cursor,Cn=Nn.isLive,_n=yn&&!Cn&&Nn.cursorIndex===wn.length-1,Sn=Nn.displayedMessages,Tn=Cn?Ae:of,In=Me(()=>mf(Sn),[Sn]),zn=Me(()=>In.filter(e=>cf(e.status)),[In]),Rn=Me(()=>De||!el(Pe),[De,Pe]),Pn=!(!Cn&&!_n)&&Rn,An=Me(()=>$l(Sn),[Sn]),Dn=Boolean(An)&&!cn,En=yn&&!Cn,$n=ln&&!En,Ln=Me(()=>function(e){for(let t=e.length-1;t>=0;t--){const n=e[t].details;if(!n)continue;const r=n.token_usage,a=df(r?.total),s=df(n.checkpoint_threshold)??df(n.checkpoint_at);if("number"!=typeof a||"number"!=typeof s||s<=0)continue;const i=Math.max(0,Math.min(100,Math.round(a/s*100)));return{usedTokens:a,checkpointTokens:s,usedPercent:i,remainingPercent:Math.max(0,100-i)}}}(Pe),[Pe]),Fn=v&&!sn&&Cn&&Boolean(Ln);He(()=>{Yo("conversation render state",{agentRunId:a,messageCount:Pe.length,playbackMessageCount:wn.length,displayedMessageCount:Sn.length,streamingCount:Ae.size,displayedStreamingCount:Tn.size,initialHistoryStatus:Ee,isCompleted:De,effectiveIsCompleted:Rn,displayedIsCompleted:Pn,agentRunStatus:We,effectiveWorkflowStatus:an,isWorkflowTerminal:sn,playbackCursor:kn,isPlaybackEnabled:yn,isPlaybackLive:Cn,isPlaybackAtLatest:_n,activeWorkstream:Et,showInitialRequest:"empty"===Ee&&0===Pe.length,pendingStartVisible:0===Pe.length&&!Rn&&Boolean(Ce)})},[Et,a,We,kn,Pn,Sn.length,Tn.size,Rn,an,Ee,De,_n,yn,Cn,sn,Pe.length,Ce,wn.length,Ae.size]);const Mn=Ve(()=>{Ot(e=>!e)},[]),On=Ve(e=>{const t=fs(kn,wn.length),n=fs(e,wn.length);yn&&(n>t||"live"===e&&"live"!==kn)&&(en.current=!0,Wt(e=>e+1)),Ft(e)},[kn,yn,wn.length]);He(()=>{yn?kn!==Lt&&Ft(kn):"live"!==Lt&&Ft("live")},[kn,yn,Lt]),He(()=>{if(!yn||!en.current)return;en.current=!1;const e=window.requestAnimationFrame(()=>{xt.current?.scrollIntoView({behavior:"smooth",block:"end"})});return()=>window.cancelAnimationFrame(e)},[yn,Ut]);const Un=Ve(()=>{rt(e=>(e||sessionStorage.setItem("plan-panel-shown","true"),!e))},[rt]),Wn=Ve(e=>{Qe(e)},[Qe]),[Bn,Vn]=Oe(Ne||ke?"conversation":"plan"),[qn,Hn]=Oe(400),[Gn,Jn]=Oe(!1),Kn=P&&(nt||it||!j&&hn.length>0||!!Ne||ke);He(()=>{!Kn&&Gn&&Jn(!1)},[Kn,Gn]),He(()=>{if(!Gn)return;const e=e=>{const t=wt.current;if(!t)return;const n=t.getBoundingClientRect(),r=Math.max(300,n.width-420),a=n.right-e.clientX,s=Math.min(Math.max(a,300),r);Hn(s)},t=()=>{Jn(!1)};return window.addEventListener("mousemove",e),window.addEventListener("mouseup",t),document.body.style.cursor="col-resize",document.body.style.userSelect="none",()=>{window.removeEventListener("mousemove",e),window.removeEventListener("mouseup",t),document.body.style.cursor="",document.body.style.userSelect=""}},[Gn]);const Qn=Ve(()=>{rt(!1),lt()},[rt,lt]),Yn=Ve(({href:t,documentId:n,children:r})=>e("a",{href:t,className:"text-info underline cursor-pointer hover:text-info/80",onClick:e=>{e.preventDefault(),e.stopPropagation(),ut(n),Vn("documents")},children:r}),[ut]),Zn=he??Yn;He(()=>(q&&(q.current=vt?ft:null),()=>{q&&(q.current=null)}),[q,ft,vt]),He(()=>{K?.(pt)},[pt,K]),He(()=>{X?.(Je,Ke)},[Je,Ke,X]),He(()=>{ee?.(Ye)},[Ye,ee]),He(()=>{Zt.current=!1,Jt(!1),Vt([]),Ht([])},[a]),He(()=>{const e="loading"!==Ee&&!Rn&&!sn&&!Gt;if(Yo("active workstreams poll state",{agentRunId:a,shouldPoll:e,initialHistoryStatus:Ee,effectiveIsCompleted:Rn,isWorkflowTerminal:sn,isWorkstreamQueryUnavailable:Gt}),!e)return void Vt(e=>0===e.length?e:[]);let t=!1,n=!1;const r=async()=>{if(n)Yo("active workstreams fetch skipped while previous request is pending",{agentRunId:a});else{n=!0;try{Yo("active workstreams fetch start",{agentRunId:a});const e=await Re.agents.getActiveWorkstreams(a);if(t)return;if(Yo("active workstreams fetch success",{agentRunId:a,runningCount:e.running?.length??0,completedCount:e.completed?.length??0,unavailable:!0===e.unavailable}),Vt(e.running??[]),Ht(e.completed??[]),e.unavailable)return void Jt(!0);Zt.current=!1}catch(e){if(t)return;Vt(e=>0===e.length?e:[]),Jt(!0),Yo("active workstreams fetch failed",{agentRunId:a,error:e instanceof Error?e.message:String(e)}),Zt.current||(console.warn("Failed to fetch active workstreams:",e),Zt.current=!0)}finally{n=!1}}};r();const s=window.setInterval(r,1e4);return()=>{t=!0,window.clearInterval(s)}},[Re.agents,a,Rn,Ee,sn,Gt]),He(()=>{0!==Pe.length&&(on?re?.(!0):tt?an&&"RUNNING"!==an?re?.(!1):null!==an&&re?.(!0):re?.(!1))},[tt,an,Pe.length,re,on]);const Xn=Ve((e,t)=>{const n=e.trim();if(!n||tn.current)return;if(dn.current&&!un.current)return;if(nn.current)return void je({status:"warning",title:ze("agent.filesProcessing"),description:ze("agent.waitForFilesProcessing"),duration:3e3});kt(!0);const r=L?.()||[],s=O?.()||{};let i=n;if(r.length>0&&!/store:\S+/.test(n)){const e=r.map(e=>`[${e.name}](/store/objects/${e.id})`);i=[n,"","Attachments:",...e].join("\n")}const o=`msg-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,l={timestamp:Date.now(),workflow_run_id:a,type:ir.QUESTION,message:i,workstream_id:"main",details:{_optimistic:!0,_messageId:o,_deliveryStatus:"sending"}};Le(l);const c={...r.length>0?{attached_docs:r.map(e=>e.id)}:{},...s,...t,id:o,_messageId:o},d=()=>Re.agents.sendSignal(a,"UserInput",{message:i,client_message_id:o,metadata:c}),u=()=>{Fe(o,"received"),F?.()};(dn.current?Re.agents.restart(a).then(()=>(Ue(),d().then(u))):d().then(u)).catch(e=>{Fe(o,"failed"),je({status:"error",title:ze("agent.failedToSend"),description:e instanceof Error?e.message:ze("agent.unknownError"),duration:3e3})}).finally(()=>{kt(!1)})},[a,Re,je,L,O,F,Ue,Le,Fe,ze]),er=Ve(async e=>{try{await Re.agents.sendSignal(a,"McpConfigChanged",{})}catch(e){console.error("Failed to signal MCP config change",e)}Xn(ze("agent.mcpConnectedMessage",{name:e.name}))},[Re,a,Xn,ze]),[nr,rr]=Oe(void 0);He(()=>{let e=!1;return Re.agents.retrieve(a).then(t=>{e||(rr(t.disabled_mcp_collections),void 0===t.tool_approval_mode&&void 0===t.interactive||Yt(vr(t.tool_approval_mode,t.interactive)))}).catch(()=>{}),()=>{e=!0}},[Re,a]);const ar=Ve(e=>{const t=e.length>0?e:void 0;rr(t),Re.agents.sendSignal(a,"McpConfigChanged",{disabled_mcp_collections:e}).catch(e=>console.error("Failed to signal MCP config change",e))},[Re,a]),sr=Ve(()=>{Re.agents.sendSignal(a,"McpConfigChanged",{}).catch(e=>console.error("Failed to signal MCP config change",e))},[Re,a]),or=Ve(e=>{const t=vr(e,o);Yt(t),Re.agents.sendSignal(a,"ToolApprovalModeChanged",{mode:t}).catch(e=>{je({status:"error",title:ze("agent.approvalMode.changeFailed"),description:e instanceof Error?e.message:ze("agent.unknownError"),duration:3e3})})},[a,Re,o,ze,je]),lr=Ve(e=>{vt&&(e.preventDefault(),e.stopPropagation(),Xt.current++,e.dataTransfer?.types?.includes("Files")&&Dt(!0))},[vt]),dr=Ve(e=>{vt&&(e.preventDefault(),e.stopPropagation())},[vt]),ur=Ve(e=>{vt&&(e.preventDefault(),e.stopPropagation(),Xt.current--,0===Xt.current&&Dt(!1))},[vt]),mr=Ve(e=>{if(vt&&(e.preventDefault(),e.stopPropagation(),Xt.current=0,Dt(!1),e.dataTransfer?.files&&e.dataTransfer.files.length>0)){const t=Array.from(e.dataTransfer.files);ft(t)}},[ft,vt]),pr=Ve(async()=>{if(jt)return;const e=`stop-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,t={timestamp:Date.now(),workflow_run_id:a,type:ir.IDLE,message:"Stopped. Waiting for your command...",workstream_id:"main",details:{_optimistic:!0,_messageId:e,_deliveryStatus:"sending",display_role:"user_stopped",status_reason:"user_stopped"}};Le(t),Pt(!0);try{await Re.agents.sendSignal(a,"Stop",{message:"User requested stop",client_message_id:e,metadata:{id:e,_messageId:e}}),Fe(e,"received")}catch(t){je({status:"error",title:ze("agent.failedToInterrupt"),description:t instanceof Error?t.message:ze("agent.unknownError"),duration:3e3}),Fe(e,"failed")}finally{Pt(!1)}},[jt,a,Le,Re.agents,je,ze,Fe]),hr=Ve(async()=>{if(!Ct&&!Rn&&Cn){_t(!0);try{await Re.agents.sendSignal(a,"TriggerCheckpoint",{reason:"manual user request"})}catch(e){je({status:"error",title:ze("agent.failedToCompactContext"),description:e instanceof Error?e.message:ze("agent.unknownError"),duration:3e3})}finally{_t(!1)}}},[a,Re.agents,Rn,Ct,Cn,ze,je]);He(()=>(ae&&(ae.current=v&&!Rn?pr:null),()=>{ae&&(ae.current=null)}),[ae,Rn,pr,v]),He(()=>{se?.(jt)},[jt,se]);const fr=s||ze("agent.agentConversation"),gr=async()=>{try{const e=await il(Re,a);e&&window.open(e,"_blank")}catch(e){console.error("Failed to download conversation",e),je({status:"error",title:ze("agent.failedToDownload"),duration:3e3})}},br=Ve(()=>{const e=(new Date).toISOString(),t=Ae.size>0?[{cursor:"live",streamingMessages:Array.from(Ae,([e,t])=>({id:e,...t}))}]:void 0,n={metadata:{title:fr,agent_run_id:a,exported_at:e,message_count:Pe.length},messages:Pe,...t?{streamingFrames:t}:{}};!function(e,t){const n=new Blob([JSON.stringify(t,null,2)],{type:"application/json"}),r=URL.createObjectURL(n),a=document.createElement("a");a.href=r,a.download=e,document.body.appendChild(a),a.click(),a.remove(),URL.revokeObjectURL(r)}(`${bf(fr)||"agent-chat"}-${bf(a)}.json`,n),je({status:"success",title:ze("agent.rewind.fixtureExported"),duration:2e3})},[fr,a,Pe,Ae,ze,je]),[xr,yr]=Oe(!1),wr=()=>{yt.current?yr(!0):je({status:"error",title:ze("agent.pdfExportFailed"),description:ze("agent.noConversationContent"),duration:3e3})},Nr=Me(()=>Pe.filter(e=>{if(e.type===ir.COMPLETE)return!0;if(e.type===ir.THOUGHT){const t=e.details;return"completed"===t?.tool_status}return!1}).length,[Pe]),kr=Me(()=>mn.plan.plan?.reduce((e,t)=>(t.id&&t.goal&&e.set(t.id.toString(),t.goal),e),new Map),[mn.plan]),Cr=t=>e(_m,{title:fr,variant:t,isCompleted:Rn,isTerminal:sn,onClose:l,isModal:c,agentRunId:a,workflowRunId:qe||"",viewMode:It,onViewModeChange:zt,showPlanPanel:P&&nt,hasPlan:P&&Je.length>0,showPlanButton:P&&!ke,onTogglePlanPanel:Un,showPlaybackButton:xn,isPlaybackEnabled:yn,onTogglePlayback:Mn,onDownload:gr,onExportFixture:br,resetWorkflow:m,onClone:f,onShowDetails:g,allowWorkflowControl:v,onExportPdf:wr,isReceivingChunks:$e}),_r=t("div",{ref:yt,"data-agent-playback-enabled":yn||void 0,"data-agent-playback-cursor":yn?kn:void 0,"data-agent-live-message-count":Pe.length,"data-agent-rendered-message-count":Sn.length,className:i("flex flex-col min-h-0 min-w-0 border-0",ke?"flex-1 h-full":Kn?"w-full flex-1 min-h-[50vh]":d?"flex-1 w-full":"flex-1 mx-auto "+(c?"":"max-w-4xl")),children:[!S&&"compact"===T&&e("div",{className:"flex flex-shrink-0 justify-end border-b border-border/60 px-2 py-1 lg:hidden",children:Cr("compact")}),!S&&"compact"!==T&&e("div",{className:"flex-shrink-0",children:Cr(T)}),yn&&e("div",{className:"flex flex-shrink-0 justify-end px-2 py-1.5",children:e(ks,{cursor:kn,messages:wn,onChangeCursor:On})}),0===Pe.length&&!Rn&&Ce&&_e?e(vf,{message:Ce,startedAt:_e}):e(yu,{messages:Sn,bottomRef:xt,isCompleted:Pn,plan:mn.plan,workstreamStatus:mn.workstreamStatus,showPlanPanel:P&&nt,onTogglePlanPanel:Un,plans:Je,activePlanIndex:Ke,onChangePlan:Wn,taskLabels:kr,streamingMessages:Tn,onSendMessage:Cn?Xn:void 0,messageItemClassNames:ie,messageStyleOverrides:oe,toolCallGroupClassNames:le,hideToolCallsInViewMode:ce,streamingMessageClassNames:de,batchProgressPanelClassNames:ue,artifactRunId:a,viewMode:It,hideWorkstreamTabs:j,workingIndicatorClassName:me,messageListClassName:pe,StoreLinkComponent:Zn,CollectionLinkComponent:fe,prependFriendlyMessage:ge,initialRequestData:ve,initialRequestSchema:be,initialRequestTitle:xe,initialRequestTemplate:ye,showInitialRequest:"empty"===Ee&&0===Pe.length,hiddenMessageTypes:$,disableAutoScroll:!Cn,renderRequestInputControls:!Dn,activeWorkstream:Et,onActiveWorkstreamChange:$t}),Dn?e(Fl,{message:An,onSendMessage:Cn?Xn:void 0,onMcpConnected:Cn?er:void 0,disabled:M||!Cn,isLoading:Nt||M}):En&&zn.length>0?e("div",{className:"flex-shrink-0 pb-safe-area",children:e(xm,{activeWorkstreams:zn})}):$n&&e("div",{className:"flex-shrink-0 pb-safe-area",children:cn?z??e(Q,{status:"error",icon:null,className:"m-2",children:"This Workflow is FAILED"}):an&&"RUNNING"!==an&&!on?"sliding"===It&&"COMPLETED"===an?e("div",{className:"mx-auto w-full max-w-3xl px-4 py-3 text-sm text-muted",children:t("div",{className:"flex items-center gap-2 border-t border-success/25 pt-3 text-success",children:[e(Rt,{className:"size-4"}),e("span",{className:"font-medium",children:"Workflow completed"})]})}):t(Q,{status:"COMPLETED"===an?"success":"done",icon:null,className:"m-2",children:["This Workflow is ",an]}):(tt||on)&&e(Xh,{onSend:Xn,onStop:v?pr:void 0,approvalModeSlot:o&&Qt?e(Ja,{mode:Qt,onChange:or,disabled:!Cn||sn||!v}):void 0,mcpSlot:e(Au,{disabledCollections:nr,onChange:ar,onConnectionChange:sr}),disabled:M||!Cn,isSending:Nt||M,isStopping:jt,isStreaming:!Rn,isCompleted:Rn,contextWindowUsage:Fn?Ln:void 0,onCompactContext:Fn?hr:void 0,isCompactingContext:Ct,activeTaskCount:gn,activeWorkstreams:fn,placeholder:bn,onFilesSelected:vt?ft:void 0,uploadedFiles:b,onRemoveFile:x,onRemoveProcessingFile:bt,acceptedFileTypes:y,maxFiles:w,processingFiles:pt,artifactRunId:a,hasProcessingFiles:ht,renderDocumentSearch:N,selectedDocuments:k,onRemoveDocument:C,hideObjectLinking:_,hideFileUpload:!vt,disableDropZone:vt,className:W,inputClassName:B})})]}),Sr=e(Ya,{children:e(Jl,{children:t("div",{ref:wt,className:i("flex flex-col lg:flex-row gap-2 w-full h-full relative overflow-hidden",vt&&At&&"ring-2 ring-blue-400 ring-inset",U),onDragEnter:vt?lr:void 0,onDragOver:vt?dr:void 0,onDragLeave:vt?ur:void 0,onDrop:vt?mr:void 0,children:[vt&&At&&e("div",{className:"absolute inset-0 flex items-center justify-center bg-blue-100/80 dark:bg-blue-900/40 z-50 pointer-events-none rounded-lg",children:t("div",{className:"text-blue-600 dark:text-blue-400 font-medium flex items-center gap-2 text-lg",children:[e(jn,{className:"size-6"}),"Drop files to upload"]})}),!ke&&_r,!ke&&"compact"===T&&!S&&e("div",{className:"hidden h-full w-12 shrink-0 items-start justify-center px-1 pt-2 lg:flex",children:Cr("compact")}),Kn&&t(n,{children:[!ke&&e("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize right panel","aria-valuenow":Math.round(qn),"aria-valuemin":300,"aria-valuetext":`${Math.round(qn)} pixels`,tabIndex:0,className:"hidden lg:block lg:w-1 lg:shrink-0 cursor-col-resize bg-border/70 hover:bg-border transition-colors",onMouseDown:()=>Jn(!0),onKeyDown:e=>{if("ArrowLeft"!==e.key&&"ArrowRight"!==e.key)return;e.preventDefault();const t=e.shiftKey?32:16,n="ArrowLeft"===e.key?t:-t,r=wt.current,a=r?Math.max(300,r.getBoundingClientRect().width-420):900;Hn(e=>Math.min(Math.max(e+n,300),a))}}),e("div",{className:ke?"w-full h-full overflow-auto":"w-full lg:w-[var(--agent-right-panel-width)] lg:shrink-0 min-h-[50vh] lg:h-full border-t lg:border-t-0",style:ke?void 0:{"--agent-right-panel-width":`${qn}px`},children:e(am,{plan:mn.plan,workstreamStatus:mn.workstreamStatus,plans:Je,activePlanIndex:Ke,onChangePlan:Wn,showPlan:!R&&nt,activeWorkstreams:hn,hideWorkstreams:j,openDocuments:at,activeDocumentId:st,onSelectDocument:dt,onCloseDocument:ct,onUpdateDocumentTitle:mt,docRefreshKey:ot,runId:a,processingFiles:Z??pt,showArtifacts:D,artifactRefreshKey:Nr,messages:Pe,payloadContent:we,conversationContent:ke?_r:Ne,onClose:Qn,defaultTab:Bn,activeTab:Bn,onTabChange:Vn})})]}),t(H,{isOpen:xr,onClose:()=>yr(!1),children:[e(G,{children:"Export conversation as PDF"}),t(J,{children:[e("p",{className:"mb-2",children:"This will open your browser's print dialog with the current conversation."}),e("p",{className:"text-sm text-muted",children:'To save a PDF, choose "Save as PDF" or a similar option in the print dialog.'})]}),t(Y,{align:"right",children:[e(r,{variant:"ghost",size:"sm",onClick:()=>yr(!1),children:"Cancel"}),e(r,{size:"sm",onClick:()=>{if(!yt.current)return void je({status:"error",title:ze("agent.pdfExportFailed"),description:ze("agent.noConversationContent"),duration:3e3});const e=`${fr} - ${a}`,t=function(e,t){if("undefined"==typeof window||"undefined"==typeof document)return!1;const n=document.createElement("iframe");n.style.position="fixed",n.style.right="0",n.style.bottom="0",n.style.width="0",n.style.height="0",n.style.border="0",n.style.visibility="hidden",document.body.appendChild(n);const r=n.contentWindow;if(!r)return n.parentNode?.removeChild(n),!1;const a=r.document;return a.open(),a.write("<!doctype html><html><head><title></title></head><body></body></html>"),a.close(),a.title=t,document.querySelectorAll('link[rel="stylesheet"], style').forEach(e=>{a.head.appendChild(e.cloneNode(!0))}),a.body.innerHTML=e.innerHTML,r.focus(),r.print(),setTimeout(()=>{n.parentNode?.removeChild(n)},1e3),!0}(yt.current,e);t?(je({status:"success",title:ze("agent.pdfExportReady"),description:ze("agent.printDialogDescription"),duration:4e3}),yr(!1)):je({status:"error",title:ze("agent.pdfExportFailed"),description:ze("agent.unableToOpenPrint"),duration:4e3})},children:"Open print dialog"})]})]})]})})});return V?e(ea,{data:V,sendMessage:Xn,ChartComponent:ds,artifactRunId:a,children:Sr}):Sr}function kf({messages:t}){const n=Fe.useMemo(()=>[...t].sort((e,t)=>("number"==typeof e.timestamp?e.timestamp:new Date(e.timestamp).getTime())-("number"==typeof t.timestamp?t.timestamp:new Date(t.timestamp).getTime())),[t]);return e("div",{className:"flex flex-col overflow-y-auto space-y-6 py-4",children:n.map(t=>e(wc,{message:t,showPulsatingCircle:!1},`${t.workstream_id??"main"}-${t.timestamp}-${t.type}`))})}function Cf({messages:t,bottomRef:n,className:r,messagesClassName:a,emptyClassName:s}){const i=Fe.useRef(null);He(()=>{n.current&&n.current.scrollIntoView({behavior:"smooth"})},[t,n]);const o=Fe.useMemo(()=>[...t].sort((e,t)=>("number"==typeof e.timestamp?e.timestamp:new Date(e.timestamp).getTime())-("number"==typeof t.timestamp?t.timestamp:new Date(t.timestamp).getTime())),[t]);return e("div",{ref:i,className:`flex-1 min-h-0 h-full overflow-y-auto py-4 px-4 sm:px-6 lg:px-8 bg-white flex flex-col ${r||""}`,"data-testid":"messages-container",children:0===o.length?e("div",{className:`flex items-center justify-center h-full text-center py-8 ${s||""}`,children:e("div",{className:"flex items-center px-4 py-3 text-gray-500",children:"Waiting for agent response..."})}):e("div",{className:`flex-1 flex flex-col justify-start h-full min-h-0 ${a||""}`,children:e(kf,{messages:o,isCompleted:!1})})})}function _f({children:t,fallback:n}){return Sf?e(Sf,{fallback:n,children:t}):e(za,{FallbackComponent:n,children:t})}let Sf=null;function Tf(e){Sf=e}function If({children:t}){return e(_f,{fallback:zf,children:t})}function zf({error:n}){const{t:r}=Ze(),a=n instanceof Error?n.message:void 0;return t(Q,{status:"error",title:r("errors.somethingWentWrong"),children:[t("div",{className:"mb-4",children:[r("errors.teamNotifiedLine1")," ",r("errors.teamNotifiedLine2")," ",e("a",{className:"text-info",href:"mailto:support@vertesiahq.com",children:"support@vertesiahq.com"}),"."]}),a&&e("code",{className:"w-full mt-4 text-sm text-muted break-words",children:a})]})}function Rf({children:t}){return e(_f,{fallback:jf,children:t})}function jf({error:n}){const r=n instanceof Error?n.message:void 0;return e("tr",{children:t("td",{colSpan:100,children:[e("span",{className:"text-xs",children:" Cannot display row"}),e("br",{}),e("span",{className:"bg-gray-400",children:r})]})})}function Pf({children:t}){return e(_f,{fallback:Af,children:t})}function Af({error:n}){const r=n instanceof Error?n.message:void 0;return console.log("WidgetError",n),t("div",{className:"text-sm",children:["Sorry, this area cannot be loaded or rendered.",r&&e("pre",{children:r})]})}const Df=/^[a-f0-9]{24}$|^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$|^(?=.*\d)(?=.*[a-zA-Z])[a-zA-Z0-9_-]{8,}$/i;function Ef(e){return Df.test(e)}function $f({className:n,children:r,title:a,description:s,actions:i,breadcrumbs:o,useDynamicBreadcrumbs:l=!0}){const c=ia();function d(e){return e.replace(/[-_]/g," ").split(" ").map(e=>$r(e)).join(" ")}const u=e=>{if(e?.title)return e.title;const t=e?.href||"";if(!t)return"Page";const n=t.split("#")[0].split("?")[0].split("/").filter(e=>e.length>0);return n.length>=1?d(n[n.length-1]):"Page"},m=(()=>{const e=[];if(l&&"undefined"!=typeof window){const t=window.history.state,n=t?.historyChain;if(Array.isArray(n))n.forEach((t,r)=>{const a=n.length-r;e.push({label:u(t),href:t.href,onClick:()=>c(t.href,{stepsBack:a})})});else{const t=window.location.pathname.split("/").filter(e=>e.length>0);for(let n=0;n<t.length;n++)if(Ef(t[n])){const r=`/${t.slice(0,n).join("/")}`;e.push({label:d(t[n-1]||r),href:r,onClick:()=>c(r,{isBasePathNested:!1})})}}}return o&&o.length>0&&o.forEach(t=>{const n=t.props?.children||t,r=t.props?.href;e.push(r?{href:r,label:n,onClick:()=>c(r,{replace:t.props.clearBreadcrumbs})}:{label:n})}),e})();return t("div",{className:Ae("pb-0 ps-4 pe-2 py-2 flex flex-col",n),children:[t("div",{className:"flex items-start gap-4",children:[t("div",{className:"w-full flex place-content-between h-auto min-h-8 flex-col items-start justify-center",children:[t("nav",{className:"flex-1 flex justify-start text-sm",children:[m.length>0&&e(te,{path:m,separator:e(ht,{className:"size-3.5 cn-rtl-flip"}),maxItems:4}),s&&e(h,{description:s,children:e(qt,{className:"size-4 text-muted ms-4"})})]}),a&&e("div",{className:"flex gap-2 items-center",children:e("h1",{className:"text-xl font-semibold break-all",children:a})})]}),e("div",{className:"flex gap-x-2 shrink-0 items-center",children:i})]}),r&&e("div",{className:"w-full flex items-center",children:r})]})}function Lf(){const{t:n}=Ze();return t("div",{className:"text-center pt-32",children:[e("h1",{className:"text-3xl font-bold text-red-500",children:"404"}),e("p",{className:"text-2xl",children:n("layout.pageNotFound")})]})}function Ff({className:t,size:n="md"}){return e("div",{className:`flex items-center justify-center ${t||""}`,children:e(st,{className:`${{sm:"w-4 h-4",md:"w-6 h-6",lg:"w-8 h-8"}[n]} animate-spin text-muted-foreground`})})}function Mf({pdfUrl:n,pageNumber:r,width:a,className:s,renderTextLayer:i=!1,renderAnnotationLayer:o=!1,onLoadSuccess:l,onError:c}){const[d,u]=Oe(!0),[m,p]=Oe(null);return m?e("div",{className:`flex items-center justify-center text-destructive text-sm ${s||""}`,children:"Failed to load PDF"}):t("div",{className:s,children:[d&&e(Ff,{className:"py-4",size:"md"}),e(ja,{file:n,onLoadSuccess:({numPages:e})=>{u(!1),l?.(e)},onLoadError:e=>{u(!1),p(e),c?.(e)},loading:null,children:e(Pa,{pageNumber:r,width:a,renderTextLayer:i,renderAnnotationLayer:o,loading:e(Ff,{className:"py-4",size:"sm"})})})]})}Ra.GlobalWorkerOptions.workerSrc=`//unpkg.com/pdfjs-dist@${Ra.version}/build/pdf.worker.min.mjs`;const Of=Ue(null);function Uf({pdfUrl:t,urlLoading:n=!1,children:r,onLoadSuccess:a}){const[s,i]=Oe(0),[o,l]=Oe(!0),[c,d]=Oe(null),[u,m]=Oe(null),p={pdfUrl:t,numPages:s,loading:n||!t||o,error:c,pageDimensions:u};return c?e("div",{className:"flex items-center justify-center text-destructive text-sm py-4",children:"Failed to load PDF"}):e(Of.Provider,{value:p,children:t?e(ja,{file:t,onLoadSuccess:async e=>{i(e.numPages),a?.(e.numPages);try{const t=(await e.getPage(1)).getViewport({scale:1});m({width:t.width,height:t.height,aspectRatio:t.width/t.height})}catch(e){console.error("Failed to get page dimensions:",e)}l(!1)},onLoadError:e=>{l(!1),d(e)},loading:e(Ff,{className:"py-4",size:"md"}),children:r((t,n)=>e(Pa,{pageNumber:t,width:n,renderTextLayer:!1,renderAnnotationLayer:!1,loading:e(Ff,{className:"py-4",size:"sm"})},t))}):e(Ff,{className:"py-4",size:"md"})})}function Wf(){return We(Of)}const Bf=210/297;function Vf({pageNumber:t,width:n,className:r}){const a=Wf(),s=a?.pageDimensions?.aspectRatio??Bf,i=n?Math.round(n/s):200;return e("div",a?.loading?{className:`flex items-center justify-center bg-muted ${r||""}`,style:{height:i,width:n||"100%"},children:e(Ff,{size:"md"})}:{className:r,children:e(Pa,{pageNumber:t,width:n,renderTextLayer:!1,renderAnnotationLayer:!1,loading:e(Ff,{className:"py-4",size:"sm"})})})}function qf({pageNumber:t,width:n,isSelected:r,onSelect:a,renderThumbnail:s,aspectRatio:i=Bf,rootMargin:o="200px 0px"}){const l=Be(null),[c,d]=Oe(!1);He(()=>{const e=l.current;if(!e)return;const t=new IntersectionObserver(e=>{const t=e[0];t?.isIntersecting&&d(!0)},{rootMargin:o,threshold:0});return t.observe(e),()=>t.disconnect()},[o]);const u=n?Math.round(n/i):200,m=c?e(Pa,{pageNumber:t,width:n,renderTextLayer:!1,renderAnnotationLayer:!1,loading:e("div",{className:"flex items-center justify-center bg-muted",style:{height:u},children:e(Ff,{size:"sm"})})}):e("div",{className:"flex items-center justify-center bg-muted",style:{height:u,width:n||"100%"},children:e("span",{className:"text-muted-foreground text-xs",children:t})});return e("div",{ref:l,children:s({pageNumber:t,isSelected:r,pageElement:m,onSelect:a})})}function Hf({pdfUrl:r,urlLoading:a=!1,pageCount:s,currentPage:i,thumbnailWidth:o,onPageSelect:l,renderThumbnail:c,scrollContainerRef:d,onAspectRatioChange:u,onItemHeightChange:m,calculateItemHeight:p,onPageCountChange:h}){const[f,g]=Oe(null),[v,b]=Oe({start:0,end:Math.min(15,s)}),[x,y]=Oe(null),w=Be(null),N=Ve(e=>{g(e)},[]),k=Ve(async e=>{h?.(e.numPages);try{const t=(await e.getPage(1)).getViewport({scale:1}),n=t.width/t.height;y(n),u?.(n)}catch(e){console.error("Failed to get page dimensions:",e),y(Bf),u?.(Bf)}},[u,h]),C=x??Bf,_=o?Math.round(o/C):200,S=p?p(_):_+16+24+8;He(()=>{S>0&&null!==x&&m?.(S)},[S,x,m]);if(He(()=>{const e=d?.current||function(e){if(!e)return null;let t=e.parentElement;for(;t;){const e=window.getComputedStyle(t).overflowY;if("auto"===e||"scroll"===e)return t;t=t.parentElement}return null}(w.current);if(!e)return;const t=()=>{const t=e.scrollTop,n=e.clientHeight,r=Math.floor(t/S),a=Math.ceil((t+n)/S),i=Math.max(0,r-5),o=Math.min(s,a+5);b(e=>e.start!==i||e.end!==o?{start:i,end:o}:e)};return t(),e.addEventListener("scroll",t,{passive:!0}),()=>e.removeEventListener("scroll",t)},[S,s,d]),f)return e("div",{className:"flex items-center justify-center text-destructive text-sm py-4",children:"Failed to load PDF"});if(a||!r)return e(Ff,{className:"py-4",size:"md"});const T=v.start*S,I=(s-v.end)*S,z=null!==x;return e("div",{ref:w,children:e(ja,{file:r,onLoadSuccess:k,onLoadError:N,loading:e(Ff,{className:"py-4",size:"md"}),children:z?t(n,{children:[T>0&&e("div",{style:{height:T}}),Array.from({length:v.end-v.start},(t,n)=>{const r=v.start+n+1;return e("div",{"data-page-index":r-1,style:{height:S,overflow:"hidden"},children:e(qf,{pageNumber:r,width:o,isSelected:r===i,onSelect:()=>l(r),renderThumbnail:c,aspectRatio:C})},r)}),I>0&&e("div",{style:{height:I}})]}):e(Ff,{className:"py-4",size:"md"})})})}function Gf({pdfUrl:n,pageNumber:r,width:a,height:s,className:i,renderTextLayer:o=!1,renderAnnotationLayer:l=!1,onPageChange:c}){const[d,u]=Oe(0),[m,p]=Oe(!0),[h,f]=Oe(null);He(()=>{d>0&&c?.(r,d)},[r,d,c]);return h?e("div",{className:`flex items-center justify-center text-destructive ${i||""}`,children:t("span",{children:["Failed to load PDF: ",h.message]})}):t("div",{className:i,children:[m&&e(Ff,{className:"py-8",size:"lg"}),e(ja,{file:n,onLoadSuccess:({numPages:e})=>{u(e),p(!1)},onLoadError:e=>{p(!1),f(e)},loading:null,children:e(Pa,{pageNumber:Math.min(r,d||1),width:a,height:s,renderTextLayer:o,renderAnnotationLayer:l,loading:e(Ff,{className:"py-8",size:"md"})})})]})}const Jf=210/297,Kf=[50,75,100,125,150,200,300];function Qf({pdfUrl:a,pdfUrlLoading:s=!1,pageCount:i,currentPage:o,onChange:l,onPageCountChange:c,className:d,compact:u=!1,headerExtra:m}){const{t:p}=Ze(),h=Be(null),f=Be(null),[g,v]=Oe(void 0),[b,y]=Oe(100),[w,N]=Oe(Jf),[k,C]=Oe(null),_=Be(null),S=g?Math.round(g*b/100):void 0,T=Ve(()=>{let e=Kf.findIndex(e=>e>=b);-1===e&&(e=Kf.length-1);const t=Math.min(e+1,Kf.length-1);y(Kf[t])},[b]),I=Ve(()=>{let e=Kf.findIndex(e=>e>=b);-1===e&&(e=Kf.length-1);const t=Math.max(e-1,0);y(Kf[t])},[b]),z=Ve(()=>{y(100)},[]),R=Ve(e=>e+(u?28:48),[u]),j=Ve((e,t)=>{const n=e?Math.round(e/t):200;return R(n)},[R]);He(()=>{const e=f.current;if(!e)return;let t=null;const n=()=>e.clientWidth-16-16-4,r=()=>{const t=n();if(t<=0)return;const r=_.current;if(r&&r>0){const n=e.scrollTop,a=Math.round(n/r),s=j(t,w),i=a*s;v(t),requestAnimationFrame(()=>{e.scrollTo({top:i,behavior:"instant"})}),_.current=s}else v(t),_.current=j(t,w)},a=n();a>0&&(v(a),_.current=j(a,w));const s=new ResizeObserver(()=>{t&&clearTimeout(t),t=setTimeout(r,150)});return s.observe(e),()=>{t&&clearTimeout(t),s.disconnect()}},[w,j]);const P=Be(!1),A=Be(null),D=Be(b);He(()=>{D.current!==b&&(D.current=b,A.current={targetPage:o},P.current=!0)},[b,o]),He(()=>{const e=f.current,t=A.current;if(t&&e&&k){A.current=null;const n=(t.targetPage-1)*k;requestAnimationFrame(()=>{e.scrollTo({top:n,behavior:"instant"}),requestAnimationFrame(()=>{P.current=!1})})}},[k]);const E=Be(!1);He(()=>{const e=f.current;if(e&&k&&!E.current)if(o>1){E.current=!0,P.current=!0;const t=(o-1)*k;e.scrollTo({top:t,behavior:"instant"}),requestAnimationFrame(()=>{P.current=!1})}else E.current=!0},[k,o]);const $=Be(o);He(()=>{const e=f.current;if(e&&k&&$.current!==o){$.current=o,P.current=!0;const t=(o-1)*k;e.scrollTo({top:t,behavior:"instant"}),requestAnimationFrame(()=>{P.current=!1})}},[o,k]),He(()=>{const e=f.current;if(!e||!k)return;let t=null;const n=()=>{P.current||(t&&clearTimeout(t),t=setTimeout(()=>{const t=e.scrollTop,n=Math.round(t/k)+1,r=Math.max(1,Math.min(n,i));r!==o&&($.current=r,l(r))},50))};return e.addEventListener("scroll",n,{passive:!0}),()=>{t&&clearTimeout(t),e.removeEventListener("scroll",n)}},[k,i,o,l]);return t("div",{ref:h,className:Ae("flex flex-col items-stretch",u?"gap-y-1":"gap-y-2",d),children:[t("div",{className:Ae("relative flex items-center justify-center px-2",u?"h-6":"h-9"),children:[e(r,{variant:"ghost",size:"xs",onClick:()=>{o>1&&l(o-1)},alt:p("pdf.previousPage"),children:e(Un,{className:"size-4"})}),t("div",{className:"absolute start-2 flex items-center gap-x-1",children:[e(Zf,{zoom:b,onZoomIn:T,onZoomOut:I,onFitToView:z,canZoomIn:b<Kf[Kf.length-1],canZoomOut:b>Kf[0]}),m&&t(n,{children:[e("div",{className:"w-px h-4 bg-border mx-1"}),m]})]}),e("div",{className:"absolute end-2",children:e(Yf,{currentPage:o,totalPages:i,onChange:l})})]}),e("div",{ref:f,className:Ae("flex flex-col items-center flex-1 overflow-y-auto px-2",u?"gap-1":"gap-2"),children:e(Hf,{pdfUrl:a,urlLoading:s,pageCount:i,currentPage:o,thumbnailWidth:S,onPageSelect:l,onPageCountChange:c,scrollContainerRef:f,onAspectRatioChange:N,onItemHeightChange:C,calculateItemHeight:R,renderThumbnail:({pageNumber:n,isSelected:a,pageElement:s,onSelect:i})=>t("div",{className:Ae("hover:bg-muted rounded-md w-full",u?"p-1":"p-2"),children:[e(r,{variant:"unstyled",size:"none","aria-pressed":a,"aria-label":`Page ${n}`,className:Ae("relative border-[2px] cursor-pointer overflow-hidden",a?"border-primary":"border-border"),onClick:i,children:s}),e(x,{className:Ae("text-muted-foreground font-semibold",u?"text-xs pt-0.5":"text-sm pt-1"),children:n})]},n)})}),e("div",{className:Ae("flex items-center justify-center",u?"h-6":"h-9"),children:e(r,{variant:"ghost",size:"xs",onClick:()=>{o<i&&l(o+1)},alt:p("pdf.nextPage"),children:e(Wn,{className:"size-4"})})})]})}function Yf({currentPage:n,totalPages:r,onChange:a}){const{t:s}=Ze(),i=Be(null),[o,l]=Oe(String(n));He(()=>{l(String(n))},[n]);const c=()=>{const e=parseInt(o,10);!Number.isNaN(e)&&e>=1&&e<=r?a(e):l(String(n))};return t("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e("span",{children:s("pdf.page")}),e("input",{ref:i,type:"text",value:o,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"===e.key?(c(),i.current?.blur()):"Escape"===e.key&&(l(String(n)),i.current?.blur())},onBlur:()=>{c()},className:"w-8 h-5 text-center text-xs px-1 py-0 bg-background border border-border rounded focus:outline-none focus:border-primary"}),t("span",{children:["/ ",r]})]})}function Zf({zoom:n,onZoomIn:a,onZoomOut:s,onFitToView:i,canZoomIn:o,canZoomOut:l}){const{t:c}=Ze();return t("div",{className:"flex items-center gap-x-0.5",children:[e(r,{variant:"ghost",size:"xs",onClick:s,isDisabled:!l,alt:c("pdf.zoomOut"),children:e(Bn,{})}),t("span",{className:"text-xs text-muted-foreground min-w-[32px] text-center",children:[n,"%"]}),e(r,{variant:"ghost",size:"xs",onClick:a,isDisabled:!o,alt:c("pdf.zoomIn"),children:e(Vn,{})}),e(r,{variant:"ghost",size:"xs",onClick:i,alt:c("pdf.fitToWidth"),className:100===n?"text-muted-foreground/40":void 0,children:e(qn,{})})]})}const Xf="magic-pdf";var eg;!function(e){e.original="original",e.instrumented="instrumented"}(eg||(eg={}));class tg{client;objectId;totalPages;cache=new Map;pending=new Map;constructor(e,t,n){this.client=e,this.objectId=t,this.totalPages=n}getCacheKey(e,t){return`${t}-${e}`}async getPageImageUrl(e,t){const n=this.getCacheKey(e,t),r=this.cache.get(n);if(r)return r;const a=this.pending.get(n);if(a)return a;const s=this.fetchImageUrl(e,t);this.pending.set(n,s);try{const e=await s;return this.cache.set(n,e),e}finally{this.pending.delete(n)}}async fetchImageUrl(e,t){const n=this.getImagePath(e,t);return(await this.client.files.getDownloadUrl(n)).url}getImagePath(e,t){const n=`${Xf}/${this.objectId}/pages`;switch(t){case eg.original:return`${n}/page-${e}.original.jpg`;case eg.instrumented:return`${n}/page-${e}.instrumented.jpg`}}}class ng{client;objectId;totalPages;cache=new Map;pending=new Map;constructor(e,t,n){this.client=e,this.objectId=t,this.totalPages=n}async getPageLayout(e){const t=this.cache.get(e);if(void 0!==t)return t;const n=this.pending.get(e);if(n)return n;const r=this.fetchPageLayout(e);this.pending.set(e,r);try{const t=await r;return this.cache.set(e,t),t}finally{this.pending.delete(e)}}async fetchPageLayout(e){const t=`${Xf}/${this.objectId}/pages/page-${e}.layout.json`,n=await this.client.files.getDownloadUrl(t),r=await fetch(n.url,{method:"GET"});if(!r.ok)throw new Error(`Failed to fetch json layout: ${r.statusText}`);return r.text()}}class rg{totalPages;pages=[];constructor(e){this.totalPages=e}initFromContent(e){this.pages=function(e,t){const n=new Array(t).fill(""),r=/<!--\s*\{\s*"page"\s*:\s*(\d+)\s*\}\s*-->/g,a=[];for(const t of e.matchAll(r))a.push({page:parseInt(t[1],10),index:t.index+t[0].length});for(let r=0;r<a.length;r++){const s=a[r],i=s.page-1;if(i<0||i>=t)continue;const o=s.index,l=e.slice(o).match(/<!--\s*\{\s*"page"\s*:\s*\d+\s*\}\s*-->/),c=l?o+l.index:e.length;let d=e.slice(o,c).trim();d=d.replace(/\n---\s*$/,"").trim(),n[i]=d}return n}(e,this.totalPages)}async loadUrls(e,t){}async getPageMarkdown(e){const t=e-1;return t<0||t>=this.pages.length?"":this.pages[t]}}const ag=Ue(void 0);function sg({children:t,object:n}){const{client:r}=tr(),a=n.metadata.page_count||10,s="markdown"===n.metadata?.content_processor?.type,[i,o]=Oe(()=>{const e=new rg(a);s&&n.text&&e.initFromContent(n.text);const t=n.text?lg(n.text):"";return{count:a,layoutProvider:new ng(r,n.id,a),markdownProvider:e,imageProvider:new tg(r,n.id,a),xml:t,xmlPages:n.text?og(t):[],pdfUrl:"",pdfUrlLoading:!0}});return He(()=>{if(s){const e=n.metadata,t=e?.renditions?.find(e=>e.name===br),a="application/pdf"===n.content?.type,s=t?.content?.source||(a?n.content?.source:void 0);s?r.store.objects.getDownloadUrl(s,void 0,"inline").then(e=>{o(t=>({...t,pdfUrl:e.url,pdfUrlLoading:!1}))}).catch(e=>{console.warn("Failed to get PDF URL:",e),o(e=>({...e,pdfUrlLoading:!1}))}):o(e=>({...e,pdfUrlLoading:!1}))}else o(e=>({...e,pdfUrlLoading:!1}))},[r,s,n.metadata,n.content?.type,n.content?.source]),e(ag.Provider,{value:i,children:t})}function ig(){const e=Fe.useContext(ag);if(!e)throw new Error("useMagicPdfContext must be used within a MagicPdfProvider");return e}function og(e){const t=(new DOMParser).parseFromString(lg(e),"text/xml").getElementsByTagName("page"),n=new XMLSerializer;return Array.from(t).map(e=>n.serializeToString(e))}function lg(e){return e.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,"").replace(/<\?xml.*?\?>/g,"")}const cg=[50,75,100,125,150,200,300],dg=11/8.5;function ug({className:n,currentPage:a,onChange:s}){const{t:i}=Ze(),[o,l]=Oe(eg.instrumented),[c,d]=Oe(dg),[u,m]=Oe(new Map),[p,h]=Oe(100),f=Be(new Set),g=Be(null),v=Be(null),b=Be(!1),{imageProvider:x,count:y}=ig(),w=Ve(()=>{let e=cg.findIndex(e=>e>=p);-1===e&&(e=cg.length-1);const t=Math.min(e+1,cg.length-1);h(cg[t])},[p]),N=Ve(()=>{let e=cg.findIndex(e=>e>=p);-1===e&&(e=cg.length-1);const t=Math.max(e-1,0);h(cg[t])},[p]),k=Ve(()=>{h(100)},[]);He(()=>{x.getPageImageUrl(1,o).then(e=>{const t=new window.Image;t.onload=()=>{t.width>0&&t.height>0&&d(t.height/t.width)},t.src=e}).catch(()=>{})},[x,o]);const C=Be(o);He(()=>{let e=!1;C.current!==o&&(C.current=o,f.current=new Set,m(new Map));const t=function(e,t){const n=[e];let r=1;for(;n.length<t;){const a=e+r,s=e-r;a<=t&&n.push(a),s>=1&&n.push(s),r++}return n}(a,y);return t.forEach(t=>{(async t=>{if(!e&&!f.current.has(t))try{const n=await x.getPageImageUrl(t,o);e||(f.current.add(t),m(e=>new Map(e).set(t,n)))}catch{}})(t)}),()=>{e=!0}},[a,y,o,x]);const _=Be(p);He(()=>{if(_.current!==p&&v.current){_.current=p,b.current=!0;const e=v.current.querySelector(`[data-page="${a}"]`);e?requestAnimationFrame(()=>{e.scrollIntoView({behavior:"instant",block:"center"}),requestAnimationFrame(()=>{b.current=!1})}):b.current=!1}},[p,a]);const S=Be(a);He(()=>{if(S.current!==a&&v.current){S.current=a,b.current=!0;const e=v.current.querySelector(`[data-page="${a}"]`);e&&e.scrollIntoView({behavior:"instant",block:"nearest"}),requestAnimationFrame(()=>{b.current=!1})}},[a]),He(()=>{const e=v.current;if(!e)return;let t=null;const n=()=>{b.current||(t&&clearTimeout(t),t=setTimeout(()=>{const t=e.getBoundingClientRect(),n=t.top+t.height/2;let r=a,i=1/0;for(let t=1;t<=y;t++){const a=e.querySelector(`[data-page="${t}"]`);if(a){const e=a.getBoundingClientRect(),s=e.top+e.height/2,o=Math.abs(s-n);o<i&&(i=o,r=t)}}r!==a&&(S.current=r,s(r))},50))};return e.addEventListener("scroll",n,{passive:!0}),()=>{t&&clearTimeout(t),e.removeEventListener("scroll",n)}},[y,a,s]);return t("div",{ref:g,className:Ae("flex flex-col items-stretch gap-y-2",n),children:[t("div",{className:"relative flex items-center justify-center px-2 h-9",children:[e(r,{variant:"ghost",size:"xs",onClick:()=>{a>1&&s(a-1)},alt:i("pdf.previousPage"),children:e(Un,{className:"size-4"})}),t("div",{className:"absolute start-2 flex items-center gap-x-1",children:[e(mg,{type:eg.original,currentType:o,onClick:()=>l(eg.original),icon:e(St,{className:"size-4"}),tooltip:i("pdf.originalImages")}),e(mg,{type:eg.instrumented,currentType:o,onClick:()=>l(eg.instrumented),icon:e(Hn,{className:"size-4"}),tooltip:i("pdf.instrumentedImages")}),e("div",{className:"w-px h-4 bg-border mx-1"}),e(pg,{zoom:p,onZoomIn:w,onZoomOut:N,onFitToView:k,canZoomIn:p<cg[cg.length-1],canZoomOut:p>cg[0]})]}),e("div",{className:"absolute end-2",children:e(fg,{currentPage:a,totalPages:y,onChange:s})})]}),e("div",{ref:v,className:"flex flex-col items-center gap-2 flex-1 overflow-y-auto px-2",children:Array.from({length:y},(t,n)=>e(hg,{currentPage:a,pageNumber:n+1,aspectRatio:c,zoom:p,url:u.get(n+1),onSelect:()=>s(n+1)},n))}),e("div",{className:"flex items-center justify-center h-9",children:e(r,{variant:"ghost",size:"xs",onClick:()=>{a<y&&s(a+1)},alt:i("pdf.nextPage"),children:e(Wn,{className:"size-4"})})})]})}function mg({type:t,currentType:n,onClick:a,icon:s,tooltip:i}){const o=t===n;return e(h,{description:i,placement:"bottom",size:"xs",children:e(r,{variant:"unstyled","aria-label":i,"aria-pressed":o,className:Ae("p-1 rounded cursor-pointer transition-colors",o?"text-primary bg-primary/10":"text-muted-foreground hover:text-foreground hover:bg-muted"),onClick:a,children:s})})}function pg({zoom:n,onZoomIn:a,onZoomOut:s,onFitToView:i,canZoomIn:o,canZoomOut:l}){const{t:c}=Ze();return t("div",{className:"flex items-center gap-x-0.5",children:[e(h,{description:c("pdf.zoomOut"),placement:"bottom",size:"xs",children:e(r,{variant:"unstyled","aria-label":c("pdf.zoomOut"),className:Ae("p-1 rounded cursor-pointer transition-colors",l?"text-muted-foreground hover:text-foreground hover:bg-muted":"text-muted-foreground/40 cursor-not-allowed"),onClick:s,disabled:!l,children:e(Bn,{className:"size-4"})})}),t("span",{className:"text-xs text-muted-foreground min-w-[32px] text-center",children:[n,"%"]}),e(h,{description:c("pdf.zoomIn"),placement:"bottom",size:"xs",children:e(r,{variant:"unstyled","aria-label":c("pdf.zoomIn"),className:Ae("p-1 rounded cursor-pointer transition-colors",o?"text-muted-foreground hover:text-foreground hover:bg-muted":"text-muted-foreground/40 cursor-not-allowed"),onClick:a,disabled:!o,children:e(Vn,{className:"size-4"})})}),e(h,{description:c("pdf.fitToWidth"),placement:"bottom",size:"xs",children:e(r,{variant:"unstyled","aria-label":c("pdf.fitToWidth"),className:Ae("p-1 rounded cursor-pointer transition-colors",100!==n?"text-muted-foreground hover:text-foreground hover:bg-muted":"text-muted-foreground/40"),onClick:i,children:e(qn,{className:"size-4"})})})]})}function hg({pageNumber:n,currentPage:a,aspectRatio:s,zoom:i,url:o,onSelect:l}){const c=n===a;return t("div",{className:"p-2 hover:bg-muted rounded-md flex flex-col items-center","data-page":n,style:{width:`${i}%`},children:[e(r,{variant:"unstyled",size:"none","aria-pressed":c,"aria-label":`Page ${n}`,className:Ae("relative border-[2px] cursor-pointer overflow-hidden !flex items-center justify-center bg-muted/50 w-full",c?"border-primary":"border-border"),style:{aspectRatio:`1 / ${s}`},onClick:l,children:o?e("img",{src:o,alt:`Page ${n}`,className:"w-full"}):e(st,{className:"w-6 h-6 animate-spin text-muted-foreground"})}),e(x,{className:"text-sm text-muted-foreground pt-1 font-semibold",children:n})]})}function fg({currentPage:n,totalPages:r,onChange:a}){const{t:s}=Ze(),i=Be(null),[o,l]=Oe(String(n));He(()=>{l(String(n))},[n]);const c=()=>{const e=parseInt(o,10);!Number.isNaN(e)&&e>=1&&e<=r?a(e):l(String(n))};return t("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e("span",{children:s("pdf.page")}),e("input",{ref:i,type:"text",value:o,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"===e.key?(c(),i.current?.blur()):"Escape"===e.key&&(l(String(n)),i.current?.blur())},onBlur:()=>{c()},className:"w-8 h-5 text-center text-xs px-1 py-0 bg-background border border-border rounded focus:outline-none focus:border-primary"}),t("span",{children:["/ ",r]})]})}function gg({object:n}){const{t:a}=Ze(),{client:s}=tr(),i=e=>{(function(e,t,n){return e.files.getDownloadUrl(`${Xf}/${t}/${n}`).then(e=>e.url)})(s,n.id,e).then(e=>window.open(e,"_blank"))},o="p-2 cursor-pointer hover:bg-muted text-start text-sm";return"markdown"===(()=>{if("document"===n.metadata?.type){const e=n.metadata;return e.content_processor?.type||"xml"}return"xml"})()?e(r,{variant:"ghost",size:"xs",onClick:()=>i("document.md"),alt:a("pdf.download"),children:e(lt,{className:"size-4"})}):t(I,{children:[e(z,{children:e(r,{variant:"ghost",size:"xs",alt:a("pdf.download"),children:e(lt,{className:"size-4"})})}),e(R,{align:"start",className:"p-0 w-auto",children:t("div",{className:"min-w-[200px] flex flex-col divide-y divide-border",children:[e(r,{variant:"unstyled",className:o,onClick:()=>i("annotated.pdf"),children:"annotated.pdf"}),e(r,{variant:"unstyled",className:o,onClick:()=>i("document.xml"),children:"document.xml"}),e(r,{variant:"unstyled",className:o,onClick:()=>i("analyzed-pages.json"),children:"analyzed-pages.json"})]})})]})}function vg({className:t}){return e("div",{className:`flex items-center justify-center ${t||""}`,children:e(st,{className:"w-6 h-6 animate-spin text-gray-400"})})}function bg({viewType:t,pageNumber:n}){switch(t){case"json":return e(yg,{pageNumber:n});case"markdown":return e(wg,{pageNumber:n});default:return e(xg,{pageNumber:n})}}function xg({pageNumber:t}){const{xmlPages:n}=ig();return e("div",{className:"px-4 py-2",children:e(fa,{xml:n[t-1],collapsible:!0})})}function yg({pageNumber:t}){const[n,r]=Oe(null),[a,s]=Oe(!0),[i,o]=Oe(null),{layoutProvider:l}=ig();return He(()=>{s(!0),o(null),l.getPageLayout(t).then(e=>{r(e?JSON.parse(e):null),s(!1)}).catch(e=>{console.error(e),o(e.message||"Failed to load layout"),s(!1)})},[t,l]),a?e("div",{className:"px-4 py-8",children:e(vg,{})}):i?e("div",{className:"px-4 py-2 text-red-500 text-sm",children:i}):n?e(ga,{className:"w-full",data:n}):null}function wg({pageNumber:n}){const[r,a]=Oe(null),[s,i]=Oe(!0),[o,l]=Oe(null),{markdownProvider:c}=ig();return He(()=>{i(!0),l(null),c.getPageMarkdown(n).then(e=>{a(e),i(!1)}).catch(e=>{console.error(e),l(e.message||"Failed to load markdown"),i(!1)})},[n,c]),s?t("div",{className:"h-full flex flex-col items-center justify-center gap-2",children:[e(vg,{}),e("span",{className:"text-sm text-muted-foreground",children:"Loading..."})]}):e("div",o?{className:"px-4 py-2 text-red-500 text-sm",children:o}:{className:"px-4 py-2 prose prose-sm max-w-none dark:prose-invert",children:r?e(oa,{children:r}):e("div",{children:"No markdown content available"})})}class Ng extends Ke{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){console.error("PDF View error:",e,t)}render(){return this.state.hasError?e("div",{className:"fixed inset-0 bg-background z-50 flex items-center justify-center",children:t("div",{className:"flex flex-col items-center gap-4 p-8 max-w-md",children:[e(b,{title:Xe.t("pdf.failedToLoadViewer",{ns:et}),children:this.state.error?.message||"An unexpected error occurred"}),this.props.onClose&&e(r,{variant:"outline",onClick:this.props.onClose,children:"Close"})]})}):this.props.children}}function kg({objectId:n,onClose:a}){const{t:s}=Ze(),{client:i}=tr(),{data:o,error:l}=S(()=>i.store.objects.retrieve(n,"+text"),[n]);return l?e("div",{className:"fixed inset-0 bg-background z-50 flex items-center justify-center",children:t("div",{className:"flex flex-col items-center gap-4 p-8 max-w-md",children:[e(b,{title:s("pdf.fetchingDocumentFailed"),children:T(l)}),a&&e(r,{variant:"outline",onClick:a,children:"Close"})]})}):o?e(Ng,{onClose:a,children:e("div",{className:"fixed inset-0 bg-background z-50 flex items-center justify-center",children:e(sg,{object:o,children:e(Cg,{object:o,onClose:a})})})}):t("div",{className:"fixed inset-0 bg-background z-50 flex flex-col",children:[e("div",{className:"flex h-9 items-center justify-end shrink-0 bg-sidebar px-2 border-b border-sidebar-border",children:a&&e(r,{variant:"ghost",size:"xs",onClick:a,alt:s("pdf.close"),children:e(ut,{className:"size-4"})})}),e("div",{className:"flex-1 flex items-center justify-center",children:e("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})]})}function Cg({object:n,onClose:a}){const{t:s}=Ze(),{count:i,pdfUrl:o,pdfUrlLoading:l}=ig(),[c,d]=Oe(1),u=(()=>{if("document"===n.metadata?.type){const e=n.metadata,t=e.content_processor?.type;if("markdown"===t)return"markdown"}return"xml"})();return t(ne,"xml"===u?{direction:"horizontal",className:"absolute inset-0",children:[e(re,{defaultSize:50,minSize:20,maxSize:80,className:"bg-muted",children:e(ug,{className:"h-full",currentPage:c,onChange:d})}),e(ae,{className:"w-[4px] bg-border cursor-ew-resize"}),t(re,{defaultSize:50,minSize:20,className:"flex flex-col",children:[t("div",{className:"flex h-9 items-center justify-between shrink-0 bg-sidebar px-2 border-b border-sidebar-border",children:[e("div",{className:"flex items-center gap-x-2",children:e(gg,{object:n})}),e("span",{className:"text-xs text-muted-foreground",children:s("pdf.pageOf",{pageNumber:c,totalPages:i})}),e("div",{className:"flex items-center gap-x-2",children:!!a&&e(r,{variant:"ghost",size:"xs",onClick:a,alt:s("pdf.close"),children:e(ut,{className:"size-4"})})})]}),e("div",{className:"flex-1 overflow-auto px-2",children:e(bg,{pageNumber:c,viewType:"xml"})})]})]}:{direction:"horizontal",className:"absolute inset-0",children:[e(re,{defaultSize:50,minSize:20,maxSize:80,className:"bg-muted",children:e(Qf,{pdfUrl:o,pdfUrlLoading:l,pageCount:i,className:"h-full",currentPage:c,onChange:d})}),e(ae,{className:"w-[4px] bg-border cursor-ew-resize"}),t(re,{defaultSize:50,minSize:20,className:"flex flex-col",children:[t("div",{className:"flex h-9 items-center justify-between shrink-0 bg-sidebar px-2 border-b border-sidebar-border",children:[e("div",{className:"flex items-center gap-x-2",children:e(gg,{object:n})}),e("span",{className:"text-xs text-muted-foreground",children:s("pdf.pageOf",{pageNumber:c,totalPages:i})}),e("div",{className:"flex items-center gap-x-2",children:!!a&&e(r,{variant:"ghost",size:"xs",onClick:a,alt:s("pdf.close"),children:e(ut,{className:"size-4"})})})]}),e("div",{className:"flex-1 overflow-auto px-2",children:e(bg,{pageNumber:c,viewType:"markdown"})})]})]})}const _g=["image/jpeg","image/jpg","image/png","image/gif","image/webp","image/svg+xml"],Sg=["video/mp4","video/webm"],Tg=["audio/mp4","audio/m4a","audio/x-m4a","audio/mpeg","audio/ogg","audio/wav","audio/webm"];function Ig(e){const t=Math.floor(e/3600),n=Math.floor(e%3600/60),r=Math.floor(e%60);return t>0?`${t}:${n.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}`:`${n}:${r.toString().padStart(2,"0")}`}function zg({url:n,source:r,object:a,className:s}){const{t:i}=Ze(),{client:o}=tr(),[l,c]=Oe(n),[d,u]=Oe(!(n||!r&&!a)),m=a?.metadata,p=(m?.renditions||[]).find(e=>e.name===xr),h=a?.content?.type&&Tg.includes(a.content.type),f=!!a&&a.metadata?.type===yr.Audio&&!p&&!h;return He(()=>{if(n)return c(n),void u(!1);c(void 0);r||a?(u(!0),(async()=>{try{if(r){const e=await o.files.getDownloadUrl(r);return void c(e.url)}if(!a)return;if(a.metadata?.type!==yr.Audio)return;let e;p?.content?.source?e=await o.files.getDownloadUrl(p.content.source):h&&a.content?.source&&(e=await o.files.getDownloadUrl(a.content.source)),e&&c(e.url)}catch(e){console.error("Failed to get audio URL",e)}finally{u(!1)}})()):u(!1)},[n,r,a,p,h,o]),f?e("div",{className:`flex justify-center items-center h-[200px] text-muted ${s??""}`.trim(),children:t("div",{className:"text-center",children:[e("p",{children:i("store.noAudioRendition")}),e("p",{className:"text-sm mt-2",children:i("store.audioFormatRequired")})]})}):d?e("div",{className:`flex justify-center items-center h-[200px] ${s??""}`.trim(),children:e(K,{size:"md"})}):l?t("div",{className:`flex flex-col items-center gap-4 ${s??""}`.trim(),children:[e("audio",{src:l,controls:!0,className:"w-full max-w-2xl",children:"Your browser does not support the audio tag."}),m?.duration&&t("div",{className:"text-sm text-muted",children:["Duration: ",Ig(m.duration)]})]}):e("div",{className:`flex justify-center items-center h-[200px] text-muted ${s??""}`.trim(),children:"Failed to load audio"})}function Rg({url:t,source:n,object:r,className:a}){const{client:s}=tr(),[i,o]=Oe(t),[l,c]=Oe(!(t||!n&&!r));return He(()=>{if(t)return o(t),void c(!1);o(void 0);n||r?(c(!0),(async()=>{try{if(n){const e=await s.files.getDownloadUrl(n);return void o(e.url)}if(!r)return;if(r.metadata?.type!==yr.Image)return;const e=r.content?.type&&_g.includes(r.content.type);try{const e=await s.objects.getRendition(r.id,{format:fr.jpeg,generate_if_missing:!1,sign_url:!0});if("found"===e.status&&e.renditions?.length)return void o(e.renditions[0])}catch{}if(e&&r.content?.source){const e=await s.files.getDownloadUrl(r.content.source);o(e.url)}}finally{c(!1)}})()):c(!1)},[t,n,r,s]),l?e("div",{className:a,children:e(K,{size:"md"})}):i?e("img",{src:i,alt:r?.name,className:`w-full object-contain ${a??""}`.trim()}):null}function jg({url:n,source:r,object:a,className:s}){const{t:i}=Ze(),{client:o}=tr(),[l,c]=Oe(n),[d,u]=Oe(),[m,p]=Oe(!(n||!r&&!a)),h=a?.metadata,f=h?.renditions||[],g=f.find(e=>"video/mp4"===e.content.type)||f.find(e=>"video/webm"===e.content.type),v=a?.content?.type&&Sg.includes(a.content.type),b=f.find(e=>e.name===wr),x=!!a&&a.metadata?.type===yr.Video&&!g&&!v;return He(()=>{if(n)return c(n),void p(!1);c(void 0),u(void 0);r||a?(p(!0),(async()=>{try{if(r){const e=await o.files.getDownloadUrl(r);return void c(e.url)}if(!a)return;if(a.metadata?.type!==yr.Video)return;let e;g?.content?.source?e=await o.files.getDownloadUrl(g.content.source):v&&a.content?.source&&(e=await o.files.getDownloadUrl(a.content.source)),e&&c(e.url)}catch(e){console.error("Failed to get video URL",e)}finally{p(!1)}})()):p(!1)},[n,r,a,g,v,o]),He(()=>{b?.content?.source&&o.files.getDownloadUrl(b.content.source).then(e=>u(e.url)).catch(e=>console.error("Failed to load poster image",e))},[b,o]),x?e("div",{className:`flex justify-center items-center h-[400px] text-muted ${s??""}`.trim(),children:t("div",{className:"text-center",children:[e("p",{children:i("store.noVideoRendition")}),e("p",{className:"text-sm mt-2",children:i("store.videoFormatRequired")})]})}):m?e("div",{className:`flex justify-center items-center h-[400px] ${s??""}`.trim(),children:e(K,{size:"md"})}):l?e("video",{src:l,poster:d,controls:!0,className:`w-full h-full object-contain ${s??""}`.trim(),children:"Your browser does not support the video tag."}):e("div",{className:`flex justify-center items-center h-[400px] text-muted ${s??""}`.trim(),children:"Failed to load video"})}function Pg({oauthProviderId:r,onAuthChange:a}){const{client:s}=tr(),{t:i}=Ze(),[o,l]=Oe(null),[c,d]=Oe(!0),[u,m]=Oe(!1),[p,h]=Oe(!1),f=Ve(async()=>{try{d(!0);const e=await s.oauthProviders.getStatus(r);l(e)}catch(e){console.error("Failed to load OAuth provider status:",e)}finally{d(!1)}},[s,r]);He(()=>{f()},[f]);const{openOAuthPopup:g}=yi({onComplete:()=>{m(!1),f(),a?.()},onError:e=>{console.error("OAuth provider auth failed:",e),m(!1)}}),v=async()=>{if(!p)try{h(!0),await s.oauthProviders.disconnect(r),await f(),a?.()}catch(e){console.error("Failed to disconnect OAuth provider:",e)}finally{h(!1)}};return c?e(xi,{className:"size-4"}):o?.authenticated?t("div",{className:"flex items-center gap-2",children:[t("div",{className:"flex items-center gap-1 text-success text-sm",children:[e(xt,{className:"size-4"}),e("span",{children:i("oauthProvider.connected")})]}),e(Ls,{variant:"outline",size:"sm",onClick:v,disabled:p,children:p?e(xi,{className:"size-3"}):i("oauthProvider.disconnect")})]}):e(Ls,{variant:"outline",size:"sm",onClick:async()=>{if(!u)try{m(!0);const e=await s.oauthProviders.authorize(r);e.authorization_url&&g(e.authorization_url)}catch(e){console.error("Failed to authorize OAuth provider:",e),m(!1)}},disabled:u,children:t(n,u?{children:[e(xi,{className:"size-4"}),e("span",{children:i("oauthProvider.authenticating")})]}:{children:[e($t,{className:"size-4 me-1"}),e("span",{children:i("oauthProvider.authenticate")})]})})}function Ag({object:n,url:a,source:s,className:i}){const{t:o}=Ze(),{client:l}=tr(),[c,d]=Oe(1),[u,m]=Oe(a||""),[p,f]=Oe(!a),[g,v]=Oe(0),[b,x]=Oe(!1);He(()=>{if(a)return m(a),void f(!1);const e=s||n?.content?.source;e?(f(!0),l.files.getDownloadUrl(e).then(e=>{m(e.url)}).catch(e=>{console.error("Failed to get PDF URL:",e)}).finally(()=>{f(!1)})):f(!1)},[a,s,n?.content?.source,l]),He(()=>{const e=n?.metadata,t=e?.pages||e?.page_count||0;t>0&&v(t)},[n?.metadata]);const y=e=>{v(e)};return p?e("div",{className:"flex items-center justify-center h-full",children:e(K,{size:"lg"})}):u?b?t("div",{className:"fixed inset-0 bg-background z-50 flex flex-col overflow-hidden",children:[e("div",{className:"flex h-9 items-center justify-end shrink-0 bg-sidebar px-2 border-b border-sidebar-border",children:e(r,{variant:"ghost",size:"xs",onClick:()=>x(!1),alt:o("pdf.closeFullscreen"),children:e(ut,{className:"size-4"})})}),e(Qf,{pdfUrl:u,pdfUrlLoading:p,pageCount:g||100,currentPage:c,onChange:d,onPageCountChange:y,className:"flex-1 min-h-0"})]}):e("div",{className:"relative h-full flex flex-col",children:e(Qf,{pdfUrl:u,pdfUrlLoading:p,pageCount:g||100,currentPage:c,onChange:d,onPageCountChange:y,className:i,compact:!0,headerExtra:e(h,{description:o("pdf.fullscreen"),placement:"bottom",size:"xs",children:e(r,{variant:"unstyled",className:"p-1 rounded cursor-pointer transition-colors text-muted-foreground hover:text-foreground hover:bg-muted",onClick:()=>x(!0),"aria-label":o("pdf.fullscreen"),children:e(dt,{className:"size-4"})})})})}):e("div",{className:"flex items-center justify-center h-full text-muted",children:o("pdf.noPdfAvailable")})}function Dg(...e){const t=Array.from(e);return t.__AnyOf__=!0,t}function Eg(...e){return Array.from(e)}function $g(e){return!0===e.__AnyOf__}class Lg{system_roles;roles;permissions;constructor(e,t){if(!e.authToken)throw new Error("No auth token found in user session");this.system_roles=t;const n=new Set(e.authToken.account_roles||[]);if(e.authToken.project_roles)for(const t of e.authToken.project_roles)n.add(t);this.roles=n;const r={};for(const e of t)r[e.name]=e.permissions;const a=e.authToken.type===hr.OAuthAccess?new Set(e.authToken.permissions??[]):void 0,s=new Set;for(const e of n){const t=r[e];if(t)for(const e of t)a&&!a.has(e)||s.add(e)}this.permissions=s}hasPermission(e){if("string"==typeof e)return this.permissions.has(e);if($g(e))return e.some(e=>this.permissions.has(e));for(const t of e)if(!this.permissions.has(t))return!1;return!0}}const Fg=Ue(void 0);function Mg(){const e=We(Fg);if(!e)throw new Error("UserPermissionContext cannot be used outside UserPermissionProvider");return e}function Og({children:t}){const{t:n}=Ze(),r=tr(),{data:a,error:s,isLoading:i}=S(()=>r.user?r.client.iam.roles.listSystem():Promise.resolve(void 0),[r.user]),o=Me(()=>r.authToken&&a&&!i?new Lg(r,a):void 0,[r,a,i]);return s?e(b,{title:n("store.failedToFetchRoleMappings"),children:T(s)}):o&&e(Fg.Provider,{value:o,children:t})}function Ug({permission:t,isDisabled:n,title:a,children:s,...i}){return Mg().hasPermission(t)?e(r,{isDisabled:n,title:a,...i,children:s}):null}function Wg({permission:t,...n}){return Mg().hasPermission(t)?e(Aa,{...n}):null}class Bg extends oe{idOf(e){return e.id}labelOf(e){return e.label}descriptionOf(e){return e.description}selectedClassName(e){return"border-3 border-primary"}}function Vg({isOpen:n,onClose:a,onConfirm:s,isLoading:i,uploadedFileName:o}){const{t:l}=Ze(),c=Me(()=>[{id:"update",label:l("modal.saveVersion.updateCurrent"),description:l(o?"modal.saveVersion.updateWithFileDescription":"modal.saveVersion.updateDescription")},{id:"new-version",label:l("modal.saveVersion.createNew"),description:l(o?"modal.saveVersion.createWithFileDescription":"modal.saveVersion.createDescription")}],[l,o]),u=o?c[1]:c[0],[m,p]=Oe(u),[h,f]=Oe(""),g=new Bg;He(()=>{n&&(p(u),f(""))},[u,n]);const v="new-version"===m?.id;return t(H,{isOpen:n,onClose:a,className:"sm:max-w-md",children:[e(G,{children:l("modal.saveChanges")}),e(J,{children:t("div",{className:"space-y-4",children:[o&&e("div",{className:"mb-4 p-3 bg-blue-50 dark:bg-blue-900/20 rounded-md",children:t("p",{className:"text-sm text-blue-700 dark:text-blue-300 font-medium",children:[l("modal.saveVersion.replaceFile")," ",e("span",{className:"font-bold",children:o})]})}),e("p",{className:"text-sm text-mixer-muted/5",children:l("modal.saveVersion.howToSave")}),e(se,{adapter:g,options:c,selected:m,onSelect:e=>{p(e)}}),v&&e(ie,{label:l("modal.saveVersion.versionLabel"),description:l("modal.saveVersion.versionLabelDescription"),className:"mt-3 ps-8",children:e(d,{value:h,onChange:f,placeholder:l("modal.saveVersion.versionLabelPlaceholder"),className:"w-full"})})]})}),t(Y,{children:[e(r,{variant:"secondary",onClick:a,disabled:i,children:l("modal.cancel")}),e(r,{variant:"primary",onClick:async()=>{await s(v,v?h:void 0)},isLoading:i,children:l("modal.save")})]})]})}function qg({isOpen:a,onClose:s,object:i,refetch:o}){const{client:l,store:c}=tr(),d=p(),{t:u}=Ze(),{theme:m}=le(),h=ia(),[f,g]=Oe(!1),[v,b]=Oe(""),[x,y]=Oe(!1),[w,N]=Oe(null),k=Be(void 0),[C,_]=Oe(null),[S,I]=Oe(null),z=Ve(async e=>{try{const t=await c.types.retrieve(e);t.object_schema&&_(t.object_schema)}catch(e){console.error("Failed to fetch JSON schema:",e)}},[c.types]);He(()=>{a&&(b(JSON.stringify(i.properties||{},null,2)),i.type?.id&&z(i.type.id))},[a,i,z]);return t(n,{children:[t(H,{isOpen:a,onClose:s,className:"sm:max-w-[90%] md:max-w-[80%] lg:max-w-[75%] xl:max-w-[70%]",children:[e(G,{children:u("store.editProperties")}),t(J,{children:[t("div",{className:"mb-2 text-sm text-gray-500",children:[i.type?.name?t("span",{children:["Editing properties for object type: ",e("strong",{children:i.type.name})]}):e("span",{children:u("store.editingGenericDocument")}),null!==C&&e("span",{className:"ms-2 text-green-600",children:"(JSON schema validation enabled)"})]}),e("div",{className:"h-[75vh] border rounded-md overflow-hidden",children:e(va,{value:v,language:"json",editorRef:k,onChange:e=>{return t=e.state.doc.toString(),void b(t);var t},beforeMount:e=>{C&&e.json.jsonDefaults.setDiagnosticsOptions({validate:!0,schemas:[{uri:"http://myserver/object-schema.json",fileMatch:["*"],schema:C}]})},theme:"dark"===m?"vs-dark":"vs"})})]}),t(Y,{children:[e(r,{variant:"secondary",onClick:s,children:"Cancel"}),e(r,{variant:"primary",onClick:function(){if(!k.current)return;const e=k.current.getValue();try{const t=JSON.parse(e);N(t),y(!0)}catch{d({status:"error",title:u("store.invalidJson"),description:u("store.pleaseFixJsonSyntax"),duration:5e3})}},children:"Save Changes"})]})]}),e(Vg,{isOpen:x,onClose:function(){y(!1)},onConfirm:async function(e,t){try{g(!0);const n=w||JSON.parse(v);if(e){const e=await l.objects.update(i.id,{properties:n},{createRevision:!0,revisionLabel:t});e.id!==i.id&&I(e.id),d({status:"success",title:u("store.newVersionCreated"),description:u("store.newVersionCreatedDesc"),duration:2e3}),y(!1),s(),e.id!==i.id&&setTimeout(()=>{h(`/objects/${e.id}`),d({status:"info",title:u("store.viewingNewVersion"),description:t?u("store.viewingVersionLabel",{label:t}):u("store.viewingNewVersionDefault"),duration:3e3})},100)}else await c.objects.update(i.id,{properties:n}),d({status:"success",title:u("store.propertiesUpdated"),description:u("store.propertiesUpdatedDesc"),duration:2e3}),o&&await o(),y(!1),s()}catch(e){d({status:"error",title:u("store.errorUpdatingProperties"),description:T(e,u("store.errorUpdatingPropertiesDefault")),duration:5e3}),g(!1)}},isLoading:f})]})}function Hg({object:a,text:s,onClose:i,onSaved:o}){const{store:l}=tr(),c=p(),{t:d}=Ze(),{theme:u}=le(),m=ia(),h=Be(void 0),[f,g]=Oe(!1),[v,b]=Oe(!1),[x,y]=Oe(!1),w=function(e){switch(e){case"text/markdown":return"markdown";case"application/json":return"json";case"application/xml":case"text/xml":return"xml";default:return"plaintext"}}(a.content?.type);console.log("Determined language for Monaco Editor:",w),console.log("TextEditorPanel rendered with object:",a,s);const N=Ve(()=>{f||g(!0)},[f]);return t(n,{children:[t("div",{className:"flex items-center gap-2 px-2 py-1 shrink-0",children:[f&&e("span",{className:"text-xs text-attention",children:d("store.unsavedChanges")}),e("div",{className:"flex-1"}),e(r,{variant:"ghost",size:"sm",onClick:i,disabled:v,children:d("store.cancelEdit")}),e(r,{variant:"secondary",size:"sm",onClick:function(){h.current&&y(!0)},disabled:!f,isLoading:v,children:d("store.saveText")})]}),e("div",{className:"flex-1 min-h-0 border rounded-md overflow-hidden mx-2 mb-2",children:e(va,{value:s,language:w,editorRef:h,onChange:N,theme:"dark"===u?"vs-dark":"vs",options:{wordWrap:"on",minimap:{enabled:!1},lineNumbers:"on",scrollBeyondLastLine:!1}})}),e(Vg,{isOpen:x,onClose:()=>y(!1),onConfirm:async function(e,t){if(!h.current)return;const n=h.current.getValue(),r=a.content?.type||"text/plain",s=a.content?.name||"content.txt";try{b(!0);const u=new Blob([n],{type:r}),p=new File([u],s,{type:r}),h=await l.objects.update(a.id,{content:p},{createRevision:e,revisionLabel:t,ifMatch:a.content?.etag});c({status:"success",title:d("store.textSaved"),duration:2e3}),y(!1),e&&h.id!==a.id?(i(),setTimeout(()=>{m(`/objects/${h.id}`)},100)):o()}catch(e){const t=T(e,d("store.errorSavingTextDefault")),n=412===("object"==typeof e&&null!==e&&"status"in e?e.status:void 0)||t.includes("412");c({status:"error",title:d("store.errorSavingText"),description:n?d("store.textConflict"):t,duration:5e3})}finally{b(!1)}},isLoading:v})]})}const Gg=131072;function Jg(e){return e===Nr.created||e===Nr.processing}function Kg(e){return e.metadata?.content_processor?.type}function Qg(e){return e?"h-full overflow-auto":"hidden"}var Yg;function Zg({object:n,loadText:r,refetch:a,canEditProperties:s=!0}){const i=p(),{t:o}=Ze(),l=async(e,t)=>{try{await navigator.clipboard.writeText(e),i({status:"success",title:o("store.contentCopied",{type:o("text"===t?"store.contentType":"store.properties")}),description:o("store.successfullyCopied",{type:t}),duration:2e3})}catch(e){console.error(`Failed to copy ${t}:`,e),i({status:"error",title:o("store.copyFailed"),description:o("store.failedToCopy",{type:t}),duration:5e3})}};return t(ne,{direction:"horizontal",className:"h-full",children:[e(re,{defaultSize:67,className:"min-w-[100px]",children:e(ev,{object:n,loadText:r??!1,handleCopyContent:l,refetch:a})}),e(ae,{withHandle:!0}),e(re,{defaultSize:33,className:"min-w-[100px]",children:e(Xg,{object:n,refetch:a??(()=>Promise.resolve()),handleCopyContent:l,canEditProperties:s})})]})}function Xg({object:a,refetch:s,handleCopyContent:i,canEditProperties:o}){const{t:l}=Ze(),[c,d]=Oe(!1),[u,m]=Oe(!1);return t(n,{children:[t("div",{className:"flex flex-col h-full",children:[t("div",{className:"flex justify-between items-center px-2",children:[t("div",{className:"flex items-center gap-1 bg-muted mb-2 p-1 rounded",children:[e(r,{variant:""+(c?"ghost":"primary"),size:"sm",alt:l("store.previewProperties"),onClick:()=>d(!c),children:"Properties"}),e(r,{variant:""+(c?"primary":"ghost"),size:"sm",alt:l("store.viewInJsonFormat"),onClick:()=>d(!c),children:"JSON"})]}),t("div",{className:"flex items-center gap-2",children:[a.properties&&e(r,{variant:"ghost",size:"sm",title:"Copy properties",onClick:()=>i(JSON.stringify(a.properties,null,2),"properties"),children:e(ot,{className:"size-4"})}),o&&e(Ug,{permission:kr.content_write,variant:"ghost",size:"sm",onClick:()=>{m(!0)},title:"Edit properties",className:"flex items-center gap-2",children:e(Gn,{className:"size-4"})})]})]}),a.properties?e("div",{className:"flex-1 min-h-0 px-2",children:e(ba,{value:a.properties,viewCode:c})}):e("div",{className:"flex-1 min-h-0 px-2",children:e("div",{children:l("store.noPropertiesDefined")})})]}),e(qg,{isOpen:u,onClose:()=>{m(!1)},object:a,refetch:s})]})}function ev({object:n,loadText:a,handleCopyContent:s,refetch:i}){const{t:o}=Ze(),l=n?.metadata?.type===yr.Image,c=n?.metadata?.type===yr.Video,d=n?.metadata?.type===yr.Audio,u="application/pdf"===n?.content?.type,m=!!n?.content?.type&&oh(n.content.type),p=Jg(n?.status),h=!(!n.transcript||!c&&!d),f=n.metadata,g=f?.renditions?.find(e=>e.name===br),[v,b]=Oe(c?Yg.Video:d?Yg.Audio:l?Yg.Image:Yg.Text),[x,y]=Oe(v===Yg.Pdf);He(()=>{v===Yg.Pdf&&y(!0)},[v]);const[w,N]=Oe(!1),k=!(!n.content?.source||!n.content?.type||p||n.is_locked||!1===n.user_permissions?.can_write||!n.content.type.startsWith("text/")&&"application/json"!==n.content.type&&"application/xml"!==n.content.type),{fullText:C,displayText:_,isLoading:S,isCropped:T,loadText:I}=function(e,t,n=!1){const{store:r}=tr(),[a,s]=Oe(t),[i,o]=Oe(()=>t&&t.length>Gg?t.substring(0,Gg):t),[l,c]=Oe(!1),[d,u]=Oe(()=>!!t&&t.length>Gg),m=Ve(()=>{c(!0),r.objects.getObjectText(e).then(e=>{s(e.text),e.text&&e.text.length>Gg?(o(e.text.substring(0,Gg)),u(!0)):(o(e.text),u(!1))}).catch(e=>{console.error("Failed to load text",e),s(void 0),o(void 0),u(!1)}).finally(()=>{c(!1)})},[e,r]);return He(()=>{t&&t.length>Gg?(s(t),o(t.substring(0,Gg)),u(!0)):(s(t),o(t),u(!1)),n&&!t&&m()},[t,n,m]),{fullText:a,displayText:i,isLoading:l,isCropped:d,loadText:m}}(n.id,n.text,a),z=(u||m)&&p&&(v===Yg.Text||v===Yg.Pdf),{progress:R,status:j,outputFormat:P,isComplete:A}=function(e,t){const{client:n}=tr(),[r,a]=Oe({isComplete:!1});return He(()=>{if(!t)return;let r,s=!1;const i=(e,t,n,r)=>{a(a=>{const s=JSON.stringify(a.progress??null),i=JSON.stringify(e??null);return a.status===t&&a.outputFormat===n&&a.isComplete===r&&s===i?a:{progress:e,status:t,outputFormat:n,isComplete:r}})};return function t(){s||n.objects.analyze(e).getStatus().then(e=>{const n=e.output_format??e.progress?.output_format;e.status===gr.RUNNING?(i(e.progress,e.status,n,!1),s||(r=setTimeout(t,2e3))):i(e.progress,e.status,n,!0)}).catch(()=>{s||(r=setTimeout(t,1e4))})}(),()=>{s=!0,r&&clearTimeout(r)}},[t,e,n]),{progress:r.progress,status:r.status,outputFormat:r.outputFormat,isComplete:r.isComplete}}(n.id,z),{pdfUrl:D,isConverting:E,error:$,triggerConversion:L}=function(e,t){const{client:n}=tr(),r=Xe.getFixedT(null,et),[a,s]=Oe(),[i,o]=Oe(!1),[l,c]=Oe(),d=Ve(async()=>{if(!t||i)return;o(!0),c(void 0);const a=async t=>{try{const i=await n.objects.getRendition(e,{format:or.pdf,generate_if_missing:t,sign_url:!0,block_on_generation:!1});"generating"===i.status?setTimeout(()=>a(!1),5e3):"found"===i.status&&i.renditions?.length?(s(i.renditions[0]),o(!1)):"failed"===i.status&&(c(r("store.pdfConversionFailed")),o(!1))}catch(e){console.error("Failed to convert Office document to PDF:",e),c(r("store.failedToConvertToPdf")),o(!1)}};await a(!0)},[e,t,i,n,r]);return{pdfUrl:a,isConverting:i,error:l,triggerConversion:d}}(n.id,m);He(()=>{A&&j===gr.COMPLETED&&I()},[A,j,I]);const F=(u||m)&&p&&!A&&j===gr.RUNNING,M=v===Yg.Pdf&&!F,O=F&&(v===Yg.Text||v===Yg.Pdf),U=x&&!F,W=Be(null);return t("div",{className:"flex flex-col h-full",children:[t("div",{className:"flex justify-between items-center px-2 shrink-0",children:[t("div",{className:"flex items-center gap-2 mb-2",children:[t("div",{className:"flex items-center gap-1 bg-muted p-1 rounded",children:[l&&e(r,{variant:v===Yg.Image?"primary":"ghost",size:"sm",alt:o("store.viewImage"),onClick:()=>b(Yg.Image),children:"Image"}),c&&e(r,{variant:v===Yg.Video?"primary":"ghost",size:"sm",alt:o("store.viewVideo"),onClick:()=>b(Yg.Video),children:"Video"}),d&&e(r,{variant:v===Yg.Audio?"primary":"ghost",size:"sm",alt:o("store.viewAudio"),onClick:()=>b(Yg.Audio),children:"Audio"}),h&&e(r,{variant:v===Yg.Transcript?"primary":"ghost",size:"sm",alt:o("store.viewTranscript"),onClick:()=>b(Yg.Transcript),children:"Transcript"}),e(r,{variant:v===Yg.Text?"primary":"ghost",size:"sm",alt:o("store.viewText"),onClick:()=>b(Yg.Text),children:"Text"}),u&&e(r,{variant:v===Yg.Pdf?"primary":"ghost",size:"sm",alt:o("store.viewPdf"),onClick:()=>b(Yg.Pdf),children:"PDF"}),m&&e(r,{variant:v===Yg.Pdf?"primary":"ghost",size:"sm",alt:o("store.viewAsPdf"),onClick:()=>{b(Yg.Pdf),g||D||E||L()},disabled:E,children:E?e(K,{size:"sm"}):"PDF"})]}),e(av,{object:n})]}),v===Yg.Text&&!F&&!w&&e(tv,{object:n,text:_,fullText:C,handleCopyContent:s,textContainerRef:W,isEditing:w,onToggleEdit:()=>N(!0),canEdit:k}),v===Yg.Pdf&&m&&(g||D)&&e(sv,{object:n,pdfRendition:g,officePdfUrl:D})]}),v===Yg.Image&&e("div",{className:Qg(!0),children:e(Rg,{object:n})}),v===Yg.Video&&e("div",{className:Qg(!0),children:e(jg,{object:n})}),v===Yg.Audio&&e("div",{className:Qg(!0),children:e(zg,{object:n})}),h&&v===Yg.Transcript&&e("div",{className:Qg(!0),children:e(rv,{object:n,handleCopyContent:s})}),u&&U&&e("div",{className:Qg(M),children:e(iv,{object:n})}),m&&U&&e("div",{className:Qg(M),children:e(ov,{pdfRendition:g,officePdfUrl:D,officePdfConverting:E,officePdfError:$,onConvert:L})}),O&&e("div",{className:Qg(!0),children:e(lv,{progress:R,status:j,outputFormat:P})}),v===Yg.Text&&!F&&!w&&S&&e("div",{className:Qg(!0),children:e("div",{className:"flex justify-center items-center flex-1",children:e(K,{size:"lg"})})}),v===Yg.Text&&!F&&!w&&!S&&e("div",{className:Qg(!0),children:e(nv,{object:n,text:_,isTextCropped:T,textContainerRef:W})}),w&&v===Yg.Text&&null!=C&&e(Hg,{object:n,text:C,onClose:()=>N(!1),onSaved:()=>{N(!1),I(),i?.()}})]})}function tv({object:a,text:s,fullText:i,handleCopyContent:o,onToggleEdit:l,canEdit:c}){const{client:d,project:u}=tr(),m=p(),{t:h}=Ze(),f=a.content,{renderDocument:b,isDownloading:x}=lc({client:d,toast:m}),{data:y}=S(()=>u?d.projects.retrieve(u.id):Promise.resolve(void 0),[u?.id]),w=y?.configuration?.pdf_template_object_id,N=f?.type&&"text/markdown"===f.type,k=Kg(a),C=async(e,t)=>{if(x)return;m({status:"info",title:`Preparing ${e.toUpperCase()}`,description:h("store.renderingDocument"),duration:2e3});const n=!1!==t?w:void 0;await b(a.id,{format:e,title:a.name||"document",useDefaultTemplate:t,templateObjectId:n})};return e("div",{className:"h-[41px] text-lg font-semibold flex justify-between items-center px-2",children:t("div",{className:"flex items-center gap-2",children:[i&&t(n,{children:[e(r,{variant:"ghost",size:"sm",title:"Copy text",onClick:()=>o(i,"text"),children:e(ot,{className:"size-4"})}),c&&l&&e(Ug,{permission:kr.content_write,variant:"ghost",size:"sm",onClick:l,title:h("store.editText"),className:"flex items-center gap-2",children:e(Gn,{className:"size-4"})})]}),x?e(r,{variant:"ghost",size:"sm",disabled:!0,className:"flex items-center gap-2",alt:"download",children:e(K,{size:"sm"})}):t(g,{trigger:e(r,{variant:"ghost",size:"sm",disabled:!s,className:"flex items-center gap-2",alt:"download",children:e(lt,{className:"size-4"})}),children:[i&&e(v,{onClick:e=>{if(e.preventDefault(),e.stopPropagation(),!i)return;let t="txt",n="text/plain";"xml"===k?(t="xml",n="text/xml"):("markdown"===k||N)&&(t="md",n="text/markdown");const r=new Blob([i],{type:n}),s=URL.createObjectURL(r),o=`${a.name||"document"}.${t}`,l=document.createElement("a");l.href=s,l.download=o,l.style.display="none",setTimeout(()=>{l.click(),URL.revokeObjectURL(s)},0)},children:t("div",{className:"flex items-center gap-2",children:[e(lt,{className:"size-4"}),"Download Text"]})}),N&&s&&t(n,{children:[e(v,{onClick:()=>C(or.docx),children:t("div",{className:"flex items-center gap-2",children:[e(lt,{className:"size-4"}),"Export as DOCX"]})}),e(v,{onClick:()=>C(or.pdf,!1),children:t("div",{className:"flex items-center gap-2",children:[e(lt,{className:"size-4"}),"Export as PDF"]})}),e(v,{onClick:()=>C(or.pdf),children:t("div",{className:"flex items-center gap-2",children:[e(lt,{className:"size-4"}),"Export as Branded PDF"]})})]})]})]})})}!function(e){e.Text="text",e.Image="image",e.Video="video",e.Audio="audio",e.Pdf="pdf",e.Transcript="transcript"}(Yg||(Yg={}));const nv=qe(({object:r,text:a,isTextCropped:s,textContainerRef:i})=>{const{t:o}=Ze(),l=r.content,c=Jg(r?.status),d="xml"===Kg(r),u=l?.type&&("text/markdown"===l.type||"text/plain"===l.type),m=!d&&(u||function(e){return!!e&&(e.includes("\n# ")||e.includes("\n## ")||e.includes("\n### ")||e.includes("\n* ")||e.includes("\n- ")||e.includes("\n+ ")||e.includes(")}(a));return a?t(n,{children:[s&&e("div",{className:"px-2 py-2 bg-attention/10 border-s-4 border-attention mx-2 mb-2 rounded",children:t("div",{className:"flex items-center gap-2 text-attention",children:[e(Gt,{className:"size-4"}),e("span",{className:"text-sm font-semibold",children:o("store.showingFirst128K")})]})}),e("div",{className:"max-w-7xl px-2 h-full overflow-auto",ref:i,children:d?e("div",{className:"px-4 py-2",children:e(fa,{xml:a,collapsible:!0})}):m?e("div",{className:"vprose prose-sm p-1",children:e(oa,{components:{a:({node:t,...n})=>{const r=n.href||"";return r.includes("/store/objects/")?e(sa,{topLevelNav:!0,href:r,className:"text-info",children:n.children}):e("a",{...n,target:"_blank",rel:"noopener noreferrer"})},p:({node:t,...n})=>e("p",{...n,className:"my-0"}),pre:({node:t,...n})=>e("pre",{...n,className:"my-2 p-2 rounded"}),code:({node:t,className:n,children:r,...a})=>{const s=/language-(\w+)/.exec(n||"");return e("code",{...a,className:s?"text-muted":"px-1.5 py-0.5 rounded",children:r})},h1:({node:t,...n})=>e("h1",{...n,className:"font-bold text-2xl my-2"}),h2:({node:t,...n})=>e("h2",{...n,className:"font-bold text-xl my-2"}),h3:({node:t,...n})=>e("h3",{...n,className:"font-bold text-lg my-2"}),li:({node:t,...n})=>e("li",{...n})},children:a})}):e("pre",{className:"text-wrap bg-muted text-muted p-2",children:a})})]}):e("div",{className:"px-2",children:e("div",{children:c?"Extracting content...":"No content"})})});function rv({object:n,handleCopyContent:a}){const{t:s}=Ze(),i=n.transcript,o=i?.text,l=i?.segments,c=o||(l?l.map(e=>e.text).join(" "):""),d=e=>{const t=Math.floor(e/3600),n=Math.floor(e%3600/60),r=Math.floor(e%60);return t>0?`${t}:${n.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}`:`${n}:${r.toString().padStart(2,"0")}`};return t("div",{className:"flex flex-col h-full",children:[e("div",{className:"flex justify-end items-center px-2 mb-2",children:c&&e(r,{variant:"ghost",size:"sm",title:"Copy transcript",onClick:()=>a(c,"text"),children:e(ot,{className:"size-4"})})}),e("div",{className:"h-full} overflow-auto px-2",children:l&&l.length>0?e("div",{className:"space-y-2",children:l.map((n,r)=>t("div",{className:"flex gap-3 text-sm",children:[t("span",{className:"text-muted font-mono text-xs shrink-0 pt-0.5",children:[d(n.start),n.end&&` - ${d(n.end)}`]}),e("span",{className:"flex-1",children:n.text})]},r))}):o?e("pre",{className:"text-wrap bg-muted text-muted p-2 whitespace-pre-wrap",children:o}):e("div",{className:"text-muted",children:s("store.noTranscriptAvailable")})})]})}function av({object:a}){const[s,i]=Oe(!1),o=Kg(a);return"xml"===o||"markdown"===o?t(n,{children:[e(r,{variant:"ghost",size:"sm",onClick:()=>i(!0),title:"Side by side view",children:e(Jn,{className:"size-4"})}),s&&e(ce,{children:e(kg,{objectId:a.id,onClose:()=>i(!1)})})]}):null}function sv({object:t,pdfRendition:n,officePdfUrl:a}){const{client:s}=tr(),i=p(),{t:o}=Ze(),[l,c]=Oe(!1);return e("div",{className:"flex items-center gap-2",children:e(r,{variant:"ghost",size:"sm",onClick:async()=>{c(!0);try{let e=a;if(!e&&n?.content?.source){e=(await s.files.getDownloadUrl(n.content.source,`${t.name||"document"}.pdf`,"attachment")).url}e&&window.open(e,"_blank")}catch(e){console.error("Failed to download PDF:",e),i({status:"error",title:o("store.downloadFailed"),description:o("store.failedToDownloadPdf"),duration:5e3})}finally{c(!1)}},disabled:l,title:"Download PDF",children:l?e(K,{size:"sm"}):e(lt,{className:"size-4"})})})}function iv({object:t}){return e("div",{className:"h-full",children:e(Ag,{object:t,className:"h-full"})})}function ov({pdfRendition:n,officePdfUrl:a,officePdfConverting:s,officePdfError:i,onConvert:o}){const{t:l}=Ze();return s?t("div",{className:"flex flex-col justify-center items-center flex-1 gap-2",children:[e(K,{size:"lg"}),e("span",{className:"text-muted",children:l("store.convertingToPdf")})]}):i?t("div",{className:"flex flex-col justify-center items-center flex-1 gap-2 text-destructive",children:[e(Gt,{className:"size-8"}),e("span",{children:i})]}):e("div",n?.content?.source?{className:"h-full",children:e(Ag,{source:n.content.source,className:"h-full"})}:a?{className:"h-full",children:e(Ag,{url:a,className:"h-full"})}:{className:"flex flex-col justify-center items-center flex-1 gap-2",children:e(r,{onClick:o,children:"Convert to PDF"})})}function lv({progress:r,status:a,outputFormat:s}){const{t:i}=Ze(),o=fh(a),l=gh(a),c="xml"===s,d=null==r?.percent||Number.isNaN(r.percent)?0:r.percent;return t("div",{className:"px-4 py-4",children:[r&&t("div",{className:"space-y-2",children:[t("div",{className:"flex flex-col gap-1",children:[e(cv,{name:c?"Analyze Layouts":"Analyze Page",progress:r.pages}),c&&t(n,{children:[e(cv,{name:"Extract Tables",progress:r.tables}),e(cv,{name:"Describe Images",progress:r.images}),e(cv,{name:"Process Visually",progress:r.visuals})]})]}),t("div",{className:"pt-2 text-sm text-muted",children:["Progress: ",d,"%",e("span",{className:"px-2",children:"•"}),e("span",{className:o,children:l}),r.started_at&&t(n,{children:[e("span",{className:"px-2",children:"•"}),t("span",{children:[((Date.now()-r.started_at)/1e3).toFixed(0)," sec. elapsed"]})]})]}),e(xa,{percent:d})]}),!r&&t("div",{className:"flex items-center gap-2 text-muted",children:[e(K,{size:"sm"}),e("span",{children:i("store.loadingProcessingStatus")})]})]})}function cv({name:e,progress:n}){return t("div",{className:"flex gap-2 text-sm",children:[t("span",{className:"text-muted min-w-36",children:[e,":"]}),t("span",{children:[n.processed," of ",n.total]})]})}const dv=Object.values(Cr),uv=Object.values(_r);function mv({onChange:n,isLoading:a,refresh:s,searchTypes:i}){const{client:o,project:l}=tr(),{t:c}=Ze(),u=p(),[m,h]=Oe(void 0),[f,g]=Oe(void 0),v=!(!l||!f?.embeddings.text&&!f?.embeddings.image),[b,x]=Oe(void 0),y=Be(s),w=Be(void 0),[N,k]=Oe(!1),[C,_]=Oe(i||dv),[S,T]=Oe(100);He(()=>{i&&_(i)},[i]);const I={};let z=!1,R=!1;C.forEach(e=>{e===Cr.full_text?z=!0:R=!0,uv.includes(e)&&(I[e]=!0)}),He(()=>{y.current!==s&&(y.current=s,h(void 0),x(void 0))}),He(()=>{l&&o.projects.retrieve(l.id).then(e=>{g(e.configuration)})},[o.projects.retrieve,l]),He(()=>{b&&u({title:b,status:"success",duration:2e3})},[b,u]),He(()=>{const e=w.current;w.current=m,!e||m&&0!==m.length||n(void 0)},[n,m]);const j=()=>{if(!v||!m)return;n({vector:R?{text:m,config:I}:void 0,full_text:z?m:void 0,limit:S}),x("Searching...")},P=e=>t=>{_(t?t=>Array.from(new Set([...t,e])):t=>t.filter(t=>t!==e))};return t("div",{className:"flex gap-1 items-center",children:[e(d,{placeholder:c("store.searchPlaceholder"),value:m,onChange:h,onKeyDown:e=>{"Enter"===e.key&&j()},className:"min-w-[200px]"}),e(r,{variant:"ghost",onClick:()=>k(!0),alt:c("store.semanticSearchSettings"),className:"ms-1",children:e(Kn,{size:18})}),t(H,{isOpen:N,onClose:()=>k(!1),children:[e(G,{children:c("store.searchTypes")}),e(J,{children:t("div",{className:"flex flex-col gap-2",children:[t("div",{className:"flex items-center gap-2",children:[e(de,{id:"search-type-full_text",checked:C.includes(Cr.full_text),onCheckedChange:P(Cr.full_text)}),e(ue,{htmlFor:"search-type-full_text",children:c("store.fullText")})]}),e("div",{className:"font-semibold mt-2 mb-1",children:c("store.embeddings")}),uv.map(n=>t("div",{className:"flex items-center gap-2",children:[e(de,{id:`search-type-${n}`,checked:C.includes(n),onCheckedChange:P(n)}),e(ue,{htmlFor:`search-type-${n}`,children:n.charAt(0).toUpperCase()+n.slice(1)})]},n)),t("div",{className:"mt-3",children:[e("span",{className:"me-2",children:c("store.limit")}),e(me,{type:"number",min:1,value:S,onChange:e=>T(Number(e??100)),style:{width:80}})]})]})}),e(Y,{children:e(r,{variant:"outline",onClick:()=>k(!1),children:c("store.close")})})]}),e(r,{variant:"secondary",isLoading:a,onClick:j,isDisabled:!v,alt:c("store.semanticSearch"),children:c("store.search")})]})}const pv=[{name:"ID",field:"id",type:"objectId?slice=-7"},{name:"Name",field:".",type:"objectName"},{name:"Type",field:"type.name",type:"string"},{name:"Status",field:"status",type:"string"},{name:"Updated At",field:"updated_at",type:"date"}];function hv({onUploadDone:t=async()=>{},layout:n}){const r=Ph(),a=p(),{t:s}=Ze(),i=Uh(Ve(async e=>{await t(e),setTimeout(()=>{console.log("Delayed refresh after upload to ensure backend consistency"),r.search().then(e=>{e&&a({title:s("store.documentListRefreshed"),description:s("store.documentListRefreshedDesc"),status:"info",duration:3e3})}).catch(e=>{console.error("Failed to refresh search results:",e)})},1e3)},[t,r,s,a])),o=Ve((e,t)=>{const n=r.collectionId;return i(e,t,n)},[r,i]);return e(fv,{layout:n,onUpload:o})}function fv({layout:n,onUpload:r,allowFilter:a=!0,allowSearch:s=!0}){const{t:i}=Ze(),o=Ph(),[l,c]=Oe(!1),[d,u]=Oe(null),{registry:m}=cp(),{search:p,isLoading:h,error:f,objects:g,hasMore:v}=Dh(),[x,y]=Oe(m?n||(w=m,((N=p.query.type)?w.getTypeLayout(N):pv)??pv):pv);var w,N;He(()=>{n&&y(n)},[n]);const[k,C]=Oe(0),[_,S]=Oe(0),[T,I]=Oe("grid"===localStorage.getItem(Jh.LAST_DISPLAYED_VIEW)),[z,R]=Oe([]),j=Be(null),P=Be(null),A=Ve((e,t)=>{c(!1),e.catch(e=>{console.error(t,e)}).finally(()=>{c(!0)})},[]);He(()=>{let e=!1;return p.initialized?(c(!0),()=>{e=!0}):(c(!1),S(0),p.search().catch(t=>{e||console.error("Initial search failed:",t)}).finally(()=>{e||c(!0)}),()=>{e=!0})},[p]),He(()=>{g.length<_&&S(g.length)},[g.length,_]),Z(j,()=>{l&&g.length>0&&g.length!==_&&(c(!1),p.loadMore().catch(e=>{console.error("Failed to load more search results:",e)}).finally(()=>{S(g.length),c(!0)}))},{deps:[l,g.length]});const D=Ah(),E=Ph(),$=fp(D),L=gp(E),F=e=>{const t="function"==typeof e?e(z):e;R(t),L(t)},M=new URL(window.location.href),O=M.searchParams.get("filters");if(O)try{const e=O.split(";"),t=e.filter(e=>{const[t]=e.split(":"),n=decodeURIComponent(t);return"start"!==n&&"end"!==n});if(t.length!==e.length){const e=t.length>0?t.join(";"):"";e?M.searchParams.set("filters",e):M.searchParams.delete("filters"),window.history.replaceState(window.history.state||{},"",M.toString())}}catch(f){console.error("Failed to clean start/end filters from URL:",f)}const U=ia();return t("div",{className:"flex flex-col gap-y-2 flex-1 min-h-0 ",children:[e(vv,{object:d,onClose:()=>u(null)}),f&&e(b,{title:i("store.error"),children:f.message}),e(gv,{isLoading:h,refreshTrigger:k,allowFilter:a,allowSearch:s,filterGroups:$,filters:z,handleFilterChange:F,handleVectorSearch:e=>{if(e?.vector){if(p.query.vector=e.vector,p.query.full_text=e.full_text,p.query.weights=e.weights,p.query.score_aggregation=e.score_aggregation,p.query.dynamic_scaling=e.dynamic_scaling,void 0!==e.limit&&(p.limit=e.limit,p.query.limit=e.limit),!x.find(e=>"Search Score"===e.name)){const e=[...x,{name:"Search Score",field:"score",render:e=>"number"==typeof e.score?e.score.toFixed(4):"0.0000"}];y(e)}A(p.search(),"Vector search failed:")}else e?.full_text?(p.query.full_text=e.full_text,void 0!==e.limit&&(p.limit=e.limit,p.query.limit=e.limit),A(p.search(),"Text search failed:")):void 0===e&&l&&(delete p.query.vector,delete p.query.full_text,A(p.search(),"Search reset failed:"))},handleRefetch:()=>{A(p.search(),"Search refresh failed:")},setIsGridView:I}),e("div",{className:"flex flex-col w-full flex-1 min-h-0 border rounded-md mb-2",children:t("div",{ref:P,className:"flex-1 min-h-0 overflow-y-auto",children:[e(Kp,{onFilter:(e,t)=>{const n=$.find(t=>t.name===e),r={name:e,type:n?.type,placeholder:n?.placeholder,multiple:n?.multiple};F(a=>{const s=a.filter(t=>t.name!==e);if("stringList"===n?.type||Array.isArray(t)){const n=Array.isArray(t)?t:[t],i=a.find(t=>t.name===e)?.value??[];return[...s,{...r,value:Array.from(new Set([...i,...n]))}]}return[...s,{...r,value:[{value:t,label:t}]}]})},children:e(Bh,{objects:g,isLoading:!g.length&&h,layout:x,onRowClick:e=>{U(`/objects/${e.id}`)},previewObject:e=>{const t=g.find(t=>t.id===e)||null;u(t)},selectedObject:d,onUpload:r,isGridView:T,collectionId:o.collectionId})}),e("div",v?{ref:j,className:"w-full flex justify-center",children:e(K,{size:"xl"})}:{className:"text-muted text-center text-sm py-1",children:`All ${g.length} objects loaded.`})]})})]})}function gv(n){const{t:a}=Ze(),{isLoading:s,refreshTrigger:i,allowFilter:o,allowSearch:l,filterGroups:c,filters:d,handleFilterChange:u,handleVectorSearch:m,handleRefetch:p,setIsGridView:f}=n;return t("div",{className:"sticky top-0 z-10 bg-background py-2 flex justify-between items-center",children:[o?e(j,{filterGroups:c,filters:d,setFilters:u,children:t("div",{children:[e("div",{className:"flex flex-row gap-4 items-center justify-between w-full",children:t("div",{className:"flex gap-2 items-center w-2/3",children:[l&&e(mv,{onChange:m,isLoading:s,refresh:i,className:"w-full"}),e(P,{})]})}),t("div",{className:"flex gap-2 items-center pt-2",children:[e(A,{}),e(D,{})]})]})}):e("div",{className:"flex flex-row gap-4 items-center justify-between w-full",children:e("div",{className:"flex gap-2 items-center w-2/3",children:l&&e(mv,{onChange:m,isLoading:s,refresh:i})})}),t("div",{className:"flex gap-1 items-center",children:[e(h,{description:a("store.refresh"),asChild:!0,size:"xs",placement:"top",children:e(r,{variant:"outline",onClick:p,"aria-label":a("store.refresh"),children:e(Tn,{size:16})})}),e(Jh,{onUpdate:f})]})]})}function vv({object:n,onClose:a}){const{store:s}=tr(),i=p(),o=ia(),{downloadFromContentSource:l}=lc({client:s,toast:i}),c=n?.content?.source,d="string"==typeof n?.properties?.title?n.properties.title:n?.name;return n?t(pe,{title:d,isOpen:!0,onClose:a,children:[t("div",{className:"flex items-center gap-x-2",children:[e(r,{variant:"ghost",size:"sm",title:"Open Object",onClick:()=>o(`/objects/${n.id}`),children:e($t,{className:"size-4"})}),c&&e(r,{variant:"ghost",size:"sm",title:"Download",onClick:()=>l(c,n.name||n.content?.name),children:e(lt,{className:"size-4"})})]}),e(he,{className:"my-2"}),e("div",{className:"pt-2",children:e(Zg,{object:n,loadText:!0},n.id)})]}):null}const bv=[{name:"ID",field:"id",type:"objectId?slice=-7"},{name:"Name",field:".",type:"objectName"},{name:"Revision",field:".",type:"revision"},{name:"Type",field:"type.name",type:"string"},{name:"Status",field:"status",type:"string"},{name:"Updated At",field:"updated_at",type:"date"}];function xv({collection:t}){const n=p(),{client:r}=tr(),{registry:a}=cp(),s=function(e,t){let n=e.table_layout;if(n&&n.length>0)return n;e.type&&t&&(n=t?.getTypeLayout(Sr(e.type)));return n&&n.length>0?n:bv}(t,a);return e("div",{className:"flex flex-col h-full",children:t.dynamic?e(fv,{layout:s}):e(hv,{onUploadDone:async e=>{e.length>0&&await r.store.collections.addMembers(t.id,e).catch(e=>{n({title:"Failed to add objects to collection",description:e.message,status:"error"})})},layout:s})})}function yv({className:n,defaultValue:r,onChange:a,isClearable:s,multiple:i}){const{t:o}=Ze(),{registry:l}=cp(),[c,d]=Oe(!1),u=n=>null===n?o("store.none"):t("div",{children:[e("div",{className:"text-sm",children:n.name}),e("div",{className:"text-xs text-muted truncate",children:n.description})]}),[m,p]=Oe(),[h,f]=Oe([]);He(()=>{if(!c&&(d(!0),l&&r)){if(i&&Array.isArray(r)){const e=l.types.filter(e=>r.includes(e.id));f(e)}const e=l.types.find(e=>e.id===r);e&&p(e)}},[c,l,r,i]);const g=e=>{f(e),a(e)};return e("div",i?{className:"flex flex-col gap-4 content-between",children:e($,{options:l?.types||[],value:h,onChange:g,placeholder:o("store.chooseContentTypes"),optionLabel:u,className:n||"text-sm bg-background",filterBy:"name",isClearable:s||!1,multiple:!0})}:{className:"flex flex-col gap-4 content-between",children:e($,{options:l?.types||[],value:m,onChange:e=>{p(e||void 0),a(e)},placeholder:o("store.chooseContentType"),optionLabel:u,className:n||"text-sm bg-background",filterBy:"name",isClearable:s||!1})})}function wv({onClose:a,redirect:s=!0,onAddToCollection:i}){const o=ia(),l=p(),{t:c}=Ze(),[u,m]=Oe(!1),{client:h}=tr(),[f,g]=Oe({dynamic:!1,name:"",description:""});function v(e,t){g({...f,[e]:t})}return t(n,{children:[e(J,{children:t("form",{onSubmit:e=>e.preventDefault(),children:[e(ie,{label:c("type.name"),required:!0,children:e(d,{type:"text",value:f.name||"",onChange:e=>v("name",e)})}),e(ie,{label:c("type.description"),className:"mt-2",children:e(X,{value:f.description||"",onChange:e=>v("description",e.target.value)})}),e(ie,{label:c("store.dynamicCollection"),className:"mt-2",direction:"row",description:c("store.dynamicCollectionDescription"),children:e(fe,{value:f.dynamic||!1,onChange:e=>v("dynamic",e)})}),!f.dynamic&&e(ie,{label:c("store.allowedContentTypes"),className:"mt-4",description:c("store.allowedContentTypesOptionalDescription"),children:e(yv,{defaultValue:f.allowed_types||null,onChange:e=>{Array.isArray(e)?v("allowed_types",e.map(e=>e.id)):v("allowed_types",e?[e.id]:[])},isClearable:!0,multiple:!0})}),e(ie,{label:c("store.contentType"),className:"mt-2",description:c("store.typeDescription"),children:e(yv,{defaultValue:f.type||null,onChange:e=>{Array.isArray(e)?v("type",e.length>0?e[0].id:null):v("type",e?.id||null)},isClearable:!0})})]})}),e(Y,{children:e(r,{isDisabled:u,onClick:()=>{f?.name?.trim()?(f.name=f.name.trim(),f.description&&(f.description=f.description.trim()),null==f.dynamic&&(f.dynamic=!1),m(!0),h.store.collections.create(f).then(e=>{a(),l({title:c("store.collectionCreated"),description:`Collection "${e.name}" created successfully`,status:"success",duration:3e3}),s&&o(`/collections/${e.id}`),i&&i(e.id)}).catch(e=>{l({title:c("store.failedToCreateCollection"),description:e.message,status:"error",duration:5e3})}).finally(()=>m(!1))):l({title:c("type.nameRequired"),description:c("store.pleaseProvideName"),status:"error",duration:5e3})},children:c("store.createCollection")})})]})}function Nv({isOpen:n,onClose:r}){const{t:a}=Ze();return t(H,{onClose:r,isOpen:n,children:[e(G,{children:a("store.createACollection")}),e(wv,{onClose:r})]})}function kv(){const{client:a}=tr(),s=p(),{t:i}=Ze(),[o,l]=Oe(),[c,d]=Oe(!0),[u,m]=Oe(!1),{data:h,error:f,refetch:g}=S(()=>a.store.collections.search({}),[]);if(He(()=>{(h||f)&&d(!1)},[h,f]),f)return e(b,{title:i("store.collectionFetchFailed"),children:T(f)});return t(n,{children:[h&&(h.length>0?t(_,{className:"w-full",children:[e("thead",{children:t("tr",{children:[e("th",{children:i("type.name")}),e("th",{children:i("type.type")}),e("th",{children:i("store.created")}),e("th",{})]})}),e(B,{columns:4,isLoading:c,children:h.map(n=>t(ge,{children:[e("td",{children:t("div",{className:"flex items-center gap-2",children:[e(Cv,{isDynamic:n.dynamic}),e(sa,{href:`/collections/${n.id}`,children:n.name})]})}),e("td",{children:n.type?.name||"-"}),e("td",{children:Dr(n.created_at).fromNow()}),e("td",{className:"text-end",children:e(r,{variant:"destructive",size:"sm",onClick:()=>l(n.id),children:e(Yn,{className:"size-4"})})})]},n.id))})]}):e(ve,{title:i("store.noCollections"),buttonLabel:i("store.newCollections"),onClick:()=>m(!0),children:i("store.getStartedCollections")})),e(Nv,{isOpen:u,onClose:()=>m(!1)}),e(be,{isOpen:!!o,title:i("store.deleteCollection"),content:i("store.areYouSureDeleteCollection"),onConfirm:async()=>{if(o)try{await a.store.collections.delete(o),s({title:i("store.collectionDeleted"),status:"success",duration:3e3}),g()}catch(e){console.error("Failed to delete collection:",e),s({title:i("store.failedToDeleteCollection"),description:T(e),status:"error",duration:5e3})}finally{l(void 0)}},onCancel:()=>l(void 0)})]})}function Cv({isDynamic:t}){const{t:n}=Ze(),r=n(t?"store.dynamicCollection":"store.staticCollection"),a=e(t?bt:Qn,{className:"size-5"});return e(h,{description:r,className:"me-2",children:a})}Dr.extend(Ta),Dr.extend(Ta);const _v="h-6 w-6 p-0 opacity-0 group-hover/field:opacity-100 text-muted hover:text-foreground transition-opacity shrink-0";function Sv({objects:n,isLoading:a,onFilter:s}){const{t:i}=Ze(),o=ia();return t(_,{className:"w-full",children:[e(W,{children:t("tr",{children:[e("th",{children:i("store.name")}),e("th",{children:i("store.strictMode")}),e("th",{children:i("store.semanticChunking")}),e("th",{children:i("store.updatedAt")})]})}),e(B,{isLoading:a&&(!n||0===n.length),columns:4,children:n?.map(n=>t("tr",{onClick:()=>o(`/types/${n.id}`),className:"cursor-pointer hover:bg-muted",children:[e("td",{className:"group/field",children:t("div",{className:"flex items-center gap-2 min-w-0",children:[e("span",{className:"truncate",children:n.name}),e(F,{content:n.id,className:_v}),s&&e(h,{description:`Filter by ${n.name}`,asChild:!0,size:"xs",children:e(r,{variant:"ghost",size:"sm","aria-label":`Filter by ${n.name}`,className:_v,onClick:e=>{e.stopPropagation(),s("name",n.name)},children:e(In,{className:"size-3"})})})]})}),e("td",{children:n.strict_mode?"Yes":"No"}),e("td",{children:n.is_chunkable?"Yes":"No"}),e("td",{children:e(h,{description:Dr(n.updated_at).format("YYYY-MM-DD HH:mm:ss"),children:Dr(n.updated_at).fromNow()})})]},n.id))})]})}function Tv({title:n,isOpen:a,onClose:s,okLabel:i,initialPayload:o,isLoading:l}){const{t:c}=Ze(),u=p(),[m,h]=Oe(o?.name),[f,g]=Oe(o?.description),v=o?.strict_mode??!1;return t(H,{isOpen:a,onClose:()=>s(),children:[e(G,{children:n}),e(J,{className:"pt-0",children:t("div",{className:"h-full flex flex-col gap-4 content-between",children:[t("div",{children:[e("div",{className:"block text-sm font-medium text-muted",children:c("type.name")}),e(d,{value:m,onChange:h})]}),t("div",{children:[e("div",{className:"block text-sm font-medium text-muted",children:c("type.description")}),e(X,{value:f,onChange:e=>g(e.target.value),minLines:5})]})]})}),e(Y,{children:t("div",{className:"flex justify-end gap-4",children:[e(r,{variant:"secondary",onClick:()=>s(),children:c("modal.cancel")}),e(r,{variant:"primary",onClick:()=>(()=>{if(!m)return void u({status:"error",title:c("type.nameRequired"),duration:5e3});s({name:m,description:f,strict_mode:v}).then(()=>s())})(),isLoading:l,children:i})]})})]})}class Iv{client;limit;result=new V({objects:[],isLoading:!1});query={};constructor(e,t=100){this.client=e,this.limit=t}get objects(){return this.result.value.objects}get error(){return this.result.value.error}get isRunning(){return this.result.value.isLoading}getFilterValue(e){return this.query[e]}setFilterValue(e,t){this.query[e]=t,this.search()}reset(e=!1){this.result.value={objects:[],isLoading:e}}_updateRunningState(e){const t=this.result.value;this.result.value={objects:t.objects,isLoading:e,error:t.error}}async _search(e=!1){if(this.isRunning)return Promise.resolve(!1);this.result.value={isLoading:!0,objects:e?this.objects:[]};const t=this.limit,n=this.objects.length;return this.client.types.list({limit:t,offset:n,query:this.query}).then(async e=>(this.result.value={isLoading:!1,objects:this.objects.concat(e)},!0)).catch(e=>{throw this.result.value={error:e,isLoading:!1,objects:this.objects},e})}search(){return this.isRunning?Promise.resolve(!1):this._search(!1)}loadMore(){return this.isRunning?Promise.resolve(!1):this._search(!0)}}const zv=Ue(void 0);function Rv(){return We(zv)}function jv(){const e=Rv();return{...q(e.result),search:e}}function Pv(){return Rv().objects.length}var Av;function Dv({isDirty:r=!1}){const{store:a}=tr(),{reload:s}=cp(),{t:i}=Ze(),o=p(),[l,c]=Oe(!1),{search:u,isLoading:m,error:h,objects:f}=jv(),[g,v]=Oe(""),x=xe(g,500),y=Be(null);Z(y,()=>{l&&u.loadMore()},{deps:[l,u]}),He(()=>{u.search().then(()=>c(!0))},[u]),He(()=>{u.query.name=x,u.search().then(()=>c(!0))},[x,u]);const[w,N]=Oe(void 0);He(()=>{u.query.chunkable=w?"Yes"===w:void 0,u.search().then(()=>c(!0))},[w,u]),He(()=>{r&&l&&u.search().then(()=>c(!0))},[r,l,u]);const[k,C]=Oe(!1);if(h)return e(b,{title:i("store.failedToFetchTypes"),children:h.message});return t("div",{className:"flex flex-col flex-1 min-h-0",children:[t("div",{className:"flex flex-shrink-0 gap-4",children:[e(d,{placeholder:i("store.filterByName"),value:g,onChange:v}),e($,{className:"w-60",isClearable:!0,options:Object.values(Av),value:w,onChange:e=>{N(e)},placeholder:i("store.isChunkable")})]}),e("div",{className:"flex flex-col w-full flex-1 min-h-0 border rounded-md my-2",children:t("div",{className:"flex-1 min-h-0 overflow-y-auto",children:[m||0!==f?.length?t(n,{children:[e(Sv,{objects:f,isLoading:m,onFilter:(e,t)=>{"name"===e&&v(t)}}),e("div",{ref:y,className:"h-4 w-full"})]}):e(ve,{title:i("store.noType"),buttonLabel:i("store.createType"),onClick:()=>{C(!0)},children:i("store.getStartedTypes")}),e(Tv,{okLabel:"Create",title:i("store.createType"),isOpen:k,onClose:async e=>e?a.types.create(e).then(async()=>{o({status:"success",title:i("store.typeCreated"),duration:2e3}),s(),u.search().then(()=>c(!0))}).catch(e=>{o({status:"error",title:i("store.errorCreatingType"),description:e.message,duration:5e3})}):(C(!1),Promise.resolve())})]})})]})}function Ev({objectType:n,onSchemaUpdate:a,readonly:s=!1}){const{store:i}=tr(),{t:o}=Ze(),l=p(),{theme:c}=le(),[d,u]=Oe(!1),m=ya(n.object_schema),h=Be(void 0),[f,g]=Oe(!1),v=Me(()=>function(e){if(!e)return"";return JSON.stringify(e,null,2)}(m.schema),[m]),b=()=>{if(h.current){const e=h.current.getValue();try{const t=function(e){if(!e?.trim())return;return JSON.parse(e.trim())}(e);$v(t),m.replaceSchema(t)}catch(e){return l({status:"error",title:o("store.invalidJsonSchema"),description:T(e),duration:5e3}),!1}}return!0},x=t("div",{className:"flex gap-2 items-center",children:[e("div",{className:"text-base font-semibold",children:o("store.schemaEditor")}),!s&&e("div",{children:e(r,{variant:"outline",size:"sm",onClick:()=>{f&&!b()||g(e=>!e)},children:o(f?"store.editSchema":"store.editJson")})})]});return e(ye,{title:x,className:"bg-background! h-full",action:s?void 0:e(r,{isLoading:d,variant:"outline",size:"sm",onClick:()=>{f&&!b()||(u(!0),i.types.update(n.id,{object_schema:m.schema}).then(()=>{a(m),l({status:"success",title:o("store.schemaUpdated"),description:o("store.schemaUpdatedSuccess"),duration:2e3})}).catch(e=>{l({status:"error",title:o("store.failedToUpdateSchema"),description:e.message,duration:5e3})}).finally(()=>{u(!1)}))},children:o("modal.saveChanges")}),children:f?e(va,{value:v,language:"json",editorRef:h,theme:"dark"===c?"vs-dark":"vs",options:{readOnly:s}}):e(wa,{schema:m,readonly:s})})}!function(e){e.true="Yes",e.false="No"}(Av||(Av={}));const $v=e=>{try{new _a({strict:!1}).compile(e)}catch(e){throw new Error(`Invalid JSON Schema definition: ${T(e)}`,{cause:e})}};function Lv({isOpen:n,onClose:a,title:s,children:i,initialSelectedType:o=null,allowNone:l=!0}){const{t:c}=Ze(),d=s??c("store.selectContentType"),{registry:u}=cp(),[m,p]=Oe(o),f=u?.types||[],g=()=>{a(void 0)};return t(H,{isOpen:n,onClose:g,className:"w-full max-w-xl mx-auto",children:[e(G,{children:d}),t(J,{children:[i,t("div",{className:"mb-4 mt-4",children:[t("div",{className:"block text-sm font-medium mb-2",children:[c("store.contentType")," ",l&&e("span",{className:"text-gray-500 font-normal",children:c("store.optional")})]}),e($,l?{options:f,value:m,optionLabel:e=>e?e.name:c("store.selectContentTypeLabel"),placeholder:c("store.selectContentTypeAuto"),onChange:e=>p(e||null),filterBy:"name",isClearable:!0}:{options:f,value:m,optionLabel:e=>e?e.name:c("store.selectContentTypeLabel"),placeholder:c("store.selectContentTypeLabel"),onChange:e=>p(e||null),filterBy:"name"})]}),!m&&t("div",{className:"flex items-center text-attention",children:[e(bn,{className:"size-4 me-1"}),c("store.automaticTypeDetection"),e(h,{description:c("store.automaticTypeDetectionDescription"),placement:"top",size:"xs",children:e(qt,{className:"size-3 ms-2"})})]})]}),t(Y,{children:[e(r,{variant:"ghost",onClick:g,alt:c("modal.cancel"),children:c("modal.cancel")}),e(r,{onClick:()=>{a(m?.id??null),p(null)},alt:c("store.confirmSelection"),children:c("modal.confirm")})]})]})}function Fv({children:t,limit:n,name:r,chunkable:a}){const{store:s}=tr(),i=Me(()=>{const e=new Iv(s,n);return e.query.name=r,e.query.chunkable=a,e},[a,n,r,s]);return e(zv.Provider,{value:i,children:t})}function Mv({objectType:t,onLayoutUpdate:n,readonly:a=!1}){const s=p(),{theme:i}=le(),{t:o}=Ze(),[l,c]=Oe(!1),{store:d}=tr(),u=Be(void 0),m=Me(()=>Ov(t.table_layout),[t.table_layout]),h=(e,t)=>{s({status:"error",title:e,description:t,duration:5e3})};return e(ye,{title:"Table Layout Editor",className:"bg-background! h-full",action:a?void 0:e(r,{isLoading:l,variant:"outline",size:"sm",onClick:()=>{if(!u.current)return;const e=u.current.getValue();let r;if(e)try{r=JSON.parse(e)}catch(e){return h("Invalid JSON",T(e))}else r=null;return Array.isArray(r)?r.some(e=>!e?.name||!e.field)?h("Invalid JSON","A table layout entry must contain the following properties:] {field, name, converter?}"):(c(!0),void d.types.update(t.id,{table_layout:r}).then(e=>{s({status:"success",title:o("store.tableLayoutUpdated"),description:o("store.tableLayoutUpdatedDesc"),duration:2e3}),n(e.table_layout)}).catch(e=>{s({status:"error",title:o("store.failedToUpdateTableLayout"),description:e.message,duration:5e3})}).finally(()=>{c(!1)})):h("Invalid JSON","The table layout must be an array")},children:o("store.saveChanges")}),children:e("div",{className:"h-full",children:e(va,{value:m,language:"json",editorRef:u,theme:"dark"===i?"vs-dark":"vs",options:{readOnly:a}})})})}function Ov(e){return e?JSON.stringify(e,null,2):"[\n\n]"}function Uv({collection:t}){const{client:n}=tr(),{t:a}=Ze(),[s,i]=Oe(void 0),[o,l]=Oe(t.shared_properties||[]),c=p();He(()=>{t.type?.id&&n.store.types.retrieve(t.type.id).then(i)},[n.store.types.retrieve,t.type?.id]);const d=s?Object.keys(s.object_schema?.properties||{}):[];return e(ye,{title:a("store.sharedProperties"),description:a("store.sharedPropertiesDescription"),action:e(r,{size:"lg",isLoading:!1,onClick:()=>{n.store.collections.update(t.id,{shared_properties:o}).then(()=>{c({title:a("store.updatedSharedProperties"),status:"success"})}).catch(e=>{c({title:a("store.failedToUpdateSharedProperties"),description:e.message,status:"error"})})},children:a("modal.save")}),children:e("div",{className:"",children:e(we,{value:o,onChange:e=>{l(e)},options:d,placeholder:a("store.selectPropertiesToShare")})})})}function Wv({collection:t}){const{client:n}=tr(),{t:r}=Ze(),[a,s]=Oe(t.skip_head_sync??!1),[i,o]=Oe(!1),l=p();return e(ye,{title:r("store.syncMemberHeads"),description:r("store.syncMemberHeadsDescription"),children:e(fe,{disabled:i,value:!a,onChange:e=>{const a=!e;o(!0),n.store.collections.update(t.id,{skip_head_sync:a}).then(()=>{l({title:r("store.updatedSkipHeadSync"),status:"success"}),s(a)}).catch(e=>{l({title:r("store.failedToUpdateSkipHeadSync"),description:e.message,status:"error"})}).finally(()=>{o(!1)})},children:r("store.enableSyncMemberHeads")})})}function Bv({refetch:a,collection:s}){const{t:i}=Ze(),o=s.type?Sr(s.type):void 0,l=Be(void 0),c=p(),{theme:u}=le(),{client:m}=tr(),h=We(jh),[g,v]=Oe(!1),[b,x]=Oe({name:s.name,description:s.description||"",query:s.query?JSON.stringify(s.query,null,2):"",tags:s.tags||[],type:s.type?Sr(s.type):"",allowed_types:s.allowed_types||[],sensitivity:s.sensitivity,compartments:s.compartments||[]}),[y,w]=Oe(""),N=Me(()=>Ov(s.table_layout),[s.table_layout]),k=(e,t)=>{x({...b,[e]:t})};return t("div",{className:"flex flex-col gap-4 py-2",children:[t(ye,{title:i("store.configuration"),action:e(r,{size:"lg",isDisabled:g,onClick:()=>{let e;try{const n=b.query?JSON.parse(b.query):void 0;if(void 0!==n&&("object"!=typeof(t=n)||null===t||Array.isArray(t)))throw new Error(i("store.invalidQueryJson"));e=n}catch(e){return void c({title:i("store.invalidQueryJson"),description:T(e),status:"error",duration:5e3})}var t;const n={name:b.name,description:b.description,query:e,tags:b.tags,type:b.type,allowed_types:b.allowed_types,sensitivity:b.sensitivity,compartments:b.compartments};let r;if(n.name||(r=i("type.nameRequired")),n.type||(n.type=null),r)c({title:i("store.validationFailed"),description:r,status:"error",duration:5e3});else{if(l.current){const e=l.current.getValue();if(e)try{n.table_layout=JSON.parse(e)}catch(e){return void c({title:i("store.invalidTableLayout"),description:T(e),status:"error",duration:5e3})}else n.table_layout=null}v(!0),m.store.collections.update(s.id,n).then(()=>{a(),s.dynamic&&h&&(h.reset(),h.search()),c({title:i("store.collectionUpdated"),description:i("store.collectionUpdatedSuccess"),status:"success",duration:3e3})}).catch(e=>{c({title:i("store.failedToUpdateCollection"),description:T(e),status:"error",duration:5e3})}).finally(()=>{v(!1)})}},children:i("modal.save")}),children:[t("div",{className:"flex justify-between mb-2",children:[t("div",{className:"w-1/2 gap-2 flex flex-col",children:[e("div",{className:"text-sm font-medium mb-1",children:i("store.createdBy")}),t("div",{className:"gap-2 flex items-center",children:[e(Qm,{userRef:s.created_by,showTitle:!0}),t("span",{children:["at ",Dr(s.created_at).format("YYYY-MM-DD HH:mm:ss")]})]})]}),t("div",{className:"w-1/2 gap-2 flex flex-col",children:[e("div",{className:"text-sm font-medium mb-1",children:i("store.updatedBy")}),t("div",{className:"gap-2 flex items-center",children:[e(Qm,{userRef:s.updated_by,showTitle:!0}),t("span",{children:["at ",Dr(s.updated_at).format("YYYY-MM-DD HH:mm:ss")]})]})]})]}),e(ie,{label:i("type.name"),required:!0,children:e(d,{value:b.name,onChange:e=>k("name",e)})}),e(ie,{label:i("type.description"),children:e(X,{value:b.description,onChange:e=>k("description",e.target.value)})}),!s.dynamic&&e(ie,{label:i("store.allowedContentTypes"),description:i("store.allowedContentTypesSelectDescription"),children:e(yv,{defaultValue:b.allowed_types||null,onChange:e=>{Array.isArray(e)?k("allowed_types",e.map(e=>e.id)):k("allowed_types",e?[e.id]:[])},isClearable:!0,multiple:!0})}),s.dynamic&&e(ie,{label:i("store.query"),description:i("store.queryDescription"),children:e(X,{className:Ne.INPUT,minLines:1,maxLines:12,value:b.query,onChange:e=>k("query",e.target.value)})}),e(ie,{label:i("store.tableLayout"),description:i("store.tableLayoutDescription"),className:"h-[200px]",children:e(va,{className:"border-1 rounded-md border-border",value:N,language:"json",editorRef:l,theme:"dark"===u?"vs-dark":"vs"})}),e(ie,{label:i("store.contentType"),description:i("store.typeSelectDescription"),children:e(yv,{defaultValue:b.type||null,onChange:e=>{Array.isArray(e)?k("type",e.length>0?e[0].id:null):k("type",e?.id||null)},isClearable:!0})}),e(ie,{label:"Sensitivity",description:"BLP sensitivity level — propagated to member documents (max across collections)",children:e($,{options:Tr.map((e,t)=>({label:`${t} — ${e}`,value:t})),value:void 0!==b.sensitivity?{label:`${b.sensitivity} — ${Tr[b.sensitivity]??"Unknown"}`,value:b.sensitivity}:void 0,onChange:e=>k("sensitivity",e.value),optionLabel:e=>e.label,by:"value",placeholder:"Not set"})}),t(ie,{label:"Compartments",description:"Security compartments — propagated to member documents (union across collections)",children:[t("div",{className:"flex gap-2",children:[e(d,{value:y,onChange:w,placeholder:"Add a compartment",onKeyDown:e=>{if("Enter"===e.key){e.preventDefault();const t=y.trim();t&&!b.compartments.includes(t)&&(k("compartments",[...b.compartments,t]),w(""))}}}),e(r,{type:"button",variant:"outline",onClick:()=>{const e=y.trim();e&&!b.compartments.includes(e)&&(k("compartments",[...b.compartments,e]),w(""))},children:"Add"})]}),e("div",{className:"flex gap-1 flex-wrap mt-2",children:b.compartments.map(e=>t(f,{variant:"secondary",className:"cursor-pointer",onClick:()=>k("compartments",b.compartments.filter(t=>t!==e)),children:[e," ×"]},e))})]})]}),o&&e(Vv,{typeId:o,collection:s}),!s.dynamic&&t(n,{children:[e(Wv,{collection:s}),e(Uv,{collection:s})]})]})}function Vv({typeId:t,collection:n}){const{t:a}=Ze(),[s,i]=Oe({}),o=p(),{client:l}=tr(),[c,d]=Oe(!1),{data:u,error:m}=S(()=>l.store.types.catalog.resolve(t),[t]),h=u?.object_schema||{},f=Me(()=>new Na(h,n.properties||{}),[h,n.properties]);if(m)return e(b,{title:a("store.failedToLoadType"),children:T(m)});if(!u)return null;return e(ye,{title:a("store.properties"),action:e(r,{size:"lg",isLoading:c,type:"submit",onClick:()=>(e=>{if(!e||!Object.keys(e).length)return;const t={properties:e||{}};d(!0),l.store.collections.update(n.id,t).then(()=>{o({title:a("store.collectionPropertiesUpdated"),description:a("store.collectionUpdatedSuccess"),status:"success",duration:3e3})}).catch(e=>{o({title:a("store.failedToUpdateCollectionProperties"),description:T(e),status:"error",duration:5e3})}).finally(()=>{d(!1)})})(s),children:a("modal.save")}),children:e(ka,{object:f,onChange:e=>{e instanceof Na&&i(e.value)}})})}function qv({onChange:n,value:a,disabled:s=!1,placeholder:o,searchPlaceholder:l,filterOut:c,allowDynamic:d=!0,multiple:u=!1}){const{client:m}=tr(),{t:p}=Ze(),h=o??p("store.selectACollection"),f=l??p("store.searchCollections"),[g,v]=Oe(""),[x,y]=Oe(!1),[w,N]=Oe(!1),k=xe(g,300),C=Ve(async e=>{y(!0);const t=e.trim(),n=await m.store.collections.search({dynamic:!!d&&void 0,name:w&&t||void 0});return y(!1),!w&&n.length>=1e3&&N(!0),c&&c.length>0?n.filter(e=>!c.includes(e.id)):n},[m,d,c,w]),{data:_,error:j}=S(()=>C(w?k:""),[w?k:"",C]),P=Me(()=>_?u&&Array.isArray(a)?_.filter(e=>a.includes(e.id)):u||"string"!=typeof a?u?[]:void 0:_.find(e=>e.id===a):u?[]:void 0,[_,a,u]),A=Ve(e=>{if(u){const t=Array.isArray(a)?a:[];if(t.includes(e.id)){const r=t.filter(t=>t!==e.id),a=_?.filter(e=>r.includes(e.id))||[];n(r,a)}else{const r=[...t,e.id],a=_?.filter(e=>r.includes(e.id))||[];n(r,a)}}else n(e.id,e)},[n,a,_,u]),D=Ve(()=>{n(void 0,void 0)},[n]),E=Ve(e=>{v(e)},[]),$=g.trim().length>0,L=Me(()=>{if(!_)return[];if(w)return _;if(!$)return _;const e=g.toLowerCase();return _.filter(t=>t.name.toLowerCase().includes(e))},[_,w,$,g]),F=u?Array.isArray(P)&&P.length>0:!!P;if(j)return e(b,{title:p("store.collectionFetchFailed"),children:T(j)});return t(I,{children:[e(z,{asChild:!0,children:t(r,{variant:"outline",role:"combobox","aria-haspopup":"listbox",className:i("w-full justify-between min-w-0"),disabled:s,children:[e("span",{className:"truncate flex-1 text-start min-w-0",children:u&&Array.isArray(P)&&P.length>0?1===P.length?P[0].name:p("store.collectionsSelected",{count:P.length}):u||!P||Array.isArray(P)?h:P.name}),F&&!s?e(r,{variant:"unstyled","aria-label":"Clear selection",className:"ms-2 shrink-0 opacity-50 hover:opacity-100 hover:text-destructive cursor-pointer",onClick:e=>{e.stopPropagation(),D()},children:e(ut,{className:"h-4 w-4"})}):e(Zn,{className:"ms-2 h-4 w-4 shrink-0 opacity-50"})]})}),e(R,{className:"mt-2 mb-2 w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:t(ke,{shouldFilter:!1,children:[t("div",{className:"flex justify-between items-center border-b px-3","cmdk-input-wrapper":"",children:[e(Ce,{placeholder:f,value:g,onValueChange:E,className:"flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50"}),x&&e("div",{className:"me-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"})]}),e(_e,{children:p(x?"store.searching":$?"store.noCollectionsFound":"store.noCollectionsAvailable")}),t(Se,{className:"max-h-[300px] overflow-auto",children:[F&&!$&&e(Te,{value:"__clear__",onSelect:D,className:"text-destructive",children:"Remove collection selection(s)"}),$&&e(Te,{value:"__clear_search__",onSelect:()=>v(""),className:"text-muted",children:p("store.clearSelection")}),L.map(n=>{const r=u&&Array.isArray(a)?a.includes(n.id):a===n.id;return t(Te,{value:n.id,onSelect:()=>A(n),className:"flex items-center justify-between",children:[e("span",{className:"truncate",children:n.name}),r&&e(it,{className:"ms-2 h-4 w-4 shrink-0"})]},n.id)})]})]})})]})}function Hv({isOpen:n,onClose:r}){return t(H,{onClose:()=>r(),isOpen:!!n,className:"min-w-[60vw]",children:[e(G,{children:"Select Content"}),e(J,{className:"pt-0 overflow-y-auto max-h-[80vh] min-h-[80vh]",children:n&&e(Qh,{onChange:r})})]})}const Gv=/store:([a-f0-9]+)/;function Jv({object:n}){const{client:a}=tr(),{off:s,on:i,isOn:o}=Ie(),[l,c]=Oe(null!=n.value?String(n.value):""),[d,u]=Oe(void 0),m=Ve(()=>{c(""),n.value="",u(void 0)},[n]);return He(()=>{if(!l||d)return;const e=l.match(Gv);e&&a.objects.retrieve(e[1]).then(e=>{u(e)}).catch(()=>{m()})},[l,a.objects.retrieve,m,d]),t("div",{children:[t("div",{className:"relative",children:[e("input",{value:l,onChange:e=>{const t=e.target.value;c(t),n.value=t},className:Ae(Ne.INPUT,"pe-10 w-full")}),d&&e("div",{className:"absolute inset-y-0 end-10 flex items-center justify-center ",children:e(r,{onClick:m,variant:"unstyled",className:"hover:text-red-500 hover:bg-gray-100 dark:hover:bg-gray-600",children:e(ut,{className:"size-5"})})}),e("div",{className:"absolute inset-y-0 end-0 flex items-center justify-center",children:e(r,{onClick:i,variant:"unstyled",className:"hover:bg-gray-100 dark:hover:bg-gray-600",children:e(Zn,{className:"size-5"})})}),e(Hv,{value:l,isOpen:o,onClose:e=>{if(e){const t=`store:${e.id}`;c(t),u(e||void 0),n.value=t}s()}})]}),d&&e("div",{className:"p-1 semibold text-sm text-gray-600 dark:text-slate-300",children:"string"==typeof d.properties?.title?d.properties.title:d.name})]})}function Kv({objectId:n,isOpen:a,onClose:s}){const i=ia(),{client:o,store:l}=tr(),[c,d]=Oe(null),[u,m]=Oe(!1),[h,f]=Oe(!1),[g,v]=Oe(),[b,x]=Oe(),[y,w]=Oe("preview"),{t:N}=Ze(),k=p(),C=Ve(async e=>{f(!0);try{const t=await l.objects.getObjectText(e);v(t.text)}catch(e){console.error("Error loading text:",e)}finally{f(!1)}},[l.objects]),_=Ve(async e=>{if(e.content?.source)try{"found"===(await o.objects.getRendition(e.id,{format:fr.jpeg,generate_if_missing:!1})).status&&console.log("Found rendition");const t=await o.files.getDownloadUrl(e.content.source);x(t.url)}catch(e){console.error("Error loading image:",e)}},[o.files,o.objects]);He(()=>{n&&a?(m(!0),l.objects.retrieve(n,"+embeddings").then(e=>{d(e),e.text?v(e.text):C(e.id);const t=e.content;t?.source&&t.type?.startsWith("image/")&&_(e)}).catch(e=>{console.error("Error loading object:",e),k({title:N("agent.error"),description:N("store.failedToLoadDocument"),status:"error",duration:3e3})}).finally(()=>{m(!1)})):(d(null),v(void 0),x(void 0))},[n,a,l.objects,C,_,N,k]);const S=()=>{c&&(i(`/legal/objects/${c.id}`),s())},T=g&&(g.startsWith("#")||g.includes("\n#")||g.includes("\n*")),I=c?.content?.type?.startsWith("image/"),z="application/pdf"===c?.content?.type;if(!a)return null;return t("div",{className:`fixed inset-y-0 end-0 w-2/5 dark:bg-slate-900 shadow-xl z-50 flex flex-col transition-transform duration-300 transform ${a?"translate-x-0":"translate-x-full rtl:-translate-x-full"}`,children:[t("div",{className:"flex items-center justify-between px-4 py-3 border-b dark:border-gray-700 bg-gradient-to-r from-indigo-50 to-gray-50 dark:from-gray-800 dark:to-gray-900",children:[t("div",{className:"flex items-center",children:[e(kt,{className:"h-5 w-5 text-indigo-600 me-2"}),e("h2",{className:"text-lg font-semibold text-gray-800 dark:text-gray-200 truncate",children:u?N("store.loadingDocument"):c?.name||N("store.documentPreview")})]}),t("div",{className:"flex items-center gap-2",children:[t(r,{variant:"ghost",size:"sm",onClick:S,className:"flex items-center gap-1 text-indigo-600 hover:text-indigo-800",children:[e(dt,{className:"h-4 w-4"}),e("span",{children:N("store.fullView")})]}),e(r,{variant:"ghost",size:"sm",onClick:s,className:"flex items-center text-gray-600 hover:text-gray-800 dark:text-gray-300 dark:hover:text-gray-100",children:e(ut,{className:"h-5 w-5"})})]})]}),u?e("div",{className:"flex-1 flex items-center justify-center",children:t("div",{className:"text-center",children:[e(K,{size:"lg",className:"text-indigo-600 dark:text-indigo-400 mb-2"}),e("p",{className:"text-gray-600 dark:text-gray-400",children:N("store.loadingDocument")})]})}):t("div",{className:"flex-1 flex flex-col h-full",children:[e("div",{className:"border-b",children:t("div",{className:"flex px-4",children:[e(r,{variant:"unstyled",className:"py-2 px-4 font-medium border-b-2 "+("preview"===y?"border-indigo-600 text-indigo-700 dark:text-indigo-300":"border-transparent text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"),onClick:()=>w("preview"),children:t("div",{className:"flex items-center gap-1",children:[e(Dn,{className:"h-4 w-4"}),e("span",{children:N("store.preview")})]})}),e(r,{variant:"unstyled",className:"py-2 px-4 font-medium border-b-2 "+("properties"===y?"border-indigo-600 text-indigo-700 dark:text-indigo-300":"border-transparent text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"),onClick:()=>w("properties"),children:t("div",{className:"flex items-center gap-1",children:[e(qt,{className:"h-4 w-4"}),e("span",{children:N("store.properties")})]})})]})}),t("div",{className:"flex-1 overflow-auto p-4",children:["preview"===y&&t("div",{className:"h-full",children:[h?e("div",{className:"flex items-center justify-center h-40",children:e(K,{size:"md",className:"text-indigo-600 dark:text-indigo-400"})}):g?e("div",{className:"shadow rounded-md p-4 border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800",children:T?e("div",{className:"prose prose-sm max-w-none prose-p:my-2 prose-pre:bg-gray-800 prose-pre:my-2 prose-headings:text-indigo-700 dark:prose-invert dark:prose-headings:text-indigo-300",children:e(oa,{children:g})}):e("pre",{className:"text-wrap whitespace-pre-wrap dark:text-gray-200",children:g})}):null,I&&e("div",{className:"mt-4",children:e("div",b?{className:"border border-gray-200 dark:border-gray-700 rounded-md p-2 bg-white dark:bg-gray-800",children:e("img",{src:b,alt:c?.name,className:"mx-auto max-h-[70vh] object-contain"})}:{className:"flex items-center justify-center h-40",children:e(K,{size:"md",className:"text-indigo-600 dark:text-indigo-400"})})}),z&&t("div",{className:"flex flex-col items-center justify-center h-64 border border-gray-200 dark:border-gray-700 rounded-md p-4 bg-gray-50 dark:bg-gray-800",children:[e(kt,{className:"h-16 w-16 text-indigo-300 dark:text-indigo-400 mb-4"}),e("p",{className:"text-gray-600 dark:text-gray-400 text-center mb-4",children:N("store.pdfPreviewFullView")}),e(r,{onClick:S,className:"bg-indigo-600 hover:bg-indigo-700 text-white",children:N("store.openFullDocumentView")})]}),!I&&!g&&!z&&!h&&t("div",{className:"flex flex-col items-center justify-center h-64 border border-gray-200 dark:border-gray-700 rounded-md p-4 bg-gray-50 dark:bg-gray-800",children:[e(kt,{className:"h-16 w-16 text-gray-300 dark:text-gray-600 mb-4"}),e("p",{className:"text-gray-600 dark:text-gray-400 text-center",children:N("store.noPreviewAvailable")})]})]}),"properties"===y&&c&&t("div",{className:"h-full",children:[c.properties?e("div",{className:"shadow rounded-md p-4 border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800",children:e(ba,{value:c.properties})}):t("div",{className:"flex flex-col items-center justify-center h-64 border border-gray-200 dark:border-gray-700 rounded-md p-4 bg-gray-50 dark:bg-gray-800",children:[e(qt,{className:"h-16 w-16 text-gray-300 dark:text-gray-600 mb-4"}),e("p",{className:"text-gray-600 dark:text-gray-400 text-center",children:N("store.noPropertiesAvailable")})]}),t("div",{className:"mt-4",children:[e("h3",{className:"text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2",children:N("store.documentInformation")}),e("div",{className:"shadow rounded-md p-4 border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800",children:t("div",{className:"grid grid-cols-2 gap-y-2 gap-x-4 text-sm",children:[e("div",{className:"text-gray-500 dark:text-gray-400",children:N("store.id")}),e("div",{className:"font-medium dark:text-gray-200",children:c.id}),e("div",{className:"text-gray-500 dark:text-gray-400",children:N("store.contentType")}),e("div",{className:"font-medium dark:text-gray-200",children:c.type?.name||N("store.unknown")}),e("div",{className:"text-gray-500 dark:text-gray-400",children:N("store.contentType")}),e("div",{className:"font-medium dark:text-gray-200",children:c.content?.type||N("store.na")}),e("div",{className:"text-gray-500",children:N("store.size")}),e("div",{className:"font-medium",children:c.content&&"size"in c.content?Qv(c.content.size):N("store.unknown")}),e("div",{className:"text-gray-500",children:N("store.created")}),e("div",{className:"font-medium",children:c.created_at?new Date(c.created_at).toLocaleString():N("store.na")}),e("div",{className:"text-gray-500",children:N("store.updated")}),e("div",{className:"font-medium",children:c.updated_at?new Date(c.updated_at).toLocaleString():N("store.na")})]})})]})]})]})]}),t("div",{className:"flex items-center justify-between p-4 border-t bg-gray-50 dark:bg-gray-800 dark:border-gray-700",children:[e("div",{children:c?.content?.source&&t(r,{onClick:()=>{c?.content?.source&&o.files.getDownloadUrl(c.content.source).then(e=>{window.open(e.url,"_blank")}).catch(e=>{console.error("Error getting download URL:",e),k({title:N("agent.error"),description:N("store.failedToDownloadFile"),status:"error",duration:3e3})})},variant:"outline",className:"text-indigo-600 border-indigo-300 hover:bg-indigo-50",children:[e(lt,{className:"h-4 w-4 me-2"}),N("pdf.download")]})}),t(r,{onClick:S,className:"bg-indigo-600 hover:bg-indigo-700 text-white",children:[N("store.openFullDocument"),e(ht,{className:"h-4 w-4 ms-2 cn-rtl-flip"})]})]})]})}function Qv(e){if(0===e)return"0 Bytes";const t=Math.floor(Math.log(e)/Math.log(1024));return`${parseFloat((e/1024**t).toFixed(2))} ${["Bytes","KB","MB","GB","TB"][t]}`}var Yv;function Zv({isExporting:n,isOpen:r,onClose:a}){return t(H,{onClose:()=>a(void 0),isOpen:r,children:[e(G,{children:"Export Object Properties"}),t(J,{children:[!n&&e(Xv,{onClose:a}),n&&e(eb,{})]})]})}function Xv({onClose:n}){const{t:a}=Ze(),[s,i]=Oe(void 0),[o,l]=Oe(void 0),c=["Export selected objects","Export all objects"];return t(J,{className:"min-h-[104px] pt-0 flex flex-col gap-y-4",children:[e("div",{className:"h-1/3",children:e($,{options:c,value:o,onChange:l,placeholder:a("store.chooseWhatToExport"),className:"h-full w-full text-sm",filterBy:"name",isClearable:!0})}),t("div",{className:"h-1/2 flex flex-col gap-y-8 content-between",children:[e($,{options:Object.values(Yv),value:s,onChange:i,placeholder:a("store.chooseAFormat"),className:"h-full w-full text-sm",filterBy:"name",isClearable:!0}),e(r,{className:"w-full",isDisabled:!s||!o,onClick:()=>{n(s,o===c[1])},children:a("store.actions.exportProperties")})]})]})}function eb(){const{t:n}=Ze();return e(J,{className:"min-h-[84px] pt-0",children:t("div",{className:"h-full grid flex-col gap-y-2 content-between justify-items-center",children:[t("div",{className:"text-sm flex flex-col gap-x-2",children:[e("p",{children:n("store.exportInProgress")}),e("p",{className:"pt-2 grid justify-items-center",children:n("store.pleaseWait")})]}),e(K,{size:"lg"})]})})}!function(e){e.CSV="CSV",e.JSON="JSON"}(Yv||(Yv={}));const tb=Ue(void 0);function nb(){const e=We(tb);if(!e)throw new Error("You cannot use useActionContext outside an ActionProvider");return e}function rb(e,t){const n=nb();return He(()=>n.registerCallback(e,t),[n,e,t]),n}function ab({action:t,objectIds:n}){const[r,a]=Oe(!1),s=Ve(()=>(n.length>0&&a(!0),Promise.resolve(!0)),[n]);return rb(t.id,s),r&&e(ce,{children:e(ob,{objectIds:n,isOpen:r,onClose:()=>{a(!1)}})})}const sb=Xe.getFixedT(null,et),ib={id:"addToCollection",name:sb("store.actions.addToCollection"),description:sb("store.actions.addToCollectionDesc"),confirm:!1,component:ab};function ob({isOpen:n,onClose:r,objectIds:a}){const{t:s}=Ze();return t(H,{isOpen:n,onClose:r,className:"max-w-lg w-full min-w-0 overflow-hidden",children:[e(G,{className:"flex flex-col min-w-0 overflow-hidden",children:s("store.actions.addToCollectionTitle")}),e(ze,{className:"min-w-0 overflow-hidden",children:s("store.actions.addToCollectionBody")}),e("div",{className:"min-w-0 max-w-full overflow-hidden",children:e(lb,{onClose:r,objectIds:a})})]})}function lb({onClose:n,objectIds:a}){const{t:s}=Ze(),i=p(),{client:o}=tr(),[l,c]=Oe(),d=({collectionId:e})=>{e&&a?.length&&o.store.collections.addMembers(e,a).then(()=>{i({title:s("store.actions.addToCollectionSuccess"),status:"success",description:s("store.actions.addToCollectionSuccessDesc",{count:a.length}),duration:3e3}),n()}).catch(()=>{i({title:s("store.actions.addToCollectionFailure"),status:"error",description:s("store.actions.addToCollectionFailureDesc"),duration:5e3})})},u=[{name:"select",label:s("store.actions.selectCollection"),content:t("div",{className:"p-4 min-w-0 max-w-full overflow-hidden",children:[e(Re,{level:5,children:s("store.actions.chooseExistingCollections")}),e(J,{className:"min-w-0 max-w-full overflow-hidden",children:e("div",{className:"mb-4 min-w-0 max-w-full overflow-hidden",children:e(qv,{onChange:(e,t)=>{"string"==typeof e||void 0===e?c(e):Array.isArray(e)&&e.length>0?c(e[0]):c(void 0)},value:l})})}),e(Y,{children:e(r,{isDisabled:!l,onClick:()=>l&&d({collectionId:l}),children:s("store.actions.addToCollectionButton")})})]})},{name:"create",label:s("store.actions.createNew"),content:e("div",{className:"p-4",children:e(wv,{onClose:n,onAddToCollection:e=>d({collectionId:e}),redirect:!1})})}];return t(y,{defaultValue:"select",tabs:u,fullWidth:!0,children:[e(je,{}),e(w,{})]})}function cb({action:n,objectIds:r,children:a}){const{t:s}=Ze(),{store:i}=tr(),o=p(),[l,c]=Oe(!1),d=Ve(()=>(c(!0),Promise.resolve(!0)),[]);rb(n.id,d);return t("div",{children:[a,e(Lv,{isOpen:l,onClose:e=>{c(!1),void 0!==e&&i.runOperation({name:"change_type",ids:r,params:{typeId:e}}).then(e=>{o({status:"success",title:s("store.actions.changeType"),description:`Change the type of ${r.length} objects is ${"in_progress"===e.status?"in progress":"completed"}`,duration:2e3})}).catch(e=>{o({status:"error",title:s("store.actions.errorChangingType"),description:e.message,duration:5e3})})},title:"Change Content Type",confirmLabel:"Change Type",children:t("p",{className:"pt-2 text-xs",children:["Note: This action will raise the ",e("code",{children:"change_type"})," event and will trigger the standard intake workflows which may reset the object properties."]})})]})}const db=Xe.getFixedT(null,et),ub={id:"changeType",name:db("store.actions.changeContentType"),description:db("store.actions.changeContentTypeDesc"),confirm:!1,component:cb};function mb({action:r,callback:a,children:s}){const{t:i}=Ze(),[o,l]=Oe(!1),c=r.confirmationText||`Are you sure you want to ${r.name}?`,d=Ve(e=>r.confirm?(l(!0),Promise.resolve(!0)):a(e),[r.confirm,a]),u=rb(r.id,d);return t(n,{children:[s,e(be,{onConfirm:()=>{l(!1),a({...u.params,action:r})},onCancel:()=>l(!1),title:i("store.actions.areYouSure"),content:c,isOpen:o})]})}function pb({action:t,objectIds:n,children:r}){const{t:a}=Ze(),s=nb(),i=p(),{client:o}=tr(),l=Ph(),c=ia(),d=Ve(()=>n?.length?o.store.objects.delete(n).then(e=>{const t=e.deleted>1?"s":"";if(i({status:"success",title:`${e.deleted} object${t} deleted`,duration:2e3}),e.failed.length>0&&i({status:"warning",title:`${e.failed.length} object(s) could not be deleted`,duration:3e3}),l){s.params?.selection?.removeAll();const e=JSON.parse(JSON.stringify(l.facets));n.length===e._value.total&&l.resetFacets(),l.search()}else c("/objects")}).catch(e=>{i({status:"error",title:a("store.actions.errorDeletingObjects"),description:e.message,duration:5e3})}):(i({status:"error",title:a("store.actions.noObjectsSelected"),description:a("store.actions.pleaseSelectObjectsToDelete"),duration:3e3}),Promise.resolve(!1)),[o.store.objects.delete,s.params?.selection?.removeAll,c,n,l,l?.facets,l?.resetFacets,l?.search,a,i]);return e(mb,{action:t,callback:d,children:r})}const hb=Xe.getFixedT(null,et),fb={id:"delete",name:hb("store.actions.delete"),description:hb("store.actions.deleteTheSelectedObjects"),confirm:!0,confirmationText:hb("store.actions.confirmDeleteAll"),component:pb,destructive:!0},gb={id:"deleteFromCollections",name:hb("store.actions.deleteObjects"),description:hb("store.actions.deleteTheSelectedObjects"),confirm:!0,confirmationText:hb("store.actions.confirmDeleteSelected"),component:pb,destructive:!0};function vb({action:t,objectIds:n}){const{t:r}=Ze(),{store:a}=tr(),s=p(),[i,o]=Oe(!1),[l,c]=Oe(!1),d=Ve(()=>(o(!0),Promise.resolve(!0)),[]),u=rb(t.id,d);return e(Zv,{isExporting:l,isOpen:i,onClose:(e,t)=>{if(e&&(t||n.length>0)){c(!0);const i=u.params?.search?.query||{},l=u.params?.search?.result?.value?.objects?.map(e=>e.id)||void 0,d=async e=>a.objects.list({query:{parent:e}}).then(e=>e.map(e=>e.id)),m=async()=>t?l?i.vector?l:[]:0===n.length?[]:(await d(n[0])).concat(n):n,p=u.params?.type?.id??i.type,h=u.params?.type?.table_layout??void 0;m().then(l=>{a.objects.exportProperties({objectIds:l,type:e,query:t&&!i.vector?{...i,type:p}:{type:p},table_layout:h}).then(e=>{const a=new Blob([e.data],{type:e.type}),i=window.URL.createObjectURL(a),o=document.createElement("a");o.download=e.name,o.href=i,o.click(),s({status:"success",title:r("store.actions.exportProperties"),description:t?"Export the properties of all objects completed":`Export the properties of ${n.length} object${n.length>1?"s":""} is completed`,duration:2e3})}).catch(e=>{s({status:"error",title:r("store.actions.errorExportProperties"),description:e.message,duration:5e3})}).finally(()=>{c(!1),o(!1)})})}else o(!1),s({status:"error",title:r("store.actions.errorExportProperties"),description:"No objects selected for export",duration:5e3})}})}const bb=Xe.getFixedT(null,et),xb={id:"exportProperties",name:bb("store.actions.exportProperties"),description:bb("store.actions.exportAllObjectProperties"),confirm:!1,component:vb};function yb({action:t,objectIds:n,collectionId:r}){const{t:a}=Ze(),s=nb(),i=p(),{client:o}=tr(),l=Ph(),c=Ve(()=>n?.length?r?o.store.collections.deleteMembers(r,n).then(()=>{const e=n.length>1?"s":"";i({status:"success",title:`${n.length} object${e} removed from collection`,description:"Objects have been removed from the collection",duration:2e3}),l&&(s.params?.selection?.removeAll(),l.search())}).catch(e=>{i({status:"error",title:a("store.actions.errorRemovingObjects"),description:T(e),duration:5e3})}):(i({status:"error",title:a("store.actions.noCollectionContext"),description:a("store.actions.cannotRemoveNoCollection"),duration:3e3}),Promise.resolve(!1)):(i({status:"error",title:a("store.actions.noObjectsSelected"),description:a("store.actions.pleaseSelectObjectsToRemove"),duration:3e3}),Promise.resolve(!1)),[o.store.collections.deleteMembers,r,s.params?.selection?.removeAll,n,l,l?.search,a,i]);return e(mb,{action:t,callback:c})}const wb=Xe.getFixedT(null,et),Nb={id:"removeFromCollection",name:wb("store.actions.removeFromCollection"),description:wb("store.actions.removeFromCollectionDesc"),confirm:!0,confirmationText:wb("store.actions.confirmRemoveFromCollection"),component:yb,destructive:!0};function kb({action:t,objectIds:n,collectionId:r}){const{t:a}=Ze(),s=p(),{client:i}=tr(),[o,l]=Oe(!1),c=Ve(()=>(l(!0),Promise.resolve(!0)),[]);return rb(t.id,c),e(Sb,{isOpen:o,onClose:e=>{if(l(!1),e)return i.store.workflows.rules.execute(e,n,{collection_id:r}).then(()=>{s({title:a("store.actions.workflowStarted"),status:"success",duration:3e3})}).catch(e=>{s({title:a("store.actions.errorStartingWorkflow"),status:"error",description:e.message,duration:9e3})})}})}const Cb=Xe.getFixedT(null,et),_b={id:"startWorkflow",name:Cb("store.actions.startWorkflow"),description:Cb("store.actions.startWorkflowDesc"),confirm:!1,hideInList:!0,component:kb};function Sb({isOpen:n,onClose:r}){const{t:a}=Ze();return t(H,{onClose:()=>r(void 0),isOpen:n,className:"",children:[e(G,{children:a("store.actions.startWorkflowByRule")}),e(Ib,{onClose:r})]})}function Tb(n){return{label:t("div",{children:[e("div",{children:n.name}),e("div",{className:"text-sm text-muted",children:n.description})]}),reverse:!0}}function Ib({onClose:n}){const{t:a}=Ze(),[s,i]=Oe(void 0),o=nb();return t("div",{children:[t(J,{children:[e("div",{className:"pb-2",children:a("store.actions.chooseWorkflowRule")}),e("div",{className:"max-h-[420px] overflow-y-scroll border-border border rounded-md",children:e(Pe,{options:o.wfRules,optionLayout:Tb,onChange:e=>{i(e)},value:s})})]}),t(Y,{children:[e(r,{variant:"secondary",onClick:()=>n(),children:"Cancel"}),e(r,{onClick:()=>{s&&n(s.id)},isDisabled:!s,children:"Start"})]})]})}class zb{params;allActions=[];wfRules=[];callbacks={};startWorkflow;constructor(e){this.params=e}get actions(){return!!this.params.selection?.collectionId?this.allActions.filter(e=>"addToCollection"!==e.id&&"delete"!==e.id):this.allActions.filter(e=>"removeFromCollection"!==e.id&&"deleteFromCollections"!==e.id)}registerCallback(e,t){return this.callbacks[e]=t,()=>{delete this.callbacks[e]}}unregisterCallback(e){delete this.callbacks[e]}findAction(e){let t=this.allActions.find(t=>t.id===e);return t||(t=this.wfRules.find(t=>t.id===e)),t}async run(e){const t=this.findAction(e);if(!t)throw new Error(`Action ${e} not found`);const n={...this.params,action:t},r=this.callbacks[e];if(r)return r(n);throw new Error("No action callback set")}}const Rb=[xb,ub,_b,ib,fb,Nb,gb];function jb({children:n,type:r}){const{t:a}=Ze(),s=qp(),i=p(),{client:o}=tr(),l=Ph(),{data:c,error:d}=S(()=>o.workflows.rules.list().then(e=>e.map(e=>({id:e.id,name:e.name,description:e.description,confirm:!1,isWorkflow:!0,component:kb})).sort((e,t)=>e.name.localeCompare(t.name))),[]),u=Me(()=>{const e=new zb({selection:s,toast:i,client:o,search:l,type:r});return e.allActions=Rb,e.wfRules=c,e},[o,l,s,c,i,r]);return d?e(b,{title:a("store.failedToFetchWorkflows"),children:T(d)}):u&&t(tb.Provider,{value:u,children:[e(Pb,{}),n]})}function Pb(){const t=nb(),n=t.params.selection,r=n.getObjectId(),a=n.isSingleSelection()&&r?[r]:n.getObjectIds();return e("div",{style:{display:"none"},children:t.allActions.map(t=>e(t.component,{action:t,objectIds:a,collectionId:n.collectionId},t.id))})}function Ab({type:n,allowMutations:a=!0,allowDelete:s=!0,allowWorkflowRun:i=!0}){const o=qp(),l=o.size(),c=l>1?"s":"",d=o?.hasSelection(),u=o?.isSingleSelection();return e(jb,{type:n,children:t("div",{className:"flex items-center gap-x-2",children:[d&&!u&&t("div",{className:"flex items-center gap-x-1 shrink-0",children:[t("div",{className:"text-sm nowrap",children:[l," document",c," selected"]}),e(r,{title:"Clear selection",variant:"ghost",onClick:()=>{o?.removeAll()},children:e(ut,{className:"size-4"})})]}),e(Fb,{selection:o,allowMutations:a,allowDelete:s,allowWorkflowRun:i,children:t=>t.length>0?e(r,{variant:"ghost",alt:"More action",size:"sm",children:e(Xn,{size:16})}):null}),d&&i&&e(Db,{selection:o})]})})}function Db(t){return e($b,{})}function Eb({collectionId:a,allowFolders:s=!0}){const{t:i}=Ze(),[o,l]=Oe([]),[c,d]=Oe(!1);return t(n,{children:[e(r,{onClick:()=>d(!0),children:i("store.upload")}),e(Oh,{collectionId:a??"",isOpen:c,onClose:()=>{d(!1),l([])},files:o,title:"Upload Files",onUploadComplete:e=>{e?.success&&l([])},allowFolders:s})]})}function $b(){const t=nb(),{t:n}=Ze();return t.params.selection.hasSelection()&&e(r,{onClick:()=>t.run(_b.id),children:n("store.actions.startWorkflow")})}function Lb(e){return{label:e.name,className:Ae("flex-1 px-2 py-2 hover:bg-accent nowrap",e.destructive?"text-destructive":"")}}function Fb({selection:n,children:r,allowMutations:a=!0,allowDelete:s=!0,allowWorkflowRun:i=!0}){const o=nb(),l=function(e,t,n){if(!t?.hasSelection())return[xb];return e.filter(e=>!e.hideInList&&("startWorkflow"===e.id?n.allowWorkflowRun:"delete"===e.id||"deleteFromCollections"===e.id?n.allowDelete:"changeType"!==e.id&&"addToCollection"!==e.id&&"removeFromCollection"!==e.id||n.allowMutations))}(o.actions,n,{allowMutations:a,allowDelete:s,allowWorkflowRun:i}),c=r(l);return c?t(I,{hover:!0,children:[e(z,{children:c}),e(R,{className:"p-0 w-50",align:"end",sideOffset:6,children:e(Mb,{executeAction:e=>{o.run(e.id)},actions:l})})]}):null}function Mb({executeAction:t,actions:n}){return e("div",{className:"rounded-md shadow-md py-2",children:e("div",{className:"px-1 text-sm",children:e(Pe,{options:n,optionLayout:Lb,onChange:e=>{t(e)},noCheck:!0})})})}function Ob({user:n}){return t("div",{className:"flex items-center",children:[e("div",{className:"w-9 h-9",children:(()=>{if(n.picture)return e("img",{className:"inline-block h-9 w-9 rounded-full",src:n.picture,alt:n.name});{const t=n.name.split(" ").map(e=>e[0]).join("");return e("span",{className:"inline-flex h-8 w-8 items-center justify-center rounded-full bg-indigo-600",children:e("span",{className:"text-sm font-medium leading-none text-white",children:t})})}})()}),t("div",{className:"ms-3",children:[e("p",{className:"text-sm font-medium text-gray-700 dark:text-slate-50 group-hover:text-gray-900",children:n.name??"Deleted User"}),e("p",{className:"text-xs font-medium text-gray-500 dark:text-slate-300 group-hover:text-gray-700",children:n.email??"Deleted User"})]})]})}export{La as ActivitiesDoc,Ma as ActivityDoc,ib as AddToCollectionAction,ab as AddToCollectionActionComponent,Ja as AgentApprovalModeSelector,ps as AgentChart,ku as AgentChatFixtureReplay,ks as AgentChatPlaybackControls,sp as AgentRunnerFacetsNav,Eg as AllOf,Ml as AnimatedThinkingDots,Dg as AnyOf,ep as ApiKeyAvatar,Oo as AskUserWidget,zg as AudioPanel,xv as BrowseCollectionView,ub as ChangeTypeAction,cb as ChangeTypeActionComponent,Cv as CollectionIcon,mp as CollectionsFacetsNav,kv as CollectionsTable,Uo as ConfirmationWidget,Jh as ContentDispositionButton,Dv as ContentObjectTypesSearch,Sv as ContentObjectTypesTable,Zg as ContentOverview,wv as CreateCollectionForm,Nv as CreateCollectionModal,Tv as CreateOrUpdateTypeModal,fb as DeleteObjectsAction,pb as DeleteObjectsActionComponent,gb as DeleteObjectsFromCollectionsAction,zh as DocumentGridView,Th as DocumentIcon,Sh as DocumentIconSkeleton,Jv as DocumentInput,Kv as DocumentPreviewPanel,Rh as DocumentSearch,Hh as DocumentSearchProvider,fv as DocumentSearchResults,hv as DocumentSearchResultsWithDropZone,Bp as DocumentSelection,Gp as DocumentSelectionProvider,Bh as DocumentTable,_h as DocumentTableColumn,Ih as DocumentTableView,Oh as DocumentUploadModal,vp as DocumentsFacetsNav,Bv as EditCollectionView,bp as EnvironmentFacet,xb as ExportPropertiesAction,vb as ExportPropertiesComponent,Zv as ExportPropertiesModal,Yv as ExportTypes,Lh as FileUploadAction,$f as GenericPageNavHeader,_m as Header,Rg as ImagePanel,wp as InteractionsFacetsNav,Cu as JumpingDots,yc as MESSAGE_STYLES,kg as MagicPdfView,Au as McpConnectionsActionMenu,ju as McpConnectionsButton,Ru as McpConnectionsDialog,Pu as McpConnectionsInlineList,wc as MessageItem,Cf as MessagesContainer,xf as ModernAgentConversation,Lf as NotFoundView,Pg as OAuthProviderConnectButton,Ev as ObjectSchemaEditor,Iv as ObjectTypeSearch,zv as ObjectTypeSearchContext,Fv as ObjectTypeSearchProvider,jb as ObjectsActionContextProvider,If as PanelErrorBoundary,wm as PayloadBuilder,km as PayloadBuilderProvider,ym as PayloadBuilderStore,Nm as PayloadContext,Gf as PdfDocumentRenderer,Mf as PdfPageRenderer,Qf as PdfPageSlider,Hf as PdfThumbnailList,kp as ProcessDefinitionsFacetsNav,_p as ProcessRunsFacetsNav,Ip as PromptsFacetsNav,qg as PropertiesEditorModal,Ol as PulsatingCircle,Wl as PulsingMessageLoader,wi as RemoteMcpConnectionButton,Nb as RemoveFromCollectionAction,yb as RemoveFromCollectionActionComponent,Rf as RowErrorBoundary,jp as RunsFacetsNav,Vg as SaveVersionConfirmModal,jh as SearchContext,Ug as SecureButton,Wg as SecureSidebarItem,qv as SelectCollection,yv as SelectContentType,Lv as SelectContentTypeModal,Qh as SelectDocument,Hv as SelectDocumentModal,Ab as SelectionActions,Uf as SharedPdfProvider,Uv as SharedPropsEditor,Vf as SimplePdfPage,Ag as SimplePdfViewer,sf as SkillWidgetProvider,_b as StartWorkflowAction,kb as StartWorkflowComponent,Nc as StreamingMessage,Pp as StringFacet,Ap as StringListFacet,Wv as SyncMemberHeadsToggle,Mv as TableLayoutEditor,Bl as ThinkingBar,ql as ThinkingMessages,Ep as TypeFacet,ip as TypeRegistry,lp as TypeRegistryProvider,Ul as TypedDots,Eb as UploadObjectsButton,Ob as UserAvatar,Qm as UserInfo,Og as UserPermissionProvider,Lg as UserPermissions,Fg as UserPermissionsContext,Rm as VInteractionFacet,Am as VStringFacet,pp as VTypeFacet,np as VUserFacet,ds as VegaLiteChart,_f as VertesiaErrorBoundary,jg as VideoPanel,Tg as WEB_SUPPORTED_AUDIO_FORMATS,_g as WEB_SUPPORTED_IMAGE_FORMATS,Sg as WEB_SUPPORTED_VIDEO_FORMATS,Vl as WavyThinking,Pf as WidgetErrorBoundary,Lp as WorkflowDefinitionsFacetsNav,Op as WorkflowExecutionsFacetsNav,Wp as WorkflowRulesFacetsNav,hs as clampPlaybackCursor,Iu as countConnectedActiveGroups,ap as createAgentRunnerFilterHandler,bs as createPlaybackState,Im as filterValueToQueryValue,Ig as formatDuration,zu as getConnectedActiveGroupLabels,vs as getNextUserTurnIndex,fs as getPlaybackCursorIndex,gs as getPreviousUserTurnIndex,fh as getWorkflowStatusColor,gh as getWorkflowStatusName,xs as isAgentChatPlaybackAvailable,ys as isAgentChatPlaybackEnabled,$g as isAnyOf,rh as isCsv,Su as isGroupDisabled,ah as isImage,ws as isLocalhostAgentChatPlaybackAvailable,Ns as isLocalhostAgentChatPlaybackEnabled,sh as isPdf,oh as isPreviewableAsPdf,ms as isRechartsSpec,us as isVegaLiteSpec,ih as isVideo,lh as printElementToPdf,mh as retrieveRendition,Tf as setErrorBoundaryComponent,zm as setSearchQueryValue,ph as shortId,hh as shortenString,Ov as stringifyTableLayout,Tu as toggleGroupDisabled,Tm as unwrapFilterOptionValue,rp as useAgentRunnerFilterGroups,dp as useCollectionsFilterGroups,up as useCollectionsFilterHandler,fp as useDocumentFilterGroups,gp as useDocumentFilterHandler,Ph as useDocumentSearch,Eh as useDocumentSearchCount,qp as useDocumentSelection,Uh as useDocumentUploadHandler,lc as useDownloadFile,Um as useFetchApiKeyInfo,Om as useFetchGroupInfo,Mm as useFetchUserInfo,xp as useInteractionsFilterGroups,yp as useInteractionsFilterHandler,_u as useMcpConnections,yi as useOAuthPopup,Hp as useOptionalDocumentSelection,Cm as usePayloadBuilder,Np as useProcessDefinitionsFilterGroups,Cp as useProcessRunsFilterGroups,Sp as usePromptsFilterGroups,Tp as usePromptsFilterHandler,zp as useRunsFilterGroups,Rp as useRunsFilterHandler,Rv as useSearch,Pv as useSearchCount,Wf as useSharedPdf,Mh as useSmartFileUploadProcessing,cp as useTypeRegistry,Mg as useUserPermissions,Ah as useWatchDocumentSearchFacets,Dh as useWatchDocumentSearchResult,jv as useWatchSearchResult,$p as useWorkflowDefinitionsFilterGroups,Fp as useWorkflowExecutionsFilterGroups,Mp as useWorkflowExecutionsFilterHandler,Up as useWorkflowRulesFilterGroups};
|
|
1
|
+
import{jsx as e,jsxs as t,Fragment as n}from"react/jsx-runtime";import{Button as r,DropdownMenu as a,DropdownMenuTrigger as s,cn as i,DropdownMenuContent as o,DropdownMenuRadioGroup as l,DropdownMenuRadioItem as c,Input as d,Slider as u,onActivateKey as m,useToast as p,VTooltip as h,Badge as f,Dropdown as g,MenuItem as v,DropdownMenuItem as b,ErrorBox as x,Center as y,Tabs as w,TabsPanel as N,MenuGroup as k,Avatar as _,Table as C,useFetch as S,errorMessage as T,Popover as I,PopoverTrigger as z,PopoverContent as R,FilterProvider as j,FilterBtn as P,FilterBar as A,FilterClear as D,useIsInModal as E,SelectBox as $,InputList as L,CopyButton as M,Card as F,Separator as O,CardContent as U,THead as W,TBody as B,SharedState as V,useWatchSharedState as q,Modal as H,ModalTitle as G,ModalBody as J,Spinner as K,MessageBox as Y,ModalFooter as Q,useIntersectionObserver as Z,Textarea as X,insertNewlineAtCursor as ee,Breadcrumbs as te,ResizablePanelGroup as ne,ResizablePanel as re,ResizableHandle as ae,RadioGroup as se,FormItem as ie,RadioGroupAdapter as oe,useTheme as le,Portal as ce,Checkbox as de,Label as ue,NumberInput as me,SidePanel as pe,Divider as he,Switch as fe,TR as ge,EmptyCollection as ve,ConfirmModal as be,useDebounce as xe,Panel as ye,TagsInput as we,Styles as Ne,Command as ke,CommandInput as _e,CommandEmpty as Ce,CommandGroup as Se,CommandItem as Te,useFlag as Ie,DialogDescription as ze,Heading as Re,TabsBar as je,SelectList as Pe}from"@vertesia/ui/core";import Ae,{clsx as De}from"clsx";import{AnimatePresence as Ee,motion as $e}from"motion/react";import*as Le from"react";import Me,{useMemo as Fe,useState as Oe,createContext as Ue,useContext as We,useRef as Be,useCallback as Ve,memo as qe,useEffect as He,forwardRef as Ge,useId as Je,useLayoutEffect as Ke,Component as Ye,useSyncExternalStore as Qe}from"react";import{useUITranslation as Ze,i18nInstance as Xe,NAMESPACE as et}from"@vertesia/ui/i18n";import{HandIcon as tt,ShieldCheckIcon as nt,ShieldAlertIcon as rt,ChevronDownIcon as at,Loader2 as st,Check as it,Copy as ot,Download as lt,Minimize2 as ct,Maximize2 as dt,X as ut,ChevronsLeft as mt,ChevronLeft as pt,ChevronRight as ht,ChevronsRight as ft,Radio as gt,CopyIcon as vt,Search as bt,CheckCircle2 as xt,Unlink2 as yt,Link2 as wt,Code as Nt,FileText as kt,Table as _t,Link as Ct,Image as St,MessageSquare as Tt,GitBranch as It,BarChart3 as zt,CheckCircle as Rt,AlertCircle as jt,HelpCircle as Pt,Send as At,XCircle as Dt,XIcon as Et,ExternalLink as $t,ImageIcon as Lt,FileTextIcon as Mt,ChevronDown as Ft,Layers as Ot,CheckCheck as Ut,Clock as Wt,Bot as Bt,RefreshCcw as Vt,Info as qt,User as Ht,AlertTriangle as Gt,ArrowLeft as Jt,Terminal as Kt,Wrench as Yt,Brain as Qt,Pencil as Zt,DownloadCloudIcon as Xt,Pause as en,Play as tn,Link2Off as nn,PackageIcon as rn,Loader2Icon as an,RefreshCwIcon as sn,ChevronRightIcon as on,FolderOpenIcon as ln,FolderIcon as cn,FileIcon as dn,MonitorIcon as un,ExternalLinkIcon as mn,ClipboardList as pn,Circle as hn,LayoutListIcon as fn,ClipboardCopyIcon as gn,XCircleIcon as vn,CheckCircleIcon as bn,Rows3 as xn,MessageSquareText as yn,Rewind as wn,InfoIcon as Nn,GitFork as kn,MoreVertical as _n,Users2 as Cn,Users as Sn,RefreshCw as Tn,Filter as In,Eye as zn,CheckIcon as Rn,UploadIcon as jn,AlertCircleIcon as Pn,TableProperties as An,LayoutGrid as Dn,PaperclipIcon as En,PlusIcon as $n,Activity as Ln,SquareIcon as Mn,ArrowUpIcon as Fn,Cpu as On,ChevronsUp as Un,ChevronsDown as Wn,Minus as Bn,Plus as Vn,Maximize as qn,ScanSearch as Hn,SquarePen as Gn,FileSearch as Jn,Settings as Kn,FolderClosed as Yn,Trash2 as Qn,ChevronsUpDown as Zn,EllipsisVertical as Xn}from"lucide-react";import*as er from"@radix-ui/react-dialog";import{useUserSession as tr,UserSessionContext as nr}from"@vertesia/ui/session";import rr from"papaparse";import{VegaEmbed as ar}from"react-vega";import{twMerge as sr}from"tailwind-merge";import{AgentMessageType as ir,MarkdownRenditionFormat as or,normalizeToolCollection as lr,FileProcessingStatus as cr,AgentSearchScope as dr,mergeInCodePromptSchemas as ur,supportsToolUse as mr,InteractionStatus as pr,PrincipalType as hr,ImageRenditionFormat as fr,WorkflowExecutionStatus as gr,normalizeAgentToolApprovalMode as vr,PDF_RENDITION_NAME as br,AUDIO_RENDITION_NAME as xr,ContentNature as yr,POSTER_RENDITION_NAME as wr,ContentObjectStatus as Nr,Permission as kr,SearchTypes as _r,SupportedEmbeddingTypes as Cr,getContentTypeRefId as Sr,SecurityLevelLabels as Tr}from"@vertesia/common";import"react-dom";import{Slot as Ir}from"@radix-ui/react-slot";import{cva as zr}from"class-variance-authority";import*as Rr from"@radix-ui/react-tooltip";import"@vertesia/ui/env";import"framer-motion";import*as jr from"@radix-ui/react-checkbox";import"@radix-ui/react-collapsible";import{Command as Pr}from"cmdk";import*as Ar from"@radix-ui/react-dropdown-menu";import Dr from"dayjs";import"react-calendar";import*as Er from"@radix-ui/react-popover";import{capitalize as $r}from"lodash-es";import*as Lr from"@radix-ui/react-label";import"@radix-ui/react-radio-group";import"react-resizable-panels";import*as Mr from"@radix-ui/react-separator";import*as Fr from"@radix-ui/react-slider";import*as Or from"@radix-ui/react-switch";import*as Ur from"@radix-ui/react-tabs";import Wr,{defaultUrlTransform as Br}from"react-markdown";import Vr from"rehype-katex";import{remarkDefinitionList as qr,defListHastHandlers as Hr}from"remark-definition-list";import Gr from"remark-directive";import Jr from"remark-gfm";import Kr from"remark-github-blockquote-alert";import Yr from"remark-math";import Qr from"remark-supersub";import{visit as Zr,SKIP as Xr}from"unist-util-visit";import{FusionFragmentProvider as ea,FusionFragmentHandler as ta}from"@vertesia/fusion-ux";import na from"dompurify";import ra from"mermaid";import{useRouterContext as aa,NavLink as sa,useNavigate as ia}from"@vertesia/ui/router";import{MarkdownRenderer as oa,DropZone as la,UploadSummary as ca,useCodeBlockContext as da,isIncompleteJson as ua,CodeBlockPlaceholder as ma,CodeBlockErrorBoundary as pa,CodeBlockRendererProvider as ha,XMLViewer as fa,JSONCode as ga,MonacoEditor as va,JSONDisplay as ba,Progress as xa,useSchema as ya,SchemaEditor as wa,ManagedObject as Na,GeneratedForm as ka}from"@vertesia/ui/widgets";import _a,{Ajv as Ca}from"ajv";import Sa from"dayjs/plugin/localizedFormat";import Ta from"dayjs/plugin/relativeTime";import{Md5 as Ia}from"ts-md5";import{ErrorBoundary as za}from"react-error-boundary";import{pdfjs as Ra,Document as ja,Page as Pa}from"react-pdf";import{SidebarItem as Aa}from"@vertesia/ui/layout";function Da({children:t,secondary:n=!1}){return e("span",{className:n?"bg-secondary text-primary":"text-foreground bg-muted",children:t})}function Ea(e){return e?"array"===e.name?Ea(e.innerType):e:void 0}function $a({property:n}){return t("div",{className:"flex items-center gap-x-2",children:[e("div",{className:"font-semibold text-gray-600",children:n.name}),n.optional&&e(Da,{children:"optional"}),e(Da,{children:n.type.value})]})}function La({activities:t}){return e("div",{className:"flex flex-col gap-y-4 divide-y divide-gray-200",children:t.map(t=>e(Fa,{activity:t},t.name))})}function Ma({code:n,children:r}){return t("div",{className:"flex gap-2 items-center border-b border-b-gray-200 mb-2",children:[e("div",{className:"text-lg font-medium text-gray-900 py-2 ",children:r}),n&&e("div",{children:e(Da,{children:n})})]})}function Fa({activity:n,headingClass:r,headingRef:a}){return t("div",{className:r,id:n.name,ref:a,children:[e("div",{className:"text-xl font-semibold pt-8",children:n.title}),e("div",{className:"pb-4",children:e(Da,{children:n.name})}),n.doc&&e("div",{className:"text-gray-700 pb-2",children:n.doc}),t("div",{className:"pb-4",children:[e(Ma,{code:n.paramsType,children:"Parameters"}),e("div",{className:"divide-y divide-gray-100",children:n.params.map(t=>e(Oa,{property:t},t.name))})]}),t("div",{className:"pb-4",children:[e(Ma,{children:"Returns"}),e("div",{children:n.returnType?n.returnType.value:"void"})]})]})}function Oa({property:n,className:r}){const a=Fe(()=>{const t=Ea(n.type.innerType)??n.type;return"object"===t.name&&t.members?e(Wa,{members:t.members}):"enum"===t.name&&t.enum?e(Ua,{values:t.enum}):null},[n.type]);return t("div",{className:Ae("py-2",r),children:[e($a,{property:n}),n.doc&&e("div",{className:"text-gray-700 text-sm pt-2",children:n.doc}),a&&e("div",{className:"my-2 overflow-hidden",children:a})]})}function Ua({values:t}){return e("div",{className:"flex flex-wrap items-center gap-2",children:t.map(t=>e(Da,{secondary:!0,children:t},t))})}function Wa({members:n}){return e(Va,{className:"rounded-md border border-gray-200",button:n=>t("div",{className:"px-4 py-2 flex items-center gap-x-2 text-sm font-medium hover:text-blue-600",children:[e(qa,{isOpen:n}),e("div",n?{children:"Hide child properties"}:{children:"Show child properties"})]}),body:e(Ba,{properties:n})})}function Ba({properties:t}){return e("div",{className:"border-s-2 border-s-blue-200 flex flex-col divide-y divide-gray-100 border-t border-t-gray-200",children:t.map(t=>e(Oa,{property:t,className:"px-4 py-2"},t.name))})}function Va({button:n,body:a,className:s,isInitiallyOpen:i}){const[o,l]=Oe(i||!1);return t("div",{className:Ae(o?"block":"inline-block",s),children:[e(r,{variant:"unstyled",className:"p-0 m-0 bg-transparent",onClick:()=>l(!o),children:e(Ee,{children:n(o)})}),e(Ee,{children:o&&e($e.div,{className:"overflow-hidden",initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.3,ease:"easeOut"},children:a})})]})}function qa({isOpen:t}){return e(Ee,{propagate:!0,mode:"wait",children:e($e.div,{className:"font-mono font-semibold text-gray-400 text-lg",initial:{rotate:0},animate:{rotate:t?45:0},transition:{duration:.2},children:"+"},"closeIcon")})}function Ha(e){return"full_control"===e?"text-attention":"auto_review"===e?"text-info":"text-muted"}function Ga(t){return e("full_control"===t?rt:"ask"===t?tt:nt,{className:"size-4"})}function Ja({mode:n,onChange:d,disabled:u=!1,className:m}){const{t:p}=Ze(),h=Fe(()=>[{mode:"ask",label:p("agent.approvalMode.ask"),description:p("agent.approvalMode.askDescription"),icon:e(tt,{className:"size-4"})},{mode:"auto_review",label:p("agent.approvalMode.autoReview"),description:p("agent.approvalMode.autoReviewDescription"),icon:e(nt,{className:"size-4"})},{mode:"full_control",label:p("agent.approvalMode.fullControl"),description:p("agent.approvalMode.fullControlDescription"),icon:e(rt,{className:"size-4"})}],[p]),f=h.find(e=>e.mode===n)??h[2];return t(a,{children:[e(s,{asChild:!0,children:t(r,{type:"button",variant:"ghost",size:"sm",disabled:u,className:i("h-8 max-w-[13rem] rounded-full px-2.5 font-medium","bg-mixer-muted/15 text-muted hover:bg-muted hover:text-foreground disabled:opacity-60",m),"aria-label":p("agent.approvalMode.selectorLabel"),children:[e("span",{className:i("shrink-0",Ha(n)),children:Ga(n)}),e("span",{className:"min-w-0 truncate",children:f.label}),e(at,{className:"size-4 shrink-0 opacity-70"})]})}),t(o,{align:"start",className:"z-[1000000] w-[min(28rem,calc(100vw-1rem))] p-2",children:[e("div",{className:"px-2 pb-1.5 pt-1 text-sm font-medium text-foreground",children:p("agent.approvalMode.dropdownTitle")}),e(l,{value:n,onValueChange:e=>{var t;(t=e)!==n&&d(t)},children:h.map(n=>t(c,{value:n.mode,className:"min-h-14 items-start gap-3 rounded-md py-2 pe-8 ps-2 text-start",children:[e("span",{className:i("mt-0.5 shrink-0",Ha(n.mode)),children:n.icon}),t("span",{className:"min-w-0 flex-1",children:[e("span",{className:"block text-sm font-medium text-foreground",children:n.label}),e("span",{className:"mt-0.5 block whitespace-normal text-sm leading-5 text-muted",children:n.description})]})]},n.mode))})]})]})}function Ka(...e){return sr(De(e))}const Ya=Ue(null);function Qa({children:t}){const n=Be(new Map),r=Be(new Map),a=Ve(e=>n.current.get(e),[]),s=Ve((e,t)=>{n.current.set(e,t)},[]),i=Ve(async(e,t)=>{const a=n.current.get(e);if(a)return a;const s=r.current.get(e);if(s)return s;const i=t().then(t=>(n.current.set(e,t),r.current.delete(e),t)).catch(t=>{throw r.current.delete(e),t});return r.current.set(e,i),i},[]),o=Me.useMemo(()=>({getUrl:a,setUrl:s,getOrFetch:i}),[a,s,i]);return e(Ya.Provider,{value:o,children:t})}function Za(){return We(Ya)}function Xa(e){return e.startsWith("agents/")||e.startsWith("documents/")}function es(e,t,n="inline"){return`artifact:${e}:${t}:${n}`}function ts(e){return`file:${e}`}function ns({error:n,chartTitle:r}){return e("div",{className:"flex items-center justify-center h-full bg-red-50 dark:bg-red-950 rounded-md p-4",children:t("div",{className:"text-center",children:[t("p",{className:"text-sm font-medium text-red-600 dark:text-red-400",children:["Cannot render ",r||"Vega-Lite"," chart"]}),e("p",{className:"text-xs text-red-500 dark:text-red-500 mt-1 max-w-xs truncate",children:n})]})})}function rs({isOpen:n,onClose:a,title:s,description:i,children:o}){const{t:l}=Ze();return e(er.Root,{open:n,onOpenChange:e=>!e&&a(),children:t(er.Portal,{children:[e(er.Overlay,{className:"fixed inset-0 z-50 bg-black/80 backdrop-blur-sm transition-all duration-300 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0"}),t(er.Content,{className:"fixed inset-2 sm:inset-4 z-50 flex flex-col bg-white dark:bg-gray-900 rounded-xl shadow-2xl transition-all duration-300 ease-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-98 data-[state=open]:zoom-in-98 data-[state=closed]:slide-out-to-bottom-2 data-[state=open]:slide-in-from-bottom-2",onEscapeKeyDown:a,children:[e(er.Close,{asChild:!0,children:e(r,{variant:"unstyled",onClick:a,className:"absolute top-3 end-3 z-10 p-2 rounded-lg bg-white/80 dark:bg-gray-800/80 backdrop-blur-sm hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors duration-150 shadow-sm","aria-label":l("agent.closeFullscreen"),children:e(ut,{className:"w-5 h-5 text-gray-600 dark:text-gray-300"})})}),e("div",{className:"flex-1 overflow-auto p-4 sm:p-6 animate-in fade-in-0 duration-500 delay-150",children:o}),e("div",{className:"flex items-center justify-between px-4 sm:px-6 py-3 border-t border-gray-200 dark:border-gray-800 bg-gray-50/50 dark:bg-gray-800/50 rounded-b-xl",children:t("div",{className:"flex flex-col",children:[e(er.Title,{className:"text-base font-semibold text-gray-900 dark:text-gray-100",children:s||l("agent.dashboard")}),i&&e(er.Description,{className:"text-sm text-gray-500 dark:text-gray-400 mt-0.5",children:i})]})})]})]})})}const as={categorical:["#6366f1","#8b5cf6","#ec4899","#f43f5e","#f97316","#eab308","#22c55e","#14b8a6","#06b6d4","#3b82f6"],blues:["#dbeafe","#93c5fd","#3b82f6","#1d4ed8","#1e3a8a"],purples:["#f3e8ff","#c4b5fd","#8b5cf6","#6d28d9","#4c1d95"],diverging:["#ef4444","#fca5a5","#fef3c7","#86efac","#22c55e"]};function ss(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function is(e){return ss(e)}function os(e,t){if(!e?.encoding)return!1;for(const n of t)for(const t of Object.values(e.encoding))if(t.field===n)return!0;if(Array.isArray(e.layer))for(const n of e.layer)if(os(n,t))return!0;return!1}function ls(e,t){if(!e)return!1;const n=e=>{if(!e)return!1;const n=e.color?.field;return!!n&&t.includes(n)};if(n(e.encoding))return!0;if(Array.isArray(e.layer))for(const t of e.layer)if(n(t.encoding))return!0;return!1}function cs(e,t=[]){const n=[];if(!e||"object"!=typeof e)return n;if(e.data&&"object"==typeof e.data){const r=e.data.url;"string"==typeof r&&r.startsWith("artifact:")&&n.push({path:[...t,"data"],artifactPath:r.replace(/^artifact:/,"").trim()})}const r=["layer","vconcat","hconcat","concat","spec","repeat","facet"];for(const a of r)if(a in e){const r=e[a];Array.isArray(r)?r.forEach((e,r)=>{is(e)&&n.push(...cs(e,[...t,a,String(r)]))}):is(r)&&n.push(...cs(r,[...t,a]))}return n}const ds=qe(function({spec:a,artifactRunId:s}){const{t:i}=Ze(),{title:o,description:l,options:c}=a,d=a.spec,[u,m]=Oe(!1),[p,h]=Oe(!1),[f,g]=Oe(null),[v,b]=Oe(!1),x=Be(null),y=Be(null),w=Be(null),{client:N}=tr(),k=Za(),_=Be(N);_.current=N;const C=Be(k);C.current=k;const[S,T]=Oe(null),[I,z]=Oe(!1),[R,j]=Oe(null),P=c?.mode||"chart",A="dashboard"===P,D=c?.enableFullscreen??A,E=c?.height||function(e,t){if("chart"===t)return 280;let n=1;if(e.vconcat)n=Array.isArray(e.vconcat)?e.vconcat.length:1;else if(e.concat){const t=e.columns||2,r=Array.isArray(e.concat)?e.concat.length:1;n=Math.ceil(r/t)}else e.facet&&(n=2);return Math.max(500,280*n+40)}(d,P);He(()=>{const e=cs(d);if(0===e.length)return T(d),z(!1),void j(null);s?console.info("[VegaLiteChart] resolving artifacts with runId:",s,e.map(e=>e.artifactPath)):console.warn("[VegaLiteChart] artifact references found but artifactRunId is missing!",{references:e.map(e=>e.artifactPath),artifactRunId:s});let t=!1;z(!0),j(null);return(async()=>{const n=new Map,r=_.current,a=C.current;for(const i of e)try{const e=i.path.join(".");let t;if(s&&!Xa(i.artifactPath)){const e=es(s,i.artifactPath,"inline");if(a)t=await a.getOrFetch(e,async()=>(await r.files.getArtifactDownloadUrl(s,i.artifactPath,"inline")).url);else{t=(await r.files.getArtifactDownloadUrl(s,i.artifactPath,"inline")).url}}else{const e=ts(i.artifactPath);if(a)t=await a.getOrFetch(e,async()=>(await r.files.getDownloadUrl(i.artifactPath)).url);else{t=(await r.files.getDownloadUrl(i.artifactPath)).url}}const o=await fetch(t);if(!o.ok)throw new Error(`Failed to fetch artifact data: ${o.statusText}`);let l;if(i.artifactPath.toLowerCase().endsWith(".csv")){const e=await o.text();l=rr.parse(e,{header:!0,skipEmptyLines:!0,dynamicTyping:!0}).data}else{const e=await o.json();l=Array.isArray(e)?e:[e]}n.set(e,l)}catch(e){return console.error(`Failed to resolve artifact: ${i.artifactPath}`,e),void(t||j(`Failed to load data from artifact: ${i.artifactPath}`))}if(!t){const e=function(e,t){const n=JSON.parse(JSON.stringify(e));for(const[e,r]of t){const t=e.split(".");let a=n;for(let e=0;e<t.length-1;e++){const n=a[t[e]];if(!ss(n))break;a=n}const s=a[t[t.length-1]];ss(s)&&(delete s.url,s.values=r)}return n}(d,n);T(e),z(!1)}})(),()=>{t=!0}},[d,s]);const[$,L]=Oe(!1),M=Be(!1);He(()=>{const e=()=>{const e=document.documentElement.classList.contains("dark");e!==M.current&&(M.current=e,L(e))};e();const t=new MutationObserver(e);return t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),()=>t.disconnect()},[]);const[F,O]=Oe(0),U=Be(0);He(()=>{if(!w.current)return;let e;const t=new ResizeObserver(t=>{clearTimeout(e),e=setTimeout(()=>{const e=t[0]?.contentRect.width;e&&e!==U.current&&(U.current=e,O(e))},100)});t.observe(w.current);const n=w.current.clientWidth;return U.current=n,O(n),()=>{clearTimeout(e),t.disconnect()}},[]);const W=Fe(()=>cs(d).length>0,[d]),B=Fe(()=>{if(W&&!S)return null;let e=S||d;return e?(c?.parameterValues&&(e=function(e,t){if(!t||0===Object.keys(t).length)return e;const n=JSON.parse(JSON.stringify(e)),r=e=>{for(const n of e)n.name&&n.name in t&&(n.value=t[n.name])};Array.isArray(n.params)&&r(n.params);const a=e=>{if(Array.isArray(e))for(const t of e)if(Array.isArray(t.params)&&r(t.params),t.vconcat&&a(t.vconcat),t.hconcat&&a(t.hconcat),t.concat&&a(t.concat),Array.isArray(t.layer))for(const e of t.layer)Array.isArray(e.params)&&r(e.params)};if(n.vconcat&&a(n.vconcat),n.hconcat&&a(n.hconcat),n.concat&&a(n.concat),Array.isArray(n.layer))for(const e of n.layer)e&&Array.isArray(e.params)&&r(e.params);return n}(e,c.parameterValues)),function(e){const t=JSON.parse(JSON.stringify(e)),n=["vconcat","hconcat","concat"];if(!n.some(e=>Array.isArray(t[e])))return t;const r=[];if(Array.isArray(t.params))for(const e of t.params)e&&"object"==typeof e&&e.name&&e.select&&r.push({name:e.name,param:e});if(0===r.length)return t;for(const{name:e,param:a}of r){const r=a.select?.fields||[],s="legend"===a.select?.bind;let i=null;for(const e of n)if(Array.isArray(t[e])){i=t[e];break}if(!i||0===i.length)continue;let o=0;for(let e=0;e<i.length;e++){const t=i[e];if(os(t,r)||s&&ls(t,r)){o=e;break}}const l=i[o];l.params||(l.params=[]),l.params.push(a);const c=t.params??[];t.params=c.filter(t=>t.name!==e)}return Array.isArray(t.params)&&0===t.params.length&&delete t.params,t}(e)):null},[S,d,W,c?.parameterValues]),V=Ve((e,t)=>{if(!e||"object"!=typeof e)return e;if(e.hconcat&&Array.isArray(e.hconcat)){const n=e.hconcat.length,r=(e.spacing??10)*(n-1),a=Math.floor((t-r)/n);return{...e,hconcat:e.hconcat.map(e=>V(e,a))}}if(e.vconcat&&Array.isArray(e.vconcat))return{...e,vconcat:e.vconcat.map(e=>V(e,t))};if(e.concat&&Array.isArray(e.concat)){const n=e.columns??e.concat.length,r=(e.spacing??10)*(n-1),a=Math.floor((t-r)/n);return{...e,concat:e.concat.map(e=>V(e,a))}}const n=e.width;return"container"===n||"number"==typeof n&&n>t?{...e,width:t}:e},[]),q=Ve((e,t=!1)=>{if(!B)return null;const n=function(e){const t={background:"transparent",view:{stroke:"transparent"},range:{category:as.categorical,diverging:as.diverging,heatmap:as.purples,ramp:as.blues},mark:{tooltip:!0},bar:{tooltip:!0,cornerRadiusTopLeft:4,cornerRadiusTopRight:4},line:{tooltip:!0,strokeWidth:2.5,strokeCap:"round"},point:{tooltip:!0,size:60,filled:!0},area:{tooltip:!0,fillOpacity:.7,line:!0},rect:{tooltip:!0,cornerRadius:2},arc:{tooltip:!0,cornerRadius:4},circle:{tooltip:!0,size:80}};return e?{...t,axis:{labelColor:"#a1a1aa",titleColor:"#e4e4e7",gridColor:"#3f3f46",domainColor:"#52525b",tickColor:"#52525b",labelFont:"Inter, system-ui, sans-serif",titleFont:"Inter, system-ui, sans-serif",labelFontSize:11,titleFontSize:12,titleFontWeight:500},legend:{labelColor:"#a1a1aa",titleColor:"#e4e4e7",labelFont:"Inter, system-ui, sans-serif",titleFont:"Inter, system-ui, sans-serif",labelFontSize:11,titleFontSize:12,symbolSize:100},title:{color:"#fafafa",font:"Inter, system-ui, sans-serif",fontSize:14,fontWeight:600}}:{...t,axis:{labelColor:"#71717a",titleColor:"#3f3f46",gridColor:"#e4e4e7",domainColor:"#d4d4d8",tickColor:"#d4d4d8",labelFont:"Inter, system-ui, sans-serif",titleFont:"Inter, system-ui, sans-serif",labelFontSize:11,titleFontSize:12,titleFontWeight:500},legend:{labelColor:"#71717a",titleColor:"#3f3f46",labelFont:"Inter, system-ui, sans-serif",titleFont:"Inter, system-ui, sans-serif",labelFontSize:11,titleFontSize:12,symbolSize:100},title:{color:"#18181b",font:"Inter, system-ui, sans-serif",fontSize:14,fontWeight:600}}}($),r=t?"undefined"!=typeof window?Math.min(window.innerWidth-80,1400):1200:F>0?F-24:500,a="vconcat"in B||"hconcat"in B||"concat"in B,s=a?{type:"pad",contains:"padding"}:{type:"fit",contains:"padding"};let i=B;a&&r&&(i=V(B,r));const l=i.width,c=a?void 0:"container"===l?r:l??r,{width:d,...u}=i;return{$schema:"https://vega.github.io/schema/vega-lite/v6.json",...!a&&c?{width:c}:{},height:t?void 0:e,autosize:s,...a?i:u,...o&&!B.title?{title:o}:{},config:{...n,...B.config}}},[B,o,$,F,V]),H=Ve(async()=>{const e=v?y.current:x.current;if(e&&!p)try{(await e.toCanvas(2)).toBlob(async e=>{e&&(await navigator.clipboard.write([new ClipboardItem({"image/png":e})]),h(!0),setTimeout(()=>h(!1),2e3))},"image/png")}catch(e){console.error("Failed to copy chart:",e)}},[p,v]),G=Ve(async()=>{const e=v?y.current:x.current;if(e&&!u){m(!0);try{const t=await e.toImageURL("png",2),n=document.createElement("a");n.download=`${o||"chart"}.png`,n.href=t,n.click()}catch(e){console.error("Failed to export chart:",e)}finally{m(!1)}}},[o,u,v]),J=Ve(e=>{x.current=e,g(null)},[]),K=Ve(e=>{y.current=e},[]),Y=Ve(e=>{console.error("Vega-Lite rendering error:",e),g(e instanceof Error?e.message:"Unknown error")},[]),Q=Ve(()=>{b(e=>!e)},[]);He(()=>{g(null)},[d]);const Z=({className:n})=>t("div",{className:Ka("flex items-center gap-2",n),children:[t(r,{variant:"unstyled",onClick:H,disabled:p,className:"text-xs px-2 py-1 rounded border border-gray-300 dark:border-gray-700 bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700 cursor-pointer transition-colors disabled:opacity-50 flex items-center gap-1",title:i("agent.copyToClipboard"),children:[e(p?it:ot,{className:"w-3 h-3"}),i(p?"agent.copied":"agent.copy")]}),t(r,{variant:"unstyled",onClick:G,disabled:u,className:"text-xs px-2 py-1 rounded border border-gray-300 dark:border-gray-700 bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700 cursor-pointer transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1",title:i("agent.exportAsPng"),children:[e(lt,{className:"w-3 h-3"}),i(u?"agent.exporting":"agent.export")]}),D&&t(r,{variant:"unstyled",onClick:Q,className:"text-xs px-2 py-1 rounded border border-gray-300 dark:border-gray-700 bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700 cursor-pointer transition-colors flex items-center gap-1",title:i(v?"agent.exitFullscreen":"agent.fullscreen"),children:[e(v?ct:dt,{className:"w-3 h-3"}),i(v?"agent.exit":"agent.fullscreen")]})]});if(I||W&&!S)return e("div",{className:"bg-white dark:bg-gray-900 rounded-lg border border-gray-200 dark:border-gray-800 shadow-sm",children:t("div",{className:"flex flex-col gap-2 p-3",children:[e("div",{className:"flex items-center justify-between",children:e("span",{className:"font-medium text-sm text-gray-900 dark:text-gray-100",children:o||"Chart"})}),e("div",{className:"flex items-center justify-center bg-gray-50 dark:bg-gray-800 rounded",style:{width:"100%",height:E},children:t("div",{className:"flex items-center gap-2 text-gray-500 dark:text-gray-400",children:[e(st,{className:"w-5 h-5 animate-spin"}),e("span",{className:"text-sm",children:"Loading data from artifacts..."})]})})]})});if(R)return e("div",{className:"bg-white dark:bg-gray-900 rounded-lg border border-gray-200 dark:border-gray-800 shadow-sm",children:t("div",{className:"flex flex-col gap-2 p-3",children:[e("div",{className:"flex items-center justify-between",children:e("span",{className:"font-medium text-sm text-gray-900 dark:text-gray-100",children:o||"Chart"})}),e("div",{style:{width:"100%",height:E},children:e(ns,{error:R,chartTitle:o})})]})});if(f)return e("div",{className:"bg-white dark:bg-gray-900 rounded-lg border border-gray-200 dark:border-gray-800 shadow-sm",children:t("div",{className:"flex flex-col gap-2 p-3",children:[e("div",{className:"flex items-center justify-between",children:e("span",{className:"font-medium text-sm text-gray-900 dark:text-gray-100",children:o||"Chart"})}),e("div",{style:{width:"100%",height:E},children:e(ns,{error:f,chartTitle:o})})]})});const X=q(E),ee=q(0,!0);return X?("undefined"!=typeof window&&localStorage.getItem("DEBUG_VEGA_RENDERS")&&console.log("VegaLite rendering with spec:",{title:o,hasData:!!X.data?.values,dataLength:X.data?.values?.length}),t(n,{children:[e("div",{className:Ka("bg-white dark:bg-gray-900 rounded-lg border border-gray-200 dark:border-gray-800 shadow-sm",A&&"border-2"),children:t("div",{className:"flex flex-col gap-2 p-3",children:[t("div",{className:"flex items-center justify-between",children:[t("div",{className:"flex items-center gap-2",children:[e("span",{className:"font-medium text-sm text-gray-900 dark:text-gray-100",children:o||(A?"Dashboard":"Chart")}),A&&e("span",{className:"text-xs px-2 py-0.5 rounded-full bg-indigo-100 dark:bg-indigo-900 text-indigo-700 dark:text-indigo-300",children:"Interactive"})]}),e(Z,{})]}),l&&e("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:l}),e("div",{ref:w,className:"bg-white dark:bg-gray-900 rounded overflow-hidden",style:{width:"100%",height:E,minWidth:0},children:e(ar,{spec:X,onEmbed:e=>J(e.view),onError:Y,options:{renderer:c?.renderer||"canvas",actions:!1}})})]})}),t(rs,{isOpen:v,onClose:()=>b(!1),title:o||(A?"Dashboard":"Chart"),description:l,children:[e("div",{className:"w-full h-full min-h-[calc(100vh-200px)]",children:ee&&e(ar,{spec:ee,onEmbed:e=>K(e.view),onError:Y,options:{renderer:c?.renderer||"canvas",actions:!1}})}),e("div",{className:"absolute bottom-6 end-6",children:e(Z,{className:"bg-white dark:bg-gray-800 rounded-lg shadow-lg p-2 border border-gray-200 dark:border-gray-700"})})]})]})):null},(e,t)=>JSON.stringify(e.spec)===JSON.stringify(t.spec)&&e.artifactRunId===t.artifactRunId);function us(e){return"vega-lite"===e.library&&"object"==typeof e.spec}function ms(e){return"recharts"===e.library||void 0===e.library}const ps=qe(function({spec:n,artifactRunId:r}){return us(n)?e(ds,{spec:n,artifactRunId:r}):function(e){return"string"==typeof e.$schema&&e.$schema.includes("vega")}(n)?e(ds,{spec:{library:"vega-lite",spec:n},artifactRunId:r}):t("div",{className:"my-5 rounded-lg border border-amber-200 bg-amber-50 p-4 text-sm text-amber-900 dark:border-amber-900 dark:bg-amber-950 dark:text-amber-200",children:["Recharts chart rendering has been retired. Use a Vega-Lite chart spec (",e("code",{children:'library: "vega-lite"'})," with ",e("code",{children:"spec"}),")."]})},(e,t)=>JSON.stringify(e.spec)===JSON.stringify(t.spec)&&e.artifactRunId===t.artifactRunId);function hs(e,t){return"live"===e?e:0===t?"live":Math.min(Math.max(e,0),t-1)}function fs(e,t){return 0===t?-1:"live"===e?t-1:Math.min(Math.max(e,0),t-1)}function gs(e,t){if(0===e.length)return null;const n="live"===t?e.length:fs(t,e.length);for(let t=Math.min(n-1,e.length-1);t>=0;t--)if(e[t].type===ir.QUESTION)return t;return null}function vs(e,t){if(0===e.length||"live"===t)return null;for(let n=fs(t,e.length)+1;n<e.length;n++)if(e[n].type===ir.QUESTION)return n;return"live"}function bs(e,t,n){const r=n?hs(t,e.length):"live",a=fs(r,e.length),s=!n||"live"===r,i=s?e:e.slice(0,a+1);return{cursor:r,cursorIndex:a,isLive:s,renderedMessageCount:i.length,displayedMessages:i}}function xs(){return"undefined"!=typeof window}function ys(){if(!xs())return!1;const e=new URLSearchParams(window.location.search),t=function(e){const t=e.indexOf("?");return-1===t?new URLSearchParams:new URLSearchParams(e.slice(t+1))}(window.location.hash),n=e.get("agentChatPlayback")??t.get("agentChatPlayback");return"1"===n||"true"===n}const ws=xs,Ns=ys;function ks({cursor:n,messages:a,onChangeCursor:s,className:o}){const{t:l}=Ze(),c=a.length,m="live"===n,p=fs(n,c),h=c>0&&(m||p>0),f=!m&&c>0,g=c>0&&(m||p>0),v=!m&&c>0&&p<c-1,b=0===c?0:p+1,[x,y]=Oe(String(b));He(()=>{y(String(b))},[b]);const w=(e,t=!1)=>{if(0===c)return void y("0");const n=Number.parseInt(e,10);if(!Number.isFinite(n))return void(t&&y(String(b)));const r=Math.min(Math.max(n,1),c);y(String(r)),s(r-1)},N=c>1,k=N?1:0,_=Math.max(1,c),C="size-7 rounded-lg text-muted hover:text-foreground disabled:opacity-35",S=`${Math.max(3,String(c).length+1)}ch`;return t("div",{className:i("inline-flex max-w-full flex-col gap-1 rounded-xl border border-border/70 bg-background/95 px-2 py-1 text-sm leading-none text-muted shadow-lg shadow-black/10 backdrop-blur",o),"data-testid":"agent-test-playback-controls","data-playback-cursor":n,"data-live-message-count":c,"data-rendered-message-count":m?c:p+1,children:[t("div",{className:"flex max-w-full items-center gap-1",children:[e("span",{className:"ms-2 me-1 font-medium leading-none text-foreground/80",children:l("agent.rewind.label")}),e(r,{type:"button",variant:"ghost",size:"icon",title:l("agent.rewind.jumpToStart"),disabled:!g,onClick:()=>{0!==c&&s(0)},className:C,children:e(mt,{className:"size-4"})}),e(r,{type:"button",variant:"ghost",size:"icon",title:l("agent.rewind.previousMessage"),disabled:!h,onClick:()=>{0!==c&&s("live"!==n?Math.max(0,p-1):c-1)},className:C,children:e(pt,{className:"size-4"})}),t("span",{className:"inline-flex min-w-16 items-center justify-center gap-0.5 px-1 font-medium leading-none tabular-nums text-foreground/80","data-testid":"agent-test-playback-position",children:[e(d,{type:"text",variant:"unstyled",size:"sm",clearable:!1,inputMode:"numeric",pattern:"[0-9]*",value:x,"aria-label":l("agent.rewind.positionInput"),disabled:0===c,onChange:e=>{const t=e.replace(/\D/g,"");y(t)},onBlur:e=>w(e.currentTarget.value,!0),onKeyDown:e=>{"Enter"===e.key&&(w(e.currentTarget.value,!0),e.currentTarget.blur())},style:{width:S},className:"h-7 w-auto rounded-md border border-transparent bg-transparent px-1 text-center text-sm font-medium leading-none tabular-nums text-foreground outline-none transition-colors hover:border-border focus:border-ring focus:bg-muted/30 disabled:opacity-50"}),e("span",{"aria-hidden":"true",className:"text-muted",children:"/"}),e("span",{className:"text-muted",children:c})]}),e(r,{type:"button",variant:"ghost",size:"icon",title:l("agent.rewind.nextMessage"),disabled:!f,onClick:()=>{0!==c&&"live"!==n&&s(p>=c-1?"live":p+1)},className:C,children:e(ht,{className:"size-4"})}),e(r,{type:"button",variant:"ghost",size:"icon",title:l("agent.rewind.jumpToLatest"),disabled:!v,onClick:()=>{0!==c&&s(c-1)},className:C,children:e(ft,{className:"size-4"})}),e(r,{type:"button",variant:m?"secondary":"ghost",size:"icon",title:l("agent.rewind.jumpToLive"),disabled:m,onClick:()=>s("live"),className:i(C,m&&"bg-muted text-foreground"),children:e(gt,{className:"size-4"})})]}),e("div",{className:"px-2 pb-1",children:e(u,{min:k,max:_,step:1,value:[b],"aria-label":l("agent.rewind.positionInput"),disabled:!N,onValueChange:([e])=>(e=>{0!==c&&w(e)})(String(e)),className:"h-2"})})]})}Ue(void 0);class _s{filter(e,t){const n=t.toLowerCase();return e.filter(e=>this.valueOf(e).toLowerCase().includes(n))}renderOption(e){return this.valueOf(e)}findById(e,t){return e.find(e=>this.idOf(e)===t)}createItem(e){return null}}class Cs extends _s{valueOf(e){return String(e)}idOf(e){return String(e)}static instance=new Cs}class Ss extends Cs{createItem(e){return e}static instance=new Ss}const Ts=Me.createContext(void 0);function Is(){return Me.useContext(Ts)}const zs=Rr.Provider,Rs=Rr.Root,js=Rr.Trigger,Ps=Le.forwardRef(({className:t,sideOffset:n=4,side:r="top",...a},s)=>{const i=Is();return e(Rr.Portal,{container:i,children:e(Rr.Content,{ref:s,sideOffset:n,side:r,style:{zIndex:100},className:Ka("max-w-[90vw]","z-50 overflow-hidden rounded-md bg-tooltips border border-border px-3 py-1.5 text-xs animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...a})})});function As({description:n,children:r,size:a="sm",placement:s="top",className:i,asChild:o}){const[l,c]=Le.useState(!1),d=Le.useRef(!1);return Le.useEffect(()=>{const e=()=>{c(!1),d.current=!0,requestAnimationFrame(()=>{d.current=!1})};return window.addEventListener("blur",e),document.addEventListener("visibilitychange",e),()=>{window.removeEventListener("blur",e),document.removeEventListener("visibilitychange",e)}},[]),e(zs,{delayDuration:0,children:t(Rs,{open:l,onOpenChange:e=>{d.current||c(e)},children:[e(js,{className:"cursor-pointer",asChild:o,children:r}),e(Ps,{side:s,className:`px-3 py-1.5 max-w-${a} text-${a} px-3 ${i}`,children:n})]})})}Ps.displayName=Rr.Content.displayName;const Ds=new Set;function Es(e,t,n){He(()=>{t&&!Ds.has(e)&&(Ds.add(e),console.warn(`[@vertesia/ui] ${e} is deprecated: ${n}`))},[t,n,e])}function $s(e){return Le.Children.toArray(e).some(e=>{if("string"==typeof e)return e.trim().length>0;if("number"==typeof e)return!0;if(Le.isValidElement(e)){const t=e.props;return!0!==t["aria-hidden"]&&"true"!==t["aria-hidden"]&&$s(t.children)}return!1})}const Ls=zr("hover:cursor-pointer inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{destructive:"bg-destructive dark:bg-destructive/10 text-destructive ring-1 ring-inset ring-destructive-muted/50 dark:ring-destructive-muted/50 shadow-xs hover:bg-destructive/50",outline:"border border-input bg-background shadow-xs hover:bg-muted ring-inset",secondary:"bg-primary/5 dark:bg-primary/10 text-primary shadow-xs hover:bg-primary/10 dark:hover:bg-primary/20 ring-inset",ghost:"hover:bg-muted/50 dark:hover:bg-muted/20 ring-inset",link:"text-foreground underline-offset-4 hover:underline ring-inset",primary:"bg-primary text-white shadow-xs hover:bg-primary/90 ring-inset",unstyled:""},size:{xs:"h-7 rounded px-2 py-1 text-xs gap-x-1",sm:"h-8 rounded px-3 text-xs",md:"h-9 rounded-md px-4 py-2",lg:"h-10 rounded-md px-3",xl:"rounded-md px-3.5 py-2.5 text-sm gap-x-2",icon:"p-0 m-0 rounded-full",none:""}},defaultVariants:{variant:"primary",size:"md"}}),Ms=Le.forwardRef(({className:r,variant:a,size:s,asChild:i=!1,alt:o,isDisabled:l,isLoading:c,title:d,tooltipPlacement:u="top",onClick:m,type:p,...h},f)=>{Es("Button.alt",void 0!==o,"use `title` instead — it drives the same tooltip and the accessible name. `alt` remains an alias for one release.");const g=i?Ir:"button",v=i?p:p??"button",b=d??o,x=h["aria-label"]??o??($s(h.children)?void 0:d),y=i?h.children:t(n,{children:[c&&e(st,{className:"animate-spin"}),h.children]}),w=e(g,{className:Ae(Ka(Ls({variant:a,size:s})),r),disabled:l||c||h.disabled,ref:f,onClick:m,type:v,autoFocus:!1,...h,"aria-label":x,children:y});return b?e(As,{description:b,asChild:!0,className:"cursor-pointer",size:"xs",placement:u,children:w}):w});Ms.displayName="Button";const Fs=Le.forwardRef(({size:t,content:n,toast:r,className:a,alt:s,"aria-label":i,...o},l)=>{const[c,d]=Oe(!1),{t:u}=Ze();Es("CopyButton.alt",void 0!==s,"use aria-label for the accessible name. `alt` is forwarded for one release.");const m=i??s??u("misc.copy");return e(Ms,{ref:l,className:Ka(a),variant:"unstyled",size:t||"sm",onClick:e=>{e.stopPropagation(),navigator.clipboard.writeText(n).then(()=>{d(!0),setTimeout(()=>d(!1),2e3),r?.toast&&r.toast({status:"success",title:r.message||u("misc.copiedToClipboard"),duration:2e3})}).catch(e=>{console.error("Failed to copy text: ",e),r?.toast&&r.toast({status:"error",title:u("misc.failedToCopy"),duration:2e3})})},...o,title:m,children:c?e(it,{className:"text-success"}):e(vt,{className:"size-4"})})});Fs.displayName="CopyButton";const Os=zr("inline-flex items-center rounded-md px-2 py-1 text-xs font-medium",{variants:{variant:{default:"text-foreground bg-muted",secondary:"bg-secondary text-primary",destructive:"bg-destructive text-destructive",attention:"bg-attention text-attention",success:"bg-success text-success",info:"bg-info text-info",done:"bg-done text-done"}},defaultVariants:{variant:"default"}});function Us({className:t,variant:n,children:r,onClick:a,...s}){const i=a?{role:"button",tabIndex:0,onClick:a,onKeyDown:(o=a,e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),o(e))})}:{};var o;return e("span",{className:Ka(Os({variant:n}),t),...i,...s,children:r})}zr("inline-flex items-center gap-x-1.5 rounded-md px-2 py-1 text-xs font-medium ring-1 ring-inset ring-border",{variants:{variant:{default:"",success:"",destructive:"",attention:"",done:"",info:""}},defaultVariants:{variant:"default"}}),zr("h-1.5 w-1.5",{variants:{variant:{default:"fill-foreground",success:"fill-success",destructive:"fill-destructive",attention:"fill-attention",done:"fill-done",info:"fill-info"}},defaultVariants:{variant:"default"}});const Ws=zr("",{variants:{size:{xs:"rounded py-1 text-xs rounded-xs",sm:"rounded text-xs rounded-sm",md:"rounded-md py-2 text-sm",lg:"rounded-md text-base",xl:"rounded-md py-2.5 text-lg"},variant:{default:"flex w-full rounded-md border border-input bg-background ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 ring-inset focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",unstyled:"block m-0 p-0 w-full border-0 focus:outline-hidden focus:ring-0 bg-transparent",noPadding:"block rounded-md border-0 bg-background shadow-2xs ring-1 ring-inset ring-ring placeholder:text-muted-foreground focus:ring-2 focus:ring-inset focus:ring-ring ring-offset-background",legacy:"py-1.5 block rounded-md border-0 bg-background shadow-2xs ring-1 ring-inset ring-ring placeholder:text-muted-foreground focus:ring-2 focus:ring-inset focus:ring-ring ring-offset-background"}},defaultVariants:{size:"md",variant:"default"}});Le.forwardRef(({className:n,type:r,size:a="md",variant:s="default",clearable:i=!0,onChange:o,value:l,invalid:c,...d},u)=>{const m=d["aria-invalid"]??(!!c||void 0);return t("div",{className:"w-full relative inline-block [&:hover_.clear-button]:opacity-100",children:[e("input",{type:r,className:Ka(Ws({size:a,variant:s}),n,i&&l?"pe-8":""),ref:u,value:null==l?"":l,onChange:e=>{o?.(e.target.value)},...d,"aria-invalid":m}),i&&l&&!d.readOnly&&!d.disabled&&e(Ms,{variant:"link",size:"icon",type:"button",onClick:()=>{o?.("")},className:"clear-button opacity-0 transition-opacity duration-200\n absolute top-1/2 -translate-y-1/2 text-muted !hover:text-destructive cursor-pointer\n flex items-center justify-center size-6 rounded end-2","aria-label":"Clear input",children:e(ut,{size:16})})]})}).displayName="Input",Ge(function(t,n){const{current:r,children:a,className:s,href:i="#",onClick:o,...l}=t;return e("li",{className:Ae(s,r?"bg-muted":"","w-full p-2 ps-3 text-sm leading-6 font-semibold hover:bg-muted"),children:e("a",{ref:n,href:i,onClick:e=>{o?(e.preventDefault(),o(e)):"#"===i&&e.preventDefault()},className:"w-full flex items-center gap-x-3",...l,children:a})})});const Bs={INPUT:"rounded-md text-sm flex w-full rounded-md border border-input bg-background ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 ring-inset focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 py-1.5"};function Vs(e){return null==e||Number.isNaN(e)?"":e.toString()}Me.forwardRef(({value:t,onChange:n,className:r,noScroll:a=!1,noSpinners:s=!1,...i},o)=>{const[l,c]=Me.useState(Vs(t));return He(()=>{if(null==t||!Number.isNaN(t)){const e=Vs(t);c(e)}},[t]),e("input",{onWheel:a?e=>{e.currentTarget.blur()}:i.onWheel,type:"number",value:l,onChange:e=>{const t=e.target.value;if(c(t),""===t)n?.(void 0,t);else{const e=parseFloat(t);n?.(e,t)}},className:Ae(r,Bs.INPUT,{"no-spinners":s},s&&"[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"),ref:o,...i})});Le.forwardRef(({...t},n)=>e("nav",{ref:n,"aria-label":"breadcrumb",...t})).displayName="Breadcrumb";Le.forwardRef(({className:t,...n},r)=>e("ol",{ref:r,className:Ka("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted sm:gap-2.5",t),...n})).displayName="BreadcrumbList";Le.forwardRef(({className:t,...n},r)=>e("li",{ref:r,className:Ka("inline-flex items-center gap-1.5 text-muted",t),...n})).displayName="BreadcrumbItem";Le.forwardRef(({asChild:t,className:n,...r},a)=>e("a",{ref:a,className:Ka("transition-colors hover:text-muted",n),...r})).displayName="BreadcrumbLink";Le.forwardRef(({className:t,href:n,onClick:r,...a},s)=>e(Ms,{variant:"ghost",size:"md",ref:s,className:Ka("p-0! hover:underline! hover:bg-background!",t),onClick:e=>{e.preventDefault(),r&&r(e)},...a})).displayName="BreadcrumbButton";Le.forwardRef(({className:t,...n},r)=>e("span",{ref:r,"aria-current":"page",className:Ka("font-normal text-foreground",t),...n})).displayName="BreadcrumbPage";Le.forwardRef(({className:t,...n},r)=>e("div",{ref:r,className:Ka("rounded-xl border bg-card text-card-foreground shadow",t),...n})).displayName="Card";Le.forwardRef(({className:t,...n},r)=>e("div",{ref:r,className:Ka("flex flex-col p-6",t),...n})).displayName="CardHeader";Le.forwardRef(({className:t,...n},r)=>e("div",{ref:r,className:Ka("font-semibold leading-none tracking-tight",t),...n})).displayName="CardTitle";Le.forwardRef(({className:t,...n},r)=>e("div",{ref:r,className:Ka("text-sm text-muted-foreground",t),...n})).displayName="CardDescription";Le.forwardRef(({className:t,...n},r)=>e("div",{ref:r,className:Ka("p-6 pt-0",t),...n})).displayName="CardContent";Le.forwardRef(({className:t,...n},r)=>e("div",{ref:r,className:Ka("flex items-center p-6 pt-0",t),...n})).displayName="CardFooter";function qs({children:t}){return e("span",{style:{border:0,clip:"rect(0 0 0 0)",height:"1px",margin:"-1px",overflow:"hidden",padding:0,position:"absolute",width:"1px",whiteSpace:"nowrap",wordWrap:"normal"},children:t})}Le.forwardRef(({className:t,...n},r)=>e(jr.Root,{ref:r,className:Ka("peer size-4 shrink-0 rounded-sm border border-1 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-white",t),...n,children:e(jr.Indicator,{className:Ka("flex items-center justify-center text-current"),children:e(it,{className:"size-4"})})})).displayName=jr.Root.displayName;const Hs=Ue(!1);function Gs({children:t}){return e(Hs.Provider,{value:!0,children:t})}function Js({className:n,children:r,isOpen:a,onClose:s,description:i="Modal Description",noCloseButton:o=!1,allowOverflow:l=!1,disableCloseOnClickOutside:c=!1,size:d="md",action:u}){const m=e=>{e||s()};return t(Qs,{open:a,onOpenChange:e=>{c&&!e||m(e)},children:[l&&e(ei,{className:"z-50 fixed inset-0 bg-black/80"}),e(qs,{children:e(ni,{children:i})}),t(ti,{className:Ka("min-h-20 p-4","fixed left-[50%] top-[50%] z-50 grid w-full translate-x-[-50%] translate-y-[-50%] border bg-background shadow-lg duration-200 sm:rounded-lg",function(){switch(d){case"sm":return"max-w-[20vw]";case"md":default:return"max-w-[60vw] lg:max-w-[40vw]";case"lg":return"max-w-[80vw] md:max-w-[60vw]";case"xl":return"max-w-[95vw] lg:max-w-[80vw]"}}(),n),children:[e("div",{className:"top-4 end-4 absolute",children:t("div",{className:"flex gap-2",children:[u&&u,!o&&e(Xs,{onClick:()=>m(!1),asChild:!0,autoFocus:!1,children:e(Ms,{variant:"outline",title:"Close",className:"data-[state=open]:bg-accent opacity-70 hover:opacity-100 rounded-sm focus:outline-none focus:ring-2 focus:ring-ring ring-offset-background focus:ring-offset-2 data-[state=open]:text-muted-foreground transition-opacity disabled:pointer-events-none",children:e(ut,{className:"size-4"})})})]})}),e(Gs,{children:r})]})]})}const Ks=({children:n,show:r=!0,className:a,description:s,showDivider:i=!1,...o})=>r?t(ri,{className:Ka(i?"border-b-solid border-b border-b-1 pb-2 mb-4":"","text-lg font-semibold leading-6 tracking-tight",{"py-2":!s},a),...o,children:[n,s&&e(ni,{className:"text-sm !font-normal text-muted-foreground pb-2",children:s})]}):t(qs,{children:[e(ri,{children:n}),s&&e(ni,{children:s})]}),Ys=({children:t,className:n,...r})=>e("div",{className:Ka("text-sm max-h-[80vh] overflow-y-auto",n),...r,children:t}),Qs=er.Root,Zs=er.Portal,Xs=er.Close,ei=Le.forwardRef(({className:t,...n},r)=>e(er.Overlay,{ref:r,className:Ka("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...n}));ei.displayName=er.Overlay.displayName;const ti=Le.forwardRef(({className:n,children:r,...a},s)=>{const i=Is();return t(Zs,{container:i,children:[e(ei,{}),e(er.Content,{ref:s,autoFocus:!1,onOpenAutoFocus:e=>{e.preventDefault()},className:Ka("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] border bg-background shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",n),...a,children:r})]})});ti.displayName=er.Content.displayName;const ni=Le.forwardRef(({className:t,...n},r)=>e(er.Description,{ref:r,className:Ka("text-sm text-muted",t),...n}));ni.displayName=er.Description.displayName;const ri=Le.forwardRef(({className:t,...n},r)=>e(er.Title,{ref:r,className:Ka("text-lg font-semibold leading-none tracking-tight",t),...n}));ri.displayName=er.Title.displayName;Le.forwardRef(({className:t,...n},r)=>e(Pr,{ref:r,className:Ka("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",t),...n})).displayName=Pr.displayName;Le.forwardRef(({className:n,...r},a)=>t("div",{className:"flex items-center px-3 border-b","cmdk-input-wrapper":"",children:[e(bt,{className:"opacity-50 size-4 shrink-0"}),e(Pr.Input,{ref:a,className:Ka("focus:ring-0","border-0 flex h-8 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",n),...r})]})).displayName=Pr.Input.displayName;Le.forwardRef(({className:t,...n},r)=>e(Pr.List,{ref:r,className:Ka("overflow-y-auto overflow-x-hidden",t),...n})).displayName=Pr.List.displayName;Le.forwardRef((t,n)=>e(Pr.Empty,{ref:n,className:"py-2 text-sm text-center",...t})).displayName=Pr.Empty.displayName;Le.forwardRef(({className:t,...n},r)=>e(Pr.Group,{ref:r,className:Ka("overflow-y-auto overflow-x-hidden p-1 text-foreground","[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",t),...n})).displayName=Pr.Group.displayName;Le.forwardRef(({className:t,...n},r)=>e(Pr.Separator,{ref:r,className:Ka("-mx-1 h-px bg-border",t),...n})).displayName=Pr.Separator.displayName;Le.forwardRef(({className:t,...n},r)=>e(Pr.Item,{ref:r,className:Ka("hover:bg-muted cursor-pointer relative flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",t),...n})).displayName=Pr.Item.displayName;const ai=Le.createContext(!1);function si({...t}){return e(Ar.Root,{"data-slot":"dropdown-menu",...t})}function ii({...t}){return e(Ar.Trigger,{"data-slot":"dropdown-menu-trigger",...t})}function oi({className:t,align:n="start",sideOffset:r=4,...a}){return e(Ar.Portal,{children:e(Ar.Content,{"data-slot":"dropdown-menu-content",sideOffset:r,align:n,className:Ka("data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 ring-foreground/10 bg-popover text-popover-foreground min-w-32 rounded-lg p-1 shadow-md ring-1 duration-100 z-50 max-h-(--radix-dropdown-menu-content-available-height) w-(--radix-dropdown-menu-trigger-width) origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto data-[state=closed]:overflow-hidden",t),...a})})}function li({className:t,inset:n,variant:r="default",...a}){return e(Ar.Item,{"data-slot":"dropdown-menu-item","data-inset":n,"data-variant":r,className:Ka("hover:bg-muted focus:bg-muted data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:text-destructive gap-2 rounded-md px-1.5 py-1 text-sm data-inset:ps-7 [&_svg:not([class*='size-'])]:size-4 group/dropdown-menu-item relative flex cursor-default items-center outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0",t),...a})}const ci={left:"start",center:"center",right:"end"};function di({trigger:n,children:r,align:a="right",hover:s}){const[i,o]=Le.useState(!1),l=Le.useRef(null);if(s){return t("div",{className:"relative inline-flex",onMouseEnter:()=>{l.current&&clearTimeout(l.current),o(!0)},onMouseLeave:()=>{l.current=setTimeout(()=>o(!1),80)},children:[n,i&&e("div",{className:Ka("absolute top-full pt-1 z-50","right"===a?"end-0":"center"===a?"left-1/2 -translate-x-1/2":"start-0"),children:e("div",{className:"min-w-32 rounded-lg p-1 shadow-md ring-1 ring-foreground/10 bg-popover text-popover-foreground",children:e(ai.Provider,{value:!0,children:r})})})]})}return t(si,{children:[e(ii,{asChild:!0,children:e("span",{className:"-m-1.5 flex items-center p-1.5",children:n})}),e(oi,{align:ci[a],className:"w-max",children:r})]})}function ui({children:t,href:n,onClick:r,isDisabled:a=!1,variant:s="default",className:i}){const o=Le.useContext(ai),l=Ka("w-full gap-2 rounded-md px-1.5 py-1 text-sm text-nowrap [&_svg:not([class*='size-'])]:size-4 flex cursor-default items-center select-none [&_svg]:pointer-events-none [&_svg]:shrink-0","destructive"===s?"text-destructive":"",a?"pointer-events-none opacity-50":"hover:bg-muted focus:bg-muted",i);if(o){const s=e=>{e.stopPropagation(),r?.(e)};return n?e("a",{href:n,className:l,children:t}):e("button",{type:"button",className:l,disabled:a,onClick:s,children:t})}return e(li,{className:Ka("data-[disabled]:pointer-events-none data-[disabled]:opacity-50 text-nowrap",i),disabled:a,variant:s,onClick:e=>{e.stopPropagation(),r?.(e)},asChild:!!n,children:n?e("a",{href:n,children:t}):t})}const mi=Le.createContext(null);function pi(e=!1,t=()=>{},n){e&&t("enter"===n)}Le.forwardRef(({children:t,...n},r)=>{const a=Le.useContext(mi);if(!a)throw new Error("PopoverTrigger must be used within a Popover");const{setOpen:s,hover:i,click:o}=a;return e(Er.Trigger,{ref:r,asChild:!0,onMouseEnter:()=>pi(i,s,"enter"),onMouseLeave:()=>pi(i,s,"leave"),onClick:()=>{o&&s(e=>!e)},...n,children:t})}).displayName=Er.Trigger.displayName;Le.forwardRef(({className:t,align:n="center",side:r="bottom",...a},s)=>{const i=Le.useContext(mi);if(!i)throw new Error("PopoverContent must be used within a Popover");const{setOpen:o,hover:l}=i,c=Is();return e(Er.Portal,{container:c,children:e(Er.Content,{ref:s,align:n,side:r,onMouseEnter:()=>pi(l,o,"enter"),onMouseLeave:()=>pi(l,o,"leave"),className:Ka("z-50 w-72 rounded-md border-popover bg-popover text-popover-foreground ring-1 ring-gray-200 dark:ring-slate-700 shadow-md focus:outline-none animate-in","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...a})})}).displayName=Er.Content.displayName;var hi;Er.Close.displayName=Er.Close.displayName,Me.createContext({filters:[],setFilters:()=>{},filterGroups:[]}),function(e){e.IS="is",e.IS_NOT="is_not",e.CONTAINS="contains",e.BEFORE="before",e.AFTER="after",e.IS_ANY_OF="is_any_of"}(hi||(hi={}));Ge(({className:t,level:n=3,...r},a)=>e(`h${n}`,{ref:a,className:Ka({h1:"text-2xl font-medium tracking-tight",h2:"text-xl font-medium tracking-tight",h3:"text-lg font-medium",h4:"text-base font-medium",h5:"text-sm font-medium",h6:"text-xs font-medium"}[`h${n}`],"mb-2",t),...r})).displayName="Heading";const fi=zr("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70");Le.forwardRef(({className:n,required:r,...a},s)=>t(Lr.Root,{ref:s,className:Ka(fi(),n),...a,children:[a.children,r&&e("span",{className:"text-destructive-foreground ms-1",children:"*"})]})).displayName=Lr.Root.displayName,Ue(()=>{});Le.forwardRef(({className:t,orientation:n="horizontal",decorative:r=!0,...a},s)=>e(Mr.Root,{ref:s,decorative:r,orientation:n,className:Ka("shrink-0 bg-border","horizontal"===n?"h-[1px] w-full":"h-full w-[1px]",t),...a})).displayName=Mr.Root.displayName;Le.forwardRef(({className:n,trackClassName:r,rangeClassName:a,thumbClassName:s,value:i,defaultValue:o,min:l=0,max:c=100,"aria-label":d,...u},m)=>{const p=Le.useId(),h=Array.isArray(i)?i.length:Array.isArray(o)?o.length:1,f=Le.useMemo(()=>Array.from({length:Math.max(1,h)},(e,t)=>`${p}-thumb-${t}`),[p,h]);return t(Fr.Root,{ref:m,"data-slot":"slider",value:i,defaultValue:o,min:l,max:c,...u,className:Ka("relative flex w-full touch-none select-none items-center data-[disabled]:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",n),children:[e(Fr.Track,{"data-slot":"slider-track",className:Ka("relative h-1.5 w-full grow overflow-hidden rounded-full bg-muted data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5",r),children:e(Fr.Range,{"data-slot":"slider-range",className:Ka("absolute h-full bg-primary data-[orientation=vertical]:w-full",a)})}),f.map(t=>e(Fr.Thumb,{"data-slot":"slider-thumb","aria-label":d,className:Ka("block size-3.5 rounded-full border border-primary bg-background shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",s)},t))]})}).displayName=Fr.Root.displayName;const gi={sm:["h-5 w-8","size-3","translate-x-4 rtl:-translate-x-4"],md:["h-6 w-11","size-4","translate-x-6 rtl:-translate-x-6"],lg:["h-8 w-16","size-6","translate-x-9 rtl:-translate-x-9"]};function vi({className:n,size:r="md",value:a,onChange:s,children:i,disabled:o,...l}){const[c,d,u]=gi[r],m=e(Or.Root,{"data-slot":"switch",checked:a,onCheckedChange:s,disabled:o,...l,className:Ka("data-[state=checked]:bg-primary data-[state=unchecked]:bg-muted focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:aria-invalid:border-destructive/50 shrink-0 rounded-full border focus-visible:ring-3 aria-invalid:ring-3 peer group/switch relative inline-flex items-center transition-all outline-none after:absolute after:-inset-x-3 after:-inset-y-2 data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",c,!i&&n),children:e(Or.Thumb,{"data-slot":"switch-thumb",className:Ka("bg-white rounded-full pointer-events-none block ring-0 transition-transform",d,a?u:"translate-x-1 rtl:-translate-x-1")})});return i?t("div",{className:Ka("flex items-center",n),children:[m,e("span",{className:"px-2",children:i})]}):m}const bi=Le.createContext({size:void 0,tabs:void 0,current:void 0,setTab:void 0,responsive:!1,variant:"tabs",updateHash:!0});Le.forwardRef(({className:t,size:n,variant:r="tabs",...a},s)=>e(bi.Provider,{value:{size:n,variant:r},children:e(Ur.List,{ref:s,className:Ka("tabs"===r?"border-b -mb-px flex gap-4":"flex gap-2 p-1 rounded-md",t),...a})})).displayName=Ur.List.displayName;Le.forwardRef(({className:t,href:n,variant:r="tabs",...a},s)=>{const{size:i}=Le.useContext(bi),o=Le.useCallback(e=>{if(n){e.preventDefault();const t=window.history.state;window.history.pushState(t,"",n)}a.onClick&&a.onClick(e)},[n,a.onClick]);return e(Ur.Trigger,{ref:s,className:Ka("tabs"===r?Ka("border-b-2 px-2 py-1.5 text-sm font-medium whitespace-nowrap cursor-pointer","border-transparent text-muted-foreground hover:border-border hover:text-foreground","data-[state=active]:border-primary data-[state=active]:text-primary","disabled:pointer-events-none disabled:opacity-50"):Ka("px-3 py-1.5 text-sm font-medium whitespace-nowrap cursor-pointer rounded-sm transition-colors","tborder border-input bg-muted shadow-xs hover:bg-muted ring-inset","data-[state=active]:bg-primary data-[state=active]:text-white data-[state=active]:shadow-sm","disabled:pointer-events-none disabled:opacity-50"),t,i?`w-1/${i}`:""),onClick:o,...a})}).displayName=Ur.Trigger.displayName;Le.forwardRef(({className:t,...n},r)=>e(Ur.Content,{ref:r,className:Ka("focus-visible:outline-none","flex-1 overflow-y-auto min-h-0 pt-2 pb-4",t),...n})).displayName=Ur.Content.displayName;const xi=zr("text-foreground",{variants:{size:{xl:"text-base md:text-lg leading-relaxed",lg:"text-base leading-relaxed",default:"text-sm leading-normal",sm:"text-sm leading-normal",xs:"text-xs leading-normal"},weight:{normal:"font-normal",medium:"font-medium",semibold:"font-semibold"}},defaultVariants:{size:"default",weight:"normal"}});Ge(({className:t,size:n,weight:r,...a},s)=>e("p",{ref:s,className:Ka(xi({size:n,weight:r,className:t})),...a})).displayName="Text";function yi({size:n,className:r}){const a=function(e){switch(e){case"xs":return"size-2";case"sm":return"size-3";case"md":return"size-4";case"lg":return"size-5";case"xl":return"size-7";case"2xl":return"size-10";default:throw new Error(`Unexpected size: ${e}`)}}(n||"md");return t("svg",{className:Ae("animate-[spin_0.8s_linear_infinite] text-indigo-500",a,r),xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",role:"img","aria-label":"Loading",children:[e("title",{children:"Loading"}),e("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]})}function wi({onComplete:e,onError:t}){const n=Be(null),r=Be(e),a=Be(t);He(()=>{r.current=e,a.current=t},[e,t]),He(()=>()=>{n.current&&(n.current(),n.current=null)},[]);return{openOAuthPopup:e=>{n.current&&(n.current(),n.current=null);const t=window.screenX+(window.outerWidth-600)/2,s=window.screenY+(window.outerHeight-700)/2,i=window.open(e,"oauth_popup",`width=600,height=700,left=${t},top=${s},popup=yes`);let o=!1,l=null;const c=new BroadcastChannel("oauth-callback");c.addEventListener("message",e=>{var t;"object"==typeof(t=e.data)&&null!==t&&"type"in t&&"oauth-complete"===t.type&&"success"in t&&"boolean"==typeof t.success&&(o=!0,c.close(),l&&clearInterval(l),r.current(),!e.data.success&&e.data.error&&a.current?.(e.data.error),n.current=null)}),i&&(l=setInterval(()=>{i.closed&&(l&&clearInterval(l),c.close(),o||r.current(),n.current=null)},1e3)),n.current=()=>{c.close(),l&&clearInterval(l)}}}}function Ni({appId:r,collectionId:a,collectionName:s,authenticated:i,onAuthChange:o,onError:l,variant:c="default",showLabel:d=!1,showDisconnect:u=!1,readOnly:m=!1}){const{client:p}=tr(),{t:h}=Ze(),[f,g]=Oe(null),[v,b]=Oe(void 0===i&&!m),[x,y]=Oe(!1),[w,N]=Oe(!1),k=i??f?.authenticated??!1,_=s??a,C="h-6 w-32 justify-center px-2 text-xs",S=Ve(async()=>{if(void 0===i)if(m)b(!1);else try{b(!0);const e=await p.remoteMcpConnections.getCollectionStatus(r,a);g(e)}catch(e){console.error("[RemoteMcpConnectionButton] Failed to load OAuth status:",e)}finally{b(!1)}else b(!1)},[p,r,a,i,m]);He(()=>{S()},[S]);const{openOAuthPopup:T}=wi({onComplete:()=>{y(!1),S(),o?.()},onError:e=>{console.error("OAuth failed:",e),y(!1)}}),I=async()=>{try{y(!0),l?.(null);const e=await p.remoteMcpConnections.authorize(r,a);e.connected?(y(!1),await S(),o?.()):e.authorization_url?T(e.authorization_url):(l?.(`${_}: Authorization URL not provided by server`),y(!1))}catch(e){console.error("Failed to authorize:",e);const t=(e instanceof Error?e.original_message??e.message:"Failed to connect").replace(/^[A-Za-z\s]+:\s/,"");l?.(`${_}: ${t}`),y(!1)}},z=async()=>{try{N(!0),await p.remoteMcpConnections.disconnect(r,a),await S(),o?.()}catch(e){console.error("Failed to disconnect:",e)}finally{N(!1)}};return v?"compact"===c?e(Ms,{variant:"outline",size:"sm",disabled:!0,className:C,title:h("mcpConnections.checkingStatus"),children:e(yi,{className:"size-3"})}):e("div",{className:"flex items-center gap-2 text-sm",children:e(yi,{className:"size-4"})}):"full"===c?t("div",k?{className:"flex items-center gap-2",children:[d&&t("span",{className:"font-medium text-sm text-foreground",children:[_,":"]}),t("div",{className:"flex items-center gap-1 text-success text-sm",children:[e(xt,{className:"size-4"}),e("span",{children:h("mcpOAuth.connected")})]}),u&&e(Ms,{variant:"ghost",size:"sm",onClick:z,disabled:w,children:w?e(yi,{className:"size-4"}):h("mcpOAuth.disconnect")})]}:{className:"flex items-center gap-2 text-sm",children:[d&&t("span",{className:"font-medium text-foreground",children:[_,":"]}),e(Ms,{variant:"ghost",size:"sm",onClick:I,disabled:x,children:t(n,x?{children:[e(yi,{className:"size-4"}),e("span",{children:h("mcpOAuth.authenticating")})]}:{children:[e(rt,{className:"size-4"}),e("span",{children:h("mcpOAuth.authenticate")})]})})]}):k?t("div","compact"===c?{className:"flex items-center gap-2",children:[d&&t("span",{className:"font-medium text-xs text-foreground",children:[_,":"]}),!m&&u&&e(Ms,{variant:"outline",size:"sm",onClick:z,disabled:w,className:C,children:w?e(yi,{className:"size-3"}):t(n,{children:[e(yt,{className:"size-3"}),e("span",{children:h("mcpOAuth.disconnect")})]})})]}:{className:"flex items-center gap-1 text-success",children:[e(xt,{className:"size-4"}),e("span",{className:"text-sm",children:h("mcpOAuth.connected")})]}):"compact"===c?t("div",m?{className:"flex items-center gap-2",children:[d&&t("span",{className:"font-medium text-xs text-foreground",children:[s,":"]}),e("div",{className:"flex items-center gap-1 text-muted",children:e("span",{className:"text-xs",children:h("mcpOAuth.notConnected")})})]}:{className:"flex items-center gap-2",children:[d&&t("span",{className:"font-medium text-xs text-foreground",children:[_,":"]}),e(Ms,{variant:"outline",size:"sm",onClick:I,disabled:x,className:C,children:t(n,x?{children:[e(yi,{className:"size-3"}),e("span",{children:h("mcpOAuth.connecting")})]}:{children:[e(wt,{className:"size-3"}),e("span",{children:h("mcpOAuth.connect")})]})})]}):e(Ms,{variant:"outline",size:"sm",onClick:I,disabled:m||x,children:t(n,x?{children:[e(yi,{className:"size-4"}),e("span",{children:h("mcpOAuth.connecting")})]}:{children:[e(wt,{className:"size-4 me-1"}),e("span",{children:h("mcpOAuth.connect")})]})})}Ue({theme:"system",setTheme:()=>null});const ki=Me.createContext({});function _i({children:t,artifactRunId:n,onProposalSelect:r,onProposalSubmit:a,MarkdownRenderer:s}){const i=Fe(()=>({artifactRunId:n,onProposalSelect:r,onProposalSubmit:a,MarkdownRenderer:s}),[n,r,a,s]);return e(ki.Provider,{value:i,children:t})}function Ci(){return Me.useContext(ki)}const Si=Ue(null);const Ti={chart:{icon:zt,label:"chart",defaultHeight:200},mermaid:{icon:It,label:"diagram",defaultHeight:150},proposal:{icon:Tt,label:"options",defaultHeight:100},code:{icon:Nt,label:"code",defaultHeight:80},image:{icon:St,label:"image",defaultHeight:150},link:{icon:Ct,label:"link",defaultHeight:24},expand:{icon:lt,label:"content",defaultHeight:100},table:{icon:_t,label:"table",defaultHeight:150},markdown:{icon:kt,label:"content",defaultHeight:100},"fusion-fragment":{icon:Nt,label:"fragment",defaultHeight:150}};function Ii({type:n,error:a,onRetry:s,message:i,height:o}){const l=Ti[n],c=o??l.defaultHeight,d="link"===n;if(a)return t("div",{className:"flex items-center gap-2 rounded border border-destructive/30 bg-destructive/5 text-destructive "+(d?"inline-flex px-2 py-1 text-sm":"p-4"),style:d?void 0:{minHeight:c},children:[t("span",{className:"text-destructive",children:["Failed to load ",l.label]}),s&&e(r,{variant:"unstyled",onClick:s,className:"ms-2 rounded bg-destructive/10 px-2 py-1 text-xs hover:bg-destructive/20 transition-colors text-destructive",children:"Retry"})]});const u=l.icon;return d?t("span",{className:"inline-flex items-center gap-1 text-muted animate-pulse",children:[e(u,{className:"h-3 w-3"}),e("span",{children:i||`Loading ${l.label}...`})]}):t("div",{className:"flex flex-col items-center justify-center gap-3 rounded border border-border bg-muted/30 animate-pulse",style:{minHeight:c},children:[e(u,{className:"h-8 w-8 text-muted"}),e("span",{className:"text-sm text-muted",children:i||`Loading ${l.label}...`}),e("div",{className:"flex gap-1",children:[...Array(3)].map((t,n)=>e("div",{className:"h-2 w-2 rounded-full bg-muted animate-bounce",style:{animationDelay:150*n+"ms"}},n))})]})}class zi extends Me.Component{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){console.error(`CodeBlock rendering error (${this.props.type}):`,e,t),this.props.onError?.(e)}handleRetry=()=>{this.setState({hasError:!1,error:void 0})};render(){if(this.state.hasError){const{type:n,fallbackCode:r}=this.props;return t("div",{className:"space-y-2",children:[e(Ii,{type:n,error:this.state.error?.message||"Rendering failed",onRetry:this.handleRetry}),r&&t("details",{className:"text-sm",children:[e("summary",{className:"cursor-pointer text-muted hover:text-foreground",children:"Show raw content"}),e("pre",{className:"mt-2 overflow-x-auto rounded bg-muted/50 p-2 text-xs",children:e("code",{children:r})})]})]})}return this.props.children}}function Ri(e){if("object"!=typeof e||null===e)return null;const t=e;return"vega-lite"===t.library&&"spec"in t&&"object"==typeof t.spec&&null!==t.spec?t:"string"==typeof t.$schema&&t.$schema.includes("vega")?{library:"vega-lite",spec:t}:null}function ji({content:n}){const{headers:r,rows:a}=Fe(()=>{if(!Array.isArray(n)||0===n.length)return{headers:[],rows:[]};const e=n[0];if("object"!=typeof e||null===e)return{headers:[],rows:[]};const t=Object.keys(e),r=n.map(e=>t.map(t=>{const n=e[t];return null==n?"":"object"==typeof n?JSON.stringify(n):String(n)}));return{headers:t,rows:r}},[n]);return 0===r.length?e(Ii,{type:"table",error:"No table data found"}):t("div",{className:"overflow-x-auto",children:[t("table",{className:"min-w-full text-sm border-collapse",children:[e("thead",{children:e("tr",{className:"border-b",children:r.map((t,n)=>e("th",{className:"px-3 py-2 text-start font-medium text-muted",children:t},n))})}),e("tbody",{children:a.slice(0,100).map((t,n)=>e("tr",{className:"border-b border-muted/20",children:t.map((t,n)=>e("td",{className:"px-3 py-2",children:t},n))},n))})]}),a.length>100&&t("div",{className:"text-sm text-muted py-2",children:["Showing 100 of ",a.length," rows"]})]})}function Pi({content:t,path:n}){const r=n.split(".").pop()?.toLowerCase()||"",a="string"==typeof t?t:JSON.stringify(t,null,2);return e("pre",{className:"overflow-x-auto p-3 bg-muted/10 rounded text-sm",children:e("code",{className:`language-${r}`,children:a})})}function Ai(e){return na.sanitize(e,{USE_PROFILES:{svg:!0,svgFilters:!0},ADD_TAGS:["use"],FORBID_TAGS:["foreignObject"]})}function Di(e){return e.replace(/<svg([^>]*)>/i,(e,t)=>{let n=t;if(!/viewBox/i.test(n)){const e=/\swidth\s*=\s*["']?(\d+(?:\.\d+)?)/i.exec(n),t=/\sheight\s*=\s*["']?(\d+(?:\.\d+)?)/i.exec(n);e&&t&&(n+=` viewBox="0 0 ${e[1]} ${t[1]}"`)}return n=n.replace(/\swidth\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/i,"").replace(/\sheight\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/i,""),/style="/i.test(n)?n=n.replace(/style="([^"]*)"/i,(e,t)=>`style="${t};width:100%;height:auto;display:block;max-width:100%;"`):n+=' style="width:100%;height:auto;display:block;max-width:100%;"',/preserveAspectRatio=/i.test(n)||(n+=' preserveAspectRatio="xMidYMid meet"'),`<svg${n}>`})}function Ei({content:t}){const n=Fe(()=>{const e="string"==typeof t?t.trim():"";return e?Di(Ai(e)):null},[t]);return n?e("div",{style:{margin:"16px 0",width:"100%",overflowX:"auto"},dangerouslySetInnerHTML:{__html:n}}):e(Ii,{type:"expand",error:"Empty mockup"})}function $i({content:t,path:n}){const r="string"==typeof t?t:"",a=n.split("/").pop()||"Artifact image";return e("img",{src:r,alt:a,className:"max-w-full h-auto rounded",loading:"lazy"})}function Li({content:t,renderType:n,path:r,runId:a,contentType:s}){const{MarkdownRenderer:i}=Ci(),o=Fe(()=>"auto"!==n?n:function(e,t,n){const r=t.split(".").pop()?.toLowerCase();if("svg"===r)return"mockup";if(["png","jpg","jpeg","gif","webp"].includes(r||""))return"image";if("md"===r)return"markdown";if("csv"===r)return"table";if("json"===n&&"object"==typeof e&&null!==e){const t=e;if("string"==typeof t.$schema&&t.$schema.includes("vega"))return"vega-lite";if("vega-lite"===t.library&&"spec"in t)return"vega-lite";if("template"in t&&"data"in t)return"fusion-fragment";if(Array.isArray(e)&&e.length>0&&"object"==typeof e[0])return"table"}return"code"}(t,r,s),[t,r,s,n]);switch(o){case"chart":{const n=Ri(t);return n?e(zi,{type:"chart",fallbackCode:JSON.stringify(t,null,2),children:e(ds,{spec:n,artifactRunId:a})}):e(Ii,{type:"chart",error:"Only Vega-Lite charts are supported. Recharts rendering has been retired."})}case"vega-lite":{const n=Ri(t);return n?e(zi,{type:"chart",fallbackCode:JSON.stringify(t,null,2),children:e(ds,{spec:n,artifactRunId:a})}):e(Ii,{type:"chart",error:"Invalid Vega-Lite specification"})}case"fusion-fragment":{const n=t;return console.log("[ArtifactContentRenderer] fusion-fragment:",{hasTemplate:!!n.template,hasData:!!n.data,runId:a,hasVegaLiteChart:!!ds}),n.template&&n.data?e(zi,{type:"fusion-fragment",fallbackCode:JSON.stringify(t,null,2),children:e(ea,{data:n.data,ChartComponent:ds,artifactRunId:a,children:e(ta,{code:JSON.stringify(n.template),data:n.data})})}):e(zi,{type:"fusion-fragment",fallbackCode:JSON.stringify(t,null,2),children:e(ta,{code:JSON.stringify(t)})})}case"table":return e(zi,{type:"table",fallbackCode:JSON.stringify(t,null,2),children:e(ji,{content:t})});case"markdown":{const n="string"==typeof t?t:String(t);return e(zi,{type:"markdown",fallbackCode:n,children:i?e(i,{artifactRunId:a,children:n}):e("pre",{className:"overflow-x-auto p-3 bg-muted/10 rounded text-sm",children:e("code",{children:n})})})}case"mockup":return e(zi,{type:"expand",fallbackCode:"string"==typeof t?t:r,children:e(Ei,{content:t})});case"image":return e(zi,{type:"image",fallbackCode:r,children:e($i,{content:t,path:r})});default:return e(Pi,{content:t,path:r})}}const Mi='Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif';function Fi({code:t,className:n}){const r=Be(null),[a,s]=Oe(null),[i,o]=Oe(null),l=Je().replace(/:/g,"_");return He(()=>{let e=!1;return(async()=>{if(!t.trim())return s(null),void o(null);try{o(null);const n=`mermaid-${l}-${Date.now()}`,r=function(e){const t=e.trim();let n="",r=!1,a=!1;for(let e=0;e<t.length;e++){const s=t[e],i=e>0?t[e-1]:"";if('"'!==s||a||"\\"===i)if("'"!==s||r||"\\"===i){if((r||a)&&"\\"===s){let r=e;for(;"\\"===t[r];)r++;if("n"===t[r]){n+="<br/>",e=r;continue}}n+=s}else a=!a,n+=s;else r=!r,n+=s}return n}(t),{svg:a}=await ra.render(n,r),i=function(e){return e.replace(/<svg([^<>]*)>/i,(e,t)=>{let n=t.replace(/\swidth="[^"]*"/i,"").replace(/\sheight="[^"]*"/i,"");return/style="/i.test(n)?n=n.replace(/style="([^"]*)"/i,(e,t)=>`style="${t};width:100%;height:auto;display:block;max-width:100%;"`):n+=' style="width:100%;height:auto;display:block;max-width:100%;"',/preserveAspectRatio=/i.test(n)||(n+=' preserveAspectRatio="xMidYMid meet"'),`<svg${n}>`})}(a);e||s(i)}catch(t){if(!e){const e=t instanceof Error?t.message:"Failed to render mermaid diagram";o(e),s(null)}}})(),()=>{e=!0}},[t,l]),i?null:e("div",a?{ref:r,className:`my-4 w-full overflow-x-auto [&_svg]:mx-auto [&_svg]:w-full [&_svg]:h-auto [&_svg]:max-w-full ${n||""}`,dangerouslySetInnerHTML:{__html:a}}:{className:`my-4 p-4 bg-gray-50 dark:bg-gray-800 rounded-lg animate-pulse ${n||""}`,children:e("div",{className:"h-32 bg-gray-200 dark:bg-gray-700 rounded"})})}function Oi(e){const t=e.trim();if(t.length<2)return!0;if(!t.startsWith("{"))return!1;try{return JSON.parse(t),!1}catch(e){const n=["unexpected end","unterminated string","expected","unexpected token"],r=(e instanceof Error?e.message:"").toLowerCase();if(n.some(e=>r.includes(e))){let e=0,n=0,r=!1,a=!1;for(const s of t)a?a=!1:"\\"!==s?'"'!==s?r||("{"===s?e++:"}"===s?e--:"["===s?n++:"]"===s&&n--):r=!r:a=!0;return e>0||n>0||r}return!1}}function Ui(e){try{let t=e.trim();const n=t.indexOf("{"),r=t.lastIndexOf("}");return-1!==n&&r>n&&(t=t.slice(n,r+1)),JSON.parse(t)}catch{return null}}function Wi({code:t}){const{artifactRunId:n}=Ci();n||console.warn("[VegaLiteCodeBlockHandler] artifactRunId is missing from CodeBlockContext");const r=Fe(()=>Oi(t),[t]),a=Fe(()=>{if(r)return null;const e=Ui(t);return e?{library:"vega-lite",spec:e}:null},[t,r]);return r?e(Ii,{type:"chart",message:"Loading chart..."}):a?e(zi,{type:"chart",fallbackCode:t,children:e(ds,{spec:a,artifactRunId:n})}):e(Ii,{type:"chart",error:"Invalid Vega-Lite specification"})}function Bi({code:t}){const{artifactRunId:n}=Ci();n||console.warn("[ChartCodeBlockHandler] artifactRunId is missing from CodeBlockContext");const r=Fe(()=>Oi(t),[t]),a=Fe(()=>{if(r)return null;const e=Ui(t);if(!e)return null;const n=function(e){const t="string"==typeof e.$schema&&e.$schema.includes("vega"),n="vega-lite"===e.library&&"spec"in e;return t||n?"vega-lite":null}(e);return n?"vega-lite"===e.library&&"spec"in e&&"object"==typeof e.spec?e:{library:"vega-lite",spec:e}:null},[t,r]);return r?e(Ii,{type:"chart",message:"Loading chart..."}):a?e(zi,{type:"chart",fallbackCode:t,children:e(ds,{spec:a,artifactRunId:n})}):e(Ii,{type:"chart",error:"Invalid Vega-Lite chart specification"})}function Vi({code:t}){const n=t.trim();return n?e(zi,{type:"mermaid",fallbackCode:t,children:e(Fi,{code:n})}):e(Ii,{type:"mermaid",error:"Empty diagram"})}function qi({code:t}){const n=Fe(()=>{const e=t.trim();return e?Di(Ai(e)):null},[t]);return n?e(zi,{type:"code",fallbackCode:t,children:e("div",{style:{margin:"16px 0",width:"100%",overflowX:"auto"},dangerouslySetInnerHTML:{__html:n}})}):e(Ii,{type:"code",error:"Empty mockup"})}function Hi({code:t,language:n}){const{artifactRunId:r}=Ci(),a=t.trim(),s=Fe(()=>{if(!n?.includes(":"))return"auto";const e=n.split(":")[1];return["chart","vega-lite","table","markdown","fusion-fragment","mockup","code","image","auto"].includes(e)?e:"auto"},[n]),{data:i,isLoading:o,error:l,contentType:c}=function({runId:e,path:t,parseJson:n=!0}){const{client:r}=tr(),a=Za(),s=Be(r);s.current=r;const i=Be(a);i.current=a;const[o,l]=Oe({data:void 0,rawContent:void 0,isLoading:!0,error:void 0,contentType:void 0}),c=Ve(async()=>{if(!e)return void l({data:void 0,rawContent:void 0,isLoading:!1,error:"No run ID provided",contentType:void 0});if(!t)return void l({data:void 0,rawContent:void 0,isLoading:!1,error:"No artifact path provided",contentType:void 0});l(e=>({...e,isLoading:!0,error:void 0}));const r=s.current,a=i.current,o=function(e){const t=e.split(".").pop()?.toLowerCase();switch(t){case"json":return"json";case"md":case"txt":case"csv":case"yaml":case"yml":default:return"text";case"png":case"jpg":case"jpeg":case"gif":case"webp":case"pdf":return"binary"}}(t);try{const s=es(e,t,"inline");let i;i=a?await a.getOrFetch(s,async()=>(await r.files.getArtifactDownloadUrl(e,t,"inline")).url):(await r.files.getArtifactDownloadUrl(e,t,"inline")).url;const c=await fetch(i);if(!c.ok)throw new Error(`Failed to fetch artifact: ${c.status} ${c.statusText}`);if("binary"===o)return void l({data:i,rawContent:void 0,isLoading:!1,error:void 0,contentType:o});const d=await c.text();let u;if(n&&"json"===o)try{u=JSON.parse(d)}catch{u=d}else u=d;l({data:u,rawContent:d,isLoading:!1,error:void 0,contentType:o})}catch(e){const n=e instanceof Error?e.message:"Failed to fetch artifact";console.error("Failed to fetch artifact content:",t,e),l({data:void 0,rawContent:void 0,isLoading:!1,error:n,contentType:o})}},[e,t,n]);He(()=>{c()},[c]);const d=Ve(()=>{l({data:void 0,rawContent:void 0,isLoading:!0,error:void 0,contentType:void 0}),c()},[c]);return{data:o.data,rawContent:o.rawContent,isLoading:o.isLoading,error:o.error,contentType:o.contentType,retry:d}}({runId:r,path:a});return r?o?e(Ii,{type:"expand",message:`Loading ${a}...`}):l?e(Ii,{type:"expand",error:`Failed to load artifact: ${l}`}):void 0===i?e(Ii,{type:"expand",error:"No content found in artifact"}):e(Li,{content:i,renderType:s,path:a,runId:r,contentType:c}):e(Ii,{type:"expand",error:"No artifact run ID available"})}function Gi(e){return e.trim().replace(/^\/+/,"")}function Ji(e){return e.startsWith("artifact:")?{scheme:"artifact",path:e.slice(9).trim()}:e.startsWith("image:")?{scheme:"image",path:e.slice(6).trim()}:e.startsWith("store:")?{scheme:"store",path:Gi(e.slice(6))}:e.startsWith("document:")?{scheme:"document",path:Gi(e.slice(9))}:e.startsWith("collection:")?{scheme:"collection",path:Gi(e.slice(11))}:{scheme:"standard",path:e}}function Ki(e,t){switch(e){case"store":case"document":return t?`/store/objects/${t}`:null;case"collection":return t?`/store/collections/${t}`:null;default:return null}}function Yi({rawUrl:e,artifactRunId:t,disposition:n="inline"}){const{client:r}=tr(),a=Za(),s=Be(r);s.current=r;const i=Be(a);i.current=a;const{scheme:o,path:l}=Ji(e),c=Ki(o,l),[d,u]=Oe(()=>{if(c)return{url:c,isLoading:!1,error:void 0};if("standard"===o)return{url:e,isLoading:!1,error:void 0};if(a&&("artifact"===o||"image"===o)){let e;e="artifact"===o&&t&&!Xa(l)?es(t,l,n):ts(l);const r=a.getUrl(e);if(r)return{url:r,isLoading:!1,error:void 0}}return{url:void 0,isLoading:!0,error:void 0}}),m=Ve(async()=>{if(c||"standard"===o)return;if("artifact"!==o&&"image"!==o)return void u({url:void 0,isLoading:!1,error:`Unknown scheme: ${o}`});u(e=>({...e,isLoading:!0,error:void 0}));const e=s.current,r=i.current;try{let a;if("artifact"===o)if(t&&!Xa(l)){const s=es(t,l,n);if(r)a=await r.getOrFetch(s,async()=>(await e.files.getArtifactDownloadUrl(t,l,n)).url);else{a=(await e.files.getArtifactDownloadUrl(t,l,n)).url}}else{const t=ts(l);if(r)a=await r.getOrFetch(t,async()=>(await e.files.getDownloadUrl(l)).url);else{a=(await e.files.getDownloadUrl(l)).url}}else{const t=ts(l);if(r)a=await r.getOrFetch(t,async()=>(await e.files.getDownloadUrl(l)).url);else{a=(await e.files.getDownloadUrl(l)).url}}u({url:a,isLoading:!1,error:void 0})}catch(e){const t=e instanceof Error?e.message:"Failed to resolve URL";console.error("Failed to resolve URL:",l,e),u({url:void 0,isLoading:!1,error:t})}},[o,l,t,n,c]);He(()=>{if(d.url&&!d.error)return;let e=!1;return e||(async()=>{await m()})(),()=>{e=!0}},[m,d.url,d.error]);const p=Ve(()=>{u({url:void 0,isLoading:!0,error:void 0}),m()},[m]);return{url:d.url,isLoading:d.isLoading,error:d.error,scheme:o,retry:p}}function Qi({src:n,alt:r,caption:a,className:s,artifactRunId:i}){const o=n||"",{scheme:l}=Ji(o);return"standard"===l?t("figure",{className:"my-4",children:[e("img",{src:n,alt:r,className:s}),e("figcaption",{className:"mt-2 text-sm text-muted text-center italic",children:a})]}):e(Zi,{rawSrc:o,alt:r,caption:a,artifactRunId:i,className:s})}function Zi({rawSrc:n,alt:r,caption:a,artifactRunId:s,className:i}){const{url:o,isLoading:l,error:c,retry:d}=Yi({rawUrl:n,artifactRunId:s,disposition:"inline"});return l?e(Ii,{type:"image",message:r?`Loading ${r}...`:void 0}):c?e(Ii,{type:"image",error:c,onRetry:d}):o?t("figure",{className:"my-4",children:[e("img",{src:o,alt:r,className:i}),e("figcaption",{className:"mt-2 text-sm text-muted text-center italic",children:a})]}):null}function Xi({node:t,src:n,alt:r,className:a,artifactRunId:s,ExistingImg:i,...o}){const l=n||"",{scheme:c}=Ji(l);return"standard"===c?"function"==typeof i?e(i,{node:t,src:n,alt:r,...o}):e("img",{src:n,alt:r,className:a,...o}):e(eo,{rawSrc:l,alt:r,artifactRunId:s,className:a,rest:o})}function eo({rawSrc:t,alt:n,artifactRunId:r,className:a,rest:s}){const{url:i,isLoading:o,error:l,retry:c}=Yi({rawUrl:t,artifactRunId:r,disposition:"inline"});return o?e(Ii,{type:"image",message:n?`Loading ${n}...`:void 0}):l?e(Ii,{type:"image",error:l,onRetry:c}):i?e("img",{src:i,alt:n,className:a,...s}):null}function to({node:t,href:n,children:r,className:a,artifactRunId:s,ExistingLink:i,...o}){const l=n||"",{scheme:c,path:d}=Ji(l),u=Ki(c,d);return u?"function"==typeof i?e(i,{node:t,href:u,...o,children:r}):e("a",{href:u,...o,className:a,target:"_blank",rel:"noopener noreferrer",children:r}):"standard"===c?"function"==typeof i?e(i,{node:t,href:n,...o,children:r}):e("a",{href:n,...o,className:a,target:"_blank",rel:"noopener noreferrer",children:r}):e(no,{rawHref:l,artifactRunId:s,className:a,rest:o,children:r})}function no({rawHref:t,artifactRunId:n,className:r,children:a,rest:s}){const{url:i,isLoading:o,error:l,retry:c}=Yi({rawUrl:t,artifactRunId:n,disposition:"attachment"});return o?e("span",{className:"inline-flex items-center gap-1 text-muted",children:e(Ii,{type:"link"})}):l?e("span",{className:"inline-flex items-center gap-1",children:e(Ii,{type:"link",error:l,onRetry:c})}):e("a",{href:i||"#",...s,className:r,target:"_blank",rel:"noopener noreferrer",children:a})}ra.initialize({startOnLoad:!1,theme:"default",securityLevel:"loose",fontFamily:Mi,suppressErrorRendering:!0,flowchart:{htmlLabels:!0,useMaxWidth:!0,nodeSpacing:40,rankSpacing:50,padding:12},sequence:{useMaxWidth:!0},themeVariables:{fontFamily:Mi}});const ro=["artifact:","image:","store:","document://","collection:"],ao=/(!?\[[^[\]\n]*\]\()((?:artifact:|image:|store:|document:\/\/|collection:)[^)[\n]+)(\))/g,so=/`[^`\n]*`/g,io=/(^|\n)(`{3,}|~{3,})[^\n]*\n[\s\S]*?\n\2(?=\n|$)/g,oo=/\s+("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|\([^)]*\))\s*$/;function lo(e){return ro.some(t=>e.startsWith(t))}function co(e){return e.replace(ao,(e,t,n,r)=>`${t}${function(e){const t=e.trim();if(t.startsWith("<")){const n=t.indexOf(">");if(n>0&&lo(t.slice(1,n).trim()))return e}const n=t.match(oo),r=n?.index??-1,a=(r>=0?t.slice(0,r):t).trim(),s=r>=0?t.slice(r):"";return lo(a)?`<${a}>${s}`:e}(n)}${r}`)}function uo(e){let t="",n=0;for(const r of e.matchAll(so))t+=co(e.slice(n,r.index)),t+=r[0],n=r.index+r[0].length;return t+=co(e.slice(n)),t}const mo=/^([ \t]*):::([^\n]*?):::[ \t]*$/gm,po=/^\w+/;const ho=/(^|\n)(`{3,}|~{3,})[^\n]*\n[\s\S]*?\n\2(?=\n|$)/g,fo=/`[^`\n]*`/g,go=/\\\$/g,vo=/\\[^\s]/,bo=/[{}]/,xo=/[_^][\w{]/,yo=/^[a-zA-Z]$/,wo=/^[a-zA-Z]\s*=/,No=/^\s/,ko=/\s$/,_o=/[+*/-]$/,Co=/\^[+-]$/;function So(e){return vo.test(e)||bo.test(e)||xo.test(e)||yo.test(e)||wo.test(e)}function To(e){return!!No.test(e)||(!!ko.test(e)||!(!_o.test(e)||Co.test(e)))}function Io(e,t,n){const r=e.slice(t+1,n);return 0===r.length||r.includes("\n")?null:r}function zo(e){const t=function(e){const t=[];for(let n=0;n<e.length;n++)"$"===e[n]&&(n>0&&"\\"===e[n-1]||(n+1<e.length&&"$"===e[n+1]?n++:n>0&&"$"===e[n-1]&&(n<2||"\\"!==e[n-2])||t.push(n)));return t}(e);if(t.length<2)return e;const n=new Set,r=new Set,a=new Array(t.length-1);for(let n=0;n<t.length-1;n++)a[n]=Io(e,t[n],t[n+1]);const s=[];for(let e=0;e<t.length-1;e++){if(n.has(e))continue;const r=a[e];null!==r&&So(r)&&(n.add(e),n.add(e+1),s.push([t[e],t[e+1]]))}let i=0;for(;i<t.length;){if(n.has(i)){i++;continue}let e=i+1;for(;e<t.length&&n.has(e);)e++;if(e>=t.length)break;if(e>i+1){r.add(t[i]),i++;continue}const s=a[i];null!==s?(To(s)&&(r.add(t[i]),r.add(t[e])),n.add(i),n.add(e),i=e+1):i++}for(let e=0;e<t.length;e++)n.has(e)||e+1<t.length&&n.has(e+1)&&r.add(t[e]);if(0===r.size&&0===s.length)return e;const o=[];let l=0;const c=Array.from(r).sort((e,t)=>e-t);let d=0,u=0;for(;d<c.length||u<s.length;){const t=d<c.length?c[d]:1/0;if(t<(u<s.length?s[u][0]:1/0))t>l&&o.push(e.slice(l,t)),o.push("\\$"),l=t+1,d++;else{const[t,n]=s[u];t>l&&o.push(e.slice(l,t));const r=e.slice(t,n+1);for(o.push(r.replace(go,"\\text{\\textdollar}")),l=n+1;d<c.length&&c[d]<=n;)d++;u++}}return l<e.length&&o.push(e.slice(l)),o.join("")}function Ro(e){const t=[];let n=0;for(const r of e.matchAll(fo))t.push(zo(e.slice(n,r.index))),t.push(r[0]),n=r.index+r[0].length;return t.push(zo(e.slice(n))),t.join("")}const jo={note:"md-callout-info",tip:"md-callout-info",warning:"md-callout-attention",important:"md-callout-attention",caution:"md-callout-destructive"},Po={note:"Note",tip:"Tip",warning:"Warning",important:"Important",caution:"Caution"};function Ao(){return e=>{Zr(e,e=>{if("containerDirective"!==e.type&&"leafDirective"!==e.type&&"textDirective"!==e.type)return;const t=e;t.data||(t.data={});const n=t.data,r=t.attributes||{},a=t.name;if("pagebreak"===a)return n.hName="hr",void(n.hProperties={className:"md-pagebreak"});if("columns"===a)return n.hName="div",void(n.hProperties={className:"md-columns"});if("column"===a){n.hName="div";const e={className:"md-column"};return r.width&&(e.style=`flex-basis:${r.width};flex-grow:0;flex-shrink:0`),void(n.hProperties=e)}if(a in jo){n.hName="div",n.hProperties={className:`md-callout ${jo[a]}`,"data-callout-type":a};const e=Po[a];if(e&&t.children){const n={type:"paragraph",data:{hName:"p",hProperties:{className:"md-callout-title"}},children:[{type:"text",value:e}]};t.children.unshift(n)}return}n.hName="div",n.hProperties={className:`md-${a}`,...Object.fromEntries(Object.entries(r).filter(([e])=>"class"!==e))},r.class&&(n.hProperties.className+=` ${r.class}`)})}}const Do=["artifact:","image:","store:","document:","document://","collection:"];function Eo(e){return Do.some(t=>e.startsWith(t))?e:Br(e)}function $o(){return e=>{Zr(e,"html",(e,t,n)=>{const r=e,a=n;if("string"==typeof r.value&&/<!--[\s\S]*?-->/.test(r.value)&&a?.children&&"number"==typeof t)return a.children.splice(t,1),[Xr,t]})}}const Lo={chart:Bi,"vega-lite":Wi,vegalite:Wi,mermaid:Vi,mockup:qi,svg:qi};function Mo({children:t,components:n,remarkPlugins:r=[],removeComments:a=!0,artifactRunId:s,className:i,codeClassName:o,inlineCodeClassName:l,linkClassName:c,imageClassName:d,onProposalSelect:u,onProposalSubmit:m}){const p=We(Si),h=Me.useMemo(()=>{return e=function(e){if(!e||!ro.some(t=>e.includes(t)))return e;let t="",n=0;for(const r of e.matchAll(io))t+=uo(e.slice(n,r.index)),t+=r[0],n=r.index+r[0].length;return t+=uo(e.slice(n)),t}(function(e){if(!e?.includes("$"))return e;const t=[];let n=0;for(const r of e.matchAll(ho))t.push(Ro(e.slice(n,r.index))),t.push(r[0]),n=r.index+r[0].length;return t.push(Ro(e.slice(n))),t.join("")}(t)),e?.includes(":::")?e.replace(mo,(e,t,n)=>{const r=n.trim(),a=po.exec(r);if(!a)return e;const s=a[0],i=r.slice(s.length).trim();return i?`${t}:::${s}\n${t}${i}\n${t}:::`:`${t}::${s}`}):e;var e},[t]),f=Me.useMemo(()=>{const e=[Jr,Gr,Ao,Kr,qr,Qr,Yr,...r];return a&&e.push($o),e},[r,a]),g=Me.useMemo(()=>[Vr],[]),v=Me.useMemo(()=>({handlers:{...Hr}}),[]),b=Me.useMemo(()=>{const t=n||{},r=t.code,a=t.a,i=t.img;return{...t,code:({node:t,className:n,children:a,...s})=>{const i=/language-([\w-]+)/.exec(n||""),c=!i,d=i?i[1]:"";if(!c&&d){if(p){const t=p.getComponent(d);if(t){const n=String(a||"").trim();return e(t,{code:n,language:d})}}if(function(e){return e?.startsWith("expand")??!1}(d)){const t=String(a||"").trim();return e(Hi,{code:t,language:d})}const t=Lo[d];if(t){const n=String(a||"").trim();return e(t,{code:n,language:d})}}if("function"==typeof r)return e(r,{node:t,className:n,...s,children:a});return e("code",{...s,className:c?`px-1.5 py-0.5 rounded ${l||""}`:` ${o||""}`,children:a})},a:t=>{const{node:n,href:r,children:i,...o}=t;return e(to,{node:n,href:r,className:c,artifactRunId:s,ExistingLink:"function"==typeof a?a:void 0,...o,children:i})},img:t=>{const{node:n,src:r,alt:a,title:o,...l}=t;return o?e(Qi,{src:r,alt:a,caption:o,className:d,artifactRunId:s}):e(Xi,{node:n,src:r,alt:a,className:d,artifactRunId:s,ExistingImg:"function"==typeof i?i:void 0,...l})}}},[n,s,p,o,l,c,d]),x=e(_i,{artifactRunId:s,onProposalSelect:u,onProposalSubmit:m,MarkdownRenderer:Mo,children:e(Wr,{remarkPlugins:f,rehypePlugins:g,remarkRehypeOptions:v,components:b,urlTransform:Eo,children:h})});return e("div",i?{className:`md-content ${i}`,children:x}:{className:"md-content",children:x})}const Fo={default:{border:"border-s-attention",bg:"bg-amber-50 dark:bg-amber-900/20",icon:"text-attention"},warning:{border:"border-s-destructive",bg:"bg-red-50 dark:bg-red-900/20",icon:"text-destructive"},info:{border:"border-s-info",bg:"bg-blue-50 dark:bg-blue-900/20",icon:"text-info"},success:{border:"border-s-success",bg:"bg-green-50 dark:bg-green-900/20",icon:"text-success"}},Oo={default:Pt,warning:jt,info:Tt,success:Rt},Uo="max-h-80 overflow-y-auto overscroll-contain pe-2";function Wo({question:a,description:s,options:o,onSelect:l,onMultiSelect:c,onSubmit:d,allowFreeResponse:u=!1,multiSelect:m=!1,placeholder:p,submitLabel:h,isLoading:f=!1,icon:g,variant:v="default",hideIcon:b=!1,hideBorder:x=!1,compact:y=!1,answered:w=!1,className:N,cardClassName:k,headerClassName:_,iconClassName:C,questionClassName:S,descriptionClassName:T,optionsClassName:I,buttonClassName:z,inputContainerClassName:R,inputClassName:j,submitButtonClassName:P}){const{t:A}=Ze(),D=p??A("agent.typeYourResponse"),E=h??A("agent.send"),[$,L]=Me.useState(""),[M,F]=Me.useState(new Set),O=Me.useRef(null),U=Fo[v],W=Oo[v],B=e=>{F(t=>{const n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},V=()=>{M.size>0&&c&&(c(Array.from(M)),F(new Set))},q=()=>{$.trim()&&d&&(d($.trim()),L(""))},H=e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),q())},G=x?"":`border-s-4 ${U.border}`;if(y){const c=g||e(W,{className:"size-4"}),d=e("div",{className:i("agent-ask-question text-sm leading-6 text-foreground/85",S),children:e(Mo,{children:a})});return e("div",w?{className:i("my-1.5 font-sans",N),children:t("div",{className:Uo,children:[d,s&&e("p",{className:i("mt-1 text-xs leading-5 text-muted",T),children:s})]})}:{className:i("my-2 font-sans",N),children:t("div",{className:i("rounded-lg border border-border bg-background/60 shadow-none",k),children:[e("div",{className:i("px-3 py-2",_),children:t("div",{className:"flex items-start gap-2.5",children:[!b&&e("div",{className:i("mt-1 flex-shrink-0 text-attention",C),children:c}),e("div",{className:"min-w-0 flex-1",children:t("div",{className:Uo,children:[d,s&&e("p",{className:i("mt-1 text-xs leading-5 text-muted",T),children:s})]})})]})}),o&&o.length>0&&e("div",{className:i("flex flex-col gap-1.5 px-3 pb-3 pt-0",I),children:m?t(n,{children:[o.map(n=>{const r=M.has(n.id);return t("label",{className:i("flex cursor-pointer items-start gap-2.5 rounded-md border px-3 py-2 text-start transition-colors",r?"border-info/60 bg-info/10":"border-border bg-background/70 hover:bg-mixer-muted/15",f&&"cursor-not-allowed opacity-50",z),children:[e("input",{type:"checkbox",checked:r,onChange:()=>B(n.id),disabled:f,className:"mt-1 size-4 rounded border-border bg-background text-info focus:ring-info"}),t("span",{className:"min-w-0 flex-1",children:[t("span",{className:"flex items-center gap-2 text-sm font-medium leading-5 text-foreground",children:[n.icon,e("span",{className:"break-words",children:n.label})]}),n.description&&e("span",{className:"mt-0.5 block break-words text-xs leading-5 text-muted",children:n.description})]})]},n.id)}),e("div",{className:"pt-1",children:t(r,{size:"sm",onClick:V,disabled:f||0===M.size,className:"inline-flex items-center gap-2",children:[e(At,{className:"size-4"}),M.size>0?A("agent.submitSelectionCount",{count:M.size}):A("agent.submitSelection")]})})]}):o.map(n=>t("button",{type:"button",onClick:()=>l?.(n.id),disabled:f,className:i("flex w-full cursor-pointer items-start gap-2.5 rounded-md border border-border bg-background/70 px-3 py-2 text-start transition-colors","hover:bg-mixer-muted/15 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",f&&"cursor-not-allowed opacity-50",z),children:[e("span",{className:"mt-1 size-4 flex-shrink-0 rounded-full border border-border","aria-hidden":"true"}),t("span",{className:"min-w-0 flex-1",children:[t("span",{className:"flex items-center gap-2 text-sm font-medium leading-5 text-foreground",children:[n.icon,e("span",{className:"break-words",children:n.label})]}),n.description&&e("span",{className:"mt-0.5 block break-words text-xs leading-5 text-muted",children:n.description})]})]},n.id))}),u&&e("div",{className:i("px-3 pb-3 pt-0",R),children:t("div",{className:"flex gap-2",children:[e("input",{ref:O,type:"text",value:$,onChange:e=>L(e.target.value),onKeyDown:H,placeholder:D,disabled:f,className:i("min-w-0 flex-1 rounded-md border border-border bg-background/70 px-3 py-2 text-sm text-foreground focus:border-transparent focus:ring-2 focus:ring-ring",j)}),e(r,{size:"sm",onClick:q,disabled:f||!$.trim(),className:P,children:f?"...":E})]})})]})})}return e("div",{className:`my-4 font-sans ${N||""}`,children:t("div",{className:`${G} ${U.bg} rounded-e-lg shadow-sm ${k||""}`,children:[e("div",{className:`px-4 py-3 ${_||""}`,children:t("div",{className:"flex items-start gap-3",children:[!b&&e("div",{className:`flex-shrink-0 mt-0.5 ${U.icon} ${C||""}`,children:g||e(W,{className:"size-5"})}),e("div",{className:"min-w-0 flex-1",children:t("div",{className:Uo,children:[e("div",{className:`agent-ask-question prose prose-sm dark:prose-invert max-w-none text-gray-900 dark:text-gray-100 ${S||""}`,children:e(Mo,{children:a})}),s&&e("p",{className:`mt-1 text-sm text-gray-600 dark:text-gray-400 ${T||""}`,children:s})]})})]})}),o&&o.length>0&&e("div",{className:`px-4 pb-3 pt-1 ${I||""}`,children:m?t("div",{className:"space-y-2",children:[o.map(n=>t("label",{className:`flex items-start gap-3 px-4 py-3 rounded-lg cursor-pointer transition-colors\n ${M.has(n.id)?"bg-blue-50 dark:bg-blue-900/30 border border-blue-300 dark:border-blue-700":"bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700"}\n ${f?"opacity-50 cursor-not-allowed":""}`,children:[e("input",{type:"checkbox",checked:M.has(n.id),onChange:()=>B(n.id),disabled:f,className:"mt-0.5 w-4 h-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500 dark:border-gray-600 dark:bg-gray-700"}),t("div",{className:"flex-1 overflow-hidden",children:[t("div",{className:"flex items-center gap-2 text-sm font-medium text-gray-900 dark:text-gray-100 break-words",children:[n.icon,e("span",{className:"break-words",children:n.label})]}),n.description&&e("div",{className:"mt-1 text-sm text-gray-500 dark:text-gray-400 break-words whitespace-pre-wrap",children:n.description})]})]},n.id)),e("div",{className:"pt-2",children:t(r,{size:"sm",onClick:V,disabled:f||0===M.size,className:"flex items-center gap-2",children:[e(At,{className:"size-4"}),M.size>0?A("agent.submitSelectionCount",{count:M.size}):A("agent.submitSelection")]})})]}):e("div",{className:"flex flex-col gap-2 w-full",children:o.map(n=>e(r,{variant:"unstyled",onClick:()=>l?.(n.id),disabled:f,className:`w-full h-auto whitespace-normal text-start px-4 py-3 rounded-lg border border-gray-200 dark:border-gray-700\n bg-white dark:bg-gray-800\n hover:bg-gray-50 dark:hover:bg-gray-700 hover:border-gray-300 dark:hover:border-gray-600\n focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-1\n transition-colors\n ${f?"opacity-50 cursor-not-allowed":"cursor-pointer"}\n ${z||""}`,children:t("div",{className:"flex items-start gap-3",children:[n.icon&&e("span",{className:"flex-shrink-0 mt-0.5 text-gray-500 dark:text-gray-400",children:n.icon}),t("div",{className:"flex-1 overflow-hidden",children:[e("div",{className:"font-medium text-sm text-gray-900 dark:text-gray-100 break-words text-center",children:n.label}),n.description&&e("div",{className:"mt-1 text-sm text-gray-500 dark:text-gray-400 break-words whitespace-pre-wrap",children:n.description})]})]})},n.id))})}),u&&e("div",{className:`px-4 pb-3 pt-1 ${R||""}`,children:t("div",{className:"flex gap-2",children:[e("input",{ref:O,type:"text",value:$,onChange:e=>L(e.target.value),onKeyDown:H,placeholder:D,disabled:f,className:`flex-1 px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-800 focus:ring-2 focus:ring-blue-500 focus:border-transparent ${j||""}`}),e(r,{size:"sm",onClick:q,disabled:f||!$.trim(),className:P,children:f?"...":E})]})})]})})}function Bo({question:t,description:n,onConfirm:r,onCancel:a,confirmLabel:s,cancelLabel:i,isLoading:o=!1,variant:l="default",className:c}){const{t:d}=Ze(),u=s??d("agent.yes"),m=i??d("agent.no");return e(Wo,{question:t,description:n,variant:l,isLoading:o,className:c,options:[{id:"confirm",label:u,icon:e(Rt,{className:"size-4"})},{id:"cancel",label:m,icon:e(Dt,{className:"size-4"})}],onSelect:e=>{"confirm"===e?r():a()}})}function Vo(e){const t=e.replace(/^workstream[:_-]?/i,"").replace(/^sys:/i,"").replace(/[-_:]?[0-9a-f]{8}-[0-9a-f-]{12,}$/i,"").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").replace(/[:_-]+/g," ").trim();return t?t.split(/\s+/).map(e=>{const t=e.toLowerCase();return"qa"===t?"QA":"ui"===t?"UI":"api"===t?"API":"url"===t?"URL":t.charAt(0).toUpperCase()+t.slice(1)}).join(" "):e}function qo(e,t){const n=t?Vo(t):"",r=Vo(e);if(!n)return r;if(function(e){return/[0-9a-f]{8}-[0-9a-f-]{12,}/i.test(e)}(e))return n;const a=n.toLowerCase().replace(/\s+/g,"");return r.toLowerCase().replace(/\s+/g,"").startsWith(a)?n:r}function Ho(e){if("string"!=typeof e)return!1;const t=e.trim().toLowerCase();return Boolean(t&&"main"!==t&&"all"!==t)}function Go(e,t){return Ho(t)&&function(e){const t=e.trim();if(!t||!/^[{[]/.test(t))return!1;try{return JSON.parse(t),!0}catch{return!1}}(e)}function Jo(e){if(!Go(function(e){return e.message?"object"==typeof e.message?JSON.stringify(e.message,null,2):String(e.message).trim():""}(e),e.workstream_id))return!1;if(e.type!==ir.ANSWER&&e.type!==ir.COMPLETE)return!1;const t=e.details?.event_class;return"user_content"===t||!0===e.details?.streamed}function Ko(e){switch(e){case"running":return"bg-info";case"canceling":return"bg-attention";case"completed":return"bg-success";case"canceled":case"failed":case"timeout":return"bg-destructive"}}function Yo(e){const t=e.details;if("launched"!==t?.workstream_event)return null;const n="string"==typeof t.workstream_id?t.workstream_id:"string"==typeof e.workstream_id?e.workstream_id:"";return n&&"main"!==n&&"all"!==n?{workstreamId:n,launchId:"string"==typeof t.launch_id?t.launch_id:void 0,kind:"string"==typeof t.kind?t.kind:void 0,interaction:"string"==typeof t.interaction?t.interaction:void 0,childWorkflowId:"string"==typeof t.child_workflow_id?t.child_workflow_id:void 0,childWorkflowRunId:"string"==typeof t.child_workflow_run_id?t.child_workflow_run_id:void 0}:null}function Qo(e){const t=e.details;if("activity"!==t?.event_class)return null;if(void 0!==t.workstream_event)return null;if(e.type===ir.ERROR)return null;const n="string"==typeof t.child_workflow_id?t.child_workflow_id:void 0,r="string"==typeof t.child_workflow_run_id?t.child_workflow_run_id:void 0;if(!n&&!r)return null;const a="string"==typeof t.workstream_id&&t.workstream_id.trim()?t.workstream_id:"string"==typeof e.workstream_id?e.workstream_id:"";return Ho(a)?{workstreamId:a,launchId:"string"==typeof t.launch_id?t.launch_id:void 0,kind:"string"==typeof t.kind?t.kind:void 0,interaction:"string"==typeof t.interaction?t.interaction:void 0,childWorkflowId:n,childWorkflowRunId:r}:null}function Zo(){if("undefined"==typeof window)return!1;const e=new URLSearchParams(window.location.search).get("agentChatDebug"),t=function(e){const t=e.indexOf("?");return-1===t?null:new URLSearchParams(e.slice(t+1)).get("agentChatDebug")}(window.location.hash),n=e??t;if(null!==n)return"1"===n||"true"===n;try{const e=window.localStorage.getItem("agentChatDebug");return"1"===e||"true"===e}catch{return!1}}function Xo(e,t){Zo()&&console.debug(`[agent-chat] ${e}`,t??{})}function el(e,t){const n="number"==typeof t.timestamp?t.timestamp:new Date(t.timestamp).getTime(),r=e.findIndex(e=>("number"==typeof e.timestamp?e.timestamp:new Date(e.timestamp).getTime())>n);-1===r?e.push(t):e.splice(r,0,t)}const tl=[ir.COMPLETE,ir.IDLE,ir.REQUEST_INPUT,ir.TERMINATED];function nl(e){if(!e.length)return!0;const t=e.filter(e=>{return t=e,!(t.details?._optimistic&&"failed"===t.details?._deliveryStatus&&tl.includes(t.type));var t}),n=t.filter(e=>"main"===sl(e));if(0===n.length){const e=t[t.length-1];return!e||!tl.includes(e.type)}const r=n[n.length-1];return!tl.includes(r.type)}function rl(e){if(e.type!==ir.IDLE)return!1;const t=e.details?.status_reason,n=e.details?.display_role;return"user_stopped"===t||"user_stopped"===n||String(e.message??"").trim().toLowerCase().startsWith("stopped.")}function al(e){return"number"==typeof e?e:new Date(e).getTime()}function sl(e){return e.workstream_id?e.workstream_id:"main"}function il(e){if("main"===sl(e))return!0;if(Yo(e)||Qo(e))return!0;const t=function(e){const t=e.details;return!t||"object"!=typeof t||Array.isArray(t)?{}:t}(e),n="string"==typeof t.child_workflow_id||"string"==typeof t.child_workflow_run_id,r="string"==typeof t.tool||"string"==typeof t.tool_run_id;return!("activity"!==t.event_class||e.type!==ir.ERROR&&e.type!==ir.WARNING||n||r)}function ol(e,t){return"all"===t?e.filter(il):e.filter(e=>{const n=Yo(e)??Qo(e);return n?.workstreamId!==t&&sl(e)===t})}async function ll(e,t){return e.agents.getArtifactUrl(t,"conversation.json").then(e=>e.url)}function cl(e){if("string"!=typeof e)return;return e.replace(/\r\n/g,"\n").trim()||void 0}function dl(e){return cl(e.message)}function ul(e,t){const n=cl(e.text);if(!n)return!1;const r=e.workstreamId||"main";return t.some(t=>{if(al(t.timestamp)<e.startTimestamp)return!1;if(sl(t)!==r)return!1;const a="string"==typeof t.details?.streaming_id?t.details.streaming_id:void 0;return e.streamingId&&a?a===e.streamingId&&("thinking"!==t.details?.display_role&&(!pl(t)&&!t.details?.tool_status)):e.activityId&&t.details?.activity_id===e.activityId?"thinking"!==t.details?.display_role&&(!pl(t)&&!t.details?.tool_status):(t.type===ir.THOUGHT||t.type===ir.ANSWER||t.type===ir.COMPLETE||t.type===ir.IDLE)&&(!!t.details?.streamed&&dl(t)===n)})}function ml(e,t){if(sl(e)!==sl(t))return!1;const n=dl(e),r=dl(t);if(!n||n!==r)return!1;const a=al(e.timestamp);return!(al(t.timestamp)-a>1e4)&&(e.type===ir.ANSWER&&(t.type===ir.COMPLETE||t.type===ir.IDLE)||(!(e.type!==ir.THOUGHT||t.type!==ir.ANSWER&&t.type!==ir.COMPLETE&&t.type!==ir.IDLE||!e.details?.streamed&&!t.details?.streamed)||!(e.type!==t.type||!e.details?.streamed&&!t.details?.streamed||t.type!==ir.THOUGHT&&t.type!==ir.ANSWER&&t.type!==ir.COMPLETE&&t.type!==ir.IDLE)))}function pl(e){return e.type===ir.THOUGHT&&!!e.details?.tool}function hl(e){const t=e.details;return e.type===ir.THOUGHT&&("tool_preamble"===t?.display_role||"think"===t?.tool)}function fl(e){if(hl(e))return!1;if(pl(e))return!0;if(e.type!==ir.THOUGHT)return!1;const t=e.details;return!!(Array.isArray(t?.tools)&&t.tools.length>0)}function gl(e){return e.details?.tool_run_id}function vl(e){return e.details?.tool_iteration}function bl(e){return e.details?.tool_status}function xl(e){const t=e.details?.activity_group_id;if("string"==typeof t&&""!==t.trim())return t}function yl(e,t){return t??e}function wl(e){return e.message?"object"==typeof e.message?JSON.stringify(e.message,null,2):String(e.message).trim():""}function Nl(e){const t=kl(e.details?.tool_approval);if(!t)return wl(e);const n=_l(t.tool_title)??_l(t.tool_name),r=function(e){if(!e)return;const t=e.indexOf(":");if(t<0)return e;const n=e.slice(0,t),r=e.slice(t+1).trim();if(!r)return e;switch(n){case"document_id":return`document ${r}`;case"object_id":return`object ${r}`;case"collection_id":return`collection ${r}`;case"process_id":return`process ${r}`;case"process_definition_id":return`process definition ${r}`;case"interaction_id":return`interaction ${r}`;case"prompt_id":return`prompt ${r}`;case"dashboard_id":return`dashboard ${r}`;case"database_id":return`database ${r}`;case"table_id":return`table ${r}`;default:return r}}(_l(t.target));if(n&&r)return`Approve ${n}: ${r}?`;const a=_l(t.action_summary);return a?`Approve ${function(e){return e.replace(/:\s*name(?::|\s+)/i,": ")}(a)}?`:wl(e)}function kl(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:void 0}function _l(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function Cl(e){const t=e.details;return e.type===ir.REQUEST_INPUT&&!!t?.ux}function Sl(e){const t=e.details;return[t?.request_id,t?.requestId,t?.activity_id,t?.activityId,t?.tool_run_id,t?.toolRunId,e.timestamp,wl(e)].filter(e=>"string"==typeof e||"number"==typeof e).map(String).join("|")}function Tl(e){const t=e.details;return[t?.ack,t?._messageId,t?._deliveryStatus,e.timestamp,sl(e),wl(e)].filter(e=>"string"==typeof e||"number"==typeof e).map(String).join("|")}function Il(e){const t=new Set;return e.forEach((n,r)=>{if(n.type!==ir.REQUEST_INPUT)return;const a=sl(n);for(let s=r+1;s<e.length;s+=1){const r=e[s];if(sl(r)===a){if(r.type===ir.REQUEST_INPUT)break;if(r.type===ir.QUESTION){t.add(Sl(n));break}}}}),t}function zl(e){const t=new Set;for(const n of e){const e=kl(n.details),r=kl(e?.approval_request),a=r?.approval_key,s=e?.approval_decision;"string"!=typeof a||"denied"!==s&&"denied_with_feedback"!==s&&"timeout"!==s&&"reviewer_denied"!==s&&"cancelled_after_denial"!==s||t.add(a)}return t}function Rl(e){const t=kl(e.details),n=kl(t?.tool_approval),r=n?.approval_key;return"string"==typeof r?r:void 0}function jl(e){return e.type===ir.REQUEST_INPUT&&void 0!==Rl(e)}const Pl=new Set(["allow_once","allow_for_run","deny"]);function Al(e,t){const n=Rl(e);if(n&&Pl.has(t))return{tool_approval_response:{decision:t,approval_key:n}}}function Dl(e){if(e.type!==ir.QUESTION)return!1;const t=wl(e).trim().toLowerCase();return"allow_once"===t||"allow_for_run"===t||"deny"===t}function El(e){return Dl(e)||function(e){if(e.type!==ir.QUESTION)return!1;const t=kl(e.details),n=kl(t?.metadata),r=kl(t?.tool_approval_response)??kl(n?.tool_approval_response),a=r?.decision;return"deny_with_feedback"===a||"string"==typeof a&&Pl.has(a)}(e)}function $l(e,t){if(e.type!==ir.REQUEST_INPUT)return!1;const n=Rl(e);return!!n&&t.has(n)}function Ll(e,t,n){return jl(e)&&(t.has(Sl(e))||$l(e,n))}function Ml(e,t){return e.type===ir.QUESTION&&t.has(Tl(e))}function Fl(e,t){return e.type===ir.REQUEST_INPUT&&t.has(Sl(e))}function Ol(e,t="main"){const n=Il(e),r=zl(e);for(let a=e.length-1;a>=0;a-=1){const s=e[a];if(Cl(s)&&(sl(s)===t&&!Fl(s,n)&&!$l(s,r)))return s}}function Ul({mcpConnect:n,onMcpConnected:a,onDecline:s,disabled:i}){const{client:o}=tr(),{t:l}=Ze();return t("div",{className:"flex shrink-0 items-center justify-end gap-2",children:[e(Ni,{appId:n.app_install_id,collectionId:n.collection_id,collectionName:n.name,variant:"default",onAuthChange:()=>{o.remoteMcpConnections.getCollectionStatus(n.app_install_id,n.collection_id).then(e=>{e.authenticated&&a?.(n)}).catch(()=>{})},readOnly:i}),t(r,{variant:"ghost",size:"sm",onClick:s,disabled:i,children:[e(Et,{className:"size-4"}),e("span",{children:l("mcpOAuth.decline")})]})]})}function Wl({message:n,onSendMessage:r,onMcpConnected:a,isLoading:s=!1,disabled:o=!1,className:l}){const{t:c}=Ze();if(!n)return null;const d=n.details.ux,u=d.options??[],m=d.mcp_connect,p=d.free_response,h=o||s||!r,f=Nl(n),g=(e,t)=>{h||(t?r?.(e,t):r?.(e))},v=i("flex-shrink-0 border-t border-border/70 bg-background/95 backdrop-blur","fixed bottom-0 end-0 start-0 z-20 lg:sticky lg:start-auto lg:end-auto","pb-safe-area",l);return e("div",m?{className:v,"data-agent-request-input-overlay":!0,children:t("div",{className:"mx-auto flex w-full max-w-3xl flex-col gap-3 px-3 py-3 sm:flex-row sm:items-center sm:justify-between",children:[e("div",{className:"min-w-0 text-sm leading-6 text-foreground/85",children:f}),e(Ul,{mcpConnect:m,onMcpConnected:a,onDecline:()=>g(c("agent.mcpDeclinedMessage",{name:m.name})),disabled:h})]})}:{className:v,"data-agent-request-input-overlay":!0,children:e("div",{className:"mx-auto w-full max-w-3xl px-3 py-3",children:e(Wo,{question:f,options:u,variant:d.variant,multiSelect:d.multiSelect,allowFreeResponse:0===u.length||!!p,placeholder:p?.placeholder,submitLabel:p?.submit_label,onSelect:e=>g(e,Al(n,e)),onMultiSelect:e=>g(e.join(", ")),onSubmit:e=>g(e,p?.metadata),hideBorder:!0,compact:!0,isLoading:h,className:"my-0",cardClassName:"bg-background/80 shadow-lg shadow-black/5 dark:shadow-none"})})})}function Bl({className:n,inline:r=!1,color:a="blue"}){const s={blue:"from-blue-400 to-indigo-500 dark:from-blue-500 dark:to-indigo-400",purple:"from-purple-400 to-violet-500 dark:from-purple-500 dark:to-violet-400",teal:"from-teal-400 to-emerald-500 dark:from-teal-500 dark:to-emerald-400",green:"from-green-400 to-emerald-500 dark:from-green-500 dark:to-emerald-400",amber:"from-amber-400 to-orange-500 dark:from-amber-500 dark:to-orange-400"}[a];return t("div",{className:i("flex items-center gap-1.5",r?"inline-flex":"",n),children:[e("div",{className:`w-2 h-2 bg-gradient-to-r ${s} rounded-full animate-[bounce_1.2s_ease-in-out_infinite]`}),e("div",{className:`w-2 h-2 bg-gradient-to-r ${s} rounded-full animate-[bounce_1.2s_ease-in-out_0.2s_infinite]`}),e("div",{className:`w-2 h-2 bg-gradient-to-r ${s} rounded-full animate-[bounce_1.2s_ease-in-out_0.4s_infinite]`})]})}function Vl({className:n,size:r="md",color:a="blue"}){const s={blue:"bg-blue-500 dark:bg-blue-400",purple:"bg-purple-500 dark:bg-purple-400",teal:"bg-teal-500 dark:bg-teal-400",green:"bg-green-500 dark:bg-green-400",amber:"bg-amber-500 dark:bg-amber-400"};return t("span",{className:i("relative flex",n),children:[e("span",{className:i("animate-ping absolute inline-flex h-full w-full rounded-full opacity-60",s[a])}),e("span",{className:i("animate-pulse absolute inline-flex h-[80%] w-[80%] rounded-full opacity-80",s[a]),style:{left:"10%",top:"10%",animationDuration:"2s"}}),e("span",{className:i("relative inline-flex rounded-full",s[a],{sm:"w-3 h-3",md:"w-5 h-5",lg:"w-7 h-7"}[r])})]})}function ql({className:t,color:n="blue"}){const[r,a]=Oe(".");return He(()=>{const e=setInterval(()=>{a(e=>"."===e?"..":".."===e?"...":".")},500);return()=>clearInterval(e)},[]),e("span",{className:i({blue:"text-blue-600 dark:text-blue-400",purple:"text-purple-600 dark:text-purple-400",teal:"text-teal-600 dark:text-teal-400",green:"text-green-600 dark:text-green-400",amber:"text-amber-600 dark:text-amber-400"}[n],"font-bold",t),children:r})}function Hl({message:n,className:r,color:a="blue"}){const s={blue:{dot:"bg-blue-500 dark:bg-blue-400",text:"text-blue-700 dark:text-blue-300"},purple:{dot:"bg-purple-500 dark:bg-purple-400",text:"text-purple-700 dark:text-purple-300"},teal:{dot:"bg-teal-500 dark:bg-teal-400",text:"text-teal-700 dark:text-teal-300"},green:{dot:"bg-green-500 dark:bg-green-400",text:"text-green-700 dark:text-green-300"},amber:{dot:"bg-amber-500 dark:bg-amber-400",text:"text-amber-700 dark:text-amber-300"}};return t("div",{className:i("flex items-center gap-2 py-1",r),children:[t("div",{className:"flex gap-1",children:[e("div",{className:`w-1.5 h-1.5 ${s[a].dot} rounded-full animate-bounce`}),e("div",{className:`w-1.5 h-1.5 ${s[a].dot} rounded-full animate-bounce`,style:{animationDelay:"0.2s"}}),e("div",{className:`w-1.5 h-1.5 ${s[a].dot} rounded-full animate-bounce`,style:{animationDelay:"0.4s"}})]}),e("div",{className:`${s[a].text} font-medium text-xs`,children:n})]})}function Gl({className:n,color:r="blue",width:a="md",message:s}){const[o,l]=Oe(15),[c,d]=Oe("increasing"),[u,m]=Oe(.4),p=Be(null),h=Be(!0);He(()=>{const e=p.current;if(!e)return;const t=new IntersectionObserver(([e])=>{h.current=e.isIntersecting},{threshold:0});return t.observe(e),()=>t.disconnect()},[]);return He(()=>{let e,t=Date.now();const n=()=>{if(!h.current)return void(e=requestAnimationFrame(n));const r=Date.now(),a=r-t;t=r,l(e=>{const t=u*(a/16),n="increasing"===c?e+t:e-t;return n>=85?(d("decreasing"),m(.3+.2*Math.random()),85):n<=15?(d("increasing"),m(.3+.2*Math.random()),15):(Math.random()>.99&&m(e=>Math.max(.2,Math.min(.5,e+(.1*Math.random()-.05)))),n)}),e=requestAnimationFrame(n)};return e=requestAnimationFrame(n),()=>{cancelAnimationFrame(e)}},[c,u]),t("div",{ref:p,className:i("flex flex-col gap-1",n),children:[s&&e("div",{className:`text-xs font-medium ${{blue:"text-blue-700 dark:text-blue-300",purple:"text-purple-700 dark:text-purple-300",teal:"text-teal-700 dark:text-teal-300",green:"text-green-700 dark:text-green-300",amber:"text-amber-700 dark:text-amber-300"}[r]} mb-1`,children:s}),e("div",{className:i("h-1.5 rounded-full overflow-hidden shadow-inner",{blue:"bg-blue-200 dark:bg-blue-900/30",purple:"bg-purple-200 dark:bg-purple-900/30",teal:"bg-teal-200 dark:bg-teal-900/30",green:"bg-green-200 dark:bg-green-900/30",amber:"bg-amber-200 dark:bg-amber-900/30"}[r],{sm:"w-24",md:"w-32",lg:"w-48",xl:"w-64",full:"w-full"}[a]),children:e("div",{className:i("h-full rounded-full",{blue:"bg-gradient-to-r from-blue-400 to-blue-500 dark:from-blue-500 dark:to-blue-400",purple:"bg-gradient-to-r from-purple-400 to-purple-500 dark:from-purple-500 dark:to-purple-400",teal:"bg-gradient-to-r from-teal-400 to-teal-500 dark:from-teal-500 dark:to-teal-400",green:"bg-gradient-to-r from-green-400 to-green-500 dark:from-green-500 dark:to-green-400",amber:"bg-gradient-to-r from-amber-400 to-amber-500 dark:from-amber-500 dark:to-amber-400"}[r]),style:{width:`${o}%`,transition:"width 150ms cubic-bezier(0.4, 0.0, 0.2, 1)"}})})]})}function Jl({className:t,color:n="blue",size:r="md"}){const[a,s]=Oe(Array(7).fill(50)),o=Be(null),l=Be(!0);He(()=>{const e=o.current;if(!e)return;const t=new IntersectionObserver(([e])=>{l.current=e.isIntersecting},{threshold:0});return t.observe(e),()=>t.disconnect()},[]);const c={sm:{width:"w-16",height:"h-4",barWidth:"w-0.5",gap:"gap-[2px]"},md:{width:"w-20",height:"h-5",barWidth:"w-1",gap:"gap-[3px]"},lg:{width:"w-24",height:"h-6",barWidth:"w-1.5",gap:"gap-1"}},d={blue:"bg-gradient-to-b from-blue-400 to-blue-500 dark:from-blue-400 dark:to-blue-500",purple:"bg-gradient-to-b from-purple-400 to-purple-500 dark:from-purple-400 dark:to-purple-500",teal:"bg-gradient-to-b from-teal-400 to-teal-500 dark:from-teal-400 dark:to-teal-500",green:"bg-gradient-to-b from-green-400 to-green-500 dark:from-green-400 dark:to-green-500",amber:"bg-gradient-to-b from-amber-400 to-amber-500 dark:from-amber-400 dark:to-amber-500"};return He(()=>{let e;const t=[1.2,1,1.5,.8,1.3,.9,1.1],n=[0,.5,1,1.5,2,2.5,3];let r=0;const a=()=>{if(!l.current)return void(e=requestAnimationFrame(a));r+=.02;const i=Array(7).fill(0).map((e,a)=>10+40*(Math.sin(r*t[a]+n[a])+1));s(i),e=requestAnimationFrame(a)};return e=requestAnimationFrame(a),()=>{cancelAnimationFrame(e)}},[]),e("div",{ref:o,className:i("flex items-end justify-center",c[r].width,c[r].height,c[r].gap,t),children:a.map((t,a)=>e("div",{className:i(c[r].barWidth,"rounded-full transform-gpu",d[n]),style:{height:`${t}%`,transition:"height 100ms cubic-bezier(0.4, 0.0, 0.2, 1)",opacity:.9}},a))})}const Kl=["Brewing some code magic...","Doing the robot dance...","Cooking up something good...","Working my gears...","Parsing the possibilities...","Crunching the numbers...","Connecting the digital dots...","Processing at maximum capacity...","Searching through my circuits...","Running advanced algorithms...","Computing optimal solutions...","Loading brilliance.exe...","Scanning the knowledge base...","Optimizing response protocols...","Having a quick brainstorm...","Thinking cap firmly on...","Pondering the digital universe...","Consulting my silicon wisdom...","Untangling the logic knots...","Assembling clever responses...","Mixing thoughtful ingredients...","Polishing the perfect answer...","Taking a momentary mind sprint...","Connecting virtual synapses...","Baking fresh ideas...","Stirring the thought pot...","Simmering solutions slowly...","Whipping up a smart response...","Adding a dash of intelligence...","Preparing a gourmet answer...","Growing brilliant ideas...","Cultivating the perfect response...","Gathering digital nectar...","Planting seeds of solutions...","Exploring the data landscape...","Mapping the solution path...","Navigating through possibilities...","Charting the course to answers...","Embarking on a thought expedition...","Sketching out concepts...","Painting with digital brushstrokes...","Composing my response symphony...","Crafting precision answers...","Weaving threads of information...","Just a moment of processing...","Taking a quick thinking break...","Almost there, final touches...","Putting the pieces together...","Making progress, hold tight..."],Yl=Ue(null);function Ql(){const e=We(Yl);return e||{openImage:e=>window.open(e,"_blank"),closeImage:()=>{}}}function Zl({children:n}){const[a,s]=Oe(null),i=Ve((e,t)=>{s({src:e,alt:t})},[]),o=Ve(()=>{s(null)},[]),{t:l}=Ze();return t(Yl.Provider,{value:{openImage:i,closeImage:o},children:[n,a&&e("div",{role:"button",tabIndex:-1,"aria-label":l("agent.close"),className:"fixed inset-0 z-[100] flex items-center justify-center bg-black/80 backdrop-blur-sm",onClick:o,onKeyDown:m(o),children:t("div",{className:"relative max-w-[90vw] max-h-[90vh]",children:[e("img",{src:a.src,alt:a.alt||l("agent.enlargedView"),className:"max-w-full max-h-[90vh] object-contain rounded-lg shadow-2xl"}),e(r,{variant:"unstyled",className:"absolute top-2 end-2 text-white bg-black/50 rounded-full p-2 hover:bg-black/70 transition-colors",onClick:o,title:l("agent.close"),children:e(ut,{className:"size-6"})}),e("a",{href:a.src,target:"_blank",rel:"noopener noreferrer",className:"absolute bottom-2 end-2 text-white bg-black/50 rounded-full p-2 hover:bg-black/70 transition-colors",onClick:e=>e.stopPropagation(),title:l("agent.openInNewTab"),children:e($t,{className:"size-5"})})]})})]})}const Xl=new Set(["png","jpg","jpeg","gif","webp","bmp","svg"]),ec=new Set(["css","csv","html","js","json","jsx","log","md","mjs","sql","ts","tsx","txt","xml","yaml","yml"]);function tc(e){const t=e?.split(/[?#]/)[0]??"";return t.includes(".")?(t.split(".").pop()??"").toLowerCase():""}function nc({item:t,children:r,StoreLinkComponent:a,CollectionLinkComponent:s}){const i=t.href;if(!i)return e(n,{children:r});if(function(e){return Boolean(e?.includes("/store/objects/")||e?.startsWith("store:")||e?.startsWith("document:"))}(i)){const t=function(e){const t=e.split("/store/objects/")[1];return t?t.split(/[?#]/)[0]:e.replace(/^store:/,"").replace(/^document:(?:\/\/)?/,"").split(/[?#]/)[0]}(i);return a?e(a,{href:i,documentId:t,children:r}):e("a",{href:i.startsWith("store:")||i.startsWith("document:")?`/store/objects/${t}`:i,children:r})}if(function(e){return Boolean(e?.includes("/store/collections/")||e?.startsWith("collection:"))}(i)){const t=function(e){return e.split("/store/collections/")[1]||e.replace(/^collection:/,"")}(i);return s?e(s,{href:i,collectionId:t,children:r}):e("a",{href:i.startsWith("collection:")?`/store/collections/${t}`:i,children:r})}return/^https?:\/\//.test(i)||i.startsWith("/")?e("a",{href:i,target:i.startsWith("/")?void 0:"_blank",rel:"noopener noreferrer",children:r}):e(n,{children:r})}function rc({item:n,artifactRunId:a,variant:s,onRemove:o,StoreLinkComponent:l,CollectionLinkComponent:c}){const{t:d}=Ze(),u=We(nr),m=Za(),{openImage:p}=Ql(),h=function(e){return e.artifactPath?e.artifactPath:e.href?.startsWith("artifact:")?e.href.slice(9):void 0}(n),f=function(e){return!!e.contentType?.toLowerCase().startsWith("image/")||Xl.has(tc(e.artifactPath||e.href||e.name))}(n),g=f&&!function(e){const t=e.contentType?.toLowerCase()??"";return!!t.startsWith("text/")||!("application/json"!==t&&!t.includes("xml"))||ec.has(tc(e.artifactPath||e.href||e.name))}(n),[v,b]=Oe(n.previewUrl);He(()=>{b(n.previewUrl)},[n.previewUrl]),He(()=>{if(!g||n.previewUrl||!a||!h||!u?.client)return;let e=!1;const t=es(a,h,"inline");return(async()=>{const n=m?await m.getOrFetch(t,async()=>(await u.client.files.getArtifactDownloadUrl(a,h,"inline")).url):(await u.client.files.getArtifactDownloadUrl(a,h,"inline")).url;e||b(n)})().catch(()=>{e||b(void 0)}),()=>{e=!0}},[h,a,n.previewUrl,u?.client,g,m]);const x={attention:"bg-attention/15 text-attention",destructive:"bg-destructive/15 text-destructive",info:"bg-info/15 text-info",muted:"bg-muted text-muted",success:"bg-success/15 text-success"}[n.statusTone??"muted"],y=Boolean(o&&!1!==n.removable),w=e=>{e.stopPropagation(),e.preventDefault(),o?.(n.id)},N=y?e(r,{variant:"unstyled",size:"none","aria-label":d("agent.removeFile",{name:n.name}),onClick:w,className:i("absolute -end-1.5 -top-1.5 inline-flex size-5 items-center justify-center rounded-full","border border-border bg-background text-muted shadow-sm transition-colors hover:text-foreground"),children:e(Et,{className:"size-3","aria-hidden":"true"})}):null,k=y?e(r,{variant:"unstyled",size:"none","aria-label":d("agent.removeFile",{name:n.name}),onClick:w,className:i("-me-1 inline-flex size-6 shrink-0 items-center justify-center rounded-md text-muted","transition-colors hover:bg-mixer-muted/30 hover:text-foreground"),children:e(Et,{className:"size-3.5","aria-hidden":"true"})}):null,_=g&&v?e(r,{type:"button",variant:"unstyled",size:"none",onClick:e=>{e.stopPropagation(),e.preventDefault(),p(v,n.name)},"aria-label":n.name,title:d("agent.enlargedView"),className:i("group shrink-0 overflow-hidden rounded border border-border/60 p-0","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","composer"===s?"size-6":"size-24"),children:e("img",{src:v,alt:n.name,className:"h-full w-full object-cover transition-transform group-hover:scale-[1.05]"})}):e(f?Lt:Mt,{className:"size-3.5 shrink-0 text-muted","aria-hidden":"true"}),C=t("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1.5",children:[_,e("span",{className:i("truncate","composer"===s?"max-w-[14rem]":"max-w-[16rem]"),children:n.name}),n.statusLabel?e("span",{className:i("shrink-0 rounded px-1.5 py-0.5 text-[10px] font-medium",x),children:n.statusLabel}):null]});if("composer"===s)return t("span",{title:n.name,className:i("inline-flex min-h-8 max-w-full items-center gap-1 rounded-xl border border-border/60","bg-mixer-muted/15 px-2.5 py-1 text-sm text-foreground/80 transition-colors",n.href&&"hover:bg-mixer-muted/25"),children:[e(nc,{item:n,StoreLinkComponent:l,CollectionLinkComponent:c,children:C}),k]});const S=e("span",{title:n.name,className:i("inline-flex max-w-full items-center gap-1.5 rounded-md border border-border/60 bg-mixer-muted/15","px-2.5 py-1.5 text-xs text-foreground/80 transition-colors",n.href&&"hover:bg-mixer-muted/25"),children:C});return t("span",{className:"relative inline-flex max-w-full",children:[e(nc,{item:n,StoreLinkComponent:l,CollectionLinkComponent:c,children:S}),N]})}function ac({items:t,artifactRunId:n,className:r,align:a="start",variant:s="message",onRemove:o,StoreLinkComponent:l,CollectionLinkComponent:c}){return 0===t.length?null:e("div",{className:i("flex flex-wrap gap-2","end"===a&&"justify-end",r),children:t.map(t=>e(rc,{item:t,artifactRunId:n,variant:s,onRemove:o,StoreLinkComponent:l,CollectionLinkComponent:c},t.id))})}const sc=/^\s*(?:\*\*)?(attachments|uploaded artifacts):(?:\*\*)?\s*$/i,ic=/^\s*(?:[-*]\s*)?\[([^\]]+)]\(([^)]+)\)(?:\s+\((.*)\))?\s*$/;function oc(e){const t=e.split(/\r?\n/),n=[],r=[];let a=!1;for(const e of t){const t=e.trim();if(sc.test(t)){a=!0;continue}if(!a){n.push(e);continue}if(!t)continue;const s=ic.exec(t);if(!s){a=!1,n.push(e);continue}const[,i,o,l]=s,c=o.startsWith("artifact:")?o.slice(9):void 0;r.push({id:`${o}-${r.length}`,name:i,href:o,artifactPath:c,contentType:l?.toLowerCase().includes("image")?"image/*":void 0})}return{body:n.join("\n").trim(),attachments:r}}const lc=qe(function({message:n,batchData:a,isRunning:s=!1,className:o,headerClassName:l,senderClassName:c,progressBarClassName:d,itemListClassName:u,itemClassName:h,summaryClassName:f}){const[g,v]=Oe(!1),b=p(),{t:x}=Ze(),{tool_name:y,total:w,completed:N,succeeded:k,failed:_,items:C,started_at:S,completed_at:T}=a,I=w>0?N/w*100:0,z=_>0,R=N===w&&!s,j=s||!R?"running":_===w?"error":_>0?"warning":"completed",P=((T?T-S:Date.now()-S)/1e3).toFixed(1);return t("div",{className:i("border-s-4 shadow-md overflow-hidden bg-white dark:bg-gray-900 mb-5","completed"===j?"border-s-success":"error"===j?"border-s-destructive":"warning"===j?"border-s-attention":"border-s-blue-500",o),children:[t("div",{role:"button",tabIndex:0,"aria-expanded":g,className:i("flex items-center justify-between px-4 py-2 border-b border-gray-100/80 dark:border-gray-800/80 bg-blue-50/50 dark:bg-blue-900/10 cursor-pointer",l),onClick:()=>v(!g),onKeyDown:m(()=>v(!g)),children:[t("div",{className:"flex items-center gap-2",children:[s||!R?e(Vl,{size:"sm",color:"blue"}):"completed"===j?e(Rt,{className:"size-4 text-success"}):"error"===j||"warning"===j?e(jt,{className:"size-4 text-destructive"}):e(Ot,{className:"size-4 text-purple-600"}),e("span",{className:i("text-xs font-medium text-muted",c),children:x("agent.batch")}),e("span",{className:"text-xs text-blue-600 dark:text-blue-400 font-medium",children:y}),t("span",{className:"text-xs text-muted",children:[N,"/",w]}),g?e(Ft,{className:"size-3 text-muted"}):e(ht,{className:"size-3 text-muted cn-rtl-flip"})]}),t("div",{className:"flex items-center gap-2",children:[t("span",{className:"text-xs text-muted",children:[P,"s"]}),e("span",{className:"text-xs text-muted",children:Dr(S).format("HH:mm:ss")}),e(r,{variant:"ghost",size:"xs",onClick:e=>{e.stopPropagation(),(()=>{const e=JSON.stringify(a,null,2);navigator.clipboard.writeText(e).then(()=>{b({status:"success",title:x("agent.copiedBatchDetails"),duration:2e3})})})()},className:"text-muted",title:x("agent.copyBatchDetails"),children:e(vt,{className:"size-3"})})]})]}),e("div",{className:i("px-4 py-2 bg-gray-50/50 dark:bg-gray-800/30",d),children:t("div",{className:"flex items-center gap-3",children:[e("div",{className:"flex-1 h-2 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden",children:e("div",{className:`h-full ${z?"bg-attention":R?"bg-success":"bg-blue-500"} transition-all duration-300 ease-out`,style:{width:`${I}%`}})}),t("div",{className:"flex items-center gap-2 text-xs",children:[k>0&&t("span",{className:"text-success flex items-center gap-1",children:[e(Rt,{className:"size-3"}),k]}),_>0&&t("span",{className:"text-destructive flex items-center gap-1",children:[e(jt,{className:"size-3"}),_]}),s&&N<w&&t("span",{className:"text-blue-500 flex items-center gap-1",children:[e(st,{className:"size-3 animate-spin"}),w-N]})]})]})}),g&&C.length>0&&e("div",{className:i("max-h-64 overflow-y-auto",u),children:C.map(n=>t("div",{className:i("flex items-center gap-2 px-4 py-1.5 text-xs border-b border-gray-100 dark:border-gray-800 last:border-b-0 hover:bg-gray-50 dark:hover:bg-gray-800/50",h),children:[t("div",{className:"w-4 flex-shrink-0",children:["success"===n.status&&e(Rt,{className:"size-3 text-success"}),"error"===n.status&&e(jt,{className:"size-3 text-destructive"}),"running"===n.status&&e(st,{className:"size-3 text-blue-500 animate-spin"}),"pending"===n.status&&e("div",{className:"size-3 rounded-full border border-gray-300 dark:border-gray-600"})]}),e("span",{className:"font-mono text-muted w-24 truncate flex-shrink-0",title:n.id,children:n.id}),e("span",{className:"text-muted truncate flex-1",title:n.message,children:n.message||("pending"===n.status?x("agent.waiting"):"")}),void 0!==n.duration_ms&&t("span",{className:"text-muted flex-shrink-0",children:[(n.duration_ms/1e3).toFixed(1),"s"]})]},n.id))}),!g&&n.message&&e("div",{className:i("px-4 py-2 text-xs text-muted",f),children:n.message})]})},(e,t)=>e.isRunning===t.isRunning&&(e.batchData.completed===t.batchData.completed&&(e.batchData.succeeded===t.batchData.succeeded&&e.batchData.failed===t.batchData.failed))),cc={sending:{icon:Wt,className:"text-muted/70"},received:{icon:it,className:"text-info"},consumed:{icon:Ut,className:"text-success"},failed:{icon:jt,className:"text-destructive"}};function dc(e){if(e.type!==ir.QUESTION&&!rl(e))return;const t=e.details?._deliveryStatus;return"sending"===(n=t)||"received"===n||"consumed"===n||"failed"===n?t:e.details?.ack?"consumed":void 0;var n}function uc({message:t,className:n}){const{t:r}=Ze(),a=dc(t);if(!a)return null;const s=cc[a],o=s.icon,l=function(e,t){switch(t){case"sending":return e("agent.messageSending");case"received":return e("agent.messageReceived");case"consumed":return e("agent.messageConsumed");case"failed":return e("agent.messageFailed")}return t}(r,a);return e(h,{description:l,asChild:!0,children:e("span",{"aria-label":l,className:i("inline-flex h-5 w-5 items-center justify-center",s.className,n),role:"img",children:e(o,{className:"size-3.5","aria-hidden":"true"})})})}function mc({client:e,toast:t}){const n=Xe.getFixedT(null,et),[r,a]=Oe(!1),s=Ve(async(r,s)=>{if(r){a(!0);try{pc((await e.files.getDownloadUrlWithOptions({file:r,name:s})).url,s)}catch(e){t({status:"error",title:n("store.downloadFailed"),description:e instanceof Error?e.message:n("store.failedToGetDownloadUrl"),duration:5e3})}finally{a(!1)}}},[e,t,n]),i=Ve((e,t)=>{e&&pc(e,t)},[]),o=Ve(async(t,n)=>{const r="store"in e?e.store:e,a=await r.rendering.render(t);if(a.download_url)pc(a.download_url,n);else{if(!a.file_uri)throw new Error("No download URL or file URI in response");pc((await e.files.getDownloadUrlWithOptions({file:a.file_uri,name:n})).url,n)}},[e]);return{downloadFromContentSource:s,downloadFromUrl:i,renderDocument:Ve(async(e,r)=>{a(!0);try{const a=`${r.title||"document"}.${r.format}`;await o({object_id:e,format:r.format,title:r.title,pandoc_options:r.pandocOptions,use_default_template:r.useDefaultTemplate,template_path:r.templateObjectId?`store:${r.templateObjectId}`:void 0},a),t({status:"success",title:n("store.documentExported"),description:n("store.successfullyExportedTo",{format:r.format.toUpperCase()}),duration:2e3})}catch(e){t({status:"error",title:n("store.exportFailed"),description:e instanceof Error?e.message:n("store.failedToExportDocument"),duration:5e3})}finally{a(!1)}},[o,t,n]),renderContent:Ve(async(e,r)=>{a(!0);try{const a=`${r.title||"export"}.${r.format}`;await o({content:e,format:r.format,title:r.title,artifact_run_id:r.artifactRunId,pandoc_options:r.pandocOptions},a),t({status:"success",title:n("store.contentExported"),description:n("store.successfullyExportedTo",{format:r.format.toUpperCase()}),duration:2e3})}catch(e){t({status:"error",title:n("store.exportFailed"),description:e instanceof Error?e.message:n("store.failedToExportContent"),duration:5e3})}finally{a(!1)}},[o,t,n]),isDownloading:r}}function pc(e,t){fetch(e).then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}`);return e.blob()}).then(n=>{const r=URL.createObjectURL(n),a=document.createElement("a");a.href=r,a.download=t||hc(e),a.style.display="none",document.body.appendChild(a),a.click(),setTimeout(()=>{document.body.removeChild(a),URL.revokeObjectURL(r)},100)}).catch(()=>{const n=document.createElement("a");n.href=e,n.download=t||hc(e),n.target="_blank",n.rel="noopener noreferrer",n.style.display="none",document.body.appendChild(n),n.click(),setTimeout(()=>{document.body.removeChild(n)},100)})}function hc(e){try{const t=new URL(e).pathname.split("/");return t[t.length-1]||"download"}catch{return"download"}}function fc(e){return void 0!==e&&e>="0"&&e<="9"}function gc(e){return" "===e||"\t"===e}function vc(e,t){if(t>0&&fc(e[t-1]))return;let n=t;for(;fc(e[n]);)n++;if(n===t||"."!==e[n])return;n++;const r=n;for(;gc(e[n]);)n++;return n>r&&(void 0!==(a=e[n])&&" "!==a&&"\t"!==a&&"\n"!==a&&"\r"!==a)?n:void 0;var a}function bc(e,t){for(let n=t;n<e.length;n++)if(void 0!==vc(e,n))return n;return-1}function xc(e){const t=bc(e,0);if(-1===t)return e;let n=e.slice(0,t),r=t;for(;-1!==r;){const t=bc(e,vc(e,r)??r+1);if(-1===t){n+=e.slice(r),n+="\n\n";break}let a=t;for(;a>r&&gc(e[a-1]);)a--;n+=e.slice(r,a),n+="\n\n",r=t}return n}function yc(e){if(!e.includes("\n"))return e;const t=e.split("\n");let n=!1;return t.map(e=>{const t=n&&e.length>=2&&!fc(e[0])&&":"!==e[1]?` ${e}`:e;return n=function(e){let t=0;for(;gc(e[t]);)t++;return void 0!==vc(e,t)}(e),t}).join("\n")}const wc=["className","cardClassName","headerClassName","contentClassName","timestampClassName","senderClassName","iconClassName","detailsClassName","artifactsClassName","proseClassName"];function Nc(e,t,...n){const r={};for(const a of wc)r[a]=i(e[a],t[a],...n.map(e=>e?.[a]));return r}const kc={Ready:"agent.ready",Error:"agent.error"},_c={[ir.ANSWER]:{borderColor:"border-s-info",iconColor:"text-info",sender:"Agent",Icon:Bt},[ir.COMPLETE]:{borderColor:"border-s-success",iconColor:"text-success",sender:"Completed",Icon:Rt},[ir.IDLE]:{borderColor:"border-s-info",iconColor:"text-info",sender:"Ready",Icon:Wt},[ir.REQUEST_INPUT]:{borderColor:"border-s-attention",iconColor:"text-attention",sender:"Input",Icon:Ht},[ir.QUESTION]:{borderColor:"border-s-muted",iconColor:"text-muted",sender:"User",Icon:Ht},[ir.THOUGHT]:{borderColor:"border-s-purple-500",iconColor:"text-purple-600 dark:text-purple-400",sender:"Agent",Icon:Bt},[ir.ERROR]:{borderColor:"border-s-destructive",iconColor:"text-destructive",sender:"Error",Icon:jt},[ir.UPDATE]:{borderColor:"border-s-success",iconColor:"text-success",sender:"Update",Icon:qt},[ir.PLAN]:{borderColor:"border-s-attention",iconColor:"text-attention",sender:"Plan",Icon:Tt},[ir.TERMINATED]:{borderColor:"border-s-muted",iconColor:"text-muted",sender:"Terminated",Icon:Rt},[ir.WARNING]:{borderColor:"border-s-attention",iconColor:"text-attention",sender:"Warning",Icon:jt},[ir.SYSTEM]:{borderColor:"border-s-muted",iconColor:"text-muted",sender:"System",Icon:qt},[ir.STREAMING_CHUNK]:{borderColor:"border-s-info",iconColor:"text-info",sender:"Agent",Icon:Bt},[ir.BATCH_PROGRESS]:{borderColor:"border-s-blue-500",iconColor:"text-blue-600 dark:text-blue-400",sender:"Batch",Icon:Ot},[ir.RESTARTING]:{borderColor:"border-s-attention",iconColor:"text-attention",sender:"Restarting",Icon:Vt},default:{borderColor:"border-s-muted",iconColor:"text-muted",sender:"Agent",Icon:Bt}};const Cc=qe(function({message:n,showPulsatingCircle:a=!1,onSendMessage:s,requestInputAnswered:o=!1,className:l,cardClassName:c,headerClassName:d,contentClassName:u,timestampClassName:m,senderClassName:h,iconClassName:b,detailsClassName:x,artifactsClassName:y,proseClassName:w,messageStyleOverrides:N,StoreLinkComponent:k,CollectionLinkComponent:_}){const[C,S]=Oe(!1),{t:T}=Ze(),{client:I}=tr(),z=p(),R=Za(),{openImage:j}=Ql(),{router:P}=aa(),A=Be(I);A.current=I;const D=Be(R);D.current=R;const{renderContent:E,isDownloading:$}=mc({client:I,toast:z}),L=Fe(()=>{const e=_c[n.type]||_c.default,t=N?.default,r=N?.[n.type];return{...e,...t,...r,...Nc(e,{className:l,cardClassName:c,headerClassName:d,contentClassName:u,timestampClassName:m,senderClassName:h,iconClassName:b,detailsClassName:x,artifactsClassName:y,proseClassName:w},t,r)}},[n.type,N,l,c,d,u,m,h,b,x,y,w]),M=Fe(()=>{let e="";if(n.message&&(e="object"==typeof n.message?JSON.stringify(n.message,null,2):n.message.trim?n.message.trim():String(n.message)),"string"==typeof e&&e.includes("%thinking_message%")){const t=Math.floor(Math.random()*Kl.length);e=e.replace(/%thinking_message%/g,Kl[t])}return e},[n.message]),F=Fe(()=>n.type===ir.QUESTION?oc(M):null,[M,n.type]),O=F?.body??M,U=F?.attachments??[],W=Fe(()=>O?function(e,t,n){if("string"!=typeof e)return e;if(t===ir.THOUGHT||"string"==typeof n&&(n.toLowerCase().includes("thinking about")||n.toLowerCase().includes("i'm thinking")||n.toLowerCase().includes("💭"))){let t=e;return t=yc(xc(t)),t.includes(":")&&!t.includes("\n\n")&&(t=t.replace(/\b(First|Next|Then|Finally|Lastly|Additionally|Step \d+):\s+/gi,"\n\n$&")),t.includes(" - ")&&(t=t.replace(/(^|\S)\s+-\s+/g,"$1\n- ")),t}return e.includes("\n\n")?e:xc(e)}(O,n.type,"string"==typeof n.message?n.message:void 0):"",[O,n.type,n.message]),B=async e=>{const t="string"==typeof M?M:"";if(!t.trim())return void z({status:"error",title:T("agent.noContentToExport"),duration:2e3});const r=`Message ${Dr(n.timestamp).format("YYYY-MM-DD HH-mm-ss")}`;await E(t,{format:e,title:r,artifactRunId:K})},V="string"==typeof M&&M.trim().length>0,q=Fe(()=>({a:({node:t,ref:n,...r})=>{const a=r.href||"",s=a.startsWith("/")?P.getTopRouter().navigator.addStickyParams(a):a;if(a.includes("/store/objects")){if(k){const t=a.split("/store/objects/")[1]||"";return e(k,{href:s,documentId:t,children:r.children})}return e(sa,{href:s,topLevelNav:!0,children:r.children})}if(a.includes("/store/collections")){if(_){const t=a.split("/store/collections/")[1]||"";return e(_,{href:s,collectionId:t,children:r.children})}return e(sa,{href:s,topLevelNav:!0,children:r.children})}return e("a",{...r,target:"_blank",rel:"noopener noreferrer"})},img:({node:t,ref:n,...a})=>e(r,{variant:"unstyled",className:"block p-0",onClick:()=>a.src&&j(a.src,a.alt),"aria-label":a.alt||a.src||"image",children:e("img",{...a,alt:a.alt??"",className:"max-w-full h-auto rounded-lg shadow-md my-3 cursor-pointer hover:shadow-lg transition-shadow",loading:"lazy"})})}),[j,k,_,P]),H=t=>{if("object"==typeof t)return e("pre",{className:"text-xs font-mono whitespace-pre-wrap overflow-x-auto bg-gray-100 dark:bg-gray-800 p-2 rounded text-gray-700",children:JSON.stringify(t,null,2)});const r=n.workflow_run_id;return!r&&"string"==typeof t&&t.includes("artifact:")&&console.warn("[MessageItem] message contains artifact references but workflow_run_id is missing!",{type:n.type,workflow_run_id:n.workflow_run_id,hasArtifact:t.includes("artifact:")}),e("div",{className:i("vprose prose prose-slate dark:prose-invert prose-p:leading-relaxed prose-p:my-3 prose-headings:font-semibold prose-headings:tracking-normal prose-headings:mt-6 prose-headings:mb-3 prose-h1:text-xl prose-h2:text-lg prose-h3:text-base prose-li:my-1 prose-ul:my-3 prose-ol:my-3 prose-table:my-5 prose-pre:my-4 prose-hr:my-6 max-w-none text-[15px] break-words",L.proseClassName),style:{overflowWrap:"anywhere"},children:e(oa,{artifactRunId:r,onProposalSelect:e=>s?.(e),onProposalSubmit:e=>s?.(e),components:q,children:t})})},[G,J]=Oe([]),K=n.workflow_run_id,Y=n.details,Q=Y?.outputFiles??Y?.files;He(()=>{(async()=>{if(!K||!Array.isArray(Q)||0===Q.length)return void J([]);const e=A.current,t=D.current;try{const n=await Promise.all(Q.map(async n=>{if("string"!=typeof n||!n.trim())return null;const r=n.trim(),a=r.startsWith("artifact:")?r.slice(9):r,s=a.split(".").pop()?.toLowerCase()||"",i=new Set(["png","jpg","jpeg","gif","webp","bmp","svg"]).has(s),o=i?"inline":"attachment";try{const n=es(K,a,o);let s;if(t)s=await t.getOrFetch(n,async()=>(await e.files.getArtifactDownloadUrl(K,a,o)).url);else{s=(await e.files.getArtifactDownloadUrl(K,a,o)).url}return{displayName:r,artifactPath:a,url:s,isImage:i}}catch(e){return console.error(`Failed to resolve artifact URL for ${a}`,e),null}}));J(n.filter(e=>!!e))}catch(e){console.error("Error loading artifact URLs from message details",e),J([])}})()},[K,Q]);const Z=sl(n),{Icon:X}=L;return e("div",{className:i("w-full max-w-full",L.className),children:t("div",{className:i("border-s-4 bg-white dark:bg-gray-900 mb-4 w-full max-w-full overflow-hidden",L.borderColor,L.cardClassName),"data-workstream-id":Z,children:[t("div",{className:i("flex items-center justify-between px-4 py-1.5",L.headerClassName),children:[t("div",{className:"flex items-center gap-1.5",children:[e("div",{className:i(a?"animate-fadeIn":"",L.iconClassName),children:a?e(Vl,{size:"sm",color:"blue"}):e(X,{className:`size-4 ${L.iconColor}`})}),e("span",{className:i("text-xs font-medium text-muted",L.senderClassName),children:kc[L.sender]?T(kc[L.sender]):L.sender}),"main"!==Z&&"all"!==Z&&e(f,{variant:"default",className:"text-xs text-muted ms-1",children:Z})]}),t("div",{className:"flex items-center gap-1.5 print:hidden",children:[e(uc,{message:n}),e("span",{className:i("text-[11px] text-muted/70",L.timestampClassName),children:Dr(n.timestamp).format("HH:mm:ss")}),e(r,{variant:"ghost",size:"xs",onClick:()=>{const e=M||"",t="string"==typeof n.details?n.details:n.details?JSON.stringify(n.details,null,2):"",r=[e,t?`\n\nDetails:\n${t}`:""].join("").trim();navigator.clipboard.writeText(r).then(()=>{z({status:"success",title:T("agent.copiedToClipboard"),duration:2e3})})},className:"text-muted/50 hover:text-muted h-5 w-5 p-0",title:T("agent.copyMessage"),children:e(vt,{className:"size-3"})}),V&&t(g,{trigger:e(r,{variant:"ghost",size:"xs",className:"text-muted/50 hover:text-muted h-5 w-5 p-0",title:T("agent.exportMessage"),disabled:$,children:e(lt,{className:"size-3 "+($?"animate-pulse":"")})}),children:[e(v,{onClick:()=>B(or.pdf),children:T("agent.exportAsPdf")}),e(v,{onClick:()=>B(or.docx),children:T("agent.exportAsWord")})]})]})]}),t("div",{className:i("px-4 pb-3 bg-white dark:bg-gray-900 overflow-hidden",L.contentClassName),children:[n.type===ir.REQUEST_INPUT&&n.details?.ux?(()=>{const t=n.details.ux;return e(Wo,{question:"string"==typeof M?M:"",options:t.options,variant:t.variant,multiSelect:t.multiSelect,onSelect:e=>s?.(e,Al(n,e)),onMultiSelect:e=>s?.(e.join(", ")),allowFreeResponse:!t.options?.length||!!t.free_response,placeholder:t.free_response?.placeholder,submitLabel:t.free_response?.submit_label,onSubmit:e=>s?.(e,t.free_response?.metadata),hideBorder:!0,compact:!0,answered:o})})():O&&e("div",{className:"message-content break-words w-full",style:{overflowWrap:"anywhere",wordBreak:"break-word"},children:H(W||O)}),U.length>0&&e(ac,{items:U,artifactRunId:K,variant:"message",className:i(O&&"mt-3"),StoreLinkComponent:k,CollectionLinkComponent:_}),G.length>0&&t("div",{className:i("mt-3 text-xs",L.artifactsClassName),children:[e("div",{className:"font-medium text-muted mb-1",children:"Artifacts"}),G.some(e=>e.isImage)&&e("div",{className:"mb-2 flex flex-wrap gap-3",children:G.filter(e=>e.isImage).map(({displayName:n,artifactPath:a,url:s})=>t(r,{variant:"unstyled",className:"max-w-xs cursor-pointer text-start p-0",onClick:()=>j(s,n),"aria-label":n,children:[e("img",{src:s,alt:n,className:"max-w-full h-auto rounded-lg shadow-sm hover:shadow-md transition-shadow"}),e("div",{className:"mt-1 text-[11px] text-muted truncate",children:n})]},`${a}-preview`))}),e("div",{className:"flex flex-wrap gap-2 print:hidden",children:G.map(({displayName:t,artifactPath:n,url:a})=>e(r,{variant:"outline",size:"xs",className:"px-2 py-1 text-xs",onClick:()=>window.open(a,"_blank"),title:n,children:t},n+a))})]}),n.details&&t("div",{className:i("mt-2 print:hidden",L.detailsClassName),children:[t(r,{variant:"unstyled",onClick:()=>S(!C),className:"text-[11px] text-muted flex items-center",children:[T(C?"agent.hideDetails":"agent.showDetails"),e("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-3 w-3 ms-1 transition-transform "+(C?"rotate-180":""),fill:"none",viewBox:"0 0 24 24",stroke:"currentColor","aria-hidden":"true",children:e("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),C&&e("div",{className:"mt-1 p-1.5 bg-muted border border-mixer-muted/40 rounded text-sm",children:"string"==typeof n.details?H(n.details):e("pre",{className:"text-xs font-mono whitespace-pre-wrap overflow-x-auto bg-muted p-2 rounded text-muted",children:JSON.stringify(n.details,null,2)})})]})]})]})})},(e,t)=>e.message.timestamp===t.message.timestamp&&e.message.type===t.message.type&&e.message.message===t.message.message&&e.message.details===t.message.details&&e.message.workstream_id===t.message.workstream_id&&e.message.workflow_run_id===t.message.workflow_run_id&&e.showPulsatingCircle===t.showPulsatingCircle&&e.onSendMessage===t.onSendMessage&&e.requestInputAnswered===t.requestInputAnswered&&e.messageStyleOverrides===t.messageStyleOverrides&&wc.every(n=>e[n]===t[n]));const Sc=Me.memo(function({text:n,workstreamId:a,artifactRunId:s,revealSpeed:o=300,isComplete:l=!1,timestamp:c,className:d,cardClassName:u,headerClassName:m,contentClassName:h,proseClassName:f,senderClassName:g,iconClassName:v}){const{t:b}=Ze(),[x,y]=Oe(0),[w,N]=Oe(""),k=Be(null),_=Be(n.length),C=Be(0),S=Be(c||Date.now()),T=Be(n),I=Be(0),z=Be(performance.now()),R=Be(o),j=Be(0);He(()=>{const e=performance.now(),t=n.length-I.current,r=e-z.current;if(t>0&&r>30){const e=t/r*1e3,n=.2;R.current=R.current*(1-n)+e*n,R.current=Math.max(50,Math.min(2e3,R.current))}I.current=n.length,z.current=e},[n.length]),_.current=n.length,T.current=n;const P=Ve(()=>{let e=performance.now();const t=n=>{const r=n-e;e=n;const a=_.current-C.current;if(a<=0)return j.current=0,void(k.current=null);let s;if(l)s=Math.max(500,2*R.current);else if(a<20)s=.85*R.current;else if(a<100)s=R.current;else if(a<500){const e=(a-100)/400;s=R.current*(1+.5*e)}else s=2*R.current;const i=s*r/1e3+j.current,o=Math.floor(i);j.current=i-o,o>0&&(C.current=Math.min(C.current+o,_.current),y(C.current)),k.current=requestAnimationFrame(t)};k.current=requestAnimationFrame(t)},[l]);He(()=>(n.length>C.current&&!k.current&&P(),()=>{k.current&&(cancelAnimationFrame(k.current),k.current=null)}),[n.length,P]),He(()=>{l&&C.current<n.length&&(k.current&&(cancelAnimationFrame(k.current),k.current=null),P())},[l,n.length,P]);const A=Be(null),D=Be(0);He(()=>{(x>=_.current||l)&&(N(T.current.slice(0,x)),D.current=x)},[x,l]);const E=x<n.length&&!l;He(()=>{if(E)return A.current||(A.current=window.setInterval(()=>{const e=C.current;e>D.current&&(N(T.current.slice(0,e)),D.current=e)},33)),()=>{A.current&&(clearInterval(A.current),A.current=null)};A.current&&(clearInterval(A.current),A.current=null)},[E]);const $=p(),L=Fe(()=>Dr(S.current).format("HH:mm:ss"),[]),M=x<n.length,F=Fe(()=>{const e=w||n.slice(0,x);return M?e+"│":e},[w,n,x,M]);return n?e("div",{className:i("w-full max-w-full",d),children:t("div",{className:i("border-s-4 bg-white dark:bg-gray-900 mb-4 border-s-purple-500 w-full max-w-full overflow-hidden",u),"data-workstream-id":a,children:[t("div",{className:i("flex items-center justify-between px-4 py-1.5",m),children:[t("div",{className:"flex items-center gap-1.5",children:[e("div",{className:i("animate-fadeIn",v),children:M?e("span",{className:"size-2 rounded-full bg-blue-500 animate-pulse inline-block"}):e(Bt,{className:"size-4 text-purple-600 dark:text-purple-400"})}),e("span",{className:i("text-xs font-medium text-muted",g),children:"Agent"}),a&&"main"!==a&&t("span",{className:"text-xs text-muted",children:["• Task ",a]})]}),t("div",{className:"flex items-center gap-2 text-muted",children:[e("span",{className:"text-[11px]",children:L}),e(r,{variant:"ghost",size:"xs",onClick:()=>{navigator.clipboard.writeText(n).then(()=>{$({status:"success",title:b("agent.copiedToClipboard"),duration:2e3})})},className:"size-6 p-0 hover:bg-gray-100 dark:hover:bg-gray-800",title:b("agent.copyMessage"),children:e(vt,{className:"size-3"})})]})]}),t("div",{className:i("px-3 pb-2 streaming-content",M&&"streaming-active",h),children:[e("div",{className:i("vprose prose prose-slate dark:prose-invert prose-p:leading-relaxed prose-p:my-3 prose-headings:font-semibold prose-headings:tracking-normal prose-headings:mt-6 prose-headings:mb-3 prose-h1:text-xl prose-h2:text-lg prose-h3:text-base prose-li:my-1 prose-ul:my-3 prose-ol:my-3 prose-table:my-5 prose-pre:my-4 prose-hr:my-6 max-w-none text-[15px] break-words",f),style:{overflowWrap:"anywhere"},children:e(oa,{artifactRunId:s,children:F})}),e("style",{children:"\n /* Ensure inline elements flow properly */\n .streaming-content p:last-child,\n .streaming-content li:last-child {\n display: inline;\n }\n /* Soft fade at reveal edge */\n .streaming-active .vprose {\n mask-image: linear-gradient(to right, black 97%, transparent 100%);\n -webkit-mask-image: linear-gradient(to right, black 97%, transparent 100%);\n }\n "})]})]})}):null});function Tc(e){return e.message?"object"==typeof e.message?JSON.stringify(e.message,null,2):String(e.message).trim():""}function Ic(e){return e.type===ir.THOUGHT&&"thinking"===e.details?.display_role}function zc(e){if(Ic(e))return!0;if(e.type!==ir.WARNING)return!1;const t=e.details,n=Tc(e).replace(/^[^A-Za-z0-9]+/,"").toLowerCase();return"number"==typeof t?.attempt&&"number"==typeof t?.maxAttempts&&"number"==typeof t?.estimatedBackoffSeconds&&"string"==typeof t?.activityId&&(n.startsWith("retrying operation")||n.startsWith("retrying checkpoint operation"))}function Rc(e){if("number"==typeof e)return e;if(!e)return-1/0;const t=new Date(e).getTime();return Number.isFinite(t)?t:-1/0}function jc(e,t){const n=e.details?.[t];if("string"!=typeof n)return;const r=n.trim();return r||void 0}function Pc(e){if(Jo(e))return!1;const t=Tc(e);return!(!t||function(e){const t=e.replace(/\s+/g," ").trim().toLowerCase();return"thinking"===t||"thinking..."===t||"working"===t||"working..."===t||"waiting"===t||"waiting..."===t}(t))&&(e.type===ir.ANSWER||!hl(e)&&(e.type===ir.THOUGHT&&Boolean(e.details?.streamed)))}function Ac(e){if(e.type!==ir.ERROR&&e.type!==ir.WARNING)return!1;const t=e.details;return Boolean(t?.tool||t?.tool_status||t?.tool_run_id||t?.activity_group_id||t?.tool_event)}function Dc(e){if(e.type!==ir.ERROR||Ac(e))return!1;const t=e.details;return Tc(e).startsWith("Error analyzing conversation:")&&"string"==typeof t?.error}function Ec(e){if(e.type!==ir.ERROR)return!1;const t=e.details;return"activity"===t?.event_class&&(!t.workstream_event&&!(t.tool||t.tool_status||t.tool_run_id||t.activity_group_id||t.tool_event))}function $c(e){return!Jo(e)&&(!Ec(e)&&(e.type===ir.QUESTION||Boolean(Yo(e))||Pc(e)||e.type===ir.REQUEST_INPUT&&!jl(e)||e.type===ir.TERMINATED||(e.type===ir.ERROR||e.type===ir.WARNING)&&!Ac(e)&&!zc(e)))}function Lc(e){const t=e.details?.tool_status;return"running"===t||"completed"===t||"error"===t||"warning"===t?t:e.type===ir.ERROR?"error":e.type===ir.WARNING?"warning":void 0}function Mc(e,t){return fl(e)&&!Ic(e)&&t.length>0&&t.every(Ic)}function Fc(e){return!Jo(e)&&(!Pc(e)&&(!Yo(e)&&(!!Ec(e)||(!!zc(e)||(!!jl(e)||(!!Ac(e)||(!!hl(e)||(!!fl(e)||(e.type===ir.UPDATE||e.type===ir.PLAN||e.type===ir.THOUGHT&&!e.details?.streamed)))))))))}function Oc(e,t,n=function(e){return e.reduce((e,t)=>Math.max(e,Rc(t.timestamp)),-1/0)}(e)){const r=[];let a=[];const s=new Set,i=(e,t)=>{if(0===a.length)return;const s=function(e,t,n){if(!e.some(zc))return e;if(!t)return e.filter(e=>!zc(e));let r=-1,a=-1;return e.forEach((e,t)=>{zc(e)?a=t:r=t}),e.filter((e,t)=>!zc(e)||t===a&&t>r&&Rc(e.timestamp)>=n)}(a,e,n);if(0===s.length)return void(a=[]);const i=s[0],o=s[s.length-1],l=function(e,t){for(let n=e.length-1;n>=0;n--){const r=Lc(e[n]);if("error"===r||"warning"===r)return r;if(r)return t?"running":"completed"}return t?"running":"completed"}(s,e);r.push({type:"work",id:e?`${i.timestamp}-active`:`${i.timestamp}-${o.timestamp}-${s.length}`,messages:s,isActive:e,status:l,startTimestamp:i.timestamp,endTimestamp:t?.timestamp??o.timestamp}),a=[]};for(const t of e){const e=Yo(t),n=e?null:Qo(t),o=e??n;if(o){const n=s.has(o.workstreamId);if(s.add(o.workstreamId),e||!n){i(!1,t),r.push({type:"message",message:t});continue}}if(t.type!==ir.COMPLETE&&t.type!==ir.IDLE)if(Fc(t)||a.length>0&&Dc(t)){if(Mc(t,a)){const e=r[r.length-1];if("work"===e?.type&&!e.isActive){r.pop(),a=[...e.messages,t];continue}}a.push(t)}else $c(t)&&(i(!1,t),r.push({type:"message",message:t}));else{if(rl(t)){const e=a[0]?.timestamp;i(!1,t);const n=r[r.length-1];r.push({type:"stopped",message:t,startTimestamp:void 0!==e&&"work"===n?.type?n.startTimestamp:e??t.timestamp,endTimestamp:t.timestamp});continue}i(!1,t)}}return i(!t),r}function Uc(e,t){if(0===t.size)return e;const n=e.find(e=>e.workflow_run_id)?.workflow_run_id??"",r=[];return t.forEach((t,a)=>{const s=t.text.trim();if(!s||ul(t,e))return;if(Go(s,t.workstreamId))return;const i=function(e,t){if(e.activityId){const n=t.find(t=>fl(t)&&(jc(t,"activity_id")===e.activityId||jc(t,"activity_group_id")===e.activityId));if(n)return n;const r=t.find(t=>jc(t,"activity_id")===e.activityId&&jc(t,"activity_group_id"))?.details?.activity_group_id;if("string"==typeof r){const e=t.find(e=>fl(e)&&jc(e,"activity_group_id")===r);if(e)return e}}if(e.isComplete)return;const n=Rc(e.startTimestamp);if(!Number.isFinite(n))return;const r=[...t].filter(e=>Rc(e.timestamp)>=n).sort((e,t)=>Rc(e.timestamp)-Rc(t.timestamp));for(const e of r){if(Rc(e.timestamp)-n>6e4)return;if(fl(e))return e;if($c(e))return}}(t,e),o=i?jc(i,"activity_group_id"):void 0;r.push({timestamp:t.startTimestamp,workflow_run_id:n,type:i?ir.THOUGHT:ir.ANSWER,message:s,workstream_id:t.workstreamId,details:{activity_id:t.activityId,activity_group_id:o,display_role:i?"tool_preamble":void 0,source:"streaming_summary",streamed:!0,streaming_id:a,tools:i?.details?.tool?[i.details.tool]:void 0}})}),0===r.length?e:[...e,...r].sort((e,t)=>Rc(e.timestamp)-Rc(t.timestamp))}const Wc=new Set(["tool","tool_event","tool_run_id","tool_use_id","activity_group_id","event_class","tool_iteration","tool_status","message_to_human","tools","streamed","files","outputFiles","display_role","observation","progress_messages","browseruse","browser_use"]);function Bc(e){return e?Object.entries(e).filter(([e,t])=>!Wc.has(e)&&null!=t&&""!==t):[]}function Vc(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/^./,e=>e.toUpperCase())}function qc(e){const t=e?.progress_messages;return Array.isArray(t)?t.flatMap(e=>{if(!e||"object"!=typeof e)return[];const t=e,n="string"==typeof t.message?t.message.trim():"";if(!n)return[];return[{message:n,status:"string"==typeof t.status?t.status:void 0,timestamp:"number"==typeof t.timestamp||"string"==typeof t.timestamp?t.timestamp:void 0}]}):[]}function Hc(e){return["progress",e.timestamp??"no-time",e.status??"status",e.message].join(":")}function Gc(e){const t=e.details,n="string"==typeof t?.tool_run_id?t.tool_run_id:void 0;if(n)return`tool-run:${n}`;const r="string"==typeof t?.activity_group_id?t.activity_group_id:void 0,a="string"==typeof t?.tool_use_id?t.tool_use_id:void 0;return r||a?`tool:${r??"no-activity"}:${a??"no-use"}`:["message",e.workstream_id??"main",e.type,e.timestamp,Xc(e)].join(":")}function Jc(e){switch(e){case"completed":return"bg-green-50 dark:bg-green-900/30 text-green-700 dark:text-green-300 border-green-200 dark:border-green-800";case"running":return"bg-blue-50 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 border-blue-200 dark:border-blue-800";case"error":return"bg-red-50 dark:bg-red-900/30 text-red-700 dark:text-red-300 border-red-200 dark:border-red-800";case"warning":return"bg-yellow-50 dark:bg-yellow-900/30 text-yellow-700 dark:text-yellow-300 border-yellow-200 dark:border-yellow-800";default:return""}}const Kc=e=>/\.(png|jpg|jpeg|gif|webp|svg)(\?|$)/i.test(e);function Yc({files:n,className:a}){const{t:s}=Ze(),{openImage:o}=Ql();return n&&0!==n.length?e("div",{className:i("mt-2 flex flex-wrap gap-2",a),children:n.map((n,a)=>{const i=n.split("/").pop()?.split("?")[0]||"file";return Kc(n)?e(r,{variant:"unstyled",className:"cursor-pointer p-0",onClick:()=>o(n,i),title:s("agent.clickToEnlarge"),"aria-label":i,children:e("img",{src:n,alt:i,className:"max-w-[300px] max-h-[200px] rounded border hover:opacity-80 transition-opacity hover:shadow-lg"})},a):t("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 px-2 py-1 bg-muted rounded text-xs hover:bg-muted/80",children:["📎 ",i]},a)})}):null}const Qc=e=>{if(!e)return;const t=e.files??e.outputFiles;return Array.isArray(t)?t:void 0},Zc=e=>{const t=e.details;return e.type===ir.THOUGHT&&"tool_preamble"===t?.display_role},Xc=e=>{const t=e.details;if(Zc(e))return"assistant";if(t?.tool)return t.tool;switch(e.type){case ir.UPDATE:return"update";case ir.WARNING:return"warning";case ir.ERROR:return"error";case ir.SYSTEM:return"system";default:return"activity"}},ed=e=>Zc(e)?"text-[10px] px-1.5 py-0.5 rounded-md bg-gray-50 dark:bg-gray-800 text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-gray-700 font-medium":"text-[10px] px-1.5 py-0.5 rounded-md bg-purple-50 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300 border border-purple-200 dark:border-purple-800 font-medium";function td({message:n,isExpanded:a,onToggle:s,artifactRunId:o,classNames:l={}}){const{t:c}=Ze(),[d,u]=Oe([]),h=p(),{client:f}=tr(),g=Za(),v=Be(f);v.current=f;const b=Be(g);b.current=g;const x=n.details,y=Xc(n),w=ed(n),N=Qc(x),k="string"==typeof n.message?n.message:"";He(()=>{if(!N||0===N.length||!o)return void u([]);let e=!1;return(async()=>{const t=v.current,n=b.current,r=await Promise.all(N.map(async e=>{if(!e||"string"!=typeof e)return null;if(e.startsWith("http://")||e.startsWith("https://"))return e;const r=e.startsWith("artifact:")?e.slice(9):e,a=r.split(".").pop()?.toLowerCase()||"",s=new Set(["png","jpg","jpeg","gif","webp","bmp","svg"]).has(a)?"inline":"attachment";try{const e=es(o,r,s);if(n)return await n.getOrFetch(e,async()=>(await t.files.getArtifactDownloadUrl(o,r,s)).url);return(await t.files.getArtifactDownloadUrl(o,r,s)).url}catch(e){return console.error(`Failed to resolve artifact URL for ${r}`,e),null}}));e||u(r.filter(e=>!!e))})(),()=>{e=!0}},[N,o]);const _=d.filter(e=>Kc(e)),C=d.filter(e=>!Kc(e));return t("div",{className:i("border-b border-gray-100 dark:border-gray-800 last:border-b-0",l.itemClassName),children:[t("div",{role:"button",tabIndex:0,className:i("flex items-start justify-between px-3 py-2 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors",l.itemHeaderClassName),onClick:s,onKeyDown:m(s),children:[t("div",{className:"flex items-start gap-2 flex-1 min-w-0",children:[e("div",{className:"flex-shrink-0 pt-0.5",children:a?e(Ft,{className:"size-3 text-muted"}):e(ht,{className:"size-3 text-muted cn-rtl-flip"})}),e("div",{className:"flex-1 min-w-0",children:k?e("span",{className:"text-xs text-foreground line-clamp-2",children:k}):t("span",{className:"text-xs text-muted italic",children:["Activity: ",y]})})]}),t("div",{className:"flex items-center gap-2 flex-shrink-0",children:[!a&&e("span",{className:i(w,l.toolBadgeClassName),children:y}),e(r,{variant:"ghost",size:"xs",onClick:e=>{e.stopPropagation(),(()=>{const e=[k,x?`\n\nDetails:\n${JSON.stringify(x,null,2)}`:""].join("").trim();navigator.clipboard.writeText(e).then(()=>{h({status:"success",title:c("agent.copiedToClipboard"),duration:2e3})})})()},className:"text-muted opacity-0 group-hover:opacity-100 transition-opacity",title:c("agent.copyMessage"),children:e(vt,{className:"size-3"})})]})]}),_.length>0&&e("div",{className:"px-3 pb-1.5",children:e(Yc,{files:_})}),a&&(()=>{const r=x?.tool_status,a=Bc(x),s=qc(x);return t("div",{className:i("px-4 py-2 bg-gray-50/50 dark:bg-gray-800/30",l.itemContentClassName),children:[t("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[e("span",{className:i(w,l.toolBadgeClassName),children:y}),r&&e("span",{className:i("text-[10px] px-1.5 py-0.5 rounded-md border font-medium",Jc(r)),children:r}),e("span",{className:"text-[10px] text-muted/70",children:Dr(n.timestamp).format("HH:mm:ss")})]}),a.length>0&&e("div",{className:"mb-2 space-y-0.5",children:a.map(([n,r])=>t("div",{className:"flex gap-1.5 text-xs",children:[t("span",{className:"text-muted font-medium flex-shrink-0",children:[Vc(n),":"]}),e("span",{className:"text-foreground break-all",children:"object"==typeof r?JSON.stringify(r):String(r)})]},n))}),s.length>0&&t("div",{className:"mb-2 space-y-1",children:[e("div",{className:"text-[10px] uppercase tracking-wide text-muted/70 font-medium",children:c("agent.progress")}),s.map(n=>t("div",{className:"text-xs text-muted",children:[n.timestamp&&e("span",{className:"me-1 text-muted/60",children:Dr(n.timestamp).format("HH:mm:ss")}),e("span",{children:n.message})]},Hc(n)))]}),(()=>{const t="string"==typeof x?.observation?x.observation:void 0;return t&&t!==k?e("div",{className:"vprose prose prose-slate dark:prose-invert prose-p:leading-relaxed prose-p:my-1.5 max-w-none text-sm",children:e(oa,{artifactRunId:o,children:t})}):null})(),C.length>0&&e(Yc,{files:C})]})})()]})}function nd({files:t,artifactRunId:n}){const[r,a]=Oe([]),{client:s}=tr(),i=Za(),o=Be(s);o.current=s;const l=Be(i);return l.current=i,He(()=>{if(!t||0===t.length||!n)return void a([]);let e=!1;return(async()=>{const r=o.current,s=l.current,i=await Promise.all(t.map(async e=>{if(!e||"string"!=typeof e)return null;const t=e.startsWith("artifact:")?e.slice(9):e,a=t.split(".").pop()?.toLowerCase()||"";if(new Set(["png","jpg","jpeg","gif","webp","bmp","svg"]).has(a))return null;if(t.startsWith("http://")||t.startsWith("https://"))return t;try{const e=es(n,t,"attachment");if(s)return await s.getOrFetch(e,async()=>(await r.files.getArtifactDownloadUrl(n,t,"attachment")).url);return(await r.files.getArtifactDownloadUrl(n,t,"attachment")).url}catch(e){return console.error(`Failed to resolve artifact URL for ${t}`,e),null}}));e||a(i.filter(e=>!!e))})(),()=>{e=!0}},[t,n]),0===r.length?null:e("div",{className:"ps-4 pe-2 pb-1.5",children:e(Yc,{files:r})})}function rd({messages:t,artifactRunId:n}){const[r,a]=Oe([]),{client:s}=tr(),i=Za(),o=Be(s);o.current=s;const l=Be(i);return l.current=i,He(()=>{if(!n||0===t.length)return void a([]);const e=t[t.length-1].details,r=Qc(e);if(!r||0===r.length)return void a([]);let s=!1;return(async()=>{const e=o.current,t=l.current,i=await Promise.all(r.map(async r=>{if(!r||"string"!=typeof r)return null;const a=r.startsWith("artifact:")?r.slice(9):r,s=a.split(".").pop()?.toLowerCase()||"";if(!new Set(["png","jpg","jpeg","gif","webp","bmp","svg"]).has(s))return null;if(a.startsWith("http://")||a.startsWith("https://"))return a;try{const r=es(n,a,"inline");if(t)return await t.getOrFetch(r,async()=>(await e.files.getArtifactDownloadUrl(n,a,"inline")).url);return(await e.files.getArtifactDownloadUrl(n,a,"inline")).url}catch(e){return console.error(`Failed to resolve artifact URL for ${a}`,e),null}}));s||a(i.filter(e=>!!e))})(),()=>{s=!0}},[t,n]),0===r.length?null:e("div",{className:"px-3 py-1.5 border-b border-gray-100 dark:border-gray-800",children:e(Yc,{files:r})})}const ad=qe(function({messages:a,showPulsatingCircle:s=!1,toolRunId:o,toolStatus:l,preambleText:c,preambleMessage:d,rootClassName:u,headerClassName:h,senderClassName:f,toolSummaryClassName:g,toolBadgeClassName:v,itemClassName:b,itemHeaderClassName:x,itemContentClassName:y}){const w=Fe(()=>function(e){const t=new Map,n=[];for(const r of e){const e=r.details?.tool_run_id;e?(t.has(e)||t.set(e,[]),t.get(e)?.push(r)):n.push(r)}for(const[e,r]of t){if(r.length<=1){n.push(...r);continue}r.sort((e,t)=>("number"==typeof e.timestamp?e.timestamp:new Date(e.timestamp).getTime())-("number"==typeof t.timestamp?t.timestamp:new Date(t.timestamp).getTime()));const e=r[r.length-1],t=r.find(e=>"started"===e.details?.tool_event),a=r.find(e=>"running"===e.details?.tool_status),s=t??a??r.find(e=>e.message?.trim()),i=("string"==typeof s?.details?.message_to_human?s.details.message_to_human:void 0)||s?.message||e.message,o=r.filter(e=>"progress"===e.details?.tool_event&&e.message?.trim()).map(e=>({message:e.message.trim(),status:e.details?.tool_status,timestamp:e.timestamp})),l={};for(const e of r)Object.assign(l,e.details);o.length>0&&(l.progress_messages=o),n.push({...e,message:i,details:l})}return n.sort((e,t)=>("number"==typeof e.timestamp?e.timestamp:new Date(e.timestamp).getTime())-("number"==typeof t.timestamp?t.timestamp:new Date(t.timestamp).getTime())),n}(a),[a]),N=Fe(()=>w.map(Gc),[w]),[k,_]=Oe(!0),[C,S]=Oe(new Set),[T,I]=Oe(new Set),z=Be(N),{t:R}=Ze(),j=p(),P=w.find(e=>e.workflow_run_id)?.workflow_run_id??w[0]?.workflow_run_id;He(()=>{const e=z.current,t=new Set(e),n=N.filter(e=>!t.has(e));if(n.length>0){I(new Set(n));const e=setTimeout(()=>{I(new Set)},500);return z.current=N,()=>clearTimeout(e)}z.current=N},[N]);const A=w[0],D=w[w.length-1],E=A.timestamp,$=D.timestamp,L=w.map(e=>Xc(e)),M=1===new Set(L).size?`${w.length}× ${L[0]}`:`${w.length} activity updates`,F=e=>{S(t=>{const n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})};return t("div",{className:i("border-s-4 overflow-hidden bg-white dark:bg-gray-900 mb-4","completed"===l?"border-s-success":"error"===l?"border-s-destructive":"warning"===l?"border-s-attention":"border-s-purple-500",u),children:[t("div",{role:"button",tabIndex:0,"aria-expanded":!k,className:i("flex items-center justify-between px-4 py-1.5 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors",h),onClick:()=>_(!k),onKeyDown:m(()=>_(!k)),children:[t("div",{className:"flex items-center gap-1 flex-1 min-w-0",children:[s?e(Vl,{size:"sm",color:"blue"}):"running"===l?e("span",{className:"size-2 rounded-full bg-blue-500 inline-block"}):"completed"===l?e(Rt,{className:"size-4 text-success"}):"error"===l?e(jt,{className:"size-4 text-destructive"}):"warning"===l?e(Gt,{className:"size-4 text-attention"}):e(Bt,{className:"size-4 text-purple-600 dark:text-purple-400"}),c?e("span",{className:i("text-xs text-foreground line-clamp-2 flex-1 min-w-0",g),children:c}):t(n,{children:[e("span",{className:i("text-xs font-medium text-muted",f),children:"Agent"}),e("span",{className:i("text-xs text-purple-600 dark:text-purple-400 font-medium",g),children:M})]}),k?e(ht,{className:"size-3 text-muted flex-shrink-0 cn-rtl-flip"}):e(Ft,{className:"size-3 text-muted flex-shrink-0"})]}),t("div",{className:"flex items-center gap-1 flex-shrink-0",children:[c&&e("span",{className:i("text-[10px] text-purple-600 dark:text-purple-400 font-medium",g),children:M}),t("span",{className:"text-[11px] text-muted/70",children:[Dr(E).format("HH:mm:ss"),w.length>1&&` - ${Dr($).format("HH:mm:ss")}`]}),e(r,{variant:"ghost",size:"xs",onClick:e=>{e.stopPropagation(),(()=>{const e=w.map(e=>{const t=e.details;return`[${Xc(e)}] ${e.message||""}\n${t?JSON.stringify(t,null,2):""}`}).join("\n\n---\n\n");navigator.clipboard.writeText(e).then(()=>{j({status:"success",title:R("agent.copiedAllToolCalls"),duration:2e3})})})()},className:"text-muted/50 hover:text-muted h-5 w-5 p-0",title:R("agent.copyAllToolCalls"),children:e(vt,{className:"size-3"})})]})]}),e(rd,{messages:w,artifactRunId:P}),k&&e("div",{className:"px-3 py-0.5 space-y-0",children:w.map((n,r)=>{const a=N[r]??Gc(n),s=n.details,o=Xc(n),l=ed(n),c="string"==typeof n.message?n.message:"",d=T.has(a),u=C.has(a),p=Qc(s);return t("div",{className:i("border-b border-gray-100 dark:border-gray-800 last:border-b-0",b),style:{opacity:d?0:1,transform:d?"translateX(-10px)":"translateX(0)",transition:"opacity 0.3s ease-out, transform 0.3s ease-out",transitionDelay:100*(r-(w.length-T.size))+"ms",animation:d?"slideInFade 0.4s ease-out forwards":"none",animationDelay:100*(r-(w.length-T.size))+"ms"},children:[t("div",{role:"button",tabIndex:0,"aria-expanded":u,className:i("flex items-start gap-2 py-1.5 text-xs cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800/50",x),onClick:()=>F(a),onKeyDown:m(()=>F(a)),title:c,children:[e("div",{className:"flex-shrink-0 pt-0.5",children:u?e(Ft,{className:"size-3 text-muted"}):e(ht,{className:"size-3 text-muted cn-rtl-flip"})}),e("div",{className:"flex-1 min-w-0",children:c?e("span",{className:"text-foreground line-clamp-2",children:c}):t("span",{className:"text-muted italic",children:["Activity: ",o]})}),!u&&e("span",{className:i(l,"flex-shrink-0",v),children:o})]}),e(nd,{files:p,artifactRunId:P}),u&&(()=>{const r=s?.tool_status,a=Bc(s),d=qc(s);return t("div",{className:i("ps-5 pe-3 pb-2 text-sm",y),children:[t("div",{className:"flex items-center gap-2 mb-1.5 flex-wrap",children:[e("span",{className:i(l,v),children:o}),r&&e("span",{className:i("text-[10px] px-1.5 py-0.5 rounded-md border font-medium",Jc(r)),children:r}),e("span",{className:"text-[10px] text-muted/70",children:Dr(n.timestamp).format("HH:mm:ss")})]}),a.length>0&&e("div",{className:"mb-1.5 space-y-0.5",children:a.map(([n,r])=>t("div",{className:"flex gap-1.5 text-xs",children:[t("span",{className:"text-muted font-medium flex-shrink-0",children:[Vc(n),":"]}),e("span",{className:"text-foreground break-all",children:"object"==typeof r?JSON.stringify(r):String(r)})]},n))}),d.length>0&&t("div",{className:"mb-1.5 space-y-1",children:[e("div",{className:"text-[10px] uppercase tracking-wide text-muted/70 font-medium",children:R("agent.progress")}),d.map(n=>t("div",{className:"text-xs text-muted",children:[n.timestamp&&e("span",{className:"me-1 text-muted/60",children:Dr(n.timestamp).format("HH:mm:ss")}),e("span",{children:n.message})]},Hc(n)))]}),(()=>{const t="string"==typeof s?.observation?s.observation:void 0;return t&&t!==c?e("div",{className:"vprose prose prose-slate dark:prose-invert prose-p:leading-relaxed prose-p:my-1.5 max-w-none text-sm",children:e(oa,{artifactRunId:P,children:t})}):null})()]})})()]},a)})}),e("style",{children:"\n @keyframes slideInFade {\n from {\n opacity: 0;\n transform: translateX(-10px);\n }\n to {\n opacity: 1;\n transform: translateX(0);\n }\n }\n "}),!k&&e("div",{className:"group",children:w.map((t,n)=>{const r=N[n]??Gc(t);return e(td,{message:t,isExpanded:C.has(r),onToggle:()=>F(r),artifactRunId:P,classNames:{toolBadgeClassName:v,itemClassName:b,itemHeaderClassName:x,itemContentClassName:y}},r)})})]})},(e,t)=>e.messages.length===t.messages.length&&(e.showPulsatingCircle===t.showPulsatingCircle&&(e.toolRunId===t.toolRunId&&(e.toolStatus===t.toolStatus&&(e.preambleText===t.preambleText&&(e.rootClassName===t.rootClassName&&(e.headerClassName===t.headerClassName&&(e.senderClassName===t.senderClassName&&(e.toolSummaryClassName===t.toolSummaryClassName&&(e.toolBadgeClassName===t.toolBadgeClassName&&(e.itemClassName===t.itemClassName&&(e.itemHeaderClassName===t.itemHeaderClassName&&(e.itemContentClassName===t.itemContentClassName&&e.messages.every((e,n)=>{return r=e,a=t.messages[n],r.timestamp===a.timestamp&&r.type===a.type&&r.message===a.message&&r.details===a.details&&r.workstream_id===a.workstream_id&&r.workflow_run_id===a.workflow_run_id;var r,a})))))))))))))),sd="flex items-center gap-1.5 px-2 py-1 text-xs font-medium whitespace-nowrap transition-colors border-b-2 shrink-0 cursor-pointer",id="border-transparent text-muted hover:bg-muted",od="border-info bg-info text-info";function ld(e){return e.length>20?`${e.substring(0,18)}...`:e}function cd({items:n,current:r,onSelect:l,label:c,active:d,count:u,completionStatus:m}){const[p,h]=Oe(!1),f=Be(null),g=Be(!1),v=()=>{f.current&&(clearTimeout(f.current),f.current=null)},x=()=>{v(),f.current=setTimeout(()=>h(!1),150)};return He(()=>()=>clearTimeout(f.current??void 0),[]),t(a,{modal:!1,open:p,onOpenChange:e=>{v(),e&&(g.current=!1),h(e)},children:[e(s,{asChild:!0,children:t("button",{type:"button",onMouseEnter:()=>{v(),g.current=!0,h(!0)},onMouseLeave:x,className:i(sd,d?od:id),children:[c,e(Ft,{className:"ms-0.5 size-3.5"})]})}),e(o,{align:"end",className:"w-max",onMouseEnter:v,onMouseLeave:x,onCloseAutoFocus:e=>{g.current&&e.preventDefault()},children:n.map(([n,a])=>{const s=u?.has(n)&&u.get(n)>0;return t(b,{onClick:()=>l(n),className:i("flex items-center gap-2",n===r&&"text-info"),children:[e("span",{className:"truncate",children:a}),s&&t("span",{className:"ms-auto inline-flex items-center gap-1",children:[e("span",{className:"inline-flex items-center justify-center rounded-full bg-muted px-1.5 text-[10px] text-muted",children:u?.get(n)}),m&&"all"!==n&&(m.get(n)?e(Rt,{className:"size-3 text-success"}):e(Wt,{className:"size-3 text-attention"}))]})]},n)})})]})}function dd({entries:r,activeWorkstream:a,onSelectWorkstream:s,count:o,completionStatus:l}){const{t:c}=Ze(),d=Be(null),u=Be([]),m=Be(null),[p,h]=Oe({count:r.length,promote:!1}),f=()=>{const e=d.current;if(!e)return;const t=e.clientWidth,n=r.map((e,t)=>u.current[t]?.offsetWidth??0),s=(e,t)=>{let a=0,s=0;for(let i=0;i<r.length;i++){if(i===t)continue;const r=a+(s>0?4:0)+n[i];if(r>e)break;a=r,s+=1}return s};let i;if(n.reduce((e,t)=>e+t,0)+4*Math.max(0,r.length-1)<=t)i={count:r.length,promote:!1};else{const e=m.current?.offsetWidth??0,o=Math.max(1,s(t-e-4,-1)),l=r.findIndex(([e])=>e===a);if(l<0||l<o)i={count:o,promote:!1};else{const r=t-e-n[l]-8;i={count:s(r,l),promote:!0}}}h(e=>e.count===i.count&&e.promote===i.promote?e:i)},g=Be(f);g.current=f,Ke(()=>{g.current()}),He(()=>{const e=d.current;if(!e||"undefined"==typeof ResizeObserver)return;const t=new ResizeObserver(()=>g.current());return t.observe(e),()=>t.disconnect()},[]);const v=r.findIndex(([e])=>e===a);let b,x;if(p.promote&&v>=0){const e=r.filter((e,t)=>t!==v);b=[...e.slice(0,p.count),r[v]],x=e.slice(p.count)}else b=r.slice(0,p.count),x=r.slice(p.count);const y=x.some(([e])=>e===a),w=c("agent.moreTabs"),N=(r,a,s)=>{const c=o?.has(r)&&o.get(r)>0;return t(n,{children:[ld(a),c&&t("span",{className:"flex items-center gap-1",children:[e("span",{className:i("inline-flex items-center justify-center p-1 text-xs rounded-full",s?"bg-info text-info":"bg-muted text-muted"),children:o?.get(r)}),l&&"all"!==r&&(l.get(r)?e(Rt,{className:"size-3 text-success"}):e(Wt,{className:"size-3 text-attention"}))]})]})};return t("div",{ref:d,className:"relative mb-1 bg-muted border-b border-muted/20",children:[t("div",{"aria-hidden":!0,className:"pointer-events-none invisible absolute start-0 top-0 flex w-max gap-1",children:[r.map(([t,n],r)=>e("button",{type:"button",tabIndex:-1,ref:e=>{u.current[r]=e},className:i(sd,id),children:N(t,n,!1)},t)),t("button",{type:"button",tabIndex:-1,ref:m,className:i(sd,id),children:[w,e(Ft,{className:"ms-0.5 size-3.5"})]})]}),t("div",{className:"flex gap-1 overflow-hidden",children:[b.map(([t,n])=>{const r=a===t;return e("button",{type:"button","aria-current":r?"page":void 0,onClick:()=>s(t),title:n.length>20?n:void 0,className:i(sd,r?od:id),children:N(t,n,r)},t)}),x.length>0&&e(cd,{items:x,current:a,onSelect:s,label:w,active:y,count:o,completionStatus:l})]})]})}function ud({workstreams:t,activeWorkstream:n,onSelectWorkstream:r,count:a,completionStatus:s}){const{t:i}=Ze(),o=new Map;o.set("all",i("agent.allMessages")),o.set("main",i("agent.main")),t.forEach((e,t)=>{"all"!==t&&"main"!==t&&"research_france"!==t&&"statistics"!==t&&o.set(t,e)}),t=o;const l=Array.from(t.entries()).sort(([e],[t])=>"all"===e?-1:"all"===t?1:"main"===e?-1:"main"===t?1:e.localeCompare(t));return l.length>2?e(dd,{entries:l,activeWorkstream:n,onSelectWorkstream:r,count:a,completionStatus:s}):e("div",{className:"py-0.5"})}const md=e=>e.type===ir.BATCH_PROGRESS&&!!e.details?.batch_id;function pd(e){if(null==e||""===e)return Date.now();const t="number"==typeof e?e:new Date(e).getTime();return Number.isFinite(t)?t:Date.now()}function hd(e){const t=Date.now()-pd(e);return Math.max(0,Math.round(t/1e3))}function fd(e,t){const n=pd(t)-pd(e);return Math.max(0,Math.round(n/1e3))}function gd(e){if(e<60)return`${e}s`;const t=Math.floor(e/60),n=e%60;return n>0?`${t}m ${n}s`:`${t}m`}function vd(e){if(null==e||""===e)return;const t="number"==typeof e?e:new Date(e).getTime();return Number.isFinite(t)?t:void 0}function bd(e){const t=vd(e);if(void 0!==t)return new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"}).format(new Date(t))}function xd(e){const t=e.filter(e=>"main"===sl(e)),n=t[t.length-1]??e[e.length-1];return n?.type===ir.QUESTION}function yd(e){return e.map((t,n)=>{const r=function(e){if(e.type!==ir.UPDATE)return;const t=qd(e);if(void 0!==t.tool||void 0!==t.activity_group_id)return;const n="string"==typeof t.path&&t.path.trim()?t.path.trim():void 0;return n&&wd(e)===`Prepared and saved artifact to ${n}`?n:void 0}(t);if(!r)return t;const a=function(e,t){const n=sl(e[t]);for(let r=t-1;r>=0;r-=1){const t=e[r];if(sl(t)!==n)continue;const a=qd(t);if("write_artifact"===a.tool&&"string"==typeof a.activity_group_id)return t;if(t.type!==ir.REQUEST_INPUT&&!eu(t)&&"thinking"!==a.display_role){if("string"==typeof a.tool&&"write_artifact"!==a.tool)return;if(t.type===ir.ANSWER||t.type===ir.COMPLETE||t.type===ir.IDLE||t.type===ir.TERMINATED)return}}}(e,n),s=a?qd(a):void 0;if(!s)return t;const i="string"==typeof s.activity_group_id?s.activity_group_id:void 0,o="string"==typeof s.tool_run_id?s.tool_run_id:void 0,l="string"==typeof s.tool_use_id?s.tool_use_id:void 0,c="number"==typeof s.tool_iteration?s.tool_iteration:void 0;return i?{...t,details:{...t.details,event_class:"activity",tool:"write_artifact",tool_run_id:o??"write_artifact",tool_use_id:l??o??"write_artifact",tool_iteration:c,tool_status:"completed",tool_event:"progress",activity_group_id:i,output:wd(t),path:r}}:t})}function wd(e){return e.message?"object"==typeof e.message?JSON.stringify(e.message,null,2):String(e.message).trim():""}function Nd({message:n,details:r,onSelectWorkstream:a}){const{t:s}=Ze(),o=qo(r.workstreamId,r.interaction),l=r.interaction?Vo(r.interaction):"",c=l&&l!==o?l:void 0;return e("div",{className:"mx-auto w-full max-w-3xl px-1","data-workstream-id":r.workstreamId,children:t("button",{type:"button",className:i("group flex w-full items-start gap-3 border-b border-border/70 py-2 text-start text-sm text-muted","transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2","focus-visible:ring-focus focus-visible:ring-offset-2 focus-visible:ring-offset-background"),onClick:()=>a?.(r.workstreamId),children:[e(Bt,{className:"mt-0.5 size-4 shrink-0 text-muted","aria-hidden":"true"}),t("div",{className:"min-w-0 flex-1",children:[t("div",{className:"flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1",children:[e("span",{className:"font-medium text-muted",children:s("agent.workstreams")}),e("span",{className:"min-w-0 truncate text-foreground/85",children:o})]}),c&&e("div",{className:"mt-0.5 truncate text-xs text-muted/75",children:c}),e("span",{className:"sr-only",children:wd(n)})]}),e(ht,{className:"mt-0.5 size-4 shrink-0 text-muted transition-transform group-hover:translate-x-0.5 rtl:rotate-180 rtl:group-hover:-translate-x-0.5"})]})})}const kd=["agent-markdown vprose prose max-w-none break-words text-sm leading-6 text-foreground/80","prose-p:my-2 prose-p:leading-6 prose-li:my-0.5 prose-pre:my-3 prose-headings:tracking-normal","prose-headings:text-foreground prose-strong:text-foreground prose-code:text-foreground","prose-a:text-foreground prose-a:underline prose-a:decoration-muted prose-a:underline-offset-4","[&_p]:text-foreground/80 [&_li]:text-foreground/80 [&_li::marker]:text-muted"].join(" "),_d=/\[[^\]]+\]\((?:\/store\/(?:objects|collections)\/|store:|document:|document:\/\/|collection:)[^)]+\)/,Cd={table:function({node:n,className:r,children:a,...s}){const i=function(e){const t=Id(e),n=Math.max(0,...t.map(e=>e.length));if(n<=1)return[];const r=function(e){const t=Id(e),n=function(e){return Td(e,"tbody").flatMap(e=>Td(e,"tr").map(e=>Td(e,"td").map(e=>Sd(e).replace(/\s+/g," ").trim())))}(e),r=Math.max(0,...t.map(e=>e.length));if(r<=1)return new Set;const a=new Set;for(let e=0;e<r;e+=1){const t=n.map(t=>t[e]||"").map(e=>e.trim()).filter(Boolean);if(0===t.length)continue;const r=t.map(e=>e.length),s=Math.max(...r),i=r.reduce((e,t)=>e+t,0)/r.length,o=t.some(e=>/\S{12,}/.test(e));s<=16&&i<=10&&!o&&a.add(e)}if(a.size>=r)return new Set;return a}(e),a=Array.from({length:n},(e,n)=>{if(r.has(n))return 8;const a=t.map(e=>e[n]||"").map(e=>e.trim()).filter(Boolean);if(0===a.length)return 18;const s=a.map(e=>e.length),i=Math.max(...s),o=s.reduce((e,t)=>e+t,0)/s.length,l=function(e){return e.reduce((e,t)=>{const n=t.match(/\S+/g)||[];return Math.max(e,...n.map(e=>e.length))},0)}(a);return c=.7*o+.25*i+.45*l,d=18,u=90,Math.min(u,Math.max(d,c));var c,d,u}),s=a.reduce((e,t)=>e+t,0);return s<=0?[]:a.map((e,t)=>{const n=`${(e/s*100).toFixed(3)}%`;return{key:`agent-markdown-table-column-${t}`,compact:r.has(t),width:n}})}(n);return t("table",{...s,className:r,children:[i.length>0?e("colgroup",{children:i.map(t=>e("col",{className:t.compact?"agent-markdown-table-compact-col":void 0,style:{"--agent-markdown-table-column-width":t.width}},t.key))}):null,a]})}};function Sd(e){if(!e||"object"!=typeof e)return"";const t=e;return"string"==typeof t.value?t.value:Array.isArray(t.children)?t.children.map(Sd).join(""):""}function Td(e,t){if(!e||"object"!=typeof e)return[];const n=e.children;return Array.isArray(n)?n.filter(e=>{if(!e||"object"!=typeof e)return!1;const n=e;return t?n.tagName===t:"string"==typeof n.tagName}):[]}function Id(e){return Td(e).filter(e=>"thead"===e.tagName||"tbody"===e.tagName).flatMap(e=>Td(e,"tr").map(e=>Td(e).filter(e=>"th"===e.tagName||"td"===e.tagName).map(e=>Sd(e).replace(/\s+/g," ").trim())))}function zd(e){if(null==e||"boolean"==typeof e)return 0;if("string"==typeof e||"number"==typeof e)return String(e).length;if(Array.isArray(e))return e.reduce((e,t)=>e+zd(t),0);if(Me.isValidElement(e)){return zd(e.props.children)}return 0}function Rd(e,t){const[n,r]=Oe(()=>hd(e));return He(()=>{if(!t)return void r(hd(e));const n=()=>r(hd(e));n();const a=window.setInterval(n,1e3);return()=>window.clearInterval(a)},[t,e]),n}function jd({children:n,message:r,workstreamId:a,className:s,artifactRunId:o,markdownComponents:l}){const{t:c}=Ze(),[d,u]=Oe(!1),m=Fe(()=>zd(n),[n])>520,p="string"==typeof n||"number"==typeof n,h=p?String(n):"",f="string"==typeof n&&_d.test(n),g=r?dc(r):void 0;return He(()=>{!m&&d&&u(!1)},[d,m]),e("div",{className:"mx-auto flex w-full max-w-3xl justify-end px-1",children:t("div",{className:i("max-w-[min(44rem,82%)] rounded-[1.35rem] bg-mixer-muted/35 px-4 py-2.5","text-sm font-normal leading-6 text-foreground/90 shadow-sm shadow-black/5 dark:bg-mixer-muted/15 dark:text-foreground/88 dark:shadow-none","break-words [overflow-wrap:anywhere]",s),"data-workstream-id":a,children:[e("div",{className:i(p&&!f&&"whitespace-pre-wrap",m&&!d&&"max-h-72 overflow-hidden [mask-image:linear-gradient(to_bottom,black_76%,transparent_100%)]"),children:f?e(oa,{artifactRunId:o,components:l,className:i("agent-markdown vprose prose max-w-none break-words text-sm leading-6 text-foreground/90","prose-p:my-0 prose-p:leading-6 prose-a:text-foreground prose-a:underline prose-a:decoration-muted prose-a:underline-offset-4","[&_p+_p]:mt-2"),children:h}):n}),m&&t("button",{type:"button","aria-expanded":d,className:"mt-2 inline-flex items-center gap-1 text-sm font-medium text-muted transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",onClick:()=>u(e=>!e),children:[c(d?"agent.showLess":"agent.showMore"),e(Ft,{className:i("size-4 transition-transform",d&&"rotate-180"),"aria-hidden":"true"})]}),r&&g?e("div",{className:"mt-1.5 flex justify-end",children:e(uc,{message:r,className:"h-4 w-4"})}):null]})})}function Pd({message:r,onSendMessage:a,onSelectWorkstream:s,requestInputAnswered:o=!1,StoreLinkComponent:l,CollectionLinkComponent:c}){const d=r.type===ir.REQUEST_INPUT?Nl(r):wd(r),u=Yo(r)??Qo(r),m=sl(r),p=r.workflow_run_id,h=Fe(()=>r.type===ir.QUESTION?oc(d):null,[d,r.type]),f=Fe(()=>({...Cd,a:({node:t,ref:n,...r})=>{const a=r.href||"";if(a.includes("/store/objects")){const t=a.split("/store/objects/")[1]||"";return l?e(l,{href:a,documentId:t,children:r.children}):e(sa,{href:a,topLevelNav:!0,children:r.children})}if(a.includes("/store/collections")){const t=a.split("/store/collections/")[1]||"";return c?e(c,{href:a,collectionId:t,children:r.children}):e(sa,{href:a,topLevelNav:!0,children:r.children})}return e("a",{...r,target:"_blank",rel:"noopener noreferrer"})}}),[l,c]);if(u)return e(Nd,{message:r,details:u,onSelectWorkstream:s});if(r.type===ir.QUESTION){const a=h?.body??d,s=h?.attachments??[];return t(n,{children:[s.length>0&&e("div",{className:"mx-auto flex w-full max-w-3xl justify-end px-1",children:e(ac,{items:s,artifactRunId:p,align:"end",variant:"message",StoreLinkComponent:l,CollectionLinkComponent:c})}),a&&e(jd,{message:r,workstreamId:m,artifactRunId:p,markdownComponents:f,children:a})]})}const g=r.details;if(r.type===ir.REQUEST_INPUT&&g?.ux){const t=g.ux;return e("div",{className:"mx-auto w-full max-w-3xl px-1",children:e(Wo,{question:d,options:t.options,variant:t.variant,multiSelect:t.multiSelect,onSelect:e=>a?.(e,Al(r,e)),onMultiSelect:e=>a?.(e.join(", ")),allowFreeResponse:!t.options?.length||!!t.free_response,placeholder:t.free_response?.placeholder,submitLabel:t.free_response?.submit_label,onSubmit:e=>a?.(e,t.free_response?.metadata),hideBorder:!0,compact:!0,answered:o})})}const v=r.type===ir.ERROR||r.type===ir.WARNING;return t("div",{className:"mx-auto w-full max-w-3xl px-1","data-workstream-id":m,children:[v&&e("div",{className:"mb-2 text-xs font-medium text-destructive",children:r.type===ir.WARNING?"Warning":"Error"}),d&&e("div",{className:i(kd,v&&"rounded-lg border border-destructive/20 bg-destructive/5 px-3 py-2"),style:{overflowWrap:"anywhere"},children:e(oa,{artifactRunId:p,onProposalSelect:e=>a?.(e),onProposalSubmit:e=>a?.(e),components:f,children:d})})]})}function Ad(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function Dd(e){return null!=e&&("string"==typeof e?e.trim().length>0:Array.isArray(e)?e.length>0:"object"!=typeof e||Object.keys(e).length>0)}function Ed(e){return null!=e&&!1!==e&&("string"!=typeof e||e.trim().length>0)}function $d(e,t){const n=e&&Ad(e)?e.title:void 0;return"string"==typeof n&&n.trim()?n:t.replace(/[_-]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/\b\w/g,e=>e.toUpperCase())}function Ld(e){if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e)return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Md(t){return null==t||""===t?e("span",{className:"text-muted",children:"Not provided"}):"boolean"==typeof t?t?"Yes":"No":"number"==typeof t?String(t):"string"==typeof t?e("span",{className:"whitespace-pre-wrap",children:t}):Array.isArray(t)&&t.every(e=>"object"!=typeof e||null===e)?t.map(e=>Ld(e)).join(", "):e("pre",{className:"max-h-40 overflow-auto whitespace-pre-wrap rounded-md bg-background/55 px-2 py-1.5 font-mono text-[12px] leading-relaxed text-foreground/80",children:Ld(t)})}function Fd(n,r,a){if(!Dd(n))return null;if(!Ad(n))return Md(n);const s=function(e){if(!e||!Ad(e))return{};const t=e.properties;return Ad(t)?t:{}}(r),i=[...Object.keys(s),...Object.keys(n).filter(e=>!(e in s))].map(e=>({key:e,label:$d(s[e],e),value:n[e]})).filter(e=>Dd(e.value));return 0===i.length?null:t("div",{className:"space-y-2 text-start",children:[a?e("div",{className:"text-xs font-medium uppercase tracking-normal text-muted",children:a}):null,e("dl",{className:"space-y-2",children:i.map(n=>t("div",{className:"grid gap-1 sm:grid-cols-[minmax(7rem,32%)_1fr] sm:gap-3",children:[e("dt",{className:"text-xs font-medium text-muted",children:n.label}),e("dd",{className:"min-w-0 break-words text-sm text-foreground",children:Md(n.value)})]},n.key))})]})}function Od({data:t,schema:n,title:r,template:a,prependFriendlyMessage:s,timestamp:i,isSummaryView:o,messageItemClassNames:l,messageStyleOverrides:c,StoreLinkComponent:d,CollectionLinkComponent:u}){const m=s?.trim()||("string"==typeof t?t.trim():""),p=a?.({data:t??s,schema:n,title:r});if(!Ed(p)&&m){const t={type:ir.QUESTION,message:m,timestamp:pd(i),workflow_run_id:"",workstream_id:"main"};return o?e(Pd,{message:t,StoreLinkComponent:d,CollectionLinkComponent:u}):e(Cc,{...l,messageStyleOverrides:c,message:t})}const h=Ed(p)?p:Fd(t,n,r);return Ed(h)?e(jd,{className:"py-3",children:h}):null}function Ud({label:n,timestamp:r,className:a}){const s=function(e=!0){const[t,n]=Oe(0);return He(()=>{if(!e)return;const t=window.setInterval(()=>{n(()=>Math.floor(Math.random()*Kl.length))},4e3);return()=>window.clearInterval(t)},[e]),t}(),o=Rd(r,!0);return e("div",{className:i("mx-auto w-full max-w-3xl px-1",a),children:t("div",{className:"border-b border-border/70 pb-4 text-sm text-muted",children:[t("div",{className:"flex items-center gap-3",children:[e(Vl,{size:"sm",color:"blue"}),t("div",{className:"min-w-0",children:[t("div",{children:[e("span",{className:"font-medium",children:n}),t("span",{className:"ms-2 text-muted/75",children:["for ",gd(o)]})]}),e("div",{className:"mt-1 truncate text-muted/80",children:Kl[s]})]})]}),e("div",{className:"mt-3 ps-6",children:e(Bl,{color:"blue"})})]})})}const Wd="_summary_started_at",Bd="_summary_finished_at",Vd=new Set(["account_id","activity_group_id","activity_id","channel_id","collection_id","document_id","display_role","event_class","id","object_id","project_id","run_id","streamed","tenant_id","thread_id","tool","tool_event","tool_iteration","tool_run_id","tool_use_id","tool_status","tools","message_to_human","progress_messages","source","token_usage","checkpoint_at","checkpoint_threshold","approval_decision","approval_request","cancellation_reason",Wd,Bd,"workflow_run_id"]);function qd(e){return Ad(e.details)?e.details:{}}function Hd(e){return e.replace(/[_-]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,e=>e.toUpperCase())}function Gd(e){const t=[];if("string"==typeof e.tool&&e.tool.trim()&&t.push(e.tool.trim()),Array.isArray(e.tools))for(const n of e.tools)if("string"==typeof n&&n.trim())t.push(n.trim());else if(Ad(n)){const e="string"==typeof n.name?n.name:n.tool;"string"==typeof e&&e.trim()&&t.push(e.trim())}return t}function Jd(e){const t=Array.from(new Set(Gd(e)));return t.length>0?t.join(", "):void 0}function Kd(e){return"number"==typeof e||"string"==typeof e?e:void 0}const Yd=["query","path","file","file_name","fileName","filename","name","title","artifact","artifact_path","url","command"];function Qd(e){for(const t of Yd){const n=e[t];if("string"==typeof n&&n.trim())return{key:t,value:n.trim()};if("number"==typeof n||"boolean"==typeof n)return{key:t,value:String(n)}}}function Zd(e){switch(e){case"search":return"Search";case"read":return"Read";case"edit":return"Edit";case"command":return"Bash";case"skill":return"Skill";case"discover":default:return"Tool";case"think":return"Thought"}}function Xd(e,t){switch(e){case"denied":case"denied_with_feedback":return`User declined to use ${t}.`;case"timeout":return`Approval timed out for ${t}.`;case"reviewer_denied":return`Approval reviewer denied ${t}.`;case"cancelled_after_denial":return`Cancelled ${t} after another tool was denied.`;default:return}}function eu(e){if(e.type!==ir.QUESTION)return;const t=wd(e).trim().toLowerCase();return"allow_once"===t||"allow_for_run"===t||"deny"===t?t:void 0}function tu(e,t){const n=[];return e.forEach((r,a)=>{if(r.type!==ir.REQUEST_INPUT)return;const s=function(e){const t=qd(e).tool_approval;return Ad(t)?t:void 0}(r),i=function(e){const t=e?.approval_key;return"string"==typeof t&&t.trim()?t.trim():void 0}(s);if(!s||!i||t.has(i))return;const o=sl(r);let l;for(let t=a+1;t<e.length;t+=1){const n=e[t];if(sl(n)===o){if(n.type===ir.REQUEST_INPUT)break;if(n.type===ir.QUESTION){l=n;break}}}if(!l||"deny"!==eu(l))return;const c="string"==typeof s.tool_name&&s.tool_name.trim()?s.tool_name.trim():"tool_action",d=function(e){const t=e.tool_title;if("string"==typeof t&&t.trim())return t.trim();const n=e.tool_name;return"string"==typeof n&&n.trim()?Hd(n.trim()):"tool action"}(s),u="string"==typeof s.target&&s.target.trim()?s.target:"",m={tool_name:c,tool_title:s.tool_title,action_summary:s.action_summary,target:s.target,approval_key:i};n.push({timestamp:l.timestamp??r.timestamp,workflow_run_id:l.workflow_run_id||r.workflow_run_id,type:ir.THOUGHT,message:Xd("denied",d)??`User declined to use ${d}.`,workstream_id:o,details:{event_class:"activity",tool:c,tool_run_id:`approval:${i}`,tool_use_id:`approval:${i}`,tool_status:"error",tool_event:"failed",activity_group_id:`approval:${i}`,approval_decision:"denied",approval_request:m,input:s.input,target:u,observation:"The user declined this tool action.",source:"synthetic_tool_approval_decision"}})}),0===n.length?e:[...e,...n].sort((e,t)=>pd(e.timestamp)-pd(t.timestamp))}function nu(e,t=160){const n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}...`:n}const ru=["batch_id","activity_group_id","activity_id","tool_run_id","tool_use_id","streaming_id","chunk_index","tool_iteration","tool_event"];function au(e,t="message"){const n=function(e){for(const t of ru){const n=e[t];if("string"==typeof n&&n.trim())return`${t}:${n.trim()}`;if("number"==typeof n||"boolean"==typeof n)return`${t}:${n}`}}(qd(e)),r=nu(wd(e),96);return[t,e.workstream_id||"main",e.workflow_run_id,e.timestamp,e.type,n??r].filter(Boolean).join(":")}function su(e){if("single"===e.type)return au(e.message);if("streaming"===e.type)return`streaming:${e.streamingId}:${e.startTimestamp}:${e.workstreamId||"main"}`;const t=e.messages[0],n=e.messages[e.messages.length-1],r=t?au(t,"first"):e.firstTimestamp,a=n?au(n,"last"):e.firstTimestamp;return["group",e.toolRunId,e.firstTimestamp,r,a].filter(Boolean).join(":")}function iu(e,t){for(let n=t-1;n>=0;n--){const t=e[n];if("single"===t.type)return t.message.timestamp;if("tool_group"===t.type)return t.firstTimestamp;if("streaming"===t.type)return t.startTimestamp}}function ou(e){const t=Ld(e).trim();return t.length>2400?`${t.slice(0,2400)}\n...`:t}function lu(e,t,n,r){if(null!=n&&""!==n&&!(Array.isArray(n)&&0===n.length||Ad(n)&&0===Object.keys(n).length))return{key:e,label:t,value:n,tone:r}}function cu(e){const t=qd(e),n=new Set,r=[],a=Qd(t),s=(e,a,s)=>{for(const i of a){const a=lu(i,e,t[i],s);if(a)return n.add(i),void r.push(a)}};s("Query",["query"]),s("Input",["input","params","arguments","args"]),s("Output",["output","stdout","result","results","content","result_summary","observation","display_message"],"string"==typeof t.approval_decision?"error":void 0),s("Files",["files","outputFiles"]),s("Error",["error","stderr"],"error"),a&&n.add(a.key);const i=function(e,t){const n=Object.entries(e).reduce((e,[n,r])=>(Vd.has(n)||t.has(n)||null==r||""===r||(e[n]=r),e),{});return Object.keys(n).length>0?n:void 0}(t,n);return 0===r.length&&i&&r.push({key:"details",label:"Details",value:i}),r}function du(e,t){if(e.type===ir.REQUEST_INPUT)return;const n=wd(e),r=qd(e),a=hl(e),s=function(e){const t=qd(e),n=Gd(t).join(" ").toLowerCase(),r="string"==typeof t.tool?t.tool.toLowerCase():"",a=r||n;return hl(e)?"think":r.startsWith("learn_")||n.includes("learn_")?"skill":"discover_tools"===r?"discover":e.type!==ir.THOUGHT||r?a.includes("search")||a.includes("web")||a.includes("fetch")?"search":a.includes("read")||a.includes("document")||a.includes("file")?"read":a.includes("edit")||a.includes("write")||a.includes("patch")||a.includes("create")?"edit":a.includes("bash")||a.includes("shell")||a.includes("command")||a.includes("terminal")?"command":e.type===ir.THOUGHT&&0===n.length?"think":"tool":"think"}(e),i=Gd(r),o=function(e){const t=Qd(e);if(t)return t.value;const n=e.files??e.outputFiles;return Array.isArray(n)&&n.length>0?n.map(e=>Ld(e)).join(", "):void 0}(r),l="string"==typeof r.command&&r.command.trim()?r.command.trim():void 0,c=i[0]?Hd(i[0]):function(e){const t=e.details,n=t?.tool||"",r=Array.isArray(t?.tools)?t.tools.map(e=>"string"==typeof e?e:e.name||e.tool||"").filter(Boolean):[],a=[n,...r].join(" ").toLowerCase(),s=n.toLowerCase(),i="string"==typeof e.message?e.message.trim():"";return"tool_preamble"===t?.display_role?a.includes("search")||a.includes("web")||a.includes("fetch")?"Preparing search":r.length>0?"Preparing tools":"Thinking":s.includes("search")?"Searching":s.includes("fetch")||s.includes("web")?"Searching the web":s.includes("read")||s.includes("document")?"Reading":s.includes("edit")||s.includes("write")||s.includes("create")?"Editing":s.includes("bash")||s.includes("shell")||s.includes("command")?"Running command":i||"Using tool"}(e),d=Xd(r.approval_decision,c),u=function(e){switch(e){case"denied":case"denied_with_feedback":return"Declined by user";case"timeout":return"Approval timed out";case"reviewer_denied":return"Denied by reviewer";case"cancelled_after_denial":return"Cancelled after denial";default:return}}(r.approval_decision),m="string"==typeof r.message_to_human&&r.message_to_human.trim()?r.message_to_human.trim():void 0,p="think"===s?n||c:nu("command"===s?m||(d?"":n)||l||c:m||o||(d?"":n)||c),h=n?"think"===s?n:nu(n,420):void 0,f=h&&h!==p&&!d;return p||f?{key:`${e.timestamp}-${r.activity_id||r.tool_run_id||t}`,kind:s,label:Zd(s),title:p,isPreamble:a,command:l,text:f?h:void 0,toolName:Jd(r),startedAt:Kd(r[Wd])??e.timestamp,finishedAt:Kd(r[Bd])??e.timestamp,status:d?"error":r.tool_status,decisionText:u,sections:cu(e)}:void 0}function uu(e){return"string"==typeof e.activity_group_id&&e.activity_group_id.trim()?e.activity_group_id.trim():void 0}function mu(e){return"string"==typeof e.tool_use_id&&e.tool_use_id.trim()?e.tool_use_id.trim():"string"==typeof e.tool_run_id&&e.tool_run_id.trim()?e.tool_run_id.trim():"string"==typeof e.tool&&e.tool.trim()?e.tool.trim():void 0}function pu(e){const t=new Map,n=[];let r;const a=function(e){const t=new Map,n=new Map,r=(e,t,n)=>{if(!t||!n)return;const r=e.get(t)??new Set;r.add(n),e.set(t,r)};for(const a of e){const e=qd(a),s=uu(e),i=mu(e);"started"===e.tool_event&&r(t,s,i),"string"==typeof e.approval_decision&&r(n,s,i)}return new Set([...t.entries(),...n.entries()].filter(([,e])=>e.size>1).map(([e])=>e))}(e);e.forEach((e,s)=>{const i=qd(e);if(hl(e))return n.push({index:s,message:e}),void(r=void 0);const o=function(e,t){const n=uu(e),r=mu(e);return n?r&&t.has(n)?`activity:${n}:tool:${r}`:`activity:${n}`:"string"==typeof e.tool_use_id&&e.tool_use_id.trim()?`tool-use:${e.tool_use_id.trim()}`:"string"==typeof e.tool_run_id&&e.tool_run_id.trim()?`run:${e.tool_run_id.trim()}`:void 0}(i,a),l=!o&&function(e){const t=qd(e);return!(e.type!==ir.UPDATE||!Array.isArray(t.updates))||e.type===ir.PLAN&&Array.isArray(t.plan)}(e)?r:void 0,c=o??l;if(!c)return void n.push({index:s,message:e});const d=t.get(c);d?d.messages.push(e):t.set(c,{index:s,messages:[e]}),!function(e){const t=qd(e);return"plan"===t.tool||"update_plan"===t.tool}(e)?e.type===ir.PLAN&&(r=void 0):r=c});const s=Array.from(t.values()).map(({index:e,messages:t})=>{const n=[...t].sort((e,t)=>pd(e.timestamp)-pd(t.timestamp)),r=n[n.length-1],a=n.find(e=>"started"===qd(e).tool_event),s=n.find(e=>wd(e)),i=n.findLast(e=>"string"==typeof qd(e).approval_decision&&Boolean(wd(e))),o=n.findLast(e=>wd(e).startsWith("$ ")),l=n.findLast(e=>(e.type===ir.ERROR||e.type===ir.WARNING)&&wd(e)),c={};for(const e of n)Object.assign(c,qd(e));l&&void 0===c.error&&void 0===c.stderr&&(c.error=wd(l)),!l&&n.some(e=>e.type===ir.PLAN&&Array.isArray(e.details?.plan))&&(c.tool_status="completed"),o&&void 0===c.command&&(c.command=wd(o)),c[Wd]=n[0]?.timestamp,c[Bd]=n[n.length-1]?.timestamp;const d="string"==typeof a?.details?.message_to_human?a.details.message_to_human:"";return{index:e,message:{...r,message:i?.message||d||(s?s.message:r.message),details:c}}});return[...n,...s].sort((e,t)=>e.index-t.index).map(({message:e})=>e)}function hu({kind:t,status:n}){if("error"===n||"warning"===n)return e(Gt,{className:"size-3.5"});switch(t){case"search":return e(bt,{className:"size-3.5"});case"read":return e(kt,{className:"size-3.5"});case"edit":return e(Zt,{className:"size-3.5"});case"command":return e(Kt,{className:"size-3.5"});case"skill":case"think":return e(Qt,{className:"size-3.5"});default:return e(Yt,{className:"size-3.5"})}}function fu(e){const t=[],n=vd(e.startedAt),r=vd(e.finishedAt),a=bd(e.startedAt),s=bd(e.finishedAt);return e.toolName&&t.push({label:"Tool",value:e.toolName}),a&&s&&void 0!==n&&void 0!==r&&n!==r?(t.push({label:"Started",value:a}),t.push({label:"Ended",value:s}),t.push({label:"Duration",value:gd(fd(e.startedAt,e.finishedAt))})):(a||s)&&t.push({label:"Time",value:a??s??""}),t}function gu({hasDetailContent:n,item:r}){const a=fu(r);return 0===a.length?null:e("dl",{className:i("flex flex-wrap gap-x-4 gap-y-1 text-xs",n&&"mb-3 border-b border-border/60 pb-2"),children:a.map(n=>t("div",{className:"flex min-w-0 items-baseline gap-1.5",children:[e("dt",{className:"shrink-0 text-muted",children:n.label}),e("dd",{className:"min-w-0 wrap-break-word font-medium text-foreground/80",children:n.value})]},n.label))})}function vu({section:n}){const r=n.value,a="string"==typeof r||"number"==typeof r||"boolean"==typeof r,s="Files"===n.label&&Array.isArray(r),o="Output"===n.label;if(s){const t=Array.from(new Set(r.map(e=>Ld(e))));return e("div",{className:"mt-2 flex flex-wrap items-center gap-1.5",children:t.map(t=>e("span",{className:"rounded-md bg-mixer-muted/15 px-1.5 py-0.5 font-mono text-[11px] text-muted",children:nu(t,64)},t))})}const l=i("text-xs font-medium","error"===n.tone?"text-destructive":"text-muted"),c=a&&!String(r).includes("\n")&&String(r).length<180?e("div",{className:i("break-words text-xs","error"===n.tone?"text-destructive":"text-foreground/75"),children:String(r)}):e("pre",{className:i("max-h-52 overflow-auto whitespace-pre-wrap rounded-lg px-3 py-2 font-mono text-[11px] leading-relaxed","error"===n.tone?"bg-destructive/5 text-destructive":"bg-mixer-muted/10 text-foreground/75"),children:ou(r)});return t("div",{className:"mt-2",children:[o?null:e("div",{className:i("mb-1",l),children:n.label}),c]})}function bu(e){return"command"===e.kind?"Shell":e.label}function xu(e){if("command"!==e.kind)return e.title;const t=e.command||e.title;return t.trim().startsWith("$")?t:`$ ${t}`}function yu({item:n}){const r="command"===n.kind&&n.command?xu(n):void 0,a=r||0!==n.sections.length?void 0:n.text,s=Boolean(r||a||n.sections.length),o=function(e){const t=[bu(e),xu(e)],n=fu(e).map(e=>`${e.label}: ${e.value}`);n.length>0&&t.push(n.join("\n")),e.text&&t.push(e.text);for(const n of e.sections)t.push(`${n.label}\n${ou(n.value)}`);return t.filter(Boolean).join("\n\n")}(n),[l,c]=Oe("idle"),d=Be(void 0);He(()=>()=>{void 0!==d.current&&window.clearTimeout(d.current)},[]);return t("div",{className:"relative mt-2 rounded-lg border border-border/70 bg-mixer-muted/10 p-3 shadow-sm",children:[s?e("div",{className:"absolute end-2 top-2",children:e("button",{type:"button",className:i("inline-flex size-7 shrink-0 items-center justify-center rounded-md text-muted opacity-70 transition","hover:bg-mixer-muted/20 hover:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","copied"===l&&"text-success opacity-100","failed"===l&&"text-destructive opacity-100"),onClick:()=>{(async function(e){try{if(navigator.clipboard?.writeText)return await navigator.clipboard.writeText(e),!0}catch{}if("undefined"==typeof document)return!1;const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly",""),t.style.position="fixed",t.style.insetInlineStart="-9999px",t.style.top="0",document.body.appendChild(t);try{return t.focus(),t.select(),document.execCommand("copy")}catch{return!1}finally{t.remove()}})(o).then(e=>{c(e?"copied":"failed"),void 0!==d.current&&window.clearTimeout(d.current),d.current=window.setTimeout(()=>c("idle"),2e3)})},"aria-label":"Copy tool details",title:"Copy tool details",children:e("copied"===l?Rt:vt,{className:"size-4"})})}):null,t("div",{className:i(s&&"pe-7"),children:[e(gu,{item:n,hasDetailContent:s}),r?e("pre",{className:"mb-3 whitespace-pre-wrap break-words font-mono text-sm leading-6 text-foreground/85",children:r}):null,a?e("div",{className:"mb-3 break-words text-sm leading-6 text-foreground/75",children:a}):null,n.sections.length>0?e("div",{className:"space-y-3",children:n.sections.map(t=>e(vu,{section:t},t.key))}):null]}),"failed"===l&&s?e("div",{className:"mt-3 text-xs text-destructive",children:"Copy failed"}):null]})}function wu({item:n}){const r=Boolean(n.decisionText),a=!r&&("error"===n.status||"warning"===n.status),s=fu(n).length>0,o=Boolean(n.command||n.text||n.sections.length||s),[l,c]=Oe(!1),d=r?void 0:n.status;return t("div",{className:"min-w-0",children:[t("button",{type:"button",className:i("grid w-full grid-cols-[1.5rem_1fr_auto] gap-2 text-start outline-none transition-colors","focus-visible:text-foreground focus-visible:underline focus-visible:underline-offset-4",o?"cursor-pointer hover:text-foreground":"cursor-default"),onClick:()=>o&&c(e=>!e),"aria-expanded":o?l:void 0,disabled:!o,children:[e("span",{className:i("flex size-5 items-center justify-center pt-0.5",a?"text-attention":"text-muted"),children:e(hu,{kind:n.kind,status:d})}),t("span",{className:"min-w-0 text-sm text-muted",children:[e("span",{className:"break-words",children:n.title}),n.decisionText?e(f,{variant:"destructive",className:"ms-2 rounded-full shadow-sm shadow-destructive/10",children:n.decisionText}):null]}),o?e(Ft,{className:i("mt-0.5 size-4 shrink-0 text-muted opacity-50 transition-transform",!l&&"-rotate-90"),"aria-hidden":"true"}):null]}),o&&l?e("div",{className:"mt-1",children:e(yu,{item:n})}):null]})}function Nu({item:n,artifactRunId:r,disableCollapse:a}){const{t:s}=Ze(),o=n.text??n.title,l=o.trim(),[c,d]=Oe(!1),u=l?l.split(/\r?\n/).length:0,m=l.length>520||u>6,p=s(c?"agent.showLess":"agent.showMore");return t("div",{className:"min-w-0 py-1",children:[e("div",{"data-testid":"summary-thought-prose",className:i(kd,m&&!a&&!c&&"[display:-webkit-box] overflow-hidden [-webkit-box-orient:vertical] [-webkit-line-clamp:6]"),style:{overflowWrap:"anywhere"},children:e(oa,{artifactRunId:r,components:Cd,children:o})}),m&&!a?e("div",{className:"mt-1.5 flex justify-end",children:t("button",{type:"button","aria-expanded":c,className:i("inline-flex items-center gap-1 text-sm font-medium text-muted transition-colors","[text-decoration:none] hover:text-foreground hover:[text-decoration:none]","focus-visible:text-foreground focus-visible:[text-decoration:none]","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),onClick:()=>d(e=>!e),children:[p,e(Ft,{className:i("size-4 transition-transform",c&&"rotate-180"),"aria-hidden":"true"})]})}):null]})}function ku({items:t,artifactRunId:n,disablePreambleCollapse:r}){return e("div",{className:"mt-3",children:e("div",{className:"space-y-3",children:t.map(t=>t.isPreamble||"think"===t.kind?e(Nu,{item:t,artifactRunId:n,disableCollapse:r},t.key):e(wu,{item:t},t.key))})})}function _u({text:t,artifactRunId:n,workstreamId:r}){return e("div",{className:"mx-auto w-full max-w-3xl px-1","data-workstream-id":r,children:e("div",{className:kd,style:{overflowWrap:"anywhere"},children:e(oa,{artifactRunId:n,components:Cd,children:t})})})}function Cu({message:n,startTimestamp:r,endTimestamp:a,className:s}){const{t:o}=Ze(),l=gd(fd(r??n.timestamp,a??n.timestamp));return t("div",{className:i("mx-auto w-full max-w-3xl px-1",s),"data-testid":"summary-stopped-message",children:[t("div",{className:"flex items-center justify-end gap-2 text-lg font-medium text-muted sm:text-xl",children:[e("span",{children:o("agent.youStoppedAfter",{duration:l})}),e(uc,{message:n,className:"h-5 w-5"})]}),e("div",{className:"mt-5 border-b border-border/70"})]})}function Su({label:r,timestamp:a,durationSeconds:s,showElapsed:o,details:l,emptyDetailsLabel:c,defaultExpanded:d=!1,disablePreambleCollapse:u=!1,className:m,artifactRunId:p,onSendMessage:h,answeredToolApprovalRequestInputKeys:f,resolvedToolApprovalKeys:g}){const[v,b]=Oe(d),x=Rd(a,o&&void 0===s),y=s??x,w=o&&void 0!==a,N=Fe(()=>function(e){const t=new Set,n=[];return pu(e).forEach((e,r)=>{const a=du(e,r);if(!a)return;const s=`${a.kind}:${a.label}:${a.title}:${a.text??""}`;t.has(s)||(t.add(s),n.push(a))}),n}(l??[]),[l]),k=Fe(()=>(l??[]).filter(e=>Cl(e)&&!Ll(e,f??new Set,g??new Set)),[f,l,g]),_=N.length>0||k.length>0||Boolean(c);return e("div",{className:i("mx-auto w-full max-w-3xl px-1",m),children:t("div",{className:"border-b border-border/70 pb-3 text-sm text-muted",children:[t("button",{type:"button",className:i("inline-flex max-w-full items-center gap-2 text-start outline-none","focus-visible:text-foreground focus-visible:underline focus-visible:underline-offset-4",_?"cursor-pointer hover:text-foreground":"cursor-default"),onClick:()=>_&&b(e=>!e),"aria-expanded":_?v:void 0,disabled:!_,children:[e("span",{className:"min-w-0 truncate font-medium",children:r}),w?t("span",{className:"shrink-0 text-muted/75",children:["for ",gd(y)]}):null,_?e(v?Ft:ht,{className:"size-4 shrink-0 opacity-50"}):null]}),_&&v?N.length>0||k.length>0?t(n,{children:[N.length>0?e(ku,{items:N,artifactRunId:p,disablePreambleCollapse:u}):null,k.length>0?e("div",{className:"mt-3 space-y-3",children:k.map(t=>{const n=t.details.ux;return e(Wo,{question:Nl(t),options:n.options,variant:n.variant,multiSelect:n.multiSelect,onSelect:e=>h?.(e,Al(t,e)),onMultiSelect:e=>h?.(e.join(", ")),allowFreeResponse:!n.options?.length||!!n.free_response,placeholder:n.free_response?.placeholder,submitLabel:n.free_response?.submit_label,onSubmit:e=>h?.(e,n.free_response?.metadata),hideBorder:!0,compact:!0,className:"my-0",cardClassName:"bg-background/60 shadow-none"},au(t,"work-request-input"))})}):null]}):t("div",{className:"mt-3 flex items-center gap-2 text-sm text-muted",children:[e(Kt,{className:"size-4 opacity-70","aria-hidden":"true"}),e("span",{children:c})]}):null]})})}function Tu({children:n,status:r}){const a="error"===r?"bg-destructive":"warning"===r?"bg-attention":"completed"===r?"bg-success":"bg-muted";return t("div",{className:"relative ps-7",children:[e("div",{className:"absolute start-2 top-0 bottom-0 w-px bg-border"}),e("div",{className:i("absolute start-[5px] top-4 size-2.5 rounded-full ring-4 ring-background",a)}),n]})}class Iu extends Ye{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(e){return console.error("Message render error:",e),{hasError:!0,error:e}}componentDidUpdate(e){this.state.hasError&&e.children!==this.props.children&&this.setState({hasError:!1,error:void 0})}render(){return this.state.hasError?t("div",{className:"border-s-4 border-s-destructive bg-destructive/10 px-4 py-2 my-2 rounded-e",children:[e("p",{className:"text-sm text-destructive font-medium",children:Xe.getFixedT(null,et)("agent.failedToRenderMessage")}),e("p",{className:"text-xs text-muted mt-1 truncate",children:this.state.error?.message||"Unknown error"})]}):this.props.children}}function zu(e,t){const n=[...e.filter(e=>!function(e){if(e.type!==ir.UPDATE)return!1;const t=qd(e).event_class;return"document_created"===t||"document_updated"===t}(e)&&!t?.includes(e.type))].sort((e,t)=>("number"==typeof e.timestamp?e.timestamp:new Date(e.timestamp).getTime())-("number"==typeof t.timestamp?t.timestamp:new Date(t.timestamp).getTime())),r=[];for(const e of n){const t=r[r.length-1];t&&ml(t,e)||(t&&Ru(t,e)||r.push(e))}return r}const Ru=(e,t)=>{if(e.type!==t.type)return!1;if(e.message!==t.message)return!1;const n=e.details,r=t.details;if("completed"!==n?.tool_status||"completed"!==r?.tool_status)return!1;const a="number"==typeof e.timestamp?e.timestamp:new Date(e.timestamp).getTime();return("number"==typeof t.timestamp?t.timestamp:new Date(t.timestamp).getTime())-a<2e3},ju=Me.memo(function({messages:a,workstreamSourceMessages:s,bottomRef:o,viewMode:l="stacked",isCompleted:c=!1,streamingMessages:d=new Map,onSendMessage:u,messageItemClassNames:m,messageStyleOverrides:p,toolCallGroupClassNames:h,hideToolCallsInViewMode:f,streamingMessageClassNames:g,batchProgressPanelClassNames:v,artifactRunId:b,hideWorkstreamTabs:x,workingIndicatorClassName:y,messageListClassName:w,StoreLinkComponent:N,CollectionLinkComponent:k,prependFriendlyMessage:_,initialRequestData:C,initialRequestSchema:S,initialRequestTitle:T,initialRequestTemplate:I,showInitialRequest:z,hiddenMessageTypes:R,disableAutoScroll:j=!1,renderRequestInputControls:P=!0,activeWorkstream:A,onActiveWorkstreamChange:D}){b||console.warn("[AllMessagesMixed] artifactRunId prop is missing!");const{t:E}=Ze(),$=Be(null),[L,M]=Oe("all"),F=A??L,O=Ve(e=>{void 0===A&&M(e),D?.(e)},[A,D]),U=Be(0),W=Be(null),B=Be(!1),V=Be(!1),q=d.size>0,H="sliding"===l;He(()=>{const e=$.current;if(!e)return;const t=()=>{if(V.current)return;const{scrollTop:t,scrollHeight:n,clientHeight:r}=e,a=n-t-r;B.current=a>80};return e.addEventListener("scroll",t,{passive:!0}),()=>e.removeEventListener("scroll",t)},[]);const G=Fe(()=>{let e=0;return d.forEach(t=>{e+=t.text?.length||0}),Math.floor(e/200)},[d]),J=Ve(()=>{o.current&&(V.current=!0,o.current.scrollIntoView({behavior:q?"instant":"smooth"}),U.current=Date.now(),requestAnimationFrame(()=>{V.current=!1})),W.current=null},[o,q]);He(()=>{if(a.length,d.size,j)return;if(B.current)return;const e=Date.now()-U.current;if(e>=100)J();else if(null===W.current){const t=100-e;W.current=window.setTimeout(J,t)}return()=>{null!==W.current&&(clearTimeout(W.current),W.current=null)}},[a.length,d.size,G,J,j]);const K=Me.useMemo(()=>zu(a,R),[a,R]),Y=Me.useMemo(()=>s?zu(s,R):K,[s,R,K]),Q=Me.useMemo(()=>{const e=function(e){const t=new Map,n=Xe.getFixedT(null,et);return t.set("all",n("agent.allMessages")),t.set("main",n("agent.main")),e.forEach(e=>{e.workstream_id&&"main"!==e.workstream_id&&"all"!==e.workstream_id&&!t.has(e.workstream_id)&&t.set(e.workstream_id,e.workstream_id)}),t}(Y);return Y.forEach(t=>{const n=Yo(t)??Qo(t);n&&e.set(n.workstreamId,qo(n.workstreamId,n.interaction))}),e},[Y]),Z=Me.useMemo(()=>{if("all"!==F)return Q.get(F)??Vo(F)},[F,Q]),X=Ve(()=>{const e=$.current;e&&(V.current=!0,"function"==typeof e.scrollTo?e.scrollTo({top:0,behavior:"smooth"}):e.scrollTop=0,requestAnimationFrame(()=>{V.current=!1}))},[]),ee=Ve(e=>{O(e),requestAnimationFrame(X)},[X,O]),te=Ve(()=>{O("all"),requestAnimationFrame(X)},[X,O]);He(()=>{"all"===F||Q.has(F)||O("all")},[F,Q,O]);const ne=Me.useMemo(()=>{const e=new Map;e.set("all",Y.length);const t=function(e){return e.filter(e=>"main"===sl(e))}(Y);return e.set("main",t.length),Y.forEach(t=>{const n=sl(t);"main"!==n&&e.set(n,(e.get(n)||0)+1)}),e},[Y]),re=Me.useMemo(()=>yd(ol(K,F)),[K,F]),ae=Me.useMemo(()=>Il(re),[re]),se=Me.useMemo(()=>zl(re),[re]),ie=Me.useMemo(()=>function(e){const t=new Set;return e.forEach((n,r)=>{if(!jl(n))return;const a=sl(n);for(let s=r+1;s<e.length;s+=1){const r=e[s];if(sl(r)===a){if(r.type===ir.REQUEST_INPUT)break;if(r.type===ir.QUESTION){El(r)&&t.add(Sl(n));break}}}}),t}(re),[re]),oe=Me.useMemo(()=>function(e,t){const n=new Set;return e.forEach((r,a)=>{if(!jl(r)||t)return;const s=sl(r);for(let t=a+1;t<e.length;t+=1){const r=e[t];if(sl(r)===s){if(r.type===ir.REQUEST_INPUT)break;if(r.type===ir.QUESTION){Dl(r)&&n.add(Tl(r));break}}}}),n}(re),[re]),le=Me.useMemo(()=>{if(P)return;const e=Ol(re);return e?Sl(e):void 0},[re,P]),ce=Me.useCallback(e=>e.type===ir.REQUEST_INPUT&&(le===Sl(e)||Ll(e,ie,se)),[ie,le,se]),de=Me.useCallback(e=>Ml(e,oe),[oe]),ue=Me.useMemo(()=>re.filter(e=>!de(e)),[re,de]),me=Be(Date.now()),pe=(Boolean(_?.trim())||Dd(C)||void 0!==I)&&(z??!0),he=Fe(()=>re.some(e=>e.type===ir.QUESTION),[re]),fe="all"===F&&pe&&!he,ge=Fe(()=>re.reduce((e,t)=>Math.max(e,pd(t.timestamp)),-1/0),[re]),ve=Fe(()=>re.reduce((e,t)=>Ic(t)?e:Math.max(e,pd(t.timestamp)),-1/0),[re]),be=Fe(()=>re.some(e=>jl(e)&&!Ll(e,ie,se)),[ie,re,se]),xe=Fe(()=>function(e,t){const n=e.filter(e=>"main"===sl(e)),r=n[n.length-1]??e[e.length-1];if(!r||!Ml(r,t))return!1;const a=eu(r);return"allow_once"===a||"allow_for_run"===a}(re,oe),[re,oe]),ye=Fe(()=>!be&&(!xe&&(!xd(ue)&&(c||!nl(ue)))),[ue,xe,be,c]),{completeStreaming:we,incompleteStreaming:Ne}=Me.useMemo(()=>{const e=new Map,t=[];return d.forEach((n,r)=>{if(F&&"all"!==F){const e=n.workstreamId||"main";if(F!==e)return}n.startTimestamp<=ve?e.set(r,n):n.text&&t.push({id:r,data:n})}),{completeStreaming:e,incompleteStreaming:t}},[d,F,ve]),ke=Me.useMemo(()=>tu(Uc(re,we),se),[re,we,se]),_e=Me.useMemo(()=>ke.filter(e=>!ce(e)&&!de(e)),[ke,ce,de]),Ce=Fe(()=>{if(Ne.some(({data:e})=>e.text.trim().length>0))return Number.POSITIVE_INFINITY;const e=Ne.reduce((e,{data:t})=>Math.max(e,t.startTimestamp),-1/0);return Math.max(ge,e)},[Ne,ge]),Se=Me.useMemo(()=>Oc(_e,ye,Ce),[_e,ye,Ce]),Te=Me.useMemo(()=>function(e){const t=[];let n=null;const r=()=>{n&&(t.push({type:"tool_group",messages:n.messages,firstTimestamp:n.firstTimestamp,toolRunId:n.toolRunId,toolStatus:n.toolStatus,preambleText:n.preambleText,preambleMessage:n.preambleMessage}),n=null)};for(const a of e)"tool_group"===a.type?n?(n.messages=[...n.messages,...a.messages],n.toolStatus=yl(n.toolStatus,a.toolStatus),!n.toolRunId&&a.toolRunId&&(n.toolRunId=a.toolRunId),!n.preambleMessage&&a.preambleMessage&&(n.preambleMessage=a.preambleMessage,n.preambleText=a.preambleText)):n={messages:[...a.messages],firstTimestamp:a.firstTimestamp,toolRunId:a.toolRunId,toolStatus:a.toolStatus,preambleText:a.preambleText,preambleMessage:a.preambleMessage}:(r(),t.push(a));return r(),t}(function(e,t,n){const r=new Map,a=new Map,s=new Map,i=[];for(const t of e){const e=xl(t);if(t.type===ir.REQUEST_INPUT||t.type===ir.BATCH_PROGRESS)i.push(t);else if(hl(t))i.push(t);else if(e)r.has(e)||r.set(e,{messages:[],firstTimestamp:al(t.timestamp)}),r.get(e)?.messages.push(t);else if(fl(t)){const e=vl(t),n=gl(t);void 0!==e?(a.has(e)||a.set(e,{messages:[],firstTimestamp:al(t.timestamp)}),a.get(e)?.messages.push(t)):n?(s.has(n)||s.set(n,{messages:[],firstTimestamp:al(t.timestamp)}),s.get(n)?.messages.push(t)):i.push(t)}else i.push(t)}const o=[];r.forEach((e,t)=>{o.push({kind:"activity_group",activityGroupId:t,messages:e.messages,timestamp:e.firstTimestamp})}),a.forEach((e,t)=>{o.push({kind:"iteration_group",iteration:t,messages:e.messages,timestamp:e.firstTimestamp})}),s.forEach((e,t)=>{o.push({kind:"tool_run",toolRunId:t,messages:e.messages,timestamp:e.firstTimestamp})});for(const e of i)o.push({kind:"message",message:e,timestamp:al(e.timestamp)});t.forEach((t,r)=>{if(t.text&&!ul(t,e)){if(n&&"all"!==n){const e=t.workstreamId||"main";if(n!==e)return}o.push({kind:"streaming",streamingId:r,data:t,timestamp:t.startTimestamp})}}),o.sort((e,t)=>{const n="streaming"===e.kind&&!e.data.isComplete,r="streaming"===t.kind&&!t.data.isComplete;return n&&!r?1:r&&!n?-1:e.timestamp-t.timestamp});const l=[];let c=[];const d=()=>{c.length>0&&(1!==c.length||hl(c[0])?l.push({type:"tool_group",messages:c,firstTimestamp:al(c[0].timestamp)}):l.push({type:"single",message:c[0]}),c=[])};for(const e of o)if("streaming"===e.kind)d(),l.push({type:"streaming",streamingId:e.streamingId,text:e.data.text,workstreamId:e.data.workstreamId,startTimestamp:e.data.startTimestamp,isComplete:e.data.isComplete});else if("activity_group"===e.kind){d();const t=[...e.messages].sort((e,t)=>al(e.timestamp)-al(t.timestamp)),n=t.reduce((e,t)=>bl(t)||e,void 0);l.push({type:"tool_group",messages:t,firstTimestamp:e.timestamp,toolRunId:e.activityGroupId,toolStatus:n})}else if("iteration_group"===e.kind){d();const t=[...e.messages].sort((e,t)=>al(e.timestamp)-al(t.timestamp)),n=t.reduce((e,t)=>bl(t)||e,void 0);l.push({type:"tool_group",messages:t,firstTimestamp:e.timestamp,toolStatus:n})}else if("tool_run"===e.kind){d();const t=[...e.messages].sort((e,t)=>al(e.timestamp)-al(t.timestamp)),n=t.reduce((e,t)=>bl(t)||e,void 0);l.push({type:"tool_group",messages:t,firstTimestamp:e.timestamp,toolRunId:e.toolRunId,toolStatus:n})}else fl(e.message)?c.push(e.message):(d(),l.push({type:"single",message:e.message}));return d(),l}(re,we,F)),[re,we,F]),Ie=Fe(()=>!ye||xd(ue),[ue,ye]),ze=function(e,t,n){if(!t||n)return!1;if(e.some(e=>"work"===e.type&&e.isActive))return!1;const r=e[e.length-1];return!!r&&("work"===r.type||r.message.type===ir.QUESTION)}(Se,Ie,Ne.length>0),Re=function(e){const t=e[e.length-1];return!!t&&"message"===t.type&&t.message.type===ir.QUESTION&&1===e.length}(Se)?E("agent.preparing"):E("agent.working"),je=0===re.length&&pe&&Ie&&0===Ne.length,Pe=Fe(()=>function(e,t,n){const r=e[e.length-1];return r?"work"===r.type?r.endTimestamp??r.startTimestamp:r.message.timestamp??n:t.reduce((e,t)=>{const n=Rc(t.timestamp);return!Number.isFinite(n)||n>=e.ms?e:{timestamp:t.timestamp,ms:n}},{ms:Number.POSITIVE_INFINITY}).timestamp??n}(Se,_e,me.current),[Se,_e]),Ae=Be(Pe),De=Be(!1),Ee=Fe(()=>{if(!ze)return Pe;const e=pd(Pe),t=pd(Ae.current);return!De.current||e<t?Pe:Ae.current},[Pe,ze]);He(()=>{Ae.current=Ee,De.current=ze},[Ee,ze]);const $e=Fe(()=>{const e=new Map,t=new Map;Y.forEach(e=>{const n=sl(e);t.has(n)||t.set(n,[]),t.get(n)?.push(e)});for(const[n,r]of t.entries())if(r.length>0){const t=r.some(e=>{if([ir.COMPLETE,ir.IDLE,ir.REQUEST_INPUT,ir.TERMINATED].includes(e.type))return!0;if(e.type===ir.UPDATE&&e.details){const t=e.details;return"completed"===t.workstream_event||"completed"===t.status||"canceled"===t.status}return!1});e.set(n,t)}return e},[Y]);return t("div",{ref:$,tabIndex:0,className:"flex-1 min-h-0 h-full w-full max-w-full overflow-y-auto overflow-x-hidden px-1.5 sm:px-2.5 lg:px-3 flex flex-col relative focus:outline-none","data-testid":"all-messages-mixed","data-message-count":a.length,"data-streaming-count":d.size,"data-view-mode":l,children:[e("style",{children:"\n /* Better vertical rhythm for markdown */\n .vprose > * + * {\n margin-top: 0.625rem;\n }\n .vprose > h1 + *,\n .vprose > h2 + *,\n .vprose > h3 + * {\n margin-top: 0.375rem;\n }\n /* Tables should read like part of the conversation, not a separate app grid. */\n .vprose table {\n margin-top: 0.875rem;\n margin-bottom: 0.875rem;\n border-collapse: collapse;\n width: 100%;\n background: transparent;\n }\n .vprose th,\n .vprose td {\n padding: 0.5rem 0.625rem;\n border: 0;\n border-bottom: 1px solid color-mix(in oklch, var(--border) 70%, transparent);\n background: transparent;\n text-align: left;\n }\n .vprose thead th {\n background: transparent;\n font-weight: 600;\n color: var(--muted);\n font-size: 0.75rem;\n text-transform: none;\n letter-spacing: 0;\n }\n .vprose tbody tr:hover {\n background: transparent;\n }\n /* Dark mode table styles */\n .dark .vprose th,\n .dark .vprose td {\n border-color: color-mix(in oklch, var(--border) 70%, transparent);\n }\n .dark .vprose thead th {\n background: transparent;\n color: var(--muted);\n }\n .dark .vprose tbody tr:hover {\n background: transparent;\n }\n /* Horizontal rules as section dividers */\n .vprose hr {\n margin-top: 1rem;\n margin-bottom: 1rem;\n border-color: var(--gray-5, #d1d5db);\n }\n /* Better blockquote styling */\n .vprose blockquote {\n margin-top: 0.875rem;\n margin-bottom: 0.875rem;\n padding-left: 1rem;\n border-left-width: 3px;\n border-left-color: var(--gray-6, #d1d5db);\n color: var(--gray-11, #6b7280);\n }\n /* Code blocks */\n .vprose pre {\n margin-top: 0.75rem;\n margin-bottom: 0.75rem;\n padding: 0.75rem;\n border-radius: 0.5rem;\n overflow-x: auto;\n background-color: var(--color-muted-background, #f3f4f6);\n color: var(--color-foreground, #1f2937);\n }\n .vprose pre code {\n color: inherit;\n }\n .dark .vprose pre {\n color: var(--color-foreground, #f9fafb);\n }\n\n /* Summary chat markdown: keep structure, but match the app's quieter conversation surface. */\n .agent-markdown {\n color: color-mix(in oklch, var(--foreground) 78%, transparent);\n font-size: 0.875rem;\n line-height: 1.625;\n overflow-x: auto;\n }\n .agent-markdown > * + * {\n margin-top: 0.65rem;\n }\n .agent-markdown p {\n margin-top: 0.5rem;\n margin-bottom: 0.5rem;\n }\n .agent-markdown h1,\n .agent-markdown h2,\n .agent-markdown h3,\n .agent-markdown h4 {\n margin-top: 1.2rem;\n margin-bottom: 0.45rem;\n color: var(--foreground);\n font-weight: 650;\n letter-spacing: 0;\n line-height: 1.3;\n }\n .agent-markdown h1 {\n font-size: 1.2rem;\n }\n .agent-markdown h2 {\n font-size: 1.05rem;\n }\n .agent-markdown h3,\n .agent-markdown h4 {\n font-size: 0.95rem;\n }\n .agent-markdown h1:first-child,\n .agent-markdown h2:first-child,\n .agent-markdown h3:first-child,\n .agent-markdown h4:first-child {\n margin-top: 0;\n }\n .agent-markdown hr {\n margin: 1.15rem 0;\n border: 0;\n border-top: 1px solid var(--border);\n opacity: 0.65;\n }\n .agent-markdown ul,\n .agent-markdown ol {\n margin-top: 0.55rem;\n margin-bottom: 0.55rem;\n padding-left: 1.25rem;\n }\n .agent-markdown li {\n margin-top: 0.2rem;\n margin-bottom: 0.2rem;\n padding-left: 0.1rem;\n color: inherit;\n }\n .agent-markdown li::marker {\n color: var(--muted);\n }\n .agent-markdown strong {\n color: var(--foreground);\n font-weight: 600;\n }\n .agent-markdown em {\n color: color-mix(in oklch, var(--foreground) 72%, transparent);\n }\n .agent-markdown a {\n color: var(--foreground);\n text-decoration-color: var(--muted);\n text-underline-offset: 3px;\n }\n .agent-markdown blockquote {\n margin-top: 0.85rem;\n margin-bottom: 0.85rem;\n padding-left: 0.875rem;\n border-left: 2px solid var(--border);\n color: var(--muted);\n font-style: normal;\n }\n .agent-markdown :not(pre) > code {\n border: 1px solid var(--border);\n border-radius: 0.375rem;\n background: var(--muted-background);\n color: var(--foreground);\n padding: 0.1rem 0.35rem;\n font-size: 0.8125em;\n font-weight: 500;\n }\n .agent-markdown pre {\n margin-top: 0.85rem;\n margin-bottom: 0.85rem;\n max-height: 32rem;\n overflow: auto;\n border: 1px solid var(--border);\n border-radius: 0.75rem;\n background: var(--muted-background);\n color: var(--foreground);\n padding: 0.875rem;\n font-size: 0.8125rem;\n line-height: 1.55;\n }\n .agent-markdown pre code {\n border: 0;\n background: transparent;\n color: inherit;\n padding: 0;\n font-size: inherit;\n }\n .agent-markdown table {\n display: table;\n width: 100%;\n max-width: 100%;\n margin: 0.9rem 0 1rem;\n border: 0;\n border-collapse: collapse;\n border-spacing: 0;\n font-size: 0.8125rem;\n table-layout: fixed;\n background: transparent;\n }\n .agent-markdown thead {\n background: transparent;\n }\n .agent-markdown th,\n .agent-markdown td {\n border: 0;\n border-bottom: 1px solid color-mix(in oklch, var(--border) 70%, transparent);\n background: transparent;\n padding: 0.55rem 0.75rem;\n text-align: left;\n vertical-align: top;\n overflow-wrap: anywhere;\n word-break: normal;\n white-space: normal;\n }\n .agent-markdown th {\n color: var(--muted);\n font-size: 0.75rem;\n font-weight: 600;\n letter-spacing: 0;\n text-transform: none;\n white-space: nowrap;\n }\n .agent-markdown td {\n color: inherit;\n }\n .agent-markdown th + th,\n .agent-markdown td + td {\n padding-inline-start: 1.75rem;\n }\n .agent-markdown th:first-child,\n .agent-markdown td:first-child {\n min-width: 0;\n width: auto;\n white-space: normal;\n }\n .agent-markdown col {\n width: var(--agent-markdown-table-column-width);\n }\n .agent-markdown .agent-markdown-table-compact-col {\n width: clamp(4.75rem, var(--agent-markdown-table-column-width), 7rem);\n }\n .agent-markdown tr:last-child td {\n border-bottom: 0;\n }\n .agent-markdown tbody tr:nth-child(even) {\n background: transparent;\n }\n .agent-markdown tbody tr:hover {\n background: transparent;\n }\n "}),"stacked"===l&&e("div",{className:i("sticky top-0 z-10",x&&"hidden"),children:e(ud,{workstreams:Q,activeWorkstream:F,onSelectWorkstream:ee,count:ne,completionStatus:$e})}),0!==re.length||pe||H&&ze?t("div",{className:i("flex-1 flex flex-col justify-start w-full max-w-full",H?"gap-6 px-2 py-6 sm:px-4":"gap-3 pb-4",w),children:[H&&"all"!==F&&Z&&e("div",{className:"sticky top-0 z-20 -mx-2 bg-background/95 px-2 pb-2 pt-1 backdrop-blur sm:-mx-4 sm:px-4",children:t("div",{className:"mx-auto flex w-full max-w-3xl items-center gap-2 border-b border-border/70 pb-3",children:[e(r,{type:"button",variant:"ghost",size:"icon",className:"size-8 shrink-0 text-muted hover:text-foreground",title:E("agent.backToMainAgent"),onClick:te,children:e(Jt,{className:"size-4","aria-hidden":"true"})}),e("div",{className:"min-w-0 flex-1 truncate text-sm font-medium text-foreground",children:Z})]})}),fe&&e(Od,{data:C,schema:S,title:T,template:I,prependFriendlyMessage:_,timestamp:re[0]?.timestamp??Date.now(),isSummaryView:H,messageItemClassNames:m,messageStyleOverrides:p,StoreLinkComponent:N,CollectionLinkComponent:k},"initial-request"),je&&e(Ud,{label:Re,timestamp:Ee,className:y}),t(n,"stacked"===l?{children:[Te.map((t,n)=>{const r=n===Te.length-1;if("tool_group"===t.type){const n=t.messages[t.messages.length-1],a="completed"===t.toolStatus||"error"===t.toolStatus||"warning"===t.toolStatus,s=!c&&r&&!tl.includes(n.type)&&!a;return f?.includes(l)?null:e(Tu,{status:t.toolStatus,children:e(Iu,{children:e(ad,{...h,messages:t.messages,showPulsatingCircle:s,toolRunId:t.toolRunId,toolStatus:t.toolStatus,preambleText:t.preambleText,preambleMessage:t.preambleMessage,rootClassName:i("rounded-lg border border-border bg-background/60 shadow-none",h?.rootClassName),headerClassName:i("px-3 py-2",h?.headerClassName),itemHeaderClassName:i("hover:bg-mixer-muted/20",h?.itemHeaderClassName)})})},su(t))}if("streaming"===t.type)return e(Tu,{children:e(Sc,{...g,text:t.text,workstreamId:t.workstreamId,isComplete:t.isComplete,timestamp:t.startTimestamp,artifactRunId:b,cardClassName:i("rounded-lg border border-border bg-background/60 shadow-none",g?.cardClassName)})},su(t));{const a=t.message;if(ce(a))return null;if(de(a))return null;if(rl(a))return e(Tu,{children:e(Cu,{message:a,startTimestamp:iu(Te,n)??a.timestamp,endTimestamp:a.timestamp})},au(a,"stopped"));const s=!c&&r&&!tl.includes(a.type);return md(a)?e(Iu,{children:e(lc,{message:a,batchData:a.details,isRunning:!a.details.completed_at,...v})},`batch-${a.details.batch_id}-${a.timestamp}`):e(Tu,{status:"message",children:e(Iu,{children:e(Cc,{...m,message:a,showPulsatingCircle:s,onSendMessage:u,requestInputAnswered:Fl(a,ae),cardClassName:i("rounded-lg border border-border bg-background/60 shadow-none",m?.cardClassName),headerClassName:i("px-3 py-2",m?.headerClassName),contentClassName:i("bg-transparent",m?.contentClassName),messageStyleOverrides:p,StoreLinkComponent:N,CollectionLinkComponent:k})})},au(a))}}),Ne.map(({id:t,data:n})=>e(Tu,{children:e(Sc,{...g,text:n.text,workstreamId:n.workstreamId,isComplete:n.isComplete,timestamp:n.startTimestamp,artifactRunId:b,cardClassName:i("rounded-lg border border-border bg-background/60 shadow-none",g?.cardClassName)})},`streaming-incomplete-${t}`)),Ie&&0===Ne.length&&!je&&e(Tu,{children:t("div",{className:i("flex items-center gap-2 py-2 text-sm text-muted",y),children:[e(Vl,{size:"sm",color:"blue"}),e("span",{children:E("agent.working")})]})})]}:{children:[Se.map(t=>{if("work"===t.type){if(f?.includes(l))return null;const r=function(e){return e.length>0&&e.every(zc)}(t.messages);return e(Su,{label:(n=t.isActive,function(e){return e?"Working":"Worked"}(n)),status:t.status,timestamp:t.startTimestamp,durationSeconds:t.isActive?void 0:fd(t.startTimestamp,t.endTimestamp),showElapsed:!0,details:r?void 0:t.messages,defaultExpanded:t.isActive&&!r,disablePreambleCollapse:t.isActive,className:y,onSendMessage:u,answeredToolApprovalRequestInputKeys:ie,resolvedToolApprovalKeys:se},`work-${t.id}-${t.isActive?"active":"done"}-${t.status}`)}var n;if("stopped"===t.type)return e(Cu,{message:t.message,startTimestamp:t.startTimestamp,endTimestamp:t.endTimestamp},au(t.message,"stopped-summary"));const r=t.message;return ce(r)||de(r)?null:md(r)?e(Iu,{children:e(lc,{message:r,batchData:r.details,isRunning:!r.details.completed_at,...v})},au(r,"batch")):e(Iu,{children:e(Pd,{message:r,onSendMessage:u,onSelectWorkstream:ee,requestInputAnswered:Fl(r,ae),StoreLinkComponent:N,CollectionLinkComponent:k})},au(r,"summary"))}),Ne.map(({id:t,data:n})=>e(_u,{text:n.text,workstreamId:n.workstreamId,artifactRunId:b},`streaming-incomplete-${t}`)),ze&&!je&&e(Su,{label:Re,status:"running",timestamp:Ee,showElapsed:!0,className:y})]}),e("div",{ref:o,className:"h-2"})]}):"all"===F&&Ie&&0===Ne.length?e("div",{className:"flex-1 px-2 py-6 sm:px-4",children:e(Ud,{label:E("agent.preparing"),timestamp:me.current,className:y})}):e("div",{className:"flex items-center justify-center h-full text-center py-8",children:e("div",{className:"flex items-center px-3 py-2 text-sm text-muted",children:E("all"===F?"agent.waitingForAgentResponse":"agent.noMessagesInWorkstream")})})]})});function Pu(e,t){if(0===t)return"live";if("live"===e)return"live";const n=fs(e,t);return n>=t-1?"live":n+1}function Au(e){return function(e){let t=0,n=e.length;for(;t<n&&"-"===e[t];)t++;for(;n>t&&"-"===e[n-1];)n--;return e.slice(t,n)}(e.trim().replace(/[^a-z0-9-_]+/gi,"-")).slice(0,80)}function Du({fixture:n,cursor:a,initialCursor:s,onCursorChange:o,autoStepMs:l,repeat:c=1,viewMode:d,className:u,title:m,showHeader:p=!0}){const{t:h}=Ze(),f=n.messages,g=s??(f.length>0?0:"live"),[v,b]=Oe(()=>hs(g,f.length)),x=a??v,y=d??"sliding",[w,N]=Oe(Boolean(l)),[k,_]=Oe(0),C=Be(null),S=Fe(()=>bs(f,x,!0),[x,f]),T=S.displayedMessages,I=Fe(()=>{return e=function(e,t){return e?.find(e=>e.cursor===t)}(n.streamingFrames,S.cursor),e?new Map(e.streamingMessages.map((e,t)=>[e.id??e.activityId??`stream-${t}`,e])):new Map;var e},[n.streamingFrames,S.cursor]),z=Ve(e=>{const t=hs(e,f.length);void 0===a&&b(t),o?.(t)},[a,f.length,o]);He(()=>{const e=hs(x,f.length);e!==x&&z(e)},[x,f.length,z]),He(()=>{if(!l||l<=0||!w)return;const e=window.setInterval(()=>{const e=Pu(x,f.length);"live"!==e||"live"!==x?z(e):_(e=>{const t=e+1;return c>0&&t>=c?(N(!1),t):(z(f.length>0?0:"live"),t)})},l);return()=>window.clearInterval(e)},[l,x,w,f.length,c,z]);const R=T.length>0&&!nl(T),j=Fe(()=>Ol(T),[T]),P=m??n.metadata?.title??h("agent.rewind.fixtureTitle"),A=Ve(()=>{const e={...n,metadata:{...n.metadata,title:P,exported_at:n.metadata?.exported_at??(new Date).toISOString(),message_count:f.length}},t=n.metadata?.agent_run_id??"fixture";!function(e,t){const n=new Blob([JSON.stringify(t,null,2)],{type:"application/json"}),r=URL.createObjectURL(n),a=document.createElement("a");a.href=r,a.download=e,document.body.appendChild(a),a.click(),a.remove(),URL.revokeObjectURL(r)}(`${Au(P)||"agent-chat"}-${Au(t)}.json`,e)},[n,f.length,P]),D=Ve(()=>{z(Pu(S.cursor,f.length))},[f.length,S.cursor,z]);return t("div",{className:i("flex h-full min-h-0 w-full flex-col bg-background text-foreground",u),"data-agent-test-playback-enabled":!0,"data-agent-playback-cursor":S.cursor,"data-agent-live-message-count":f.length,"data-agent-rendered-message-count":S.renderedMessageCount,"data-agent-replay-playing":w||void 0,"data-agent-replay-loop":k,children:[p&&t("div",{className:"flex flex-wrap items-center justify-between gap-2 border-b border-border px-3 py-2",children:[t("div",{className:"min-w-0",children:[e("div",{className:"truncate text-sm font-medium",children:P}),e("div",{className:"text-xs text-muted",children:h("agent.rewind.fixtureMeta",{messageCount:f.length,loops:k})})]}),t("div",{className:"flex items-center gap-2",children:[t(r,{type:"button",variant:"secondary",size:"sm",onClick:A,children:[e(Xt,{className:"size-4"}),e("span",{className:"ms-1.5",children:h("agent.rewind.exportFixture")})]}),l&&l>0&&t(r,{type:"button",variant:"secondary",size:"sm",onClick:()=>N(e=>!e),children:[e(w?en:tn,{className:"size-4"}),e("span",{className:"ms-1.5",children:h(w?"agent.rewind.pause":"agent.rewind.resume")})]})]})]}),e("div",{className:"flex flex-shrink-0 justify-end px-2 py-1.5",children:e(ks,{cursor:S.cursor,messages:f,onChangeCursor:z})}),e(ju,{messages:T,isCompleted:R,streamingMessages:I,bottomRef:C,artifactRunId:n.metadata?.agent_run_id??"agent-chat-fixture",viewMode:y,renderRequestInputControls:!j}),j&&e(Wl,{message:j,onSendMessage:D,isLoading:!1})]})}function Eu({className:n,inline:r=!1}){return t("div",{className:i("flex items-center gap-1",r?"inline-flex":"",n),children:[e("div",{className:"w-2 h-2 bg-blue-500 rounded-full animate-[jumping_1s_infinite_ease-in-out] hover:bg-blue-600",style:{transform:"translateY(0)",animationRange:"0px -8px"}}),e("div",{className:"w-2 h-2 bg-blue-500 rounded-full animate-[jumping_1s_0.3s_infinite_ease-in-out] hover:bg-blue-600",style:{transform:"translateY(0)",animationRange:"0px -8px"}}),e("div",{className:"w-2 h-2 bg-blue-500 rounded-full animate-[jumping_1s_0.6s_infinite_ease-in-out] hover:bg-blue-600",style:{transform:"translateY(0)",animationRange:"0px -8px"}})]})}function $u(){const{client:e}=tr(),[t,n]=Oe([]),[r,a]=Oe(!0),[s,i]=Oe(!1),o=Be(0),l=Ve(async()=>{const t=o.current+1;o.current=t,a(!0),i(!1);try{const r=await e.apps.getInstalledApps("tools"),s=[];for(const e of r){const t=e,n=t.oauth_collection_ids??[],r=t.manifest.oauth_providers??{};if(!t.manifest.tool_collections)continue;const a=t.manifest.tool_collections.map(e=>lr(e)).filter(e=>"mcp"===e.type&&n.includes(e.id)),i=new Map,o=new Map,l=[];for(const e of a)if(e.oauth_provider){const t=i.get(e.oauth_provider)??[];t.push(e),i.set(e.oauth_provider,t)}else if(e.oauth_app){const t=o.get(e.oauth_app)??[];t.push(e),o.set(e.oauth_app,t)}else l.push(e);for(const[e,n]of i)s.push({key:`${t.id}:provider:${e}`,appId:t.id,appName:t.manifest.title||t.manifest.name,label:r[e]?.display_name||e,representativeId:n[0].id,memberIds:n.map(e=>e.id),memberNames:n.map(e=>e.name)});for(const[e,n]of o)s.push({key:`${t.id}:oauthapp:${e}`,appId:t.id,appName:t.manifest.title||t.manifest.name,label:e,representativeId:n[0].id,memberIds:n.map(e=>e.id),memberNames:n.map(e=>e.name)});for(const e of l)s.push({key:`${t.id}:individual:${e.id}`,appId:t.id,appName:t.manifest.title||t.manifest.name,label:e.name,representativeId:e.id,memberIds:[e.id],memberNames:[e.name]})}if(o.current!==t)return;if(n(s),a(!1),0===s.length)return;i(!0);const l=new Map,c=await Promise.all(s.map(async t=>{try{let n=l.get(t.appId);n||(n=e.remoteMcpConnections.getStatus(t.appId),l.set(t.appId,n));const r=(await n).find(e=>e.collection_id===t.representativeId);return{...t,authStatus:r}}catch{return t}}));if(o.current!==t)return;n(c)}catch(e){o.current===t&&(console.error("Failed to load MCP tool collections:",e),n([]))}finally{o.current===t&&(a(!1),i(!1))}},[e]);return He(()=>{l()},[l]),{groups:t,loading:r,statusLoading:s,reload:l}}function Lu(e,t){return!!t?.length&&e.memberIds.every(e=>t.includes(e))}function Mu(e,t,n){const r=new Set(t??[]);if(n)for(const t of e.memberIds)r.delete(t);else for(const t of e.memberIds)r.add(t);return Array.from(r)}function Fu(e,t){return e.filter(e=>!0===e.authStatus?.authenticated&&!Lu(e,t)).length}function Ou(e,t){return e.filter(e=>!0===e.authStatus?.authenticated&&!Lu(e,t)).map(e=>e.label)}function Uu({isOpen:n,onClose:r,groups:a,loading:s,statusLoading:i=!1,reload:o,disabledCollections:l,onChange:c,onConnectionChange:d,readOnly:u=!1}){const{t:m}=Ze(),p=()=>{o(),d?.()};return t(Js,{isOpen:n,onClose:r,size:"md",className:"max-w-[92vw] sm:max-w-[620px] lg:max-w-[620px]",children:[e(Ks,{children:m("mcpConnections.title")}),t(Ys,{children:[e("p",{className:"mb-4 text-sm text-muted",children:m("mcpConnections.subtitle")}),s?e("div",{className:"flex items-center justify-center py-8",children:e(yi,{className:"size-5"})}):0===a.length?e("div",{className:"py-8 text-center text-sm text-muted",children:m("mcpConnections.empty")}):e("div",{className:"space-y-1",children:a.map(n=>{const r=!Lu(n,l),a=!0===n.authStatus?.authenticated;return t("div",{className:"flex items-center justify-between gap-3 py-3",children:[t("div",{className:"flex min-w-0 items-center gap-2",children:[e(a?wt:nn,{className:"size-4 shrink-0 "+(a?"text-success":"text-muted"),"aria-hidden":"true"}),e(As,{description:t("div",{className:"space-y-0.5",children:[e("div",{className:"font-medium",children:n.appName}),n.memberNames.length>1&&e("div",{className:"text-xs text-muted",children:n.memberNames.join(" · ")})]}),placement:"top",asChild:!0,children:e("span",{className:"truncate "+(r?"text-foreground":"text-muted line-through"),children:n.label})})]}),t("div",{className:"flex shrink-0 items-center gap-3",children:[i&&!n.authStatus?e(Ms,{variant:"outline",size:"sm",disabled:!0,className:"h-6 w-32 justify-center px-2 text-xs",title:m("mcpConnections.checkingStatus"),children:e(yi,{className:"size-3"})}):e(Ni,{appId:n.appId,collectionId:n.representativeId,collectionName:n.label,authenticated:n.authStatus?.authenticated,onAuthChange:p,variant:"compact",showDisconnect:!0,readOnly:u}),c&&e(vi,{size:"sm",value:r,onChange:e=>c(Mu(n,l,e)),disabled:u,"aria-label":m(r?"mcpConnections.deactivateAria":"mcpConnections.activateAria",{name:n.label})})]})]},n.key)})})]})]})}function Wu({disabledCollections:r,onChange:a,onConnectionChange:s,readOnly:i=!1,variant:o="outline",size:l="sm"}){const{t:c}=Ze(),{groups:d,loading:u,statusLoading:m,reload:p}=$u(),[h,f]=Oe(!1);if(!u&&0===d.length)return null;const g=Fu(d,r),v=Ou(d,r),b=v.slice(0,2),x=v.length-b.length,y=b.length>0?`${b.join(", ")}${x>0?` +${x}`:""}`:void 0;return t(n,{children:[t("div",{className:"flex min-w-0 items-center gap-2",children:[y&&e("span",{className:"max-w-48 truncate text-muted",title:v.join(", "),children:y}),t(Ms,{variant:o,size:l,className:"shrink-0",onClick:()=>f(!0),disabled:u,"aria-label":c("mcpConnections.manage"),children:[e("span",{children:c("mcpConnections.label")}),g>0&&e(Us,{variant:"success",children:g})]})]}),e(Uu,{isOpen:h,onClose:()=>f(!1),groups:d,loading:u,reload:p,statusLoading:m,disabledCollections:r,onChange:a,onConnectionChange:s,readOnly:i})]})}function Bu({disabledCollections:n,onChange:r,onConnectionChange:a,readOnly:s=!1}){const{t:i}=Ze(),{groups:o,loading:l,statusLoading:c,reload:d}=$u();if(!l&&0===o.length)return null;const u=()=>{d(),a?.()};return l&&0===o.length?t("div",{className:"flex items-center gap-2 border-y border-border/70 py-2 text-sm text-muted",children:[e(yi,{className:"size-4"}),e("span",{children:i("mcpConnections.label")})]}):e("div",{className:"space-y-1",children:o.map(a=>{const o=!Lu(a,n),l=!0===a.authStatus?.authenticated;return t("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-2 py-2 text-sm",children:[t("div",{className:"flex min-w-36 flex-1 items-center gap-2",children:[e(l?wt:nn,{className:"size-4 shrink-0 "+(l?"text-success":"text-muted"),"aria-hidden":"true"}),e(As,{description:t("div",{className:"space-y-0.5",children:[e("div",{className:"font-medium",children:a.appName}),a.memberNames.length>1&&e("div",{className:"text-xs text-muted",children:a.memberNames.join(" · ")})]}),placement:"top",asChild:!0,children:e("span",{className:"block truncate "+(o?"text-foreground":"text-muted line-through"),children:a.label})})]}),c&&!a.authStatus?e(Ms,{variant:"outline",size:"sm",disabled:!0,className:"h-6 w-32 justify-center px-2 text-xs",title:i("mcpConnections.checkingStatus"),children:e(yi,{className:"size-3"})}):e(Ni,{appId:a.appId,collectionId:a.representativeId,collectionName:a.label,authenticated:a.authStatus?.authenticated,onAuthChange:u,variant:"compact",showDisconnect:!0,readOnly:s}),r&&t("div",{className:"flex min-w-24 items-center justify-end gap-2 text-xs",children:[e("span",{className:o?"text-muted":"text-attention",children:i(o?"mcpConnections.enabled":"mcpConnections.disabled")}),e(vi,{size:"sm",value:o,onChange:e=>r(Mu(a,n,e)),disabled:s,"aria-label":i(o?"mcpConnections.deactivateAria":"mcpConnections.activateAria",{name:a.label})})]})]},a.key)})})}function Vu({disabledCollections:r,onChange:a,onConnectionChange:s,readOnly:i=!1}){const{t:o}=Ze(),{groups:l,loading:c,statusLoading:d,reload:u}=$u(),[m,p]=Oe(!1);if(!c&&0===l.length)return null;const h=Fu(l,r);return t(n,{children:[e(di,{align:"left",trigger:e(Ms,{variant:"ghost",size:"icon",className:"size-8 rounded-md text-muted hover:bg-muted",title:o("mcpConnections.settings"),disabled:c,children:e("span",{className:"flex size-5 items-center justify-center rounded-[3px] border border-muted text-sm font-semibold leading-none","aria-hidden":"true",children:"/"})}),children:t(ui,{onClick:()=>p(!0),isDisabled:c,children:[e("span",{children:o("mcpConnections.title")}),h>0&&e(Us,{variant:"success",children:h})]})}),e(Uu,{isOpen:m,onClose:()=>p(!1),groups:l,loading:c,reload:u,statusLoading:d,disabledCollections:r,onChange:a,onConnectionChange:s,readOnly:i})]})}const qu=[/conversation\.json$/,/-conversation\.json$/,/^tools\.json$/];function Hu(e,t,n=0){const[r,a]=Oe([]),[s,i]=Oe(!1),[o,l]=Oe(null),[c,d]=Oe(0),u=Be(0),m=Ve(async()=>{if(!t)return;const n=++u.current;i(!0),l(null);try{const r=await e.files.listArtifacts(t);if(n!==u.current)return;const s=r.map(e=>function(e,t){const n=`agents/${t}/`,r=e.indexOf(n);return-1!==r?e.slice(r+n.length):e.split("/").pop()??e}(e,t)).filter(e=>e&&!function(e){const t=e.split("/").pop()??e;return qu.some(e=>e.test(t))}(e));a(s)}catch(e){if(n!==u.current)return;l(e instanceof Error?e.message:"Failed to list artifacts"),a([])}finally{n===u.current&&i(!1)}},[e,t]);He(()=>{m()},[m,n,c]);const p=Fe(()=>function(e){const t={children:[]};for(const n of e){const e=n.split("/");let r=t,a="";for(let t=0;t<e.length;t++){const n=e[t];a=a?`${a}/${n}`:n;const s=t===e.length-1;let i=r.children.find(e=>e.name===n);i||(i={name:n,path:a,isDirectory:!s,children:[]},r.children.push(i)),r=i}}const n=e=>{e.children.sort((e,t)=>e.isDirectory!==t.isDirectory?e.isDirectory?-1:1:e.name.localeCompare(t.name)),e.children.forEach(n)};return n(t),t.children}(r),[r]),h=Ve(()=>{d(e=>e+1)},[]);return{tree:p,flatFiles:r,isLoading:s,error:o,refresh:h}}function Gu({node:n,depth:a,runId:s,onDownload:i,downloadingPath:o,forceExpanded:l=!1}){const[c,d]=Oe(!1),u=l||c;if(n.isDirectory)return t("div",{className:"min-w-0",children:[t(r,{variant:"unstyled",className:"flex w-full max-w-full items-center justify-start gap-1.5 rounded px-1 py-1 text-start text-sm hover:bg-muted/30",style:{paddingInlineStart:14*a+4+"px"},onClick:()=>d(e=>!e),"aria-expanded":u,children:[u?e(at,{className:"size-3.5 shrink-0 text-muted"}):e(on,{className:"size-3.5 shrink-0 text-muted cn-rtl-flip"}),e(u?ln:cn,{className:"size-4 shrink-0 text-info"}),e("span",{className:"min-w-0 truncate font-medium",title:n.path,children:(m=n.name,m.replace(/[_-]/g," ").replace(/\b\w/g,e=>e.toUpperCase()))})]}),u&&n.children.map(t=>e(Gu,{node:t,depth:a+1,runId:s,onDownload:i,downloadingPath:o,forceExpanded:l},`${s}:${t.path}`))]});var m;const p=o===n.path;return e("div",{className:"min-w-0",children:t(r,{variant:"unstyled",className:"flex w-full max-w-full items-center justify-start gap-1.5 rounded px-1 py-1 text-start text-sm hover:bg-muted/30",style:{paddingInlineStart:14*a+4+"px"},onClick:()=>i(n.path),disabled:p,title:n.path,children:[p?e(an,{className:"size-3.5 shrink-0 animate-spin text-info"}):e("span",{className:"size-3.5 shrink-0"}),e(dn,{className:"size-4 shrink-0 text-muted"}),e("span",{className:"min-w-0 truncate",children:n.name})]})})}function Ju(e){return e.reduce((e,t)=>t.isDirectory?e+Ju(t.children):e+1,0)}function Ku(e,t){const n=t.trim().toLocaleLowerCase();return n?e.flatMap(e=>{const t=`${e.name} ${e.path}`.toLocaleLowerCase().includes(n);if(!e.isDirectory)return t?[e]:[];const r=Ku(e.children,n);return t?[{...e}]:r.length>0?[{...e,children:r}]:[]}):e}function Yu({icon:n,children:r,action:a}){return t(y,{className:"h-full min-h-[240px] flex-col text-center text-muted",children:[n,e("span",{className:"text-sm",children:r}),a]})}const Qu=Me.memo(function({runId:a,refreshKey:s=0}){const{t:i}=Ze(),{client:o}=tr(),{tree:l,flatFiles:c,isLoading:u,error:m,refresh:p}=Hu(o,a,s),[h,f]=Oe(null),[g,v]=Oe(""),b=g.trim(),y=Fe(()=>Ku(l,b),[l,b]),w=Fe(()=>Ju(y),[y]),N=Je(),k=Ve(async e=>{if(a){f(e);try{const{url:t}=await o.files.getArtifactDownloadUrl(a,e,"attachment");!function(e,t){const n=document.createElement("a");n.href=e,n.download=t,n.rel="noopener noreferrer",n.style.display="none",document.body.appendChild(n),n.click(),n.remove()}(t,e.split("/").pop()||"artifact")}catch(e){console.error("Failed to get artifact download URL:",e)}finally{f(null)}}},[o,a]);return a?u&&0===c.length?e(Yu,{icon:e(an,{className:"mb-2 size-6 animate-spin"}),children:i("agent.loadingArtifacts")}):m?e("div",{className:"flex flex-col items-center justify-center p-4 text-muted w-full",children:t(x,{title:"Fail to load Artifacts",className:"w-full",action:p,actionLabel:t(n,{children:[e(sn,{className:"size-3.5 me-1.5"}),i("agent.retry")]}),children:[e("span",{className:"break-all text-muted",children:m})," ",e("br",{})]})}):0===c.length?e(Yu,{icon:e(rn,{className:"mb-2 size-8"}),action:t(r,{variant:"ghost",size:"sm",className:"mt-2",onClick:p,children:[e(sn,{className:"size-3.5 me-1.5"}),i("agent.refresh")]}),children:i("agent.noArtifactsYet")}):t("div",{className:"flex flex-col h-full",children:[t("div",{className:"flex shrink-0 flex-col gap-2 px-3 py-2",children:[t("div",{className:"flex items-center justify-between gap-2 text-xs text-muted",children:[e("span",{children:b?`${w} of ${c.length} file${1!==c.length?"s":""}`:`${c.length} file${1!==c.length?"s":""}`}),e(r,{variant:"ghost",size:"sm",onClick:p,disabled:u,className:"h-6 w-6 p-0",children:e(sn,{className:"size-3.5 "+(u?"animate-spin":"")})})]}),e("label",{htmlFor:N,className:"sr-only",children:i("form.filter")}),e(d,{id:N,type:"text",role:"searchbox",autoComplete:"off",placeholder:i("store.searchPlaceholder"),value:g,onChange:v,clearable:!0})]}),e("div",{className:"flex-1 overflow-y-auto px-3 pb-2",children:y.length>0?e("div",{className:"min-w-0",children:y.map(t=>e(Gu,{node:t,depth:0,runId:a,onDownload:k,downloadingPath:h,forceExpanded:!!b},`${a}:${t.path}`))}):e("div",{className:"px-1 py-6 text-sm text-muted",children:i("agent.noContentAvailable")})})]}):e(Yu,{icon:e(rn,{className:"mb-2 size-8"}),children:"No run selected"})});function Zu(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Xu(e){if(!Zu(e))return;const t=e.browseruse??e.browser_use;if(!Zu(t))return;const n={widget:"string"==typeof t.widget?t.widget:void 0,browser_workflow_id:"string"==typeof t.browser_workflow_id?t.browser_workflow_id:void 0,workstream_id:"string"==typeof t.workstream_id?t.workstream_id:void 0,phase:"string"==typeof t.phase?t.phase:void 0,url:"string"==typeof t.url?t.url:void 0,title:"string"==typeof t.title?t.title:void 0,screenshot:"string"==typeof t.screenshot?t.screenshot:void 0,raw_screenshot:"string"==typeof t.raw_screenshot?t.raw_screenshot:void 0,prefer_raw_screenshot:"boolean"==typeof t.prefer_raw_screenshot?t.prefer_raw_screenshot:void 0,updated_at:"number"==typeof t.updated_at?t.updated_at:void 0};return n.widget&&"browseruse"!==n.widget||!(n.url||n.title||n.screenshot||n.raw_screenshot)?void 0:n}function em(e){return e.replace(/^artifact:\/\//,"").replace(/^artifact:/,"").replace(/^\/+/,"")}function tm(e){return e?e.replace(/_/g," "):"browser"}function nm({state:n,runId:r,className:a,compact:s}){const{t:o}=Ze(),{client:l}=tr(),c=Za(),{openImage:d}=Ql(),[u,m]=Oe(),p=!1===n.prefer_raw_screenshot?n.screenshot||n.raw_screenshot:n.raw_screenshot||n.screenshot,h=n.title||n.url||o("agent.browserUse"),g=Fe(()=>p&&em(p).split("/").pop()||o("agent.browserScreenshot"),[p,o]);return He(()=>{if(!p)return void m(void 0);if(p.startsWith("http://")||p.startsWith("https://"))return void m(p);if(!r)return void m(void 0);let e=!1;return(async()=>{const t=em(p);try{const n=es(r,t,"inline"),a=c?await c.getOrFetch(n,async()=>(await l.files.getArtifactDownloadUrl(r,t,"inline")).url):(await l.files.getArtifactDownloadUrl(r,t,"inline")).url;e||m(a)}catch(n){console.error(`Failed to resolve browser screenshot ${t}`,n),e||m(void 0)}})(),()=>{e=!0}},[l,r,p,c]),t("div",s?{className:i("overflow-hidden rounded-md border border-border/70 bg-transparent",a),children:[t("div",{className:"flex items-center gap-2 px-2 py-1.5",children:[e(un,{className:"size-3.5 shrink-0 text-info"}),t("div",{className:"min-w-0 flex-1",children:[t("div",{className:"flex min-w-0 items-center gap-1",children:[e("span",{className:"text-xs font-medium text-foreground",children:o("agent.browserPreview")}),n.phase&&t("span",{className:"truncate text-[11px] capitalize text-muted",children:["· ",tm(n.phase)]})]}),e("div",{className:"truncate text-[11px] text-muted",title:h,children:h})]}),n.url&&e("a",{href:n.url,target:"_blank",rel:"noopener noreferrer",title:o("agent.openInNewTab"),className:i("inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-md","text-muted hover:bg-muted hover:text-foreground"),children:e(mn,{className:"size-3"})})]}),p&&(u?e("button",{type:"button",className:"block w-full bg-mixer-muted/20 text-start",onClick:()=>d(u,g),title:o("agent.clickToEnlarge"),children:e("img",{src:u,alt:g,className:"block max-h-32 w-full object-contain"})}):t("div",{className:"flex min-h-16 items-center justify-center gap-2 bg-mixer-muted/20 px-3 py-4 text-xs text-muted",children:[e(Lt,{className:"size-4"}),e("span",{children:o("agent.browserScreenshotPending")})]}))]}:{className:i("overflow-hidden rounded-md border border-muted bg-mixer-muted/10",a),children:[t("div",{className:"flex items-start justify-between gap-2 border-b border-muted px-2.5 py-2",children:[t("div",{className:"flex min-w-0 items-start gap-2",children:[e(un,{className:"mt-0.5 size-4 shrink-0 text-info"}),t("div",{className:"min-w-0",children:[e("div",{className:"text-xs font-medium text-foreground",children:o("agent.browserUse")}),e("div",{className:"truncate text-xs text-muted",title:h,children:h})]})]}),e(f,{variant:"info",className:"shrink-0 capitalize",children:tm(n.phase)})]}),u?e("button",{type:"button",className:"block w-full bg-mixer-muted/20 text-start",onClick:()=>d(u,g),title:o("agent.clickToEnlarge"),children:e("img",{src:u,alt:g,className:"block max-h-56 w-full object-contain"})}):t("div",{className:"flex min-h-28 items-center justify-center gap-2 bg-mixer-muted/20 px-3 py-6 text-xs text-muted",children:[e(Lt,{className:"size-4"}),e("span",{children:o("agent.browserScreenshotPending")})]}),n.url&&t("div",{className:"flex items-center gap-2 border-t border-muted px-2.5 py-1.5",children:[e("a",{href:n.url,target:"_blank",rel:"noopener noreferrer",className:"min-w-0 flex-1 truncate text-xs text-info hover:underline",title:n.url,children:n.url}),e("a",{href:n.url,target:"_blank",rel:"noopener noreferrer",title:o("agent.openInNewTab"),className:i("inline-flex h-6 shrink-0 items-center justify-center rounded-md px-1.5","text-muted hover:bg-muted hover:text-foreground"),children:e(mn,{className:"size-3"})})]})]})}function rm({documents:t,activeId:n,onSelect:a}){return 0===t.length?null:e("div",{className:"flex items-center gap-1 px-2 py-1.5",children:e(g,{align:"right",trigger:e(r,{variant:"ghost",size:"xs",title:"All opened documents",className:"flex items-center gap-1.5 max-w-[220px] text-xs h-7 px-2",children:e(at,{className:"size-3 shrink-0"})}),children:t.map(t=>e(v,{onClick:()=>a(t.id),className:t.id===n?"font-medium":"",children:e("span",{className:"truncate max-w-[200px]",children:t.title})},t.id))})})}const am=Me.memo(function({isOpen:n,documents:a,activeDocumentId:s,onSelectDocument:i,onCloseDocument:o,onUpdateDocumentTitle:l,refreshKey:c,runId:d}){const{client:u}=tr(),{t:m}=Ze(),[p,f]=Oe(null),[g,v]=Oe(!1),[b,x]=Oe(null),[y,w]=Oe(null),N=Ve(async e=>{v(!0),x(null);try{const[t,n]=await Promise.all([u.store.objects.getObjectText(e),u.store.objects.retrieve(e)]);f(t.text??null);const r=n.name;w(r),r&&l?.(e,r)}catch(e){const t=e instanceof Error?e.message:m("agent.failedToLoadDocument");x(t),f(null)}finally{v(!1)}},[u,l,m]);return He(()=>{s&&n&&N(s)},[s,c,n,N]),n&&0!==a.length?t("div",{className:"h-full shadow-xl border border-muted/20 overflow-hidden flex flex-col",children:[t("div",{className:"flex items-center justify-between px-3 py-2 border-b border-muted/20 shrink-0",children:[t("div",{className:"flex items-center gap-2 min-w-0",children:[e(Mt,{className:"size-4 text-muted shrink-0"}),e("h3",{className:"font-bold text-sm truncate",children:y||m("agent.document")})]}),t("div",{className:"flex items-center gap-1",children:[e(rm,{documents:a,activeId:s,onSelect:i}),s&&e(sa,{href:`/store/objects/${s}#overview`,topLevelNav:!0,className:"inline-flex items-center justify-center rounded-md text-sm font-medium h-8 w-8 hover:bg-muted/20 text-muted hover:text-foreground",children:e(h,{description:m("agent.openDocument"),placement:"top",size:"xs",children:e(mn,{className:"size-4"})})}),e(r,{variant:"ghost",size:"sm",onClick:()=>s&&o(s),title:m("agent.close"),children:e(ut,{className:"size-4"})})]})]}),e("div",{className:"flex-1 overflow-y-auto px-4 py-4",children:g?t("div",{className:"flex items-center justify-center py-12",children:[e(an,{className:"size-5 animate-spin text-muted"}),e("span",{className:"ms-2 text-sm text-muted",children:m("agent.loadingDocument")})]}):b?e("div",{className:"p-4 rounded-md bg-destructive/10 text-destructive text-sm",children:b}):p?e("div",{className:"prose prose-sm dark:prose-invert max-w-none",children:e(oa,{artifactRunId:d,children:p})}):t("div",{className:"flex flex-col items-center justify-center py-12 text-muted",children:[e(Mt,{className:"size-8 mb-2"}),e("span",{className:"text-sm",children:m("agent.noContentAvailable")})]})})]}):null});const sm=Me.memo(function({plan:n,workstreamStatus:a,isOpen:s,onClose:o,plans:l=[],activePlanIndex:c=0,onChangePlan:d=()=>{}}){const{t:u}=Ze();if(!s)return null;const m=n.plan||[],p=m.length,h=m.reduce((e,t)=>t?.id&&("completed"===a.get(t.id.toString())||"completed"===t.status)?e+1:e,0),f=p>0?Math.round(h/p*100):0,g=l.length>0?l.length-c:1,v=l[c]?.timestamp;return 0===m.length?e("div",{className:"h-full overflow-hidden",children:t(y,{className:"h-full min-h-[240px] flex-col text-center text-muted",children:[e(pn,{className:"mb-2 size-8"}),e("span",{className:"text-sm",children:u("agent.noPlanAvailable")})]})}):e("div",{className:"h-full overflow-hidden",children:t("div",{className:"flex h-full flex-col gap-4 overflow-y-auto px-2 py-3",children:[t("div",{className:"space-y-2",children:[t("div",{className:"flex items-start justify-between gap-3",children:[t("div",{className:"min-w-0",children:[e("div",{className:"text-sm font-medium text-foreground",children:u("agent.taskProgress")}),e("div",{className:"text-xs text-muted",children:u("agent.tasksCompleted",{completed:h,total:p})})]}),l.length>1&&t("div",{className:"flex shrink-0 items-center gap-1 text-xs text-muted",children:[e(r,{variant:"ghost",size:"icon",className:"size-7",onClick:()=>d(Math.min(l.length-1,c+1)),disabled:c>=l.length-1,"aria-label":u("agent.olderPlan"),title:u("agent.olderPlan"),children:e(pt,{className:"size-4","aria-hidden":"true"})}),t("div",{className:"min-w-20 text-center",children:[t("div",{className:"font-medium text-foreground",children:[g,"/",l.length]}),e("div",{className:"truncate",children:v?new Date(v).toLocaleTimeString():u("agent.unknownTime")})]}),e(r,{variant:"ghost",size:"icon",className:"size-7",onClick:()=>d(Math.max(0,c-1)),disabled:c<=0,"aria-label":u("agent.newerPlan"),title:u("agent.newerPlan"),children:e(ht,{className:"size-4","aria-hidden":"true"})})]})]}),e("div",{className:"h-2 overflow-hidden rounded-full bg-mixer-muted/20",role:"progressbar","aria-valuemin":0,"aria-valuemax":p,"aria-valuenow":h,"aria-label":u("agent.taskProgress"),children:e("div",{className:"h-full rounded-full bg-success transition-all duration-300",style:{width:`${f}%`}})})]}),e("ol",{className:"divide-y divide-border/60",children:m.map((n,r)=>{const s=n.id?n.id.toString():`task-${r}`,o=n.goal||`Task ${r+1}`,l=n.id?`task-${n.id.toString()}`:`task-${o}-${n.status||"pending"}`;let c=n.status||"pending";a.has(s)&&(c=a.get(s));let d=hn,m="text-muted";"in_progress"===c?(d=Wt,m="text-info"):"completed"===c&&(d=Rt,m="text-success");const p=u("completed"===c?"agent.completed":"in_progress"===c?"agent.inProgress":"agent.pending");return t("li",{className:"grid grid-cols-[auto_minmax(0,1fr)_auto] items-start gap-3 px-1 py-3",children:[e("span",{className:"mt-0.5 min-w-5 text-center text-xs font-medium tabular-nums text-muted/80",children:s}),e("span",{className:"min-w-0 text-sm leading-5 text-foreground/85",children:o}),t("span",{className:i("flex items-center gap-1.5 text-xs font-medium",m),children:[e(d,{className:"size-3.5 shrink-0","aria-hidden":"true"}),e("span",{children:p})]})]},l)})}),(()=>{const n=new Set(m.filter(e=>e?.id).map(e=>e.id.toString())),r=Array.from(a.entries()).filter(([e])=>"main"!==e&&!n.has(e));return r.length>0?t("div",{className:"mt-1 px-1 py-2",children:[e("div",{className:"mb-2 text-xs font-medium text-muted",children:u("agent.workstreams")}),e("div",{className:"divide-y divide-border/60",children:r.map(([n,r])=>{let a=hn,s="text-muted",o=u("agent.pending");return"in_progress"===r?(a=Wt,s="text-info",o=u("agent.inProgress")):"completed"===r&&(a=Rt,s="text-success",o=u("agent.completed")),t("div",{className:"flex items-center gap-2 py-2",children:[e(a,{className:i("size-3.5 shrink-0",s)}),e("span",{className:"min-w-0 flex-1 truncate text-xs font-medium text-foreground/80",children:n}),e("span",{className:"text-xs font-medium text-muted",children:o})]},n)})})]}):null})()]})})});function im({icon:n,children:r}){return t(y,{className:"h-full min-h-[240px] flex-col text-center text-muted",children:[n,e("span",{className:"text-sm",children:r})]})}function om({files:n}){const{t:r}=Ze(),a=Fe(()=>n?Array.from(n.values()):[],[n]),s=t=>{switch(t){case cr.UPLOADING:case cr.PROCESSING:return e(an,{className:"size-4 animate-spin text-info"});case cr.READY:return e(bn,{className:"size-4 text-success"});case cr.ERROR:return e(vn,{className:"size-4 text-destructive"});default:return e(Mt,{className:"size-4 text-muted"})}},i=t=>{switch(t){case cr.UPLOADING:return e(f,{variant:"info",children:r("agent.uploading")});case cr.PROCESSING:return e(f,{variant:"info",children:r("agent.processing")});case cr.READY:return e(f,{variant:"success",children:r("agent.ready")});case cr.ERROR:return e(f,{variant:"destructive",children:r("agent.error")});default:return null}};return e("div",{className:"h-full min-h-0",children:0===a.length?e(im,{icon:e(Mt,{className:"mb-2 size-8"}),children:r("agent.noFilesUploadedYet")}):e("div",{className:"space-y-2 p-2",children:a.map(n=>t("div",{className:"flex items-start gap-2 p-2 border border-muted rounded-md",children:[e("div",{className:"mt-0.5",children:s(n.status)}),t("div",{className:"flex-1 min-w-0",children:[t("div",{className:"flex items-center justify-between gap-2",children:[e("span",{className:"text-sm font-medium truncate",children:n.name}),i(n.status)]}),n.error&&e("div",{className:"text-xs text-destructive mt-1",children:n.error})]})]},n.id))})})}class lm extends Me.Component{state={hasError:!1};static getDerivedStateFromError(e){return{hasError:!0,message:e instanceof Error?e.message:String(e)}}componentDidCatch(e,t){console.error("Agent right panel section failed to render",{error:e,componentStack:t.componentStack})}render(){return this.state.hasError?t("div",{className:i("rounded-md border border-destructive bg-mixer-destructive/10 text-destructive",this.props.compact?"p-2 text-xs":"m-3 p-3 text-sm"),children:[e("div",{className:"font-medium",children:this.props.title}),e("div",{className:"mt-1 text-xs text-muted",children:this.props.description}),this.state.message&&e("div",{className:"mt-1 break-all text-[11px] text-muted",children:this.state.message})]}):this.props.children}}function cm({workstreams:n,messages:a,runId:s}){const{t:o}=Ze(),{client:l}=tr(),c=p(),d=Fe(()=>function(e){const t=new Map;for(const n of e){const e=Xu(n.details);if(!e)continue;const r=e.workstream_id||n.workstream_id||"main",a=e.updated_at??("number"==typeof n.timestamp?n.timestamp:new Date(n.timestamp).getTime()),s=t.get(r);(!s||a>=s.timestamp)&&t.set(r,{state:{...e,workstream_id:r},timestamp:a})}return new Map(Array.from(t.entries()).map(([e,t])=>[e,t.state]))}(a),[a]),u=o("agent.panelRenderErrorDescription"),m=Ve(e=>{navigator.clipboard.writeText(e),c({status:"success",title:o("agent.runIdCopied"),duration:2e3})},[o,c]),h=Ve(async e=>{try{const t=await ll(l,e);t&&window.open(t,"_blank")}catch{c({status:"error",title:o("agent.failedToDownload")})}},[l,o,c]);return 0===n.length?e(im,{icon:e(fn,{className:"mb-2 size-8"}),children:o("agent.noActiveParallelTasks")}):t("div",{className:"h-full min-h-0 overflow-y-auto px-2 py-2",children:[e("div",{className:"px-1 pb-2 text-xs text-muted",children:o("agent.parallelWorkDescription")}),e("div",{className:"divide-y divide-border/60",children:n.map(n=>{const a="running"===n.status||"canceling"===n.status,l=Math.round(n.elapsed_ms/1e3),c=Math.max(0,Math.round(n.remaining_ms/1e3)),p=n.deadline_ms>0?Math.min(100,Math.round(n.elapsed_ms/n.deadline_ms*100)):0,g=d.get(n.workstream_id),v=n.deadline_ms>0,b=[n.phase?Vo(n.phase):void 0,l>0?o("agent.elapsed",{seconds:l}):void 0,v&&c>0?o("agent.remaining",{seconds:c}):void 0].filter(Boolean),x=(()=>{switch(n.status){case"running":return e(f,{variant:"info",children:o("agent.running")});case"canceling":return e(f,{variant:"attention",children:o("agent.canceling")});case"completed":return e(f,{variant:"done",children:o("agent.completed")});case"failed":return e(f,{variant:"destructive",children:o("agent.failed")});case"timeout":return e(f,{variant:"destructive",children:o("agent.timeout")});case"canceled":return e(f,{variant:"destructive",children:o("agent.canceled")})}})();return e(lm,{title:o("agent.workstreamRenderError"),description:u,compact:!0,children:e("div",{className:"py-3",children:t("div",{className:"flex items-start gap-2",children:[e("span",{className:i("mt-2 size-2 shrink-0 rounded-full",Ko(n.status)),"aria-hidden":"true"}),t("div",{className:"min-w-0 flex-1",children:[t("div",{className:"flex min-w-0 items-center justify-between gap-2",children:[e("span",{className:"min-w-0 truncate text-sm font-medium text-foreground",title:n.workstream_id,children:Vo(n.workstream_id)}),x]}),b.length>0&&e("div",{className:"mt-0.5 truncate text-xs text-muted",children:b.join(" · ")}),a&&v&&e("div",{className:"mt-2 h-1 rounded-full bg-muted",role:"progressbar","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":p,"aria-valuetext":o("agent.workstreamProgress",{percent:p}),children:e("div",{className:"h-full rounded-full bg-info transition-all duration-500",style:{width:`${p}%`}})}),g&&e(lm,{title:o("agent.browserWidgetRenderError"),description:u,compact:!0,children:e(nm,{state:g,runId:s,compact:!0,className:"mt-2"})}),n.child_workflow_run_id&&t("div",{className:"mt-2 flex flex-wrap gap-1",children:[t(r,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs text-muted hover:text-foreground",onClick:()=>m(n.child_workflow_run_id),children:[e(gn,{className:"size-3 me-1"}),o("agent.copyRunId")]}),t(r,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs text-muted hover:text-foreground",onClick:()=>h(n.child_workflow_run_id),children:[e(Xt,{className:"size-3 me-1"}),o("agent.download")]})]})]})]})})},n.launch_id)})})]})}const dm="flex items-center border-b-2 px-2 py-1.5 text-sm font-medium whitespace-nowrap cursor-pointer shrink-0",um="border-transparent text-muted-foreground hover:border-border hover:text-foreground",mm="border-primary text-primary";function pm({tabs:n,current:r,onTabChange:l,label:c,active:d}){const[u,m]=Oe(!1),p=Be(null),h=Be(!1),f=()=>{p.current&&(clearTimeout(p.current),p.current=null)},g=()=>{f(),p.current=setTimeout(()=>m(!1),150)};return He(()=>()=>clearTimeout(p.current??void 0),[]),t(a,{modal:!1,open:u,onOpenChange:e=>{f(),e&&(h.current=!1),m(e)},children:[e(s,{asChild:!0,children:t("button",{type:"button",onMouseEnter:()=>{f(),h.current=!0,m(!0)},onMouseLeave:g,className:i(dm,d?mm:um),children:[c,e(at,{className:"ms-1 size-4"})]})}),e(o,{align:"end",className:"w-max",onMouseEnter:f,onMouseLeave:g,onCloseAutoFocus:e=>{h.current&&e.preventDefault()},children:n.map(t=>e(b,{disabled:t.disabled,onClick:()=>l(t.name),className:i(t.name===r&&"text-primary"),children:t.label},t.name))})]})}function hm({tabs:n,current:r,onTabChange:a,className:s}){const{t:o}=Ze(),l=Be(null),c=Be([]),d=Be(null),[u,m]=Oe({count:n.length,promote:!1}),p=()=>{const e=l.current;if(!e)return;const t=e.clientWidth,a=n.map((e,t)=>c.current[t]?.offsetWidth??0),s=(e,t)=>{let r=0,s=0;for(let i=0;i<n.length;i++){if(i===t)continue;const n=r+(s>0?4:0)+a[i];if(n>e)break;r=n,s+=1}return s};let i;if(a.reduce((e,t)=>e+t,0)+4*Math.max(0,n.length-1)<=t)i={count:n.length,promote:!1};else{const e=d.current?.offsetWidth??0,o=Math.max(1,s(t-e-4,-1)),l=n.findIndex(e=>e.name===r);if(l<0||l<o)i={count:o,promote:!1};else{const n=t-e-a[l]-8;i={count:s(n,l),promote:!0}}}m(e=>e.count===i.count&&e.promote===i.promote?e:i)},h=Be(p);h.current=p,Ke(()=>{h.current()}),He(()=>{const e=l.current;if(!e||"undefined"==typeof ResizeObserver)return;const t=new ResizeObserver(()=>h.current());return t.observe(e),()=>t.disconnect()},[]);const f=n.findIndex(e=>e.name===r);let g,v;if(u.promote&&f>=0){const e=n.filter((e,t)=>t!==f);g=[...e.slice(0,u.count),n[f]],v=e.slice(u.count)}else g=n.slice(0,u.count),v=n.slice(u.count);const b=v.some(e=>e.name===r),x=o("agent.moreTabs");return t("div",{ref:l,className:i("relative",s),children:[t("div",{"aria-hidden":!0,className:"pointer-events-none invisible absolute start-0 top-0 flex w-max gap-1",children:[n.map((t,n)=>e("button",{type:"button",tabIndex:-1,ref:e=>{c.current[n]=e},className:i(dm,um),children:t.label},t.name)),t("button",{type:"button",tabIndex:-1,ref:d,className:i(dm,um),children:[x,e(at,{className:"ms-1 size-4"})]})]}),t("div",{className:"-mb-px flex gap-1 overflow-hidden border-b",children:[g.map(t=>{const n=t.name===r;return e("button",{type:"button","aria-current":n?"page":void 0,disabled:t.disabled,onClick:()=>a(t.name),className:i(dm,n?mm:um,"disabled:pointer-events-none disabled:opacity-50"),children:t.label},t.name)}),v.length>0&&e(pm,{tabs:v,current:r,onTabChange:a,label:x,active:b})]})]})}const fm=Me.memo(function({plan:n,workstreamStatus:a,plans:s=[],activePlanIndex:i=0,onChangePlan:o,activeWorkstreams:l=[],messages:c=[],hideWorkstreams:d=!1,openDocuments:u=[],activeDocumentId:m,onSelectDocument:p,onCloseDocument:h,onUpdateDocumentTitle:f,docRefreshKey:g=0,runId:v,processingFiles:b,showArtifacts:x=!1,artifactRefreshKey:y=0,payloadContent:k,conversationContent:_,onClose:C,defaultTab:S,activeTab:T,onTabChange:I}){const{t:z}=Ze(),[R,j]=Oe(S||"plan"),P=T??R,A=e=>{j(e),I?.(e)},D=!d&&l.length>0,E=u.length>0,$=!!b&&b.size>0,L=Ve((t,n)=>e(lm,{title:z("agent.panelRenderError",{name:t}),description:z("agent.panelRenderErrorDescription"),children:n}),[z]),M={name:"conversation",label:"Conversation",content:_?L("Conversation",e("div",{className:"flex flex-col h-full min-h-0",children:_})):null,is_allowed:!!_},F=[..._?[M]:[],{name:"plan",label:z("agent.plan"),content:L(z("agent.plan"),n?e(sm,{plan:n,workstreamStatus:a||new Map,isOpen:!0,onClose:C,plans:s,activePlanIndex:i,onChangePlan:o}):e(im,{icon:e(fn,{className:"mb-2 size-8"}),children:z("agent.noPlanAvailable")})),is_allowed:!0},{name:"workstreams",label:D?t("span",{className:"inline-flex min-w-0 items-center gap-1 whitespace-nowrap",children:[z("agent.workstreams")," ",e("span",{className:"inline-flex shrink-0 items-center justify-center rounded-full bg-info px-1.5 py-0.5 text-[10px] text-info",children:l.length})]}):z("agent.workstreams"),content:L(z("agent.workstreams"),e(cm,{workstreams:l,messages:c,runId:v})),is_allowed:!d},{name:"documents",label:E?t("span",{className:"inline-flex min-w-0 items-center gap-1 whitespace-nowrap",children:[z("agent.documents")," ",e("span",{className:"inline-flex shrink-0 items-center justify-center rounded-full bg-info px-1.5 py-0.5 text-[10px] text-info",children:u.length})]}):z("agent.documents"),content:L(z("agent.documents"),u.length>0&&p&&h?e(am,{isOpen:!0,documents:u,activeDocumentId:m??null,onSelectDocument:p,onCloseDocument:h,onUpdateDocumentTitle:f,refreshKey:g,runId:v}):e(im,{icon:e(Mt,{className:"mb-2 size-8"}),children:z("agent.noDocumentsOpen")})),is_allowed:!0},{name:"uploads",label:$?t("span",{className:"inline-flex min-w-0 items-center gap-1 whitespace-nowrap",children:[z("agent.uploads")," ",e("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-info"})]}):z("agent.uploads"),content:L(z("agent.uploads"),e(om,{files:b})),is_allowed:!0},{name:"artifacts",label:z("agent.artifacts"),content:L(z("agent.artifacts"),e(Qu,{runId:v,refreshKey:y})),is_allowed:x},{name:"payload",label:z("agent.payload"),content:k?L(z("agent.payload"),e("div",{className:"overflow-y-auto",children:k})):null,is_allowed:!!k}],O=F.filter(e=>void 0===e.is_allowed||!0===e.is_allowed);return t(w,{tabs:F,current:P,onTabChange:A,fullHeight:!0,className:"px-0",children:[t("div",{className:"flex items-end justify-between shrink-0 px-1 py-1 gap-1",children:[e(hm,{tabs:O,current:P,onTabChange:A,className:"min-w-0 flex-1"}),!_&&e(r,{variant:"ghost",size:"sm",className:"shrink-0 ms-1",onClick:C,title:"Close Right Panel",children:e(Et,{className:"size-4"})})]}),e(N,{className:"flex-1 min-h-0 pt-0 pb-0"})]})});function gm(e){if(!e)return[];const t=[];for(let n=0;n<e.length;n++){const r=e[n];if("file"!==r.kind)continue;const a=r.getAsFile();if(a)if(!r.type.startsWith("image/")||a.name&&"image.png"!==a.name)t.push(a);else{const e=r.type.split("/")[1]||"png";t.push(new File([a],`pasted-image-${Date.now()}.${e}`,{type:a.type}))}}return t}function vm(e,t){return{...e,details:{...e.details??{},_deliveryStatus:t}}}function bm(e){const t=e.details,n=t?._messageId;if("string"==typeof n&&n)return n;const r=t?.ack;return"string"==typeof r&&r?r:void 0}function xm(e,t){const n=e?.[t];return"string"==typeof n&&n?n:void 0}function ym(e){return"workflow_run"===e?.streaming_id_scope}function wm(e){if(e.type===ir.STREAMING_CHUNK)return!1;if(e.type===ir.SYSTEM){const t=e.details;if("file_processing"===t?.system_type&&t.files)return!1}return Boolean(e.message)||function(e){return[ir.COMPLETE,ir.IDLE,ir.TERMINATED,ir.REQUEST_INPUT].includes(e.type)}(e)}function Nm(e){if(e)return{type:e.type,timestamp:e.timestamp,workstream_id:e.workstream_id,text:"string"==typeof e.message?e.message.slice(0,80):e.message?"[non-string]":"",display_role:e.details?.display_role,source:e.details?.source}}function km(e,t){if(e.find(e=>e.timestamp===t.timestamp))return e;if(!t.details?._optimistic&&(t.type===ir.QUESTION||rl(t))){const n="string"==typeof t.details?.ack?t.details.ack:void 0,r=n?vm(t,"consumed"):t;if(n){const a=e.filter(e=>!((e.type===t.type||rl(e))&&e.details?._optimistic&&bm(e)===n));return el(a,r),a}if(t.type===ir.QUESTION){const n=e.filter(e=>e.type===ir.QUESTION&&e.details?._optimistic&&e.message===t.message&&(e.workstream_id??"main")===(t.workstream_id??"main"));if(1===n.length){const r=e.filter(e=>e!==n[0]);return el(r,t),r}}}const n=[...e];return el(n,t),n}function _m(e,t){const[n,r]=Oe([]),[a,s]=Oe(!1),[i,o]=Oe("loading"),[l,c]=Oe(null),[d,u]=Oe(null),[m,p]=Oe(new Map),[h,f]=Oe(0),g=Ve(()=>f(e=>e+1),[]),v=Be(null),b=Be(0),[x,y]=Oe(new Map),w=Be(new Map),N=Be(null),[k,_]=Oe(!1),C=Be(null),S=Ve(()=>{const e=N.current;e&&("raf"===e.mode?cancelAnimationFrame(e.id):clearTimeout(e.id),N.current=null)},[]),T=Ve(()=>{w.current.size>0&&(y(new Map(w.current)),_(!0),C.current&&clearTimeout(C.current),C.current=setTimeout(()=>_(!1),50)),N.current=null},[]);He(()=>{s(!nl(n))},[n]),He(()=>{Xo("stream state",{agentRunId:t,messageCount:n.length,streamingCount:x.size,initialHistoryStatus:i,isCompleted:a,lastDeliveredTs:b.current,first:Nm(n[0]),last:Nm(n[n.length-1])})},[t,i,a,n,x.size]),He(()=>{const n=v.current!==t;v.current=t,n&&(r([]),o("loading"),c(null),u(null),y(new Map),p(new Map),b.current=0);const a=new AbortController,s=n?void 0:b.current||void 0;return Xo("stream start",{agentRunId:t,isNewConversation:n,since:s,streamNonce:h}),e.agents.getInternals(t).then(e=>{a.signal.aborted||(Xo("internals loaded",{agentRunId:t,status:e.status,first_workflow_run_id:e.first_workflow_run_id}),c(e.status?.toUpperCase()??null),u(e.first_workflow_run_id??null))}).catch(e=>{a.signal.aborted||console.error("Failed to check agent run status:",e)}),e.agents.streamMessages(t,e=>{if(!a.signal.aborted){if(Xo("stream message",{agentRunId:t,type:e.type,timestamp:e.timestamp,workstream_id:e.workstream_id,hasMessage:Boolean(e.message),display_role:e.details?.display_role,source:e.details?.source}),e.timestamp&&e.timestamp>b.current&&(b.current=e.timestamp),e.type===ir.STREAMING_CHUNK){const t=e.details,n=function(e){const t=e.details,n=xm(t,"streaming_id"),r=xm(t,"activity_id");return n&&ym(t)?n:r??n}(e);if(!n)return;const r=w.current.get(n)||{text:"",workstreamId:e.workstream_id,startTimestamp:Date.now(),activityId:t?.activity_id,streamingId:t?.streaming_id},a=r.text+(e.message||"");return w.current.set(n,{text:a,workstreamId:e.workstream_id,isComplete:t.is_final,startTimestamp:r.startTimestamp,activityId:t?.activity_id,streamingId:t?.streaming_id}),void(null===N.current&&(document.hidden?N.current={mode:"timeout",id:window.setTimeout(T,16)}:N.current={mode:"raf",id:requestAnimationFrame(T)}))}if(e.type===ir.SYSTEM){const t=e.details;if("file_processing"===t?.system_type&&t.files)return void p(new Map(t.files.map(e=>[e.id,e])))}if(e.type===ir.THOUGHT||e.type===ir.ANSWER){const t=function(e){const t=e.details,n=xm(t,"streaming_id"),r=xm(t,"activity_id"),a=[];return n&&ym(t)&&a.push(n),r&&a.push(r),[...new Set(a)]}(e);if(t.length>0){for(const e of t)w.current.delete(e);y(e=>{const n=new Map(e);let r=!1;for(const e of t)r=n.delete(e)||r;return r?n:e})}}e.type!==ir.COMPLETE&&e.type!==ir.IDLE||w.current.size>0&&T(),wm(e)&&r(t=>km(t,e))}},s,a.signal,{onHistoryLoaded:e=>{if(a.signal.aborted)return;const n=e.filter(wm);Xo("history loaded",{agentRunId:t,count:e.length,timelineCount:n.length,since:s,first:Nm(e[0]),last:Nm(e[e.length-1])}),o(e.length>0?"has_messages":"empty"),n.length>0&&r(e=>n.reduce((e,t)=>(t.timestamp&&t.timestamp>b.current&&(b.current=t.timestamp),km(e,t)),e))},onHistoryError:e=>{a.signal.aborted||(Xo("history error",{agentRunId:t,error:e instanceof Error?e.message:String(e)}),o("error"))}}).then(()=>{if(!a.signal.aborted)return Xo("stream resolved",{agentRunId:t}),e.agents.getInternals(t).then(e=>{a.signal.aborted||(Xo("internals refreshed after stream end",{agentRunId:t,status:e.status}),c(e.status?.toUpperCase()??null))}).catch(e=>{a.signal.aborted||console.error("Failed to refresh agent run status on stream end:",e)})}).catch(e=>{a.signal.aborted||(Xo("stream failed",{agentRunId:t,error:e instanceof Error?e.message:String(e)}),console.error("Failed to stream agent messages:",e))}),()=>{Xo("stream cleanup",{agentRunId:t,streamNonce:h}),a.abort(),S(),w.current.clear(),C.current&&(clearTimeout(C.current),C.current=null)}},[t,h,e.agents,T,S]),He(()=>{const e=()=>{!document.hidden&&w.current.size>0&&(S(),T())};return document.addEventListener("visibilitychange",e),()=>{document.removeEventListener("visibilitychange",e)}},[T,S]);const I=Ve(e=>{r(t=>{const n=[...t,e];return n.sort((e,t)=>("number"==typeof e.timestamp?e.timestamp:new Date(e.timestamp).getTime())-("number"==typeof t.timestamp?t.timestamp:new Date(t.timestamp).getTime())),n})},[]),z=Ve((e,t)=>{r(n=>n.map(n=>n.details?._optimistic&&bm(n)===e?vm(n,t):n))},[]),R=Ve(e=>{r(t=>t.filter(t=>!e(t)))},[]);return{messages:n,streamingMessages:x,isCompleted:a,initialHistoryStatus:i,debugChunkFlash:k,addOptimisticMessage:I,updateOptimisticMessageStatus:z,removeOptimisticMessages:R,reconnect:g,agentRunStatus:l,workflowRunId:d,serverFileUpdates:m}}function Cm(e){if("string"==typeof e&&e.trim().length>0)return e}function Sm(e,t){const n=Cm(e.revision_root_id)||Cm(e.revision_root)||Cm(e.root_document_id)||Cm(e.root_id);if(n)return n;const r=e.revision_info;if(r&&"object"==typeof r){const e=Cm(r.root);if(e)return e}return t}function Tm(e,t){return e.revisionRootId&&t.revisionRootId?e.revisionRootId===t.revisionRootId:t.revisionRootId?e.id===t.revisionRootId:e.revisionRootId?e.revisionRootId===t.id:e.id===t.id}function Im(e){if(function(e){return e.type.startsWith("image/")}(e)&&"undefined"!=typeof URL&&URL.createObjectURL)return URL.createObjectURL(e)}function zm(e){"undefined"!=typeof URL&&URL.revokeObjectURL&&URL.revokeObjectURL(e)}function Rm({activeWorkstreams:n,className:r}){const{t:a}=Ze(),s=Fe(()=>n.filter(e=>"running"===e.status||"canceling"===e.status),[n]),o=s.slice(0,3),l=Math.max(0,s.length-o.length);return 0===s.length?null:e("div",{className:i("mx-auto mb-2 w-full max-w-3xl px-1",r),"data-agent-active-workstreams":!0,children:t("output",{className:"flex flex-col gap-1.5 rounded-2xl border border-border/70 bg-background/95 p-2 text-xs text-muted shadow-lg shadow-black/5","aria-live":"polite",children:[t("div",{className:"flex items-center gap-2 px-1 font-medium",children:[e(Bt,{className:"size-3.5 text-muted","aria-hidden":"true"}),e("span",{children:a("agent.activeWorkstreams",{count:s.length})})]}),t("div",{className:"flex flex-col gap-0.5",children:[o.map(n=>{const r=qo(n.workstream_id,n.interaction);return t("span",{className:"flex min-w-0 items-center gap-2 rounded-lg px-1 py-1 text-sm text-foreground/80",title:r,children:[e("span",{className:i("size-1.5 shrink-0 rounded-full",Ko(n.status)),"aria-hidden":"true"}),e("span",{className:"truncate font-medium",children:r}),n.phase&&e("span",{className:"truncate text-xs text-muted/75",children:Vo(n.phase)})]},n.launch_id||n.workstream_id)}),l>0&&t("span",{className:"px-1 py-1 text-xs text-muted",children:["+",l]})]})]})})}class jm{_listeners=new Set;snapshot;constructor(e){this.snapshot=new Pm(e,this)}subscribe=e=>(this._listeners.add(e),()=>{this._listeners.delete(e)});getSnapshot=()=>this.snapshot;notify(){this._listeners.forEach(e=>{e()})}}class Pm{vertesia;_interactive=!0;_debug_mode=!1;_non_blocking_subagents=!0;_checkpoint_tokens;_visibility;_user_channels;_collection;_disabled_mcp_collections;_start=!1;_preserveRunValues=!1;_interaction;_environment;_model="";_model_options;_tool_names=[];_data;_mode="start";_scheduledWorkflowConfig;_interactionParamsSchema;_schemaVersion=0;_inputValidator;_store;constructor(e,t){this.vertesia=e,this._store=t}onStateChanged(){const e=this.clone();this._store.snapshot=e,this._store.notify()}clone(){const e=new Pm(this.vertesia,this._store);return e._interactionParamsSchema=this._interactionParamsSchema,e._schemaVersion=this._schemaVersion,e._interaction=this._interaction,e._data=this._data,e._environment=this._environment,e._model=this._model,e._model_options=this._model_options?{...this._model_options}:void 0,e._tool_names=[...this._tool_names],e._interactive=this._interactive,e._debug_mode=this._debug_mode,e._non_blocking_subagents=this._non_blocking_subagents,e._checkpoint_tokens=this._checkpoint_tokens,e._visibility=this._visibility,e._user_channels=this._user_channels?[...this._user_channels]:void 0,e._inputValidator=this._inputValidator,e._start=this._start,e._collection=this._collection,e._disabled_mcp_collections=this._disabled_mcp_collections?[...this._disabled_mcp_collections]:void 0,e._preserveRunValues=this._preserveRunValues,e._mode=this._mode,e._scheduledWorkflowConfig=this._scheduledWorkflowConfig,e}set mode(e){e!==this._mode&&(this._mode=e,"schedule"!==e||this._scheduledWorkflowConfig||(this._scheduledWorkflowConfig={name:"",description:"",cron_expression:"0 9 * * *",timezone:"UTC"}),this.onStateChanged())}get mode(){return this._mode}set scheduledWorkflowConfig(e){this._scheduledWorkflowConfig=e,this.onStateChanged()}get scheduledWorkflowConfig(){return this._scheduledWorkflowConfig}updateScheduledWorkflowConfig(e){this._scheduledWorkflowConfig={...this._scheduledWorkflowConfig,...e},this.onStateChanged()}get interactive(){return this._interactive}set interactive(e){e!==this._interactive&&(this._interactive=e,this.onStateChanged())}get debug_mode(){return this._debug_mode}set debug_mode(e){e!==this._debug_mode&&(this._debug_mode=e,this.onStateChanged())}get non_blocking_subagents(){return this._non_blocking_subagents}set non_blocking_subagents(e){e!==this._non_blocking_subagents&&(this._non_blocking_subagents=e,this.onStateChanged())}get checkpoint_tokens(){return this._checkpoint_tokens}set checkpoint_tokens(e){e!==this._checkpoint_tokens&&(this._checkpoint_tokens=e,this.onStateChanged())}get visibility(){return this._visibility}set visibility(e){e!==this._visibility&&(this._visibility=e,this.onStateChanged())}get user_channels(){return this._user_channels}set user_channels(e){this._user_channels=e,this.onStateChanged()}get collection(){return this._collection}set collection(e){e!==this._collection&&(this._collection=e,this.onStateChanged())}get disabled_mcp_collections(){return this._disabled_mcp_collections}set disabled_mcp_collections(e){this._disabled_mcp_collections=e&&e.length>0?e:void 0,this.onStateChanged()}get search_scope(){return this._collection?dr.Collection:void 0}async restoreConversation(e){let t=e.interaction;if(e.version){/^[a-fA-F0-9]{24}$/.test(t)||(t=`${t}@${e.version}`)}const n=await this.vertesia.interactions.catalog.resolve(t),r=n.runtime?.environment||e.config?.environment,a=e.config?.model,s=await(r?this.vertesia.environments.retrieve(r).catch(()=>{}):Promise.resolve(void 0));this._data=e.data,this.interaction=n,null!=e.interactionParamsSchema&&(this.interactionParamsSchema=e.interactionParamsSchema),this._tool_names=e.tool_names||[],this._interactive=e.interactive,this._debug_mode=e.debug_mode??!1,this._non_blocking_subagents=e.non_blocking_subagents??!0,this._checkpoint_tokens=e.checkpoint_tokens,this._user_channels=e.user_channels,this._disabled_mcp_collections=e.disabled_mcp_collections,this._model_options=e.config?.model_options,this.collection=e.collection_id??void 0,this._model_options=e.config?.model_options,this.environment=s,a&&(this._model=a),this.onStateChanged()}get interaction(){return this._interaction}set interaction(e){if(e?.id!==this._interaction?.id){if(this._interaction=e,this.interactionParamsSchema=e?ur(e.prompts):void 0,this._inputValidator=void 0,e&&!this._preserveRunValues&&(this._model_options=e.model_options,e.runtime?.environment)){const t=e.runtime.environment;this.vertesia.environments.retrieve(t).then(e=>this.environment=e)}this.onStateChanged()}}get environment(){return this._environment}set environment(e){if(e?.id!==this._environment?.id){if(this._environment=e,!this._preserveRunValues){const t=this.interaction?.runtime?.model;t&&e&&mr(t,e.provider)?this._model=t:this._model=e?.default_model&&mr(e.default_model,e.provider)?e.default_model:""}this.onStateChanged()}}get model(){return this._model}set model(e){e!==this._model&&(this._model=e||"",this.onStateChanged())}get model_options(){return this._model_options}set model_options(e){JSON.stringify(e)!==JSON.stringify(this._model_options)&&(this._model_options=e,this.onStateChanged())}get tool_names(){return this._tool_names}set tool_names(e){this._tool_names=e,this.onStateChanged()}get data(){return this._data}set data(e){this._data=e,this.onStateChanged()}set run(e){console.log("run",e),this.onStateChanged()}set start(e){this._start!==e&&(this._start=e,this.onStateChanged())}markStarted(){this.start=!0}setMode(e){this.mode=e}setInteraction(e){this.interaction=e}setEnvironment(e){this.environment=e}setModel(e){this.model=e}setModelOptions(e){this.model_options=e}setToolNames(e){this.tool_names=e}setCollection(e){this.collection=e}setDisabledMcpCollections(e){this.disabled_mcp_collections=e}setInteractive(e){this.interactive=e}setDebugMode(e){this.debug_mode=e}setUserChannels(e){this.user_channels=e}setCheckpointTokens(e){this.checkpoint_tokens=e}setVisibility(e){this.visibility=e}setData(e){this.data=e}setPreserveRunValues(e){this.preserveRunValues=e}get start(){return this._start}get preserveRunValues(){return this._preserveRunValues}set preserveRunValues(e){this._preserveRunValues=e}get schemaVersion(){return this._schemaVersion}get interactionParamsSchema(){return this._interactionParamsSchema}set interactionParamsSchema(e){this._interactionParamsSchema!==e&&(this._interactionParamsSchema=e,this._schemaVersion+=1,e&&(this._data=this.initializeBooleanDefaults(this._data||{},e)),this.onStateChanged())}initializeBooleanDefaults(e,t){if(!t.properties)return e;const n={...e};for(const[e,r]of Object.entries(t.properties)){const t=r;"boolean"===t.type&&void 0===n[e]?n[e]=!1:"object"===t.type&&t.properties&&(n[e]=this.initializeBooleanDefaults(n[e]||{},t))}return n}reset(){if(this._start=!1,this._interactive=!0,this._debug_mode=!1,this._non_blocking_subagents=!0,this._checkpoint_tokens=void 0,this._visibility=void 0,this._user_channels=void 0,this._collection=void 0,this._disabled_mcp_collections=void 0,this._preserveRunValues=!1,this._model="",this._model_options=void 0,this._environment=void 0,this._tool_names=[],this._interaction=void 0,this._data=void 0,this._interactionParamsSchema=null,this._inputValidator=void 0,this.model=void 0,this.environment=void 0,this.onStateChanged(),location.hash){const e=window.location.origin+window.location.pathname+window.location.search;history.replaceState(null,"",e),location.hash=""}}validateInput(){if(!this._interactionParamsSchema)return{isValid:!0};if(!this._inputValidator||this._inputValidator.schema!==this._interactionParamsSchema){const e=new _a({strict:!1});this._inputValidator={validate:e.compile(this._interactionParamsSchema),schema:this._interactionParamsSchema}}const e=this._data||{};if(!this._inputValidator.validate(e)){return{isValid:!1,errorMessage:this._inputValidator.validate.errors?this._inputValidator.validate.errors.map(e=>`${e.instancePath}: ${e.message}`).join(", "):"Invalid payload data"}}return{isValid:!0}}}const Am=Ue(void 0);function Dm({children:t}){const{client:n}=tr(),[r]=Oe(()=>new jm(n)),a=Qe(r.subscribe,r.getSnapshot);return e(Am.Provider,{value:a,children:t})}function Em(){const e=We(Am);if(!e)throw new Error("usePayloadBuilder must be used within a PayloadProvider");return e}function $m({title:n,variant:a="full",isTerminal:s=!1,onClose:o,isModal:l,agentRunId:c,workflowRunId:d,viewMode:u,onViewModeChange:m,showPlanPanel:p,showPlanButton:h=!0,onTogglePlanPanel:f,showPlaybackButton:g=!1,isPlaybackEnabled:v=!1,onTogglePlayback:b,onDownload:x,onExportFixture:y,resetWorkflow:w,onExportPdf:N,onShowDetails:k,allowWorkflowControl:_=!0,onClone:C,isReceivingChunks:S=!1,className:T}){const{t:I}=Ze(),z="compact"===a,R="sliding"===u?"stacked":"sliding",j=I("agent.verbose"),P=I("agent.summary"),A="stacked"===R?j:P,D=t("div",{className:i(z?"flex flex-row items-center gap-1 lg:flex-col":"flex justify-end items-center gap-2 ms-auto"),children:[h&&e("div",{className:"relative",children:t(r,{size:"compact"===a?"icon":"sm",variant:p?"primary":"ghost",onClick:f,className:i("transition-all duration-200 rounded-md","compact"===a&&"size-8 rounded-lg"),title:I("agent.toggleRightSidebar"),children:[e(pn,{className:i("size-4","full"===a&&"me-1.5")}),e("span","full"===a?{className:"font-medium text-xs",children:I(p?"agent.hideSidebar":"agent.showSidebar")}:{className:"sr-only",children:I(p?"agent.hideSidebar":"agent.showSidebar")})]})}),z?e(r,{variant:"ghost",size:"icon",onClick:()=>m(R),className:"size-8 rounded-lg",title:A,"aria-label":A,children:e("stacked"===R?xn:yn,{className:"size-4"})}):t("div",{className:"flex items-center gap-1 bg-muted rounded p-0.5 mt-2 lg:mt-0",children:[t(r,{variant:"stacked"===u?"outline":"ghost",size:"xs",onClick:()=>m("stacked"),"aria-pressed":"stacked"===u,className:"gap-1.5",children:[e(xn,{className:"size-3.5"}),j]}),t(r,{variant:"sliding"===u?"outline":"ghost",size:"xs",onClick:()=>m("sliding"),"aria-pressed":"sliding"===u,className:"gap-1.5",children:[e(yn,{className:"size-3.5"}),P]})]}),g&&b&&t(r,{type:"button",size:"compact"===a?"icon":"sm",variant:v?"primary":"ghost",onClick:b,"aria-pressed":v,title:I("agent.rewind.label"),className:i("transition-all duration-200 rounded-md","compact"===a&&"size-8 rounded-lg"),children:[e(wn,{className:i("size-4","full"===a&&"me-1.5")}),e("span","full"===a?{className:"font-medium text-xs",children:I("agent.rewind.label")}:{className:"sr-only",children:I("agent.rewind.label")})]}),e(Lm,{compact:z,agentRunId:c,workflowRunId:d,isModal:l,isTerminal:s,onClose:o,onDownload:x,onExportFixture:y,resetWorkflow:w,onExportPdf:N,onShowDetails:k,allowWorkflowControl:_,onClone:C}),o&&!l&&e(r,{size:"xs",variant:"ghost",onClick:o,"aria-label":I("agent.close"),children:e(Et,{className:"size-4"})})]});return e(Dm,"compact"===a?{children:e("div",{className:i("inline-flex items-center rounded-xl border border-border/70 bg-background/90 p-1 shadow-lg shadow-black/10 backdrop-blur",T),children:D})}:{children:t("div",{className:i("flex flex-wrap items-end justify-between py-1.5 px-2 border-b shadow-sm flex-shrink-0",T),children:[t("div",{className:"flex flex-wrap items-center gap-2",children:[t("div",{className:"flex items-center gap-1",children:[e(Bt,{className:"size-5 text-muted"}),e("span",{className:"font-medium",children:n})]}),t("span",{className:"text-xs text-muted ms-1 flex items-center gap-1.5",children:["(Agent Run ID: ",c,")",e("span",{className:i("w-2 h-2 rounded-full transition-colors duration-200",S?"bg-purple-500 shadow-[0_0_6px_2px_rgba(168,85,247,0.6)]":"bg-gray-400")})]})]}),D]})})}function Lm({compact:n=!1,agentRunId:a,workflowRunId:s,isModal:i,isTerminal:o,onClose:l,onDownload:c,onExportFixture:d,resetWorkflow:u,onExportPdf:m,onShowDetails:h,allowWorkflowControl:f=!0,onClone:b}){const{t:x}=Ze(),y=p(),{client:w}=tr(),N=Em(),{router:_}=aa();return e(g,{align:"right",trigger:e(r,{size:n?"icon":"xs",variant:"ghost",title:x("agent.moreActions"),className:n?"size-8 rounded-lg":void 0,children:e(_n,{className:"size-4"})}),children:t(k,{label:"Actions",children:[i&&t(v,{onClick:()=>(e=>{const t=e.startsWith("/")?_.getTopRouter().navigator.addStickyParams(e):e;return window.open(t,"_blank"),t})(`/store/agent-runner/${a}`),children:[e($t,{className:"size-3.5 text-muted"})," ",x("agent.openInNewTab")]}),t(v,{onClick:()=>{navigator.clipboard.writeText(a),y({status:"success",title:x("agent.agentRunIdCopied"),duration:2e3})},children:[e(vt,{className:"size-3.5 text-muted"})," ",x("agent.copyAgentRunId")]}),t(v,{onClick:()=>{navigator.clipboard.writeText(s),y({status:"success",title:x("agent.workflowRunIdCopied"),duration:2e3})},children:[e(vt,{className:"size-3.5 text-muted"})," ",x("agent.copyWorkflowRunId")]}),h&&t(v,{onClick:h,children:[e(Nn,{className:"size-3.5 text-muted"})," ",x("agent.details")]}),t(v,{onClick:()=>{c?c():ll(w,a).then(e=>window.open(e,"_blank"))},children:[e(Xt,{className:"size-3.5 text-muted"})," ",x("agent.downloadConversation")]}),m&&t(v,{onClick:m,children:[e(Xt,{className:"size-3.5 text-muted"})," ",x("agent.exportAsPdf")]}),d&&t(v,{onClick:d,children:[e(Xt,{className:"size-3.5 text-muted"})," ",x("agent.rewind.exportFixture")]}),l&&i&&t(v,{onClick:l,children:[e(Et,{className:"size-3.5 text-muted"})," ",x("agent.close")]}),b&&t(v,{onClick:async()=>{try{const e=await w.agents.fork(a);y({status:"success",title:x("agent.conversationCloned"),duration:2e3}),b?.(e)}catch(e){y({status:"error",title:x("agent.failedToCloneConversation"),duration:2e3})}},children:[e(kn,{className:"size-3.5 text-muted"})," ",x("agent.cloneConversation")]}),f&&!o&&t(v,{onClick:async()=>{try{return await w.agents.terminate(a,"cancel"),y({status:"success",title:x("agent.workflowCancelled"),duration:2e3}),N.reset(),u?.(),!0}catch(e){return y({status:"error",title:x("agent.failedToCancelWorkflow"),duration:2e3}),!1}},variant:"destructive",children:[e(Et,{className:"size-3.5"})," ",x("agent.cancelWorkflow")]})]})})}function Mm(e){return function(e){return"object"==typeof e&&null!==e&&"value"in e}(e)?e.value:e}function Fm(e){if("stringList"===e.type)return e.value.map(e=>"string"==typeof e?e:Mm(e));if(e.multiple)return e.value.map(Mm);const t=e.value[0];return void 0===t?void 0:Mm(t)}function Om(e,t,n){e.query[t]=n}function Um({buckets:n,name:r,placeholder:a}){const s=n.map(e=>({label:`(${e.count})`,value:e._id}));return{name:r,placeholder:a||`${r.charAt(0).toUpperCase()+r.slice(1)}`,options:s,type:"select",labelRenderer:r=>{const a=n.find(e=>e._id===r),s=a?.name||r;let i="success";if(a?.status)switch(a.status){case pr.published:i="success";break;case pr.archived:i="destructive";break;case pr.code:i="info"}const o=a?.version&&a?.status?`v${a.version} ${a.status!==pr.unknown?a.status:""}`:a?.status||(a?.version?`v${a.version}`:"");return t("div",{className:"w-full flex items-center justify-between",children:[t("div",{className:"flex flex-row flex-wrap items-center gap-2 min-w-0 flex-1",children:[e("span",{className:"text-sm truncate",children:s}),o&&e(f,{variant:i,className:"text-xs w-fit",children:o})]}),(a?.count??0)>0&&t("span",{className:"ms-2 text-xs shrink-0",children:["(",a?.count,")"]})]})},filterBy:(e,t)=>{const r=n.find(t=>t._id===e);return(r?.name||e).toLowerCase().includes(t.toLowerCase())}}}function Wm(e){return`${e._id} (${e.count})`}function Bm(e){return`${e.name} (${e.count})`}function Vm({buckets:e,name:t,placeholder:n,type:r,multiple:a}){return function({buckets:e,name:t,placeholder:n,type:r="select",multiple:a=!1}){return{name:t,options:e.map(e=>({label:Wm(e),value:e._id})),type:r,multiple:a,placeholder:`${n??`${t.charAt(0).toUpperCase()+t.slice(1)}`}`,allowCreate:!1}}({buckets:e,name:t,placeholder:n,type:r,multiple:a})}const qm={},Hm={},Gm={};function Jm(e){return"object"==typeof e&&null!==e&&"status"in e&&404===e.status}function Km(e,t,n){let r=e[t];return r||(r=n().catch(n=>{throw Jm(n)||delete e[t],n}),e[t]=r),r}function Ym(e){const{client:t}=tr();return S(()=>Km(qm,e,()=>t.users.retrieve(e)),{deps:[e],condition:()=>!!e})}function Qm(e){const{client:t}=tr();return S(()=>Km(Hm,e,()=>t.iam.groups.retrieve(e)),{deps:[e],condition:()=>!!e})}function Zm(e){const{client:t}=tr();return S(()=>Km(Gm,e,()=>t.apikeys.retrieve(e)),{deps:[e],condition:()=>!!e})}function Xm(){return e("div",{className:"size-8"})}function ep({showTitle:n=!1,size:r="md"}){const{t:a}=Ze();return e(mp,{title:a("user.systemUser"),description:a("user.systemUserDescription"),children:t("div",{className:"flex gap-2 items-center",children:[e(_,{src:"/icon.svg",size:r}),n&&e("div",{className:"text-sm font-semibold ps-2",children:a("user.systemUser")})]})})}function tp({showTitle:n=!1,size:r="md"}){const{t:a}=Ze();return e(mp,{title:a("user.allProjectMembers"),description:a("user.allProjectMembersDescription"),children:t("div",{className:"flex gap-2 items-center",children:[e(Cn,{className:"size-4",size:r}),n&&e("div",{className:"text-sm font-semibold ps-2",children:a("user.allProjectMembers")})]})})}function np({accountId:r,showTitle:a=!1,size:s="md"}){const{t:i}=Ze(),o=r.split(":")[0],l=r.split(":")[1],c=t(n,{children:[e("div",{children:i("user.serviceAccountDescription")}),t("div",{className:"text-muted text-sm",children:[e("span",{className:"font-semibold",children:"Type:"})," ",o]}),t("div",{className:"text-muted text-sm",children:[e("span",{className:"font-semibold",children:"ID:"})," ",l]})]});return e(mp,{title:i("user.serviceAccount"),description:c,children:t("div",{className:"flex flex-row items-center gap-2",children:[e(_,{src:"/cloud.svg",name:"SA",color:"bg-amber-500",className:"px-[5px] text-white",size:s}),a&&t("div",{className:"text-sm font-semibold ps-2 truncate",children:[i("user.serviceAccount")," : ~",l.slice(-6)]})]})})}function rp({email:r,showTitle:a=!1,size:s="md"}){const{t:i}=Ze(),o=t(n,{children:[e("div",{children:i("user.agentOnBehalfOf")}),t("div",{className:"text-muted text-sm",children:[e("span",{className:"font-semibold",children:"Email:"})," ",r]})]});return e(mp,{title:"Email Agent",description:o,children:t("div",{className:"flex items-center gap-2",children:[t("div",{className:"flex items-center -space-x-2",children:[e(_,{src:"/cloud.svg",color:"bg-amber-500",className:"px-[5px] text-white border-2 border-white dark:border-gray-800",size:s}),e(_,{name:r,size:s,className:"border-2 border-white dark:border-gray-800"})]}),a&&t("div",{className:"text-sm font-semibold truncate",children:["Agent (",r,")"]})]})})}function ap({agentId:r,onBehalfOfType:a,onBehalfOfId:s,showTitle:i=!1,size:o="md",isScheduleAgent:l=!1}){const{t:c}=Ze(),d="user"===a&&s,u="apikey"===a&&s,m=Ym(s||""),p=Zm(s||""),h=d?m.data:void 0,f=u?p.data:void 0,g=r.slice(-6),v=h?c("user.agentOnBehalfOf"):f?c("user.agentOnBehalfOfApiKey"):`${c("user.serviceAccount")}~${g}`,b=l?c("user.schedule",{title:v}):v,x=t("div",{className:"space-y-2",children:[h&&t("div",{className:"flex items-center gap-2",children:[e(_,{src:h.picture,name:h.name,size:"sm"}),t("div",{children:[e("div",{className:"font-medium",children:h.name||h.email}),h.email&&h.name&&e("div",{className:"text-xs text-muted",children:h.email})]})]}),f&&t("div",{children:[e("div",{className:"font-medium",children:f.name}),t("div",{className:"text-xs text-muted-foreground",children:["Key ID: ",f.id]})]}),!h&&!f&&t(n,{children:[e("div",{children:c("user.serviceAccountDescription")}),t("div",{className:"text-gray-800 dark:text-gray-500 text-sm",children:[e("span",{className:"font-semibold",children:"ID:"})," ",r]})]})]});return e(mp,{title:b,description:x,children:t("div",{className:"flex items-center gap-2",children:[t("div",{className:"flex items-center -space-x-2",children:[e(_,{src:"/cloud.svg",color:"bg-amber-500",className:"px-[5px] text-white border-2 border-white dark:border-gray-800",size:o}),h&&e(_,{src:h.picture,name:h.name,size:o,className:"border-2 border-white dark:border-gray-800"}),f&&e(_,{name:"API",color:"bg-gray-400",size:o,className:"border-2 border-white dark:border-gray-800"})]}),i&&e("div",{className:"text-sm font-semibold truncate",children:h?`Agent (${h.name||h.email})`:f?`Agent (${f.name})`:v})]})})}function sp({title:t="Error",error:n,showTitle:r=!1,size:a="md"}){return e(lp,{title:t,message:T(n),color:"bg-red-500",showTitle:r,size:a})}function ip({showTitle:t=!1,size:n="md",color:r}){const{t:a}=Ze();return e(lp,{title:a("user.unknownUser"),message:a("user.unknownUserDescription"),color:r,showTitle:t,size:n})}function op({userRef:t,showTitle:n=!1,size:r="md"}){const{t:a}=Ze();if(!t)return e(lp,{title:a("user.unknownUser"),message:a("user.unknownUserDescription"),showTitle:n,size:r});const s=t.split(":"),i=s[0];switch(i){case hr.User:return e(dp,{userId:s[1],showTitle:n,size:r});case hr.Group:return e(cp,{userId:s[1],showTitle:n,size:r});case"system":return e(ep,{showTitle:n,size:r});case hr.ServiceAccount:return e(np,{accountId:s.slice(1).join(":"),showTitle:n,size:r});case hr.Agent:{let t,a,i;return"agent"===s[1]?(t=s.slice(2,5).join(":"),a=s[5],i=s[6]):(t=s.slice(1,4).join(":"),a=s[4],i=s[5]),e(ap,{agentId:t,onBehalfOfType:a,onBehalfOfId:i,showTitle:n,size:r})}case hr.Schedule:{const t="agent"===s[2]?s.slice(3,6).join(":"):"unknown-agent",a=s[6],i=s[7];return e(ap,{agentId:t,onBehalfOfType:a,onBehalfOfId:i,showTitle:n,size:r,isScheduleAgent:!0})}case"email":return e(rp,{email:s[1],showTitle:n,size:r});case hr.ApiKey:return e(up,{keyId:s[1],size:r,showTitle:n});case"project":if("*"===s[1])return e(tp,{showTitle:n,size:r});break;default:return e(sp,{title:a("user.unknownUser"),error:`Invalid user ref type: ${i}`,showTitle:n,size:r})}}function lp({title:n,message:r,color:a,size:s="md",showTitle:i=!1}){return e(mp,{title:n,description:r,children:t("div",{className:"flex flex-row items-center gap-2",children:[e(_,{color:a,size:s}),i&&e("div",{className:"text-sm font-semibold ps-1",children:n})]})})}function cp({userId:n,showTitle:r=!1,size:a="md"}){const{t:s}=Ze(),{data:i,error:o}=Qm(n);if(o)return Jm(o)?e(ip,{showTitle:r,size:a,color:"bg-indigo-500"}):e(sp,{title:s("user.failedToFetchGroup"),error:o,showTitle:r,size:a});if(!i)return e(Xm,{});const l=t("div",{className:"space-y-1",children:[i.description&&e("div",{className:"text-sm",children:i.description}),e("div",{className:"text-xs text-muted-foreground",children:s("user.groupId",{id:i.id})}),i.tags&&i.tags.length>0&&e("div",{className:"flex flex-wrap gap-1",children:i.tags.map(t=>e("span",{className:"px-1.5 py-0.5 bg-muted rounded text-xs",children:t},t))})]});return e(mp,{title:i.name||s("user.unnamedGroup"),description:l,children:t("div",{className:"flex flex-row items-center gap-2",children:[e(Sn,{className:"size-6 text-indigo-500",size:a}),r&&e("div",{className:"text-sm font-semibold ps-2",children:i.name||s("user.unnamedGroup")})]})})}function dp({userId:n,showTitle:r=!1,size:a="md"}){const{t:s}=Ze(),{data:i,error:o}=Ym(n);if(o)return Jm(o)?e(ip,{showTitle:r,size:a,color:"bg-indigo-500"}):e(sp,{title:s("user.failedToFetchUser"),error:o,showTitle:r,size:a});if(!i)return e(Xm,{});const l=e("div",{className:"truncate",title:i.email,children:i.email});return e(mp,{title:i.name||i.email||i.username||s("user.unknown"),description:l,children:t("div",{className:"flex flex-row items-center gap-2",children:[e(_,{src:i.picture,name:i.name,color:"bg-indigo-500",size:a}),r&&e("div",{className:"text-sm font-semibold ps-2",children:i.name||i.email||i.username||s("user.unknown")})]})})}function up({keyId:n,showTitle:r=!1,size:a="md"}){const{t:s}=Ze(),{data:i,error:o}=Zm(n);if(o)return Jm(o)?e(ip,{showTitle:r,size:a,color:"bg-pink-500"}):e(sp,{title:s("user.failedToFetchApiKey"),error:o,showTitle:r,size:a});if(!i)return e(Xm,{});const l=s("user.privateKey"),c=e(_,{name:"PK",color:"bg-pink-500",size:a}),d=t(C,{className:"dark:bg-gray-800 dark:text-gray-200 table-fixed w-full",children:[t("tr",{children:[e("td",{className:"font-semibold w-20",children:s("user.key")}),e("td",{className:"truncate max-w-0",children:i?.name})]}),t("tr",{children:[e("td",{className:"font-semibold w-20",children:s("user.account")}),e("td",{className:"truncate max-w-0",children:i?.account})]}),t("tr",{children:[e("td",{className:"font-semibold w-20",children:s("user.project")}),e("td",{className:"truncate max-w-0",children:i?.project.name})]})]});return e(mp,{title:l,description:d,children:t("div",{className:"flex flex-row items-center gap-2",children:[c,r&&e("div",{className:"text-sm font-semibold",children:i?.name||i?.account||i?.project.name||s("user.unknown")})]})})}function mp({title:n,description:r,children:a}){return t(I,{hover:!0,children:[e(z,{className:"cursor-pointer flex items-center inline-block",children:e("div",{children:a})}),e(R,{align:"center",sideOffset:8,side:"right",children:t("div",{className:"flex flex-col gap-1 rounded-md shadow-md p-2",children:[e("div",{className:"text-md font-semibold",children:n}),r]})})]})}function pp({buckets:n,name:r,placeholder:a}){return function({buckets:n,name:r,placeholder:a}){const s=n.map(e=>({value:e._id,label:`(${e.count})`}));return{name:r,placeholder:a||`${r.charAt(0).toUpperCase()+r.slice(1)}`,options:s,labelRenderer:r=>{if("Unknown User"===r||!r){const e=n.find(e=>e._id===r);return`Unknown User (${e?.count||0})`}const a=n.find(e=>e._id===r);return t("div",{className:"flex items-center w-full gap-2",children:[e("div",{className:"flex-1 min-w-0 flex items-center truncate",children:e(op,{userRef:r,showTitle:!0,size:"sm"})}),t("span",{className:"text-muted-foreground flex-shrink-0",children:["(",a?.count||0,")"]})]})}}}({buckets:n,name:r,placeholder:a})}function hp(e){const t=[];return t.push({name:"id",placeholder:"Agent Run ID",type:"text",multiple:!1}),t.push(Um({buckets:e.interactions||[],name:"interaction",placeholder:"Interaction"})),t.push(Vm({buckets:e.statuses||[],name:"status",placeholder:"Status"})),t.push(pp({buckets:e.initiated_by||[],name:"initiated_by",placeholder:"Initiated By"})),t.push({name:"start",placeholder:"Started After",type:"date",multiple:!1}),t.push({name:"end",placeholder:"Started Before",type:"date",multiple:!1}),t}function fp(e){return t=>{e.clearFilters(!1,!1),t.forEach(t=>{if(t.value&&t.value.length>0){const n=t.name,r=Fm(t);Om(e,n,r)}}),e.search()}}function gp({facets:n,search:a,selectionCount:s,actions:i,filters:o,setFilters:l,filterGroups:c}){const[d,u]=Oe([]),m=o??d,p=l??u,h=Be(!1),f=Be("undefined"!=typeof window&&Boolean(new URLSearchParams(window.location.search).get("filters"))),g=hp(n),v=c??g,b=Fe(()=>fp(a),[a]);He(()=>{h.current?f.current?f.current=!1:b(m):h.current=!0},[m,b]);return e(j,{filterGroups:v,filters:m,setFilters:p,children:t("div",{className:"gap-2 items-center w-full",children:[t("div",{className:"flex justify-between mb-1",children:[e(P,{}),t("div",{className:"flex justify-end",children:[!s&&e("div",{className:"flex items-center justify-between px-2 py-1",children:e("div",{className:"text-sm text-muted-foreground",children:a.initialized?`${a.totalCount} agent runs`:"Loading agent runs..."})}),i&&i.length>0?e("div",{className:"flex items-center gap-2 mb-1 me-2",children:i.map((t,n)=>e("div",{children:t},n))}):null,e(r,{onClick:()=>{a.search()},variant:"outline",title:"Refresh",children:e(Tn,{className:"size-5"})})]})]}),m.length>0&&t("div",{className:"flex items-center gap-2 mb-1",children:[e(A,{}),e(D,{})]})]})})}class vp{types;map={};constructor(e){this.types=e,e.sort((e,t)=>e.name.localeCompare(t.name));for(const t of e)this.map[t.id]=t}getType(e){return this.map[e]}getTypeLayout(e){const t=this.map[e];return t?t.table_layout:void 0}getTypeName(e){const t=this.map[e];return t?t.name:void 0}}const bp=Ue({registry:void 0,isLoading:!1,load:()=>Promise.resolve(),reload:()=>Promise.resolve()});function xp({children:t}){const{store:n,project:r}=tr(),[a,s]=Oe(),[i,o]=Oe(!1),l=Be(!1),c=Be(r?.id),d=Ve(async()=>{if(r&&!l.current){l.current=!0,o(!0);try{const e=await n.types.catalog.list({layout:!0});s(new vp(e))}catch(e){console.error("Failed to fetch types",e)}finally{o(!1),l.current=!1}}},[n,r]),u=Ve(async()=>(l.current=!1,d()),[d]);return He(()=>{c.current!==r?.id&&(c.current=r?.id,s(void 0),l.current=!1)}),e(bp.Provider,{value:{registry:a,isLoading:i,load:d,reload:u},children:t})}function yp(){const e=We(bp);return He(()=>{e.registry||e.isLoading||e.load()},[e.registry,e.isLoading,e.load]),e}function wp(e){const{registry:t}=yp(),n=[];if(n.push({name:"name",placeholder:"Name",type:"text",multiple:!1}),t){const e=t.types.map(e=>({label:e.name,value:e.id})),r={name:"types",placeholder:"Type",type:"select",multiple:!0,options:e,filterBy:(t,n)=>{const r=e.find(e=>e.value===t);return r?.label?.toLowerCase().includes(n.toLowerCase())??!1}};n.push(r)}return n}function Np(e){return t=>{0!==t.length?(e.clearFilters(!1),t.forEach(t=>{if(t.value&&t.value.length>0){const n=t.name,r=Fm(t);Om(e,n,r)}}),e.search()):e.clearFilters(!0)}}function kp({facets:n,search:r,filters:a,setFilters:s,filterGroups:i}){const[o,l]=Oe([]),c=wp(),d=Np(r),u=void 0!==a&&void 0!==s;return e(j,{filterGroups:i??c,filters:u?a:o,setFilters:e=>{if(u)return void s(e);const t="function"==typeof e?e(o):e;l(t),d(t)},children:t("div",{className:"flex gap-2 items-center",children:[e(P,{}),e(A,{}),e(D,{})]})})}function _p({buckets:n,typeRegistry:r,type:a="select",multiple:s=!1}){const i=new Map;r||console.warn("Type names cannot be resolved"),n.forEach(e=>{let t,n=e._id;null==e._id?(n="Document",t="Document"):(t=r?.getTypeName(e._id),t||(console.warn("Content Object Type not found",e._id),t=e._id)),i.set(n,{name:t,count:e.count})});return{name:"types",placeholder:"Types",type:a,multiple:s,options:n.map(e=>{const t=e._id,n=t||"Document",r=i.get(n);return{value:t,label:r?`${r.name} (${r.count})`:`Unknown (${e.count})`}}),labelRenderer:n=>{const r=i.get(n);return r?t("div",{className:"w-full flex items-center",children:[e("span",{className:"text-sm truncate",children:r.name}),t("span",{className:"ms-2 text-xs",children:["(",r.count,")"]})]}):(console.warn(`Type data not found for ${n}`),n)},filterBy:(e,t)=>{const n=i.get(e);return n?n.name.toLowerCase().includes(t.toLowerCase()):(console.warn(`Type name not found for ${e}`),!1)}}}function Cp(e){return Array.isArray(e)?e:[]}function Sp(e){const{registry:t}=yp(),n=[];if(n.push({placeholder:"ID",name:"id",type:"text",options:[]}),n.push({placeholder:"Name",name:"name",type:"text",options:[]}),e.type){const r=_p({buckets:Cp(e.type),typeRegistry:t,type:"select",multiple:!0});n.push(r)}if(e.status){const t=Vm({buckets:Cp(e.status),name:"status",placeholder:"Status",type:"select",multiple:!0});n.push(t)}return e.tags&&n.push({name:"tags",placeholder:"Tags",type:"stringList",options:Cp(e.tags).map(e=>({label:e._id,value:e._id}))}),n.push({name:"created_at",placeholder:"Created Date",type:"date",multiple:!0,options:[]}),n.push({name:"updated_at",placeholder:"Updated Date",type:"date",multiple:!0,options:[]}),n}function Tp(e){return t=>{0!==t.length?(e.clearFilters(!1),t.forEach(t=>{if(t.value&&t.value.length>0){const n=t.name;let r;if("date"===t.type&&t.multiple){if(Array.isArray(t.value)&&t.value.length>0)if(1===t.value.length){const e=Mm(t.value[0]);r={gte:e,lte:e}}else if(2===t.value.length){r={gte:Mm(t.value[0]),lte:Mm(t.value[1])}}}else r=Fm(t);Om(e,"name"===n?"name":"id"===n?"id":n,r)}}),e.search()):e.clearFilters()}}function Ip({facets:n,search:r}){const[a,s]=Oe([]),i=Sp(n),o=Tp(r),l=E();return e(j,{filterGroups:i,filters:a,setFilters:e=>{const t="function"==typeof e?e(a):e;s(t),o(t)},inModal:l,children:t("div",{className:"flex gap-2 items-center",children:[e(P,{}),e(A,{}),e(D,{})]})})}function zp({search:t,buckets:n,placeholder:r="All Environments",className:a}){const{client:s}=tr(),[i,o]=Oe([]),l=t.getFilterValue("environment");He(()=>{if(s){const e=n.map(async e=>{let t;return await s.environments.retrieve(e._id).then(e=>{t=e.name}).catch(()=>{t=`${e._id} (deleted)`}),t||(t=e._id),{...e,name:t}});Promise.all(e).then(e=>{e.sort((e,t)=>e.name.localeCompare(t.name)),o(e)})}},[n,s]);const c=i?.find(e=>e._id===l);return e($,{filterBy:"name",className:a,isClearable:!0,optionLabel:Bm,options:i,value:c,onChange:e=>{t.setFilterValue("environment",e?._id)},by:"_id",placeholder:r})}function Rp(e){const t=[];t.push({name:"name",placeholder:"Name",type:"text",multiple:!1});t.push({name:"prompt",placeholder:"Prompt Name",type:"text",multiple:!1});t.push({name:"model",placeholder:"Model",type:"text",multiple:!1});return t.push({name:"tags",placeholder:"Tags",type:"stringList",multiple:!0}),t}function jp(e){return t=>{0!==t.length?(e.clearFilters(!1,!1),t.forEach(t=>{if(t.value&&t.value.length>0){const n=t.name,r=Fm(t);Om(e,n,r)}}),e.search(!0)):e.clearFilters(!0,!0)}}function Pp({facets:n,search:r}){const[a,s]=Oe([]),i=Rp(),o=jp(r);return e(j,{filterGroups:i,filters:a,setFilters:e=>{const t="function"==typeof e?e(a):e;s(t),o(t)},children:t("div",{className:"flex gap-2 items-center",children:[e(P,{}),e(A,{}),e(D,{})]})})}function Ap(e){const t=[];return t.push(Vm({buckets:e.statuses||[],name:"status",placeholder:"Status",multiple:!1})),t.push({name:"name",placeholder:"Name",type:"text",multiple:!1}),t}function Dp({facets:n,filters:r,setFilters:a}){const s=Ap(n);return e(j,{filterGroups:s,filters:r,setFilters:a,children:t("div",{className:"flex items-center gap-2",children:[e(P,{}),e(A,{}),e(D,{})]})})}function Ep(e){const t=[];return t.push(Vm({buckets:e.statuses||[],name:"status",placeholder:"Status",multiple:!0})),t.push(pp({buckets:e.started_by||[],name:"started_by",placeholder:"Started By"})),t.push(Vm({buckets:e.run_type||[],name:"run_type",placeholder:"Mode",multiple:!0})),t.push(Vm({buckets:e.processes||[],name:"process",placeholder:"Process",multiple:!0})),t.push({name:"start",placeholder:"Started After",type:"date",multiple:!1}),t.push({name:"end",placeholder:"Started Before",type:"date",multiple:!1}),t}function $p({facets:n,filters:r,setFilters:a}){const s=Ep(n);return e(j,{filterGroups:s,filters:r,setFilters:a,children:t("div",{className:"flex items-center gap-2",children:[e(P,{}),e(A,{}),e(D,{})]})})}function Lp(e){const t=[];if(t.push({name:"name",placeholder:"Name",type:"text",multiple:!1}),e.role&&e.role.length>0){const n={name:"role",placeholder:"Role",type:"select",options:e.role.map(e=>({label:e._id,value:e._id,count:e.count}))};t.push(n)}return t}function Mp(e){return t=>{0!==t.length?(e.clearFilters(!1,!1),t.forEach(t=>{if(t.value&&t.value.length>0){const n=t.name,r=Fm(t);Om(e,n,r)}}),e.search()):e.clearFilters(!0,!1)}}function Fp({facets:n,search:r,filters:a,setFilters:s,filterGroups:i}){const[o,l]=Oe([]),c=Lp(n),d=Mp(r),u=void 0!==a&&void 0!==s;return e(j,{filterGroups:i??c,filters:u?a:o,setFilters:e=>{if(u)return void s(e);const t="function"==typeof e?e(o):e;l(t),d(t)},children:t("div",{className:"flex gap-2 items-center",children:[e(P,{}),e(A,{}),e(D,{})]})})}function Op(n){const r=[];if(r.push({name:"run_ids",placeholder:"Run ID",type:"text",multiple:!1}),n.interactions){const e=Um({buckets:n.interactions||[],name:"interaction",placeholder:"Interactions"});r.push(e)}if(n.environments){const a=function({buckets:n,name:r}){const a=n.map(e=>({label:`(${e.count})`,value:e._id}));return{name:"environment",placeholder:r.charAt(0).toUpperCase()+r.slice(1),options:a,type:"select",labelRenderer:r=>{const a=n.find(e=>e._id===r);return t("div",{className:"w-full flex items-center",children:[e("span",{className:"text-sm truncate",children:a?.name||r}),t("span",{className:"ms-2 text-xs",children:["(",a?.count||0,")"]})]})},filterBy:(e,t)=>{const r=n.find(t=>t._id===e);return(r?.name||e).toLowerCase().includes(t.toLowerCase())}}}({buckets:n.environments||[],name:"environments"});r.push(a)}if(r.push({name:"tags",placeholder:"Tags",type:"stringList",multiple:!0}),n.models){const e=Vm({buckets:n.models||[],name:"model"});r.push(e)}if(n.statuses){const e=Vm({buckets:n.statuses||[],name:"status"});r.push(e)}if(n.finish_reason){const e=Vm({buckets:n.finish_reason.map(e=>({...e,_id:null===e._id?"none":e._id})),name:"finish_reason",placeholder:"Finish Reason"});r.push(e)}if(n.created_by){const e=pp({buckets:n.created_by||[],name:"created_by",placeholder:"Created By"});r.push(e)}r.push({name:"start",placeholder:"Date After",type:"date",multiple:!1});r.push({name:"end",placeholder:"Date Before",type:"date",multiple:!1});r.push({name:"workflow_run_ids",placeholder:"Workflow Run ID",type:"text",multiple:!1});return r.push({name:"workflow_ids",placeholder:"Workflow ID",type:"text",multiple:!1}),r}function Up(e){return t=>{0!==t.length?(e.clearFilters(!1,!1),t.forEach(t=>{if(t.value&&t.value.length>0){const n=t.name;let r=Fm(t);"run_ids"!==n&&"workflow_run_ids"!==n&&"workflow_ids"!==n||Array.isArray(r)||(r=[r]),Om(e,n,r)}}),e.search()):e.clearFilters(!0,!1)}}function Wp({facets:n,search:a,actions:s,selectionCount:i,filters:o,setFilters:l,filterGroups:c}){const[d,u]=Oe([]),m=Op(n),p=Up(a),h=void 0!==o&&void 0!==l,f=h?o:d;return e(j,{filterGroups:c??m,filters:f,setFilters:e=>{if(h)return void l(e);const t="function"==typeof e?e(d):e;u(t),p(t)},children:t("div",{className:"gap-2 items-center w-full",children:[t("div",{className:"flex justify-between mb-1",children:[e(P,{}),t("div",{className:"flex justify-end",children:[!i&&e("div",{className:"flex items-center justify-between px-2 py-1",children:e("div",{className:"text-sm text-muted",children:a.initialized?`${a.totalCount} calls`:"Loading calls..."})}),s&&s.length>0?e("div",{className:"flex items-center gap-2 mb-1 me-2",children:s.map((t,n)=>e("div",{children:t},n))}):null,e(r,{onClick:()=>{a.search()},variant:"outline",title:"Refresh",children:e(Tn,{className:"size-5"})})]})]}),f.length>0&&t("div",{className:"flex items-center gap-2 mb-1",children:[e(A,{}),e(D,{})]})]})})}function Bp({search:t,buckets:n,name:r,placeholder:a,className:s}){const i=t.getFilterValue(r),o=n?.find(e=>JSON.stringify(e._id)===JSON.stringify(i));return e($,{filterBy:"_id",className:s,isClearable:!0,optionLabel:Wm,options:n,value:o,onChange:e=>{t.setFilterValue(r,e?._id)},by:"_id",placeholder:a})}function Vp({search:t,name:n,placeholder:r,className:a}){const[s,i]=Oe([]);return He(()=>{t.setFilterValue(n,s)},[n,t,s]),e(L,{className:a,value:s,onChange:i,placeholder:r})}function qp(e){return`${e.name} (${e.count})`}function Hp({search:t,buckets:n,placeholder:r="Filter by Type",className:a}){const[s,i]=Oe([]),{registry:o}=yp(),l=t.getFilterValue("type");He(()=>{if(o){const e=n.map(e=>{let t;return null==e._id?(e._id="Document",t="Document"):(t=o.getTypeName(e._id),t||(console.warn("Content Object Type not found",e._id),t=e._id)),{...e,name:t}});e.sort((e,t)=>e.name.localeCompare(t.name)),i(e)}},[n,o]);const c=s?.find(e=>e._id===l);return e($,{filterBy:"name",className:a,isClearable:!0,optionLabel:qp,options:s,value:c,onChange:e=>{t.setFilterValue("type",e?._id)},by:"_id",placeholder:r})}function Gp(e){const t=[];return t.push(Vm({buckets:e.tags||[],name:"tags",placeholder:"Tags",multiple:!0})),t.push({name:"name",placeholder:"Name",type:"text",multiple:!1}),t}function Jp({facets:n,filters:r,setFilters:a}){const s=Gp(n);return e(j,{filterGroups:s,filters:r,setFilters:a,children:t("div",{className:"flex items-center gap-2",children:[e(P,{}),e(A,{}),e(D,{})]})})}function Kp(e){const t=[];if(t.push({placeholder:"Workflow Name or Workflow Run ID",name:"name",type:"text",options:[]}),e.status){const n=Vm({buckets:e.status||[],name:"status",placeholder:"Status"});t.push(n)}if(e.initiated_by){const n=pp({buckets:e.initiated_by||[],name:"initiated_by",placeholder:"Initiated By"});t.push(n)}t.push({name:"start",placeholder:"Date After",type:"date",multiple:!1});t.push({name:"end",placeholder:"Date Before",type:"date",multiple:!1});return t.push({name:"has_reported_errors",placeholder:"Has Reported Errors",type:"select",multiple:!1,options:[{label:"Yes",value:"true"},{label:"No",value:"false"}]}),t}function Yp(e){return t=>{0!==t.length?(e.clearFilters(!1),t.forEach(t=>{if(t.value&&t.value.length>0){const n=t.name,r=Fm(t);if("name"===n)Om(e,"search_term",r),Om(e,"name",r);else if("has_reported_errors"===n){const t=Array.isArray(r)?r[0]:r;"true"!==t&&"false"!==t||Om(e,n,"true"===t)}else Om(e,n,r)}}),e.search()):e.clearFilters()}}function Qp({facets:n,search:r}){const[a,s]=Oe([]),i=Kp(n),o=Yp(r);return e(j,{filterGroups:i,filters:a,setFilters:e=>{const t="function"==typeof e?e(a):e;s(t),o(t)},children:t("div",{className:"flex gap-2 items-center",children:[e(P,{}),e(A,{}),e(D,{})]})})}function Zp(e){const t=[];return t.push({name:"name",placeholder:"Name",type:"text",multiple:!1}),t}function Xp({facets:n,filters:r,setFilters:a}){const s=Zp();return e(j,{filterGroups:s,filters:r,setFilters:a,children:t("div",{className:"flex items-center gap-2",children:[e(P,{}),e(A,{}),e(D,{})]})})}class eh{object;objects;setState;collectionId;singleSelection=!1;constructor(e,t,n,r){this.object=e,this.objects=n,this.setState=r,this.singleSelection=0===Object.keys(this.objects).length,this.collectionId=t}isSingleSelection(){return this.singleSelection}hasSelection(){return void 0!==this.object||0!==this.size()}size(){return Object.keys(this.objects).length}getObjectIds(){return Object.keys(this.objects)}getObjectId(){return this.object?.id}clone(){return new eh(this.object,this.collectionId,this.objects,this.setState)}add(e){this.objects[e.id]=e,this.singleSelection=0===Object.keys(this.objects).length,this.setState(this.clone())}remove(e){delete this.objects[e],this.singleSelection=0===Object.keys(this.objects).length,this.setState(this.clone())}addAll(e){for(const t of e)this.objects[t.id]=t;this.setState(this.clone())}isSelected(e){return void 0!==this.objects[e]}removeAll(){this.objects={},this.singleSelection=!0,this.setState(this.clone())}}const th=Ue(void 0);function nh(){const e=We(th);if(!e)throw new Error("useObjectSelection must be used within a ObjectSelectionProvider");return e}function rh(){return We(th)}function ah({value:t,collectionId:n,children:r}){const[a,s]=Oe();return He(()=>{const e=new eh(t,n,{},s);s(e)},[n,t]),a&&e(th.Provider,{value:a,children:r})}const sh=Ue(void 0);function ih({onFilter:t,children:n}){return e(sh.Provider,{value:t,children:n})}const oh="h-6 w-6 p-0 opacity-0 group-hover/field:opacity-100 text-muted hover:text-foreground transition-opacity shrink-0";function lh({field:a,value:s,label:i,copyContent:o}){const l=We(sh),c=Array.isArray(s)?s.length>0:void 0!==s&&""!==s;return t(n,{children:[void 0!==o&&""!==o&&e(M,{content:o,className:oh}),c&&void 0!==s&&e(r,{variant:"ghost",size:"sm",title:`Filter by ${i}`,className:oh,onClick:e=>{e.stopPropagation(),l?.(a,s)},children:e(In,{className:"size-3"})})]})}const ch="text/csv",dh="image/",uh="application/pdf",mh="video/",ph=["application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/msword","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.ms-powerpoint"],hh=e=>e===ch||ch.includes(e),fh=e=>e.startsWith(dh)||dh.includes(e),gh=e=>e===uh||uh.includes(e),vh=e=>e.startsWith(mh)||mh.includes(e),bh=e=>ph.includes(e);function xh(e,t){if("undefined"==typeof window||"undefined"==typeof document)return!1;const n=document.createElement("iframe");n.style.position="fixed",n.style.right="0",n.style.bottom="0",n.style.width="0",n.style.height="0",n.style.border="0",n.style.visibility="hidden",document.body.appendChild(n);const r=n.contentWindow;if(!r)return n.parentNode?.removeChild(n),!1;const a=r.document;a.open(),a.write("<!doctype html><html><head><title></title></head><body></body></html>"),a.close(),a.title=t;document.querySelectorAll('link[rel="stylesheet"], style').forEach(e=>{a.head.appendChild(e.cloneNode(!0))});const s=a.createElement("style");return s.textContent='\n@media print {\n body {\n margin: 24px;\n font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;\n font-size: 14px;\n line-height: 1.5;\n color: #111827;\n background-color: #ffffff;\n }\n\n .vprose {\n max-width: 800px;\n margin: 0 auto;\n }\n\n .vprose h1 {\n font-size: 24px;\n font-weight: 700;\n margin: 1.5rem 0 0.75rem;\n }\n\n .vprose h2 {\n font-size: 20px;\n font-weight: 600;\n margin: 1.25rem 0 0.75rem;\n }\n\n .vprose h3 {\n font-size: 18px;\n font-weight: 600;\n margin: 1rem 0 0.5rem;\n }\n\n .vprose p {\n margin: 0 0 0.5rem;\n }\n\n .vprose ul,\n .vprose ol {\n margin: 0.5rem 0 0.5rem 1.5rem;\n padding: 0;\n }\n\n .vprose li {\n margin: 0.25rem 0;\n }\n\n .vprose table {\n width: 100%;\n border-collapse: collapse;\n margin: 1rem 0;\n }\n\n .vprose th,\n .vprose td {\n border: 1px solid #d1d5db;\n padding: 0.5rem 0.75rem;\n vertical-align: top;\n }\n\n .vprose thead th {\n background-color: #f3f4f6;\n font-weight: 600;\n }\n\n .vprose pre,\n .vprose code {\n font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;\n font-size: 12px;\n }\n\n .vprose pre {\n padding: 0.75rem;\n border-radius: 4px;\n border: 1px solid #e5e7eb;\n background-color: #f9fafb;\n white-space: pre-wrap;\n word-break: break-word;\n }\n\n /* Hide chart action buttons when printing */\n .chart-actions {\n display: none !important;\n }\n\n /* Hide interactive elements in agent conversation when printing */\n .print-hidden,\n [class*="print:hidden"],\n button[title="Copy message"],\n button[title="Copy to clipboard"],\n button[title="Export as PNG"],\n .message-actions {\n display: none !important;\n }\n\n /* Prevent page breaks inside elements */\n .vprose table,\n .vprose pre,\n .vprose blockquote,\n .vprose figure,\n .vprose img,\n [class*="chart"],\n [class*="Chart"] {\n break-inside: avoid;\n page-break-inside: avoid;\n }\n\n /* Keep headings with following content */\n .vprose h1,\n .vprose h2,\n .vprose h3,\n .vprose h4,\n .vprose h5,\n .vprose h6 {\n break-after: avoid;\n page-break-after: avoid;\n }\n\n /* Keep list items together when possible */\n .vprose li {\n break-inside: avoid;\n page-break-inside: avoid;\n }\n}\n',a.head.appendChild(s),a.body.innerHTML=e.innerHTML,r.focus(),r.print(),setTimeout(()=>{n.parentNode?.removeChild(n)},1e3),!0}const yh=import.meta.env,wh={max_hw:yh?.VITE_RENDITION_HW||256,format:fr.jpeg,generate_if_missing:!0},Nh="vertesia.content_store.renditionId";async function kh(e,t,n,r,a){if(!t?.content?.type||!(fh(t.content.type)||vh(t.content.type)||gh(t.content.type)))return void a("No preview available");a("Preparing preview...");const s=Date.now()/1e3,i=localStorage.getItem(`${Nh}_${t.id}_${wh.max_hw}`),o=localStorage.getItem(`${Nh}_${t.id}_${wh.max_hw}_time`);if(i?.length&&o&&Math.abs(s-parseInt(o,10))<=900)return n(i),r(`${t.name} Rendition`),a("ready"),i;a("Preparing preview..."),e.objects.getRendition(t.id,wh).then(s=>{if("generating"===s.status)a("Preparing preview..."),n(""),r(""),setTimeout(()=>kh(e,t,n,r,a),6e4);else{if("failed"===s.status)return a("No preview available"),n(""),void r("");{if(!s?.renditions?.length)return a("No preview available"),n(""),void r("");const e=s.renditions[0];localStorage.setItem(`${Nh}_${t.id}_${wh.max_hw}`,e),localStorage.setItem(`${Nh}_${t.id}_${wh.max_hw}_time`,(Date.now()/1e3).toString()),n(e),r(`${t.name} Rendition`),a("ready"),console.log(`Rendition for document ${t.id} retrieved successfully: ${e}`)}}}).catch(e=>{a("No preview available"),console.warn("Failed to retrieve rendition:",e),n(""),r("")})}function _h(e,t=7){return e?`~${e.slice(-t)}`:""}function Ch(e,t){return e.length>t?`${e.substring(0,t)}...`:e}function Sh(e){switch(e){case gr.RUNNING:return"text-info";case gr.COMPLETED:return"text-success";case gr.FAILED:return"text-destructive";case gr.TERMINATED:case gr.CANCELED:return"text-attention";default:return"text-muted"}}function Th(e){switch(e){case gr.RUNNING:return"Running";case gr.COMPLETED:return"Completed";case gr.FAILED:return"Failed";case gr.CONTINUED_AS_NEW:return"Continued As New";case gr.TERMINATED:return"Terminated";case gr.TIMED_OUT:return"Timed Out";case gr.CANCELED:return"Canceled";default:return"Unknown"}}function Ih(e){return"object"==typeof e&&null!==e}function zh(e,t){if(!Ih(e))return;const n=e[t];return"string"==typeof n?n:void 0}function Rh(e){return"string"==typeof e?e:zh(e,"id")||""}Dr.extend(Ta),Dr.extend(Sa);const jh={string(n,r){const a=[];if(n){const e=n.get("slice");e&&a.push(t=>t.slice(parseInt(e,10)));const t=n.get("max_length");t&&a.push(e=>e.slice(0,parseInt(t,10))),n.has("upper")&&a.push(e=>e.toUpperCase()),n.has("lower")&&a.push(e=>e.toLowerCase()),n.has("capitalize")&&a.push(e=>e[0].toUpperCase()+e.substring(1)),n.has("ellipsis")&&a.push(e=>`${e}...`)}return(n,r,s)=>{let i;if(n){if(i=String(n),a.length>0)for(const e of a)i=e(i)}else i="";return e("td",{className:"group/field",children:s?t("div",{className:"flex items-center gap-2 min-w-0",children:[e("span",{className:"truncate",children:i}),s]}):i},r)}},fileSize:(t,n)=>(t,n)=>{let r="";if(t){const e=Number(t);if(Number.isNaN(e))r=String(t);else{const t=["Bytes","KB","MB","GB","TB"];if(0===e)r="0 Bytes";else{const n=Math.floor(Math.log(e)/Math.log(1024));r=`${(e/1024**n).toFixed(2)} ${t[n]}`}}}return e("td",{className:"group/field",children:r},n)},number(t,n){let r,a;t&&(r=t.get("currency")||void 0,a=t.get("decimals")||void 0);const s=a?parseInt(a,10):2;return(t,n)=>{const a=Number(t),i=new Intl.NumberFormat("en-US",{style:r?"currency":"decimal",currency:r,maximumFractionDigits:s}).format(Number.isFinite(a)?a:0);return e("td",{className:"group/field",children:i},n)}},objectId(n,a){const s=[];let i=!1;if(n){const e=n.get("slice");e&&(i=!0,s.push(t=>t.slice(parseInt(e,10))))}return(n,o,l)=>{const c=Rh(n),d=s.reduce((e,t)=>t(e),c);return t("td",{className:"flex justify-start items-center gap-2 group/field",children:[e(r,{variant:"ghost",title:"Preview Object",onClick:e=>{e.stopPropagation(),a?.(c)},children:e(zn,{className:"size-4"})}),i?"~":"",d,l]},o)}},objectName(n,r){let a="title";return n&&(a=n.get("title")||"title"),(n,r,s)=>{const i=Ih(n)&&Ih(n.properties)?n.properties:void 0,o=i?.[a],l=function(e){return null==e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e?e:String(e)}(o),c=zh(n,"name"),d=zh(n,"id"),u=l||c||(d?_h(d):"");return e("td",{className:"group/field",children:s?t("div",{className:"flex items-center gap-2 min-w-0",children:[e("span",{className:"truncate",children:u}),s]}):u},r)}},objectLink(n,a){const s=[];return s.push(e=>e.slice(-7)),(n,i)=>{const o=Rh(n),l=s.reduce((e,t)=>t(e),o);return t("td",{className:"flex justify-between items-center gap-2 max-w-48 group/field",children:["~",l,e(r,{variant:"ghost",title:"Preview Object",onClick:e=>{e.stopPropagation(),a?.(o)},children:e(zn,{className:"size-4"})})]},i)}},typeLink:(n,r)=>(n,r,a)=>{const s=zh(n,"name")||"n/a";return e("td",{className:"group/field",children:a?t("div",{className:"flex items-center gap-2 min-w-0",children:[e("span",{className:"truncate",children:s}),a]}):s},r)},revision:(n,r)=>(n,r)=>{const a=Ih(n)&&Ih(n.revision)?n.revision:void 0;if(!a)return e("td",{},r);const s=zh(a,"root"),i=zh(a,"label");return e("td",{className:"group/field",children:t("div",{className:"flex flex-col gap-0.5",children:[s&&t("div",{className:"flex items-center gap-1",children:[t("span",{className:"text-xs text-muted font-mono",children:["root: ~",s.slice(-7)]}),e("a",{href:`/store/objects/${s}`,onClick:e=>e.stopPropagation(),children:e($t,{className:"size-3 text-muted"})})]}),i&&t("span",{className:"text-xs text-muted",children:["label: ",i]})]})},r)},date(n,r){let a,s="fromNow";if(n){const e=n.get("localized");if(e)s="format",a=e;else{const e=n.get("relative");e&&(s=e)}}return(n,r,i)=>{const o="string"==typeof n||"number"==typeof n||n instanceof Date?n:void 0;if(void 0===o)return e("td",{children:i},r);const l=Dr(o),c="format"===s?l.format(a):"toNow"===s?l.toNow():l.fromNow();return e("td",{className:"group/field",children:t("div",{className:"flex items-center gap-2",children:[e(h,{description:l.format("LLL"),children:c}),i]})},r)}}},Ph=jh.string();function Ah(e){return"object"==typeof e&&null!==e}function Dh(e,t){let n=e;if(!n)return;if(!t.length)return n;const r=t.length-1;for(let e=0;e<r;e++){if(!Ah(n))return;if(n=n[t[e]],!n)return}return Ah(n)?n[t[r]]:void 0}function Eh(e){return e&&"."!==e?e.split("."):[]}class $h{layout;renderer=Ph;path;fallbackPath;previewObject;constructor(e,t){if(this.layout=e,this.path=Eh(e.field||""),this.fallbackPath=e.fallback?Eh(e.fallback):void 0,this.previewObject=t,e.render)this.renderer=(e,t)=>null;else{const t=e.type||"string",n=t.indexOf("?");if(n>0){const e=t.substring(0,n),r=new URLSearchParams(t.substring(n+1));this.renderer=jh[e](r)}else this.renderer=jh[t]()}}get name(){return this.layout.name}resolveValue(e){let t=Dh(e,this.path);return void 0===t&&this.fallbackPath&&(t=Dh(e,this.fallbackPath)),void 0===t&&(t=this.layout.default),t}render(t,n){if(this.layout.render)return e("td",{className:"whitespace-nowrap px-3 py-4 text-sm group",children:this.layout.render(t)},n);const r=this.layout.type||"string",a=r.indexOf("?")>0?r.substring(0,r.indexOf("?")):r,s=this.buildActions(t,a);if(("objectId"===a||"objectLink"===a)&&this.previewObject){const e=r.indexOf("?"),i=e>0?new URLSearchParams(r.substring(e+1)):void 0;return jh[a](i,e=>{this.previewObject?.(t.id)})(t,n,s)}return this.renderer(this.resolveValue(t),n,s)}buildActions(t,n){const r=this.layout.field;if("objectId"===n||"objectLink"===n||"id"===r)return e(lh,{field:"id",value:t.id,label:t.id,copyContent:t.id});if("objectName"===n||"name"===r)return e(lh,{field:"name",value:t.name,label:t.name??t.id});if("typeLink"===n||"type.name"===r||"type"===r){const n=t.type?.id;return e(lh,{field:"type",value:n,label:t.type?.name??n??"type"})}return"status"===r?e(lh,{field:"status",value:t.status,label:t.status}):void 0}}function Lh({isLoading:n=!1,counts:r=6}){return n?e("div",{className:"flex flex-wrap gap-2 justify-between",children:Array(r).fill(0).map((n,r)=>e("div",{className:"w-[15vw] animate-pulse",children:t(F,{className:"relative flex flex-col border h-fit",children:[e("div",{className:"h-48 bg-muted rounded-t-xl flex items-center justify-center text-muted",children:" "}),e(O,{className:"bg-muted h-[2px]"}),t(U,{className:"p-2 flex flex-col",children:[t("div",{className:"flex flex-col overflow-hidden",children:[e("div",{className:"h-5 bg-muted rounded w-3/4 mb-2"}),e("div",{className:"h-4 bg-muted rounded w-1/2"})]}),e("div",{className:"text-xs text-muted w-full flex justify-end mt-2",children:e("div",{className:"h-3 bg-muted rounded w-1/4"})})]})]})},r))}):null}function Mh({selection:n,document:a,onSelectionChange:s,onRowClick:i,highlightRow:o,previewObject:l,selectedObject:c}){const{client:d}=tr(),[u,m]=Oe(void 0),[p,f]=Oe(void 0),[g,v]=Oe(void 0),b="string"==typeof a.properties?.title?a.properties.title:a.name;He(()=>{a?.content&&kh(d,a,m,f,v)},[d,a]);const x=o?.(a);return t(F,{className:`relative flex flex-col border h-fit w-full ${c?.id===a.id?"border-attention border-4":""} ${x?"border-blue-400 dark:border-blue-500 bg-blue-50/50 dark:bg-blue-900/20":""}`,onClick:()=>i?.(a),children:[x&&e("div",{className:"absolute top-2 end-8 z-10",children:e(Rn,{className:"size-4 text-blue-600 dark:text-blue-400"})}),n&&e("div",{className:"absolute top-2 start-2 z-10 flex flex-col items-center gap-1",children:e("input",{checked:n.isSelected(a.id),type:"checkbox",onChange:e=>{e.stopPropagation(),s(a,e)},onClick:e=>e.stopPropagation()})}),e("div",{className:"absolute top-1 end-1 z-10 flex flex-col items-center",children:e(r,{variant:"ghost",size:"sm",title:"Preview Object",onClick:e=>{e.stopPropagation(),l?.(a.id)},children:e(zn,{className:"size-4 "+("ready"===g?"text-muted":"text-white")})})}),u&&"ready"===g?e("img",{src:u,alt:p,className:"w-auto h-48 object-cover rounded-t-xl"}):e("div",{className:"h-48 bg-gray-700 rounded-t-xl flex items-center justify-center text-muted",children:g}),e(O,{className:"bg-gray-200 h-[2px]"}),t(U,{className:"p-2 flex flex-col",children:[t("div",{className:"flex flex-col overflow-hidden",children:[e(h,{placement:"top",description:b,children:e("h3",{className:"text-start font-medium leading-none truncate",children:b})}),a?.type?.name?e(h,{placement:"bottom",size:"xs",description:a?.type?.name,children:e("p",{className:"text-start text-xs text-muted truncate",children:a?.type?.name})}):e("p",{className:"text-xs text-muted",children:" "})]}),a.score&&t("div",{className:"text-xs text-muted w-full flex justify-end",children:["Score: ",a.score.toFixed(4)??"-"]})]})]})}function Fh({objects:n,selection:r,isLoading:a,columns:s,onRowClick:i,highlightRow:o,selectedObject:l,toggleAll:c,onSelectionChange:d}){const{t:u}=Ze();return t(C,{className:"w-full",children:[e(W,{children:t("tr",{children:[r&&e("th",{children:e("input",{type:"checkbox",onChange:c})}),s.map(t=>e("th",{children:t.name},t.name))]})}),t(B,{isLoading:a,columns:s.length+1,children:[n?.map(n=>{const a=o?.(n);return t("tr",{className:`group cursor-pointer hover:bg-muted ${l?.id===n.id?"bg-muted":""} ${a?"bg-blue-50 dark:bg-blue-900/20":""}`,onClick:()=>{i?.(n)},children:[r&&e("td",{onClick:e=>e.stopPropagation(),children:e("input",{checked:r.isSelected(n.id),type:"checkbox",className:""+(r.isSelected(n.id)?"":"hidden group-hover:block"),onChange:e=>d(n,e)})}),s.map((e,t)=>e.render(n,t)),e("td",{className:"w-8 text-center",children:a&&e(Rn,{className:"size-4 text-blue-600 dark:text-blue-400 inline-block"})})]},n.id)}),0===n.length&&e("tr",{children:e("td",{colSpan:s.length+(r?1:0),className:"text-center",children:u("store.noObjectsDragAndDrop")})})]})]})}function Oh({objects:r,selection:a,isLoading:s,onSelectionChange:i,onRowClick:o,highlightRow:l,previewObject:c,selectedObject:d}){return t(n,{children:[e(Lh,{isLoading:s}),e("div",{className:"w-full gap-2 grid xs:grid-cols-1 sm:grid-cols-2 md:grid-cols-4 lg:grid-cols-6 @xs:grid-cols-1 @sm:grid-cols-2 @md:grid-cols-3 @lg:grid-cols-4",children:r.map(t=>e(Mh,{document:t,selection:a,onSelectionChange:i,onRowClick:o,highlightRow:l,previewObject:c,selectedObject:d},t.id))})]})}class Uh{client;limit;collectionId;facets=new V({});result=new V({objects:[],isLoading:!1});initialized=!1;facetSpecs=[];query={};constructor(e,t=100){this.client=e,this.limit=t}withFacets(e){return this.facetSpecs=e,this}get objects(){return this.result.value.objects}get error(){return this.result.value.error}get isRunning(){return this.result.value.isLoading}get hasMore(){return this.result.value.hasMore||!1}getFilterValue(e){return this.query[e]}setFilterValue(e,t){this.query[e]=t,this.search()}setDefaultKeys(e){}clearFilters(e=!0){const{parent:t,full_text:n,vector:r,weights:a,score_aggregation:s,dynamic_scaling:i,limit:o,all_revisions:l}=this.query;this.query={parent:t,...void 0!==n&&{full_text:n},...void 0!==r&&{vector:r},...void 0!==a&&{weights:a},...void 0!==s&&{score_aggregation:s},...void 0!==i&&{dynamic_scaling:i},...void 0!==o&&{limit:o},...void 0!==l&&{all_revisions:l}},e&&this.search()}getFacetBuckets(e){const t=this.facets.value[e];return Array.isArray(t)?t:[]}resetFacets(){this.query={}}reset(e=!1){this.initialized=!1,this.result.value={objects:[],isLoading:e,hasMore:!0}}_updateRunningState(e){const t=this.result.value;this.result.value={objects:t.objects,isLoading:e,error:t.error,hasMore:t.hasMore}}_searchRequest(e,t,n,r=!0){const a={limit:t,offset:n,query:e,facets:r?this.facetSpecs:void 0};return this.collectionId?this.client.collections.searchMembers(this.collectionId,a):this.client.objects.search(a)}_facetsRequest(){const e={facets:this.facetSpecs,query:this.query};return this.collectionId?this.client.collections.computeFacets(this.collectionId,e):this.client.objects.computeFacets(e)}computeFacets(e){this._facetsRequest().then(e=>{this.facets.value=e})}async _search(e=!1,t=!1){if(this.isRunning&&e)return!1;const n=this.result.value;e||(this.initialized=!0),this.result.value={isLoading:!0,objects:e?this.objects:[],hasMore:!e||this.result.value.hasMore};const r=this.limit,a=e?this.objects.length:0;try{const n=await this._searchRequest(this.query,r,a,!t),s=n.results||[],i=n.facets||{};return this.result.value={isLoading:!1,objects:e?this.objects.concat(s):s,hasMore:s.length===r},!t&&i&&Object.keys(i).length>0&&(this.facets.value=i),!0}catch(e){if("object"==typeof e&&null!==e&&"status"in e&&404===e.status)return this.result.value={isLoading:!1,objects:[],hasMore:!1},!1;const t=e instanceof Error?e:new Error(String(e));return this.result.value={error:t,isLoading:!1,objects:n.objects,hasMore:!1},!1}}search(e=!1){return this.isRunning?Promise.resolve(!1):this._search(!1,e)}loadMore(e=!1){return this.isRunning||!this.hasMore||this.query.vector?Promise.resolve(!1):(this.objects.length>0&&(e=!0),this._search(!0,e))}}const Wh=Ue(void 0);function Bh(){return We(Wh)}function Vh(){return q(Bh().facets)}function qh(){const e=Bh();return{...q(e.result),search:e}}function Hh(){const e=Bh();return q(e.facets).total}const Gh=Xe.getFixedT(null,et);var Jh;async function Kh(e){try{const t=await e.arrayBuffer(),n=new Ia;n.appendByteArray(new Uint8Array(t));const r=n.end();return r?.toString()}catch(e){return void console.error("Error calculating file hash:",e)}}function Yh(){const{client:e}=tr(),t=p();return{checkDocumentProcessing:Ve(async(n,r,a)=>{try{console.log(`Preparing metadata for ${n.length} files...`);const t=await async function(e,t){const n=[];for(let r=0;r<e.length;r+=5){const a=e.slice(r,r+5),s=await Promise.all(a.map(async e=>{let n=t||"/";if(e.webkitRelativePath){const r=e.webkitRelativePath.split("/");if(r.length>1){const e=r.slice(0,-1).join("/");n=t?`${t}/${e}`:e}}return{file:e,hash:await Kh(e),name:e.name,size:e.size,location:n}}));n.push(...s)}return n}(n,r),s=async()=>{const n=t.map(e=>e.hash).filter(Boolean);if(0===n.length)return;const r={"content.etag":{$in:n}};let s;if(a){const t={query:{match:r},select:"id content.etag"};s=(await e.store.collections.searchMembers(a,t)).results}else{const t={query:r,select:"id content.etag"};s=await e.store.objects.find(t)}for(const e of s){const n=t.find(t=>t.hash===e.content?.etag);n&&(n.existingId=e.id,n.action=Jh.SKIP)}},i=async()=>{const n=t.filter(e=>e.action!==Jh.SKIP),r=n.map(e=>e.location),s=Array.from(new Set(r)),i=[];for(const t of s){const r={"content.name":{$in:n.filter(e=>e.location===t).map(e=>e.name)},location:t||"/"};if(a){const t=e.store.collections.searchMembers(a,{query:{match:r},select:"id content.name location"}).then(e=>e.results);i.push(t)}else{const t=e.store.objects.find({query:r,select:"id content.name location"});i.push(t)}}const o=(await Promise.all(i)).flat();console.log(`Found ${o.length} document to update`,o);for(const e of o){const n=t.find(t=>t.name===e.content?.name&&(t.location?t.location===e.location:"/"===e.location));n&&(n.existingId=e.id,n.action=Jh.UPDATE)}console.log(`Reconciled ${t.filter(e=>e.action===Jh.UPDATE).length}`)};return await s(),await i(),t.forEach(e=>{e.action||(e.action=Jh.CREATE)}),console.log("Document processing check results:",{totalFiles:n.length,toCreate:t.filter(e=>e.action===Jh.CREATE).length,toUpdate:t.filter(e=>e.action===Jh.UPDATE).length,toSkip:t.filter(e=>e.action===Jh.SKIP).length}),t}catch(e){throw t({title:Gh("store.errorInUploadProcessingCheck"),status:"error",description:T(e)}),console.log("Error in file upload processing check",e),new Error(`Error in file upload processing check: ${T(e)}`,{cause:e})}},[e,t])}}function Qh({isOpen:a,onClose:s,files:i,collectionId:o,selectedFolder:l,title:c,children:d,onUploadComplete:u,hideFileSelection:m=!1,showTypeSelectionOnly:f=!1,allowFolders:g=!0}){const{client:v}=tr(),{registry:b}=yp(),x=p(),{t:y}=Ze(),w=c??y("upload.uploadFiles"),[N,k]=Oe([]),[_,C]=Oe([]),[S,I]=Oe(!1),[z,R]=Oe(null),[j,P]=Oe([]),[A,D]=Oe(!1),[E,L]=Oe(!1),[M,F]=Oe(0),[O,U]=Oe(Date.now()),[W,B]=Oe(void 0),[V,q]=Oe(null),[Z,X]=Oe(w),[ee,te]=Oe("");He(()=>{o&&v.store.collections.retrieve(o).then(B)},[v.store.collections.retrieve,o]),He(()=>{A?(X(y("upload.uploadingFiles")),te(`${Math.round(M)}% complete`)):E?(X(y("upload.uploadComplete")),te("")):S?(X(y("upload.fileAnalysisResults")),te(`${N.length} file${1!==N.length?"s":""}`)):N.length>0?(X(w),te(y("upload.checkingForDuplicates"))):(X(w),te(""))},[A,E,S,w,M,N.length,y]);const ne=()=>W||l?t(Y,{className:"mb-4",status:"default",icon:e(cn,{className:"size-5"}),children:[e("div",{className:"flex items-center",children:e("span",{className:"font-medium",children:y("upload.uploadLocation")})}),t("div",{className:"text-sm mt-1",children:[W&&t("div",{className:"flex items-center",children:[e("span",{className:"me-1",children:y("upload.collectionLabel")}),e("span",{className:"font-medium",children:W.name})]}),l&&t("div",{className:"flex items-center mt-1",children:[e("span",{className:"me-1",children:y("upload.folderLabel")}),e("span",{className:"font-medium",children:l})]})]})]}):null,[re,ae]=Oe({toCreate:0,toUpdate:0,toSkip:0}),{checkDocumentProcessing:se}=Yh(),ie=Fe(()=>b?.types||[],[b?.types]),oe=Ve(async e=>{if(e.length)try{console.log(`Processing ${e.length} files to determine required actions...`);const t=await se(e,l,o);C(t);const n=t.filter(e=>e.action===Jh.CREATE).length,r=t.filter(e=>e.action===Jh.UPDATE).length,a=t.filter(e=>e.action===Jh.SKIP).length;ae({toCreate:n,toUpdate:r,toSkip:a}),x({title:y("upload.filesAnalyzed"),description:`${e.length} file(s): ${n} new, ${r} to update, ${a} to skip`,status:"info",duration:4e3}),I(!0)}catch(e){console.error("Error processing files:",e),x({title:y("agent.error"),description:y("upload.errorAnalyzingFiles"),status:"error",duration:5e3})}},[se,o,l,y,x]);He(()=>{a&&(C([]),I(!1),R(null),P([]),D(!1),L(!1),F(0),ae({toCreate:0,toUpdate:0,toSkip:0}),q(null),X(w),te(""),i&&i.length>0?(k(i),oe(i)):k([]),U(Date.now()))},[a,i,oe,w]);const le=()=>{k([]),C([]),I(!1),R(null),P([]),D(!1),L(!1),F(0),ae({toCreate:0,toUpdate:0,toSkip:0}),q(null),X(w),te(""),U(Date.now()),s()},ce=e=>{e&&e.length>0&&(k(e),oe(e))},de=async()=>{if(!_.length)return;const e=z?.id||null,t=_.map(e=>({file:e.file,status:"pending",progress:0,action:e.action===Jh.CREATE?"create":e.action===Jh.UPDATE?"update":"skip"}));P(t),D(!0),L(!1);const n=_.filter(e=>e.action===Jh.SKIP),r=_.filter(e=>e.action===Jh.UPDATE),a=_.filter(e=>e.action===Jh.CREATE),s={success:!0,objectIds:[],uploadedFiles:[],skippedFiles:[],failedFiles:[]};for(const t of n)t.existingId&&(s.objectIds.push(t.existingId),s.skippedFiles.push({id:t.existingId,name:t.name,type:e,status:"skipped",location:t.location}),P(e=>e.map(e=>e.file===t.file?{...e,status:"success",progress:100,id:t.existingId}:e)));const i=async(t,n)=>{const r=[];for(let e=0;e<t.length;e+=50)r.push(t.slice(e,e+50));for(let a=0;a<r.length;a++){const i=r[a];if(console.log(`Processing ${n} batch ${a+1}/${r.length} (${i.length} files)`),t.length>50){const e=50*a;x({title:y("upload.processingFilesAction",{action:n}),description:y("upload.processedCount",{processed:e,total:t.length}),status:"info",duration:2e3})}let l=0;await Promise.all(i.map(async t=>{try{if(P(e=>e.map(e=>e.file===t.file?{...e,status:"uploading",progress:20}:e)),"update"===n&&t.existingId)await v.store.objects.update(t.existingId,{type:e||void 0,content:t.file,location:t.location,name:t.name},{createRevision:!0,revisionLabel:`upload on ${(new Date).toISOString()}`}),P(e=>e.map(e=>e.file===t.file?{...e,status:"success",progress:100,id:t.existingId}:e)),s.objectIds.push(t.existingId),s.uploadedFiles.push({id:t.existingId,name:t.name,type:e,status:"updated",location:t.location});else{const n=await v.store.objects.create({type:e||void 0,content:t.file,location:t.location||t.file.webkitRelativePath||t.name},{collection_id:o});P(e=>e.map(e=>e.file===t.file?{...e,status:"success",progress:100,id:n.id}:e)),s.objectIds.push(n.id),s.uploadedFiles.push({id:n.id,name:t.name,type:e,status:"created",location:t.location})}}catch(n){console.error(`Failed to process file ${t.name}:`,n),P(e=>e.map(e=>e.file===t.file?{...e,status:"error",progress:100,message:T(n,"Unknown error")}:e)),s.failedFiles.push({name:t.name,error:T(n,"Unknown error"),status:"failed",location:t.location,type:e}),s.success=!1}l++,l%5!=0&&l!==i.length||P(e=>{const t=e.filter(e=>"success"===e.status||"error"===e.status).length,n=e.length,r=n>0?Math.round(t/n*100):0;return F(r),e})}))}};r.length>0&&await i(r,"update"),a.length>0&&await i(a,"create"),P(e=>{const t=e.filter(e=>"pending"===e.status).map(e=>({...e,status:"error",progress:100,message:y("upload.uploadProcessInterrupted")}));return t.length>0?(t.forEach(e=>{s.failedFiles.push({name:e.file.name,error:y("upload.uploadProcessInterrupted"),status:"failed",type:z?.id||null})}),s.success=!1,e.map(e=>"pending"===e.status?{...e,status:"error",progress:100,message:y("upload.uploadProcessInterrupted")}:e)):e}),D(!1),L(!0);const l=s.uploadedFiles.filter(e=>"created"===e.status).length,c=s.uploadedFiles.filter(e=>"updated"===e.status).length,d=s.skippedFiles.length,u=s.failedFiles.length;let m="";l>0&&(m+=`${l} file${1!==l?"s":""} uploaded`),c>0&&(m+=m?", ":"",m+=`${c} file${1!==c?"s":""} updated`),d>0&&(m+=m?", ":"",m+=`${d} file${1!==d?"s":""} skipped`),u>0&&(m+=m?", ":"",m+=`${u} file${1!==u?"s":""} failed`),x({title:y("upload.uploadComplete"),description:m,status:u>0?"warning":"success",duration:5e3}),q(s)},ue=()=>t("div",{className:"mb-4",children:[t("div",{className:"block text-sm font-medium mb-2",children:[y("store.contentType")," ",e("span",{className:"text-muted font-normal",children:y("store.optional")}),e(h,{description:y("upload.contentTypeTooltip"),placement:"top",size:"xs",children:e(qt,{className:"size-3 ms-2"})})]}),e($,{options:ie,value:z,optionLabel:e=>e?e.name:y("store.selectContentTypeLabel"),placeholder:y("store.selectContentTypeAuto"),onChange:e=>R(void 0===e?null:e),filterBy:"name",isClearable:!0}),!z&&e("div",{className:"p-2 rounded-md",children:t("div",{className:"flex items-center text-attention",children:[e(bn,{className:"size-4 me-1"}),y("store.automaticTypeDetection"),e(h,{description:y("store.automaticTypeDetectionDescription"),placement:"top",size:"xs",children:e(qt,{className:"size-3 ms-2"})})]})})]});return t(H,{isOpen:a,onClose:le,className:"mx-auto",disableCloseOnClickOutside:!0,children:[e(G,{description:ee,children:Z}),f?t(J,{children:[d,ne(),ue()]}):0!==N.length||m?A||E?A?t(J,{children:[ne(),e("div",{className:"mb-4",children:e("div",{className:"h-2 bg-muted/20 rounded-full overflow-hidden",children:e("div",{className:"h-full bg-primary rounded-full",style:{width:`${M}%`}})})}),e("div",{className:"max-h-96 overflow-y-auto",children:j.map((n,r)=>t("div",{className:"flex items-center py-2 border-b border-border last:border-b-0",children:[t("div",{className:"me-3",children:["pending"===n.status&&e(dn,{className:"size-5 text-muted"}),"uploading"===n.status&&e(K,{size:"sm"}),"success"===n.status&&e(bn,{className:"size-5 text-success"}),"error"===n.status&&e(vn,{className:"size-5 text-destructive"})]}),t("div",{className:"flex-1 min-w-0",children:[e("div",{className:"truncate font-medium",children:n.file.name}),t("div",{className:"text-xs text-muted",children:["pending"===n.status&&y("agent.waiting"),"uploading"===n.status&&y("agent.uploading"),"success"===n.status&&("create"===n.action?y("store.created"):"update"===n.action?y("store.updated"):y("upload.skip")),"error"===n.status&&n.message]})]})]},`${n.file.name}-${n.file.size}-${n.file.lastModified}`))})]}):e(J,{children:t("div",{className:"mb-4",children:[ne(),e(ca,{files:j.map(e=>{let t;return t="success"===e.status?"create"===e.action?"success":"update"===e.action?"updated":"skipped":"failed",{name:e.file.name,status:t,error:"error"===e.status?e.message:void 0}}),location:l||void 0,collection:W?.name})]})}):e(J,{children:S?t(n,{children:[ne(),e("div",{className:"mb-4",children:e("div",{className:"p-4 rounded-md mb-4",children:t("div",{className:"grid grid-cols-3 gap-4",children:[t("div",{className:"flex flex-col items-center",children:[t("div",{className:"flex items-center gap-2",children:[e(jn,{className:"size-5 text-primary"}),e("span",{className:"font-medium",children:y("upload.new")})]}),e("div",{className:"text-2xl font-semibold",children:re.toCreate})]}),t("div",{className:"flex flex-col items-center",children:[t("div",{className:"flex items-center gap-2",children:[e(bn,{className:"size-5 text-success"}),e("span",{className:"font-medium",children:y("upload.update")})]}),e("div",{className:"text-2xl font-semibold",children:re.toUpdate})]}),t("div",{className:"flex flex-col items-center",children:[t("div",{className:"flex items-center gap-2",children:[e(Pn,{className:"size-5 text-mixer-attention/40"}),e("span",{className:"font-medium",children:y("upload.skip")})]}),e("div",{className:"text-2xl font-semibold",children:re.toSkip})]})]})})}),ue(),e(Y,{className:"mb-4",status:"info",children:re.toCreate+re.toUpdate>0?t("div",{className:"space-y-1",children:[e("p",{children:y("upload.filesReadyToProcess",{count:re.toCreate+re.toUpdate})}),e("p",{children:re.toSkip>0&&y("upload.filesToSkip",{count:re.toSkip})})]}):re.toSkip>0?e("span",{children:y("upload.allFilesExist",{count:re.toSkip})}):e("span",{children:y("upload.noFilesToProcess")})})]}):t("div",{className:"flex flex-col items-center justify-center py-4",children:[e(K,{size:"lg",className:"mb-4"}),e("div",{className:"text-lg font-medium",children:y("upload.analyzingFiles")})]})}):t(J,{className:"flex flex-col items-center justify-center p-8",children:[ne(),e(la,{onDrop:ce,message:y("upload.dragAndDrop"),buttonLabel:y("upload.selectFiles"),className:"w-full h-64",allowFolders:g}),d]}),(()=>{if(f)return t(Q,{children:[e(r,{variant:"ghost",onClick:le,children:y("modal.cancel")}),e(r,{onClick:()=>{u&&u({success:!0,objectIds:[],uploadedFiles:[{name:"type-selection",type:z?.id||null,status:"created"}],skippedFiles:[],failedFiles:[]}),le()},children:z?y("upload.useTypeName",{typeName:z.name}):y("upload.useAutoDetection")})]});if(0===N.length&&!m)return e(Q,{children:e(r,{variant:"ghost",onClick:le,children:y("modal.cancel")})});if(!A&&!E){const n=S;return t(Q,{children:[e(r,{variant:"ghost",onClick:le,children:y("modal.cancel")}),e(r,{disabled:!n,onClick:de,children:re.toCreate+re.toUpdate>0?y("agent.upload"):y("upload.continue")})]})}return A?e(Q,{children:e(r,{variant:"ghost",disabled:!0,children:y("agent.uploading")})}):t(Q,{children:[e(r,{variant:"ghost",onClick:()=>{k([]),C([]),I(!1),R(null),P([]),D(!1),L(!1),F(0),ae({toCreate:0,toUpdate:0,toSkip:0})},children:y("upload.uploadMore")}),e(r,{onClick:()=>{u&&V&&u(V),le()},children:y("agent.close")})]})})()]},O)}function Zh(e){const t="function"==typeof e?e:e.onUploadDone,{client:n,project:r,store:a}=tr(),s=Bh(),i=p(),o=Xe.getFixedT(null,et),{checkDocumentProcessing:l}=Yh();return async(e,c,d)=>{const u={success:!1,objectIds:[],uploadedFiles:[],skippedFiles:[],failedFiles:[]};if(!r)return i({status:"error",title:o("store.noProjectSelected"),duration:3e3}),u;if(!e||0===e.length)return i({status:"warning",title:o("store.noFilesSelected"),duration:3e3}),u;const m=Array.from(e).filter(e=>e.size>0);if(0===m.length)return i({status:"error",title:o("store.noValidFilesSelected"),description:o("store.pleaseSelectValidFiles"),duration:5e3}),u;const p=[],h=[],f=[];console.log(`Processing ${m.length} files with smart file processing...`);const g=await l(m,null,d),v=g.filter(e=>e.action===Jh.CREATE).length,b=g.filter(e=>e.action===Jh.UPDATE).length,x=g.filter(e=>e.action===Jh.SKIP).length;i({title:o("store.filesAnalyzedTitle"),description:`${m.length} file(s): ${v} new, ${b} to update, ${x} to skip`,status:"info",duration:4e3});for(const e of g.filter(e=>e.action===Jh.SKIP&&e.existingId))p.push({id:e.existingId,name:e.name,type:c,status:"skipped",location:e.location});const y=g.filter(e=>(e.action===Jh.CREATE||e.action===Jh.UPDATE)&&e.file);if(y.length>0){console.log(`Processing ${y.length} files (${y.filter(e=>e.action===Jh.CREATE).length} create, ${y.filter(e=>e.action===Jh.UPDATE).length} update)...`);const e=50,t=[];for(let n=0;n<y.length;n+=e)t.push(y.slice(n,n+e));for(let r=0;r<t.length;r++){const s=t[r],l=r*e;console.log(`Processing batch ${r+1}/${t.length} (${s.length} files)`),y.length>e&&i({title:o("store.processingFiles"),description:`Processed ${l}/${y.length} files...`,status:"info",duration:2e3});const m=await Promise.all(s.map(async e=>{try{if(e.action===Jh.UPDATE&&e.existingId){const t=await n.store.objects.update(e.existingId,{type:c||void 0,content:e.file,location:e.location,name:e.name},{createRevision:!0,revisionLabel:`upload on ${(new Date).toISOString()}`});return h.push({id:e.existingId,name:e.name,type:c,status:"updated",location:e.location}),u.objectIds.push(e.existingId),{success:!0,id:t.id,name:e.name,action:"update"}}{const t=d?{collection_id:d}:void 0,n=await a.objects.create({type:c||void 0,content:e.file,location:e.location||e.file.webkitRelativePath||e.name},t);h.push({id:n.id,name:e.name,type:c,status:"created",location:e.location})}}catch(t){console.error(`Failed to process file ${e.name}:`,t),f.push({name:e.name,error:T(t,"Unknown error"),status:"failed",location:e.location,type:c}),i({status:"error",title:o("store.processingFailedFor",{name:e.name}),description:T(t),duration:4e3})}})),p=h.filter(e=>"created"===e.status),g=h.filter(e=>"updated"===e.status),v=h.filter(e=>"failed"===e.status);console.log(`Batch ${r+1} results:`,{creates:p,updates:g,failures:v,total:m.length})}}const w=h.filter(e=>"created"===e.status).length,N=h.filter(e=>"updated"===e.status).length,k=h.filter(e=>"failed"===e.status).length,_=h.filter(e=>"skipped"===e.status).length;t&&(console.log("Upload complete:",{totalObjectIds:u.objectIds.length,uploadedFiles:w,updatedFiles:N,skippedFiles:_,failedFiles:k}),await t(u.objectIds));let C="";return w>0&&(C+=`${w} file${1!==w?"s":""} uploaded`),N>0&&(C+=C?", ":"",C+=`${N} file${1!==N?"s":""} updated`),_>0&&(C+=C?", ":"",C+=`${_} file${1!==_?"s":""} skipped (already existed)`),k>0&&(C+=C?", ":"",C+=`${k} file${1!==k?"s":""} failed`),C&&i({status:k>0?"warning":"success",title:C,duration:4e3}),s.search(),u}}!function(e){e.CREATE="create",e.SKIP="skip",e.UPDATE="update"}(Jh||(Jh={}));const Xh=[{name:"ID",field:"id",type:"objectId?slice=-7"},{name:"Name",field:".",type:"objectName"},{name:"Type",field:"type.name",type:"string"},{name:"Status",field:"status",type:"string"},{name:"Updated At",field:"updated_at",type:"date"}];function ef({isGridView:t=!1,onUpload:n,collectionId:r,...a}){return n?e(tf,{...a,onUpload:n,isGridView:t,collectionId:r}):e(nf,{...a,isGridView:t})}function tf({isGridView:n,onUpload:r,collectionId:a,skipTypeModal:s=!1,...i}){const[o,l]=Oe(!1),[c,d]=Oe([]),[u,m]=Oe(!1),[h,f]=Oe(null),[g,v]=Oe(!1),b=Bh(),x=p(),{t:y}=Ze(),{checkDocumentProcessing:w}=Yh(),N=async(e,t)=>{console.log("Files dropped on ObjectTable:",e.length,t),l(!0);try{if(a){const t=await w(e,null,a);f(t);const n=t.filter(e=>"create"===e.action).length,r=t.filter(e=>"update"===e.action).length,s=t.filter(e=>"skip"===e.action).length;x({title:y("store.filesReadyToProcess"),description:`${e.length} file(s): ${n} new, ${r} to update, ${s} to skip`,status:"info",duration:4e3})}else f(null)}catch(e){console.error("Error processing files:",e),x({title:y("store.errorProcessingFiles"),description:y("store.errorCheckingDuplicates"),status:"error",duration:4e3}),f(null)}finally{if(l(!1),d(e),m(!1),s){console.log("Skipping type modal and calling onUpload directly",{filesLength:e.length,processedFilesLength:h?.length});const t=r(e,null,a);t&&"object"==typeof t&&(t.processedFiles=h)}else console.log("Setting typeSelectionOpen to true",{filesLength:e.length}),v(!0)}},k=e=>{const t=[...c];d([]),f(null),v(!1),t.length>0&&void 0!==e&&(l(!0),console.log("Starting upload with",{typeId:e,filesCount:t.length,hasProcessingResults:!!h,collectionId:a}),r(t,e,a).finally(()=>{l(!1),b.search()}))},_=e=>{e.preventDefault(),e.stopPropagation(),m(!0)};return t("div",{className:"min-h-[400px] relative",onDragOver:_,onDragEnter:_,onDragLeave:e=>{e.preventDefault(),e.stopPropagation(),e.currentTarget.contains(e.relatedTarget)||m(!1)},onDrop:e=>{if(e.preventDefault(),e.stopPropagation(),m(!1),e.dataTransfer.items){const t=[];for(let n=0;n<e.dataTransfer.items.length;n++){const r=e.dataTransfer.items[n];if("file"===r.kind){const e=r.getAsFile();e&&t.push(e)}}if(t.length>0){const e={count:t.length,message:`Preparing to upload ${t.length} file${1===t.length?"":"s"}...`};N(t,e)}}},children:[e("div",{className:Ae("bg-white dark:bg-gray-800 opacity-40 absolute inset-0 z-50 flex justify-center items-center",o?"block":"hidden"),children:e(K,{size:"xl"})}),e(nf,{...i,isGridView:n}),e("div",{className:Ae("absolute inset-0 pointer-events-none",u?"z-40":"-z-10"),children:e("div",{className:"w-full h-full relative",children:e(la,{onDrop:N,message:"Drop files or folders here to upload",className:Ae("absolute inset-0 bg-white/90 dark:bg-gray-800/90 pointer-events-auto",u?"flex":"hidden"),buttonLabel:"Select Files or Folders",allowFolders:!0})})}),e(Qh,{isOpen:g&&c.length>0,onClose:()=>{d([]),f(null),v(!1),k(void 0)},files:c,collectionId:a,selectedFolder:null,title:"Upload Files",onUploadComplete:e=>{if(e){if(e.failedFiles&&e.failedFiles.length>0&&x({title:y("store.uploadIssues"),description:`${e.failedFiles.length} file(s) failed to upload`,status:"warning",duration:5e3}),e.success){const t=e.uploadedFiles.filter(e=>"created"===e.status).length,n=e.uploadedFiles.filter(e=>"updated"===e.status).length,r=e.skippedFiles.length;(t>0||n>0)&&x({title:y("store.uploadComplete"),description:`${t>0?`${t} created`:""}${t>0&&n>0?", ":""}${n>0?`${n} updated`:""}${r>0?`, ${r} skipped`:""}`,status:"success",duration:5e3})}b.search()}d([]),f(null),v(!1),e?.success&&e.objectIds.length>0?k(null):k(void 0)}})]})}function nf({objects:t,layout:n=Xh,isLoading:r,onRowClick:a,onSelectionChange:s,highlightRow:i,previewObject:o,selectedObject:l,isGridView:c}){const d=rh(),u=(e,n)=>{if(d){const r=n.nativeEvent instanceof MouseEvent&&n.nativeEvent.shiftKey;if(n.target.checked){if(d.add(e),r){const n=t.findIndex(t=>t.id===e.id),r=function(e,t,n){for(let r=t-1;r>=0;r--)if(n.isSelected(e[r].id))return r;return-1}(t,n,d);if(r>-1&&r<n-1){const e=[];for(let a=r+1;a<n;a++)e.push(t[a]);d.addAll(e)}else{const e=function(e,t,n){const r=e.length;for(let a=t+1;a<r;a++)if(n.isSelected(e[a].id))return a;return-1}(t,n,d);if(e>-1&&e>n+1){const r=[];for(let a=n+1;a<e;a++)r.push(t[a]);d.addAll(r)}}}}else d.remove(e.id);s?.(d)}},m=e=>{if(d){e.target.checked?d.addAll(t):d.removeAll()}},p=Fe(()=>{const e=n.length>0?n:Xh;return console.log("Using layout with columns:",e.map(e=>e.name).join(", ")),e.map(e=>new $h(e,o))},[n,o]);return e(c?Oh:Fh,{objects:t,isLoading:r,columns:p,onRowClick:a,highlightRow:i,previewObject:o,selectedObject:l,selection:d,toggleAll:m,onSelectionChange:u})}function rf({children:t,limit:n,parent:r,typeId:a,facets:s,name:i,collectionId:o}){const{store:l}=tr(),c=Fe(()=>{let e;s?e=s:(e=[{name:"status",field:"status"},{name:"location",field:"location"}],a||e.unshift({name:"type",field:"type"}));const t=new Uh(l,n).withFacets(e);return t.collectionId=o,t.query.type=a,t.query.parent=r,t.query.name=i,o&&(t.query.all_revisions=!0),t},[o,s,n,i,r,l,a]);return e(Wh.Provider,{value:c,children:t})}const af="vertesia.content_store.lastDisplayedView";function sf({onUpdate:t}){const{t:n}=Ze(),[a,s]=Oe("grid"===localStorage.getItem(af)),i=()=>{localStorage.setItem(af,"grid"),s(!0),t(!0)},o=()=>{localStorage.setItem(af,"table"),s(!1),t(!1)};return e(r,{variant:"outline",onClick:()=>{a?o():i()},title:n(a?"misc.tableView":"misc.thumbnailView"),children:e(a?An:Dn,{})})}sf.LAST_DISPLAYED_VIEW=af;const of=[{name:"Name",field:"properties.title",type:"string",fallback:"name"},{name:"Type",field:"type.name",type:"string"},{name:"Status",field:"status",type:"string"},{name:"Created At",field:"created_at",type:"date"}];function lf({onChange:t,selectedIds:n}){return e(rf,{children:e(cf,{onRowClick:e=>{t(e||void 0)},selectedIds:n})})}function cf({onRowClick:n,selectedIds:a}){const{t:s}=Ze(),i=Ve(e=>!!a?.has(e.id),[a]),[o,l]=Oe(!1),[c,d]=Oe("grid"===localStorage.getItem("vertesia.content_store.lastDisplayedView")),{search:u,isLoading:m,error:p,objects:h,hasMore:f}=qh(),g=Be(null);Z(g,()=>{o&&f&&!m&&(l(!1),u.loadMore(!0).finally(()=>{l(!0)}))},{threshold:.1,deps:[o,f,m]}),He(()=>{u.search().finally(()=>{l(!0)})},[u]);const v=Vh(),b=Bh();return p?e(x,{title:s("store.searchFailed"),children:p.message}):t("div",{className:"flex flex-col gap-2 h-full w-full",children:[t("div",{className:"flex justify-between items-center flex-shrink-0",children:[e(Ip,{facets:v,search:b}),t("div",{className:"flex items-center gap-2",children:[e(r,{variant:"outline",onClick:()=>{l(!1),u.search().then(()=>l(!0))},"aria-label":"Refresh",children:e(Tn,{size:16})}),e(sf,{onUpdate:d})]})]}),t("div",{className:"@container relative flex-1 overflow-y-auto",children:[e(ef,{objects:h||[],isLoading:!h.length&&m,layout:of,onRowClick:n,highlightRow:a?.size?i:void 0,isGridView:c}),e("div",{ref:g,className:"h-4 w-full"})]})]})}function df(e){const t=Math.max(0,e)/1e3,n=t>0&&t<10&&!Number.isInteger(t)?1:0;return`${new Intl.NumberFormat(void 0,{maximumFractionDigits:n}).format(t)}K`}function uf({onSend:n,onStop:a,approvalModeSlot:s,mcpSlot:o,disabled:l=!1,isSending:c=!1,isStopping:d=!1,isStreaming:u=!1,isCompleted:m=!1,contextWindowUsage:p,onCompactContext:f,isCompactingContext:b=!1,activeTaskCount:x=0,activeWorkstreams:y=[],placeholder:w,onFilesSelected:N,uploadedFiles:k=[],onRemoveFile:_,onRemoveProcessingFile:C,acceptedFileTypes:S,maxFiles:T=5,processingFiles:I,artifactRunId:z,hasProcessingFiles:R=!1,renderDocumentSearch:j,selectedDocuments:P=[],onRemoveDocument:A,hideObjectLinking:D=!1,hideFileUpload:E=!1,disableDropZone:$=!1,className:L,inputClassName:M}){const{t:F}=Ze(),O=w??F("agent.typeYourMessage"),U=Be(null),W=Be(null),[B,V]=Oe(""),[q,Y]=Oe(!1),[Q,Z]=Oe(!1),[te,ne]=Oe(!1),re=Boolean(N&&!E),ae=re&&!$,se=!D||re||Boolean(j),ie=k.length>=T,oe=C??_,le=Fe(()=>y.filter(e=>"running"===e.status||"canceling"===e.status),[y]),ce=le.length||x,de=p?F("agent.contextUsageCompactLabel",{percent:p.usedPercent}):void 0,ue=p?F("agent.contextTokenUsage",{used:df(p.usedTokens),limit:df(p.checkpointTokens)}):void 0,me=Fe(()=>{const e=[];if(!E&&I)for(const t of I.values()){const n=t.preview_url,r=t.status===cr.UPLOADING?F("agent.uploading"):t.status===cr.PROCESSING?F("agent.processing"):t.status===cr.ERROR?F("agent.error"):t.status===cr.READY?F("agent.ready"):t.status;e.push({id:t.id,name:t.name,contentType:t.content_type,artifactPath:t.artifact_path,previewUrl:n,removable:Boolean(oe),statusLabel:r,statusTone:t.status===cr.ERROR?"destructive":t.status===cr.READY?"success":"attention"})}if(!E)for(const t of k)e.push({id:t.id,name:t.name,contentType:t.type,artifactPath:t.artifact_path,previewUrl:t.previewUrl,removable:Boolean(_),statusLabel:F("agent.ready"),statusTone:"success"});for(const t of P)e.push({id:t.id,name:t.name,href:`/store/objects/${t.id}`,removable:Boolean(A),statusTone:"info"});return e},[oe,E,A,_,I,P,F,k]);He(()=>{!l&&m&&U.current?.focus()},[l,m]);const pe=Ve(e=>{if(!re||!N)return;const t=Array.from(e),n=T-k.length,r=t.slice(0,n);r.length>0&&N(r)},[re,N,T,k.length]),he=Ve(e=>{e.preventDefault(),e.stopPropagation(),ae&&ne(!0)},[ae]),fe=Ve(e=>{e.preventDefault(),e.stopPropagation(),ne(!1)},[]),ge=Ve(e=>{e.preventDefault(),e.stopPropagation(),ne(!1),ae&&e.dataTransfer?.files&&e.dataTransfer.files.length>0&&pe(e.dataTransfer.files)},[ae,pe]),ve=Ve(e=>{if(!re)return;const t=gm(e.clipboardData?.items);t.length>0&&pe(t)},[re,pe]),be=Ve(e=>{re&&e.target.files&&e.target.files.length>0&&(pe(e.target.files),e.target.value="")},[re,pe]),xe=Ve(()=>{W.current?.click()},[]),ye=Ve(()=>Z(!1),[]),we=Ve(e=>Z(!1),[]),Ne=()=>{const e=B.trim();!e||l||c||R||(n(e),V(""))},ke=()=>{a&&!d&&a()},_e=Be(0),Ce=Ve(()=>{const e=U.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]);He(()=>{Ce()},[B,Ce]);return t("div",{className:i("px-3 py-3 flex-shrink-0 transition-all fixed lg:sticky bottom-0 start-0 end-0 lg:start-auto lg:end-auto w-full bg-background/95 backdrop-blur z-10",te&&ae&&"bg-info/10 border-info",L),onDragOver:ae?he:void 0,onDragLeave:ae?fe:void 0,onDrop:ae?ge:void 0,children:[te&&ae&&e("div",{className:"absolute inset-0 flex items-center justify-center bg-blue-100/80 dark:bg-blue-900/40 rounded-lg z-10 pointer-events-none",children:t("div",{className:"text-blue-600 dark:text-blue-400 font-medium flex items-center gap-2",children:[e(jn,{className:"size-5"}),F("agent.dropFilesToUpload")]})}),re&&e("input",{ref:W,type:"file",multiple:!0,accept:S,onChange:be,className:"hidden"}),e(Rm,{activeWorkstreams:y}),t("div",{className:"mx-auto flex max-w-3xl flex-col gap-2 rounded-2xl border border-border/70 bg-mixer-muted/15 p-2.5 shadow-lg shadow-black/5",children:[me.length>0&&e(ac,{items:me,artifactRunId:z,variant:"composer",onRemove:e=>{I?.has(e)?oe?.(e):k.some(t=>t.id===e)?_?.(e):A?.(e)},className:"gap-1.5"}),e("div",{className:"flex min-w-0 flex-1",children:e(X,{ref:U,value:B,onKeyDown:e=>{if("Enter"===e.key){return e.metaKey||e.ctrlKey||e.altKey||e.shiftKey?void(e.shiftKey||(e.preventDefault(),ee(e.currentTarget,V))):(e.preventDefault(),void(B.trim().length>0&&Ne()))}if("Escape"===e.key&&u&&a){const e=Date.now();e-_e.current<500?(ke(),_e.current=0):_e.current=e}},onChange:e=>V(e.target.value),onPaste:ve,disabled:l,"aria-label":O,placeholder:O,rows:1,style:{maxHeight:"160px"},className:i("min-h-[44px] resize-none border-0 bg-transparent px-0 py-0 text-sm leading-6 shadow-none focus-visible:ring-0",M)})}),t("div",{className:"flex items-center justify-between gap-3",children:[t("div",{className:"flex min-w-0 flex-wrap items-center gap-1.5",children:[se&&t(g,{align:"left",trigger:e(r,{variant:"ghost",size:"icon",className:"size-8 rounded-full text-muted hover:bg-muted",title:F("agent.addAttachment"),children:e($n,{className:"size-4"})}),children:[!D&&t(v,{onClick:()=>Y(!0),isDisabled:!m,children:[e(En,{className:"size-4"}),F("agent.linkObject")]}),re&&t(v,{onClick:xe,isDisabled:ie,children:[e(jn,{className:"size-4"}),F("agent.upload")]}),j&&t(v,{onClick:()=>Z(!0),children:[e(Mt,{className:"size-4"}),e("span",{children:F("agent.searchDocuments")}),P.length>0&&e("span",{className:"ms-auto inline-flex items-center justify-center rounded-full bg-info/20 px-1.5 py-0.5 text-[10px] font-medium text-info",children:P.length})]})]}),s,o,p&&e(h,{asChild:!0,placement:"top",size:"md",className:"text-foreground shadow-lg",description:t("span",{className:"block max-w-56 text-start text-sm leading-6",children:[e("span",{className:"block",children:F("agent.contextRemainingUntilCompact",{percent:p.remainingPercent})}),ue&&e("span",{className:"mt-1 block text-foreground/80",children:ue})]}),children:e(r,{type:"button",variant:"ghost",size:"icon",className:i("size-8 rounded-lg text-info hover:bg-muted hover:text-info disabled:opacity-60","focus-visible:ring-2 focus-visible:ring-info/40"),"aria-label":de,onClick:f,disabled:!f||b,children:b?e(K,{size:"sm"}):t("svg",{viewBox:"0 0 24 24",className:i("size-8 -rotate-90",p.usedPercent>=90?"text-destructive":p.usedPercent>=70?"text-attention":"text-info"),"aria-hidden":"true",children:[e("circle",{cx:"12",cy:"12",r:"9.75",fill:"none",strokeWidth:"4.5",className:"stroke-current text-muted/50"}),e("circle",{cx:"12",cy:"12",r:"9.75",fill:"none",pathLength:100,strokeWidth:"4.5",strokeLinecap:"round",strokeDasharray:100,style:{strokeDashoffset:100-p.usedPercent},className:"stroke-current"})]})})}),0===le.length&&ce>0&&e("output",{className:"flex min-w-0 flex-wrap items-center gap-1.5","aria-live":"polite",children:t("span",{className:"inline-flex h-8 items-center gap-1 rounded-full px-2 text-xs text-muted",children:[e(Ln,{className:"size-3 text-attention"}),F("agent.activeWorkstreams",{count:ce})]})})]}),u&&a&&!B.trim()?e(r,{onClick:ke,disabled:d,variant:"ghost",size:"icon",className:i("size-9 rounded-full border border-border/60 bg-foreground text-background shadow-sm","hover:bg-foreground/90 hover:text-background","disabled:bg-mixer-muted/25 disabled:text-muted disabled:opacity-100","[&_svg]:text-destructive disabled:[&_svg]:text-muted"),title:F("agent.stopTooltip"),children:d?e(K,{size:"sm"}):e(Mn,{className:"size-3 fill-current stroke-current"})}):e(r,{onClick:Ne,disabled:l||c||!B.trim()||R,variant:"ghost",size:"icon",className:i("size-9 rounded-full border border-border/60 bg-foreground text-background shadow-sm","hover:bg-foreground/90 hover:text-background","disabled:bg-mixer-muted/25 disabled:text-muted disabled:opacity-100"),title:F(R?"agent.waitForFiles":"agent.sendTooltip"),"aria-label":F(R?"agent.waitForFiles":"agent.send"),children:c?e(K,{size:"sm"}):e(Fn,{className:"size-4"})})]})]}),t(H,{isOpen:q,onClose:()=>Y(!1),className:"min-w-[60vw]",children:[e(G,{children:F("agent.linkObject")}),e(J,{className:"pb-6",children:e(lf,{onChange:e=>{const t=`[${e.properties?.title||e.name||"Object"}](store:${e.id})`,n=B||"",r=U.current?.selectionStart||n.length,a=n.substring(0,r)+t+n.substring(r);V(a),Y(!1),setTimeout(()=>{if(U.current){U.current.focus();const e=r+t.length;U.current.setSelectionRange(e,e)}},100)}})})]}),j?.({isOpen:Q,onClose:ye,onSelect:we})]})}function mf({code:t}){const{onProposalSelect:n,onProposalSubmit:r}=da(),a=Fe(()=>ua(t),[t]),s=Fe(()=>{if(a)return null;try{const e=t.trim(),a=JSON.parse(e);if(!a.options||!a.question&&!a.title)return null;const s={question:a.question||a.title||"",description:a.description,options:Array.isArray(a.options)?a.options.map(e=>({id:e.id||e.value||"",label:e.label||"",description:e.description})):void 0,allowFreeResponse:a.allowFreeResponse??a.multiple,variant:a.variant,onSelect:n,onSubmit:r};return s.question&&s.options?.length?s:null}catch{return null}},[t,n,r,a]);return a?e(ma,{type:"proposal",message:"Loading options..."}):s?e(pa,{type:"proposal",fallbackCode:t,children:e(Wo,{...s})}):e(ma,{type:"proposal",error:"Invalid proposal specification"})}const pf=qe(function({code:t}){const n=Fe(()=>{try{const e=JSON.parse(t);return"vega-lite"===e?.library&&e?.spec&&"object"==typeof e.spec?e:"string"==typeof e?.$schema&&e.$schema.includes("vega")?{library:"vega-lite",spec:e}:null}catch{return null}},[t]);return n?e(ds,{spec:n}):null}),hf=qe(function({code:t}){const n=Fe(()=>{try{return{library:"vega-lite",spec:JSON.parse(t)}}catch{return null}},[t]);return n?e(ds,{spec:n}):null}),ff={chart:pf,"vega-lite":hf,vegalite:hf,"fusion-fragment":ta,proposal:mf,askuser:mf};function gf({url:t,code:n}){const[r,a]=Oe(null);return He(()=>{import(t).then(e=>{a(()=>e.default)}).catch(e=>{console.error("Failed to load remote widget component from ",t,e)})},[t]),r?e(r,{code:n}):null}function vf({children:t}){const{client:n}=tr(),[r,a]=Oe(ff);return He(()=>{(async function(t){const n=await t.apps.getInstalledApps("tools"),r=new Set;for(const e of n){if(e.manifest.tool_collections&&e.manifest.tool_collections.length>0)for(const t of e.manifest.tool_collections||[]){const e=lr(t).url;if(e.startsWith("http://")||e.startsWith("https://")){const t=e.indexOf("/api/");if(t>0){const n=e.substring(0,t);r.add(`${n}/api/widgets`)}}}e.manifest.endpoint&&e.manifest.capabilities?.includes("tools")&&r.add(new URL("/api/widgets",e.manifest.endpoint).toString())}const a=await Promise.all(Array.from(r).map(t=>fetch(t).then(e=>{if(!e.ok)throw new Error(`Failed to fetch widgets: ${e.status} ${e.statusText}`);return e.json()}).then(t=>{const n=[],r=t.widgets;for(const[t,a]of Object.entries(r))n.push({name:t,component:t=>e(gf,{url:a.url,code:t.code})});return n}).catch(()=>(console.error("Failed to fetch skill widgets from ",t),null)))),s={};for(const e of a.flat())e&&(s[e.name]=e.component);return s})(n).then(e=>{a({...ff,...e})})},[n]),e(ha,{components:r,children:t})}const bf=new Map;function xf(e){if("number"==typeof e)return e;if(!e)return Date.now();const t=new Date(e).getTime();return Number.isFinite(t)?t:Date.now()}function yf(e){return"running"===e||"canceling"===e}function wf(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function Nf(e,t){return yf(e.status)||!yf(t.status)?{...e,...t}:{...e,interaction:e.interaction??t.interaction,elapsed_ms:Math.max(e.elapsed_ms,t.elapsed_ms),deadline_ms:Math.max(e.deadline_ms,t.deadline_ms),remaining_ms:0,phase:e.phase??t.phase,child_workflow_id:e.child_workflow_id??t.child_workflow_id,child_workflow_run_id:e.child_workflow_run_id??t.child_workflow_run_id}}function kf(e){const t=new Map,n=new Map;return e.forEach((e,r)=>{const a=xf(e.timestamp),s=function(e){const t=e.details,n="string"==typeof t?.workstream_id&&t.workstream_id.trim()?t.workstream_id:sl(e);return"main"===n||"all"===n?null:{workstreamId:n,launchId:"string"==typeof t?.launch_id?t.launch_id:void 0,interaction:"string"==typeof t?.interaction?t.interaction:void 0,childWorkflowId:"string"==typeof t?.child_workflow_id?t.child_workflow_id:void 0,childWorkflowRunId:"string"==typeof t?.child_workflow_run_id?t.child_workflow_run_id:void 0}}(e),i=Yo(e),o=i?.workstreamId??s?.workstreamId;if(!o)return;const l=i?.launchId??s?.launchId,c=Jo(e);if(!i&&!l&&c&&!n.has(o))return;const d=function(e,t,n,r,a,s){if(r){const s=t.get(n);if(s?.startsWith("message-derived:")){const t=e.get(s);t&&(e.delete(s),e.set(r,{...t,launch_id:r,updated_at:Math.max(t.updated_at,a)}))}t.set(n,r)}const i=r??t.get(n)??`message-derived:${n}`,o=e.get(i);if(o)return o;const l={workstream_id:n,launch_id:i,elapsed_ms:0,deadline_ms:0,remaining_ms:0,status:"running",started_at:a,updated_at:a,order:s};return e.set(i,l),t.has(n)||t.set(n,i),l}(t,n,o,l,a,r);i?(d.interaction=i.interaction??d.interaction,d.child_workflow_id=i.childWorkflowId??d.child_workflow_id,d.child_workflow_run_id=i.childWorkflowRunId??d.child_workflow_run_id,d.status="running"):(d.interaction=s?.interaction??d.interaction,d.child_workflow_id=s?.childWorkflowId??d.child_workflow_id,d.child_workflow_run_id=s?.childWorkflowRunId??d.child_workflow_run_id);const u=function(e){const t=e.details,n=t?.status;return"running"===n||"canceling"===n||"completed"===n||"canceled"===n||"failed"===n||"timeout"===n?n:"completed"===t?.workstream_event?"completed":void 0}(e);u?d.status=u:c||(!function(e){if(e.type!==ir.ERROR)return!1;const t=e.details;return"activity"===t?.event_class&&!t.workstream_event&&!(t.tool||t.tool_status||t.tool_run_id||t.activity_group_id||t.tool_event)}(e)?e.type!==ir.COMPLETE&&e.type!==ir.IDLE||(d.status="completed"):d.status="failed"),c||(d.updated_at=Math.max(d.updated_at,a),yf(d.status)?d.elapsed_ms=Math.max(d.elapsed_ms,a-d.started_at):(d.elapsed_ms=Math.max(d.elapsed_ms,a-d.started_at),d.remaining_ms=0))}),Array.from(t.values()).sort((e,t)=>{const n=Number(!yf(e.status))-Number(!yf(t.status));return 0!==n?n:yf(e.status)?e.order-t.order:t.updated_at-e.updated_at||e.order-t.order}).map(({started_at:e,updated_at:t,order:n,...r})=>r)}function _f(e){return{workstream_id:e.workstream_id,launch_id:e.launch_id,interaction:e.interaction,elapsed_ms:e.elapsed_ms,deadline_ms:e.deadline_ms,remaining_ms:Math.max(0,e.deadline_ms-e.elapsed_ms),status:e.status,phase:e.latest_progress?.phase,child_workflow_id:e.child_workflow_id,child_workflow_run_id:e.child_workflow_run_id}}function Cf(e){return{workstream_id:e.workstream_id,launch_id:e.launch_id,interaction:e.interaction,elapsed_ms:e.duration_ms??0,deadline_ms:0,remaining_ms:0,status:e.status,phase:e.last_progress?.phase,child_workflow_id:e.child_workflow_id,child_workflow_run_id:e.child_workflow_run_id}}function Sf(e,t){const n=e.findIndex(e=>e.launch_id===t.launch_id);if(n>=0)return void(e[n]=Nf(e[n],t));const r=e.findIndex(e=>e.workstream_id===t.workstream_id&&e.launch_id.startsWith("message-derived:"));r>=0&&!t.launch_id.startsWith("message-derived:")?e[r]=Nf(e[r],t):e.push(t)}function Tf(e){if(e<60)return`${e}s`;const t=Math.floor(e/60),n=e%60;return n>0?`${t}m ${n}s`:`${t}m`}function If({message:n,startedAt:r}){const{t:a}=Ze(),s=function(e,t=!0){const[n,r]=Oe(()=>Math.max(0,Math.floor((Date.now()-xf(e))/1e3)));return He(()=>{if(!t)return;const n=()=>{r(Math.max(0,Math.floor((Date.now()-xf(e))/1e3)))};n();const a=window.setInterval(n,1e3);return()=>window.clearInterval(a)},[t,e]),n}(r),o=function(e=!0){const[t,n]=Oe(0);return He(()=>{if(!e)return;const t=window.setInterval(()=>{n(()=>Math.floor(Math.random()*Kl.length))},4e3);return()=>window.clearInterval(t)},[e]),t}();return t("div",{className:"mx-auto flex min-h-full w-full max-w-3xl flex-col justify-end gap-6 px-1 py-8",children:[e("div",{className:"flex w-full justify-end",children:e("div",{className:i("max-w-[min(44rem,82%)] rounded-[1.35rem] bg-mixer-muted/35 px-4 py-2.5","break-words text-sm font-normal leading-6 text-foreground/90 shadow-sm shadow-black/5","dark:bg-mixer-muted/15 dark:text-foreground/88 dark:shadow-none [overflow-wrap:anywhere]"),children:e("div",{className:"whitespace-pre-wrap",children:n})})}),t("div",{className:"border-b border-border/70 pb-4 text-sm text-muted",children:[t("div",{className:"flex items-center gap-3",children:[e(Vl,{size:"sm",color:"blue"}),t("div",{className:"min-w-0",children:[t("div",{children:[e("span",{className:"font-medium",children:a("agent.preparing")}),t("span",{className:"ms-2 text-muted/75",children:["for ",Tf(s)]})]}),e("div",{className:"mt-1 truncate text-muted/80",children:Kl[o]})]})]}),e("div",{className:"mt-3 ps-6",children:e(Bl,{color:"blue"})})]})]})}function zf(e){return function(e){let t=0,n=e.length;for(;t<n&&"-"===e[t];)t++;for(;n>t&&"-"===e[n-1];)n--;return e.slice(t,n)}(e.trim().replace(/[^a-z0-9-_]+/gi,"-")).slice(0,80)}function Rf(t){const{agentRunId:n,startWorkflow:r}=t;return n?e(vf,{children:e(Af,{...t,agentRunId:n})}):r?e(Pf,{...t}):e(jf,{})}function jf(){const{t:n}=Ze();return t(Y,{status:"info",icon:e(Bt,{className:"size-16 text-muted mb-4"}),children:[e("div",{className:"text-base font-medium text-muted",children:n("agent.noAgentRunning")}),e("div",{className:"mt-3 text-sm text-muted",children:n("agent.selectInteraction")})]})}function Pf({initialMessage:n,interactive:a=!0,startWorkflow:s,onClose:o,isModal:l=!1,fullWidth:c=!1,placeholder:d,startButtonText:u,title:m,getAttachedDocs:h,onAttachmentsSent:f,acceptedFileTypes:g,maxFiles:v=5,hideHeader:b=!1,hideFileUpload:x=!1,hideObjectLinking:y,headerVariant:w,inputContainerClassName:N,inputClassName:k,className:_,allowWorkflowControl:C,initialToolApprovalMode:S}){const{t:T}=Ze(),I=!x,z=d??T("agent.typeYourMessage"),R=u??T("agent.startAgent"),j=m??T("agent.startNewConversation"),{client:P}=tr(),[A,D]=Oe(""),[E,$]=Oe(!1),[L,M]=Oe(null),[F,O]=Oe(null),[U,W]=Oe(null),[B,V]=Oe(()=>vr(S,a)),q=p(),H=Be(null),G=Be(null),[J,Y]=Oe([]),[Q,Z]=Oe(!1),te=Be(0),ne=Ve(e=>{I&&(e.preventDefault(),e.stopPropagation(),te.current++,e.dataTransfer?.types?.includes("Files")&&Z(!0))},[I]),re=Ve(e=>{I&&(e.preventDefault(),e.stopPropagation())},[I]),ae=Ve(e=>{I&&(e.preventDefault(),e.stopPropagation(),te.current--,0===te.current&&Z(!1))},[I]),se=Ve(e=>{if(I&&(e.preventDefault(),e.stopPropagation(),te.current=0,Z(!1),e.dataTransfer?.files&&e.dataTransfer.files.length>0)){const t=Array.from(e.dataTransfer.files);Y(e=>[...e,...t].slice(0,v))}},[v,I]),ie=Ve(e=>{if(!I)return;const t=gm(e.clipboardData?.items);t.length>0&&Y(e=>[...e,...t].slice(0,v))},[I,v]),oe=Ve(e=>{if(e.target.files&&e.target.files.length>0){const t=Array.from(e.target.files);Y(e=>[...e,...t].slice(0,v))}e.target.value=""},[v]),le=Ve(e=>{Y(t=>t.filter((t,n)=>n!==e))},[]);He(()=>{H.current&&H.current.focus()},[]);const ce=async()=>{if(!s)return;const e=A.trim();if(e&&!E){$(!0);try{sessionStorage.removeItem("plan-panel-shown"),q({title:I&&J.length>0?T("agent.startingAgentUploading"):T("agent.startingAgent"),status:"info",duration:3e3});const t=h?.()||[];let n=e;if(t.length>0&&!/store:\S+/.test(e)){n=[e,"","Attachments:",...t.map(e=>`[${e.name}](/store/objects/${e.id})`)].join("\n")}if(I&&J.length>0){const e=J.map(e=>e.name).join(", ");n=[n,"",`[System: ${J.length} file(s) are being uploaded: ${e}. Please wait for the "Files Ready" notification before processing them.]`].join("\n")}O(n),W(Date.now());const r=await s(n,{tool_approval_mode:B});if(r){const e=r.agent_run_id,t=[];if(I&&J.length>0){for(const n of J)try{const r=`files/${n.name}`;await P.agents.uploadArtifact(e,r,n),await P.agents.sendSignal(e,"FileUploaded",{id:`file-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,name:n.name,content_type:n.type||"application/octet-stream",reference:`artifact:${r}`,artifact_path:r}),t.push(n.name)}catch(e){console.error(`Failed to upload staged file ${n.name}:`,e)}if(t.length>0)try{await P.agents.sendSignal(e,"UserInput",{message:`[Files Ready] All ${t.length} file(s) have been uploaded and are now available: ${t.join(", ")}. You can now process them.`,metadata:{type:"files_ready",files:t}})}catch(e){console.error("Failed to send files ready signal:",e)}Y([])}f?.(),M(e),D(""),q({title:T("agent.agentStarted"),status:"success",duration:3e3})}}catch(e){O(null),W(null),q({title:T("agent.errorStarting"),status:"error",duration:3e3,description:e instanceof Error?e.message:T("agent.unknownError")})}finally{$(!1)}}},de=Ve(()=>{const e=H.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]);return He(()=>{de()},[A,de]),L?e(Af,{onClose:o,isModal:l,initialMessage:n,placeholder:d,fullWidth:c,hideHeader:b,headerVariant:w,hideFileUpload:x,hideObjectLinking:y,inputContainerClassName:N,inputClassName:k,className:_,allowWorkflowControl:C,agentRunId:L,title:m,pendingStartMessage:F??void 0,pendingStartTimestamp:U??void 0,initialToolApprovalMode:B}):e("div",{className:i("flex h-full flex-col items-center bg-background",_),children:t("div",{className:i("relative flex h-full w-full flex-col overflow-hidden border-0",c?"":"max-w-4xl"),onDragEnter:I?ne:void 0,onDragOver:I?re:void 0,onDragLeave:I?ae:void 0,onDrop:I?se:void 0,children:[I&&Q&&e("div",{className:"absolute inset-0 flex items-center justify-center bg-info-background z-50 pointer-events-none rounded-lg",children:t("div",{className:"text-info font-medium flex items-center gap-2 text-lg",children:[e(jn,{className:"size-6"}),"Drop files to stage for upload"]})}),I&&e("input",{ref:G,type:"file",multiple:!0,accept:g,onChange:oe,className:"hidden"}),!b&&t("div",{className:"flex items-center justify-between border-b border-border/60 bg-background px-3 py-2",children:[t("div",{className:"flex items-center gap-2",children:[e("div",{className:"p-1",children:e(On,{className:"size-3.5 text-muted"})}),e("span",{className:"text-sm font-medium text-foreground",children:j})]}),o&&!l&&e(r,{size:"xs",variant:"ghost",onClick:o,title:T("agent.close"),className:"text-muted hover:text-foreground",children:e(Et,{className:"size-4"})})]}),e("div",{className:"flex flex-1 flex-col items-center justify-end overflow-y-auto bg-background px-4",children:F&&U?e(If,{message:F,startedAt:U}):e("div",{className:"mx-auto flex min-h-full w-full max-w-3xl flex-col justify-end py-8",children:n&&e("div",{className:"text-[15px] leading-relaxed text-foreground/80",children:n})})}),e("div",{className:"shrink-0 bg-background px-4 pb-safe-area-4 pt-2",children:t("div",{className:i("mx-auto flex max-w-3xl flex-col gap-3 rounded-2xl border border-border/70 bg-mixer-muted/15 p-3 shadow-lg shadow-black/5",N),children:[I&&J.length>0&&e("div",{className:"flex flex-wrap gap-2",children:J.map((n,a)=>t("div",{className:"flex items-center gap-1.5 rounded-md bg-attention/10 px-2 py-1 text-sm text-attention",title:T("agent.fileStagedTooltip"),children:[e(Mt,{className:"size-3.5"}),e("span",{className:"max-w-[120px] truncate",children:n.name}),e("span",{className:"text-xs opacity-70",children:T("agent.staged")}),e(r,{variant:"unstyled","aria-label":`Remove staged file ${n.name}`,onClick:()=>le(a),className:"ms-1 rounded p-0.5 hover:bg-attention/20",children:e(Et,{className:"size-3"})})]},`${n.name}-${n.size}-${n.lastModified}`))}),e(X,{ref:H,value:A,onChange:e=>D(e.target.value),onKeyDown:e=>{if("Enter"!==e.key)return;if(!(e.metaKey||e.ctrlKey||e.altKey||e.shiftKey))return e.preventDefault(),void ce();e.shiftKey||(e.preventDefault(),ee(e.currentTarget,D))},onPaste:ie,placeholder:z,disabled:E,rows:2,className:i("min-h-[72px] resize-none overflow-hidden border-0 bg-transparent px-0 py-0 text-sm leading-6 shadow-none focus-visible:ring-0",k),style:{minHeight:"72px",maxHeight:"200px"}}),t("div",{className:"flex items-center justify-between gap-3",children:[t("div",{className:"flex min-w-0 items-center gap-2",children:[I&&e(r,{variant:"ghost",size:"icon",onClick:()=>G.current?.click(),disabled:E||J.length>=v,"aria-label":T("agent.upload"),className:"rounded-full text-muted",title:T("agent.upload"),children:e(jn,{className:"size-4"})}),a&&e(Ja,{mode:B,onChange:V,disabled:E})]}),e(r,{onClick:ce,disabled:!A.trim()||E,variant:"ghost",size:"icon",className:i("size-9 rounded-full border border-border/60 bg-foreground text-background shadow-sm","hover:bg-foreground/90 hover:text-background","disabled:bg-mixer-muted/25 disabled:text-muted disabled:opacity-100"),title:R,children:E?e(K,{size:"sm"}):e(Fn,{className:"size-4"})})]})]})})]})})}function Af({agentRunId:a,title:s,interactive:o=!0,onClose:l,isModal:c=!1,fullWidth:d=!1,placeholder:u,resetWorkflow:m,onRestart:h,onClone:f,onShowDetails:g,allowWorkflowControl:v=!0,uploadedFiles:b,onRemoveFile:x,acceptedFileTypes:y,maxFiles:w,renderDocumentSearch:N,selectedDocuments:k,onRemoveDocument:_,hideObjectLinking:C,hideHeader:S,headerVariant:T="full",hideMessageInput:I,failedAction:z,hidePlanPanel:R,hideWorkstreamTabs:j,showRightPanel:P=!0,hideFileUpload:A,showArtifacts:D=!1,hideDocumentPanel:E,hiddenMessageTypes:$,getAttachedDocs:L,onAttachmentsSent:M,isUploading:F=!1,getMessageContext:O,className:U,inputContainerClassName:W,inputClassName:B,fusionData:V,fileUploadRef:q,onProcessingFilesChange:K,processingFiles:Z,onPlansChange:X,onWorkstreamStatusChange:ee,viewMode:te,onViewModeChange:ne,onShowInputChange:re,stopRef:ae,onStoppingChange:se,messageItemClassNames:ie,messageStyleOverrides:oe,toolCallGroupClassNames:le,hideToolCallsInViewMode:ce,streamingMessageClassNames:de,batchProgressPanelClassNames:ue,workingIndicatorClassName:me,messageListClassName:pe,StoreLinkComponent:he,CollectionLinkComponent:fe,prependFriendlyMessage:ge,initialRequestData:ve,initialRequestSchema:be,initialRequestTitle:xe,initialRequestTemplate:ye,payloadContent:we,conversationContent:Ne,conversationTab:ke=!1,pendingStartMessage:_e,pendingStartTimestamp:Ce,initialToolApprovalMode:Se,enablePlayback:Te,showPlaybackToggle:Ie=!0}){const{t:ze}=Ze(),{client:Re}=tr(),je=p(),{messages:Pe,streamingMessages:Ae,isCompleted:De,initialHistoryStatus:Ee,debugChunkFlash:$e,addOptimisticMessage:Le,updateOptimisticMessageStatus:Me,reconnect:Ue,agentRunStatus:We,workflowRunId:qe,serverFileUpdates:Ge}=_m(Re,a),{plans:Je,activePlanIndex:Ke,setActivePlanIndex:Ye,workstreamStatusMap:Qe,showInput:tt,showSlidingPanel:nt,setShowSlidingPanel:rt}=function(e,t,n=!1){const[r,a]=Oe([]),[s,i]=Oe(0),[o,l]=Oe(new Map),[c,d]=Oe(t),[u,m]=Oe(!n),p=Be(-1),h=Be(new Set);He(()=>{0===e.length&&(a([]),i(0),l(new Map),m(!n),p.current=-1,h.current.clear())},[e.length,n]);const f=Ve(e=>{const n=e[e.length-1];n&&(n.type===ir.TERMINATED?d(!1):d(!!t||n.type===ir.REQUEST_INPUT))},[t]);return He(()=>{if(0===e.length)return;const t=p.current+1;if(t>=e.length)return void f(e);let n=!1;const r=[],s=[];for(let a=t;a<e.length;a++){const t=e[a];if(t.type===ir.PLAN)try{let e=null;if(t.details&&"object"==typeof t.details&&t.details.plan&&Array.isArray(t.details.plan)&&(e={plan:t.details.plan}),e){const a="number"==typeof t.timestamp?t.timestamp:new Date(t.timestamp).getTime();if(!h.current.has(a)){h.current.add(a),n=!0,r.push({plan:e,timestamp:a});const t=new Map;t.set("main","in_progress"),Array.isArray(e.plan)&&e.plan.forEach(e=>{if(e&&"object"==typeof e&&e.id){const n=e.id.toString();t.set(n,e.status||"pending")}}),s.push({timestamp:a,statusMap:t})}}}catch(e){console.error("Failed to parse plan from message:",e)}}p.current=e.length-1,n&&r.length>0&&(a(e=>[...[...r].reverse(),...e]),i(0),m(!0),s.length>0&&l(e=>{const t=new Map(e);for(const e of s)t.set(e.timestamp,e.statusMap);return t})),f(e)},[e,f]),He(()=>{if(1===r.length&&!u&&!sessionStorage.getItem("plan-panel-shown")){const e=setTimeout(()=>{m(!0),sessionStorage.setItem("plan-panel-shown","true")},500);return()=>clearTimeout(e)}},[r.length,u]),{plans:r,activePlanIndex:s,setActivePlanIndex:i,workstreamStatusMap:o,showInput:c,showSlidingPanel:u,setShowSlidingPanel:m}}(Pe,o,c),{openDocuments:at,activeDocumentId:st,isDocPanelOpen:it,docRefreshKey:ot,closeDocPanel:lt,closeDocument:ct,selectDocument:dt,openDocInPanel:ut,updateDocumentTitle:mt}=function(e){const[t,n]=Oe([]),[r,a]=Oe(null),[s,i]=Oe(!1),[o,l]=Oe(0),c=Be(-1);return He(()=>{0===e.length&&(n([]),a(null),i(!1),l(0),c.current=-1)},[e.length]),He(()=>{const t=c.current+1;if(!(t>=e.length)){for(let r=t;r<e.length;r++){const t=e[r];if(t.type===ir.UPDATE&&t.details){const e=t.details;if("document_created"===e.event_class||"document_updated"===e.event_class){const t=Cm(e.document_id),r=Cm(e.updated_document_id)||t,s=e.title;if(r){const o={id:r,title:s||"Document",revisionRootId:Sm(e,t||r)};n(e=>{const t=e.findIndex(e=>Tm(e,o));if(t<0)return[...e,o];const n=e[t];if(n.id===o.id&&n.title===o.title&&n.revisionRootId===o.revisionRootId)return e;const r=[...e];return r[t]=o,r}),a(o.id),i(!0),"document_updated"===e.event_class&&l(e=>e+1)}}}}c.current=e.length-1}},[e]),{openDocuments:t,activeDocumentId:r,isDocPanelOpen:s,docRefreshKey:o,closeDocPanel:Ve(()=>{i(!1)},[]),closeDocument:Ve(e=>{n(t=>{const n=t.filter(t=>t.id!==e);return 0===n.length?(i(!1),a(null)):a(t=>t===e?n[0].id:t),n})},[]),selectDocument:Ve(e=>{a(e)},[]),openDocInPanel:Ve(e=>{n(t=>t.some(t=>t.id===e)?t:[...t,{id:e,title:"Document",revisionRootId:e}]),a(e),i(!0)},[]),updateDocumentTitle:Ve((e,t)=>{n(n=>n.map(n=>n.id===e?{...n,title:t}:n))},[])}}(Pe),{processingFiles:pt,hasProcessingFiles:ht,handleFileUpload:ft,removeProcessingFile:gt,clearProcessingFiles:vt}=function(e,t,n,r){const a=Xe.getFixedT(null,et),[s,i]=Oe(new Map),[o,l]=Oe(new Set),c=Be(new Set),d=Be(new Map),u=Be(t),m=Be(s);m.current=s;const p=Be(n);p.current=n;const h=Ve(e=>{const t=d.current.get(e);t&&(zm(t),d.current.delete(e))},[]);He(()=>{if(u.current!==t){u.current=t,d.current.forEach(zm),d.current.clear(),i(new Map);const e=new Set;c.current=e,l(e)}},[t]),He(()=>()=>{d.current.forEach(zm),d.current.clear()},[]);const f=Fe(()=>{const e=new Map;return s.forEach((t,n)=>{o.has(n)||e.set(n,t)}),n.forEach((t,n)=>{if(!o.has(n)){const r=s.get(n);e.set(n,{...t,artifact_path:t.artifact_path??r?.artifact_path,reference:t.reference??r?.reference,...r?.preview_url?{preview_url:r.preview_url}:{}})}}),e},[s,o,n]),g=Fe(()=>Array.from(f.values()).some(e=>e.status===cr.UPLOADING||e.status===cr.PROCESSING),[f]),v=Ve(async n=>{for(const s of n){const n=`file-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,o=`files/${s.name}`,l=Im(s);l&&d.current.set(n,l);const u={id:n,name:s.name,content_type:s.type||"application/octet-stream",size:s.size,status:cr.UPLOADING,started_at:Date.now(),preview_url:l};i(e=>new Map(e).set(n,u));try{if(await e.agents.uploadArtifact(t,o,s),i(e=>{const t=new Map(e),r=t.get(n);return r&&(r.status=cr.PROCESSING,r.artifact_path=o,r.reference=`artifact:${o}`),t}),c.current.has(n))continue;await e.agents.sendSignal(t,"FileUploaded",{id:n,name:s.name,content_type:s.type||"application/octet-stream",reference:`artifact:${o}`,artifact_path:o})}catch(e){if(c.current.has(n))continue;i(t=>{const r=new Map(t),a=r.get(n);return a&&(a.status=cr.ERROR,a.error=e instanceof Error?e.message:"Upload failed",a.completed_at=Date.now()),r}),r({status:"error",title:a("agent.uploadFailed"),description:e instanceof Error?e.message:"Failed to upload file",duration:3e3})}}},[e,t,r,a]),b=Ve(async n=>{l(e=>{if(e.has(n))return e;const t=new Set(e);return t.add(n),c.current=t,t}),i(e=>{if(!e.has(n))return e;const t=new Map(e);return t.delete(n),t}),h(n);try{await e.agents.sendSignal(t,"FileRemoved",{id:n})}catch(e){r({status:"error",title:a("agent.removeFileFailed"),description:e instanceof Error?e.message:"Failed to remove file",duration:3e3})}},[t,e,h,a,r]),x=Ve(()=>{d.current.forEach(zm),d.current.clear(),l(e=>{const t=new Set(e);for(const e of p.current.keys())t.add(e);for(const e of m.current.keys())t.add(e);return c.current=t,t}),i(new Map)},[]);return{processingFiles:f,hasProcessingFiles:g,handleFileUpload:v,removeProcessingFile:b,clearProcessingFiles:x}}(Re,a,Ge,je),bt=o&&!A,xt=Ve(e=>{gt(e)},[gt]),yt=Be(null),wt=Be(null),Nt=Be(null),[kt,_t]=Oe(!1),[Ct,St]=Oe(!1),[Tt,It]=Oe("sliding"),zt=te??Tt,jt=Ve(e=>{ne?ne(e):It(e)},[ne]),[Pt,At]=Oe(!1),[Dt,Et]=Oe(!1),[$t,Lt]=Oe("all"),[Mt,Ft]=Oe("live"),[Ot,Ut]=Oe(!1),[Wt,Bt]=Oe(0),[Vt,qt]=Oe([]),[Ht,Gt]=Oe([]),[Jt,Kt]=Oe(!1),Yt=Fe(()=>void 0===Se&&o?void 0:vr(Se,o),[Se,o]),[Qt,Zt]=Oe(Yt),Xt=Be(!1),en=Be(0),tn=Be(!1),nn=Be(0),rn=Be(null);He(()=>{Zt(Yt)},[Yt]);const an=Be(kt);an.current=kt;const sn=Be(ht);sn.current=ht;const on=Be(pt);on.current=pt;const ln=Fe(()=>{const e=Pe.filter(e=>"main"===(e.workstream_id||"main"));return e[e.length-1]},[Pe]),cn=Fe(()=>ln?.type===ir.TERMINATED?"TERMINATED":ln?.type!==ir.COMPLETE||We&&"RUNNING"!==We?We:"COMPLETED",[ln,We]),dn=Fe(()=>{const e=cn?.toUpperCase();return"COMPLETED"===e||"FAILED"===e||"CANCELED"===e||"CANCELLED"===e||"TERMINATED"===e||"TIMED_OUT"===e},[cn]),un=Fe(()=>dn&&"FAILED"!==cn?.toUpperCase()&&!!h,[dn,cn,h]),mn=!I||un,pn=Fe(()=>"FAILED"===cn?.toUpperCase()||"FAILED"===We?.toUpperCase(),[cn,We]),hn=Be(dn);hn.current=dn;const fn=Be(un);fn.current=un;const gn=Fe(()=>{const e=Je[Ke]||{plan:{plan:[]},timestamp:0},t=Qe.get(e.timestamp)||new Map;return{plan:e.plan,workstreamStatus:t}},[Je,Ke,Qe]),vn=Fe(()=>kf(Pe),[Pe]),bn=Fe(()=>{const e=[...vn];for(const t of Ht)Sf(e,Cf(t));for(const t of Vt)Sf(e,_f(t));return e.map((e,t)=>({workstream:e,index:t})).sort((e,t)=>Number(!yf(e.workstream.status))-Number(!yf(t.workstream.status))||e.index-t.index).map(({workstream:e})=>e)},[vn,Vt,Ht]),xn=Fe(()=>bn.filter(e=>yf(e.status)),[bn]),yn=Fe(()=>xn.filter(e=>"running"===e.status).length,[xn]),wn=Fe(()=>{if("all"===$t)return;const e=bn.find(e=>e.workstream_id===$t||e.launch_id===$t);return e?qo(e.workstream_id,e.interaction):qo($t)},[$t,bn]),Nn=Fe(()=>u||(wn?ze("agent.messageMainAgentWhileViewingWorkstream",{workstream:wn}):void 0),[wn,u,ze]),kn=Ie&&void 0===Te&&xs(),_n=Te??(ys()||Ot),Cn=Fe(()=>ol($?.length?Pe.filter(e=>!$.includes(e.type)):Pe,$t),[$t,$,Pe]),Sn=Fe(()=>bs(Cn,Mt,_n),[_n,Mt,Cn]),Tn=Sn.cursor,In=Sn.isLive,zn=_n&&!In&&Sn.cursorIndex===Cn.length-1,Rn=Sn.displayedMessages,Pn=In?Ae:bf,An=Fe(()=>kf(Rn),[Rn]),Dn=Fe(()=>An.filter(e=>yf(e.status)),[An]),En=Fe(()=>De||!nl(Pe),[De,Pe]),$n=!(!In&&!zn)&&En,Ln=Fe(()=>Ol(Rn),[Rn]),Mn=Boolean(Ln)&&!pn,Fn=_n&&!In,On=mn&&!Fn,Un=Fe(()=>function(e){for(let t=e.length-1;t>=0;t--){const n=e[t].details;if(!n)continue;const r=n.token_usage,a=wf(r?.total),s=wf(n.checkpoint_threshold)??wf(n.checkpoint_at);if("number"!=typeof a||"number"!=typeof s||s<=0)continue;const i=Math.max(0,Math.min(100,Math.round(a/s*100)));return{usedTokens:a,checkpointTokens:s,usedPercent:i,remainingPercent:Math.max(0,100-i)}}}(Pe),[Pe]),Wn=v&&!dn&&In&&Boolean(Un);He(()=>{Xo("conversation render state",{agentRunId:a,messageCount:Pe.length,playbackMessageCount:Cn.length,displayedMessageCount:Rn.length,streamingCount:Ae.size,displayedStreamingCount:Pn.size,initialHistoryStatus:Ee,isCompleted:De,effectiveIsCompleted:En,displayedIsCompleted:$n,agentRunStatus:We,effectiveWorkflowStatus:cn,isWorkflowTerminal:dn,playbackCursor:Tn,isPlaybackEnabled:_n,isPlaybackLive:In,isPlaybackAtLatest:zn,activeWorkstream:$t,showInitialRequest:"empty"===Ee&&0===Pe.length,pendingStartVisible:0===Pe.length&&!En&&Boolean(_e)})},[$t,a,We,Tn,$n,Rn.length,Pn.size,En,cn,Ee,De,zn,_n,In,dn,Pe.length,_e,Cn.length,Ae.size]);const Bn=Ve(()=>{Ut(e=>!e)},[]),Vn=Ve(e=>{const t=fs(Tn,Cn.length),n=fs(e,Cn.length);_n&&(n>t||"live"===e&&"live"!==Tn)&&(tn.current=!0,Bt(e=>e+1)),Ft(e)},[Tn,_n,Cn.length]);He(()=>{_n?Tn!==Mt&&Ft(Tn):"live"!==Mt&&Ft("live")},[Tn,_n,Mt]),He(()=>{if(!_n||!tn.current)return;tn.current=!1;const e=window.requestAnimationFrame(()=>{yt.current?.scrollIntoView({behavior:"smooth",block:"end"})});return()=>window.cancelAnimationFrame(e)},[_n,Wt]);const qn=Ve(()=>{rt(e=>(e||sessionStorage.setItem("plan-panel-shown","true"),!e))},[rt]),Hn=Ve(e=>{Ye(e)},[Ye]),[Gn,Jn]=Oe(Ne||ke?"conversation":"plan"),[Kn,Yn]=Oe(400),[Qn,Zn]=Oe(!1),Xn=P&&(nt||it||!j&&bn.length>0||!!Ne||ke);He(()=>{!Xn&&Qn&&Zn(!1)},[Xn,Qn]),He(()=>{if(!Qn)return;const e=e=>{const t=Nt.current;if(!t)return;const n=t.getBoundingClientRect(),r=Math.max(300,n.width-420),a=n.right-e.clientX,s=Math.min(Math.max(a,300),r);Yn(s)},t=()=>{Zn(!1)};return window.addEventListener("mousemove",e),window.addEventListener("mouseup",t),document.body.style.cursor="col-resize",document.body.style.userSelect="none",()=>{window.removeEventListener("mousemove",e),window.removeEventListener("mouseup",t),document.body.style.cursor="",document.body.style.userSelect=""}},[Qn]);const er=Ve(()=>{rt(!1),lt()},[rt,lt]),nr=Ve(({href:t,documentId:n,children:r})=>e("a",{href:t,className:"text-info underline cursor-pointer hover:text-info/80",onClick:e=>{e.preventDefault(),e.stopPropagation(),ut(n),Jn("documents")},children:r}),[ut]),rr=he??nr;He(()=>(q&&(q.current=bt?ft:null),()=>{q&&(q.current=null)}),[q,ft,bt]),He(()=>{K?.(pt)},[pt,K]),He(()=>{X?.(Je,Ke)},[Je,Ke,X]),He(()=>{ee?.(Qe)},[Qe,ee]),He(()=>{Xt.current=!1,Kt(!1),qt([]),Gt([])},[a]),He(()=>{const e="loading"!==Ee&&!En&&!dn&&!Jt;if(Xo("active workstreams poll state",{agentRunId:a,shouldPoll:e,initialHistoryStatus:Ee,effectiveIsCompleted:En,isWorkflowTerminal:dn,isWorkstreamQueryUnavailable:Jt}),!e)return void qt(e=>0===e.length?e:[]);let t=!1,n=!1;const r=async()=>{if(n)Xo("active workstreams fetch skipped while previous request is pending",{agentRunId:a});else{n=!0;try{Xo("active workstreams fetch start",{agentRunId:a});const e=await Re.agents.getActiveWorkstreams(a);if(t)return;if(Xo("active workstreams fetch success",{agentRunId:a,runningCount:e.running?.length??0,completedCount:e.completed?.length??0,unavailable:!0===e.unavailable}),qt(e.running??[]),Gt(e.completed??[]),e.unavailable)return void Kt(!0);Xt.current=!1}catch(e){if(t)return;qt(e=>0===e.length?e:[]),Kt(!0),Xo("active workstreams fetch failed",{agentRunId:a,error:e instanceof Error?e.message:String(e)}),Xt.current||(console.warn("Failed to fetch active workstreams:",e),Xt.current=!0)}finally{n=!1}}};r();const s=window.setInterval(r,1e4);return()=>{t=!0,window.clearInterval(s)}},[Re.agents,a,En,Ee,dn,Jt]),He(()=>{0!==Pe.length&&(un?re?.(!0):tt?cn&&"RUNNING"!==cn?re?.(!1):null!==cn&&re?.(!0):re?.(!1))},[tt,cn,Pe.length,re,un]);const ar=Ve(async()=>{const e=rn.current;e&&await e},[]),sr=Ve((e,t)=>{const n=e.trim();if(!n||an.current)return;if(hn.current&&!fn.current)return;if(sn.current)return void je({status:"warning",title:ze("agent.filesProcessing"),description:ze("agent.waitForFilesProcessing"),duration:3e3});_t(!0);const r=L?.()||[],s=O?.()||{};let i=n;if(r.length>0&&!/store:\S+/.test(n)){const e=r.map(e=>`[${e.name}](/store/objects/${e.id})`);i=[n,"","Attachments:",...e].join("\n")}const o=Array.from(on.current.values()).filter(e=>e.status===cr.READY).map(e=>{const t=e.reference?.startsWith("artifact:")?e.reference:e.artifact_path?`artifact:${e.artifact_path}`:void 0;return t?`[${e.name}](${t})`:void 0}).filter(e=>Boolean(e));o.length>0&&(i=[i,"","Uploaded artifacts:",...o].join("\n"));const l=`msg-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,c={timestamp:Date.now(),workflow_run_id:a,type:ir.QUESTION,message:i,workstream_id:"main",details:{_optimistic:!0,_messageId:l,_deliveryStatus:"sending"}};Le(c);const d={...r.length>0?{attached_docs:r.map(e=>e.id)}:{},...s,...t,id:l,_messageId:l};(async()=>{await ar(),hn.current&&(await Re.agents.restart(a),Ue()),await Re.agents.sendSignal(a,"UserInput",{message:i,client_message_id:l,metadata:d}),Me(l,"received"),M?.(),vt()})().catch(e=>{Me(l,"failed"),je({status:"error",title:ze("agent.failedToSend"),description:e instanceof Error?e.message:ze("agent.unknownError"),duration:3e3})}).finally(()=>{_t(!1)})},[a,Re,je,L,O,M,vt,Ue,Le,Me,ze,ar]),or=Ve(async e=>{try{await Re.agents.sendSignal(a,"McpConfigChanged",{})}catch(e){console.error("Failed to signal MCP config change",e)}sr(ze("agent.mcpConnectedMessage",{name:e.name}))},[Re,a,sr,ze]),[lr,dr]=Oe(void 0);He(()=>{let e=!1;const t=nn.current;return Re.agents.retrieve(a).then(n=>{e||(dr(n.disabled_mcp_collections),nn.current!==t||void 0===n.tool_approval_mode&&void 0===n.interactive||Zt(vr(n.tool_approval_mode,n.interactive)))}).catch(()=>{}),()=>{e=!0}},[Re,a]);const ur=Ve(e=>{const t=e.length>0?e:void 0;dr(t),Re.agents.sendSignal(a,"McpConfigChanged",{disabled_mcp_collections:e}).catch(e=>console.error("Failed to signal MCP config change",e))},[Re,a]),mr=Ve(()=>{Re.agents.sendSignal(a,"McpConfigChanged",{}).catch(e=>console.error("Failed to signal MCP config change",e))},[Re,a]),pr=Ve(e=>{const t=vr(e,o),n=Qt;nn.current+=1,Zt(t);const r=Re.agents.sendSignal(a,"ToolApprovalModeChanged",{mode:t}).then(()=>{}).catch(e=>{Zt(e=>e===t?n:e),je({status:"error",title:ze("agent.approvalMode.changeFailed"),description:e instanceof Error?e.message:ze("agent.unknownError"),duration:3e3})});rn.current=r,r.finally(()=>{rn.current===r&&(rn.current=null)})},[a,Re,o,ze,je,Qt]),hr=Ve(e=>{bt&&(e.preventDefault(),e.stopPropagation(),en.current++,e.dataTransfer?.types?.includes("Files")&&Et(!0))},[bt]),fr=Ve(e=>{bt&&(e.preventDefault(),e.stopPropagation())},[bt]),gr=Ve(e=>{bt&&(e.preventDefault(),e.stopPropagation(),en.current--,0===en.current&&Et(!1))},[bt]),br=Ve(e=>{if(bt&&(e.preventDefault(),e.stopPropagation(),en.current=0,Et(!1),e.dataTransfer?.files&&e.dataTransfer.files.length>0)){const t=Array.from(e.dataTransfer.files);ft(t)}},[ft,bt]),xr=Ve(async()=>{if(Pt)return;const e=`stop-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,t={timestamp:Date.now(),workflow_run_id:a,type:ir.IDLE,message:"Stopped. Waiting for your command...",workstream_id:"main",details:{_optimistic:!0,_messageId:e,_deliveryStatus:"sending",display_role:"user_stopped",status_reason:"user_stopped"}};Le(t),At(!0);try{await Re.agents.sendSignal(a,"Stop",{message:"User requested stop",client_message_id:e,metadata:{id:e,_messageId:e}}),Me(e,"received")}catch(t){je({status:"error",title:ze("agent.failedToInterrupt"),description:t instanceof Error?t.message:ze("agent.unknownError"),duration:3e3}),Me(e,"failed")}finally{At(!1)}},[Pt,a,Le,Re.agents,je,ze,Me]),yr=Ve(async()=>{if(!Ct&&!En&&In){St(!0);try{await Re.agents.sendSignal(a,"TriggerCheckpoint",{reason:"manual user request"})}catch(e){je({status:"error",title:ze("agent.failedToCompactContext"),description:e instanceof Error?e.message:ze("agent.unknownError"),duration:3e3})}finally{St(!1)}}},[a,Re.agents,En,Ct,In,ze,je]);He(()=>(ae&&(ae.current=v&&!En?xr:null),()=>{ae&&(ae.current=null)}),[ae,En,xr,v]),He(()=>{se?.(Pt)},[Pt,se]);const wr=s||ze("agent.agentConversation"),Nr=async()=>{try{const e=await ll(Re,a);e&&window.open(e,"_blank")}catch(e){console.error("Failed to download conversation",e),je({status:"error",title:ze("agent.failedToDownload"),duration:3e3})}},kr=Ve(()=>{const e=(new Date).toISOString(),t=Ae.size>0?[{cursor:"live",streamingMessages:Array.from(Ae,([e,t])=>({id:e,...t}))}]:void 0,n={metadata:{title:wr,agent_run_id:a,exported_at:e,message_count:Pe.length},messages:Pe,...t?{streamingFrames:t}:{}};!function(e,t){const n=new Blob([JSON.stringify(t,null,2)],{type:"application/json"}),r=URL.createObjectURL(n),a=document.createElement("a");a.href=r,a.download=e,document.body.appendChild(a),a.click(),a.remove(),URL.revokeObjectURL(r)}(`${zf(wr)||"agent-chat"}-${zf(a)}.json`,n),je({status:"success",title:ze("agent.rewind.fixtureExported"),duration:2e3})},[wr,a,Pe,Ae,ze,je]),[_r,Cr]=Oe(!1),Sr=()=>{wt.current?Cr(!0):je({status:"error",title:ze("agent.pdfExportFailed"),description:ze("agent.noConversationContent"),duration:3e3})},Tr=Fe(()=>Pe.filter(e=>{if(e.type===ir.COMPLETE)return!0;if(e.type===ir.THOUGHT){const t=e.details;return"completed"===t?.tool_status}return!1}).length,[Pe]),Ir=Fe(()=>gn.plan.plan?.reduce((e,t)=>(t.id&&t.goal&&e.set(t.id.toString(),t.goal),e),new Map),[gn.plan]),zr=t=>e($m,{title:wr,variant:t,isCompleted:En,isTerminal:dn,onClose:l,isModal:c,agentRunId:a,workflowRunId:qe||"",viewMode:zt,onViewModeChange:jt,showPlanPanel:P&&nt,hasPlan:P&&Je.length>0,showPlanButton:P&&!ke,onTogglePlanPanel:qn,showPlaybackButton:kn,isPlaybackEnabled:_n,onTogglePlayback:Bn,onDownload:Nr,onExportFixture:kr,resetWorkflow:m,onClone:f,onShowDetails:g,allowWorkflowControl:v,onExportPdf:Sr,isReceivingChunks:$e}),Rr=t("div",{ref:wt,"data-agent-playback-enabled":_n||void 0,"data-agent-playback-cursor":_n?Tn:void 0,"data-agent-live-message-count":Pe.length,"data-agent-rendered-message-count":Rn.length,className:i("flex flex-col min-h-0 min-w-0 border-0",ke?"flex-1 h-full":Xn?"w-full flex-1 min-h-[50vh]":d?"flex-1 w-full":"flex-1 mx-auto "+(c?"":"max-w-4xl")),children:[!S&&"compact"===T&&e("div",{className:"flex flex-shrink-0 justify-end border-b border-border/60 px-2 py-1 lg:hidden",children:zr("compact")}),!S&&"compact"!==T&&e("div",{className:"flex-shrink-0",children:zr(T)}),_n&&e("div",{className:"flex flex-shrink-0 justify-end px-2 py-1.5",children:e(ks,{cursor:Tn,messages:Cn,onChangeCursor:Vn})}),0===Pe.length&&!En&&_e&&Ce?e(If,{message:_e,startedAt:Ce}):e(ju,{messages:Rn,workstreamSourceMessages:Pe,bottomRef:yt,isCompleted:$n,plan:gn.plan,workstreamStatus:gn.workstreamStatus,showPlanPanel:P&&nt,onTogglePlanPanel:qn,plans:Je,activePlanIndex:Ke,onChangePlan:Hn,taskLabels:Ir,streamingMessages:Pn,onSendMessage:In?sr:void 0,messageItemClassNames:ie,messageStyleOverrides:oe,toolCallGroupClassNames:le,hideToolCallsInViewMode:ce,streamingMessageClassNames:de,batchProgressPanelClassNames:ue,artifactRunId:a,viewMode:zt,hideWorkstreamTabs:j,workingIndicatorClassName:me,messageListClassName:pe,StoreLinkComponent:rr,CollectionLinkComponent:fe,prependFriendlyMessage:ge,initialRequestData:ve,initialRequestSchema:be,initialRequestTitle:xe,initialRequestTemplate:ye,showInitialRequest:"empty"===Ee&&0===Pe.length,hiddenMessageTypes:$,disableAutoScroll:!In,renderRequestInputControls:!Mn,activeWorkstream:$t,onActiveWorkstreamChange:Lt}),Mn?e(Wl,{message:Ln,onSendMessage:In?sr:void 0,onMcpConnected:In?or:void 0,disabled:F||!In,isLoading:kt||F}):Fn&&Dn.length>0?e("div",{className:"flex-shrink-0 pb-safe-area",children:e(Rm,{activeWorkstreams:Dn})}):On&&e("div",{className:"flex-shrink-0 pb-safe-area",children:pn?z??e(Y,{status:"error",icon:null,className:"m-2",children:"This Workflow is FAILED"}):cn&&"RUNNING"!==cn&&!un?"sliding"===zt&&"COMPLETED"===cn?e("div",{className:"mx-auto w-full max-w-3xl px-4 py-3 text-sm text-muted",children:t("div",{className:"flex items-center gap-2 border-t border-success/25 pt-3 text-success",children:[e(Rt,{className:"size-4"}),e("span",{className:"font-medium",children:"Workflow completed"})]})}):t(Y,{status:"COMPLETED"===cn?"success":"done",icon:null,className:"m-2",children:["This Workflow is ",cn]}):(tt||un)&&e(uf,{onSend:sr,onStop:v?xr:void 0,approvalModeSlot:o&&Qt?e(Ja,{mode:Qt,onChange:pr,disabled:!In||dn||!v}):void 0,mcpSlot:e(Vu,{disabledCollections:lr,onChange:ur,onConnectionChange:mr}),disabled:F||!In,isSending:kt||F,isStopping:Pt,isStreaming:!En,isCompleted:En,contextWindowUsage:Wn?Un:void 0,onCompactContext:Wn?yr:void 0,isCompactingContext:Ct,activeTaskCount:yn,activeWorkstreams:xn,placeholder:Nn,onFilesSelected:bt?ft:void 0,uploadedFiles:b,onRemoveFile:x,onRemoveProcessingFile:xt,acceptedFileTypes:y,maxFiles:w,processingFiles:pt,artifactRunId:a,hasProcessingFiles:ht,renderDocumentSearch:N,selectedDocuments:k,onRemoveDocument:_,hideObjectLinking:C,hideFileUpload:!bt,disableDropZone:bt,className:W,inputClassName:B})})]}),jr=e(Qa,{children:e(Zl,{children:t("div",{ref:Nt,className:i("flex flex-col lg:flex-row gap-2 w-full h-full relative overflow-hidden",bt&&Dt&&"ring-2 ring-blue-400 ring-inset",U),onDragEnter:bt?hr:void 0,onDragOver:bt?fr:void 0,onDragLeave:bt?gr:void 0,onDrop:bt?br:void 0,children:[bt&&Dt&&e("div",{className:"absolute inset-0 flex items-center justify-center bg-blue-100/80 dark:bg-blue-900/40 z-50 pointer-events-none rounded-lg",children:t("div",{className:"text-blue-600 dark:text-blue-400 font-medium flex items-center gap-2 text-lg",children:[e(jn,{className:"size-6"}),"Drop files to upload"]})}),!ke&&Rr,!ke&&"compact"===T&&!S&&e("div",{className:"hidden h-full w-12 shrink-0 items-start justify-center px-1 pt-2 lg:flex",children:zr("compact")}),Xn&&t(n,{children:[!ke&&e("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize right panel","aria-valuenow":Math.round(Kn),"aria-valuemin":300,"aria-valuetext":`${Math.round(Kn)} pixels`,tabIndex:0,className:"hidden lg:block lg:w-1 lg:shrink-0 cursor-col-resize bg-border/70 hover:bg-border transition-colors",onMouseDown:()=>Zn(!0),onKeyDown:e=>{if("ArrowLeft"!==e.key&&"ArrowRight"!==e.key)return;e.preventDefault();const t=e.shiftKey?32:16,n="ArrowLeft"===e.key?t:-t,r=Nt.current,a=r?Math.max(300,r.getBoundingClientRect().width-420):900;Yn(e=>Math.min(Math.max(e+n,300),a))}}),e("div",{className:ke?"w-full h-full overflow-auto":"w-full lg:w-[var(--agent-right-panel-width)] lg:shrink-0 min-h-[50vh] lg:h-full border-t lg:border-t-0",style:ke?void 0:{"--agent-right-panel-width":`${Kn}px`},children:e(fm,{plan:gn.plan,workstreamStatus:gn.workstreamStatus,plans:Je,activePlanIndex:Ke,onChangePlan:Hn,showPlan:!R&&nt,activeWorkstreams:bn,hideWorkstreams:j,openDocuments:at,activeDocumentId:st,onSelectDocument:dt,onCloseDocument:ct,onUpdateDocumentTitle:mt,docRefreshKey:ot,runId:a,processingFiles:Z??pt,showArtifacts:D,artifactRefreshKey:Tr,messages:Pe,payloadContent:we,conversationContent:ke?Rr:Ne,onClose:er,defaultTab:Gn,activeTab:Gn,onTabChange:Jn})})]}),t(H,{isOpen:_r,onClose:()=>Cr(!1),children:[e(G,{children:"Export conversation as PDF"}),t(J,{children:[e("p",{className:"mb-2",children:"This will open your browser's print dialog with the current conversation."}),e("p",{className:"text-sm text-muted",children:'To save a PDF, choose "Save as PDF" or a similar option in the print dialog.'})]}),t(Q,{align:"right",children:[e(r,{variant:"ghost",size:"sm",onClick:()=>Cr(!1),children:"Cancel"}),e(r,{size:"sm",onClick:()=>{if(!wt.current)return void je({status:"error",title:ze("agent.pdfExportFailed"),description:ze("agent.noConversationContent"),duration:3e3});const e=`${wr} - ${a}`,t=function(e,t){if("undefined"==typeof window||"undefined"==typeof document)return!1;const n=document.createElement("iframe");n.style.position="fixed",n.style.right="0",n.style.bottom="0",n.style.width="0",n.style.height="0",n.style.border="0",n.style.visibility="hidden",document.body.appendChild(n);const r=n.contentWindow;if(!r)return n.parentNode?.removeChild(n),!1;const a=r.document;return a.open(),a.write("<!doctype html><html><head><title></title></head><body></body></html>"),a.close(),a.title=t,document.querySelectorAll('link[rel="stylesheet"], style').forEach(e=>{a.head.appendChild(e.cloneNode(!0))}),a.body.innerHTML=e.innerHTML,r.focus(),r.print(),setTimeout(()=>{n.parentNode?.removeChild(n)},1e3),!0}(wt.current,e);t?(je({status:"success",title:ze("agent.pdfExportReady"),description:ze("agent.printDialogDescription"),duration:4e3}),Cr(!1)):je({status:"error",title:ze("agent.pdfExportFailed"),description:ze("agent.unableToOpenPrint"),duration:4e3})},children:"Open print dialog"})]})]})]})})});return V?e(ea,{data:V,sendMessage:sr,ChartComponent:ds,artifactRunId:a,children:jr}):jr}function Df({messages:t}){const n=Me.useMemo(()=>[...t].sort((e,t)=>("number"==typeof e.timestamp?e.timestamp:new Date(e.timestamp).getTime())-("number"==typeof t.timestamp?t.timestamp:new Date(t.timestamp).getTime())),[t]);return e("div",{className:"flex flex-col overflow-y-auto space-y-6 py-4",children:n.map(t=>e(Cc,{message:t,showPulsatingCircle:!1},`${t.workstream_id??"main"}-${t.timestamp}-${t.type}`))})}function Ef({messages:t,bottomRef:n,className:r,messagesClassName:a,emptyClassName:s}){const i=Me.useRef(null);He(()=>{n.current&&n.current.scrollIntoView({behavior:"smooth"})},[t,n]);const o=Me.useMemo(()=>[...t].sort((e,t)=>("number"==typeof e.timestamp?e.timestamp:new Date(e.timestamp).getTime())-("number"==typeof t.timestamp?t.timestamp:new Date(t.timestamp).getTime())),[t]);return e("div",{ref:i,className:`flex-1 min-h-0 h-full overflow-y-auto py-4 px-4 sm:px-6 lg:px-8 bg-white flex flex-col ${r||""}`,"data-testid":"messages-container",children:0===o.length?e("div",{className:`flex items-center justify-center h-full text-center py-8 ${s||""}`,children:e("div",{className:"flex items-center px-4 py-3 text-gray-500",children:"Waiting for agent response..."})}):e("div",{className:`flex-1 flex flex-col justify-start h-full min-h-0 ${a||""}`,children:e(Df,{messages:o,isCompleted:!1})})})}function $f({children:t,fallback:n}){return Lf?e(Lf,{fallback:n,children:t}):e(za,{FallbackComponent:n,children:t})}let Lf=null;function Mf(e){Lf=e}function Ff({children:t}){return e($f,{fallback:Of,children:t})}function Of({error:n}){const{t:r}=Ze(),a=n instanceof Error?n.message:void 0;return t(Y,{status:"error",title:r("errors.somethingWentWrong"),children:[t("div",{className:"mb-4",children:[r("errors.teamNotifiedLine1")," ",r("errors.teamNotifiedLine2")," ",e("a",{className:"text-info",href:"mailto:support@vertesiahq.com",children:"support@vertesiahq.com"}),"."]}),a&&e("code",{className:"w-full mt-4 text-sm text-muted break-words",children:a})]})}function Uf({children:t}){return e($f,{fallback:Wf,children:t})}function Wf({error:n}){const r=n instanceof Error?n.message:void 0;return e("tr",{children:t("td",{colSpan:100,children:[e("span",{className:"text-xs",children:" Cannot display row"}),e("br",{}),e("span",{className:"bg-gray-400",children:r})]})})}function Bf({children:t}){return e($f,{fallback:Vf,children:t})}function Vf({error:n}){const r=n instanceof Error?n.message:void 0;return console.log("WidgetError",n),t("div",{className:"text-sm",children:["Sorry, this area cannot be loaded or rendered.",r&&e("pre",{children:r})]})}const qf=/^[a-f0-9]{24}$|^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$|^(?=.*\d)(?=.*[a-zA-Z])[a-zA-Z0-9_-]{8,}$/i;function Hf(e){return qf.test(e)}function Gf({className:n,children:r,title:a,description:s,actions:i,breadcrumbs:o,useDynamicBreadcrumbs:l=!0}){const c=ia();function d(e){return e.replace(/[-_]/g," ").split(" ").map(e=>$r(e)).join(" ")}const u=e=>{if(e?.title)return e.title;const t=e?.href||"";if(!t)return"Page";const n=t.split("#")[0].split("?")[0].split("/").filter(e=>e.length>0);return n.length>=1?d(n[n.length-1]):"Page"},m=(()=>{const e=[];if(l&&"undefined"!=typeof window){const t=window.history.state,n=t?.historyChain;if(Array.isArray(n))n.forEach((t,r)=>{const a=n.length-r;e.push({label:u(t),href:t.href,onClick:()=>c(t.href,{stepsBack:a})})});else{const t=window.location.pathname.split("/").filter(e=>e.length>0);for(let n=0;n<t.length;n++)if(Hf(t[n])){const r=`/${t.slice(0,n).join("/")}`;e.push({label:d(t[n-1]||r),href:r,onClick:()=>c(r,{isBasePathNested:!1})})}}}return o&&o.length>0&&o.forEach(t=>{const n=t.props?.children||t,r=t.props?.href;e.push(r?{href:r,label:n,onClick:()=>c(r,{replace:t.props.clearBreadcrumbs})}:{label:n})}),e})();return t("div",{className:Ae("pb-0 ps-4 pe-2 py-2 flex flex-col",n),children:[t("div",{className:"flex items-start gap-4",children:[t("div",{className:"w-full flex place-content-between h-auto min-h-8 flex-col items-start justify-center",children:[t("nav",{className:"flex-1 flex justify-start text-sm",children:[m.length>0&&e(te,{path:m,separator:e(ht,{className:"size-3.5 cn-rtl-flip"}),maxItems:4}),s&&e(h,{description:s,children:e(qt,{className:"size-4 text-muted ms-4"})})]}),a&&e("div",{className:"flex gap-2 items-center",children:e("h1",{className:"text-xl font-semibold break-all",children:a})})]}),e("div",{className:"flex gap-x-2 shrink-0 items-center",children:i})]}),r&&e("div",{className:"w-full flex items-center",children:r})]})}function Jf(){const{t:n}=Ze();return t("div",{className:"text-center pt-32",children:[e("h1",{className:"text-3xl font-bold text-red-500",children:"404"}),e("p",{className:"text-2xl",children:n("layout.pageNotFound")})]})}function Kf({className:t,size:n="md"}){return e("div",{className:`flex items-center justify-center ${t||""}`,children:e(st,{className:`${{sm:"w-4 h-4",md:"w-6 h-6",lg:"w-8 h-8"}[n]} animate-spin text-muted-foreground`})})}function Yf({pdfUrl:n,pageNumber:r,width:a,className:s,renderTextLayer:i=!1,renderAnnotationLayer:o=!1,onLoadSuccess:l,onError:c}){const[d,u]=Oe(!0),[m,p]=Oe(null);return m?e("div",{className:`flex items-center justify-center text-destructive text-sm ${s||""}`,children:"Failed to load PDF"}):t("div",{className:s,children:[d&&e(Kf,{className:"py-4",size:"md"}),e(ja,{file:n,onLoadSuccess:({numPages:e})=>{u(!1),l?.(e)},onLoadError:e=>{u(!1),p(e),c?.(e)},loading:null,children:e(Pa,{pageNumber:r,width:a,renderTextLayer:i,renderAnnotationLayer:o,loading:e(Kf,{className:"py-4",size:"sm"})})})]})}Ra.GlobalWorkerOptions.workerSrc=`//unpkg.com/pdfjs-dist@${Ra.version}/build/pdf.worker.min.mjs`;const Qf=Ue(null);function Zf({pdfUrl:t,urlLoading:n=!1,children:r,onLoadSuccess:a}){const[s,i]=Oe(0),[o,l]=Oe(!0),[c,d]=Oe(null),[u,m]=Oe(null),p={pdfUrl:t,numPages:s,loading:n||!t||o,error:c,pageDimensions:u};return c?e("div",{className:"flex items-center justify-center text-destructive text-sm py-4",children:"Failed to load PDF"}):e(Qf.Provider,{value:p,children:t?e(ja,{file:t,onLoadSuccess:async e=>{i(e.numPages),a?.(e.numPages);try{const t=(await e.getPage(1)).getViewport({scale:1});m({width:t.width,height:t.height,aspectRatio:t.width/t.height})}catch(e){console.error("Failed to get page dimensions:",e)}l(!1)},onLoadError:e=>{l(!1),d(e)},loading:e(Kf,{className:"py-4",size:"md"}),children:r((t,n)=>e(Pa,{pageNumber:t,width:n,renderTextLayer:!1,renderAnnotationLayer:!1,loading:e(Kf,{className:"py-4",size:"sm"})},t))}):e(Kf,{className:"py-4",size:"md"})})}function Xf(){return We(Qf)}const eg=210/297;function tg({pageNumber:t,width:n,className:r}){const a=Xf(),s=a?.pageDimensions?.aspectRatio??eg,i=n?Math.round(n/s):200;return e("div",a?.loading?{className:`flex items-center justify-center bg-muted ${r||""}`,style:{height:i,width:n||"100%"},children:e(Kf,{size:"md"})}:{className:r,children:e(Pa,{pageNumber:t,width:n,renderTextLayer:!1,renderAnnotationLayer:!1,loading:e(Kf,{className:"py-4",size:"sm"})})})}function ng({pageNumber:t,width:n,isSelected:r,onSelect:a,renderThumbnail:s,aspectRatio:i=eg,rootMargin:o="200px 0px"}){const l=Be(null),[c,d]=Oe(!1);He(()=>{const e=l.current;if(!e)return;const t=new IntersectionObserver(e=>{const t=e[0];t?.isIntersecting&&d(!0)},{rootMargin:o,threshold:0});return t.observe(e),()=>t.disconnect()},[o]);const u=n?Math.round(n/i):200,m=c?e(Pa,{pageNumber:t,width:n,renderTextLayer:!1,renderAnnotationLayer:!1,loading:e("div",{className:"flex items-center justify-center bg-muted",style:{height:u},children:e(Kf,{size:"sm"})})}):e("div",{className:"flex items-center justify-center bg-muted",style:{height:u,width:n||"100%"},children:e("span",{className:"text-muted-foreground text-xs",children:t})});return e("div",{ref:l,children:s({pageNumber:t,isSelected:r,pageElement:m,onSelect:a})})}function rg({pdfUrl:r,urlLoading:a=!1,pageCount:s,currentPage:i,thumbnailWidth:o,onPageSelect:l,renderThumbnail:c,scrollContainerRef:d,onAspectRatioChange:u,onItemHeightChange:m,calculateItemHeight:p,onPageCountChange:h}){const[f,g]=Oe(null),[v,b]=Oe({start:0,end:Math.min(15,s)}),[x,y]=Oe(null),w=Be(null),N=Ve(e=>{g(e)},[]),k=Ve(async e=>{h?.(e.numPages);try{const t=(await e.getPage(1)).getViewport({scale:1}),n=t.width/t.height;y(n),u?.(n)}catch(e){console.error("Failed to get page dimensions:",e),y(eg),u?.(eg)}},[u,h]),_=x??eg,C=o?Math.round(o/_):200,S=p?p(C):C+16+24+8;He(()=>{S>0&&null!==x&&m?.(S)},[S,x,m]);if(He(()=>{const e=d?.current||function(e){if(!e)return null;let t=e.parentElement;for(;t;){const e=window.getComputedStyle(t).overflowY;if("auto"===e||"scroll"===e)return t;t=t.parentElement}return null}(w.current);if(!e)return;const t=()=>{const t=e.scrollTop,n=e.clientHeight,r=Math.floor(t/S),a=Math.ceil((t+n)/S),i=Math.max(0,r-5),o=Math.min(s,a+5);b(e=>e.start!==i||e.end!==o?{start:i,end:o}:e)};return t(),e.addEventListener("scroll",t,{passive:!0}),()=>e.removeEventListener("scroll",t)},[S,s,d]),f)return e("div",{className:"flex items-center justify-center text-destructive text-sm py-4",children:"Failed to load PDF"});if(a||!r)return e(Kf,{className:"py-4",size:"md"});const T=v.start*S,I=(s-v.end)*S,z=null!==x;return e("div",{ref:w,children:e(ja,{file:r,onLoadSuccess:k,onLoadError:N,loading:e(Kf,{className:"py-4",size:"md"}),children:z?t(n,{children:[T>0&&e("div",{style:{height:T}}),Array.from({length:v.end-v.start},(t,n)=>{const r=v.start+n+1;return e("div",{"data-page-index":r-1,style:{height:S,overflow:"hidden"},children:e(ng,{pageNumber:r,width:o,isSelected:r===i,onSelect:()=>l(r),renderThumbnail:c,aspectRatio:_})},r)}),I>0&&e("div",{style:{height:I}})]}):e(Kf,{className:"py-4",size:"md"})})})}function ag({pdfUrl:n,pageNumber:r,width:a,height:s,className:i,renderTextLayer:o=!1,renderAnnotationLayer:l=!1,onPageChange:c}){const[d,u]=Oe(0),[m,p]=Oe(!0),[h,f]=Oe(null);He(()=>{d>0&&c?.(r,d)},[r,d,c]);return h?e("div",{className:`flex items-center justify-center text-destructive ${i||""}`,children:t("span",{children:["Failed to load PDF: ",h.message]})}):t("div",{className:i,children:[m&&e(Kf,{className:"py-8",size:"lg"}),e(ja,{file:n,onLoadSuccess:({numPages:e})=>{u(e),p(!1)},onLoadError:e=>{p(!1),f(e)},loading:null,children:e(Pa,{pageNumber:Math.min(r,d||1),width:a,height:s,renderTextLayer:o,renderAnnotationLayer:l,loading:e(Kf,{className:"py-8",size:"md"})})})]})}const sg=210/297,ig=[50,75,100,125,150,200,300];function og({pdfUrl:a,pdfUrlLoading:s=!1,pageCount:i,currentPage:o,onChange:l,onPageCountChange:c,className:d,compact:u=!1,headerExtra:m}){const{t:p}=Ze(),h=Be(null),f=Be(null),[g,v]=Oe(void 0),[b,x]=Oe(100),[w,N]=Oe(sg),[k,_]=Oe(null),C=Be(null),S=g?Math.round(g*b/100):void 0,T=Ve(()=>{let e=ig.findIndex(e=>e>=b);-1===e&&(e=ig.length-1);const t=Math.min(e+1,ig.length-1);x(ig[t])},[b]),I=Ve(()=>{let e=ig.findIndex(e=>e>=b);-1===e&&(e=ig.length-1);const t=Math.max(e-1,0);x(ig[t])},[b]),z=Ve(()=>{x(100)},[]),R=Ve(e=>e+(u?28:48),[u]),j=Ve((e,t)=>{const n=e?Math.round(e/t):200;return R(n)},[R]);He(()=>{const e=f.current;if(!e)return;let t=null;const n=()=>e.clientWidth-16-16-4,r=()=>{const t=n();if(t<=0)return;const r=C.current;if(r&&r>0){const n=e.scrollTop,a=Math.round(n/r),s=j(t,w),i=a*s;v(t),requestAnimationFrame(()=>{e.scrollTo({top:i,behavior:"instant"})}),C.current=s}else v(t),C.current=j(t,w)},a=n();a>0&&(v(a),C.current=j(a,w));const s=new ResizeObserver(()=>{t&&clearTimeout(t),t=setTimeout(r,150)});return s.observe(e),()=>{t&&clearTimeout(t),s.disconnect()}},[w,j]);const P=Be(!1),A=Be(null),D=Be(b);He(()=>{D.current!==b&&(D.current=b,A.current={targetPage:o},P.current=!0)},[b,o]),He(()=>{const e=f.current,t=A.current;if(t&&e&&k){A.current=null;const n=(t.targetPage-1)*k;requestAnimationFrame(()=>{e.scrollTo({top:n,behavior:"instant"}),requestAnimationFrame(()=>{P.current=!1})})}},[k]);const E=Be(!1);He(()=>{const e=f.current;if(e&&k&&!E.current)if(o>1){E.current=!0,P.current=!0;const t=(o-1)*k;e.scrollTo({top:t,behavior:"instant"}),requestAnimationFrame(()=>{P.current=!1})}else E.current=!0},[k,o]);const $=Be(o);He(()=>{const e=f.current;if(e&&k&&$.current!==o){$.current=o,P.current=!0;const t=(o-1)*k;e.scrollTo({top:t,behavior:"instant"}),requestAnimationFrame(()=>{P.current=!1})}},[o,k]),He(()=>{const e=f.current;if(!e||!k)return;let t=null;const n=()=>{P.current||(t&&clearTimeout(t),t=setTimeout(()=>{const t=e.scrollTop,n=Math.round(t/k)+1,r=Math.max(1,Math.min(n,i));r!==o&&($.current=r,l(r))},50))};return e.addEventListener("scroll",n,{passive:!0}),()=>{t&&clearTimeout(t),e.removeEventListener("scroll",n)}},[k,i,o,l]);return t("div",{ref:h,className:Ae("flex flex-col items-stretch",u?"gap-y-1":"gap-y-2",d),children:[t("div",{className:Ae("relative flex items-center justify-center px-2",u?"h-6":"h-9"),children:[e(r,{variant:"ghost",size:"xs",onClick:()=>{o>1&&l(o-1)},title:p("pdf.previousPage"),children:e(Un,{className:"size-4"})}),t("div",{className:"absolute start-2 flex items-center gap-x-1",children:[e(cg,{zoom:b,onZoomIn:T,onZoomOut:I,onFitToView:z,canZoomIn:b<ig[ig.length-1],canZoomOut:b>ig[0]}),m&&t(n,{children:[e("div",{className:"w-px h-4 bg-border mx-1"}),m]})]}),e("div",{className:"absolute end-2",children:e(lg,{currentPage:o,totalPages:i,onChange:l})})]}),e("div",{ref:f,className:Ae("flex flex-col items-center flex-1 overflow-y-auto px-2",u?"gap-1":"gap-2"),children:e(rg,{pdfUrl:a,urlLoading:s,pageCount:i,currentPage:o,thumbnailWidth:S,onPageSelect:l,onPageCountChange:c,scrollContainerRef:f,onAspectRatioChange:N,onItemHeightChange:_,calculateItemHeight:R,renderThumbnail:({pageNumber:n,isSelected:a,pageElement:s,onSelect:i})=>t("div",{className:Ae("hover:bg-muted rounded-md w-full",u?"p-1":"p-2"),children:[e(r,{variant:"unstyled",size:"none","aria-pressed":a,"aria-label":`Page ${n}`,className:Ae("relative border-[2px] cursor-pointer overflow-hidden",a?"border-primary":"border-border"),onClick:i,children:s}),e(y,{className:Ae("text-muted-foreground font-semibold",u?"text-xs pt-0.5":"text-sm pt-1"),children:n})]},n)})}),e("div",{className:Ae("flex items-center justify-center",u?"h-6":"h-9"),children:e(r,{variant:"ghost",size:"xs",onClick:()=>{o<i&&l(o+1)},title:p("pdf.nextPage"),children:e(Wn,{className:"size-4"})})})]})}function lg({currentPage:n,totalPages:r,onChange:a}){const{t:s}=Ze(),i=Be(null),[o,l]=Oe(String(n));He(()=>{l(String(n))},[n]);const c=()=>{const e=parseInt(o,10);!Number.isNaN(e)&&e>=1&&e<=r?a(e):l(String(n))};return t("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e("span",{children:s("pdf.page")}),e("input",{ref:i,type:"text",value:o,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"===e.key?(c(),i.current?.blur()):"Escape"===e.key&&(l(String(n)),i.current?.blur())},onBlur:()=>{c()},className:"w-8 h-5 text-center text-xs px-1 py-0 bg-background border border-border rounded focus:outline-none focus:border-primary"}),t("span",{children:["/ ",r]})]})}function cg({zoom:n,onZoomIn:a,onZoomOut:s,onFitToView:i,canZoomIn:o,canZoomOut:l}){const{t:c}=Ze();return t("div",{className:"flex items-center gap-x-0.5",children:[e(r,{variant:"ghost",size:"xs",onClick:s,isDisabled:!l,title:c("pdf.zoomOut"),children:e(Bn,{})}),t("span",{className:"text-xs text-muted-foreground min-w-[32px] text-center",children:[n,"%"]}),e(r,{variant:"ghost",size:"xs",onClick:a,isDisabled:!o,title:c("pdf.zoomIn"),children:e(Vn,{})}),e(r,{variant:"ghost",size:"xs",onClick:i,title:c("pdf.fitToWidth"),className:100===n?"text-muted-foreground/40":void 0,children:e(qn,{})})]})}const dg="magic-pdf";var ug;!function(e){e.original="original",e.instrumented="instrumented"}(ug||(ug={}));class mg{client;objectId;totalPages;cache=new Map;pending=new Map;constructor(e,t,n){this.client=e,this.objectId=t,this.totalPages=n}getCacheKey(e,t){return`${t}-${e}`}async getPageImageUrl(e,t){const n=this.getCacheKey(e,t),r=this.cache.get(n);if(r)return r;const a=this.pending.get(n);if(a)return a;const s=this.fetchImageUrl(e,t);this.pending.set(n,s);try{const e=await s;return this.cache.set(n,e),e}finally{this.pending.delete(n)}}async fetchImageUrl(e,t){const n=this.getImagePath(e,t);return(await this.client.files.getDownloadUrl(n)).url}getImagePath(e,t){const n=`${dg}/${this.objectId}/pages`;switch(t){case ug.original:return`${n}/page-${e}.original.jpg`;case ug.instrumented:return`${n}/page-${e}.instrumented.jpg`}}}class pg{client;objectId;totalPages;cache=new Map;pending=new Map;constructor(e,t,n){this.client=e,this.objectId=t,this.totalPages=n}async getPageLayout(e){const t=this.cache.get(e);if(void 0!==t)return t;const n=this.pending.get(e);if(n)return n;const r=this.fetchPageLayout(e);this.pending.set(e,r);try{const t=await r;return this.cache.set(e,t),t}finally{this.pending.delete(e)}}async fetchPageLayout(e){const t=`${dg}/${this.objectId}/pages/page-${e}.layout.json`,n=await this.client.files.getDownloadUrl(t),r=await fetch(n.url,{method:"GET"});if(!r.ok)throw new Error(`Failed to fetch json layout: ${r.statusText}`);return r.text()}}class hg{totalPages;pages=[];constructor(e){this.totalPages=e}initFromContent(e){this.pages=function(e,t){const n=new Array(t).fill(""),r=/<!--\s*\{\s*"page"\s*:\s*(\d+)\s*\}\s*-->/g,a=[];for(const t of e.matchAll(r))a.push({page:parseInt(t[1],10),index:t.index+t[0].length});for(let r=0;r<a.length;r++){const s=a[r],i=s.page-1;if(i<0||i>=t)continue;const o=s.index,l=e.slice(o).match(/<!--\s*\{\s*"page"\s*:\s*\d+\s*\}\s*-->/),c=l?o+l.index:e.length;let d=e.slice(o,c).trim();d=d.replace(/\n---\s*$/,"").trim(),n[i]=d}return n}(e,this.totalPages)}async loadUrls(e,t){}async getPageMarkdown(e){const t=e-1;return t<0||t>=this.pages.length?"":this.pages[t]}}const fg=Ue(void 0);function gg({children:t,object:n}){const{client:r}=tr(),a=n.metadata.page_count||10,s="markdown"===n.metadata?.content_processor?.type,[i,o]=Oe(()=>{const e=new hg(a);s&&n.text&&e.initFromContent(n.text);const t=n.text?xg(n.text):"";return{count:a,layoutProvider:new pg(r,n.id,a),markdownProvider:e,imageProvider:new mg(r,n.id,a),xml:t,xmlPages:n.text?bg(t):[],pdfUrl:"",pdfUrlLoading:!0}});return He(()=>{if(s){const e=n.metadata,t=e?.renditions?.find(e=>e.name===br),a="application/pdf"===n.content?.type,s=t?.content?.source||(a?n.content?.source:void 0);s?r.store.objects.getDownloadUrl(s,void 0,"inline").then(e=>{o(t=>({...t,pdfUrl:e.url,pdfUrlLoading:!1}))}).catch(e=>{console.warn("Failed to get PDF URL:",e),o(e=>({...e,pdfUrlLoading:!1}))}):o(e=>({...e,pdfUrlLoading:!1}))}else o(e=>({...e,pdfUrlLoading:!1}))},[r,s,n.metadata,n.content?.type,n.content?.source]),e(fg.Provider,{value:i,children:t})}function vg(){const e=Me.useContext(fg);if(!e)throw new Error("useMagicPdfContext must be used within a MagicPdfProvider");return e}function bg(e){const t=(new DOMParser).parseFromString(xg(e),"text/xml").getElementsByTagName("page"),n=new XMLSerializer;return Array.from(t).map(e=>n.serializeToString(e))}function xg(e){return e.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,"").replace(/<\?xml.*?\?>/g,"")}const yg=[50,75,100,125,150,200,300],wg=11/8.5;function Ng({className:n,currentPage:a,onChange:s}){const{t:i}=Ze(),[o,l]=Oe(ug.instrumented),[c,d]=Oe(wg),[u,m]=Oe(new Map),[p,h]=Oe(100),f=Be(new Set),g=Be(null),v=Be(null),b=Be(!1),{imageProvider:x,count:y}=vg(),w=Ve(()=>{let e=yg.findIndex(e=>e>=p);-1===e&&(e=yg.length-1);const t=Math.min(e+1,yg.length-1);h(yg[t])},[p]),N=Ve(()=>{let e=yg.findIndex(e=>e>=p);-1===e&&(e=yg.length-1);const t=Math.max(e-1,0);h(yg[t])},[p]),k=Ve(()=>{h(100)},[]);He(()=>{x.getPageImageUrl(1,o).then(e=>{const t=new window.Image;t.onload=()=>{t.width>0&&t.height>0&&d(t.height/t.width)},t.src=e}).catch(()=>{})},[x,o]);const _=Be(o);He(()=>{let e=!1;_.current!==o&&(_.current=o,f.current=new Set,m(new Map));const t=function(e,t){const n=[e];let r=1;for(;n.length<t;){const a=e+r,s=e-r;a<=t&&n.push(a),s>=1&&n.push(s),r++}return n}(a,y);return t.forEach(t=>{(async t=>{if(!e&&!f.current.has(t))try{const n=await x.getPageImageUrl(t,o);e||(f.current.add(t),m(e=>new Map(e).set(t,n)))}catch{}})(t)}),()=>{e=!0}},[a,y,o,x]);const C=Be(p);He(()=>{if(C.current!==p&&v.current){C.current=p,b.current=!0;const e=v.current.querySelector(`[data-page="${a}"]`);e?requestAnimationFrame(()=>{e.scrollIntoView({behavior:"instant",block:"center"}),requestAnimationFrame(()=>{b.current=!1})}):b.current=!1}},[p,a]);const S=Be(a);He(()=>{if(S.current!==a&&v.current){S.current=a,b.current=!0;const e=v.current.querySelector(`[data-page="${a}"]`);e&&e.scrollIntoView({behavior:"instant",block:"nearest"}),requestAnimationFrame(()=>{b.current=!1})}},[a]),He(()=>{const e=v.current;if(!e)return;let t=null;const n=()=>{b.current||(t&&clearTimeout(t),t=setTimeout(()=>{const t=e.getBoundingClientRect(),n=t.top+t.height/2;let r=a,i=1/0;for(let t=1;t<=y;t++){const a=e.querySelector(`[data-page="${t}"]`);if(a){const e=a.getBoundingClientRect(),s=e.top+e.height/2,o=Math.abs(s-n);o<i&&(i=o,r=t)}}r!==a&&(S.current=r,s(r))},50))};return e.addEventListener("scroll",n,{passive:!0}),()=>{t&&clearTimeout(t),e.removeEventListener("scroll",n)}},[y,a,s]);return t("div",{ref:g,className:Ae("flex flex-col items-stretch gap-y-2",n),children:[t("div",{className:"relative flex items-center justify-center px-2 h-9",children:[e(r,{variant:"ghost",size:"xs",onClick:()=>{a>1&&s(a-1)},title:i("pdf.previousPage"),children:e(Un,{className:"size-4"})}),t("div",{className:"absolute start-2 flex items-center gap-x-1",children:[e(kg,{type:ug.original,currentType:o,onClick:()=>l(ug.original),icon:e(St,{className:"size-4"}),tooltip:i("pdf.originalImages")}),e(kg,{type:ug.instrumented,currentType:o,onClick:()=>l(ug.instrumented),icon:e(Hn,{className:"size-4"}),tooltip:i("pdf.instrumentedImages")}),e("div",{className:"w-px h-4 bg-border mx-1"}),e(_g,{zoom:p,onZoomIn:w,onZoomOut:N,onFitToView:k,canZoomIn:p<yg[yg.length-1],canZoomOut:p>yg[0]})]}),e("div",{className:"absolute end-2",children:e(Sg,{currentPage:a,totalPages:y,onChange:s})})]}),e("div",{ref:v,className:"flex flex-col items-center gap-2 flex-1 overflow-y-auto px-2",children:Array.from({length:y},(t,n)=>e(Cg,{currentPage:a,pageNumber:n+1,aspectRatio:c,zoom:p,url:u.get(n+1),onSelect:()=>s(n+1)},n))}),e("div",{className:"flex items-center justify-center h-9",children:e(r,{variant:"ghost",size:"xs",onClick:()=>{a<y&&s(a+1)},title:i("pdf.nextPage"),children:e(Wn,{className:"size-4"})})})]})}function kg({type:t,currentType:n,onClick:a,icon:s,tooltip:i}){const o=t===n;return e(r,{title:i,tooltipPlacement:"bottom",variant:"unstyled","aria-pressed":o,className:Ae("p-1 rounded cursor-pointer transition-colors",o?"text-primary bg-primary/10":"text-muted-foreground hover:text-foreground hover:bg-muted"),onClick:a,children:s})}function _g({zoom:n,onZoomIn:a,onZoomOut:s,onFitToView:i,canZoomIn:o,canZoomOut:l}){const{t:c}=Ze();return t("div",{className:"flex items-center gap-x-0.5",children:[e(r,{title:c("pdf.zoomOut"),tooltipPlacement:"bottom",variant:"unstyled",className:Ae("p-1 rounded cursor-pointer transition-colors",l?"text-muted-foreground hover:text-foreground hover:bg-muted":"text-muted-foreground/40 cursor-not-allowed"),onClick:s,disabled:!l,children:e(Bn,{className:"size-4"})}),t("span",{className:"text-xs text-muted-foreground min-w-[32px] text-center",children:[n,"%"]}),e(r,{title:c("pdf.zoomIn"),tooltipPlacement:"bottom",variant:"unstyled",className:Ae("p-1 rounded cursor-pointer transition-colors",o?"text-muted-foreground hover:text-foreground hover:bg-muted":"text-muted-foreground/40 cursor-not-allowed"),onClick:a,disabled:!o,children:e(Vn,{className:"size-4"})}),e(r,{title:c("pdf.fitToWidth"),tooltipPlacement:"bottom",variant:"unstyled",className:Ae("p-1 rounded cursor-pointer transition-colors",100!==n?"text-muted-foreground hover:text-foreground hover:bg-muted":"text-muted-foreground/40"),onClick:i,children:e(qn,{className:"size-4"})})]})}function Cg({pageNumber:n,currentPage:a,aspectRatio:s,zoom:i,url:o,onSelect:l}){const c=n===a;return t("div",{className:"p-2 hover:bg-muted rounded-md flex flex-col items-center","data-page":n,style:{width:`${i}%`},children:[e(r,{variant:"unstyled",size:"none","aria-pressed":c,"aria-label":`Page ${n}`,className:Ae("relative border-[2px] cursor-pointer overflow-hidden !flex items-center justify-center bg-muted/50 w-full",c?"border-primary":"border-border"),style:{aspectRatio:`1 / ${s}`},onClick:l,children:o?e("img",{src:o,alt:`Page ${n}`,className:"w-full"}):e(st,{className:"w-6 h-6 animate-spin text-muted-foreground"})}),e(y,{className:"text-sm text-muted-foreground pt-1 font-semibold",children:n})]})}function Sg({currentPage:n,totalPages:r,onChange:a}){const{t:s}=Ze(),i=Be(null),[o,l]=Oe(String(n));He(()=>{l(String(n))},[n]);const c=()=>{const e=parseInt(o,10);!Number.isNaN(e)&&e>=1&&e<=r?a(e):l(String(n))};return t("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e("span",{children:s("pdf.page")}),e("input",{ref:i,type:"text",value:o,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"===e.key?(c(),i.current?.blur()):"Escape"===e.key&&(l(String(n)),i.current?.blur())},onBlur:()=>{c()},className:"w-8 h-5 text-center text-xs px-1 py-0 bg-background border border-border rounded focus:outline-none focus:border-primary"}),t("span",{children:["/ ",r]})]})}function Tg({object:n}){const{t:a}=Ze(),{client:s}=tr(),i=e=>{(function(e,t,n){return e.files.getDownloadUrl(`${dg}/${t}/${n}`).then(e=>e.url)})(s,n.id,e).then(e=>window.open(e,"_blank"))},o="p-2 cursor-pointer hover:bg-muted text-start text-sm";return"markdown"===(()=>{if("document"===n.metadata?.type){const e=n.metadata;return e.content_processor?.type||"xml"}return"xml"})()?e(r,{variant:"ghost",size:"xs",onClick:()=>i("document.md"),title:a("pdf.download"),children:e(lt,{className:"size-4"})}):t(I,{children:[e(z,{children:e(r,{variant:"ghost",size:"xs",title:a("pdf.download"),children:e(lt,{className:"size-4"})})}),e(R,{align:"start",className:"p-0 w-auto",children:t("div",{className:"min-w-[200px] flex flex-col divide-y divide-border",children:[e(r,{variant:"unstyled",className:o,onClick:()=>i("annotated.pdf"),children:"annotated.pdf"}),e(r,{variant:"unstyled",className:o,onClick:()=>i("document.xml"),children:"document.xml"}),e(r,{variant:"unstyled",className:o,onClick:()=>i("analyzed-pages.json"),children:"analyzed-pages.json"})]})})]})}function Ig({className:t}){return e("div",{className:`flex items-center justify-center ${t||""}`,children:e(st,{className:"w-6 h-6 animate-spin text-gray-400"})})}function zg({viewType:t,pageNumber:n}){switch(t){case"json":return e(jg,{pageNumber:n});case"markdown":return e(Pg,{pageNumber:n});default:return e(Rg,{pageNumber:n})}}function Rg({pageNumber:t}){const{xmlPages:n}=vg();return e("div",{className:"px-4 py-2",children:e(fa,{xml:n[t-1],collapsible:!0})})}function jg({pageNumber:t}){const[n,r]=Oe(null),[a,s]=Oe(!0),[i,o]=Oe(null),{layoutProvider:l}=vg();return He(()=>{s(!0),o(null),l.getPageLayout(t).then(e=>{r(e?JSON.parse(e):null),s(!1)}).catch(e=>{console.error(e),o(e.message||"Failed to load layout"),s(!1)})},[t,l]),a?e("div",{className:"px-4 py-8",children:e(Ig,{})}):i?e("div",{className:"px-4 py-2 text-red-500 text-sm",children:i}):n?e(ga,{className:"w-full",data:n}):null}function Pg({pageNumber:n}){const[r,a]=Oe(null),[s,i]=Oe(!0),[o,l]=Oe(null),{markdownProvider:c}=vg();return He(()=>{i(!0),l(null),c.getPageMarkdown(n).then(e=>{a(e),i(!1)}).catch(e=>{console.error(e),l(e.message||"Failed to load markdown"),i(!1)})},[n,c]),s?t("div",{className:"h-full flex flex-col items-center justify-center gap-2",children:[e(Ig,{}),e("span",{className:"text-sm text-muted-foreground",children:"Loading..."})]}):e("div",o?{className:"px-4 py-2 text-red-500 text-sm",children:o}:{className:"px-4 py-2 prose prose-sm max-w-none dark:prose-invert",children:r?e(oa,{children:r}):e("div",{children:"No markdown content available"})})}class Ag extends Ye{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){console.error("PDF View error:",e,t)}render(){return this.state.hasError?e("div",{className:"fixed inset-0 bg-background z-50 flex items-center justify-center",children:t("div",{className:"flex flex-col items-center gap-4 p-8 max-w-md",children:[e(x,{title:Xe.t("pdf.failedToLoadViewer",{ns:et}),children:this.state.error?.message||"An unexpected error occurred"}),this.props.onClose&&e(r,{variant:"outline",onClick:this.props.onClose,children:"Close"})]})}):this.props.children}}function Dg({objectId:n,onClose:a}){const{t:s}=Ze(),{client:i}=tr(),{data:o,error:l}=S(()=>i.store.objects.retrieve(n,"+text"),[n]);return l?e("div",{className:"fixed inset-0 bg-background z-50 flex items-center justify-center",children:t("div",{className:"flex flex-col items-center gap-4 p-8 max-w-md",children:[e(x,{title:s("pdf.fetchingDocumentFailed"),children:T(l)}),a&&e(r,{variant:"outline",onClick:a,children:"Close"})]})}):o?e(Ag,{onClose:a,children:e("div",{className:"fixed inset-0 bg-background z-50 flex items-center justify-center",children:e(gg,{object:o,children:e(Eg,{object:o,onClose:a})})})}):t("div",{className:"fixed inset-0 bg-background z-50 flex flex-col",children:[e("div",{className:"flex h-9 items-center justify-end shrink-0 bg-sidebar px-2 border-b border-sidebar-border",children:a&&e(r,{variant:"ghost",size:"xs",onClick:a,title:s("pdf.close"),children:e(ut,{className:"size-4"})})}),e("div",{className:"flex-1 flex items-center justify-center",children:e("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})]})}function Eg({object:n,onClose:a}){const{t:s}=Ze(),{count:i,pdfUrl:o,pdfUrlLoading:l}=vg(),[c,d]=Oe(1),u=(()=>{if("document"===n.metadata?.type){const e=n.metadata,t=e.content_processor?.type;if("markdown"===t)return"markdown"}return"xml"})();return t(ne,"xml"===u?{direction:"horizontal",className:"absolute inset-0",children:[e(re,{defaultSize:50,minSize:20,maxSize:80,className:"bg-muted",children:e(Ng,{className:"h-full",currentPage:c,onChange:d})}),e(ae,{className:"w-[4px] bg-border cursor-ew-resize"}),t(re,{defaultSize:50,minSize:20,className:"flex flex-col",children:[t("div",{className:"flex h-9 items-center justify-between shrink-0 bg-sidebar px-2 border-b border-sidebar-border",children:[e("div",{className:"flex items-center gap-x-2",children:e(Tg,{object:n})}),e("span",{className:"text-xs text-muted-foreground",children:s("pdf.pageOf",{pageNumber:c,totalPages:i})}),e("div",{className:"flex items-center gap-x-2",children:!!a&&e(r,{variant:"ghost",size:"xs",onClick:a,title:s("pdf.close"),children:e(ut,{className:"size-4"})})})]}),e("div",{className:"flex-1 overflow-auto px-2",children:e(zg,{pageNumber:c,viewType:"xml"})})]})]}:{direction:"horizontal",className:"absolute inset-0",children:[e(re,{defaultSize:50,minSize:20,maxSize:80,className:"bg-muted",children:e(og,{pdfUrl:o,pdfUrlLoading:l,pageCount:i,className:"h-full",currentPage:c,onChange:d})}),e(ae,{className:"w-[4px] bg-border cursor-ew-resize"}),t(re,{defaultSize:50,minSize:20,className:"flex flex-col",children:[t("div",{className:"flex h-9 items-center justify-between shrink-0 bg-sidebar px-2 border-b border-sidebar-border",children:[e("div",{className:"flex items-center gap-x-2",children:e(Tg,{object:n})}),e("span",{className:"text-xs text-muted-foreground",children:s("pdf.pageOf",{pageNumber:c,totalPages:i})}),e("div",{className:"flex items-center gap-x-2",children:!!a&&e(r,{variant:"ghost",size:"xs",onClick:a,title:s("pdf.close"),children:e(ut,{className:"size-4"})})})]}),e("div",{className:"flex-1 overflow-auto px-2",children:e(zg,{pageNumber:c,viewType:"markdown"})})]})]})}const $g=["image/jpeg","image/jpg","image/png","image/gif","image/webp","image/svg+xml"],Lg=["video/mp4","video/webm"],Mg=["audio/mp4","audio/m4a","audio/x-m4a","audio/mpeg","audio/ogg","audio/wav","audio/webm"];function Fg(e){const t=Math.floor(e/3600),n=Math.floor(e%3600/60),r=Math.floor(e%60);return t>0?`${t}:${n.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}`:`${n}:${r.toString().padStart(2,"0")}`}function Og({url:n,source:r,object:a,className:s}){const{t:i}=Ze(),{client:o}=tr(),[l,c]=Oe(n),[d,u]=Oe(!(n||!r&&!a)),m=a?.metadata,p=(m?.renditions||[]).find(e=>e.name===xr),h=a?.content?.type&&Mg.includes(a.content.type),f=!!a&&a.metadata?.type===yr.Audio&&!p&&!h;return He(()=>{if(n)return c(n),void u(!1);c(void 0);r||a?(u(!0),(async()=>{try{if(r){const e=await o.files.getDownloadUrl(r);return void c(e.url)}if(!a)return;if(a.metadata?.type!==yr.Audio)return;let e;p?.content?.source?e=await o.files.getDownloadUrl(p.content.source):h&&a.content?.source&&(e=await o.files.getDownloadUrl(a.content.source)),e&&c(e.url)}catch(e){console.error("Failed to get audio URL",e)}finally{u(!1)}})()):u(!1)},[n,r,a,p,h,o]),f?e("div",{className:`flex justify-center items-center h-[200px] text-muted ${s??""}`.trim(),children:t("div",{className:"text-center",children:[e("p",{children:i("store.noAudioRendition")}),e("p",{className:"text-sm mt-2",children:i("store.audioFormatRequired")})]})}):d?e("div",{className:`flex justify-center items-center h-[200px] ${s??""}`.trim(),children:e(K,{size:"md"})}):l?t("div",{className:`flex flex-col items-center gap-4 ${s??""}`.trim(),children:[e("audio",{src:l,controls:!0,className:"w-full max-w-2xl",children:"Your browser does not support the audio tag."}),m?.duration&&t("div",{className:"text-sm text-muted",children:["Duration: ",Fg(m.duration)]})]}):e("div",{className:`flex justify-center items-center h-[200px] text-muted ${s??""}`.trim(),children:"Failed to load audio"})}function Ug({url:t,source:n,object:r,className:a}){const{client:s}=tr(),[i,o]=Oe(t),[l,c]=Oe(!(t||!n&&!r));return He(()=>{if(t)return o(t),void c(!1);o(void 0);n||r?(c(!0),(async()=>{try{if(n){const e=await s.files.getDownloadUrl(n);return void o(e.url)}if(!r)return;if(r.metadata?.type!==yr.Image)return;const e=r.content?.type&&$g.includes(r.content.type);try{const e=await s.objects.getRendition(r.id,{format:fr.jpeg,generate_if_missing:!1,sign_url:!0});if("found"===e.status&&e.renditions?.length)return void o(e.renditions[0])}catch{}if(e&&r.content?.source){const e=await s.files.getDownloadUrl(r.content.source);o(e.url)}}finally{c(!1)}})()):c(!1)},[t,n,r,s]),l?e("div",{className:a,children:e(K,{size:"md"})}):i?e("img",{src:i,alt:r?.name,className:`w-full object-contain ${a??""}`.trim()}):null}function Wg({url:n,source:r,object:a,className:s}){const{t:i}=Ze(),{client:o}=tr(),[l,c]=Oe(n),[d,u]=Oe(),[m,p]=Oe(!(n||!r&&!a)),h=a?.metadata,f=h?.renditions||[],g=f.find(e=>"video/mp4"===e.content.type)||f.find(e=>"video/webm"===e.content.type),v=a?.content?.type&&Lg.includes(a.content.type),b=f.find(e=>e.name===wr),x=!!a&&a.metadata?.type===yr.Video&&!g&&!v;return He(()=>{if(n)return c(n),void p(!1);c(void 0),u(void 0);r||a?(p(!0),(async()=>{try{if(r){const e=await o.files.getDownloadUrl(r);return void c(e.url)}if(!a)return;if(a.metadata?.type!==yr.Video)return;let e;g?.content?.source?e=await o.files.getDownloadUrl(g.content.source):v&&a.content?.source&&(e=await o.files.getDownloadUrl(a.content.source)),e&&c(e.url)}catch(e){console.error("Failed to get video URL",e)}finally{p(!1)}})()):p(!1)},[n,r,a,g,v,o]),He(()=>{b?.content?.source&&o.files.getDownloadUrl(b.content.source).then(e=>u(e.url)).catch(e=>console.error("Failed to load poster image",e))},[b,o]),x?e("div",{className:`flex justify-center items-center h-[400px] text-muted ${s??""}`.trim(),children:t("div",{className:"text-center",children:[e("p",{children:i("store.noVideoRendition")}),e("p",{className:"text-sm mt-2",children:i("store.videoFormatRequired")})]})}):m?e("div",{className:`flex justify-center items-center h-[400px] ${s??""}`.trim(),children:e(K,{size:"md"})}):l?e("video",{src:l,poster:d,controls:!0,className:`w-full h-full object-contain ${s??""}`.trim(),children:"Your browser does not support the video tag."}):e("div",{className:`flex justify-center items-center h-[400px] text-muted ${s??""}`.trim(),children:"Failed to load video"})}function Bg({oauthProviderId:r,onAuthChange:a}){const{client:s}=tr(),{t:i}=Ze(),[o,l]=Oe(null),[c,d]=Oe(!0),[u,m]=Oe(!1),[p,h]=Oe(!1),f=Ve(async()=>{try{d(!0);const e=await s.oauthProviders.getStatus(r);l(e)}catch(e){console.error("Failed to load OAuth provider status:",e)}finally{d(!1)}},[s,r]);He(()=>{f()},[f]);const{openOAuthPopup:g}=wi({onComplete:()=>{m(!1),f(),a?.()},onError:e=>{console.error("OAuth provider auth failed:",e),m(!1)}}),v=async()=>{if(!p)try{h(!0),await s.oauthProviders.disconnect(r),await f(),a?.()}catch(e){console.error("Failed to disconnect OAuth provider:",e)}finally{h(!1)}};return c?e(yi,{className:"size-4"}):o?.authenticated?t("div",{className:"flex items-center gap-2",children:[t("div",{className:"flex items-center gap-1 text-success text-sm",children:[e(xt,{className:"size-4"}),e("span",{children:i("oauthProvider.connected")})]}),e(Ms,{variant:"outline",size:"sm",onClick:v,disabled:p,children:p?e(yi,{className:"size-3"}):i("oauthProvider.disconnect")})]}):e(Ms,{variant:"outline",size:"sm",onClick:async()=>{if(!u)try{m(!0);const e=await s.oauthProviders.authorize(r);e.authorization_url&&g(e.authorization_url)}catch(e){console.error("Failed to authorize OAuth provider:",e),m(!1)}},disabled:u,children:t(n,u?{children:[e(yi,{className:"size-4"}),e("span",{children:i("oauthProvider.authenticating")})]}:{children:[e($t,{className:"size-4 me-1"}),e("span",{children:i("oauthProvider.authenticate")})]})})}function Vg({object:n,url:a,source:s,className:i}){const{t:o}=Ze(),{client:l}=tr(),[c,d]=Oe(1),[u,m]=Oe(a||""),[p,h]=Oe(!a),[f,g]=Oe(0),[v,b]=Oe(!1);He(()=>{if(a)return m(a),void h(!1);const e=s||n?.content?.source;e?(h(!0),l.files.getDownloadUrl(e).then(e=>{m(e.url)}).catch(e=>{console.error("Failed to get PDF URL:",e)}).finally(()=>{h(!1)})):h(!1)},[a,s,n?.content?.source,l]),He(()=>{const e=n?.metadata,t=e?.pages||e?.page_count||0;t>0&&g(t)},[n?.metadata]);const x=e=>{g(e)};return p?e("div",{className:"flex items-center justify-center h-full",children:e(K,{size:"lg"})}):u?v?t("div",{className:"fixed inset-0 bg-background z-50 flex flex-col overflow-hidden",children:[e("div",{className:"flex h-9 items-center justify-end shrink-0 bg-sidebar px-2 border-b border-sidebar-border",children:e(r,{variant:"ghost",size:"xs",onClick:()=>b(!1),title:o("pdf.closeFullscreen"),children:e(ut,{className:"size-4"})})}),e(og,{pdfUrl:u,pdfUrlLoading:p,pageCount:f||100,currentPage:c,onChange:d,onPageCountChange:x,className:"flex-1 min-h-0"})]}):e("div",{className:"relative h-full flex flex-col",children:e(og,{pdfUrl:u,pdfUrlLoading:p,pageCount:f||100,currentPage:c,onChange:d,onPageCountChange:x,className:i,compact:!0,headerExtra:e(r,{title:o("pdf.fullscreen"),tooltipPlacement:"bottom",variant:"unstyled",className:"p-1 rounded cursor-pointer transition-colors text-muted-foreground hover:text-foreground hover:bg-muted",onClick:()=>b(!0),children:e(dt,{className:"size-4"})})})}):e("div",{className:"flex items-center justify-center h-full text-muted",children:o("pdf.noPdfAvailable")})}function qg(...e){const t=Array.from(e);return t.__AnyOf__=!0,t}function Hg(...e){return Array.from(e)}function Gg(e){return!0===e.__AnyOf__}class Jg{system_roles;roles;permissions;constructor(e,t){if(!e.authToken)throw new Error("No auth token found in user session");this.system_roles=t;const n=new Set(e.authToken.account_roles||[]);if(e.authToken.project_roles)for(const t of e.authToken.project_roles)n.add(t);this.roles=n;const r={};for(const e of t)r[e.name]=e.permissions;const a=e.authToken.type===hr.OAuthAccess?new Set(e.authToken.permissions??[]):void 0,s=new Set;for(const e of n){const t=r[e];if(t)for(const e of t)a&&!a.has(e)||s.add(e)}this.permissions=s}hasPermission(e){if("string"==typeof e)return this.permissions.has(e);if(Gg(e))return e.some(e=>this.permissions.has(e));for(const t of e)if(!this.permissions.has(t))return!1;return!0}}const Kg=Ue(void 0);function Yg(){const e=We(Kg);if(!e)throw new Error("UserPermissionContext cannot be used outside UserPermissionProvider");return e}function Qg({children:t}){const{t:n}=Ze(),r=tr(),{data:a,error:s,isLoading:i}=S(()=>r.user?r.client.iam.roles.listSystem():Promise.resolve(void 0),[r.user]),o=Fe(()=>r.authToken&&a&&!i?new Jg(r,a):void 0,[r,a,i]);return s?e(x,{title:n("store.failedToFetchRoleMappings"),children:T(s)}):o&&e(Kg.Provider,{value:o,children:t})}function Zg({permission:t,isDisabled:n,title:a,children:s,...i}){return Yg().hasPermission(t)?e(r,{isDisabled:n,title:a,...i,children:s}):null}function Xg({permission:t,...n}){return Yg().hasPermission(t)?e(Aa,{...n}):null}class ev extends oe{idOf(e){return e.id}labelOf(e){return e.label}descriptionOf(e){return e.description}selectedClassName(e){return"border-3 border-primary"}}function tv({isOpen:n,onClose:a,onConfirm:s,isLoading:i,uploadedFileName:o}){const{t:l}=Ze(),c=Fe(()=>[{id:"update",label:l("modal.saveVersion.updateCurrent"),description:l(o?"modal.saveVersion.updateWithFileDescription":"modal.saveVersion.updateDescription")},{id:"new-version",label:l("modal.saveVersion.createNew"),description:l(o?"modal.saveVersion.createWithFileDescription":"modal.saveVersion.createDescription")}],[l,o]),u=o?c[1]:c[0],[m,p]=Oe(u),[h,f]=Oe(""),g=new ev;He(()=>{n&&(p(u),f(""))},[u,n]);const v="new-version"===m?.id;return t(H,{isOpen:n,onClose:a,className:"sm:max-w-md",children:[e(G,{children:l("modal.saveChanges")}),e(J,{children:t("div",{className:"space-y-4",children:[o&&e("div",{className:"mb-4 p-3 bg-blue-50 dark:bg-blue-900/20 rounded-md",children:t("p",{className:"text-sm text-blue-700 dark:text-blue-300 font-medium",children:[l("modal.saveVersion.replaceFile")," ",e("span",{className:"font-bold",children:o})]})}),e("p",{className:"text-sm text-mixer-muted/5",children:l("modal.saveVersion.howToSave")}),e(se,{adapter:g,options:c,selected:m,onSelect:e=>{p(e)}}),v&&e(ie,{label:l("modal.saveVersion.versionLabel"),description:l("modal.saveVersion.versionLabelDescription"),className:"mt-3 ps-8",children:e(d,{value:h,onChange:f,placeholder:l("modal.saveVersion.versionLabelPlaceholder"),className:"w-full"})})]})}),t(Q,{children:[e(r,{variant:"secondary",onClick:a,disabled:i,children:l("modal.cancel")}),e(r,{variant:"primary",onClick:async()=>{await s(v,v?h:void 0)},isLoading:i,children:l("modal.save")})]})]})}function nv({isOpen:a,onClose:s,object:i,refetch:o}){const{client:l,store:c}=tr(),d=p(),{t:u}=Ze(),{theme:m}=le(),h=ia(),[f,g]=Oe(!1),[v,b]=Oe(""),[x,y]=Oe(!1),[w,N]=Oe(null),k=Be(void 0),[_,C]=Oe(null),[S,I]=Oe(null),z=Ve(async e=>{try{const t=await c.types.retrieve(e);t.object_schema&&C(t.object_schema)}catch(e){console.error("Failed to fetch JSON schema:",e)}},[c.types]);He(()=>{a&&(b(JSON.stringify(i.properties||{},null,2)),i.type?.id&&z(i.type.id))},[a,i,z]);return t(n,{children:[t(H,{isOpen:a,onClose:s,className:"sm:max-w-[90%] md:max-w-[80%] lg:max-w-[75%] xl:max-w-[70%]",children:[e(G,{children:u("store.editProperties")}),t(J,{children:[t("div",{className:"mb-2 text-sm text-gray-500",children:[i.type?.name?t("span",{children:["Editing properties for object type: ",e("strong",{children:i.type.name})]}):e("span",{children:u("store.editingGenericDocument")}),null!==_&&e("span",{className:"ms-2 text-green-600",children:"(JSON schema validation enabled)"})]}),e("div",{className:"h-[75vh] border rounded-md overflow-hidden",children:e(va,{value:v,language:"json",editorRef:k,onChange:e=>{return t=e.state.doc.toString(),void b(t);var t},beforeMount:e=>{_&&e.json.jsonDefaults.setDiagnosticsOptions({validate:!0,schemas:[{uri:"http://myserver/object-schema.json",fileMatch:["*"],schema:_}]})},theme:"dark"===m?"vs-dark":"vs"})})]}),t(Q,{children:[e(r,{variant:"secondary",onClick:s,children:"Cancel"}),e(r,{variant:"primary",onClick:function(){if(!k.current)return;const e=k.current.getValue();try{const t=JSON.parse(e);N(t),y(!0)}catch{d({status:"error",title:u("store.invalidJson"),description:u("store.pleaseFixJsonSyntax"),duration:5e3})}},children:"Save Changes"})]})]}),e(tv,{isOpen:x,onClose:function(){y(!1)},onConfirm:async function(e,t){try{g(!0);const n=w||JSON.parse(v);if(e){const e=await l.objects.update(i.id,{properties:n},{createRevision:!0,revisionLabel:t});e.id!==i.id&&I(e.id),d({status:"success",title:u("store.newVersionCreated"),description:u("store.newVersionCreatedDesc"),duration:2e3}),y(!1),s(),e.id!==i.id&&setTimeout(()=>{h(`/objects/${e.id}`),d({status:"info",title:u("store.viewingNewVersion"),description:t?u("store.viewingVersionLabel",{label:t}):u("store.viewingNewVersionDefault"),duration:3e3})},100)}else await c.objects.update(i.id,{properties:n}),d({status:"success",title:u("store.propertiesUpdated"),description:u("store.propertiesUpdatedDesc"),duration:2e3}),o&&await o(),y(!1),s()}catch(e){d({status:"error",title:u("store.errorUpdatingProperties"),description:T(e,u("store.errorUpdatingPropertiesDefault")),duration:5e3}),g(!1)}},isLoading:f})]})}function rv({object:a,text:s,onClose:i,onSaved:o}){const{store:l}=tr(),c=p(),{t:d}=Ze(),{theme:u}=le(),m=ia(),h=Be(void 0),[f,g]=Oe(!1),[v,b]=Oe(!1),[x,y]=Oe(!1),w=function(e){switch(e){case"text/markdown":return"markdown";case"application/json":return"json";case"application/xml":case"text/xml":return"xml";default:return"plaintext"}}(a.content?.type);console.log("Determined language for Monaco Editor:",w),console.log("TextEditorPanel rendered with object:",a,s);const N=Ve(()=>{f||g(!0)},[f]);return t(n,{children:[t("div",{className:"flex items-center gap-2 px-2 py-1 shrink-0",children:[f&&e("span",{className:"text-xs text-attention",children:d("store.unsavedChanges")}),e("div",{className:"flex-1"}),e(r,{variant:"ghost",size:"sm",onClick:i,disabled:v,children:d("store.cancelEdit")}),e(r,{variant:"secondary",size:"sm",onClick:function(){h.current&&y(!0)},disabled:!f,isLoading:v,children:d("store.saveText")})]}),e("div",{className:"flex-1 min-h-0 border rounded-md overflow-hidden mx-2 mb-2",children:e(va,{value:s,language:w,editorRef:h,onChange:N,theme:"dark"===u?"vs-dark":"vs",options:{wordWrap:"on",minimap:{enabled:!1},lineNumbers:"on",scrollBeyondLastLine:!1}})}),e(tv,{isOpen:x,onClose:()=>y(!1),onConfirm:async function(e,t){if(!h.current)return;const n=h.current.getValue(),r=a.content?.type||"text/plain",s=a.content?.name||"content.txt";try{b(!0);const u=new Blob([n],{type:r}),p=new File([u],s,{type:r}),h=await l.objects.update(a.id,{content:p},{createRevision:e,revisionLabel:t,ifMatch:a.content?.etag});c({status:"success",title:d("store.textSaved"),duration:2e3}),y(!1),e&&h.id!==a.id?(i(),setTimeout(()=>{m(`/objects/${h.id}`)},100)):o()}catch(e){const t=T(e,d("store.errorSavingTextDefault")),n=412===("object"==typeof e&&null!==e&&"status"in e?e.status:void 0)||t.includes("412");c({status:"error",title:d("store.errorSavingText"),description:n?d("store.textConflict"):t,duration:5e3})}finally{b(!1)}},isLoading:v})]})}const av=131072;function sv(e){return e===Nr.created||e===Nr.processing}function iv(e){return e.metadata?.content_processor?.type}function ov(e){return e?"h-full overflow-auto":"hidden"}var lv;function cv({object:n,loadText:r,refetch:a,canEditProperties:s=!0}){const i=p(),{t:o}=Ze(),l=async(e,t)=>{try{await navigator.clipboard.writeText(e),i({status:"success",title:o("store.contentCopied",{type:o("text"===t?"store.contentType":"store.properties")}),description:o("store.successfullyCopied",{type:t}),duration:2e3})}catch(e){console.error(`Failed to copy ${t}:`,e),i({status:"error",title:o("store.copyFailed"),description:o("store.failedToCopy",{type:t}),duration:5e3})}};return t(ne,{direction:"horizontal",className:"h-full",children:[e(re,{defaultSize:67,className:"min-w-[100px]",children:e(uv,{object:n,loadText:r??!1,handleCopyContent:l,refetch:a})}),e(ae,{withHandle:!0}),e(re,{defaultSize:33,className:"min-w-[100px]",children:e(dv,{object:n,refetch:a??(()=>Promise.resolve()),handleCopyContent:l,canEditProperties:s})})]})}function dv({object:a,refetch:s,handleCopyContent:i,canEditProperties:o}){const{t:l}=Ze(),[c,d]=Oe(!1),[u,m]=Oe(!1);return t(n,{children:[t("div",{className:"flex flex-col h-full",children:[t("div",{className:"flex justify-between items-center px-2",children:[t("div",{className:"flex items-center gap-1 bg-muted mb-2 p-1 rounded",children:[e(r,{variant:""+(c?"ghost":"primary"),size:"sm",title:l("store.previewProperties"),onClick:()=>d(!c),children:"Properties"}),e(r,{variant:""+(c?"primary":"ghost"),size:"sm",title:l("store.viewInJsonFormat"),onClick:()=>d(!c),children:"JSON"})]}),t("div",{className:"flex items-center gap-2",children:[a.properties&&e(r,{variant:"ghost",size:"sm",title:"Copy properties",onClick:()=>i(JSON.stringify(a.properties,null,2),"properties"),children:e(ot,{className:"size-4"})}),o&&e(Zg,{permission:kr.content_write,variant:"ghost",size:"sm",onClick:()=>{m(!0)},title:"Edit properties",className:"flex items-center gap-2",children:e(Gn,{className:"size-4"})})]})]}),a.properties?e("div",{className:"flex-1 min-h-0 px-2",children:e(ba,{value:a.properties,viewCode:c})}):e("div",{className:"flex-1 min-h-0 px-2",children:e("div",{children:l("store.noPropertiesDefined")})})]}),e(nv,{isOpen:u,onClose:()=>{m(!1)},object:a,refetch:s})]})}function uv({object:n,loadText:a,handleCopyContent:s,refetch:i}){const{t:o}=Ze(),l=n?.metadata?.type===yr.Image,c=n?.metadata?.type===yr.Video,d=n?.metadata?.type===yr.Audio,u="application/pdf"===n?.content?.type,m=!!n?.content?.type&&bh(n.content.type),p=sv(n?.status),h=!(!n.transcript||!c&&!d),f=n.metadata,g=f?.renditions?.find(e=>e.name===br),[v,b]=Oe(c?lv.Video:d?lv.Audio:l?lv.Image:lv.Text),[x,y]=Oe(v===lv.Pdf);He(()=>{v===lv.Pdf&&y(!0)},[v]);const[w,N]=Oe(!1),k=!(!n.content?.source||!n.content?.type||p||n.is_locked||!1===n.user_permissions?.can_write||!n.content.type.startsWith("text/")&&"application/json"!==n.content.type&&"application/xml"!==n.content.type),{fullText:_,displayText:C,isLoading:S,isCropped:T,loadText:I}=function(e,t,n=!1){const{store:r}=tr(),[a,s]=Oe(t),[i,o]=Oe(()=>t&&t.length>av?t.substring(0,av):t),[l,c]=Oe(!1),[d,u]=Oe(()=>!!t&&t.length>av),m=Ve(()=>{c(!0),r.objects.getObjectText(e).then(e=>{s(e.text),e.text&&e.text.length>av?(o(e.text.substring(0,av)),u(!0)):(o(e.text),u(!1))}).catch(e=>{console.error("Failed to load text",e),s(void 0),o(void 0),u(!1)}).finally(()=>{c(!1)})},[e,r]);return He(()=>{t&&t.length>av?(s(t),o(t.substring(0,av)),u(!0)):(s(t),o(t),u(!1)),n&&!t&&m()},[t,n,m]),{fullText:a,displayText:i,isLoading:l,isCropped:d,loadText:m}}(n.id,n.text,a),z=(u||m)&&p&&(v===lv.Text||v===lv.Pdf),{progress:R,status:j,outputFormat:P,isComplete:A}=function(e,t){const{client:n}=tr(),[r,a]=Oe({isComplete:!1});return He(()=>{if(!t)return;let r,s=!1;const i=(e,t,n,r)=>{a(a=>{const s=JSON.stringify(a.progress??null),i=JSON.stringify(e??null);return a.status===t&&a.outputFormat===n&&a.isComplete===r&&s===i?a:{progress:e,status:t,outputFormat:n,isComplete:r}})};return function t(){s||n.objects.analyze(e).getStatus().then(e=>{const n=e.output_format??e.progress?.output_format;e.status===gr.RUNNING?(i(e.progress,e.status,n,!1),s||(r=setTimeout(t,2e3))):i(e.progress,e.status,n,!0)}).catch(()=>{s||(r=setTimeout(t,1e4))})}(),()=>{s=!0,r&&clearTimeout(r)}},[t,e,n]),{progress:r.progress,status:r.status,outputFormat:r.outputFormat,isComplete:r.isComplete}}(n.id,z),{pdfUrl:D,isConverting:E,error:$,triggerConversion:L}=function(e,t){const{client:n}=tr(),r=Xe.getFixedT(null,et),[a,s]=Oe(),[i,o]=Oe(!1),[l,c]=Oe(),d=Ve(async()=>{if(!t||i)return;o(!0),c(void 0);const a=async t=>{try{const i=await n.objects.getRendition(e,{format:or.pdf,generate_if_missing:t,sign_url:!0,block_on_generation:!1});"generating"===i.status?setTimeout(()=>a(!1),5e3):"found"===i.status&&i.renditions?.length?(s(i.renditions[0]),o(!1)):"failed"===i.status&&(c(r("store.pdfConversionFailed")),o(!1))}catch(e){console.error("Failed to convert Office document to PDF:",e),c(r("store.failedToConvertToPdf")),o(!1)}};await a(!0)},[e,t,i,n,r]);return{pdfUrl:a,isConverting:i,error:l,triggerConversion:d}}(n.id,m);He(()=>{A&&j===gr.COMPLETED&&I()},[A,j,I]);const M=(u||m)&&p&&!A&&j===gr.RUNNING,F=v===lv.Pdf&&!M,O=M&&(v===lv.Text||v===lv.Pdf),U=x&&!M,W=Be(null);return t("div",{className:"flex flex-col h-full",children:[t("div",{className:"flex justify-between items-center px-2 shrink-0",children:[t("div",{className:"flex items-center gap-2 mb-2",children:[t("div",{className:"flex items-center gap-1 bg-muted p-1 rounded",children:[l&&e(r,{variant:v===lv.Image?"primary":"ghost",size:"sm",title:o("store.viewImage"),onClick:()=>b(lv.Image),children:"Image"}),c&&e(r,{variant:v===lv.Video?"primary":"ghost",size:"sm",title:o("store.viewVideo"),onClick:()=>b(lv.Video),children:"Video"}),d&&e(r,{variant:v===lv.Audio?"primary":"ghost",size:"sm",title:o("store.viewAudio"),onClick:()=>b(lv.Audio),children:"Audio"}),h&&e(r,{variant:v===lv.Transcript?"primary":"ghost",size:"sm",title:o("store.viewTranscript"),onClick:()=>b(lv.Transcript),children:"Transcript"}),e(r,{variant:v===lv.Text?"primary":"ghost",size:"sm",title:o("store.viewText"),onClick:()=>b(lv.Text),children:"Text"}),u&&e(r,{variant:v===lv.Pdf?"primary":"ghost",size:"sm",title:o("store.viewPdf"),onClick:()=>b(lv.Pdf),children:"PDF"}),m&&e(r,{variant:v===lv.Pdf?"primary":"ghost",size:"sm",title:o("store.viewAsPdf"),onClick:()=>{b(lv.Pdf),g||D||E||L()},disabled:E,children:E?e(K,{size:"sm"}):"PDF"})]}),e(fv,{object:n})]}),v===lv.Text&&!M&&!w&&e(mv,{object:n,text:C,fullText:_,handleCopyContent:s,textContainerRef:W,isEditing:w,onToggleEdit:()=>N(!0),canEdit:k}),v===lv.Pdf&&m&&(g||D)&&e(gv,{object:n,pdfRendition:g,officePdfUrl:D})]}),v===lv.Image&&e("div",{className:ov(!0),children:e(Ug,{object:n})}),v===lv.Video&&e("div",{className:ov(!0),children:e(Wg,{object:n})}),v===lv.Audio&&e("div",{className:ov(!0),children:e(Og,{object:n})}),h&&v===lv.Transcript&&e("div",{className:ov(!0),children:e(hv,{object:n,handleCopyContent:s})}),u&&U&&e("div",{className:ov(F),children:e(vv,{object:n})}),m&&U&&e("div",{className:ov(F),children:e(bv,{pdfRendition:g,officePdfUrl:D,officePdfConverting:E,officePdfError:$,onConvert:L})}),O&&e("div",{className:ov(!0),children:e(xv,{progress:R,status:j,outputFormat:P})}),v===lv.Text&&!M&&!w&&S&&e("div",{className:ov(!0),children:e("div",{className:"flex justify-center items-center flex-1",children:e(K,{size:"lg"})})}),v===lv.Text&&!M&&!w&&!S&&e("div",{className:ov(!0),children:e(pv,{object:n,text:C,isTextCropped:T,textContainerRef:W})}),w&&v===lv.Text&&null!=_&&e(rv,{object:n,text:_,onClose:()=>N(!1),onSaved:()=>{N(!1),I(),i?.()}})]})}function mv({object:a,text:s,fullText:i,handleCopyContent:o,onToggleEdit:l,canEdit:c}){const{client:d,project:u}=tr(),m=p(),{t:h}=Ze(),f=a.content,{renderDocument:b,isDownloading:x}=mc({client:d,toast:m}),{data:y}=S(()=>u?d.projects.retrieve(u.id):Promise.resolve(void 0),[u?.id]),w=y?.configuration?.pdf_template_object_id,N=f?.type&&"text/markdown"===f.type,k=iv(a),_=async(e,t)=>{if(x)return;m({status:"info",title:`Preparing ${e.toUpperCase()}`,description:h("store.renderingDocument"),duration:2e3});const n=!1!==t?w:void 0;await b(a.id,{format:e,title:a.name||"document",useDefaultTemplate:t,templateObjectId:n})};return e("div",{className:"h-[41px] text-lg font-semibold flex justify-between items-center px-2",children:t("div",{className:"flex items-center gap-2",children:[i&&t(n,{children:[e(r,{variant:"ghost",size:"sm",title:"Copy text",onClick:()=>o(i,"text"),children:e(ot,{className:"size-4"})}),c&&l&&e(Zg,{permission:kr.content_write,variant:"ghost",size:"sm",onClick:l,title:h("store.editText"),className:"flex items-center gap-2",children:e(Gn,{className:"size-4"})})]}),x?e(r,{variant:"ghost",size:"sm",disabled:!0,className:"flex items-center gap-2",title:"download",children:e(K,{size:"sm"})}):t(g,{trigger:e(r,{variant:"ghost",size:"sm",disabled:!s,className:"flex items-center gap-2",title:"download",children:e(lt,{className:"size-4"})}),children:[i&&e(v,{onClick:e=>{if(e.preventDefault(),e.stopPropagation(),!i)return;let t="txt",n="text/plain";"xml"===k?(t="xml",n="text/xml"):("markdown"===k||N)&&(t="md",n="text/markdown");const r=new Blob([i],{type:n}),s=URL.createObjectURL(r),o=`${a.name||"document"}.${t}`,l=document.createElement("a");l.href=s,l.download=o,l.style.display="none",setTimeout(()=>{l.click(),URL.revokeObjectURL(s)},0)},children:t("div",{className:"flex items-center gap-2",children:[e(lt,{className:"size-4"}),"Download Text"]})}),N&&s&&t(n,{children:[e(v,{onClick:()=>_(or.docx),children:t("div",{className:"flex items-center gap-2",children:[e(lt,{className:"size-4"}),"Export as DOCX"]})}),e(v,{onClick:()=>_(or.pdf,!1),children:t("div",{className:"flex items-center gap-2",children:[e(lt,{className:"size-4"}),"Export as PDF"]})}),e(v,{onClick:()=>_(or.pdf),children:t("div",{className:"flex items-center gap-2",children:[e(lt,{className:"size-4"}),"Export as Branded PDF"]})})]})]})]})})}!function(e){e.Text="text",e.Image="image",e.Video="video",e.Audio="audio",e.Pdf="pdf",e.Transcript="transcript"}(lv||(lv={}));const pv=qe(({object:r,text:a,isTextCropped:s,textContainerRef:i})=>{const{t:o}=Ze(),l=r.content,c=sv(r?.status),d="xml"===iv(r),u=l?.type&&("text/markdown"===l.type||"text/plain"===l.type),m=!d&&(u||function(e){return!!e&&(e.includes("\n# ")||e.includes("\n## ")||e.includes("\n### ")||e.includes("\n* ")||e.includes("\n- ")||e.includes("\n+ ")||e.includes(")}(a));return a?t(n,{children:[s&&e("div",{className:"px-2 py-2 bg-attention/10 border-s-4 border-attention mx-2 mb-2 rounded",children:t("div",{className:"flex items-center gap-2 text-attention",children:[e(Gt,{className:"size-4"}),e("span",{className:"text-sm font-semibold",children:o("store.showingFirst128K")})]})}),e("div",{className:"max-w-7xl px-2 h-full overflow-auto",ref:i,children:d?e("div",{className:"px-4 py-2",children:e(fa,{xml:a,collapsible:!0})}):m?e("div",{className:"vprose prose-sm p-1",children:e(oa,{components:{a:({node:t,...n})=>{const r=n.href||"";return r.includes("/store/objects/")?e(sa,{topLevelNav:!0,href:r,className:"text-info",children:n.children}):e("a",{...n,target:"_blank",rel:"noopener noreferrer"})},p:({node:t,...n})=>e("p",{...n,className:"my-0"}),pre:({node:t,...n})=>e("pre",{...n,className:"my-2 p-2 rounded"}),code:({node:t,className:n,children:r,...a})=>{const s=/language-(\w+)/.exec(n||"");return e("code",{...a,className:s?"text-muted":"px-1.5 py-0.5 rounded",children:r})},h1:({node:t,...n})=>e("h1",{...n,className:"font-bold text-2xl my-2"}),h2:({node:t,...n})=>e("h2",{...n,className:"font-bold text-xl my-2"}),h3:({node:t,...n})=>e("h3",{...n,className:"font-bold text-lg my-2"}),li:({node:t,...n})=>e("li",{...n})},children:a})}):e("pre",{className:"text-wrap bg-muted text-muted p-2",children:a})})]}):e("div",{className:"px-2",children:e("div",{children:c?"Extracting content...":"No content"})})});function hv({object:n,handleCopyContent:a}){const{t:s}=Ze(),i=n.transcript,o=i?.text,l=i?.segments,c=o||(l?l.map(e=>e.text).join(" "):""),d=e=>{const t=Math.floor(e/3600),n=Math.floor(e%3600/60),r=Math.floor(e%60);return t>0?`${t}:${n.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}`:`${n}:${r.toString().padStart(2,"0")}`};return t("div",{className:"flex flex-col h-full",children:[e("div",{className:"flex justify-end items-center px-2 mb-2",children:c&&e(r,{variant:"ghost",size:"sm",title:"Copy transcript",onClick:()=>a(c,"text"),children:e(ot,{className:"size-4"})})}),e("div",{className:"h-full} overflow-auto px-2",children:l&&l.length>0?e("div",{className:"space-y-2",children:l.map((n,r)=>t("div",{className:"flex gap-3 text-sm",children:[t("span",{className:"text-muted font-mono text-xs shrink-0 pt-0.5",children:[d(n.start),n.end&&` - ${d(n.end)}`]}),e("span",{className:"flex-1",children:n.text})]},r))}):o?e("pre",{className:"text-wrap bg-muted text-muted p-2 whitespace-pre-wrap",children:o}):e("div",{className:"text-muted",children:s("store.noTranscriptAvailable")})})]})}function fv({object:a}){const[s,i]=Oe(!1),o=iv(a);return"xml"===o||"markdown"===o?t(n,{children:[e(r,{variant:"ghost",size:"sm",onClick:()=>i(!0),title:"Side by side view",children:e(Jn,{className:"size-4"})}),s&&e(ce,{children:e(Dg,{objectId:a.id,onClose:()=>i(!1)})})]}):null}function gv({object:t,pdfRendition:n,officePdfUrl:a}){const{client:s}=tr(),i=p(),{t:o}=Ze(),[l,c]=Oe(!1);return e("div",{className:"flex items-center gap-2",children:e(r,{variant:"ghost",size:"sm",onClick:async()=>{c(!0);try{let e=a;if(!e&&n?.content?.source){e=(await s.files.getDownloadUrl(n.content.source,`${t.name||"document"}.pdf`,"attachment")).url}e&&window.open(e,"_blank")}catch(e){console.error("Failed to download PDF:",e),i({status:"error",title:o("store.downloadFailed"),description:o("store.failedToDownloadPdf"),duration:5e3})}finally{c(!1)}},disabled:l,title:"Download PDF",children:l?e(K,{size:"sm"}):e(lt,{className:"size-4"})})})}function vv({object:t}){return e("div",{className:"h-full",children:e(Vg,{object:t,className:"h-full"})})}function bv({pdfRendition:n,officePdfUrl:a,officePdfConverting:s,officePdfError:i,onConvert:o}){const{t:l}=Ze();return s?t("div",{className:"flex flex-col justify-center items-center flex-1 gap-2",children:[e(K,{size:"lg"}),e("span",{className:"text-muted",children:l("store.convertingToPdf")})]}):i?t("div",{className:"flex flex-col justify-center items-center flex-1 gap-2 text-destructive",children:[e(Gt,{className:"size-8"}),e("span",{children:i})]}):e("div",n?.content?.source?{className:"h-full",children:e(Vg,{source:n.content.source,className:"h-full"})}:a?{className:"h-full",children:e(Vg,{url:a,className:"h-full"})}:{className:"flex flex-col justify-center items-center flex-1 gap-2",children:e(r,{onClick:o,children:"Convert to PDF"})})}function xv({progress:r,status:a,outputFormat:s}){const{t:i}=Ze(),o=Sh(a),l=Th(a),c="xml"===s,d=null==r?.percent||Number.isNaN(r.percent)?0:r.percent;return t("div",{className:"px-4 py-4",children:[r&&t("div",{className:"space-y-2",children:[t("div",{className:"flex flex-col gap-1",children:[e(yv,{name:c?"Analyze Layouts":"Analyze Page",progress:r.pages}),c&&t(n,{children:[e(yv,{name:"Extract Tables",progress:r.tables}),e(yv,{name:"Describe Images",progress:r.images}),e(yv,{name:"Process Visually",progress:r.visuals})]})]}),t("div",{className:"pt-2 text-sm text-muted",children:["Progress: ",d,"%",e("span",{className:"px-2",children:"•"}),e("span",{className:o,children:l}),r.started_at&&t(n,{children:[e("span",{className:"px-2",children:"•"}),t("span",{children:[((Date.now()-r.started_at)/1e3).toFixed(0)," sec. elapsed"]})]})]}),e(xa,{percent:d})]}),!r&&t("div",{className:"flex items-center gap-2 text-muted",children:[e(K,{size:"sm"}),e("span",{children:i("store.loadingProcessingStatus")})]})]})}function yv({name:e,progress:n}){return t("div",{className:"flex gap-2 text-sm",children:[t("span",{className:"text-muted min-w-36",children:[e,":"]}),t("span",{children:[n.processed," of ",n.total]})]})}const wv=Object.values(_r),Nv=Object.values(Cr);function kv({onChange:n,isLoading:a,refresh:s,searchTypes:i}){const{client:o,project:l}=tr(),{t:c}=Ze(),u=p(),[m,h]=Oe(void 0),[f,g]=Oe(void 0),v=!(!l||!f?.embeddings.text&&!f?.embeddings.image),[b,x]=Oe(void 0),y=Be(s),w=Be(void 0),[N,k]=Oe(!1),[_,C]=Oe(i||wv),[S,T]=Oe(100);He(()=>{i&&C(i)},[i]);const I={};let z=!1,R=!1;_.forEach(e=>{e===_r.full_text?z=!0:R=!0,Nv.includes(e)&&(I[e]=!0)}),He(()=>{y.current!==s&&(y.current=s,h(void 0),x(void 0))}),He(()=>{l&&o.projects.retrieve(l.id).then(e=>{g(e.configuration)})},[o.projects.retrieve,l]),He(()=>{b&&u({title:b,status:"success",duration:2e3})},[b,u]),He(()=>{const e=w.current;w.current=m,!e||m&&0!==m.length||n(void 0)},[n,m]);const j=()=>{if(!v||!m)return;n({vector:R?{text:m,config:I}:void 0,full_text:z?m:void 0,limit:S}),x("Searching...")},P=e=>t=>{C(t?t=>Array.from(new Set([...t,e])):t=>t.filter(t=>t!==e))};return t("div",{className:"flex gap-1 items-center",children:[e(d,{placeholder:c("store.searchPlaceholder"),value:m,onChange:h,onKeyDown:e=>{"Enter"===e.key&&j()},className:"min-w-[200px]"}),e(r,{variant:"ghost",onClick:()=>k(!0),title:c("store.semanticSearchSettings"),className:"ms-1",children:e(Kn,{size:18})}),t(H,{isOpen:N,onClose:()=>k(!1),children:[e(G,{children:c("store.searchTypes")}),e(J,{children:t("div",{className:"flex flex-col gap-2",children:[t("div",{className:"flex items-center gap-2",children:[e(de,{id:"search-type-full_text",checked:_.includes(_r.full_text),onCheckedChange:P(_r.full_text)}),e(ue,{htmlFor:"search-type-full_text",children:c("store.fullText")})]}),e("div",{className:"font-semibold mt-2 mb-1",children:c("store.embeddings")}),Nv.map(n=>t("div",{className:"flex items-center gap-2",children:[e(de,{id:`search-type-${n}`,checked:_.includes(n),onCheckedChange:P(n)}),e(ue,{htmlFor:`search-type-${n}`,children:n.charAt(0).toUpperCase()+n.slice(1)})]},n)),t("div",{className:"mt-3",children:[e("span",{className:"me-2",children:c("store.limit")}),e(me,{type:"number",min:1,value:S,onChange:e=>T(Number(e??100)),style:{width:80}})]})]})}),e(Q,{children:e(r,{variant:"outline",onClick:()=>k(!1),children:c("store.close")})})]}),e(r,{variant:"secondary",isLoading:a,onClick:j,isDisabled:!v,title:c("store.semanticSearch"),children:c("store.search")})]})}const _v=[{name:"ID",field:"id",type:"objectId?slice=-7"},{name:"Name",field:".",type:"objectName"},{name:"Type",field:"type.name",type:"string"},{name:"Status",field:"status",type:"string"},{name:"Updated At",field:"updated_at",type:"date"}];function Cv({onUploadDone:t=async()=>{},layout:n}){const r=Bh(),a=p(),{t:s}=Ze(),i=Zh(Ve(async e=>{await t(e),setTimeout(()=>{console.log("Delayed refresh after upload to ensure backend consistency"),r.search().then(e=>{e&&a({title:s("store.documentListRefreshed"),description:s("store.documentListRefreshedDesc"),status:"info",duration:3e3})}).catch(e=>{console.error("Failed to refresh search results:",e)})},1e3)},[t,r,s,a])),o=Ve((e,t)=>{const n=r.collectionId;return i(e,t,n)},[r,i]);return e(Sv,{layout:n,onUpload:o})}function Sv({layout:n,onUpload:r,allowFilter:a=!0,allowSearch:s=!0}){const{t:i}=Ze(),o=Bh(),[l,c]=Oe(!1),[d,u]=Oe(null),{registry:m}=yp(),{search:p,isLoading:h,error:f,objects:g,hasMore:v}=qh(),[b,y]=Oe(m?n||(w=m,((N=p.query.type)?w.getTypeLayout(N):_v)??_v):_v);var w,N;He(()=>{n&&y(n)},[n]);const[k,_]=Oe(0),[C,S]=Oe(0),[T,I]=Oe("grid"===localStorage.getItem(sf.LAST_DISPLAYED_VIEW)),[z,R]=Oe([]),j=Be(null),P=Be(null),A=Ve((e,t)=>{c(!1),e.catch(e=>{console.error(t,e)}).finally(()=>{c(!0)})},[]);He(()=>{let e=!1;return p.initialized?(c(!0),()=>{e=!0}):(c(!1),S(0),p.search().catch(t=>{e||console.error("Initial search failed:",t)}).finally(()=>{e||c(!0)}),()=>{e=!0})},[p]),He(()=>{g.length<C&&S(g.length)},[g.length,C]),Z(j,()=>{l&&g.length>0&&g.length!==C&&(c(!1),p.loadMore().catch(e=>{console.error("Failed to load more search results:",e)}).finally(()=>{S(g.length),c(!0)}))},{deps:[l,g.length]});const D=Vh(),E=Bh(),$=Sp(D),L=Tp(E),M=e=>{const t="function"==typeof e?e(z):e;R(t),L(t)},F=new URL(window.location.href),O=F.searchParams.get("filters");if(O)try{const e=O.split(";"),t=e.filter(e=>{const[t]=e.split(":"),n=decodeURIComponent(t);return"start"!==n&&"end"!==n});if(t.length!==e.length){const e=t.length>0?t.join(";"):"";e?F.searchParams.set("filters",e):F.searchParams.delete("filters"),window.history.replaceState(window.history.state||{},"",F.toString())}}catch(f){console.error("Failed to clean start/end filters from URL:",f)}const U=ia();return t("div",{className:"flex flex-col gap-y-2 flex-1 min-h-0 ",children:[e(Iv,{object:d,onClose:()=>u(null)}),f&&e(x,{title:i("store.error"),children:f.message}),e(Tv,{isLoading:h,refreshTrigger:k,allowFilter:a,allowSearch:s,filterGroups:$,filters:z,handleFilterChange:M,handleVectorSearch:e=>{if(e?.vector){if(p.query.vector=e.vector,p.query.full_text=e.full_text,p.query.weights=e.weights,p.query.score_aggregation=e.score_aggregation,p.query.dynamic_scaling=e.dynamic_scaling,void 0!==e.limit&&(p.limit=e.limit,p.query.limit=e.limit),!b.find(e=>"Search Score"===e.name)){const e=[...b,{name:"Search Score",field:"score",render:e=>"number"==typeof e.score?e.score.toFixed(4):"0.0000"}];y(e)}A(p.search(),"Vector search failed:")}else e?.full_text?(p.query.full_text=e.full_text,void 0!==e.limit&&(p.limit=e.limit,p.query.limit=e.limit),A(p.search(),"Text search failed:")):void 0===e&&l&&(delete p.query.vector,delete p.query.full_text,A(p.search(),"Search reset failed:"))},handleRefetch:()=>{A(p.search(),"Search refresh failed:")},setIsGridView:I}),e("div",{className:"flex flex-col w-full flex-1 min-h-0 border rounded-md mb-2",children:t("div",{ref:P,className:"flex-1 min-h-0 overflow-y-auto",children:[e(ih,{onFilter:(e,t)=>{const n=$.find(t=>t.name===e),r={name:e,type:n?.type,placeholder:n?.placeholder,multiple:n?.multiple};M(a=>{const s=a.filter(t=>t.name!==e);if("stringList"===n?.type||Array.isArray(t)){const n=Array.isArray(t)?t:[t],i=a.find(t=>t.name===e)?.value??[];return[...s,{...r,value:Array.from(new Set([...i,...n]))}]}return[...s,{...r,value:[{value:t,label:t}]}]})},children:e(ef,{objects:g,isLoading:!g.length&&h,layout:b,onRowClick:e=>{U(`/objects/${e.id}`)},previewObject:e=>{const t=g.find(t=>t.id===e)||null;u(t)},selectedObject:d,onUpload:r,isGridView:T,collectionId:o.collectionId})}),e("div",v?{ref:j,className:"w-full flex justify-center",children:e(K,{size:"xl"})}:{className:"text-muted text-center text-sm py-1",children:`All ${g.length} objects loaded.`})]})})]})}function Tv(n){const{t:a}=Ze(),{isLoading:s,refreshTrigger:i,allowFilter:o,allowSearch:l,filterGroups:c,filters:d,handleFilterChange:u,handleVectorSearch:m,handleRefetch:p,setIsGridView:h}=n;return t("div",{className:"sticky top-0 z-10 bg-background py-2 flex justify-between items-center",children:[o?e(j,{filterGroups:c,filters:d,setFilters:u,children:t("div",{children:[e("div",{className:"flex flex-row gap-4 items-center justify-between w-full",children:t("div",{className:"flex gap-2 items-center w-2/3",children:[l&&e(kv,{onChange:m,isLoading:s,refresh:i,className:"w-full"}),e(P,{})]})}),t("div",{className:"flex gap-2 items-center pt-2",children:[e(A,{}),e(D,{})]})]})}):e("div",{className:"flex flex-row gap-4 items-center justify-between w-full",children:e("div",{className:"flex gap-2 items-center w-2/3",children:l&&e(kv,{onChange:m,isLoading:s,refresh:i})})}),t("div",{className:"flex gap-1 items-center",children:[e(r,{variant:"outline",onClick:p,title:a("store.refresh"),children:e(Tn,{size:16})}),e(sf,{onUpdate:h})]})]})}function Iv({object:n,onClose:a}){const{store:s}=tr(),i=p(),o=ia(),{downloadFromContentSource:l}=mc({client:s,toast:i}),c=n?.content?.source,d="string"==typeof n?.properties?.title?n.properties.title:n?.name;return n?t(pe,{title:d,isOpen:!0,onClose:a,children:[t("div",{className:"flex items-center gap-x-2",children:[e(r,{variant:"ghost",size:"sm",title:"Open Object",onClick:()=>o(`/objects/${n.id}`),children:e($t,{className:"size-4"})}),c&&e(r,{variant:"ghost",size:"sm",title:"Download",onClick:()=>l(c,n.name||n.content?.name),children:e(lt,{className:"size-4"})})]}),e(he,{className:"my-2"}),e("div",{className:"pt-2",children:e(cv,{object:n,loadText:!0},n.id)})]}):null}const zv=[{name:"ID",field:"id",type:"objectId?slice=-7"},{name:"Name",field:".",type:"objectName"},{name:"Revision",field:".",type:"revision"},{name:"Type",field:"type.name",type:"string"},{name:"Status",field:"status",type:"string"},{name:"Updated At",field:"updated_at",type:"date"}];function Rv({collection:t}){const n=p(),{client:r}=tr(),{registry:a}=yp(),s=function(e,t){let n=e.table_layout;if(n&&n.length>0)return n;e.type&&t&&(n=t?.getTypeLayout(Sr(e.type)));return n&&n.length>0?n:zv}(t,a);return e("div",{className:"flex flex-col h-full",children:t.dynamic?e(Sv,{layout:s}):e(Cv,{onUploadDone:async e=>{e.length>0&&await r.store.collections.addMembers(t.id,e).catch(e=>{n({title:"Failed to add objects to collection",description:e.message,status:"error"})})},layout:s})})}function jv({className:n,defaultValue:r,onChange:a,isClearable:s,multiple:i}){const{t:o}=Ze(),{registry:l}=yp(),[c,d]=Oe(!1),u=n=>null===n?o("store.none"):t("div",{children:[e("div",{className:"text-sm",children:n.name}),e("div",{className:"text-xs text-muted truncate",children:n.description})]}),[m,p]=Oe(),[h,f]=Oe([]);He(()=>{if(!c&&(d(!0),l&&r)){if(i&&Array.isArray(r)){const e=l.types.filter(e=>r.includes(e.id));f(e)}const e=l.types.find(e=>e.id===r);e&&p(e)}},[c,l,r,i]);const g=e=>{f(e),a(e)};return e("div",i?{className:"flex flex-col gap-4 content-between",children:e($,{options:l?.types||[],value:h,onChange:g,placeholder:o("store.chooseContentTypes"),optionLabel:u,className:n||"text-sm bg-background",filterBy:"name",isClearable:s||!1,multiple:!0})}:{className:"flex flex-col gap-4 content-between",children:e($,{options:l?.types||[],value:m,onChange:e=>{p(e||void 0),a(e)},placeholder:o("store.chooseContentType"),optionLabel:u,className:n||"text-sm bg-background",filterBy:"name",isClearable:s||!1})})}function Pv({onClose:a,redirect:s=!0,onAddToCollection:i}){const o=ia(),l=p(),{t:c}=Ze(),[u,m]=Oe(!1),{client:h}=tr(),[f,g]=Oe({dynamic:!1,name:"",description:""});function v(e,t){g({...f,[e]:t})}return t(n,{children:[e(J,{children:t("form",{onSubmit:e=>e.preventDefault(),children:[e(ie,{label:c("type.name"),required:!0,children:e(d,{type:"text",value:f.name||"",onChange:e=>v("name",e)})}),e(ie,{label:c("type.description"),className:"mt-2",children:e(X,{value:f.description||"",onChange:e=>v("description",e.target.value)})}),e(ie,{label:c("store.dynamicCollection"),className:"mt-2",direction:"row",description:c("store.dynamicCollectionDescription"),children:e(fe,{value:f.dynamic||!1,onChange:e=>v("dynamic",e)})}),!f.dynamic&&e(ie,{label:c("store.allowedContentTypes"),className:"mt-4",description:c("store.allowedContentTypesOptionalDescription"),children:e(jv,{defaultValue:f.allowed_types||null,onChange:e=>{Array.isArray(e)?v("allowed_types",e.map(e=>e.id)):v("allowed_types",e?[e.id]:[])},isClearable:!0,multiple:!0})}),e(ie,{label:c("store.contentType"),className:"mt-2",description:c("store.typeDescription"),children:e(jv,{defaultValue:f.type||null,onChange:e=>{Array.isArray(e)?v("type",e.length>0?e[0].id:null):v("type",e?.id||null)},isClearable:!0})})]})}),e(Q,{children:e(r,{isDisabled:u,onClick:()=>{f?.name?.trim()?(f.name=f.name.trim(),f.description&&(f.description=f.description.trim()),null==f.dynamic&&(f.dynamic=!1),m(!0),h.store.collections.create(f).then(e=>{a(),l({title:c("store.collectionCreated"),description:`Collection "${e.name}" created successfully`,status:"success",duration:3e3}),s&&o(`/collections/${e.id}`),i&&i(e.id)}).catch(e=>{l({title:c("store.failedToCreateCollection"),description:e.message,status:"error",duration:5e3})}).finally(()=>m(!1))):l({title:c("type.nameRequired"),description:c("store.pleaseProvideName"),status:"error",duration:5e3})},children:c("store.createCollection")})})]})}function Av({isOpen:n,onClose:r}){const{t:a}=Ze();return t(H,{onClose:r,isOpen:n,children:[e(G,{children:a("store.createACollection")}),e(Pv,{onClose:r})]})}function Dv(){const{client:a}=tr(),s=p(),{t:i}=Ze(),[o,l]=Oe(),[c,d]=Oe(!0),[u,m]=Oe(!1),{data:h,error:f,refetch:g}=S(()=>a.store.collections.search({}),[]);if(He(()=>{(h||f)&&d(!1)},[h,f]),f)return e(x,{title:i("store.collectionFetchFailed"),children:T(f)});return t(n,{children:[h&&(h.length>0?t(C,{className:"w-full",children:[e("thead",{children:t("tr",{children:[e("th",{children:i("type.name")}),e("th",{children:i("type.type")}),e("th",{children:i("store.created")}),e("th",{})]})}),e(B,{columns:4,isLoading:c,children:h.map(n=>t(ge,{children:[e("td",{children:t("div",{className:"flex items-center gap-2",children:[e(Ev,{isDynamic:n.dynamic}),e(sa,{href:`/collections/${n.id}`,children:n.name})]})}),e("td",{children:n.type?.name||"-"}),e("td",{children:Dr(n.created_at).fromNow()}),e("td",{className:"text-end",children:e(r,{variant:"destructive",size:"sm",onClick:()=>l(n.id),children:e(Qn,{className:"size-4"})})})]},n.id))})]}):e(ve,{title:i("store.noCollections"),buttonLabel:i("store.newCollections"),onClick:()=>m(!0),children:i("store.getStartedCollections")})),e(Av,{isOpen:u,onClose:()=>m(!1)}),e(be,{isOpen:!!o,title:i("store.deleteCollection"),content:i("store.areYouSureDeleteCollection"),onConfirm:async()=>{if(o)try{await a.store.collections.delete(o),s({title:i("store.collectionDeleted"),status:"success",duration:3e3}),g()}catch(e){console.error("Failed to delete collection:",e),s({title:i("store.failedToDeleteCollection"),description:T(e),status:"error",duration:5e3})}finally{l(void 0)}},onCancel:()=>l(void 0)})]})}function Ev({isDynamic:t}){const{t:n}=Ze(),r=n(t?"store.dynamicCollection":"store.staticCollection"),a=e(t?bt:Yn,{className:"size-5"});return e(h,{description:r,className:"me-2",children:a})}Dr.extend(Ta),Dr.extend(Ta);const $v="h-6 w-6 p-0 opacity-0 group-hover/field:opacity-100 text-muted hover:text-foreground transition-opacity shrink-0";function Lv({objects:n,isLoading:a,onFilter:s}){const{t:i}=Ze(),o=ia();return t(C,{className:"w-full",children:[e(W,{children:t("tr",{children:[e("th",{children:i("store.name")}),e("th",{children:i("store.strictMode")}),e("th",{children:i("store.semanticChunking")}),e("th",{children:i("store.updatedAt")})]})}),e(B,{isLoading:a&&(!n||0===n.length),columns:4,children:n?.map(n=>t("tr",{onClick:()=>o(`/types/${n.id}`),className:"cursor-pointer hover:bg-muted",children:[e("td",{className:"group/field",children:t("div",{className:"flex items-center gap-2 min-w-0",children:[e("span",{className:"truncate",children:n.name}),e(M,{content:n.id,className:$v}),s&&e(r,{variant:"ghost",size:"sm",title:`Filter by ${n.name}`,className:$v,onClick:e=>{e.stopPropagation(),s("name",n.name)},children:e(In,{className:"size-3"})})]})}),e("td",{children:n.strict_mode?"Yes":"No"}),e("td",{children:n.is_chunkable?"Yes":"No"}),e("td",{children:e(h,{description:Dr(n.updated_at).format("YYYY-MM-DD HH:mm:ss"),children:Dr(n.updated_at).fromNow()})})]},n.id))})]})}function Mv({title:n,isOpen:a,onClose:s,okLabel:i,initialPayload:o,isLoading:l}){const{t:c}=Ze(),u=p(),[m,h]=Oe(o?.name),[f,g]=Oe(o?.description),v=o?.strict_mode??!1;return t(H,{isOpen:a,onClose:()=>s(),children:[e(G,{children:n}),e(J,{className:"pt-0",children:t("div",{className:"h-full flex flex-col gap-4 content-between",children:[t("div",{children:[e("div",{className:"block text-sm font-medium text-muted",children:c("type.name")}),e(d,{value:m,onChange:h})]}),t("div",{children:[e("div",{className:"block text-sm font-medium text-muted",children:c("type.description")}),e(X,{value:f,onChange:e=>g(e.target.value),minLines:5})]})]})}),e(Q,{children:t("div",{className:"flex justify-end gap-4",children:[e(r,{variant:"secondary",onClick:()=>s(),children:c("modal.cancel")}),e(r,{variant:"primary",onClick:()=>(()=>{if(!m)return void u({status:"error",title:c("type.nameRequired"),duration:5e3});s({name:m,description:f,strict_mode:v}).then(()=>s())})(),isLoading:l,children:i})]})})]})}class Fv{client;limit;result=new V({objects:[],isLoading:!1});query={};constructor(e,t=100){this.client=e,this.limit=t}get objects(){return this.result.value.objects}get error(){return this.result.value.error}get isRunning(){return this.result.value.isLoading}getFilterValue(e){return this.query[e]}setFilterValue(e,t){this.query[e]=t,this.search()}reset(e=!1){this.result.value={objects:[],isLoading:e}}_updateRunningState(e){const t=this.result.value;this.result.value={objects:t.objects,isLoading:e,error:t.error}}async _search(e=!1){if(this.isRunning)return Promise.resolve(!1);this.result.value={isLoading:!0,objects:e?this.objects:[]};const t=this.limit,n=this.objects.length;return this.client.types.list({limit:t,offset:n,query:this.query}).then(async e=>(this.result.value={isLoading:!1,objects:this.objects.concat(e)},!0)).catch(e=>{throw this.result.value={error:e,isLoading:!1,objects:this.objects},e})}search(){return this.isRunning?Promise.resolve(!1):this._search(!1)}loadMore(){return this.isRunning?Promise.resolve(!1):this._search(!0)}}const Ov=Ue(void 0);function Uv(){return We(Ov)}function Wv(){const e=Uv();return{...q(e.result),search:e}}function Bv(){return Uv().objects.length}var Vv;function qv({isDirty:r=!1}){const{store:a}=tr(),{reload:s}=yp(),{t:i}=Ze(),o=p(),[l,c]=Oe(!1),{search:u,isLoading:m,error:h,objects:f}=Wv(),[g,v]=Oe(""),b=xe(g,500),y=Be(null);Z(y,()=>{l&&u.loadMore()},{deps:[l,u]}),He(()=>{u.search().then(()=>c(!0))},[u]),He(()=>{u.query.name=b,u.search().then(()=>c(!0))},[b,u]);const[w,N]=Oe(void 0);He(()=>{u.query.chunkable=w?"Yes"===w:void 0,u.search().then(()=>c(!0))},[w,u]),He(()=>{r&&l&&u.search().then(()=>c(!0))},[r,l,u]);const[k,_]=Oe(!1);if(h)return e(x,{title:i("store.failedToFetchTypes"),children:h.message});return t("div",{className:"flex flex-col flex-1 min-h-0",children:[t("div",{className:"flex flex-shrink-0 gap-4",children:[e(d,{placeholder:i("store.filterByName"),value:g,onChange:v}),e($,{className:"w-60",isClearable:!0,options:Object.values(Vv),value:w,onChange:e=>{N(e)},placeholder:i("store.isChunkable")})]}),e("div",{className:"flex flex-col w-full flex-1 min-h-0 border rounded-md my-2",children:t("div",{className:"flex-1 min-h-0 overflow-y-auto",children:[m||0!==f?.length?t(n,{children:[e(Lv,{objects:f,isLoading:m,onFilter:(e,t)=>{"name"===e&&v(t)}}),e("div",{ref:y,className:"h-4 w-full"})]}):e(ve,{title:i("store.noType"),buttonLabel:i("store.createType"),onClick:()=>{_(!0)},children:i("store.getStartedTypes")}),e(Mv,{okLabel:"Create",title:i("store.createType"),isOpen:k,onClose:async e=>e?a.types.create(e).then(async()=>{o({status:"success",title:i("store.typeCreated"),duration:2e3}),s(),u.search().then(()=>c(!0))}).catch(e=>{o({status:"error",title:i("store.errorCreatingType"),description:e.message,duration:5e3})}):(_(!1),Promise.resolve())})]})})]})}function Hv({objectType:n,onSchemaUpdate:a,readonly:s=!1}){const{store:i}=tr(),{t:o}=Ze(),l=p(),{theme:c}=le(),[d,u]=Oe(!1),m=ya(n.object_schema),h=Be(void 0),[f,g]=Oe(!1),v=Fe(()=>function(e){if(!e)return"";return JSON.stringify(e,null,2)}(m.schema),[m]),b=()=>{if(h.current){const e=h.current.getValue();try{const t=function(e){if(!e?.trim())return;return JSON.parse(e.trim())}(e);Gv(t),m.replaceSchema(t)}catch(e){return l({status:"error",title:o("store.invalidJsonSchema"),description:T(e),duration:5e3}),!1}}return!0},x=t("div",{className:"flex gap-2 items-center",children:[e("div",{className:"text-base font-semibold",children:o("store.schemaEditor")}),!s&&e("div",{children:e(r,{variant:"outline",size:"sm",onClick:()=>{f&&!b()||g(e=>!e)},children:o(f?"store.editSchema":"store.editJson")})})]});return e(ye,{title:x,className:"bg-background! h-full",action:s?void 0:e(r,{isLoading:d,variant:"outline",size:"sm",onClick:()=>{f&&!b()||(u(!0),i.types.update(n.id,{object_schema:m.schema}).then(()=>{a(m),l({status:"success",title:o("store.schemaUpdated"),description:o("store.schemaUpdatedSuccess"),duration:2e3})}).catch(e=>{l({status:"error",title:o("store.failedToUpdateSchema"),description:e.message,duration:5e3})}).finally(()=>{u(!1)}))},children:o("modal.saveChanges")}),children:f?e(va,{value:v,language:"json",editorRef:h,theme:"dark"===c?"vs-dark":"vs",options:{readOnly:s}}):e(wa,{schema:m,readonly:s})})}!function(e){e.true="Yes",e.false="No"}(Vv||(Vv={}));const Gv=e=>{try{new Ca({strict:!1}).compile(e)}catch(e){throw new Error(`Invalid JSON Schema definition: ${T(e)}`,{cause:e})}};function Jv({isOpen:n,onClose:a,title:s,children:i,initialSelectedType:o=null,allowNone:l=!0}){const{t:c}=Ze(),d=s??c("store.selectContentType"),{registry:u}=yp(),[m,p]=Oe(o),f=u?.types||[],g=()=>{a(void 0)};return t(H,{isOpen:n,onClose:g,className:"w-full max-w-xl mx-auto",children:[e(G,{children:d}),t(J,{children:[i,t("div",{className:"mb-4 mt-4",children:[t("div",{className:"block text-sm font-medium mb-2",children:[c("store.contentType")," ",l&&e("span",{className:"text-gray-500 font-normal",children:c("store.optional")})]}),e($,l?{options:f,value:m,optionLabel:e=>e?e.name:c("store.selectContentTypeLabel"),placeholder:c("store.selectContentTypeAuto"),onChange:e=>p(e||null),filterBy:"name",isClearable:!0}:{options:f,value:m,optionLabel:e=>e?e.name:c("store.selectContentTypeLabel"),placeholder:c("store.selectContentTypeLabel"),onChange:e=>p(e||null),filterBy:"name"})]}),!m&&t("div",{className:"flex items-center text-attention",children:[e(bn,{className:"size-4 me-1"}),c("store.automaticTypeDetection"),e(h,{description:c("store.automaticTypeDetectionDescription"),placement:"top",size:"xs",children:e(qt,{className:"size-3 ms-2"})})]})]}),t(Q,{children:[e(r,{variant:"ghost",onClick:g,title:c("modal.cancel"),children:c("modal.cancel")}),e(r,{onClick:()=>{a(m?.id??null),p(null)},title:c("store.confirmSelection"),children:c("modal.confirm")})]})]})}function Kv({children:t,limit:n,name:r,chunkable:a}){const{store:s}=tr(),i=Fe(()=>{const e=new Fv(s,n);return e.query.name=r,e.query.chunkable=a,e},[a,n,r,s]);return e(Ov.Provider,{value:i,children:t})}function Yv({objectType:t,onLayoutUpdate:n,readonly:a=!1}){const s=p(),{theme:i}=le(),{t:o}=Ze(),[l,c]=Oe(!1),{store:d}=tr(),u=Be(void 0),m=Fe(()=>Qv(t.table_layout),[t.table_layout]),h=(e,t)=>{s({status:"error",title:e,description:t,duration:5e3})};return e(ye,{title:"Table Layout Editor",className:"bg-background! h-full",action:a?void 0:e(r,{isLoading:l,variant:"outline",size:"sm",onClick:()=>{if(!u.current)return;const e=u.current.getValue();let r;if(e)try{r=JSON.parse(e)}catch(e){return h("Invalid JSON",T(e))}else r=null;return Array.isArray(r)?r.some(e=>!e?.name||!e.field)?h("Invalid JSON","A table layout entry must contain the following properties:] {field, name, converter?}"):(c(!0),void d.types.update(t.id,{table_layout:r}).then(e=>{s({status:"success",title:o("store.tableLayoutUpdated"),description:o("store.tableLayoutUpdatedDesc"),duration:2e3}),n(e.table_layout)}).catch(e=>{s({status:"error",title:o("store.failedToUpdateTableLayout"),description:e.message,duration:5e3})}).finally(()=>{c(!1)})):h("Invalid JSON","The table layout must be an array")},children:o("store.saveChanges")}),children:e("div",{className:"h-full",children:e(va,{value:m,language:"json",editorRef:u,theme:"dark"===i?"vs-dark":"vs",options:{readOnly:a}})})})}function Qv(e){return e?JSON.stringify(e,null,2):"[\n\n]"}function Zv({collection:t}){const{client:n}=tr(),{t:a}=Ze(),[s,i]=Oe(void 0),[o,l]=Oe(t.shared_properties||[]),c=p();He(()=>{t.type?.id&&n.store.types.retrieve(t.type.id).then(i)},[n.store.types.retrieve,t.type?.id]);const d=s?Object.keys(s.object_schema?.properties||{}):[];return e(ye,{title:a("store.sharedProperties"),description:a("store.sharedPropertiesDescription"),action:e(r,{size:"lg",isLoading:!1,onClick:()=>{n.store.collections.update(t.id,{shared_properties:o}).then(()=>{c({title:a("store.updatedSharedProperties"),status:"success"})}).catch(e=>{c({title:a("store.failedToUpdateSharedProperties"),description:e.message,status:"error"})})},children:a("modal.save")}),children:e("div",{className:"",children:e(we,{value:o,onChange:e=>{l(e)},options:d,placeholder:a("store.selectPropertiesToShare")})})})}function Xv({collection:t}){const{client:n}=tr(),{t:r}=Ze(),[a,s]=Oe(t.skip_head_sync??!1),[i,o]=Oe(!1),l=p();return e(ye,{title:r("store.syncMemberHeads"),description:r("store.syncMemberHeadsDescription"),children:e(fe,{disabled:i,value:!a,onChange:e=>{const a=!e;o(!0),n.store.collections.update(t.id,{skip_head_sync:a}).then(()=>{l({title:r("store.updatedSkipHeadSync"),status:"success"}),s(a)}).catch(e=>{l({title:r("store.failedToUpdateSkipHeadSync"),description:e.message,status:"error"})}).finally(()=>{o(!1)})},children:r("store.enableSyncMemberHeads")})})}function eb({refetch:a,collection:s}){const{t:i}=Ze(),o=s.type?Sr(s.type):void 0,l=Be(void 0),c=p(),{theme:u}=le(),{client:m}=tr(),h=We(Wh),[g,v]=Oe(!1),[b,x]=Oe({name:s.name,description:s.description||"",query:s.query?JSON.stringify(s.query,null,2):"",tags:s.tags||[],type:s.type?Sr(s.type):"",allowed_types:s.allowed_types||[],sensitivity:s.sensitivity,compartments:s.compartments||[]}),[y,w]=Oe(""),N=Fe(()=>Qv(s.table_layout),[s.table_layout]),k=(e,t)=>{x({...b,[e]:t})};return t("div",{className:"flex flex-col gap-4 py-2",children:[t(ye,{title:i("store.configuration"),action:e(r,{size:"lg",isDisabled:g,onClick:()=>{let e;try{const n=b.query?JSON.parse(b.query):void 0;if(void 0!==n&&("object"!=typeof(t=n)||null===t||Array.isArray(t)))throw new Error(i("store.invalidQueryJson"));e=n}catch(e){return void c({title:i("store.invalidQueryJson"),description:T(e),status:"error",duration:5e3})}var t;const n={name:b.name,description:b.description,query:e,tags:b.tags,type:b.type,allowed_types:b.allowed_types,sensitivity:b.sensitivity,compartments:b.compartments};let r;if(n.name||(r=i("type.nameRequired")),n.type||(n.type=null),r)c({title:i("store.validationFailed"),description:r,status:"error",duration:5e3});else{if(l.current){const e=l.current.getValue();if(e)try{n.table_layout=JSON.parse(e)}catch(e){return void c({title:i("store.invalidTableLayout"),description:T(e),status:"error",duration:5e3})}else n.table_layout=null}v(!0),m.store.collections.update(s.id,n).then(()=>{a(),s.dynamic&&h&&(h.reset(),h.search()),c({title:i("store.collectionUpdated"),description:i("store.collectionUpdatedSuccess"),status:"success",duration:3e3})}).catch(e=>{c({title:i("store.failedToUpdateCollection"),description:T(e),status:"error",duration:5e3})}).finally(()=>{v(!1)})}},children:i("modal.save")}),children:[t("div",{className:"flex justify-between mb-2",children:[t("div",{className:"w-1/2 gap-2 flex flex-col",children:[e("div",{className:"text-sm font-medium mb-1",children:i("store.createdBy")}),t("div",{className:"gap-2 flex items-center",children:[e(op,{userRef:s.created_by,showTitle:!0}),t("span",{children:["at ",Dr(s.created_at).format("YYYY-MM-DD HH:mm:ss")]})]})]}),t("div",{className:"w-1/2 gap-2 flex flex-col",children:[e("div",{className:"text-sm font-medium mb-1",children:i("store.updatedBy")}),t("div",{className:"gap-2 flex items-center",children:[e(op,{userRef:s.updated_by,showTitle:!0}),t("span",{children:["at ",Dr(s.updated_at).format("YYYY-MM-DD HH:mm:ss")]})]})]})]}),e(ie,{label:i("type.name"),required:!0,children:e(d,{value:b.name,onChange:e=>k("name",e)})}),e(ie,{label:i("type.description"),children:e(X,{value:b.description,onChange:e=>k("description",e.target.value)})}),!s.dynamic&&e(ie,{label:i("store.allowedContentTypes"),description:i("store.allowedContentTypesSelectDescription"),children:e(jv,{defaultValue:b.allowed_types||null,onChange:e=>{Array.isArray(e)?k("allowed_types",e.map(e=>e.id)):k("allowed_types",e?[e.id]:[])},isClearable:!0,multiple:!0})}),s.dynamic&&e(ie,{label:i("store.query"),description:i("store.queryDescription"),children:e(X,{className:Ne.INPUT,minLines:1,maxLines:12,value:b.query,onChange:e=>k("query",e.target.value)})}),e(ie,{label:i("store.tableLayout"),description:i("store.tableLayoutDescription"),className:"h-[200px]",children:e(va,{className:"border-1 rounded-md border-border",value:N,language:"json",editorRef:l,theme:"dark"===u?"vs-dark":"vs"})}),e(ie,{label:i("store.contentType"),description:i("store.typeSelectDescription"),children:e(jv,{defaultValue:b.type||null,onChange:e=>{Array.isArray(e)?k("type",e.length>0?e[0].id:null):k("type",e?.id||null)},isClearable:!0})}),e(ie,{label:"Sensitivity",description:"BLP sensitivity level — propagated to member documents (max across collections)",children:e($,{options:Tr.map((e,t)=>({label:`${t} — ${e}`,value:t})),value:void 0!==b.sensitivity?{label:`${b.sensitivity} — ${Tr[b.sensitivity]??"Unknown"}`,value:b.sensitivity}:void 0,onChange:e=>k("sensitivity",e.value),optionLabel:e=>e.label,by:"value",placeholder:"Not set"})}),t(ie,{label:"Compartments",description:"Security compartments — propagated to member documents (union across collections)",children:[t("div",{className:"flex gap-2",children:[e(d,{value:y,onChange:w,placeholder:"Add a compartment",onKeyDown:e=>{if("Enter"===e.key){e.preventDefault();const t=y.trim();t&&!b.compartments.includes(t)&&(k("compartments",[...b.compartments,t]),w(""))}}}),e(r,{type:"button",variant:"outline",onClick:()=>{const e=y.trim();e&&!b.compartments.includes(e)&&(k("compartments",[...b.compartments,e]),w(""))},children:"Add"})]}),e("div",{className:"flex gap-1 flex-wrap mt-2",children:b.compartments.map(e=>t(f,{variant:"secondary",className:"cursor-pointer",onClick:()=>k("compartments",b.compartments.filter(t=>t!==e)),children:[e," ×"]},e))})]})]}),o&&e(tb,{typeId:o,collection:s}),!s.dynamic&&t(n,{children:[e(Xv,{collection:s}),e(Zv,{collection:s})]})]})}function tb({typeId:t,collection:n}){const{t:a}=Ze(),[s,i]=Oe({}),o=p(),{client:l}=tr(),[c,d]=Oe(!1),{data:u,error:m}=S(()=>l.store.types.catalog.resolve(t),[t]),h=u?.object_schema||{},f=Fe(()=>new Na(h,n.properties||{}),[h,n.properties]);if(m)return e(x,{title:a("store.failedToLoadType"),children:T(m)});if(!u)return null;return e(ye,{title:a("store.properties"),action:e(r,{size:"lg",isLoading:c,type:"submit",onClick:()=>(e=>{if(!e||!Object.keys(e).length)return;const t={properties:e||{}};d(!0),l.store.collections.update(n.id,t).then(()=>{o({title:a("store.collectionPropertiesUpdated"),description:a("store.collectionUpdatedSuccess"),status:"success",duration:3e3})}).catch(e=>{o({title:a("store.failedToUpdateCollectionProperties"),description:T(e),status:"error",duration:5e3})}).finally(()=>{d(!1)})})(s),children:a("modal.save")}),children:e(ka,{object:f,onChange:e=>{e instanceof Na&&i(e.value)}})})}function nb({onChange:n,value:a,disabled:s=!1,placeholder:o,searchPlaceholder:l,filterOut:c,allowDynamic:d=!0,multiple:u=!1}){const{client:m}=tr(),{t:p}=Ze(),h=o??p("store.selectACollection"),f=l??p("store.searchCollections"),[g,v]=Oe(""),[b,y]=Oe(!1),[w,N]=Oe(!1),k=xe(g,300),_=Ve(async e=>{y(!0);const t=e.trim(),n=await m.store.collections.search({dynamic:!!d&&void 0,name:w&&t||void 0});return y(!1),!w&&n.length>=1e3&&N(!0),c&&c.length>0?n.filter(e=>!c.includes(e.id)):n},[m,d,c,w]),{data:C,error:j}=S(()=>_(w?k:""),[w?k:"",_]),P=Fe(()=>C?u&&Array.isArray(a)?C.filter(e=>a.includes(e.id)):u||"string"!=typeof a?u?[]:void 0:C.find(e=>e.id===a):u?[]:void 0,[C,a,u]),A=Ve(e=>{if(u){const t=Array.isArray(a)?a:[];if(t.includes(e.id)){const r=t.filter(t=>t!==e.id),a=C?.filter(e=>r.includes(e.id))||[];n(r,a)}else{const r=[...t,e.id],a=C?.filter(e=>r.includes(e.id))||[];n(r,a)}}else n(e.id,e)},[n,a,C,u]),D=Ve(()=>{n(void 0,void 0)},[n]),E=Ve(e=>{v(e)},[]),$=g.trim().length>0,L=Fe(()=>{if(!C)return[];if(w)return C;if(!$)return C;const e=g.toLowerCase();return C.filter(t=>t.name.toLowerCase().includes(e))},[C,w,$,g]),M=u?Array.isArray(P)&&P.length>0:!!P;if(j)return e(x,{title:p("store.collectionFetchFailed"),children:T(j)});return t(I,{children:[e(z,{asChild:!0,children:t(r,{variant:"outline",role:"combobox","aria-haspopup":"listbox",className:i("w-full justify-between min-w-0"),disabled:s,children:[e("span",{className:"truncate flex-1 text-start min-w-0",children:u&&Array.isArray(P)&&P.length>0?1===P.length?P[0].name:p("store.collectionsSelected",{count:P.length}):u||!P||Array.isArray(P)?h:P.name}),M&&!s?e(r,{variant:"unstyled","aria-label":"Clear selection",className:"ms-2 shrink-0 opacity-50 hover:opacity-100 hover:text-destructive cursor-pointer",onClick:e=>{e.stopPropagation(),D()},children:e(ut,{className:"h-4 w-4"})}):e(Zn,{className:"ms-2 h-4 w-4 shrink-0 opacity-50"})]})}),e(R,{className:"mt-2 mb-2 w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:t(ke,{shouldFilter:!1,children:[t("div",{className:"flex justify-between items-center border-b px-3","cmdk-input-wrapper":"",children:[e(_e,{placeholder:f,value:g,onValueChange:E,className:"flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50"}),b&&e("div",{className:"me-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"})]}),e(Ce,{children:p(b?"store.searching":$?"store.noCollectionsFound":"store.noCollectionsAvailable")}),t(Se,{className:"max-h-[300px] overflow-auto",children:[M&&!$&&e(Te,{value:"__clear__",onSelect:D,className:"text-destructive",children:"Remove collection selection(s)"}),$&&e(Te,{value:"__clear_search__",onSelect:()=>v(""),className:"text-muted",children:p("store.clearSelection")}),L.map(n=>{const r=u&&Array.isArray(a)?a.includes(n.id):a===n.id;return t(Te,{value:n.id,onSelect:()=>A(n),className:"flex items-center justify-between",children:[e("span",{className:"truncate",children:n.name}),r&&e(it,{className:"ms-2 h-4 w-4 shrink-0"})]},n.id)})]})]})})]})}function rb({isOpen:n,onClose:r}){return t(H,{onClose:()=>r(),isOpen:!!n,className:"min-w-[60vw]",children:[e(G,{children:"Select Content"}),e(J,{className:"pt-0 overflow-y-auto max-h-[80vh] min-h-[80vh]",children:n&&e(lf,{onChange:r})})]})}const ab=/store:([a-f0-9]+)/;function sb({object:n}){const{client:a}=tr(),{off:s,on:i,isOn:o}=Ie(),[l,c]=Oe(null!=n.value?String(n.value):""),[d,u]=Oe(void 0),m=Ve(()=>{c(""),n.value="",u(void 0)},[n]);return He(()=>{if(!l||d)return;const e=l.match(ab);e&&a.objects.retrieve(e[1]).then(e=>{u(e)}).catch(()=>{m()})},[l,a.objects.retrieve,m,d]),t("div",{children:[t("div",{className:"relative",children:[e("input",{value:l,onChange:e=>{const t=e.target.value;c(t),n.value=t},className:Ae(Ne.INPUT,"pe-10 w-full")}),d&&e("div",{className:"absolute inset-y-0 end-10 flex items-center justify-center ",children:e(r,{onClick:m,variant:"unstyled",className:"hover:text-red-500 hover:bg-gray-100 dark:hover:bg-gray-600",children:e(ut,{className:"size-5"})})}),e("div",{className:"absolute inset-y-0 end-0 flex items-center justify-center",children:e(r,{onClick:i,variant:"unstyled",className:"hover:bg-gray-100 dark:hover:bg-gray-600",children:e(Zn,{className:"size-5"})})}),e(rb,{value:l,isOpen:o,onClose:e=>{if(e){const t=`store:${e.id}`;c(t),u(e||void 0),n.value=t}s()}})]}),d&&e("div",{className:"p-1 semibold text-sm text-gray-600 dark:text-slate-300",children:"string"==typeof d.properties?.title?d.properties.title:d.name})]})}function ib({objectId:n,isOpen:a,onClose:s}){const i=ia(),{client:o,store:l}=tr(),[c,d]=Oe(null),[u,m]=Oe(!1),[h,f]=Oe(!1),[g,v]=Oe(),[b,x]=Oe(),[y,w]=Oe("preview"),{t:N}=Ze(),k=p(),_=Ve(async e=>{f(!0);try{const t=await l.objects.getObjectText(e);v(t.text)}catch(e){console.error("Error loading text:",e)}finally{f(!1)}},[l.objects]),C=Ve(async e=>{if(e.content?.source)try{"found"===(await o.objects.getRendition(e.id,{format:fr.jpeg,generate_if_missing:!1})).status&&console.log("Found rendition");const t=await o.files.getDownloadUrl(e.content.source);x(t.url)}catch(e){console.error("Error loading image:",e)}},[o.files,o.objects]);He(()=>{n&&a?(m(!0),l.objects.retrieve(n,"+embeddings").then(e=>{d(e),e.text?v(e.text):_(e.id);const t=e.content;t?.source&&t.type?.startsWith("image/")&&C(e)}).catch(e=>{console.error("Error loading object:",e),k({title:N("agent.error"),description:N("store.failedToLoadDocument"),status:"error",duration:3e3})}).finally(()=>{m(!1)})):(d(null),v(void 0),x(void 0))},[n,a,l.objects,_,C,N,k]);const S=()=>{c&&(i(`/legal/objects/${c.id}`),s())},T=g&&(g.startsWith("#")||g.includes("\n#")||g.includes("\n*")),I=c?.content?.type?.startsWith("image/"),z="application/pdf"===c?.content?.type;if(!a)return null;return t("div",{className:`fixed inset-y-0 end-0 w-2/5 dark:bg-slate-900 shadow-xl z-50 flex flex-col transition-transform duration-300 transform ${a?"translate-x-0":"translate-x-full rtl:-translate-x-full"}`,children:[t("div",{className:"flex items-center justify-between px-4 py-3 border-b dark:border-gray-700 bg-gradient-to-r from-indigo-50 to-gray-50 dark:from-gray-800 dark:to-gray-900",children:[t("div",{className:"flex items-center",children:[e(kt,{className:"h-5 w-5 text-indigo-600 me-2"}),e("h2",{className:"text-lg font-semibold text-gray-800 dark:text-gray-200 truncate",children:u?N("store.loadingDocument"):c?.name||N("store.documentPreview")})]}),t("div",{className:"flex items-center gap-2",children:[t(r,{variant:"ghost",size:"sm",onClick:S,className:"flex items-center gap-1 text-indigo-600 hover:text-indigo-800",children:[e(dt,{className:"h-4 w-4"}),e("span",{children:N("store.fullView")})]}),e(r,{variant:"ghost",size:"sm",onClick:s,className:"flex items-center text-gray-600 hover:text-gray-800 dark:text-gray-300 dark:hover:text-gray-100",children:e(ut,{className:"h-5 w-5"})})]})]}),u?e("div",{className:"flex-1 flex items-center justify-center",children:t("div",{className:"text-center",children:[e(K,{size:"lg",className:"text-indigo-600 dark:text-indigo-400 mb-2"}),e("p",{className:"text-gray-600 dark:text-gray-400",children:N("store.loadingDocument")})]})}):t("div",{className:"flex-1 flex flex-col h-full",children:[e("div",{className:"border-b",children:t("div",{className:"flex px-4",children:[e(r,{variant:"unstyled",className:"py-2 px-4 font-medium border-b-2 "+("preview"===y?"border-indigo-600 text-indigo-700 dark:text-indigo-300":"border-transparent text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"),onClick:()=>w("preview"),children:t("div",{className:"flex items-center gap-1",children:[e(Dn,{className:"h-4 w-4"}),e("span",{children:N("store.preview")})]})}),e(r,{variant:"unstyled",className:"py-2 px-4 font-medium border-b-2 "+("properties"===y?"border-indigo-600 text-indigo-700 dark:text-indigo-300":"border-transparent text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"),onClick:()=>w("properties"),children:t("div",{className:"flex items-center gap-1",children:[e(qt,{className:"h-4 w-4"}),e("span",{children:N("store.properties")})]})})]})}),t("div",{className:"flex-1 overflow-auto p-4",children:["preview"===y&&t("div",{className:"h-full",children:[h?e("div",{className:"flex items-center justify-center h-40",children:e(K,{size:"md",className:"text-indigo-600 dark:text-indigo-400"})}):g?e("div",{className:"shadow rounded-md p-4 border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800",children:T?e("div",{className:"prose prose-sm max-w-none prose-p:my-2 prose-pre:bg-gray-800 prose-pre:my-2 prose-headings:text-indigo-700 dark:prose-invert dark:prose-headings:text-indigo-300",children:e(oa,{children:g})}):e("pre",{className:"text-wrap whitespace-pre-wrap dark:text-gray-200",children:g})}):null,I&&e("div",{className:"mt-4",children:e("div",b?{className:"border border-gray-200 dark:border-gray-700 rounded-md p-2 bg-white dark:bg-gray-800",children:e("img",{src:b,alt:c?.name,className:"mx-auto max-h-[70vh] object-contain"})}:{className:"flex items-center justify-center h-40",children:e(K,{size:"md",className:"text-indigo-600 dark:text-indigo-400"})})}),z&&t("div",{className:"flex flex-col items-center justify-center h-64 border border-gray-200 dark:border-gray-700 rounded-md p-4 bg-gray-50 dark:bg-gray-800",children:[e(kt,{className:"h-16 w-16 text-indigo-300 dark:text-indigo-400 mb-4"}),e("p",{className:"text-gray-600 dark:text-gray-400 text-center mb-4",children:N("store.pdfPreviewFullView")}),e(r,{onClick:S,className:"bg-indigo-600 hover:bg-indigo-700 text-white",children:N("store.openFullDocumentView")})]}),!I&&!g&&!z&&!h&&t("div",{className:"flex flex-col items-center justify-center h-64 border border-gray-200 dark:border-gray-700 rounded-md p-4 bg-gray-50 dark:bg-gray-800",children:[e(kt,{className:"h-16 w-16 text-gray-300 dark:text-gray-600 mb-4"}),e("p",{className:"text-gray-600 dark:text-gray-400 text-center",children:N("store.noPreviewAvailable")})]})]}),"properties"===y&&c&&t("div",{className:"h-full",children:[c.properties?e("div",{className:"shadow rounded-md p-4 border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800",children:e(ba,{value:c.properties})}):t("div",{className:"flex flex-col items-center justify-center h-64 border border-gray-200 dark:border-gray-700 rounded-md p-4 bg-gray-50 dark:bg-gray-800",children:[e(qt,{className:"h-16 w-16 text-gray-300 dark:text-gray-600 mb-4"}),e("p",{className:"text-gray-600 dark:text-gray-400 text-center",children:N("store.noPropertiesAvailable")})]}),t("div",{className:"mt-4",children:[e("h3",{className:"text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2",children:N("store.documentInformation")}),e("div",{className:"shadow rounded-md p-4 border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800",children:t("div",{className:"grid grid-cols-2 gap-y-2 gap-x-4 text-sm",children:[e("div",{className:"text-gray-500 dark:text-gray-400",children:N("store.id")}),e("div",{className:"font-medium dark:text-gray-200",children:c.id}),e("div",{className:"text-gray-500 dark:text-gray-400",children:N("store.contentType")}),e("div",{className:"font-medium dark:text-gray-200",children:c.type?.name||N("store.unknown")}),e("div",{className:"text-gray-500 dark:text-gray-400",children:N("store.contentType")}),e("div",{className:"font-medium dark:text-gray-200",children:c.content?.type||N("store.na")}),e("div",{className:"text-gray-500",children:N("store.size")}),e("div",{className:"font-medium",children:c.content&&"size"in c.content?ob(c.content.size):N("store.unknown")}),e("div",{className:"text-gray-500",children:N("store.created")}),e("div",{className:"font-medium",children:c.created_at?new Date(c.created_at).toLocaleString():N("store.na")}),e("div",{className:"text-gray-500",children:N("store.updated")}),e("div",{className:"font-medium",children:c.updated_at?new Date(c.updated_at).toLocaleString():N("store.na")})]})})]})]})]})]}),t("div",{className:"flex items-center justify-between p-4 border-t bg-gray-50 dark:bg-gray-800 dark:border-gray-700",children:[e("div",{children:c?.content?.source&&t(r,{onClick:()=>{c?.content?.source&&o.files.getDownloadUrl(c.content.source).then(e=>{window.open(e.url,"_blank")}).catch(e=>{console.error("Error getting download URL:",e),k({title:N("agent.error"),description:N("store.failedToDownloadFile"),status:"error",duration:3e3})})},variant:"outline",className:"text-indigo-600 border-indigo-300 hover:bg-indigo-50",children:[e(lt,{className:"h-4 w-4 me-2"}),N("pdf.download")]})}),t(r,{onClick:S,className:"bg-indigo-600 hover:bg-indigo-700 text-white",children:[N("store.openFullDocument"),e(ht,{className:"h-4 w-4 ms-2 cn-rtl-flip"})]})]})]})}function ob(e){if(0===e)return"0 Bytes";const t=Math.floor(Math.log(e)/Math.log(1024));return`${parseFloat((e/1024**t).toFixed(2))} ${["Bytes","KB","MB","GB","TB"][t]}`}var lb;function cb({isExporting:n,isOpen:r,onClose:a}){return t(H,{onClose:()=>a(void 0),isOpen:r,children:[e(G,{children:"Export Object Properties"}),t(J,{children:[!n&&e(db,{onClose:a}),n&&e(ub,{})]})]})}function db({onClose:n}){const{t:a}=Ze(),[s,i]=Oe(void 0),[o,l]=Oe(void 0),c=["Export selected objects","Export all objects"];return t(J,{className:"min-h-[104px] pt-0 flex flex-col gap-y-4",children:[e("div",{className:"h-1/3",children:e($,{options:c,value:o,onChange:l,placeholder:a("store.chooseWhatToExport"),className:"h-full w-full text-sm",filterBy:"name",isClearable:!0})}),t("div",{className:"h-1/2 flex flex-col gap-y-8 content-between",children:[e($,{options:Object.values(lb),value:s,onChange:i,placeholder:a("store.chooseAFormat"),className:"h-full w-full text-sm",filterBy:"name",isClearable:!0}),e(r,{className:"w-full",isDisabled:!s||!o,onClick:()=>{n(s,o===c[1])},children:a("store.actions.exportProperties")})]})]})}function ub(){const{t:n}=Ze();return e(J,{className:"min-h-[84px] pt-0",children:t("div",{className:"h-full grid flex-col gap-y-2 content-between justify-items-center",children:[t("div",{className:"text-sm flex flex-col gap-x-2",children:[e("p",{children:n("store.exportInProgress")}),e("p",{className:"pt-2 grid justify-items-center",children:n("store.pleaseWait")})]}),e(K,{size:"lg"})]})})}!function(e){e.CSV="CSV",e.JSON="JSON"}(lb||(lb={}));const mb=Ue(void 0);function pb(){const e=We(mb);if(!e)throw new Error("You cannot use useActionContext outside an ActionProvider");return e}function hb(e,t){const n=pb();return He(()=>n.registerCallback(e,t),[n,e,t]),n}function fb({action:t,objectIds:n}){const[r,a]=Oe(!1),s=Ve(()=>(n.length>0&&a(!0),Promise.resolve(!0)),[n]);return hb(t.id,s),r&&e(ce,{children:e(bb,{objectIds:n,isOpen:r,onClose:()=>{a(!1)}})})}const gb=Xe.getFixedT(null,et),vb={id:"addToCollection",name:gb("store.actions.addToCollection"),description:gb("store.actions.addToCollectionDesc"),confirm:!1,component:fb};function bb({isOpen:n,onClose:r,objectIds:a}){const{t:s}=Ze();return t(H,{isOpen:n,onClose:r,className:"max-w-lg w-full min-w-0 overflow-hidden",children:[e(G,{className:"flex flex-col min-w-0 overflow-hidden",children:s("store.actions.addToCollectionTitle")}),e(ze,{className:"min-w-0 overflow-hidden",children:s("store.actions.addToCollectionBody")}),e("div",{className:"min-w-0 max-w-full overflow-hidden",children:e(xb,{onClose:r,objectIds:a})})]})}function xb({onClose:n,objectIds:a}){const{t:s}=Ze(),i=p(),{client:o}=tr(),[l,c]=Oe(),d=({collectionId:e})=>{e&&a?.length&&o.store.collections.addMembers(e,a).then(()=>{i({title:s("store.actions.addToCollectionSuccess"),status:"success",description:s("store.actions.addToCollectionSuccessDesc",{count:a.length}),duration:3e3}),n()}).catch(()=>{i({title:s("store.actions.addToCollectionFailure"),status:"error",description:s("store.actions.addToCollectionFailureDesc"),duration:5e3})})},u=[{name:"select",label:s("store.actions.selectCollection"),content:t("div",{className:"p-4 min-w-0 max-w-full overflow-hidden",children:[e(Re,{level:5,children:s("store.actions.chooseExistingCollections")}),e(J,{className:"min-w-0 max-w-full overflow-hidden",children:e("div",{className:"mb-4 min-w-0 max-w-full overflow-hidden",children:e(nb,{onChange:(e,t)=>{"string"==typeof e||void 0===e?c(e):Array.isArray(e)&&e.length>0?c(e[0]):c(void 0)},value:l})})}),e(Q,{children:e(r,{isDisabled:!l,onClick:()=>l&&d({collectionId:l}),children:s("store.actions.addToCollectionButton")})})]})},{name:"create",label:s("store.actions.createNew"),content:e("div",{className:"p-4",children:e(Pv,{onClose:n,onAddToCollection:e=>d({collectionId:e}),redirect:!1})})}];return t(w,{defaultValue:"select",tabs:u,fullWidth:!0,children:[e(je,{}),e(N,{})]})}function yb({action:n,objectIds:r,children:a}){const{t:s}=Ze(),{store:i}=tr(),o=p(),[l,c]=Oe(!1),d=Ve(()=>(c(!0),Promise.resolve(!0)),[]);hb(n.id,d);return t("div",{children:[a,e(Jv,{isOpen:l,onClose:e=>{c(!1),void 0!==e&&i.runOperation({name:"change_type",ids:r,params:{typeId:e}}).then(e=>{o({status:"success",title:s("store.actions.changeType"),description:`Change the type of ${r.length} objects is ${"in_progress"===e.status?"in progress":"completed"}`,duration:2e3})}).catch(e=>{o({status:"error",title:s("store.actions.errorChangingType"),description:e.message,duration:5e3})})},title:"Change Content Type",confirmLabel:"Change Type",children:t("p",{className:"pt-2 text-xs",children:["Note: This action will raise the ",e("code",{children:"change_type"})," event and will trigger the standard intake workflows which may reset the object properties."]})})]})}const wb=Xe.getFixedT(null,et),Nb={id:"changeType",name:wb("store.actions.changeContentType"),description:wb("store.actions.changeContentTypeDesc"),confirm:!1,component:yb};function kb({action:r,callback:a,children:s}){const{t:i}=Ze(),[o,l]=Oe(!1),c=r.confirmationText||`Are you sure you want to ${r.name}?`,d=Ve(e=>r.confirm?(l(!0),Promise.resolve(!0)):a(e),[r.confirm,a]),u=hb(r.id,d);return t(n,{children:[s,e(be,{onConfirm:()=>{l(!1),a({...u.params,action:r})},onCancel:()=>l(!1),title:i("store.actions.areYouSure"),content:c,isOpen:o})]})}function _b({action:t,objectIds:n,children:r}){const{t:a}=Ze(),s=pb(),i=p(),{client:o}=tr(),l=Bh(),c=ia(),d=Ve(()=>n?.length?o.store.objects.delete(n).then(e=>{const t=e.deleted>1?"s":"";if(i({status:"success",title:`${e.deleted} object${t} deleted`,duration:2e3}),e.failed.length>0&&i({status:"warning",title:`${e.failed.length} object(s) could not be deleted`,duration:3e3}),l){s.params?.selection?.removeAll();const e=JSON.parse(JSON.stringify(l.facets));n.length===e._value.total&&l.resetFacets(),l.search()}else c("/objects")}).catch(e=>{i({status:"error",title:a("store.actions.errorDeletingObjects"),description:e.message,duration:5e3})}):(i({status:"error",title:a("store.actions.noObjectsSelected"),description:a("store.actions.pleaseSelectObjectsToDelete"),duration:3e3}),Promise.resolve(!1)),[o.store.objects.delete,s.params?.selection?.removeAll,c,n,l,l?.facets,l?.resetFacets,l?.search,a,i]);return e(kb,{action:t,callback:d,children:r})}const Cb=Xe.getFixedT(null,et),Sb={id:"delete",name:Cb("store.actions.delete"),description:Cb("store.actions.deleteTheSelectedObjects"),confirm:!0,confirmationText:Cb("store.actions.confirmDeleteAll"),component:_b,destructive:!0},Tb={id:"deleteFromCollections",name:Cb("store.actions.deleteObjects"),description:Cb("store.actions.deleteTheSelectedObjects"),confirm:!0,confirmationText:Cb("store.actions.confirmDeleteSelected"),component:_b,destructive:!0};function Ib({action:t,objectIds:n}){const{t:r}=Ze(),{store:a}=tr(),s=p(),[i,o]=Oe(!1),[l,c]=Oe(!1),d=Ve(()=>(o(!0),Promise.resolve(!0)),[]),u=hb(t.id,d);return e(cb,{isExporting:l,isOpen:i,onClose:(e,t)=>{if(e&&(t||n.length>0)){c(!0);const i=u.params?.search?.query||{},l=u.params?.search?.result?.value?.objects?.map(e=>e.id)||void 0,d=async e=>a.objects.list({query:{parent:e}}).then(e=>e.map(e=>e.id)),m=async()=>t?l?i.vector?l:[]:0===n.length?[]:(await d(n[0])).concat(n):n,p=u.params?.type?.id??i.type,h=u.params?.type?.table_layout??void 0;m().then(l=>{a.objects.exportProperties({objectIds:l,type:e,query:t&&!i.vector?{...i,type:p}:{type:p},table_layout:h}).then(e=>{const a=new Blob([e.data],{type:e.type}),i=window.URL.createObjectURL(a),o=document.createElement("a");o.download=e.name,o.href=i,o.click(),s({status:"success",title:r("store.actions.exportProperties"),description:t?"Export the properties of all objects completed":`Export the properties of ${n.length} object${n.length>1?"s":""} is completed`,duration:2e3})}).catch(e=>{s({status:"error",title:r("store.actions.errorExportProperties"),description:e.message,duration:5e3})}).finally(()=>{c(!1),o(!1)})})}else o(!1),s({status:"error",title:r("store.actions.errorExportProperties"),description:"No objects selected for export",duration:5e3})}})}const zb=Xe.getFixedT(null,et),Rb={id:"exportProperties",name:zb("store.actions.exportProperties"),description:zb("store.actions.exportAllObjectProperties"),confirm:!1,component:Ib};function jb({action:t,objectIds:n,collectionId:r}){const{t:a}=Ze(),s=pb(),i=p(),{client:o}=tr(),l=Bh(),c=Ve(()=>n?.length?r?o.store.collections.deleteMembers(r,n).then(()=>{const e=n.length>1?"s":"";i({status:"success",title:`${n.length} object${e} removed from collection`,description:"Objects have been removed from the collection",duration:2e3}),l&&(s.params?.selection?.removeAll(),l.search())}).catch(e=>{i({status:"error",title:a("store.actions.errorRemovingObjects"),description:T(e),duration:5e3})}):(i({status:"error",title:a("store.actions.noCollectionContext"),description:a("store.actions.cannotRemoveNoCollection"),duration:3e3}),Promise.resolve(!1)):(i({status:"error",title:a("store.actions.noObjectsSelected"),description:a("store.actions.pleaseSelectObjectsToRemove"),duration:3e3}),Promise.resolve(!1)),[o.store.collections.deleteMembers,r,s.params?.selection?.removeAll,n,l,l?.search,a,i]);return e(kb,{action:t,callback:c})}const Pb=Xe.getFixedT(null,et),Ab={id:"removeFromCollection",name:Pb("store.actions.removeFromCollection"),description:Pb("store.actions.removeFromCollectionDesc"),confirm:!0,confirmationText:Pb("store.actions.confirmRemoveFromCollection"),component:jb,destructive:!0};function Db({action:t,objectIds:n,collectionId:r}){const{t:a}=Ze(),s=p(),{client:i}=tr(),[o,l]=Oe(!1),c=Ve(()=>(l(!0),Promise.resolve(!0)),[]);return hb(t.id,c),e(Lb,{isOpen:o,onClose:e=>{if(l(!1),e)return i.store.workflows.rules.execute(e,n,{collection_id:r}).then(()=>{s({title:a("store.actions.workflowStarted"),status:"success",duration:3e3})}).catch(e=>{s({title:a("store.actions.errorStartingWorkflow"),status:"error",description:e.message,duration:9e3})})}})}const Eb=Xe.getFixedT(null,et),$b={id:"startWorkflow",name:Eb("store.actions.startWorkflow"),description:Eb("store.actions.startWorkflowDesc"),confirm:!1,hideInList:!0,component:Db};function Lb({isOpen:n,onClose:r}){const{t:a}=Ze();return t(H,{onClose:()=>r(void 0),isOpen:n,size:"lg",children:[e(G,{children:a("store.actions.startWorkflowByRule")}),e(Fb,{onClose:r})]})}function Mb(n){return{label:t("div",{children:[e("div",{className:"text-start",children:n.name}),e("div",{className:"text-sm text-muted text-wrap text-start",children:n.description})]}),reverse:!0}}function Fb({onClose:a}){const{t:s}=Ze(),[i,o]=Oe(void 0),l=pb();return t(n,{children:[t(J,{children:[e("div",{className:"pb-2",children:s("store.actions.chooseWorkflowRule")}),e("div",{className:"max-h-[420px] overflow-y-scroll border-border border rounded-md",children:e(Pe,{className:"w-full",options:l.wfRules,optionLayout:Mb,onChange:e=>{o(e)},value:i})})]}),t(Q,{children:[e(r,{variant:"secondary",onClick:()=>a(),children:"Cancel"}),e(r,{onClick:()=>{i&&a(i.id)},isDisabled:!i,children:"Start"})]})]})}class Ob{params;allActions=[];wfRules=[];callbacks={};startWorkflow;constructor(e){this.params=e}get actions(){return!!this.params.selection?.collectionId?this.allActions.filter(e=>"addToCollection"!==e.id&&"delete"!==e.id):this.allActions.filter(e=>"removeFromCollection"!==e.id&&"deleteFromCollections"!==e.id)}registerCallback(e,t){return this.callbacks[e]=t,()=>{delete this.callbacks[e]}}unregisterCallback(e){delete this.callbacks[e]}findAction(e){let t=this.allActions.find(t=>t.id===e);return t||(t=this.wfRules.find(t=>t.id===e)),t}async run(e){const t=this.findAction(e);if(!t)throw new Error(`Action ${e} not found`);const n={...this.params,action:t},r=this.callbacks[e];if(r)return r(n);throw new Error("No action callback set")}}const Ub=[Rb,Nb,$b,vb,Sb,Ab,Tb];function Wb({children:n,type:r}){const{t:a}=Ze(),s=nh(),i=p(),{client:o}=tr(),l=Bh(),{data:c,error:d}=S(()=>o.workflows.rules.list().then(e=>e.map(e=>({id:e.id,name:e.name,description:e.description,confirm:!1,isWorkflow:!0,component:Db})).sort((e,t)=>e.name.localeCompare(t.name))),[]),u=Fe(()=>{const e=new Ob({selection:s,toast:i,client:o,search:l,type:r});return e.allActions=Ub,e.wfRules=c,e},[o,l,s,c,i,r]);return d?e(x,{title:a("store.failedToFetchWorkflows"),children:T(d)}):u&&t(mb.Provider,{value:u,children:[e(Bb,{}),n]})}function Bb(){const t=pb(),n=t.params.selection,r=n.getObjectId(),a=n.isSingleSelection()&&r?[r]:n.getObjectIds();return e("div",{style:{display:"none"},children:t.allActions.map(t=>e(t.component,{action:t,objectIds:a,collectionId:n.collectionId},t.id))})}function Vb({type:n,allowMutations:a=!0,allowDelete:s=!0,allowWorkflowRun:i=!0}){const o=nh(),l=o.size(),c=l>1?"s":"",d=o?.hasSelection(),u=o?.isSingleSelection();return e(Wb,{type:n,children:t("div",{className:"flex items-center gap-x-2",children:[d&&!u&&t("div",{className:"flex items-center gap-x-1 shrink-0",children:[t("div",{className:"text-sm nowrap",children:[l," document",c," selected"]}),e(r,{title:"Clear selection",variant:"ghost",onClick:()=>{o?.removeAll()},children:e(ut,{className:"size-4"})})]}),e(Kb,{selection:o,allowMutations:a,allowDelete:s,allowWorkflowRun:i,children:t=>t.length>0?e(r,{variant:"ghost",title:"More action",size:"sm",children:e(Xn,{size:16})}):null}),d&&i&&e(qb,{selection:o})]})})}function qb(t){return e(Gb,{})}function Hb({collectionId:a,allowFolders:s=!0}){const{t:i}=Ze(),[o,l]=Oe([]),[c,d]=Oe(!1);return t(n,{children:[e(r,{onClick:()=>d(!0),children:i("store.upload")}),e(Qh,{collectionId:a??"",isOpen:c,onClose:()=>{d(!1),l([])},files:o,title:"Upload Files",onUploadComplete:e=>{e?.success&&l([])},allowFolders:s})]})}function Gb(){const t=pb(),{t:n}=Ze();return t.params.selection.hasSelection()&&e(r,{onClick:()=>t.run($b.id),children:n("store.actions.startWorkflow")})}function Jb(e){return{label:e.name,className:Ae("flex-1 px-2 py-2 hover:bg-accent nowrap",e.destructive?"text-destructive":"")}}function Kb({selection:n,children:r,allowMutations:a=!0,allowDelete:s=!0,allowWorkflowRun:i=!0}){const o=pb(),l=function(e,t,n){if(!t?.hasSelection())return[Rb];return e.filter(e=>!e.hideInList&&("startWorkflow"===e.id?n.allowWorkflowRun:"delete"===e.id||"deleteFromCollections"===e.id?n.allowDelete:"changeType"!==e.id&&"addToCollection"!==e.id&&"removeFromCollection"!==e.id||n.allowMutations))}(o.actions,n,{allowMutations:a,allowDelete:s,allowWorkflowRun:i}),c=r(l);return c?t(I,{hover:!0,children:[e(z,{children:c}),e(R,{className:"p-0 w-50",align:"end",sideOffset:6,children:e(Yb,{executeAction:e=>{o.run(e.id)},actions:l})})]}):null}function Yb({executeAction:t,actions:n}){return e("div",{className:"rounded-md shadow-md py-2",children:e("div",{className:"px-1 text-sm",children:e(Pe,{options:n,optionLayout:Jb,onChange:e=>{t(e)},noCheck:!0})})})}function Qb({user:n}){return t("div",{className:"flex items-center",children:[e("div",{className:"w-9 h-9",children:(()=>{if(n.picture)return e("img",{className:"inline-block h-9 w-9 rounded-full",src:n.picture,alt:n.name});{const t=n.name.split(" ").map(e=>e[0]).join("");return e("span",{className:"inline-flex h-8 w-8 items-center justify-center rounded-full bg-indigo-600",children:e("span",{className:"text-sm font-medium leading-none text-white",children:t})})}})()}),t("div",{className:"ms-3",children:[e("p",{className:"text-sm font-medium text-gray-700 dark:text-slate-50 group-hover:text-gray-900",children:n.name??"Deleted User"}),e("p",{className:"text-xs font-medium text-gray-500 dark:text-slate-300 group-hover:text-gray-700",children:n.email??"Deleted User"})]})]})}export{La as ActivitiesDoc,Fa as ActivityDoc,vb as AddToCollectionAction,fb as AddToCollectionActionComponent,Ja as AgentApprovalModeSelector,ps as AgentChart,Du as AgentChatFixtureReplay,ks as AgentChatPlaybackControls,gp as AgentRunnerFacetsNav,Hg as AllOf,Bl as AnimatedThinkingDots,qg as AnyOf,up as ApiKeyAvatar,Wo as AskUserWidget,Og as AudioPanel,Rv as BrowseCollectionView,Nb as ChangeTypeAction,yb as ChangeTypeActionComponent,Ev as CollectionIcon,kp as CollectionsFacetsNav,Dv as CollectionsTable,Bo as ConfirmationWidget,sf as ContentDispositionButton,qv as ContentObjectTypesSearch,Lv as ContentObjectTypesTable,cv as ContentOverview,Pv as CreateCollectionForm,Av as CreateCollectionModal,Mv as CreateOrUpdateTypeModal,Sb as DeleteObjectsAction,_b as DeleteObjectsActionComponent,Tb as DeleteObjectsFromCollectionsAction,Oh as DocumentGridView,Mh as DocumentIcon,Lh as DocumentIconSkeleton,sb as DocumentInput,ib as DocumentPreviewPanel,Uh as DocumentSearch,rf as DocumentSearchProvider,Sv as DocumentSearchResults,Cv as DocumentSearchResultsWithDropZone,eh as DocumentSelection,ah as DocumentSelectionProvider,ef as DocumentTable,$h as DocumentTableColumn,Fh as DocumentTableView,Qh as DocumentUploadModal,Ip as DocumentsFacetsNav,eb as EditCollectionView,zp as EnvironmentFacet,Rb as ExportPropertiesAction,Ib as ExportPropertiesComponent,cb as ExportPropertiesModal,lb as ExportTypes,Jh as FileUploadAction,Gf as GenericPageNavHeader,$m as Header,Ug as ImagePanel,Pp as InteractionsFacetsNav,Eu as JumpingDots,_c as MESSAGE_STYLES,Dg as MagicPdfView,Vu as McpConnectionsActionMenu,Wu as McpConnectionsButton,Uu as McpConnectionsDialog,Bu as McpConnectionsInlineList,Cc as MessageItem,Ef as MessagesContainer,Rf as ModernAgentConversation,Jf as NotFoundView,Bg as OAuthProviderConnectButton,Hv as ObjectSchemaEditor,Fv as ObjectTypeSearch,Ov as ObjectTypeSearchContext,Kv as ObjectTypeSearchProvider,Wb as ObjectsActionContextProvider,Ff as PanelErrorBoundary,Pm as PayloadBuilder,Dm as PayloadBuilderProvider,jm as PayloadBuilderStore,Am as PayloadContext,ag as PdfDocumentRenderer,Yf as PdfPageRenderer,og as PdfPageSlider,rg as PdfThumbnailList,Dp as ProcessDefinitionsFacetsNav,$p as ProcessRunsFacetsNav,Fp as PromptsFacetsNav,nv as PropertiesEditorModal,Vl as PulsatingCircle,Hl as PulsingMessageLoader,Ni as RemoteMcpConnectionButton,Ab as RemoveFromCollectionAction,jb as RemoveFromCollectionActionComponent,Uf as RowErrorBoundary,Wp as RunsFacetsNav,tv as SaveVersionConfirmModal,Wh as SearchContext,Zg as SecureButton,Xg as SecureSidebarItem,nb as SelectCollection,jv as SelectContentType,Jv as SelectContentTypeModal,lf as SelectDocument,rb as SelectDocumentModal,Vb as SelectionActions,Zf as SharedPdfProvider,Zv as SharedPropsEditor,tg as SimplePdfPage,Vg as SimplePdfViewer,vf as SkillWidgetProvider,$b as StartWorkflowAction,Db as StartWorkflowComponent,Sc as StreamingMessage,Bp as StringFacet,Vp as StringListFacet,Xv as SyncMemberHeadsToggle,Yv as TableLayoutEditor,Gl as ThinkingBar,Kl as ThinkingMessages,Hp as TypeFacet,vp as TypeRegistry,xp as TypeRegistryProvider,ql as TypedDots,Hb as UploadObjectsButton,Qb as UserAvatar,op as UserInfo,Qg as UserPermissionProvider,Jg as UserPermissions,Kg as UserPermissionsContext,Um as VInteractionFacet,Vm as VStringFacet,_p as VTypeFacet,pp as VUserFacet,ds as VegaLiteChart,$f as VertesiaErrorBoundary,Wg as VideoPanel,Mg as WEB_SUPPORTED_AUDIO_FORMATS,$g as WEB_SUPPORTED_IMAGE_FORMATS,Lg as WEB_SUPPORTED_VIDEO_FORMATS,Jl as WavyThinking,Bf as WidgetErrorBoundary,Jp as WorkflowDefinitionsFacetsNav,Qp as WorkflowExecutionsFacetsNav,Xp as WorkflowRulesFacetsNav,hs as clampPlaybackCursor,Fu as countConnectedActiveGroups,fp as createAgentRunnerFilterHandler,bs as createPlaybackState,Fm as filterValueToQueryValue,Fg as formatDuration,Ou as getConnectedActiveGroupLabels,vs as getNextUserTurnIndex,fs as getPlaybackCursorIndex,gs as getPreviousUserTurnIndex,Sh as getWorkflowStatusColor,Th as getWorkflowStatusName,xs as isAgentChatPlaybackAvailable,ys as isAgentChatPlaybackEnabled,Gg as isAnyOf,hh as isCsv,Lu as isGroupDisabled,fh as isImage,ws as isLocalhostAgentChatPlaybackAvailable,Ns as isLocalhostAgentChatPlaybackEnabled,gh as isPdf,bh as isPreviewableAsPdf,ms as isRechartsSpec,us as isVegaLiteSpec,vh as isVideo,xh as printElementToPdf,kh as retrieveRendition,Mf as setErrorBoundaryComponent,Om as setSearchQueryValue,_h as shortId,Ch as shortenString,Qv as stringifyTableLayout,Mu as toggleGroupDisabled,Mm as unwrapFilterOptionValue,hp as useAgentRunnerFilterGroups,wp as useCollectionsFilterGroups,Np as useCollectionsFilterHandler,Sp as useDocumentFilterGroups,Tp as useDocumentFilterHandler,Bh as useDocumentSearch,Hh as useDocumentSearchCount,nh as useDocumentSelection,Zh as useDocumentUploadHandler,mc as useDownloadFile,Zm as useFetchApiKeyInfo,Qm as useFetchGroupInfo,Ym as useFetchUserInfo,Rp as useInteractionsFilterGroups,jp as useInteractionsFilterHandler,$u as useMcpConnections,wi as useOAuthPopup,rh as useOptionalDocumentSelection,Em as usePayloadBuilder,Ap as useProcessDefinitionsFilterGroups,Ep as useProcessRunsFilterGroups,Lp as usePromptsFilterGroups,Mp as usePromptsFilterHandler,Op as useRunsFilterGroups,Up as useRunsFilterHandler,Uv as useSearch,Bv as useSearchCount,Xf as useSharedPdf,Yh as useSmartFileUploadProcessing,yp as useTypeRegistry,Yg as useUserPermissions,Vh as useWatchDocumentSearchFacets,qh as useWatchDocumentSearchResult,Wv as useWatchSearchResult,Gp as useWorkflowDefinitionsFilterGroups,Kp as useWorkflowExecutionsFilterGroups,Yp as useWorkflowExecutionsFilterHandler,Zp as useWorkflowRulesFilterGroups};
|
|
2
2
|
//# sourceMappingURL=vertesia-ui-features.js.map
|