@vertesia/ui 1.0.0-dev.20260225.024852Z → 1.0.0-dev.20260227.112605Z
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/esm/env/index.js +3 -0
- package/lib/esm/env/index.js.map +1 -1
- package/lib/esm/features/agent/chat/ModernAgentOutput/utils.js +8 -1
- package/lib/esm/features/agent/chat/ModernAgentOutput/utils.js.map +1 -1
- package/lib/esm/features/facets/CollectionsFacetsNav.js +2 -2
- package/lib/esm/features/facets/CollectionsFacetsNav.js.map +1 -1
- package/lib/esm/features/facets/DocumentsFacetsNav.js +2 -2
- package/lib/esm/features/facets/DocumentsFacetsNav.js.map +1 -1
- package/lib/esm/features/facets/utils/TypeFacet.js +2 -2
- package/lib/esm/features/facets/utils/TypeFacet.js.map +1 -1
- package/lib/esm/features/store/collections/BrowseCollectionView.js +3 -1
- package/lib/esm/features/store/collections/BrowseCollectionView.js.map +1 -1
- package/lib/esm/features/store/objects/DocumentSearchResults.js +2 -1
- package/lib/esm/features/store/objects/DocumentSearchResults.js.map +1 -1
- package/lib/esm/features/store/objects/upload/DocumentUploadModal.js +3 -1
- package/lib/esm/features/store/objects/upload/DocumentUploadModal.js.map +1 -1
- package/lib/esm/features/store/types/ContentObjectTypesSearch.js +4 -3
- package/lib/esm/features/store/types/ContentObjectTypesSearch.js.map +1 -1
- package/lib/esm/features/store/types/SelectContentType.js +8 -8
- package/lib/esm/features/store/types/SelectContentType.js.map +1 -1
- package/lib/esm/features/store/types/SelectContentTypeModal.js +2 -2
- package/lib/esm/features/store/types/SelectContentTypeModal.js.map +1 -1
- package/lib/esm/features/store/types/TypeRegistry.js.map +1 -0
- package/lib/esm/features/store/types/TypeRegistryProvider.js +53 -0
- package/lib/esm/features/store/types/TypeRegistryProvider.js.map +1 -0
- package/lib/esm/features/store/types/index.js +2 -0
- package/lib/esm/features/store/types/index.js.map +1 -1
- package/lib/esm/session/UserSession.js +1 -27
- package/lib/esm/session/UserSession.js.map +1 -1
- package/lib/esm/session/index.js +0 -1
- package/lib/esm/session/index.js.map +1 -1
- package/lib/esm/shell/SplashScreen.js +2 -2
- package/lib/esm/shell/SplashScreen.js.map +1 -1
- package/lib/esm/shell/VertesiaShell.js +2 -2
- package/lib/esm/shell/VertesiaShell.js.map +1 -1
- package/lib/tsconfig.tsbuildinfo +1 -1
- package/lib/types/env/index.d.ts +2 -0
- package/lib/types/env/index.d.ts.map +1 -1
- package/lib/types/features/agent/chat/ModernAgentOutput/utils.d.ts.map +1 -1
- package/lib/types/features/facets/CollectionsFacetsNav.d.ts.map +1 -1
- package/lib/types/features/facets/utils/TypeFacet.d.ts.map +1 -1
- package/lib/types/features/facets/utils/VTypeFacet.d.ts +1 -1
- package/lib/types/features/facets/utils/VTypeFacet.d.ts.map +1 -1
- package/lib/types/features/store/collections/BrowseCollectionView.d.ts.map +1 -1
- package/lib/types/features/store/objects/DocumentSearchResults.d.ts.map +1 -1
- package/lib/types/features/store/objects/upload/DocumentUploadModal.d.ts.map +1 -1
- package/lib/types/features/store/types/ContentObjectTypesSearch.d.ts.map +1 -1
- package/lib/types/features/store/types/TypeRegistry.d.ts.map +1 -0
- package/lib/types/features/store/types/TypeRegistryProvider.d.ts +15 -0
- package/lib/types/features/store/types/TypeRegistryProvider.d.ts.map +1 -0
- package/lib/types/features/store/types/index.d.ts +2 -0
- package/lib/types/features/store/types/index.d.ts.map +1 -1
- package/lib/types/session/UserSession.d.ts +0 -4
- package/lib/types/session/UserSession.d.ts.map +1 -1
- package/lib/types/session/index.d.ts +0 -1
- package/lib/types/session/index.d.ts.map +1 -1
- package/lib/types/shell/VertesiaShell.d.ts.map +1 -1
- package/lib/vertesia-ui-env.js +1 -1
- package/lib/vertesia-ui-env.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-session.js +1 -1
- package/lib/vertesia-ui-session.js.map +1 -1
- package/lib/vertesia-ui-shell.js +1 -1
- package/lib/vertesia-ui-shell.js.map +1 -1
- package/package.json +15 -7
- package/src/env/index.ts +5 -0
- package/src/features/agent/chat/ModernAgentOutput/utils.ts +7 -1
- package/src/features/facets/CollectionsFacetsNav.tsx +2 -2
- package/src/features/facets/DocumentsFacetsNav.tsx +2 -2
- package/src/features/facets/utils/TypeFacet.tsx +2 -2
- package/src/features/facets/utils/VTypeFacet.tsx +1 -1
- package/src/features/store/collections/BrowseCollectionView.tsx +5 -2
- package/src/features/store/objects/DocumentSearchResults.tsx +4 -2
- package/src/features/store/objects/upload/DocumentUploadModal.tsx +3 -1
- package/src/features/store/types/ContentObjectTypesSearch.tsx +4 -3
- package/src/features/store/types/SelectContentType.tsx +8 -8
- package/src/features/store/types/SelectContentTypeModal.tsx +2 -2
- package/src/features/store/types/TypeRegistryProvider.tsx +73 -0
- package/src/features/store/types/index.ts +2 -0
- package/src/session/UserSession.ts +1 -28
- package/src/session/index.ts +0 -1
- package/src/shell/SplashScreen.tsx +4 -2
- package/src/shell/VertesiaShell.tsx +10 -8
- package/lib/esm/session/TypeRegistry.js.map +0 -1
- package/lib/types/session/TypeRegistry.d.ts.map +0 -1
- /package/lib/esm/{session → features/store/types}/TypeRegistry.js +0 -0
- /package/lib/types/{session → features/store/types}/TypeRegistry.d.ts +0 -0
- /package/src/{session → features/store/types}/TypeRegistry.ts +0 -0
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{jsx as e,jsxs as t,Fragment as n}from"react/jsx-runtime";import r,{clsx as s}from"clsx";import{AnimatePresence as a,motion as i}from"motion/react";import o,{useMemo as l,useState as c,createContext as d,useContext as m,useRef as u,useCallback as p,memo as h,useEffect as g,Component as f}from"react";import*as b from"@radix-ui/react-dialog";import{Loader2 as y,Check as v,Copy as x,Download as w,Minimize2 as N,Maximize2 as k,X as C,ExternalLink as S,ChevronDown as _,ChevronRight as j,CopyIcon as I,CheckCircle as P,AlertCircle as T,Layers as z,MessageSquare as A,HelpCircle as D,Send as F,XCircle as E,TableProperties as $,LayoutGrid as O,ChevronsUp as R,ChevronsDown as L,Minus as M,Plus as U,Maximize as V,Image as W,ScanSearch as q,AlertTriangle as B,SquarePen as H,FileSearch as G,Eye as J,Users as K,RefreshCw as Y,UploadIcon as Z,CheckCircleIcon as Q,AlertCircleIcon as X,FileIcon as ee,XCircleIcon as te,FolderIcon as ne,Info as re,ChevronsUpDown as se,FileText as ae,Settings as ie,Trash2 as oe,Search as le,FolderClosed as ce,EllipsisVertical as de,Bot as me,User as ue,Clock as pe,ClipboardList as he,XIcon as ge,MoreVertical as fe,DownloadCloudIcon as be,HelpCircleIcon as ye,FileTextIcon as ve,PaperclipIcon as xe,StopCircleIcon as we,SendIcon as Ne,Activity as ke,Circle as Ce,Loader2Icon as Se,Cpu as _e}from"lucide-react";import je from"papaparse";import{VegaEmbed as Ie}from"react-vega";import{twMerge as Pe}from"tailwind-merge";import{useUserSession as Te}from"@vertesia/ui/session";import{cn as ze,useToast as Ae,Button as De,Center as Fe,VTooltip as Ee,useFetch as $e,ErrorBox as Oe,ResizablePanelGroup as Re,ResizablePanel as Le,ResizableHandle as Me,Spinner as Ue,Modal as Ve,ModalTitle as We,ModalBody as qe,RadioGroup as Be,FormItem as He,Input as Ge,ModalFooter as Je,RadioOptionAdapter as Ke,useTheme as Ye,Portal as Ze,Card as Qe,Separator as Xe,CardContent as et,SelectBox as tt,InputList as nt,Avatar as rt,Table as st,Popover as at,PopoverTrigger as it,PopoverContent as ot,Badge as lt,FilterProvider as ct,FilterBtn as dt,FilterBar as mt,FilterClear as ut,TBody as pt,SharedState as ht,useWatchSharedState as gt,MessageBox as ft,useIntersectionObserver as bt,useFlag as yt,Styles as vt,Checkbox as xt,NumberInput as wt,SidePanel as Nt,Divider as kt,Textarea as Ct,Switch as St,TR as _t,EmptyCollection as jt,ConfirmModal as It,THead as Pt,useDebounce as Tt,Panel as zt,Command as At,CommandInput as Dt,CommandEmpty as Ft,CommandGroup as Et,CommandItem as $t,TagsInput as Ot,SelectList as Rt,DialogDescription as Lt,Heading as Mt,Tabs as Ut,TabsBar as Vt,TabsPanel as Wt,Dropdown as qt,MenuItem as Bt,CommandList as Ht,Breadcrumbs as Gt}from"@vertesia/ui/core";import{AgentMessageType as Jt,PDF_RENDITION_NAME as Kt,ImageRenditionFormat as Yt,WorkflowExecutionStatus as Zt,MarkdownRenditionFormat as Qt,ContentObjectStatus as Xt,ContentNature as en,POSTER_RENDITION_NAME as tn,AUDIO_RENDITION_NAME as nn,PrincipalType as rn,InteractionStatus as sn,SearchTypes as an,SupportedEmbeddingTypes as on,getContentTypeRefId as ln,AgentSearchScope as cn,mergeInCodePromptSchemas as dn,supportsToolUse as mn,FileProcessingStatus as un,normalizeToolCollection as pn}from"@vertesia/common";import{FusionFragmentHandler as hn,FusionFragmentProvider as gn}from"@vertesia/fusion-ux";import fn from"dayjs";import{useNavigate as bn,NavLink as yn}from"@vertesia/ui/router";import{MarkdownRenderer as vn,Popover as xn,XMLViewer as wn,JSONCode as Nn,MonacoEditor as kn,JSONDisplay as Cn,Progress as Sn,DropZone as _n,UploadSummary as jn,useSchema as In,SchemaEditor as Pn,ManagedObject as Tn,GeneratedForm as zn,CodeBlockRendererProvider as An}from"@vertesia/ui/widgets";import{pdfjs as Dn,Document as Fn,Page as En}from"react-pdf";import $n from"dayjs/plugin/localizedFormat";import On from"dayjs/plugin/relativeTime";import{Md5 as Rn}from"ts-md5";import{UserInfo as Ln,SyncMemberHeadsToggle as Mn,SharedPropsEditor as Un}from"@vertesia/ui/features";import Vn,{Ajv as Wn}from"ajv";import{ErrorBoundary as qn}from"react-error-boundary";import{capitalize as Bn}from"lodash-es";import{SidebarItem as Hn}from"@vertesia/ui/layout";function Gn({children:t,secondary:n=!1}){return e("span",{className:n?"bg-secondary text-primary":"text-foreground bg-muted",children:t})}function Jn(e){return e?"array"===e.name?Jn(e.innerType):e:void 0}function Kn({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(Gn,{children:"optional"}),e(Gn,{children:n.type.value})]})}function Yn({activities:t}){return e("div",{className:"flex flex-col gap-y-4 divide-y divide-gray-200",children:t.map(t=>e(Qn,{activity:t},t.name))})}function Zn({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(Gn,{children:n})})]})}function Qn({activity:n,headingClass:r,headingRef:s}){return t("div",{className:r,id:n.name,ref:s,children:[e("div",{className:"text-xl font-semibold pt-8",children:n.title}),e("div",{className:"pb-4",children:e(Gn,{children:n.name})}),n.doc&&e("div",{className:"text-gray-700 pb-2",children:n.doc}),t("div",{className:"pb-4",children:[e(Zn,{code:n.paramsType,children:"Parameters"}),e("div",{className:"divide-y divide-gray-100",children:n.params.map(t=>e(Xn,{property:t},t.name))})]}),t("div",{className:"pb-4",children:[e(Zn,{children:"Returns"}),e("div",{children:n.returnType?n.returnType.value:"void"})]})]})}function Xn({property:n,className:s}){const a=l(()=>{const t=Jn(n.type.innerType)??n.type;return"object"===t.name&&t.members?e(tr,{members:t.members}):"enum"===t.name&&t.enum?e(er,{values:t.enum}):null},[n.type.innerType]);return t("div",{className:r("py-2",s),children:[e(Kn,{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 er({values:t}){return e("div",{className:"flex flex-wrap items-center gap-2",children:t.map((t,n)=>e(Gn,{secondary:!0,children:t},n))})}function tr({members:n}){return e(rr,{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(sr,{isOpen:n}),e("div",n?{children:"Hide child properties"}:{children:"Show child properties"})]}),body:e(nr,{properties:n})})}function nr({properties:t}){return e("div",{className:"border-l-2 border-l-blue-200 flex flex-col divide-y divide-gray-100 border-t border-t-gray-200",children:t.map(t=>e(Xn,{property:t,className:"px-4 py-2"},t.name))})}function rr({button:n,body:s,className:o,isInitiallyOpen:l}){const[d,m]=c(l||!1);return t("div",{className:r(d?"block":"inline-block",o),children:[e("button",{className:"p-0 m-0 bg-transparent",onClick:()=>m(!d),children:e(a,{children:n(d)})}),e(a,{children:d&&e(i.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:s})})]})}function sr({isOpen:t}){return e(a,{propagate:!0,mode:"wait",children:e(i.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 ar(...e){return Pe(s(e))}const ir=d(null);function or({children:t}){const n=u(new Map),r=u(new Map),s=p(e=>n.current.get(e),[]),a=p((e,t)=>{n.current.set(e,t)},[]),i=p(async(e,t)=>{const s=n.current.get(e);if(s)return s;const a=r.current.get(e);if(a)return a;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},[]),l=o.useMemo(()=>({getUrl:s,setUrl:a,getOrFetch:i}),[s,a,i]);return e(ir.Provider,{value:l,children:t})}function lr(){return m(ir)}function cr(e,t,n="inline"){return`artifact:${e}:${t}:${n}`}function dr(e){return`file:${e}`}function mr({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 ur({isOpen:n,onClose:r,title:s,description:a,children:i}){return e(b.Root,{open:n,onOpenChange:e=>!e&&r(),children:t(b.Portal,{children:[e(b.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(b.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:r,children:[e(b.Close,{asChild:!0,children:e("button",{onClick:r,className:"absolute top-3 right-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":"Close fullscreen",children:e(C,{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:i}),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(b.Title,{className:"text-base font-semibold text-gray-900 dark:text-gray-100",children:s||"Dashboard"}),a&&e(b.Description,{className:"text-sm text-gray-500 dark:text-gray-400 mt-0.5",children:a})]})})]})]})})}const pr={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 hr(e,t){if(!e||!e.encoding)return!1;for(const n of t)for(const t of Object.values(e.encoding))if(t&&"object"==typeof t&&t.field===n)return!0;if(Array.isArray(e.layer))for(const n of e.layer)if(hr(n,t))return!0;return!1}function gr(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 fr(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 s of r)if(s in e){const r=e[s];Array.isArray(r)?r.forEach((e,r)=>{n.push(...fr(e,[...t,s,String(r)]))}):"object"==typeof r&&null!==r&&n.push(...fr(r,[...t,s]))}return n}const br=h(function({spec:r,artifactRunId:s}){const{title:a,description:i,spec:o,options:d}=r,[m,h]=c(!1),[f,b]=c(!1),[C,S]=c(null),[_,j]=c(!1),I=u(null),P=u(null),T=u(null),{client:z}=Te(),A=lr(),D=u(z);D.current=z;const F=u(A);F.current=A;const[E,$]=c(null),[O,R]=c(!1),[L,M]=c(null),U=d?.mode||"chart",V="dashboard"===U,W=d?.enableFullscreen??V,q=d?.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)}(o,U);g(()=>{const e=fr(o);if(0===e.length)return $(o),R(!1),void M(null);let t=!1;R(!0),M(null);return(async()=>{const n=new Map,r=D.current,a=F.current;for(const i of e)try{const e=i.path.join(".");let t;if(s&&!i.artifactPath.startsWith("agents/")){const e=cr(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=dr(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=je.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||M(`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 s=n;for(let e=0;e<t.length-1&&void 0!==s[t[e]];e++)s=s[t[e]];const a=t[t.length-1];s[a]&&"object"==typeof s[a]&&(delete s[a].url,s[a].values=r)}return n}(o,n);$(e),R(!1)}})(),()=>{t=!0}},[o,s]);const[B,H]=c(!1),G=u(!1);g(()=>{const e=()=>{const e=document.documentElement.classList.contains("dark");e!==G.current&&(G.current=e,H(e))};e();const t=new MutationObserver(e);return t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),()=>t.disconnect()},[]);const[J,K]=c(0),Y=u(0);g(()=>{if(!T.current)return;let e;const t=new ResizeObserver(t=>{clearTimeout(e),e=setTimeout(()=>{const e=t[0]?.contentRect.width;e&&e!==Y.current&&(Y.current=e,K(e))},100)});t.observe(T.current);const n=T.current.clientWidth;return Y.current=n,K(n),()=>{clearTimeout(e),t.disconnect()}},[]);const Z=l(()=>fr(o).length>0,[o]),Q=l(()=>{if(Z&&!E)return null;let e=E||o;return e?(d?.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&&"object"==typeof n&&n.name&&n.name in t&&(n.value=t[n.name])};Array.isArray(n.params)&&r(n.params);const s=e=>{if(Array.isArray(e))for(const t of e)if(t&&Array.isArray(t.params)&&r(t.params),t.vconcat&&s(t.vconcat),t.hconcat&&s(t.hconcat),t.concat&&s(t.concat),Array.isArray(t.layer))for(const e of t.layer)e&&Array.isArray(e.params)&&r(e.params)};if(n.vconcat&&s(n.vconcat),n.hconcat&&s(n.hconcat),n.concat&&s(n.concat),Array.isArray(n.layer))for(const e of n.layer)e&&Array.isArray(e.params)&&r(e.params);return n}(e,d.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:s}of r){const r=s.select?.fields||[],a="legend"===s.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(hr(t,r)||a&&gr(t,r)){o=e;break}}const l=i[o];l.params||(l.params=[]),l.params.push(s),t.params=t.params.filter(t=>t.name!==e)}return Array.isArray(t.params)&&0===t.params.length&&delete t.params,t}(e)):null},[E,o,Z,d?.parameterValues]),X=p((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),s=Math.floor((t-r)/n);return{...e,hconcat:e.hconcat.map(e=>X(e,s))}}if(e.vconcat&&Array.isArray(e.vconcat))return{...e,vconcat:e.vconcat.map(e=>X(e,t))};if(e.concat&&Array.isArray(e.concat)){const n=e.columns??e.concat.length,r=(e.spacing??10)*(n-1),s=Math.floor((t-r)/n);return{...e,concat:e.concat.map(e=>X(e,s))}}const n=e.width;return"container"===n||"number"==typeof n&&n>t?{...e,width:t}:e},[]),ee=p((e,t=!1)=>{if(!Q)return null;const n=function(e){const t={background:"transparent",view:{stroke:"transparent"},range:{category:pr.categorical,diverging:pr.diverging,heatmap:pr.purples,ramp:pr.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}}}(B),r=t?"undefined"!=typeof window?Math.min(window.innerWidth-80,1400):1200:J>0?J-24:500,s="vconcat"in Q||"hconcat"in Q||"concat"in Q,i=s?{type:"pad",contains:"padding"}:{type:"fit",contains:"padding"};let o=Q;s&&r&&(o=X(Q,r));const l=o.width,c=s?void 0:"container"===l?r:l??r,{width:d,...m}=o;return{$schema:"https://vega.github.io/schema/vega-lite/v6.json",...!s&&c?{width:c}:{},height:t?void 0:e,autosize:i,...s?o:m,...a&&!Q.title?{title:a}:{},config:{...n,...Q.config}}},[Q,a,B,J,X]),te=p(async()=>{const e=_?P.current:I.current;if(e&&!f)try{(await e.toCanvas(2)).toBlob(async e=>{e&&(await navigator.clipboard.write([new ClipboardItem({"image/png":e})]),b(!0),setTimeout(()=>b(!1),2e3))},"image/png")}catch(e){console.error("Failed to copy chart:",e)}},[f,_]),ne=p(async()=>{const e=_?P.current:I.current;if(e&&!m){h(!0);try{const t=await e.toImageURL("png",2),n=document.createElement("a");n.download=`${a||"chart"}.png`,n.href=t,n.click()}catch(e){console.error("Failed to export chart:",e)}finally{h(!1)}}},[a,m,_]),re=p(e=>{I.current=e,S(null)},[]),se=p(e=>{P.current=e},[]),ae=p(e=>{console.error("Vega-Lite rendering error:",e),S(e instanceof Error?e.message:"Unknown error")},[]),ie=p(()=>{j(e=>!e)},[]);g(()=>{S(null)},[o]);const oe=({className:n})=>t("div",{className:ar("flex items-center gap-2",n),children:[t("button",{onClick:te,disabled:f,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:"Copy to clipboard",children:[e(f?v:x,{className:"w-3 h-3"}),f?"Copied":"Copy"]}),t("button",{onClick:ne,disabled:m,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:"Export as PNG",children:[e(w,{className:"w-3 h-3"}),m?"Exporting...":"Export"]}),W&&t("button",{onClick:ie,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:_?"Exit fullscreen":"Fullscreen",children:[e(_?N:k,{className:"w-3 h-3"}),_?"Exit":"Fullscreen"]})]});if(O||Z&&!E)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:a||"Chart"})}),e("div",{className:"flex items-center justify-center bg-gray-50 dark:bg-gray-800 rounded",style:{width:"100%",height:q},children:t("div",{className:"flex items-center gap-2 text-gray-500 dark:text-gray-400",children:[e(y,{className:"w-5 h-5 animate-spin"}),e("span",{className:"text-sm",children:"Loading data from artifacts..."})]})})]})});if(L)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:a||"Chart"})}),e("div",{style:{width:"100%",height:q},children:e(mr,{error:L,chartTitle:a})})]})});if(C)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:a||"Chart"})}),e("div",{style:{width:"100%",height:q},children:e(mr,{error:C,chartTitle:a})})]})});const le=ee(q),ce=ee(0,!0);return le?("undefined"!=typeof window&&localStorage.getItem("DEBUG_VEGA_RENDERS")&&console.log("VegaLite rendering with spec:",{title:a,hasData:!!le.data?.values,dataLength:le.data?.values?.length}),t(n,{children:[e("div",{className:ar("bg-white dark:bg-gray-900 rounded-lg border border-gray-200 dark:border-gray-800 shadow-sm",V&&"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:a||(V?"Dashboard":"Chart")}),V&&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(oe,{})]}),i&&e("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:i}),e("div",{ref:T,className:"bg-white dark:bg-gray-900 rounded overflow-hidden",style:{width:"100%",height:q,minWidth:0},children:e(Ie,{spec:le,onEmbed:e=>re(e.view),onError:ae,options:{renderer:d?.renderer||"canvas",actions:!1}})})]})}),t(ur,{isOpen:_,onClose:()=>j(!1),title:a||(V?"Dashboard":"Chart"),description:i,children:[e("div",{className:"w-full h-full min-h-[calc(100vh-200px)]",children:ce&&e(Ie,{spec:ce,onEmbed:e=>se(e.view),onError:ae,options:{renderer:d?.renderer||"canvas",actions:!1}})}),e("div",{className:"absolute bottom-6 right-6",children:e(oe,{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 yr(e){return"vega-lite"===e.library&&"object"==typeof e.spec}function vr(e){return"recharts"===e.library||void 0===e.library}const xr=h(function({spec:n,artifactRunId:r}){return yr(n)?e(br,{spec:n,artifactRunId:r}):function(e){return"string"==typeof e.$schema&&e.$schema.includes("vega")}(n)?e(br,{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 wr({className:n,inline:r=!1,color:s="blue"}){const a={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"}[s];return t("div",{className:ze("flex items-center gap-1.5",r?"inline-flex":"",n),children:[e("div",{className:`w-2 h-2 bg-gradient-to-r ${a} rounded-full animate-[bounce_1.2s_ease-in-out_infinite]`}),e("div",{className:`w-2 h-2 bg-gradient-to-r ${a} rounded-full animate-[bounce_1.2s_ease-in-out_0.2s_infinite]`}),e("div",{className:`w-2 h-2 bg-gradient-to-r ${a} rounded-full animate-[bounce_1.2s_ease-in-out_0.4s_infinite]`})]})}function Nr({className:n,size:r="md",color:s="blue"}){const a={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:ze("relative flex",n),children:[e("span",{className:ze("animate-ping absolute inline-flex h-full w-full rounded-full opacity-60",a[s])}),e("span",{className:ze("animate-pulse absolute inline-flex h-[80%] w-[80%] rounded-full opacity-80",a[s]),style:{left:"10%",top:"10%",animationDuration:"2s"}}),e("span",{className:ze("relative inline-flex rounded-full",a[s],{sm:"w-3 h-3",md:"w-5 h-5",lg:"w-7 h-7"}[r])})]})}function kr({className:t,color:n="blue"}){const[r,s]=c(".");return g(()=>{const e=setInterval(()=>{s(e=>"."===e?"..":".."===e?"...":".")},500);return()=>clearInterval(e)},[]),e("span",{className:ze({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 Cr({message:n,className:r,color:s="blue"}){const a={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:ze("flex items-center gap-2 py-1",r),children:[t("div",{className:"flex space-x-1",children:[e("div",{className:`w-1.5 h-1.5 ${a[s].dot} rounded-full animate-bounce`}),e("div",{className:`w-1.5 h-1.5 ${a[s].dot} rounded-full animate-bounce`,style:{animationDelay:"0.2s"}}),e("div",{className:`w-1.5 h-1.5 ${a[s].dot} rounded-full animate-bounce`,style:{animationDelay:"0.4s"}})]}),e("div",{className:`${a[s].text} font-medium text-xs`,children:n})]})}function Sr({className:n,color:r="blue",width:s="md",message:a}){const[i,o]=c(15),[l,d]=c("increasing"),[m,p]=c(.4),h=u(null),f=u(!0);g(()=>{const e=h.current;if(!e)return;const t=new IntersectionObserver(([e])=>{f.current=e.isIntersecting},{threshold:0});return t.observe(e),()=>t.disconnect()},[]);return g(()=>{let e,t=Date.now();const n=()=>{if(!f.current)return void(e=requestAnimationFrame(n));const r=Date.now(),s=r-t;t=r,o(e=>{const t=m*(s/16);let n="increasing"===l?e+t:e-t;return n>=85?(d("decreasing"),p(.3+.2*Math.random()),85):n<=15?(d("increasing"),p(.3+.2*Math.random()),15):(Math.random()>.99&&p(e=>Math.max(.2,Math.min(.5,e+(.1*Math.random()-.05)))),n)}),e=requestAnimationFrame(n)};return e=requestAnimationFrame(n),()=>{cancelAnimationFrame(e)}},[l,m]),t("div",{ref:h,className:ze("flex flex-col gap-1",n),children:[a&&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:a}),e("div",{className:ze("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"}[s]),children:e("div",{className:ze("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:`${i}%`,transition:"width 150ms cubic-bezier(0.4, 0.0, 0.2, 1)"}})})]})}function _r({className:t,color:n="blue",size:r="md"}){const[s,a]=c(Array(7).fill(50)),i=u(null),o=u(!0);g(()=>{const e=i.current;if(!e)return;const t=new IntersectionObserver(([e])=>{o.current=e.isIntersecting},{threshold:0});return t.observe(e),()=>t.disconnect()},[]);const l={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 g(()=>{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 s=()=>{if(!o.current)return void(e=requestAnimationFrame(s));r+=.02;const i=Array(7).fill(0).map((e,s)=>10+40*(Math.sin(r*t[s]+n[s])+1));a(i),e=requestAnimationFrame(s)};return e=requestAnimationFrame(s),()=>{cancelAnimationFrame(e)}},[]),e("div",{ref:i,className:ze("flex items-end justify-center",l[r].width,l[r].height,l[r].gap,t),children:s.map((t,s)=>e("div",{className:ze(l[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}},s))})}function jr({className:n,inline:r=!1}){return t("div",{className:ze("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"}})]})}const Ir=d(null);function Pr(){const e=m(Ir);return e||{openImage:e=>window.open(e,"_blank"),closeImage:()=>{}}}function Tr({children:n}){const[r,s]=c(null),a=p((e,t)=>{s({src:e,alt:t})},[]),i=p(()=>{s(null)},[]);return t(Ir.Provider,{value:{openImage:a,closeImage:i},children:[n,r&&e("div",{className:"fixed inset-0 z-[100] flex items-center justify-center bg-black/80 backdrop-blur-sm",onClick:i,children:t("div",{className:"relative max-w-[90vw] max-h-[90vh]",children:[e("img",{src:r.src,alt:r.alt||"Enlarged view",className:"max-w-full max-h-[90vh] object-contain rounded-lg shadow-2xl"}),e("button",{className:"absolute top-2 right-2 text-white bg-black/50 rounded-full p-2 hover:bg-black/70 transition-colors",onClick:i,title:"Close",children:e(C,{className:"size-6"})}),e("a",{href:r.src,target:"_blank",rel:"noopener noreferrer",className:"absolute bottom-2 right-2 text-white bg-black/50 rounded-full p-2 hover:bg-black/70 transition-colors",onClick:e=>e.stopPropagation(),title:"Open in new tab",children:e(S,{className:"size-5"})})]})})]})}const zr=h(function({message:n,batchData:r,isRunning:s=!1,className:a,headerClassName:i,senderClassName:o,progressBarClassName:l,itemListClassName:d,itemClassName:m,summaryClassName:u}){const[p,h]=c(!1),g=Ae(),{tool_name:f,total:b,completed:v,succeeded:x,failed:w,items:N,started_at:k,completed_at:C}=r,S=b>0?v/b*100:0,A=w>0,D=v===b&&!s,F=s||!D?"running":w===b?"error":w>0?"warning":"completed",E=((C?C-k:Date.now()-k)/1e3).toFixed(1);return t("div",{className:ze("border-l-4 shadow-md overflow-hidden bg-white dark:bg-gray-900 mb-5","completed"===F?"border-l-success":"error"===F?"border-l-destructive":"warning"===F?"border-l-attention":"border-l-blue-500",a),children:[t("div",{className:ze("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",i),onClick:()=>h(!p),children:[t("div",{className:"flex items-center gap-2",children:[s||!D?e(Nr,{size:"sm",color:"blue"}):"completed"===F?e(P,{className:"size-4 text-success"}):"error"===F||"warning"===F?e(T,{className:"size-4 text-destructive"}):e(z,{className:"size-4 text-purple-600"}),e("span",{className:ze("text-xs font-medium text-muted",o),children:"Batch"}),e("span",{className:"text-xs text-blue-600 dark:text-blue-400 font-medium",children:f}),t("span",{className:"text-xs text-muted",children:[v,"/",b]}),e(p?_:j,{className:"size-3 text-muted"})]}),t("div",{className:"flex items-center gap-2",children:[t("span",{className:"text-xs text-muted",children:[E,"s"]}),e("span",{className:"text-xs text-muted",children:fn(k).format("HH:mm:ss")}),e(De,{variant:"ghost",size:"xs",onClick:e=>{e.stopPropagation(),(()=>{const e=JSON.stringify(r,null,2);navigator.clipboard.writeText(e).then(()=>{g({status:"success",title:"Copied batch details to clipboard",duration:2e3})})})()},className:"text-muted",title:"Copy batch details",children:e(I,{className:"size-3"})})]})]}),e("div",{className:ze("px-4 py-2 bg-gray-50/50 dark:bg-gray-800/30",l),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 ${A?"bg-attention":D?"bg-success":"bg-blue-500"} transition-all duration-300 ease-out`,style:{width:`${S}%`}})}),t("div",{className:"flex items-center gap-2 text-xs",children:[x>0&&t("span",{className:"text-success flex items-center gap-1",children:[e(P,{className:"size-3"}),x]}),w>0&&t("span",{className:"text-destructive flex items-center gap-1",children:[e(T,{className:"size-3"}),w]}),s&&v<b&&t("span",{className:"text-blue-500 flex items-center gap-1",children:[e(y,{className:"size-3 animate-spin"}),b-v]})]})]})}),p&&N.length>0&&e("div",{className:ze("max-h-64 overflow-y-auto",d),children:N.map(n=>t("div",{className:ze("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",m),children:[t("div",{className:"w-4 flex-shrink-0",children:["success"===n.status&&e(P,{className:"size-3 text-success"}),"error"===n.status&&e(T,{className:"size-3 text-destructive"}),"running"===n.status&&e(y,{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?"Waiting...":"")}),void 0!==n.duration_ms&&t("span",{className:"text-muted flex-shrink-0",children:[(n.duration_ms/1e3).toFixed(1),"s"]})]},n.id))}),!p&&n.message&&e("div",{className:ze("px-4 py-2 text-xs text-muted",u),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))),Ar={default:{border:"border-l-attention",bg:"bg-amber-50 dark:bg-amber-900/20",icon:"text-attention"},warning:{border:"border-l-destructive",bg:"bg-red-50 dark:bg-red-900/20",icon:"text-destructive"},info:{border:"border-l-info",bg:"bg-blue-50 dark:bg-blue-900/20",icon:"text-info"},success:{border:"border-l-success",bg:"bg-green-50 dark:bg-green-900/20",icon:"text-success"}},Dr={default:D,warning:T,info:A,success:P};function Fr({question:n,description:r,options:s,onSelect:a,onMultiSelect:i,onSubmit:l,allowFreeResponse:c=!1,multiSelect:d=!1,placeholder:m="Type your response...",isLoading:u=!1,icon:p,variant:h="default",hideIcon:g=!1,hideBorder:f=!1,className:b,cardClassName:y,headerClassName:v,iconClassName:x,questionClassName:w,descriptionClassName:N,optionsClassName:k,buttonClassName:C,inputContainerClassName:S,inputClassName:_,submitButtonClassName:j}){const[I,P]=o.useState(""),[T,z]=o.useState(new Set),A=o.useRef(null),D=Ar[h],E=Dr[h],$=()=>{I.trim()&&l&&(l(I.trim()),P(""))},O=f?"":`border-l-4 ${D.border}`;return e("div",{className:`my-4 font-sans ${b||""}`,children:t("div",{className:`${O} ${D.bg} rounded-r-lg shadow-sm ${y||""}`,children:[e("div",{className:`px-4 py-3 ${v||""}`,children:t("div",{className:"flex items-start gap-3",children:[!g&&e("div",{className:`flex-shrink-0 mt-0.5 ${D.icon} ${x||""}`,children:p||e(E,{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 ${w||""}`,children:e(vn,{children:n})}),r&&e("p",{className:`mt-1 text-sm text-gray-600 dark:text-gray-400 ${N||""}`,children:r})]})]})}),s&&s.length>0&&e("div",{className:`px-4 pb-3 pt-1 ${k||""}`,children:d?t("div",{className:"space-y-2",children:[s.map(n=>t("label",{className:`flex items-start gap-3 px-4 py-3 rounded-lg cursor-pointer transition-colors\n ${T.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 ${u?"opacity-50 cursor-not-allowed":""}`,children:[e("input",{type:"checkbox",checked:T.has(n.id),onChange:()=>{return e=n.id,void z(t=>{const n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n});var e},disabled:u,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(De,{size:"sm",onClick:()=>{T.size>0&&i&&(i(Array.from(T)),z(new Set))},disabled:u||0===T.size,className:"flex items-center gap-2",children:[e(F,{className:"size-4"}),"Submit Selection",T.size>0?` (${T.size})`:""]})})]}):e("div",{className:"flex flex-col gap-2 w-full",children:s.map(n=>e("button",{onClick:()=>a?.(n.id),disabled:u,className:`w-full text-left 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 ${u?"opacity-50 cursor-not-allowed":"cursor-pointer"}\n ${C||""}`,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",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))})}),c&&e("div",{className:`px-4 pb-3 pt-1 ${S||""}`,children:t("div",{className:"flex gap-2",children:[e("input",{ref:A,type:"text",value:I,onChange:e=>P(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),$())},placeholder:m,disabled:u,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 ${_||""}`}),e(De,{size:"sm",onClick:$,disabled:u||!I.trim(),className:j,children:u?"...":"Send"})]})})]})})}function Er({question:t,description:n,onConfirm:r,onCancel:s,confirmLabel:a="Yes",cancelLabel:i="No",isLoading:o=!1,variant:l="default",className:c}){return e(Fr,{question:t,description:n,variant:l,isLoading:o,className:c,options:[{id:"confirm",label:a,icon:e(P,{className:"size-4"})},{id:"cancel",label:i,icon:e(E,{className:"size-4"})}],onSelect:e=>{"confirm"===e?r():s()}})}const $r=["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..."];function Or(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 Rr=[Jt.COMPLETE,Jt.IDLE,Jt.REQUEST_INPUT,Jt.TERMINATED];function Lr(e){return e.workstream_id?(e.type===Jt.COMPLETE&&console.log("[getWorkstreamId] COMPLETE message with workstream_id:",e.workstream_id),e.workstream_id):(e.type===Jt.COMPLETE&&console.log("[getWorkstreamId] COMPLETE message without workstream_id, defaulting to 'main'"),"main")}function Mr(e){return e.type===Jt.THOUGHT&&!!e.details?.tool}function Ur(e){return e.details?.tool_run_id}function Vr(e){return e.details?.tool_iteration}function Wr(e){return e.details?.tool_status}function qr(e){const t=e.details?.activity_group_id;if("string"==typeof t&&""!==t.trim())return t}function Br(e){return"number"==typeof e?e:new Date(e).getTime()}function Hr(e,t,n){const r=new Map,s=new Map,a=new Map,i=[];for(const t of e){const e=qr(t);if(e)r.has(e)||r.set(e,{messages:[],firstTimestamp:Br(t.timestamp)}),r.get(e).messages.push(t);else if(Mr(t)){const e=Vr(t),n=Ur(t);void 0!==e?(s.has(e)||s.set(e,{messages:[],firstTimestamp:Br(t.timestamp)}),s.get(e).messages.push(t)):n?(a.has(n)||a.set(n,{messages:[],firstTimestamp:Br(t.timestamp)}),a.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})}),s.forEach((e,t)=>{o.push({kind:"iteration_group",iteration:t,messages:e.messages,timestamp:e.firstTimestamp})}),a.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:Br(e.timestamp)});t.forEach((e,t)=>{if(e.text){if(n&&"all"!==n){const t=e.workstreamId||"main";if(n!==t)return}o.push({kind:"streaming",streamingId:t,data:e,timestamp:e.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?l.push({type:"single",message:c[0]}):l.push({type:"tool_group",messages:c,firstTimestamp:Br(c[0].timestamp)}),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)=>Br(e.timestamp)-Br(t.timestamp)),n=t.reduce((e,t)=>Wr(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)=>Br(e.timestamp)-Br(t.timestamp)),n=t.reduce((e,t)=>Wr(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)=>Br(e.timestamp)-Br(t.timestamp)),n=t.reduce((e,t)=>Wr(t)||e,void 0);l.push({type:"tool_group",messages:t,firstTimestamp:e.timestamp,toolRunId:e.toolRunId,toolStatus:n})}else Mr(e.message)?c.push(e.message):(d(),l.push({type:"single",message:e.message}));return d(),l}function Gr(e,t){const n={error:4,warning:3,running:2,completed:1};return(e?n[e]:0)>=(t?n[t]:0)?e??t:t}function Jr(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}),n=null)};for(const s of e)"tool_group"===s.type?n?(n.messages=[...n.messages,...s.messages],n.toolStatus=Gr(n.toolStatus,s.toolStatus),!n.toolRunId&&s.toolRunId&&(n.toolRunId=s.toolRunId)):n={messages:[...s.messages],firstTimestamp:s.firstTimestamp,toolRunId:s.toolRunId,toolStatus:s.toolStatus}:(r(),t.push(s));return r(),t}const Kr="vertesia.content_store.lastDisplayedView";function Yr({onUpdate:t}){const[n,r]=c("grid"===localStorage.getItem(Kr)),s=()=>{localStorage.setItem(Kr,"grid"),r(!0),t(!0)},a=()=>{localStorage.setItem(Kr,"table"),r(!1),t(!1)};return e(De,{variant:"outline",onClick:()=>{n?a():s()},alt:n?"Table View":"Thumbnail View",children:e(n?$:O,{})})}function Zr({className:t,size:n="md"}){return e("div",{className:`flex items-center justify-center ${t||""}`,children:e(y,{className:`${{sm:"w-4 h-4",md:"w-6 h-6",lg:"w-8 h-8"}[n]} animate-spin text-muted-foreground`})})}function Qr({pdfUrl:n,pageNumber:r,width:s,className:a,renderTextLayer:i=!1,renderAnnotationLayer:o=!1,onLoadSuccess:l,onError:d}){const[m,u]=c(!0),[p,h]=c(null);return p?e("div",{className:`flex items-center justify-center text-destructive text-sm ${a||""}`,children:"Failed to load PDF"}):t("div",{className:a,children:[m&&e(Zr,{className:"py-4",size:"md"}),e(Fn,{file:n,onLoadSuccess:({numPages:e})=>{u(!1),l?.(e)},onLoadError:e=>{u(!1),h(e),d?.(e)},loading:null,children:e(En,{pageNumber:r,width:s,renderTextLayer:i,renderAnnotationLayer:o,loading:e(Zr,{className:"py-4",size:"sm"})})})]})}Yr.LAST_DISPLAYED_VIEW=Kr,Dn.GlobalWorkerOptions.workerSrc=`//unpkg.com/pdfjs-dist@${Dn.version}/build/pdf.worker.min.mjs`;const Xr=d(null);function es({pdfUrl:t,urlLoading:n=!1,children:r,onLoadSuccess:s}){const[a,i]=c(0),[o,l]=c(!0),[d,m]=c(null),[u,p]=c(null),h={pdfUrl:t,numPages:a,loading:n||!t||o,error:d,pageDimensions:u};return d?e("div",{className:"flex items-center justify-center text-destructive text-sm py-4",children:"Failed to load PDF"}):e(Xr.Provider,{value:h,children:t?e(Fn,{file:t,onLoadSuccess:async e=>{i(e.numPages),s?.(e.numPages);try{const t=(await e.getPage(1)).getViewport({scale:1});p({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),m(e)},loading:e(Zr,{className:"py-4",size:"md"}),children:r((t,n)=>e(En,{pageNumber:t,width:n,renderTextLayer:!1,renderAnnotationLayer:!1,loading:e(Zr,{className:"py-4",size:"sm"})},t))}):e(Zr,{className:"py-4",size:"md"})})}function ts(){return m(Xr)}const ns=210/297;function rs({pageNumber:t,width:n,className:r}){const s=ts(),a=s?.pageDimensions?.aspectRatio??ns,i=n?Math.round(n/a):200;return e("div",s?.loading?{className:`flex items-center justify-center bg-muted ${r||""}`,style:{height:i,width:n||"100%"},children:e(Zr,{size:"md"})}:{className:r,children:e(En,{pageNumber:t,width:n,renderTextLayer:!1,renderAnnotationLayer:!1,loading:e(Zr,{className:"py-4",size:"sm"})})})}function ss({pageNumber:t,width:n,isSelected:r,onSelect:s,renderThumbnail:a,aspectRatio:i=ns,rootMargin:o="200px 0px"}){const l=u(null),[d,m]=c(!1);g(()=>{const e=l.current;if(!e)return;const t=new IntersectionObserver(e=>{const t=e[0];t?.isIntersecting&&m(!0)},{rootMargin:o,threshold:0});return t.observe(e),()=>t.disconnect()},[o]);const p=n?Math.round(n/i):200,h=d?e(En,{pageNumber:t,width:n,renderTextLayer:!1,renderAnnotationLayer:!1,loading:e("div",{className:"flex items-center justify-center bg-muted",style:{height:p},children:e(Zr,{size:"sm"})})}):e("div",{className:"flex items-center justify-center bg-muted",style:{height:p,width:n||"100%"},children:e("span",{className:"text-muted-foreground text-xs",children:t})});return e("div",{ref:l,children:a({pageNumber:t,isSelected:r,pageElement:h,onSelect:s})})}function as({pdfUrl:r,urlLoading:s=!1,pageCount:a,currentPage:i,thumbnailWidth:o,onPageSelect:l,renderThumbnail:d,scrollContainerRef:m,onAspectRatioChange:h,onItemHeightChange:f,calculateItemHeight:b,onPageCountChange:y}){const[v,x]=c(null),[w,N]=c({start:0,end:Math.min(15,a)}),[k,C]=c(null),S=u(null),_=p(e=>{x(e)},[]),j=p(async e=>{y?.(e.numPages);try{const t=(await e.getPage(1)).getViewport({scale:1}),n=t.width/t.height;C(n),h?.(n)}catch(e){console.error("Failed to get page dimensions:",e),C(ns),h?.(ns)}},[h,y]),I=k??ns,P=o?Math.round(o/I):200,T=b?b(P):P+16+24+8;g(()=>{T>0&&null!==k&&f?.(T)},[T,k,f]);if(g(()=>{const e=m?.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}(S.current);if(!e)return;const t=()=>{const t=e.scrollTop,n=e.clientHeight,r=Math.floor(t/T),s=Math.ceil((t+n)/T),i=Math.max(0,r-5),o=Math.min(a,s+5);N(e=>e.start!==i||e.end!==o?{start:i,end:o}:e)};return t(),e.addEventListener("scroll",t,{passive:!0}),()=>e.removeEventListener("scroll",t)},[T,a,m]),v)return e("div",{className:"flex items-center justify-center text-destructive text-sm py-4",children:"Failed to load PDF"});if(s||!r)return e(Zr,{className:"py-4",size:"md"});const z=w.start*T,A=(a-w.end)*T,D=null!==k;return e("div",{ref:S,children:e(Fn,{file:r,onLoadSuccess:j,onLoadError:_,loading:e(Zr,{className:"py-4",size:"md"}),children:D?t(n,{children:[z>0&&e("div",{style:{height:z}}),Array.from({length:w.end-w.start},(t,n)=>{const r=w.start+n+1;return e("div",{"data-page-index":r-1,style:{height:T,overflow:"hidden"},children:e(ss,{pageNumber:r,width:o,isSelected:r===i,onSelect:()=>l(r),renderThumbnail:d,aspectRatio:I})},r)}),A>0&&e("div",{style:{height:A}})]}):e(Zr,{className:"py-4",size:"md"})})})}function is({pdfUrl:n,pageNumber:r,width:s,height:a,className:i,renderTextLayer:o=!1,renderAnnotationLayer:l=!1,onPageChange:d}){const[m,u]=c(0),[p,h]=c(!0),[f,b]=c(null);g(()=>{m>0&&d?.(r,m)},[r,m,d]);return f?e("div",{className:`flex items-center justify-center text-destructive ${i||""}`,children:t("span",{children:["Failed to load PDF: ",f.message]})}):t("div",{className:i,children:[p&&e(Zr,{className:"py-8",size:"lg"}),e(Fn,{file:n,onLoadSuccess:({numPages:e})=>{u(e),h(!1)},onLoadError:e=>{h(!1),b(e)},loading:null,children:e(En,{pageNumber:Math.min(r,m||1),width:s,height:a,renderTextLayer:o,renderAnnotationLayer:l,loading:e(Zr,{className:"py-8",size:"md"})})})]})}const os=210/297,ls=[50,75,100,125,150,200,300];function cs({pdfUrl:s,pdfUrlLoading:a=!1,pageCount:i,currentPage:o,onChange:l,onPageCountChange:d,className:m,compact:h=!1,headerExtra:f}){const b=u(null),y=u(null),[v,x]=c(void 0),[w,N]=c(100),[k,C]=c(os),[S,_]=c(null),j=u(null),I=v?Math.round(v*w/100):void 0,P=p(()=>{let e=ls.findIndex(e=>e>=w);-1===e&&(e=ls.length-1);const t=Math.min(e+1,ls.length-1);N(ls[t])},[w]),T=p(()=>{let e=ls.findIndex(e=>e>=w);-1===e&&(e=ls.length-1);const t=Math.max(e-1,0);N(ls[t])},[w]),z=p(()=>{N(100)},[]),A=p(e=>e+(h?28:48),[h]),D=(e,t)=>{const n=e?Math.round(e/t):200;return A(n)};g(()=>{const e=y.current;if(!e)return;let t=null;const n=()=>e.clientWidth-16-16-4,r=()=>{const t=n();if(t<=0)return;const r=j.current;if(r&&r>0){const n=e.scrollTop,s=Math.round(n/r),a=D(t,k),i=s*a;x(t),requestAnimationFrame(()=>{e.scrollTo({top:i,behavior:"instant"})}),j.current=a}else x(t),j.current=D(t,k)},s=n();s>0&&(x(s),j.current=D(s,k));const a=new ResizeObserver(()=>{t&&clearTimeout(t),t=setTimeout(r,150)});return a.observe(e),()=>{t&&clearTimeout(t),a.disconnect()}},[k]);const F=u(!1),E=u(null),$=u(w);g(()=>{$.current!==w&&($.current=w,E.current={targetPage:o},F.current=!0)},[w,o]),g(()=>{const e=y.current,t=E.current;if(t&&e&&S){E.current=null;const n=(t.targetPage-1)*S;requestAnimationFrame(()=>{e.scrollTo({top:n,behavior:"instant"}),requestAnimationFrame(()=>{F.current=!1})})}},[S]);const O=u(!1);g(()=>{const e=y.current;if(e&&S&&!O.current)if(o>1){O.current=!0,F.current=!0;const t=(o-1)*S;e.scrollTo({top:t,behavior:"instant"}),requestAnimationFrame(()=>{F.current=!1})}else O.current=!0},[S,o]);const M=u(o);g(()=>{const e=y.current;if(e&&S&&M.current!==o){M.current=o,F.current=!0;const t=(o-1)*S;e.scrollTo({top:t,behavior:"instant"}),requestAnimationFrame(()=>{F.current=!1})}},[o,S]),g(()=>{const e=y.current;if(!e||!S)return;let t=null;const n=()=>{F.current||(t&&clearTimeout(t),t=setTimeout(()=>{const t=e.scrollTop,n=Math.round(t/S)+1,r=Math.max(1,Math.min(n,i));r!==o&&(M.current=r,l(r))},50))};return e.addEventListener("scroll",n,{passive:!0}),()=>{t&&clearTimeout(t),e.removeEventListener("scroll",n)}},[S,i,o,l]);return t("div",{ref:b,className:r("flex flex-col items-stretch",h?"gap-y-1":"gap-y-2",m),children:[t("div",{className:r("relative flex items-center justify-center px-2",h?"h-6":"h-9"),children:[e(De,{variant:"ghost",size:"xs",onClick:()=>{o>1&&l(o-1)},alt:"Previous page",children:e(R,{className:"size-4"})}),t("div",{className:"absolute left-2 flex items-center gap-x-1",children:[e(ms,{zoom:w,onZoomIn:P,onZoomOut:T,onFitToView:z,canZoomIn:w<ls[ls.length-1],canZoomOut:w>ls[0]}),f&&t(n,{children:[e("div",{className:"w-px h-4 bg-border mx-1"}),f]})]}),e("div",{className:"absolute right-2",children:e(ds,{currentPage:o,totalPages:i,onChange:l})})]}),e("div",{ref:y,className:r("flex flex-col items-center flex-1 overflow-y-auto px-2",h?"gap-1":"gap-2"),children:e(as,{pdfUrl:s,urlLoading:a,pageCount:i,currentPage:o,thumbnailWidth:I,onPageSelect:l,onPageCountChange:d,scrollContainerRef:y,onAspectRatioChange:C,onItemHeightChange:_,calculateItemHeight:A,renderThumbnail:({pageNumber:n,isSelected:s,pageElement:a,onSelect:i})=>t("div",{className:r("hover:bg-muted rounded-md w-full",h?"p-1":"p-2"),children:[e("div",{className:r("relative border-[2px] cursor-pointer overflow-hidden",s?"border-primary":"border-border"),onClick:i,children:a}),e(Fe,{className:r("text-muted-foreground font-semibold",h?"text-xs pt-0.5":"text-sm pt-1"),children:n})]},n)})}),e("div",{className:r("flex items-center justify-center",h?"h-6":"h-9"),children:e(De,{variant:"ghost",size:"xs",onClick:()=>{o<i&&l(o+1)},alt:"Next page",children:e(L,{className:"size-4"})})})]})}function ds({currentPage:n,totalPages:r,onChange:s}){const a=u(null),[i,o]=c(String(n));g(()=>{o(String(n))},[n]);const l=()=>{const e=parseInt(i,10);!isNaN(e)&&e>=1&&e<=r?s(e):o(String(n))};return t("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e("span",{children:"Page"}),e("input",{ref:a,type:"text",value:i,onChange:e=>o(e.target.value),onKeyDown:e=>{"Enter"===e.key?(l(),a.current?.blur()):"Escape"===e.key&&(o(String(n)),a.current?.blur())},onBlur:()=>{l()},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 ms({zoom:n,onZoomIn:s,onZoomOut:a,onFitToView:i,canZoomIn:o,canZoomOut:l}){return t("div",{className:"flex items-center gap-x-0.5",children:[e(Ee,{description:"Zoom out",placement:"bottom",size:"xs",children:e("button",{className:r("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:a,disabled:!l,children:e(M,{className:"size-4"})})}),t("span",{className:"text-xs text-muted-foreground min-w-[32px] text-center",children:[n,"%"]}),e(Ee,{description:"Zoom in",placement:"bottom",size:"xs",children:e("button",{className:r("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:s,disabled:!o,children:e(U,{className:"size-4"})})}),e(Ee,{description:"Fit to width",placement:"bottom",size:"xs",children:e("button",{className:r("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(V,{className:"size-4"})})})]})}const us="magic-pdf";var ps;!function(e){e.original="original",e.instrumented="instrumented"}(ps||(ps={}));class hs{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 s=this.pending.get(n);if(s)return s;const a=this.fetchImageUrl(e,t);this.pending.set(n,a);try{const e=await a;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=`${us}/${this.objectId}/pages`;switch(t){case ps.original:return`${n}/page-${e}.original.jpg`;case ps.instrumented:return`${n}/page-${e}.instrumented.jpg`}}}class gs{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=`${us}/${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 fs{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,s=[];let a;for(;null!==(a=r.exec(e));)s.push({page:parseInt(a[1],10),index:a.index+a[0].length});for(let r=0;r<s.length;r++){const a=s[r],i=a.page-1;if(i<0||i>=t)continue;const o=a.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 bs=d(void 0);function ys({children:t,object:n}){const{client:r}=Te(),s=n.metadata.page_count||10,a="markdown"===n.metadata?.content_processor?.type,[i,o]=c(()=>{const e=new fs(s);a&&n.text&&e.initFromContent(n.text);const t=n.text?ws(n.text):"";return{count:s,layoutProvider:new gs(r,n.id,s),markdownProvider:e,imageProvider:new hs(r,n.id,s),xml:t,xmlPages:n.text?xs(t):[],pdfUrl:"",pdfUrlLoading:!0}});return g(()=>{if(a){const e=n.metadata,t=e?.renditions?.find(e=>e.name===Kt),s="application/pdf"===n.content?.type,a=t?.content?.source||(s?n.content?.source:void 0);a?r.store.objects.getDownloadUrl(a,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}))},[n.id,r,a,s]),e(bs.Provider,{value:i,children:t})}function vs(){const e=o.useContext(bs);if(!e)throw new Error("useMagicPdfContext must be used within a MagicPdfProvider");return e}function xs(e){const t=(new DOMParser).parseFromString(ws(e),"text/xml").getElementsByTagName("page"),n=new XMLSerializer;return Array.from(t).map(e=>n.serializeToString(e))}function ws(e){return e.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,"").replace(/<\?xml.*?\?>/g,"")}const Ns=[50,75,100,125,150,200,300],ks=11/8.5;function Cs({className:n,currentPage:s,onChange:a}){const[i,o]=c(ps.instrumented),[l,d]=c(ks),[m,h]=c(new Map),[f,b]=c(100),y=u(new Set),v=u(null),x=u(null),w=u(!1),{imageProvider:N,count:k}=vs(),C=p(()=>{let e=Ns.findIndex(e=>e>=f);-1===e&&(e=Ns.length-1);const t=Math.min(e+1,Ns.length-1);b(Ns[t])},[f]),S=p(()=>{let e=Ns.findIndex(e=>e>=f);-1===e&&(e=Ns.length-1);const t=Math.max(e-1,0);b(Ns[t])},[f]),_=p(()=>{b(100)},[]);g(()=>{N.getPageImageUrl(1,i).then(e=>{const t=new window.Image;t.onload=()=>{t.width>0&&t.height>0&&d(t.height/t.width)},t.src=e}).catch(()=>{})},[N,i]);const j=u(i);g(()=>{let e=!1;j.current!==i&&(j.current=i,y.current=new Set,h(new Map));const t=function(e,t){const n=[e];let r=1;for(;n.length<t;){const s=e+r,a=e-r;s<=t&&n.push(s),a>=1&&n.push(a),r++}return n}(s,k);return t.forEach(t=>(async t=>{if(!e&&!y.current.has(t))try{const n=await N.getPageImageUrl(t,i);e||(y.current.add(t),h(e=>new Map(e).set(t,n)))}catch{}})(t)),()=>{e=!0}},[s,k,i,N]);const I=u(f);g(()=>{if(I.current!==f&&x.current){I.current=f,w.current=!0;const e=x.current.querySelector(`[data-page="${s}"]`);e?requestAnimationFrame(()=>{e.scrollIntoView({behavior:"instant",block:"center"}),requestAnimationFrame(()=>{w.current=!1})}):w.current=!1}},[f,s]);const P=u(s);g(()=>{if(P.current!==s&&x.current){P.current=s,w.current=!0;const e=x.current.querySelector(`[data-page="${s}"]`);e&&e.scrollIntoView({behavior:"instant",block:"nearest"}),requestAnimationFrame(()=>{w.current=!1})}},[s]),g(()=>{const e=x.current;if(!e)return;let t=null;const n=()=>{w.current||(t&&clearTimeout(t),t=setTimeout(()=>{const t=e.getBoundingClientRect(),n=t.top+t.height/2;let r=s,i=1/0;for(let t=1;t<=k;t++){const s=e.querySelector(`[data-page="${t}"]`);if(s){const e=s.getBoundingClientRect(),a=e.top+e.height/2,o=Math.abs(a-n);o<i&&(i=o,r=t)}}r!==s&&(P.current=r,a(r))},50))};return e.addEventListener("scroll",n,{passive:!0}),()=>{t&&clearTimeout(t),e.removeEventListener("scroll",n)}},[k,s,a]);return t("div",{ref:v,className:r("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(De,{variant:"ghost",size:"xs",onClick:()=>{s>1&&a(s-1)},alt:"Previous page",children:e(R,{className:"size-4"})}),t("div",{className:"absolute left-2 flex items-center gap-x-1",children:[e(Ss,{type:ps.original,currentType:i,onClick:()=>o(ps.original),icon:e(W,{className:"size-4"}),tooltip:"Original images"}),e(Ss,{type:ps.instrumented,currentType:i,onClick:()=>o(ps.instrumented),icon:e(q,{className:"size-4"}),tooltip:"Instrumented images"}),e("div",{className:"w-px h-4 bg-border mx-1"}),e(_s,{zoom:f,onZoomIn:C,onZoomOut:S,onFitToView:_,canZoomIn:f<Ns[Ns.length-1],canZoomOut:f>Ns[0]})]}),e("div",{className:"absolute right-2",children:e(Is,{currentPage:s,totalPages:k,onChange:a})})]}),e("div",{ref:x,className:"flex flex-col items-center gap-2 flex-1 overflow-y-auto px-2",children:Array.from({length:k},(t,n)=>e(js,{currentPage:s,pageNumber:n+1,aspectRatio:l,zoom:f,url:m.get(n+1),onSelect:()=>a(n+1)},n))}),e("div",{className:"flex items-center justify-center h-9",children:e(De,{variant:"ghost",size:"xs",onClick:()=>{s<k&&a(s+1)},alt:"Next page",children:e(L,{className:"size-4"})})})]})}function Ss({type:t,currentType:n,onClick:s,icon:a,tooltip:i}){return e(Ee,{description:i,placement:"bottom",size:"xs",children:e("button",{className:r("p-1 rounded cursor-pointer transition-colors",t===n?"text-primary bg-primary/10":"text-muted-foreground hover:text-foreground hover:bg-muted"),onClick:s,children:a})})}function _s({zoom:n,onZoomIn:s,onZoomOut:a,onFitToView:i,canZoomIn:o,canZoomOut:l}){return t("div",{className:"flex items-center gap-x-0.5",children:[e(Ee,{description:"Zoom out",placement:"bottom",size:"xs",children:e("button",{className:r("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:a,disabled:!l,children:e(M,{className:"size-4"})})}),t("span",{className:"text-xs text-muted-foreground min-w-[32px] text-center",children:[n,"%"]}),e(Ee,{description:"Zoom in",placement:"bottom",size:"xs",children:e("button",{className:r("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:s,disabled:!o,children:e(U,{className:"size-4"})})}),e(Ee,{description:"Fit to width",placement:"bottom",size:"xs",children:e("button",{className:r("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(V,{className:"size-4"})})})]})}function js({pageNumber:n,currentPage:s,aspectRatio:a,zoom:i,url:o,onSelect:l}){return t("div",{className:"p-2 hover:bg-muted rounded-md flex flex-col items-center","data-page":n,style:{width:`${i}%`},children:[e("div",{className:r("relative border-[2px] cursor-pointer overflow-hidden flex items-center justify-center bg-muted/50 w-full",n===s?"border-primary":"border-border"),style:{aspectRatio:`1 / ${a}`},onClick:l,children:o?e("img",{src:o,alt:`Page ${n}`,className:"w-full"}):e(y,{className:"w-6 h-6 animate-spin text-muted-foreground"})}),e(Fe,{className:"text-sm text-muted-foreground pt-1 font-semibold",children:n})]})}function Is({currentPage:n,totalPages:r,onChange:s}){const a=u(null),[i,o]=c(String(n));g(()=>{o(String(n))},[n]);const l=()=>{const e=parseInt(i,10);!isNaN(e)&&e>=1&&e<=r?s(e):o(String(n))};return t("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e("span",{children:"Page"}),e("input",{ref:a,type:"text",value:i,onChange:e=>o(e.target.value),onKeyDown:e=>{"Enter"===e.key?(l(),a.current?.blur()):"Escape"===e.key&&(o(String(n)),a.current?.blur())},onBlur:()=>{l()},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 Ps({object:n}){const{client:r}=Te(),s=e=>{(function(e,t,n){return e.files.getDownloadUrl(`${us}/${t}/${n}`).then(e=>e.url)})(r,n.id,e).then(e=>window.open(e,"_blank"))},a="p-2 cursor-pointer hover:bg-muted text-left text-sm";return"markdown"===(()=>{if("document"===n.metadata?.type){const e=n.metadata;return e.content_processor?.type||"xml"}return"xml"})()?e(De,{variant:"ghost",size:"xs",onClick:()=>s("document.md"),alt:"Download",children:e(w,{className:"size-4"})}):t(xn,{strategy:"absolute",placement:"bottom-start",zIndex:100,offset:8,children:[e(xn.Trigger,{click:!0,children:e(De,{variant:"ghost",size:"xs",alt:"Download",children:e(w,{className:"size-4"})})}),e(xn.Content,{children:t("div",{className:"rounded-md shadow-md border border-border bg-popover min-w-[200px] flex flex-col divide-y divide-border",children:[e("button",{className:a,onClick:()=>s("annotated.pdf"),children:"annotated.pdf"}),e("button",{className:a,onClick:()=>s("document.xml"),children:"document.xml"}),e("button",{className:a,onClick:()=>s("analyzed-pages.json"),children:"analyzed-pages.json"})]})})]})}function Ts({className:t}){return e("div",{className:`flex items-center justify-center ${t||""}`,children:e(y,{className:"w-6 h-6 animate-spin text-gray-400"})})}function zs({viewType:t,pageNumber:n}){switch(t){case"json":return e(Ds,{pageNumber:n});case"markdown":return e(Fs,{pageNumber:n});default:return e(As,{pageNumber:n})}}function As({pageNumber:t}){const{xmlPages:n}=vs();return e("div",{className:"px-4 py-2",children:e(wn,{xml:n[t-1],collapsible:!0})})}function Ds({pageNumber:t}){const[n,r]=c(null),[s,a]=c(!0),[i,o]=c(null),{layoutProvider:l}=vs();return g(()=>{a(!0),o(null),l.getPageLayout(t).then(e=>{r(e?JSON.parse(e):null),a(!1)}).catch(e=>{console.error(e),o(e.message||"Failed to load layout"),a(!1)})},[t,l]),s?e("div",{className:"px-4 py-8",children:e(Ts,{})}):i?e("div",{className:"px-4 py-2 text-red-500 text-sm",children:i}):n?e(Nn,{className:"w-full",data:n}):null}function Fs({pageNumber:n}){const[r,s]=c(null),[a,i]=c(!0),[o,l]=c(null),{markdownProvider:d}=vs();return g(()=>{i(!0),l(null),d.getPageMarkdown(n).then(e=>{s(e),i(!1)}).catch(e=>{console.error(e),l(e.message||"Failed to load markdown"),i(!1)})},[n,d]),a?t("div",{className:"h-full flex flex-col items-center justify-center gap-2",children:[e(Ts,{}),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(vn,{children:r}):e("div",{children:"No markdown content available"})})}class Es extends f{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(Oe,{title:"Failed to load PDF viewer",children:this.state.error?.message||"An unexpected error occurred"}),this.props.onClose&&e(De,{variant:"outline",onClick:this.props.onClose,children:"Close"})]})}):this.props.children}}function $s({objectId:n,onClose:r}){const{client:s}=Te(),{data:a,error:i}=$e(()=>s.store.objects.retrieve(n,"+text"),[n]);return i?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(Oe,{title:"Fetching document failed",children:i.message}),r&&e(De,{variant:"outline",onClick:r,children:"Close"})]})}):a?e(Es,{onClose:r,children:e("div",{className:"fixed inset-0 bg-background z-50 flex items-center justify-center",children:e(ys,{object:a,children:e(Os,{object:a,onClose:r})})})}):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:r&&e(De,{variant:"ghost",size:"xs",onClick:r,alt:"Close",children:e(C,{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 Os({object:n,onClose:r}){const{count:s,pdfUrl:a,pdfUrlLoading:i}=vs(),[o,l]=c(1),d=(()=>{if("document"===n.metadata?.type){const e=n.metadata,t=e.content_processor?.type;if("markdown"===t)return"markdown"}return"xml"})();return t(Re,"xml"===d?{direction:"horizontal",className:"absolute inset-0",children:[e(Le,{defaultSize:50,minSize:20,maxSize:80,className:"bg-muted",children:e(Cs,{className:"h-full",currentPage:o,onChange:l})}),e(Me,{className:"w-[4px] bg-border cursor-ew-resize"}),t(Le,{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(Ps,{object:n})}),t("span",{className:"text-xs text-muted-foreground",children:["Page ",o," / ",s]}),e("div",{className:"flex items-center gap-x-2",children:!!r&&e(De,{variant:"ghost",size:"xs",onClick:r,alt:"Close",children:e(C,{className:"size-4"})})})]}),e("div",{className:"flex-1 overflow-auto px-2",children:e(zs,{pageNumber:o,viewType:"xml"})})]})]}:{direction:"horizontal",className:"absolute inset-0",children:[e(Le,{defaultSize:50,minSize:20,maxSize:80,className:"bg-muted",children:e(cs,{pdfUrl:a,pdfUrlLoading:i,pageCount:s,className:"h-full",currentPage:o,onChange:l})}),e(Me,{className:"w-[4px] bg-border cursor-ew-resize"}),t(Le,{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(Ps,{object:n})}),t("span",{className:"text-xs text-muted-foreground",children:["Page ",o," / ",s]}),e("div",{className:"flex items-center gap-x-2",children:!!r&&e(De,{variant:"ghost",size:"xs",onClick:r,alt:"Close",children:e(C,{className:"size-4"})})})]}),e("div",{className:"flex-1 overflow-auto px-2",children:e(zs,{pageNumber:o,viewType:"markdown"})})]})]})}function Rs({object:n,url:r,source:s,className:a}){const{client:i}=Te(),[o,l]=c(1),[d,m]=c(r||""),[u,p]=c(!r),[h,f]=c(0),[b,y]=c(!1);g(()=>{if(r)return m(r),void p(!1);const e=s||n?.content?.source;e?(p(!0),i.files.getDownloadUrl(e).then(e=>{m(e.url)}).catch(e=>{console.error("Failed to get PDF URL:",e)}).finally(()=>{p(!1)})):p(!1)},[r,s,n?.content?.source,i]),g(()=>{const e=n?.metadata,t=e?.pages||e?.page_count||0;t>0&&f(t)},[n?.metadata]);const v=e=>{f(e)};return u?e("div",{className:"flex items-center justify-center h-full",children:e(Ue,{size:"lg"})}):d?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(De,{variant:"ghost",size:"xs",onClick:()=>y(!1),alt:"Close fullscreen",children:e(C,{className:"size-4"})})}),e(cs,{pdfUrl:d,pdfUrlLoading:u,pageCount:h||100,currentPage:o,onChange:l,onPageCountChange:v,className:"flex-1 min-h-0"})]}):e("div",{className:"relative h-full flex flex-col",children:e(cs,{pdfUrl:d,pdfUrlLoading:u,pageCount:h||100,currentPage:o,onChange:l,onPageCountChange:v,className:a,compact:!0,headerExtra:e(Ee,{description:"Fullscreen",placement:"bottom",size:"xs",children:e("button",{className:"p-1 rounded cursor-pointer transition-colors text-muted-foreground hover:text-foreground hover:bg-muted",onClick:()=>y(!0),children:e(k,{className:"size-4"})})})})}):e("div",{className:"flex items-center justify-center h-full text-muted",children:"No PDF available"})}function Ls(e,t=7){return e?"~"+e.slice(-t):""}function Ms(e,t){return e.length>t?e.substring(0,t)+"...":e}const Us="text/csv",Vs="image/",Ws="application/pdf",qs="video/",Bs=["application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/msword","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.ms-powerpoint"],Hs=e=>e===Us||Us.includes(e),Gs=e=>e.startsWith(Vs)||Vs.includes(e),Js=e=>e===Ws||Ws.includes(e),Ks=e=>e.startsWith(qs)||qs.includes(e),Ys=e=>Bs.includes(e),Zs=import.meta.env,Qs={max_hw:Zs?.VITE_RENDITION_HW||256,format:Yt.jpeg,generate_if_missing:!0},Xs="vertesia.content_store.renditionId";async function ea(e,t,n,r,s){if(!t?.content?.type||!(Gs(t.content.type)||Ks(t.content.type)||Js(t.content.type)))return void s("No preview available");s("Preparing preview...");const a=(new Date).getTime()/1e3,i=localStorage.getItem(`${Xs}_${t.id}_${Qs.max_hw}`),o=localStorage.getItem(`${Xs}_${t.id}_${Qs.max_hw}_time`);if(i?.length&&o&&Math.abs(a-parseInt(o))<=900)return n(i),r(`${t.name} Rendition`),s("ready"),i;s("Preparing preview..."),e.objects.getRendition(t.id,Qs).then(a=>{if("generating"===a.status)s("Preparing preview..."),n(""),r(""),setTimeout(()=>ea(e,t,n,r,s),6e4);else{if("failed"===a.status)return s("No preview available"),n(""),void r("");{if(!a?.renditions?.length)return s("No preview available"),n(""),void r("");const e=a.renditions[0];localStorage.setItem(`${Xs}_${t.id}_${Qs.max_hw}`,e),localStorage.setItem(`${Xs}_${t.id}_${Qs.max_hw}_time`,((new Date).getTime()/1e3).toString()),n(e),r(`${t.name} Rendition`),s("ready"),console.log(`Rendition for document ${t.id} retrieved successfully: ${e}`)}}}).catch(e=>{s("No preview available"),console.warn("Failed to retrieve rendition:",e),n(""),r("")})}function ta(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 s=r.document;s.open(),s.write(`<!doctype html><html><head><title>${t}</title></head><body></body></html>`),s.close(),s.title=t;document.querySelectorAll('link[rel="stylesheet"], style').forEach(e=>{s.head.appendChild(e.cloneNode(!0))});const a=s.createElement("style");return a.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',s.head.appendChild(a),s.body.innerHTML=e.innerHTML,r.focus(),r.print(),setTimeout(()=>{n.parentNode?.removeChild(n)},1e3),!0}function na(e){switch(e){case Zt.RUNNING:return"text-info";case Zt.COMPLETED:return"text-success";case Zt.FAILED:return"text-destructive";case Zt.TERMINATED:case Zt.CANCELED:return"text-attention";default:return"text-muted"}}function ra(e){switch(e){case Zt.RUNNING:return"Running";case Zt.COMPLETED:return"Completed";case Zt.FAILED:return"Failed";case Zt.CONTINUED_AS_NEW:return"Continued As New";case Zt.TERMINATED:return"Terminated";case Zt.TIMED_OUT:return"Timed Out";case Zt.CANCELED:return"Canceled";default:return"Unknown"}}class sa extends Ke{labelOf(e){return e.label}idOf(e){return e.id}renderOption(n){return t("div",{children:[e("div",{className:"font-medium",children:n.label}),e("p",{className:"text-sm text-gray-500 dark:text-gray-400 mt-1",children:n.description})]})}}function aa({isOpen:n,onClose:r,onConfirm:s,isLoading:a,uploadedFileName:i}){const o=[{id:"update",label:"Update current version",description:i?"Replace the content file and modify properties directly in the current revision.":"Modify the properties directly in the current revision."},{id:"new-version",label:"Create new version",description:i?"Create a new revision with the replacement file while preserving the original.":"Create a new revision with these property changes while preserving the original."}],l=i?o[1]:o[0],[d,m]=c(l),[u,p]=c(""),h=new sa;g(()=>{n&&(m(l),p(""))},[n,i]);const f="new-version"===d?.id;return t(Ve,{isOpen:n,onClose:r,className:"sm:max-w-md",children:[e(We,{children:"Save Changes"}),e(qe,{children:t("div",{className:"space-y-4",children:[i&&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:["You're about to replace the content file with: ",e("span",{className:"font-bold",children:i})]})}),e("p",{className:"text-sm text-mixer-muted/5",children:"How would you like to save these changes?"}),e(Be,{adapter:h,options:o,value:d,onChange:e=>{m(e)},gap:"gap-4"}),f&&e(He,{label:"Version Label (Optional)",description:"Optional label for the new version.",className:"mt-3 pl-8",children:e(Ge,{value:u,onChange:p,placeholder:"e.g., v1.2, approved, post-review",className:"w-full"})})]})}),t(Je,{children:[e(De,{variant:"secondary",onClick:r,disabled:a,children:"Cancel"}),e(De,{variant:"primary",onClick:async()=>{await s(f,f?u:void 0)},isLoading:a,children:"Save"})]})]})}function ia({isOpen:r,onClose:s,object:a,refetch:i}){const{client:o,store:l}=Te(),d=Ae(),{theme:m}=Ye(),p=bn(),[h,f]=c(!1),[b,y]=c(""),[v,x]=c(!1),[w,N]=c(null),k=u(void 0),[C,S]=c(null),[_,j]=c(null);g(()=>{r&&(y(JSON.stringify(a.properties||{},null,2)),a.type?.id&&async function(e){try{const t=await l.types.retrieve(e);t.object_schema&&S(t.object_schema)}catch(e){console.error("Failed to fetch JSON schema:",e)}}(a.type.id))},[r,a]);return t(n,{children:[t(Ve,{isOpen:r,onClose:s,className:"sm:max-w-[90%] md:max-w-[80%] lg:max-w-[75%] xl:max-w-[70%]",children:[e(We,{children:"Edit Properties"}),t(qe,{children:[t("div",{className:"mb-2 text-sm text-gray-500",children:[a.type?.name?t("span",{children:["Editing properties for object type: ",e("strong",{children:a.type.name})]}):e("span",{children:"Editing properties for generic document"}),C&&e("span",{className:"ml-2 text-green-600",children:"(JSON schema validation enabled)"})]}),e("div",{className:"h-[75vh] border rounded-md overflow-hidden",children:e(kn,{value:b,language:"json",editorRef:k,onChange:e=>{return t=e.state.doc.toString(),void y(t);var t},beforeMount:e=>{C&&e.languages.json.jsonDefaults.setDiagnosticsOptions({validate:!0,schemas:[{uri:"http://myserver/object-schema.json",fileMatch:["*"],schema:C}]})},theme:"dark"===m?"vs-dark":"vs"})})]}),t(Je,{children:[e(De,{variant:"secondary",onClick:s,children:"Cancel"}),e(De,{variant:"primary",onClick:function(){if(!k.current)return;const e=k.current.getValue();try{const t=JSON.parse(e);N(t),x(!0)}catch(e){d({status:"error",title:"Invalid JSON",description:"Please fix the JSON syntax errors before saving.",duration:5e3})}},children:"Save Changes"})]})]}),e(aa,{isOpen:v,onClose:function(){x(!1)},onConfirm:async function(e,t){try{f(!0);const n=w||JSON.parse(b);if(e){const e=await o.objects.update(a.id,{properties:n},{createRevision:!0,revisionLabel:t});e.id!==a.id&&j(e.id),d({status:"success",title:"New version created",description:"A new version with updated properties has been created.",duration:2e3}),x(!1),s(),e.id!==a.id&&setTimeout(()=>{p(`/objects/${e.id}`),d({status:"info",title:"Viewing New Version",description:t?`Now viewing version '${t}'`:"Now viewing the new version",duration:3e3})},100)}else await l.objects.update(a.id,{properties:n}),d({status:"success",title:"Properties updated",description:"The object properties have been updated successfully.",duration:2e3}),i&&await i(),x(!1),s()}catch(e){d({status:"error",title:"Error updating properties",description:e.message||"An error occurred while updating the properties.",duration:5e3}),f(!1)}},isLoading:h})]})}const oa=131072;function la({client:e,toast:t}){const[n,r]=c(!1),s=p(async(n,s)=>{if(n){r(!0);try{ca((await e.files.getDownloadUrlWithOptions({file:n,name:s})).url,s)}catch(e){t({status:"error",title:"Download failed",description:e instanceof Error?e.message:"Failed to get download URL",duration:5e3})}finally{r(!1)}}},[e,t]),a=p((e,t)=>{e&&ca(e,t)},[]),i=p(async(t,n)=>{const r="store"in e?e.store:e,s=await r.rendering.render(t);if(s.download_url)ca(s.download_url,n);else{if(!s.file_uri)throw new Error("No download URL or file URI in response");ca((await e.files.getDownloadUrlWithOptions({file:s.file_uri,name:n})).url,n)}},[e]);return{downloadFromContentSource:s,downloadFromUrl:a,renderDocument:p(async(e,n)=>{r(!0);try{const r=`${n.title||"document"}.${n.format}`;await i({object_id:e,format:n.format,title:n.title,pandoc_options:n.pandocOptions},r),t({status:"success",title:"Document exported",description:`Successfully exported to ${n.format.toUpperCase()}`,duration:2e3})}catch(e){t({status:"error",title:"Export failed",description:e instanceof Error?e.message:"Failed to export document",duration:5e3})}finally{r(!1)}},[i,t]),renderContent:p(async(e,n)=>{r(!0);try{const r=`${n.title||"export"}.${n.format}`;await i({content:e,format:n.format,title:n.title,artifact_run_id:n.artifactRunId,pandoc_options:n.pandocOptions},r),t({status:"success",title:"Content exported",description:`Successfully exported to ${n.format.toUpperCase()}`,duration:2e3})}catch(e){t({status:"error",title:"Export failed",description:e instanceof Error?e.message:"Failed to export content",duration:5e3})}finally{r(!1)}},[i,t]),isDownloading:n}}function ca(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),s=document.createElement("a");s.href=r,s.download=t||da(e),s.style.display="none",document.body.appendChild(s),s.click(),setTimeout(()=>{document.body.removeChild(s),URL.revokeObjectURL(r)},100)}).catch(()=>{const n=document.createElement("a");n.href=e,n.download=t||da(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 da(e){try{const t=new URL(e).pathname.split("/");return t[t.length-1]||"download"}catch{return"download"}}const ma=["image/jpeg","image/jpg","image/png","image/gif","image/webp","image/svg+xml"],ua=["video/mp4","video/webm"],pa=["audio/mp4","audio/m4a","audio/x-m4a","audio/mpeg","audio/ogg","audio/wav","audio/webm"],ha="h-[calc(100vh-208px)]",ga="h-[calc(100vh-228px)]",fa="h-[calc(100vh-218px)]",ba="max-h-[calc(100vh-268px)]";function ya(e){return e===Xt.created||e===Xt.processing}function va(e){return e.metadata?.content_processor?.type}function xa(e){return e?"":"hidden"}var wa;function Na({object:r,loadText:s,refetch:a}){const i=Ae(),o=async(e,t)=>{try{await navigator.clipboard.writeText(e),i({status:"success",title:("text"===t?"Content":"Properties")+" copied",description:`Successfully copied ${t} to clipboard`,duration:2e3})}catch(e){console.error(`Failed to copy ${t}:`,e),i({status:"error",title:"Copy failed",description:`Failed to copy ${t} to clipboard`,duration:5e3})}};return e(n,{children:t(Re,{direction:"horizontal",className:ha,children:[e(Le,{className:"min-w-[100px]",children:e(ka,{object:r,refetch:a??(()=>Promise.resolve()),handleCopyContent:o})}),e(Me,{withHandle:!0}),e(Le,{className:"min-w-[100px]",children:e(Ca,{object:r,loadText:s??!1,handleCopyContent:o,refetch:a})})]})})}function ka({object:r,refetch:s,handleCopyContent:a}){const[i,o]=c(!1),[l,d]=c(!1);return t(n,{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(De,{variant:""+(i?"ghost":"primary"),size:"sm",alt:"Preview properties",onClick:()=>o(!i),children:"Properties"}),e(De,{variant:""+(i?"primary":"ghost"),size:"sm",alt:"View in JSON format",onClick:()=>o(!i),children:"JSON"})]}),t("div",{className:"flex items-center gap-2",children:[r.properties&&e(De,{variant:"ghost",size:"sm",title:"Copy properties",onClick:()=>a(JSON.stringify(r.properties,null,2),"properties"),children:e(x,{className:"size-4"})}),e(De,{variant:"ghost",size:"sm",onClick:()=>{d(!0)},title:"Edit properties",className:"flex items-center gap-2",children:e(H,{className:"size-4"})})]})]}),r.properties?e("div",{className:`${ga} overflow-auto px-2`,children:e(Cn,{value:r.properties,viewCode:i})}):e("div",{className:`${ga} overflow-auto px-2`,children:e("div",{children:"No properties defined"})}),e(ia,{isOpen:l,onClose:()=>{d(!1)},object:r,refetch:s})]})}function Ca({object:n,loadText:r,handleCopyContent:s,refetch:a}){const i=n?.metadata?.type===en.Image,o=n?.metadata?.type===en.Video,l=n?.metadata?.type===en.Audio,d="application/pdf"===n?.content?.type,m=!!n?.content?.type&&Ys(n.content.type),h=ya(n?.status),f=!(!n.transcript||!o&&!l),b=n.metadata,y=b?.renditions?.find(e=>e.name===Kt),[v,x]=c(o?wa.Video:l?wa.Audio:i?wa.Image:wa.Text),{fullText:w,displayText:N,isLoading:k,isCropped:C}=function(e,t,n=!1){const{store:r}=Te(),[s,a]=c(t),[i,o]=c(()=>t&&t.length>oa?t.substring(0,oa):t),[l,d]=c(!1),[m,u]=c(()=>!!t&&t.length>oa),h=p(()=>{d(!0),r.objects.getObjectText(e).then(e=>{a(e.text),e.text&&e.text.length>oa?(o(e.text.substring(0,oa)),u(!0)):(o(e.text),u(!1))}).catch(e=>{console.error("Failed to load text",e),a(void 0),o(void 0),u(!1)}).finally(()=>{d(!1)})},[e,r]);return g(()=>{t&&t.length>oa?(a(t),o(t.substring(0,oa)),u(!0)):(a(t),o(t),u(!1)),n&&!t&&h()},[e,t,n,h]),{fullText:s,displayText:i,isLoading:l,isCropped:m,loadText:h}}(n.id,n.text,r),S=(d||m)&&h,{progress:_,status:j,outputFormat:I,isComplete:P}=function(e,t){const{client:n}=Te(),[r,s]=c(),[a,i]=c(),[o,l]=c(),[d,m]=c(!1);return g(()=>{if(!t)return;let r=!1;return function t(){r||n.objects.analyze(e).getStatus().then(e=>{s(e.progress),i(e.status),l(e.output_format??e.progress?.output_format),e.status===Zt.RUNNING?r||setTimeout(t,2e3):m(!0)}).catch(()=>{r||setTimeout(t,1e4)})}(),()=>{r=!0}},[t,e,n]),{progress:r,status:a,outputFormat:o,isComplete:d}}(n.id,S),{pdfUrl:T,isConverting:z,error:A,triggerConversion:D}=function(e,t){const{client:n}=Te(),[r,s]=c(),[a,i]=c(!1),[o,l]=c(),d=p(async()=>{if(!t||a)return;i(!0),l(void 0);const r=async t=>{try{const a=await n.objects.getRendition(e,{format:Qt.pdf,generate_if_missing:t,sign_url:!0,block_on_generation:!1});"generating"===a.status?setTimeout(()=>r(!1),5e3):"found"===a.status&&a.renditions?.length?(s(a.renditions[0]),i(!1)):"failed"===a.status&&(l("PDF conversion failed"),i(!1))}catch(e){console.error("Failed to convert Office document to PDF:",e),l("Failed to convert to PDF"),i(!1)}};await r(!0)},[e,t,a,n]);return{pdfUrl:r,isConverting:a,error:o,triggerConversion:d}}(n.id,m);g(()=>{P&&j===Zt.COMPLETED&&a?.()},[P,j,a]);const F=(d||m)&&h&&!P&&j===Zt.RUNNING,E=u(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:[i&&e(De,{variant:v===wa.Image?"primary":"ghost",size:"sm",alt:"View Image",onClick:()=>x(wa.Image),children:"Image"}),o&&e(De,{variant:v===wa.Video?"primary":"ghost",size:"sm",alt:"View Video",onClick:()=>x(wa.Video),children:"Video"}),l&&e(De,{variant:v===wa.Audio?"primary":"ghost",size:"sm",alt:"View Audio",onClick:()=>x(wa.Audio),children:"Audio"}),f&&e(De,{variant:v===wa.Transcript?"primary":"ghost",size:"sm",alt:"View Transcript",onClick:()=>x(wa.Transcript),children:"Transcript"}),e(De,{variant:v===wa.Text?"primary":"ghost",size:"sm",alt:"View Text",onClick:()=>x(wa.Text),children:"Text"}),d&&e(De,{variant:v===wa.Pdf?"primary":"ghost",size:"sm",alt:"View PDF",onClick:()=>x(wa.Pdf),children:"PDF"}),m&&e(De,{variant:v===wa.Pdf?"primary":"ghost",size:"sm",alt:"View as PDF",onClick:()=>{x(wa.Pdf),y||T||z||D()},disabled:z,children:z?e(Ue,{size:"sm"}):"PDF"})]}),e(Aa,{object:n})]}),v===wa.Text&&!F&&e(Sa,{object:n,text:N,fullText:w,handleCopyContent:s,textContainerRef:E}),v===wa.Pdf&&m&&(y||T)&&e(Da,{object:n,pdfRendition:y,officePdfUrl:T})]}),e("div",{className:xa(v===wa.Image),children:e(ja,{object:n})}),e("div",{className:xa(v===wa.Video),children:e(Ia,{object:n})}),e("div",{className:xa(v===wa.Audio),children:e(Pa,{object:n})}),f&&e("div",{className:xa(v===wa.Transcript),children:e(za,{object:n,handleCopyContent:s})}),d&&e("div",{className:xa(v===wa.Pdf),children:e(Fa,{object:n})}),m&&e("div",{className:xa(v===wa.Pdf),children:e(Ea,{pdfRendition:y,officePdfUrl:T,officePdfConverting:z,officePdfError:A,onConvert:D})}),F&&e("div",{className:xa(v===wa.Text),children:e($a,{progress:_,status:j,outputFormat:I})}),e("div",{className:xa(v===wa.Text&&!F&&k),children:e("div",{className:"flex justify-center items-center flex-1",children:e(Ue,{size:"lg"})})}),e("div",{className:xa(v===wa.Text&&!F&&!k),children:e(_a,{object:n,text:N,isTextCropped:C,textContainerRef:E})})]})}function Sa({object:r,text:s,fullText:a,handleCopyContent:i}){const{client:o}=Te(),l=Ae(),c=r.content,{renderDocument:d,isDownloading:m}=la({client:o,toast:l}),u=c&&c.type&&"text/markdown"===c.type,p=va(r),h=async e=>{m||(l({status:"info",title:`Preparing ${e.toUpperCase()}`,description:"Rendering your document...",duration:2e3}),await d(r.id,{format:e,title:r.name||"document"}))};return e(n,{children: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:[a&&t(n,{children:[e(De,{variant:"ghost",size:"sm",title:"Copy text",onClick:()=>i(a,"text"),children:e(x,{className:"size-4"})}),e(De,{variant:"ghost",size:"sm",title:"Download text",onClick:e=>{if(e.preventDefault(),e.stopPropagation(),!a)return;let t="txt",n="text/plain";"xml"===p?(t="xml",n="text/xml"):("markdown"===p||u)&&(t="md",n="text/markdown");const s=new Blob([a],{type:n}),i=URL.createObjectURL(s),o=`${r.name||"document"}.${t}`,l=document.createElement("a");l.href=i,l.download=o,l.style.display="none",setTimeout(()=>{l.click(),URL.revokeObjectURL(i)},0)},children:e(w,{className:"size-4"})})]}),u&&s&&t(n,{children:[t(De,{variant:"ghost",size:"sm",onClick:()=>h(Qt.docx),disabled:m,className:"flex items-center gap-2",children:[m?e(Ue,{size:"sm"}):e(w,{className:"size-4"}),"DOCX"]}),t(De,{variant:"ghost",size:"sm",onClick:()=>h(Qt.pdf),disabled:m,className:"flex items-center gap-2",children:[m?e(Ue,{size:"sm"}):e(w,{className:"size-4"}),"PDF"]})]})]})})})}!function(e){e.Text="text",e.Image="image",e.Video="video",e.Audio="audio",e.Pdf="pdf",e.Transcript="transcript"}(wa||(wa={}));const _a=h(({object:r,text:s,isTextCropped:a,textContainerRef:i})=>{const o=r.content,l=ya(r?.status),c="xml"===va(r),d=o&&o.type&&("text/markdown"===o.type||"text/plain"===o.type),m=!c&&(d||function(e){return!!e&&(e.includes("\n# ")||e.includes("\n## ")||e.includes("\n### ")||e.includes("\n* ")||e.includes("\n- ")||e.includes("\n+ ")||e.includes(")}(s));return s?t(n,{children:[a&&e("div",{className:"px-2 py-2 bg-attention/10 border-l-4 border-attention mx-2 mb-2 rounded",children:t("div",{className:"flex items-center gap-2 text-attention",children:[e(B,{className:"size-4"}),e("span",{className:"text-sm font-semibold",children:"Showing first 128K characters only"})]})}),e("div",{className:`max-w-7xl px-2 ${fa} overflow-auto`,ref:i,children:c?e("div",{className:"px-4 py-2",children:e(wn,{xml:s,collapsible:!0})}):m?e("div",{className:"vprose prose-sm p-1",children:e(vn,{components:{a:({node:t,...n})=>{const r=n.href||"";return r.includes("/store/objects/")?e(yn,{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,...s})=>{const a=/language-(\w+)/.exec(n||"");return e("code",{...s,className:a?"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:s})}):e("pre",{className:"text-wrap bg-muted text-muted p-2",children:s})})]}):e("div",{className:"px-2",children:e("div",{children:l?"Extracting content...":"No content"})})});function ja({object:t}){const{client:n}=Te(),[r,s]=c(),a=t.content,i=t.metadata&&t.metadata.type===en.Image;return g(()=>{if(i){s(void 0);(async()=>{const e=a?.type&&ma.includes(a.type);try{const r=await n.objects.getRendition(t.id,{format:Yt.jpeg,generate_if_missing:!1,sign_url:!0});if("found"===r.status&&r.renditions?.length)s(r.renditions[0]);else if(e){const e=await n.files.getDownloadUrl(t.content.source);s(e.url)}}catch(r){if(e){const e=await n.files.getDownloadUrl(t.content.source);s(e.url)}}})()}},[t.id,i,a?.type,a?.source,n]),e("div",{className:"mb-4 px-2",children:r?e("img",{src:r,alt:t.name,className:"w-full object-contain"}):e(Ue,{size:"md"})})}function Ia({object:n}){const{client:r}=Te(),[s,a]=c(),[i,o]=c(),[l,d]=c(!0),m=n.content,u=n.metadata?.type===en.Video,p=n.metadata,h=p?.renditions||[],f=h.find(e=>"video/mp4"===e.content.type)||h.find(e=>"video/webm"===e.content.type),b=m?.type&&ua.includes(m.type),y=h.find(e=>e.name===tn);return g(()=>{a(void 0),o(void 0),d(!0)},[n.id]),g(()=>{(async()=>{if(y?.content?.source)try{const e=await r.files.getDownloadUrl(y.content.source);o(e.url)}catch(e){console.error("Failed to load poster image",e)}})()},[y,r]),g(()=>{if(u&&(f?.content?.source||b)){(async()=>{try{let e;f?.content?.source?e=await r.files.getDownloadUrl(f.content.source):b&&m?.source&&(e=await r.files.getDownloadUrl(m.source)),e&&a(e.url)}catch(e){console.error("Failed to get video URL",e)}finally{d(!1)}})()}else d(!1)},[u,f,b,m?.source,r]),e("div",{className:"mb-4 px-2",children:f||b?l?e("div",{className:"flex justify-center items-center h-[400px]",children:e(Ue,{size:"md"})}):s?e("video",{src:s,poster:i,controls:!0,className:`w-full ${ba} object-contain`,children:"Your browser does not support the video tag."}):e("div",{className:"flex justify-center items-center h-[400px] text-muted",children:"Failed to load video"}):e("div",{className:"flex justify-center items-center h-[400px] text-muted",children:t("div",{className:"text-center",children:[e("p",{children:"No web-compatible video rendition available"}),e("p",{className:"text-sm mt-2",children:"MP4 or WebM format required"})]})})})}function Pa({object:n}){const{client:r}=Te(),[s,a]=c(),[i,o]=c(!0),l=n.content,d=n.metadata?.type===en.Audio,m=n.metadata,u=(m?.renditions||[]).find(e=>e.name===nn),p=l?.type&&pa.includes(l.type);return g(()=>{a(void 0),o(!0)},[n.id]),g(()=>{if(d&&(u?.content?.source||p)){(async()=>{try{let e;u?.content?.source?e=await r.files.getDownloadUrl(u.content.source):p&&l?.source&&(e=await r.files.getDownloadUrl(l.source)),e&&a(e.url)}catch(e){console.error("Failed to get audio URL",e)}finally{o(!1)}})()}else o(!1)},[d,u,p,l?.source,r]),e("div",{className:"mb-4 px-2",children:u||p?i?e("div",{className:"flex justify-center items-center h-[200px]",children:e(Ue,{size:"md"})}):s?t("div",{className:"flex flex-col items-center gap-4",children:[e("audio",{src:s,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: ",Ta(m.duration)]})]}):e("div",{className:"flex justify-center items-center h-[200px] text-muted",children:"Failed to load audio"}):e("div",{className:"flex justify-center items-center h-[200px] text-muted",children:t("div",{className:"text-center",children:[e("p",{children:"No web-compatible audio rendition available"}),e("p",{className:"text-sm mt-2",children:"MP3, M4A, OGG, WAV, or WebM format required"})]})})})}function Ta(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 za({object:n,handleCopyContent:r}){const s=n.transcript,a=s?.text,i=s?.segments,o=a||(i?i.map(e=>e.text).join(" "):""),l=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:o&&e(De,{variant:"ghost",size:"sm",title:"Copy transcript",onClick:()=>r(o,"text"),children:e(x,{className:"size-4"})})}),e("div",{className:`${fa} overflow-auto px-2`,children:i&&i.length>0?e("div",{className:"space-y-2",children:i.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:[l(n.start),n.end&&` - ${l(n.end)}`]}),e("span",{className:"flex-1",children:n.text})]},r))}):a?e("pre",{className:"text-wrap bg-muted text-muted p-2 whitespace-pre-wrap",children:a}):e("div",{className:"text-muted",children:"No transcript available"})})]})}function Aa({object:r}){const[s,a]=c(!1),i=va(r);return"xml"===i||"markdown"===i?t(n,{children:[e(De,{variant:"ghost",size:"sm",onClick:()=>a(!0),title:"Side by side view",children:e(G,{className:"size-4"})}),s&&e(Ze,{children:e($s,{objectId:r.id,onClose:()=>a(!1)})})]}):null}function Da({object:t,pdfRendition:n,officePdfUrl:r}){const{client:s}=Te(),a=Ae(),[i,o]=c(!1);return e("div",{className:"flex items-center gap-2",children:e(De,{variant:"ghost",size:"sm",onClick:async()=>{o(!0);try{let e=r;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),a({status:"error",title:"Download failed",description:"Failed to download the PDF file",duration:5e3})}finally{o(!1)}},disabled:i,title:"Download PDF",children:i?e(Ue,{size:"sm"}):e(w,{className:"size-4"})})})}function Fa({object:t}){return e("div",{className:fa,children:e(Rs,{object:t,className:"h-full"})})}function Ea({pdfRendition:n,officePdfUrl:r,officePdfConverting:s,officePdfError:a,onConvert:i}){return s?t("div",{className:"flex flex-col justify-center items-center flex-1 gap-2",children:[e(Ue,{size:"lg"}),e("span",{className:"text-muted",children:"Converting to PDF..."})]}):a?t("div",{className:"flex flex-col justify-center items-center flex-1 gap-2 text-destructive",children:[e(B,{className:"size-8"}),e("span",{children:a})]}):e("div",n?.content?.source?{className:fa,children:e(Rs,{source:n.content.source,className:"h-full"})}:r?{className:fa,children:e(Rs,{url:r,className:"h-full"})}:{className:"flex flex-col justify-center items-center flex-1 gap-2",children:e(De,{onClick:i,children:"Convert to PDF"})})}function $a({progress:r,status:s,outputFormat:a}){const i=na(s),o=ra(s),l="xml"===a,c=null==r?.percent||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(Oa,{name:l?"Analyze Layouts":"Analyze Page",progress:r.pages}),l&&t(n,{children:[e(Oa,{name:"Extract Tables",progress:r.tables}),e(Oa,{name:"Describe Images",progress:r.images}),e(Oa,{name:"Process Visually",progress:r.visuals})]})]}),t("div",{className:"pt-2 text-sm text-muted",children:["Progress: ",c,"%",e("span",{className:"px-2",children:"•"}),e("span",{className:i,children:o}),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(Sn,{percent:c})]}),!r&&t("div",{className:"flex items-center gap-2 text-muted",children:[e(Ue,{size:"sm"}),e("span",{children:"Loading processing status..."})]})]})}function Oa({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]})]})}function Ra({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(Qe,{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(Xe,{className:"bg-muted h-[2px]"}),t(et,{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 La({selection:n,document:r,onSelectionChange:s,onRowClick:a,previewObject:i,selectedObject:o}){const{client:l}=Te(),[d,m]=c(void 0),[u,p]=c(void 0),[h,f]=c(void 0);return g(()=>{r?.content&&ea(l,r,m,p,f)},[r]),t(Qe,{className:"relative flex flex-col border h-fit w-full "+(o?.id===r.id?"border-attention border-4":""),onClick:()=>a&&a(r),children:[n&&e("div",{className:"absolute top-2 left-2 z-10 flex flex-col items-center gap-1",children:e("input",{checked:n.isSelected(r.id),type:"checkbox",onChange:e=>{e.stopPropagation(),s(r,e)},onClick:e=>e.stopPropagation()})}),e("div",{className:"absolute top-1 right-1 z-10 flex flex-col items-center",children:e(De,{variant:"ghost",size:"sm",title:"Preivew Object",onClick:e=>{e.stopPropagation(),i?.(r.id)},children:e(J,{className:"size-4 "+("ready"===h?"text-muted":"text-white")})})}),d&&"ready"==h?e("img",{src:d,alt:u,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:h}),e(Xe,{className:"bg-gray-200 h-[2px]"}),t(et,{className:"p-2 flex flex-col",children:[t("div",{className:"flex flex-col overflow-hidden",children:[e(Ee,{placement:"top",description:r.properties?.title??r.name,children:e("h3",{className:"text-start font-medium leading-none truncate",children:r.properties?.title??r.name})}),r?.type?.name?e(Ee,{placement:"bottom",size:"xs",description:r?.type?.name,children:e("p",{className:"text-start text-xs text-muted truncate",children:r?.type?.name})}):e("p",{className:"text-xs text-muted",children:" "})]}),r.score&&t("div",{className:"text-xs text-muted w-full flex justify-end",children:["Score: ",r.score.toFixed(4)??"-"]})]})]})}function Ma(e){return`${e._id} (${e.count})`}function Ua(e){return`${e.name} (${e.count})`}function Va({search:t,buckets:n,name:r,placeholder:s,className:a}){const i=t.getFilterValue(r),o=n?.find(e=>JSON.stringify(e._id)===JSON.stringify(i));return e(tt,{filterBy:"_id",className:a,isClearable:!0,optionLabel:Ma,options:n,value:o,onChange:e=>{t.setFilterValue(r,e?._id)},by:"_id",placeholder:s})}function Wa({search:t,name:n,placeholder:r,className:s}){const[a,i]=c([]);return g(()=>{t.setFilterValue(n,a)},[a]),e(nt,{className:s,value:a,onChange:i,placeholder:r})}function qa(e){return`${e.name} (${e.count})`}function Ba({search:t,buckets:n,placeholder:r="Filter by Type",className:s}){const[a,i]=c([]),{typeRegistry:o}=Te(),l=t.getFilterValue("type");g(()=>{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 d=a?.find(e=>e._id===l);return e(tt,{filterBy:"name",className:s,isClearable:!0,optionLabel:qa,options:a,value:d,onChange:e=>{t.setFilterValue("type",e?._id)},by:"_id",placeholder:r})}function Ha({buckets:e,name:t,placeholder:n,type:r,multiple:s}){return function({buckets:e,name:t,placeholder:n,type:r="select",multiple:s=!1}){return{name:t,options:e.map(e=>({label:Ma(e),value:e._id})),type:r,multiple:s,placeholder:`${n??`${t.charAt(0).toUpperCase()+t.slice(1)}`}`,allowCreate:!1}}({buckets:e,name:t,placeholder:n,type:r,multiple:s})}function Ga({buckets:n,typeRegistry:r,type:s="select",multiple:a=!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:s,multiple:a,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:"ml-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)}}}const Ja={},Ka={},Ya={};function Za(e){const{client:t}=Te();return $e(()=>{let n=Ja[e];return n||(n=t.users.retrieve(e).then(e=>e),Ja[e]=n),n},[e])}function Qa(e){const{client:t}=Te();return $e(()=>{let n=Ka[e];return n||(n=t.iam.groups.retrieve(e).then(e=>e),Ka[e]=n),n},[e])}function Xa(e){const{client:t}=Te();return $e(()=>{let n=Ya[e];return n||(n=t.apikeys.retrieve(e).then(e=>e),Ya[e]=n),n},[e])}function ei(){return e("div",{className:"size-8"})}function ti({showTitle:n=!1,size:r="md"}){return e(di,{title:"System User",description:"The system user is used to initialize built-in objects.",children:t("div",{className:"flex gap-2 items-center",children:[e(rt,{src:"/icon.svg",size:r}),n&&e("div",{className:"text-sm font-semibold pl-2",children:"System User"})]})})}function ni({accountId:r,showTitle:s=!1,size:a="md"}){const i=t(n,{children:[e("div",{children:"This user is used by robots like workflow workers."}),t("div",{className:"text-gray-800 dark:text-gray-500 text-sm",children:[e("span",{className:"font-semibold",children:"ID:"})," ",r]})]});return e(di,{title:"Service Account",description:i,children:t("div",{className:"flex flex-row items-center gap-2",children:[e(rt,{src:"/cloud.svg",name:"SA",color:"bg-amber-500",className:"px-[5px] text-white",size:a}),s&&t("div",{className:"text-sm font-semibold pl-2 truncate",children:["Service Account : ",r]})]})})}function ri({agentId:r,onBehalfOfType:s,onBehalfOfId:a,showTitle:i=!1,size:o="md",isScheduleAgent:l=!1}){const c="user"===s&&a,d="apikey"===s&&a,m=Za(a||""),u=Xa(a||""),p=c?m.data:void 0,h=d?u.data:void 0,g=p?"Agent on behalf of":h?"Agent on behalf of API key":"Service Account",f=l?`Schedule ${g}`:g,b=t("div",{className:"space-y-2",children:[p&&e(n,{children:t("div",{className:"flex items-center gap-2",children:[e(rt,{src:p.picture,name:p.name,size:"sm"}),t("div",{children:[e("div",{className:"font-medium",children:p.name||p.email}),p.email&&p.name&&e("div",{className:"text-xs text-muted-foreground",children:p.email})]})]})}),h&&e(n,{children:t("div",{children:[e("div",{className:"font-medium",children:h.name}),t("div",{className:"text-xs text-muted-foreground",children:["Key ID: ",h.id]})]})}),!p&&!h&&t(n,{children:[e("div",{children:"This user is used by robots like workflow workers."}),t("div",{className:"text-gray-800 dark:text-gray-500 text-sm",children:[e("span",{className:"font-semibold",children:"ID:"})," ",r]})]})]});return e(di,{title:f,description:b,children:t("div",{className:"flex items-center gap-2",children:[t("div",{className:"flex items-center -space-x-2",children:[e(rt,{src:"/cloud.svg",color:"bg-amber-500",className:"px-[5px] text-white border-2 border-white dark:border-gray-800",size:o}),p&&e(rt,{src:p.picture,name:p.name,size:o,className:"border-2 border-white dark:border-gray-800"}),h&&e(rt,{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:p?`Agent (${p.name||p.email})`:h?`Agent (${h.name})`:g})]})})}function si({title:t="Error",error:n,showTitle:r=!1,size:s="md"}){return e(ii,{title:t,message:"string"==typeof n?n:n.message,color:"bg-red-500",showTitle:r,size:s})}function ai({userRef:t,showTitle:n=!1,size:r="md"}){if(!t)return e(ii,{title:"Unknown User",message:"User information is not available.",showTitle:n,size:r});const s=t.split(":"),a=s[0];switch(a){case rn.User:return e(li,{userId:s[1],showTitle:n,size:r});case rn.Group:return e(oi,{userId:s[1],showTitle:n,size:r});case"system":return e(ti,{showTitle:n,size:r});case rn.ServiceAccount:return e(ni,{accountId:s.slice(1).join(":"),showTitle:n,size:r});case rn.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(ri,{agentId:t,onBehalfOfType:a,onBehalfOfId:i,showTitle:n,size:r})}case rn.Schedule:{const t=s[1],a=s[2],i=s[3];return e(ri,{agentId:t,onBehalfOfType:a,onBehalfOfId:i,showTitle:n,size:r,isScheduleAgent:!0})}case rn.ApiKey:return e(ci,{keyId:s[1],size:r,showTitle:n});default:return e(si,{title:"Unknown User",error:`Invalid user ref type: ${a}`,showTitle:n,size:r})}}function ii({title:n,message:r,color:s,size:a="md",showTitle:i=!1}){return e(di,{title:n,description:r,children:t("div",{className:"flex flex-row items-center gap-2",children:[e(rt,{color:s,size:a}),i&&e("div",{className:"text-sm font-semibold pl-1",children:n})]})})}function oi({userId:n,showTitle:r=!1,size:s="md"}){const{data:a,error:i}=Qa(n);if(i)return e(si,{title:"Failed to fetch group",error:i,showTitle:r,size:s});if(!a)return e(ei,{});const o=t("div",{className:"space-y-1",children:[a.description&&e("div",{className:"text-sm",children:a.description}),t("div",{className:"text-xs text-muted-foreground",children:["Group ID: ",a.id]}),a.tags&&a.tags.length>0&&e("div",{className:"flex flex-wrap gap-1",children:a.tags.map(t=>e("span",{className:"px-1.5 py-0.5 bg-muted rounded text-xs",children:t},t))})]});return e(di,{title:a.name||"Unnamed Group",description:o,children:t("div",{className:"flex flex-row items-center gap-2",children:[e(K,{className:"size-6 text-indigo-500",size:s}),r&&e("div",{className:"text-sm font-semibold pl-2",children:a.name||"Unnamed Group"})]})})}function li({userId:n,showTitle:r=!1,size:s="md"}){const{data:a,error:i}=Za(n);if(i)return e(si,{title:"Failed to fetch user",error:i,showTitle:r,size:s});if(!a)return e(ei,{});const o=e("div",{className:"truncate",title:a.email,children:a.email});return e(di,{title:a.name||a.email||a.username||"unknown",description:o,children:t("div",{className:"flex flex-row items-center gap-2",children:[e(rt,{src:a.picture,name:a.name,color:"bg-indigo-500",size:s}),r&&e("div",{className:"text-sm font-semibold pl-2",children:a.name||a.email||a.username||"unknown"})]})})}function ci({keyId:n,showTitle:r=!1,size:s="md"}){const{client:a}=Te(),{data:i,error:o}=$e(()=>a.apikeys.retrieve(n),[]);if(o)return e(si,{title:"Failed to fetch the apikey",error:o,showTitle:r,size:s});if(!i)return e(ei,{});const l=e(rt,{name:"PK",color:"bg-pink-500",size:s}),c=t(st,{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:"Key:"}),e("td",{className:"truncate max-w-0",children:i?.name})]}),t("tr",{children:[e("td",{className:"font-semibold w-20",children:"Account:"}),e("td",{className:"truncate max-w-0",children:i?.account})]}),t("tr",{children:[e("td",{className:"font-semibold w-20",children:"Project:"}),e("td",{className:"truncate max-w-0",children:i?.project.name})]})]});return e(di,{title:"Private Key",description:c,children:t("div",{className:"flex flex-row items-center gap-2",children:[l,r&&e("div",{className:"text-sm font-semibold",children:i?.name||i?.account||i?.project.name||"unknown"})]})})}function di({title:n,description:r,children:s}){return t(at,{hover:!0,children:[e(it,{className:"cursor-pointer flex items-center inline-block",children:e("div",{children:s})}),e(ot,{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 mi({buckets:n,name:r,placeholder:s}){return function({buckets:n,name:r,placeholder:s}){const a=n.map(e=>({value:e._id,label:`(${e.count})`}));return{name:r,placeholder:s||`${r.charAt(0).toUpperCase()+r.slice(1)}`,options:a,labelRenderer:r=>{if("Unknown User"===r||!r){const e=n.find(e=>e._id===r);return`Unknown User (${e?.count||0})`}const s=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(ai,{userRef:r,showTitle:!0,size:"sm"})}),t("span",{className:"text-muted-foreground flex-shrink-0",children:["(",s?.count||0,")"]})]})}}}({buckets:n,name:r,placeholder:s})}function ui({search:t,buckets:n,placeholder:r="All Environments",className:s}){const{client:a}=Te(),[i,o]=c([]),l=t.getFilterValue("environment");g(()=>{if(a){const e=n.map(async e=>{let t;return await a.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,a]);const d=i?.find(e=>e._id===l);return e(tt,{filterBy:"name",className:s,isClearable:!0,optionLabel:Ua,options:i,value:d,onChange:e=>{t.setFilterValue("environment",e?._id)},by:"_id",placeholder:r})}function pi(n){const r=[];if(r.push({name:"run_ids",placeholder:"Run ID",type:"text",multiple:!1}),n.interactions){const s=function({buckets:n,name:r,placeholder:s}){return{name:r,placeholder:s,options:n.map(e=>({label:`(${e.count})`,value:e._id})),type:"select",labelRenderer:r=>{const s=n.find(e=>e._id===r),a=s?.name||r;let i="success";if(s?.status)switch(s.status){case sn.published:i="success";break;case sn.archived:i="destructive";break;default:i="attention"}const o=s?.version&&s?.status?`v${s.version} ${s.status}`:s?.status||(s?.version?`v${s.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:a}),o&&e(lt,{variant:i,className:"text-xs w-fit",children:o})]}),t("span",{className:"ml-2 text-xs shrink-0",children:["(",s?.count||0,")"]})]})},filterBy:(e,t)=>{const r=n.find(t=>t._id===e);return(r?.name||e).toLowerCase().includes(t.toLowerCase())}}}({buckets:n.interactions||[],name:"interaction",placeholder:"Interactions"});r.push(s)}if(n.environments){const s=function({buckets:n,name:r}){const s=n.map(e=>({label:`(${e.count})`,value:e._id}));return{name:"environment",placeholder:r.charAt(0).toUpperCase()+r.slice(1),options:s,type:"select",labelRenderer:r=>{const s=n.find(e=>e._id===r);return t("div",{className:"w-full flex items-center",children:[e("span",{className:"text-sm truncate",children:s?.name||r}),t("span",{className:"ml-2 text-xs",children:["(",s?.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(s)}if(r.push({name:"tags",placeholder:"Tags",type:"stringList",multiple:!0}),n.models){const e=Ha({buckets:n.models||[],name:"model"});r.push(e)}if(n.statuses){const e=Ha({buckets:n.statuses||[],name:"status"});r.push(e)}if(n.finish_reason){const e=Ha({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=mi({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});return r.push({name:"workflow_run_ids",placeholder:"Workflow Run ID",type:"text",multiple:!1}),r}function hi(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;r="stringList"===t.type?t.value.map(e=>"string"==typeof e?e:e.value):t.multiple?Array.isArray(t.value)?t.value.map(e=>"object"==typeof e&&e.value?e.value:e):["object"==typeof t.value&&t.value.value?t.value.value:t.value]:Array.isArray(t.value)&&t.value[0]&&"object"==typeof t.value[0]?t.value[0].value:Array.isArray(t.value)&&t.value[0]?t.value[0]:t.value,"run_ids"!==n&&"workflow_run_ids"!==n||Array.isArray(r)||(r=[r]),e.query[n]=r}}),e.search()):e.clearFilters(!0,!1)}}function gi({facets:n,search:r}){const[s,a]=c([]),i=pi(n),o=hi(r);return t(ct,{filterGroups:i,filters:s,setFilters:e=>{const t="function"==typeof e?e(s):e;a(t),o(t)},children:[t("div",{className:"flex justify-between mb-1",children:[e(dt,{}),e(De,{onClick:()=>{r.search()},variant:"outline",title:"Refresh",children:e(Y,{className:"size-5"})})]}),t("div",{className:"flex gap-2 items-center",children:[e(mt,{}),e(ut,{})]})]})}function fi(e){const t=[];if(t.push({placeholder:"Workflow or Run ID",name:"name",type:"text",options:[]}),e.status){const n=Ha({buckets:e.status||[],name:"status",placeholder:"Status"});t.push(n)}if(e.initiated_by){const n=mi({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 bi(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(r="stringList"===t.type?t.value.map(e=>"string"==typeof e?e:e.value):t.multiple?Array.isArray(t.value)?t.value.map(e=>"object"==typeof e&&e.value?e.value:e):["object"==typeof t.value&&t.value.value?t.value.value:t.value]:Array.isArray(t.value)&&t.value[0]&&"object"==typeof t.value[0]?t.value[0].value:Array.isArray(t.value)&&t.value[0]?t.value[0]:t.value,"name"===n)e.query.search_term=r,e.query.name=r;else if("has_reported_errors"===n){const t=Array.isArray(r)?r[0]:r;"true"!==t&&"false"!==t||(e.query[n]="true"===t)}else e.query[n]=r}}),e.search()):e.clearFilters()}}function yi({facets:n,search:r}){const[s,a]=c([]),i=fi(n),o=bi(r);return e(ct,{filterGroups:i,filters:s,setFilters:e=>{const t="function"==typeof e?e(s):e;a(t),o(t)},children:t("div",{className:"flex gap-2 items-center",children:[e(dt,{}),e(mt,{}),e(ut,{})]})})}function vi(e){const{typeRegistry:t}=Te(),n=[];if(n.push({placeholder:"ID",name:"id",type:"text",options:[]}),n.push({placeholder:"Name",name:"name",type:"text",options:[]}),e.type){const r=Ga({buckets:e.type||[],typeRegistry:t,type:"select",multiple:!0});n.push(r)}if(e.status){const t=Ha({buckets: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:e.tags.map(e=>({label:e,value:e}))}),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 xi(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="object"==typeof t.value[0]?t.value[0].value:t.value[0];r={gte:e,lte:e}}else if(2===t.value.length){r={gte:"object"==typeof t.value[0]?t.value[0].value:t.value[0],lte:"object"==typeof t.value[1]?t.value[1].value:t.value[1]}}}else if(t.multiple)if(Array.isArray(t.value))r=t.value.map(e=>"object"==typeof e&&e.value?e.value:e);else{r=["object"==typeof t.value&&t.value.value?t.value.value:t.value]}else r=Array.isArray(t.value)&&t.value[0]&&"object"==typeof t.value[0]?t.value[0].value:Array.isArray(t.value)&&t.value[0]?t.value[0]:t.value;"name"===n?e.query.name=r:"id"===n?e.query.id=r:e.query[n]=r}}),e.search()):e.clearFilters()}}function wi({facets:n,search:r}){const[s,a]=c([]),i=vi(n),o=xi(r);return e(ct,{filterGroups:i,filters:s,setFilters:e=>{const t="function"==typeof e?e(s):e;a(t),o(t)},children:t("div",{className:"flex gap-2 items-center",children:[e(dt,{}),e(mt,{}),e(ut,{})]})})}function Ni(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 ki(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;r="stringList"===t.type?t.value.map(e=>"string"==typeof e?e:e.value):t.multiple?Array.isArray(t.value)?t.value.map(e=>"object"==typeof e&&e.value?e.value:e):["object"==typeof t.value&&t.value.value?t.value.value:t.value]:Array.isArray(t.value)&&t.value[0]&&"object"==typeof t.value[0]?t.value[0].value:Array.isArray(t.value)&&t.value[0]?t.value[0]:t.value,e.query[n]=r}}),e.search(!0)):e.clearFilters(!0,!0)}}function Ci({facets:n,search:r}){const[s,a]=c([]),i=Ni(),o=ki(r);return e(ct,{filterGroups:i,filters:s,setFilters:e=>{const t="function"==typeof e?e(s):e;a(t),o(t)},children:t("div",{className:"flex gap-2 items-center",children:[e(dt,{}),e(mt,{}),e(ut,{})]})})}function Si(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 _i(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;r="stringList"===t.type?t.value.map(e=>"string"==typeof e?e:e.value):t.multiple?Array.isArray(t.value)?t.value.map(e=>"object"==typeof e&&e.value?e.value:e):["object"==typeof t.value&&t.value.value?t.value.value:t.value]:Array.isArray(t.value)&&t.value[0]&&"object"==typeof t.value[0]?t.value[0].value:Array.isArray(t.value)&&t.value[0]?t.value[0]:t.value,e.query[n]=r}}),e.search()):e.clearFilters(!0,!1)}}function ji({facets:n,search:r}){const[s,a]=c([]),i=Si(n),o=_i(r);return e(ct,{filterGroups:i,filters:s,setFilters:e=>{const t="function"==typeof e?e(s):e;a(t),o(t)},children:t("div",{className:"flex gap-2 items-center",children:[e(dt,{}),e(mt,{}),e(ut,{})]})})}function Ii(e){const{typeRegistry:t}=Te(),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 Pi(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;r="stringList"===t.type?t.value.map(e=>"string"==typeof e?e:e.value):t.multiple?Array.isArray(t.value)?t.value.map(e=>"object"==typeof e&&e.value?e.value:e):["object"==typeof t.value&&t.value.value?t.value.value:t.value]:Array.isArray(t.value)&&t.value[0]&&"object"==typeof t.value[0]?t.value[0].value:Array.isArray(t.value)&&t.value[0]?t.value[0]:t.value,e.query[n]=r}}),e.search()):e.clearFilters(!0)}}function Ti({facets:n,search:r}){const[s,a]=c([]),i=Ii(),o=Pi(r);return e(ct,{filterGroups:i,filters:s,setFilters:e=>{const t="function"==typeof e?e(s):e;a(t),o(t)},children:t("div",{className:"flex gap-2 items-center",children:[e(dt,{}),e(mt,{}),e(ut,{})]})})}function zi(e){const t=[];if(e.statuses){const n=Ha({buckets:e.statuses||[],name:"status",placeholder:"Status"});t.push(n)}if(e.initiated_by){const n=mi({buckets:e.initiated_by||[],name:"initiated_by",placeholder:"Initiated By"});t.push(n)}t.push({name:"start",placeholder:"Started After",type:"date",multiple:!1});return t.push({name:"end",placeholder:"Started Before",type:"date",multiple:!1}),t}function Ai(e){return t=>{e.clearFilters(!1,!1),t.forEach(t=>{if(t.value&&t.value.length>0){const n=t.name;let r;r=t.multiple?Array.isArray(t.value)?t.value.map(e=>"object"==typeof e&&e.value?e.value:e):["object"==typeof t.value&&t.value.value?t.value.value:t.value]:Array.isArray(t.value)&&t.value[0]&&"object"==typeof t.value[0]?t.value[0].value:Array.isArray(t.value)&&t.value[0]?t.value[0]:t.value,e.query[n]=r}}),e.search()}}function Di({facets:n,search:r}){const[s,a]=c([]),i=zi(n),o=Ai(r);return e(ct,{filterGroups:i,filters:s,setFilters:e=>{const t="function"==typeof e?e(s):e;a(t),o(t)},children:t("div",{className:"flex justify-between mb-1",children:[t("div",{className:"flex gap-2 items-center",children:[e(dt,{}),e(mt,{}),e(ut,{})]}),e(De,{onClick:()=>{r.search()},variant:"outline",title:"Refresh",children:e(Y,{className:"size-5"})})]})})}class Fi{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 Fi(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 Ei=d(void 0);function $i(){const e=m(Ei);if(!e)throw new Error("useObjectSelection must be used within a ObjectSelectionProvider");return e}function Oi(){return m(Ei)}function Ri({value:t,collectionId:n,children:r}){const[s,a]=c();return g(()=>{const e=new Fi(t,n,{},a);a(e)},[t]),s&&e(Ei.Provider,{value:s,children:r})}fn.extend(On),fn.extend($n);const Li={string(t,n){let r=[];if(t){const e=t.get("slice");e&&r.push(t=>t.slice(parseInt(e)));const n=t.get("max_length");n&&r.push(e=>e.slice(0,parseInt(n))),t.has("upper")&&r.push(e=>e.toUpperCase()),t.has("lower")&&r.push(e=>e.toLowerCase()),t.has("capitalize")&&r.push(e=>e[0].toUpperCase()+e.substring(1)),t.has("ellipsis")&&r.push(e=>e+"...")}return(t,n)=>{let s;if(t){if(s=String(t),r.length>0)for(const e of r)s=e(s)}else s="";return e("td",{children:s},n)}},fileSize:(t,n)=>(t,n)=>{let r="";if(t){const e=Number(t);if(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/Math.pow(1024,n)).toFixed(2)} ${t[n]}`}}}return e("td",{children:r},n)},number(t,n){let r,s;t&&(r=t.get("currency")||void 0,s=t.get("decimals")||void 0);const a=s?parseInt(s):2;return(t,n)=>{let s=new Intl.NumberFormat("en-US",{style:r?"currency":"decimal",currency:r,maximumFractionDigits:a}).format(t);return e("td",{children:s},n)}},objectId(n,r){let s=[],a=!1;if(n){const e=n.get("slice");e&&(a=!0,s.push(t=>t.slice(parseInt(e))))}return(n,i)=>{const o=s.reduce((e,t)=>t(e),n.id);return t("td",{className:"flex justify-between items-center gap-2",children:[a?"~":"",o,e(De,{variant:"ghost",alt:"Preview Object",onClick:e=>{e.stopPropagation(),r?.(n.id)},children:e(J,{className:"size-4"})})]},i)}},objectName(t,n){let r="title";return t&&(r=t.get("title")||"title"),(t,n)=>e("td",{children:t.properties?.[r]||t.name||Ls(t.id)},n)},objectLink(n,r){const s=[];return s.push(e=>e.slice(-7)),(n,a)=>{const i=s.reduce((e,t)=>t(e),n.id);return t("td",{className:"flex justify-between items-center gap-2 max-w-48",children:["~",i,e(De,{variant:"ghost",alt:"Preview Object",onClick:e=>{e.stopPropagation(),r?.(n.id)},children:e(J,{className:"size-4"})})]},a)}},typeLink:(t,n)=>(t,n)=>e("td",{children:t?.name||"n/a"},n),date(t,n){let r="format",s="LLL";if(t){const e=t.get("localized");if(e)s=e;else{const e=t.get("relative");e&&(r=e,s=void 0)}}return(t,n)=>e("td",{children:fn(t)[r](s)},n)}},Mi=Li.string();function Ui(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(n=n[t[e]],!n)return;return n[t[r]]}function Vi(e){return e&&"."!==e?e.split("."):[]}class Wi{layout;renderer=Mi;path;fallbackPath;previewObject;constructor(e,t){if(this.layout=e,this.path=Vi(e.field||""),this.fallbackPath=e.fallback?Vi(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=Li[e](r)}else this.renderer=Li[t]()}}get name(){return this.layout.name}resolveValue(e){let t=Ui(e,this.path);return void 0===t&&this.fallbackPath&&(t=Ui(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",children:this.layout.render(t)},n);const r=this.layout.type||"string",s=r.indexOf("?")>0?r.substring(0,r.indexOf("?")):r;if(("objectId"===s||"objectLink"===s)&&this.previewObject){const e=r.indexOf("?"),a=e>0?new URLSearchParams(r.substring(e+1)):void 0;return Li[s](a,e=>{this.previewObject(t.id)})(t,n)}return this.renderer(this.resolveValue(t),n)}}function qi({objects:n,selection:r,isLoading:s,columns:a,onRowClick:i,selectedObject:o,toggleAll:l,onSelectionChange:c}){return t(st,{className:"w-full border-t",children:[e("thead",{children:t("tr",{children:[r&&e("th",{children:e("input",{type:"checkbox",onChange:l})}),a.map(t=>e("th",{children:t.name},t.name))]})}),t(pt,{isLoading:s,columns:a.length+1,children:[n?.map(n=>t("tr",{className:"cursor-pointer hover:bg-muted group "+(o?.id===n.id?"bg-muted":""),onClick:()=>{i&&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=>c(n,e)})}),a.map((e,t)=>e.render(n,t))]},n.id)),0===n.length&&e("tr",{children:e("td",{colSpan:a.length+(r?1:0),className:"text-center",children:"No objects. Just drag and drop documents or images here to create content objects."})})]})]})}function Bi({objects:r,selection:s,isLoading:a,onSelectionChange:i,onRowClick:o,previewObject:l,selectedObject:c}){return t(n,{children:[e(Ra,{isLoading:a}),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(La,{document:t,selection:s,onSelectionChange:i,onRowClick:o,previewObject:l,selectedObject:c},t.id))})]})}class Hi{client;limit;collectionId;facets=new ht({});result=new ht({objects:[],isLoading:!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:s,score_aggregation:a,dynamic_scaling:i,limit:o}=this.query;this.query={parent:t,...void 0!==n&&{full_text:n},...void 0!==r&&{vector:r},...void 0!==s&&{weights:s},...void 0!==a&&{score_aggregation:a},...void 0!==i&&{dynamic_scaling:i},...void 0!==o&&{limit:o}},e&&this.search()}getFacetBuckets(e){return this.facets.value[e]?.buckets||[]}resetFacets(){this.query={}}reset(e=!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 s={limit:t,offset:n,query:e,facets:r?this.facetSpecs:void 0};return this.collectionId?this.client.collections.searchMembers(this.collectionId,s):this.client.objects.search(s)}_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})}_search(e=!1,t=!1){if(this.isRunning&&e)return Promise.resolve(!1);this.result.value={isLoading:!0,objects:e?this.objects:[],hasMore:!e||this.result.value.hasMore};const n=this.limit,r=e?this.objects.length:0;return this._searchRequest(this.query,n,r,!t).then(async r=>{const s=r.results||[],a=r.facets||{};return this.result.value={isLoading:!1,objects:e?this.objects.concat(s):s,hasMore:s.length===n},!t&&a&&Object.keys(a).length>0&&(this.facets.value=a),!0}).catch(e=>{throw this.result.value={error:e,isLoading:!1,objects:this.objects,hasMore:this.result.value.hasMore},e})}search(e=!1){return this.isRunning&&this.objects.length>0?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 Gi=d(void 0);function Ji(){return m(Gi)}function Ki(){return gt(Ji().facets)}function Yi(){const e=Ji();return{...gt(e.result),search:e}}function Zi(){const e=Ji();return gt(e.facets).total}var Qi;async function Xi(e){try{const t=await e.arrayBuffer(),n=new Rn;n.appendByteArray(new Uint8Array(t));const r=n.end();return r?.toString()}catch(e){return void console.error("Error calculating file hash:",e)}}function eo(){const{client:e}=Te(),t=Ae();return{checkDocumentProcessing:async(n,r,s)=>{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 s=e.slice(r,r+5),a=await Promise.all(s.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 Xi(e),name:e.name,size:e.size,location:n}}));n.push(...a)}return n}(n,r),a=async()=>{const n=t.map(e=>e.hash).filter(Boolean);if(0===n.length)return;const r={"content.etag":{$in:n}};let a;if(s){const t={query:{match:r},select:"id content.etag"};a=(await e.store.collections.searchMembers(s,t)).results}else{const t={query:r,select:"id content.etag"};a=await e.store.objects.find(t)}for(const e of a){const n=t.find(t=>t.hash===e.content?.etag);n&&(n.existingId=e.id,n.action=Qi.SKIP)}},i=async()=>{const n=t.filter(e=>e.action!==Qi.SKIP),r=n.map(e=>e.location),a=Array.from(new Set(r)),i=[];for(const t of a){const r={"content.name":{$in:n.filter(e=>e.location===t).map(e=>e.name)},location:t||"/"};if(s){const t=e.store.collections.searchMembers(s,{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=Qi.UPDATE)}console.log(`Reconciled ${t.filter(e=>e.action===Qi.UPDATE).length}`)};return await a(),await i(),t.forEach(e=>{e.action||(e.action=Qi.CREATE)}),console.log("Document processing check results:",{totalFiles:n.length,toCreate:t.filter(e=>e.action===Qi.CREATE).length,toUpdate:t.filter(e=>e.action===Qi.UPDATE).length,toSkip:t.filter(e=>e.action===Qi.SKIP).length}),t}catch(e){throw t({title:"Error in file upload processing check",status:"error",description:e.message}),console.log("Error in file upload processing check",e),new Error("Error in file upload processing check: "+e.message)}}}}function to({isOpen:r,onClose:s,files:a,collectionId:i,selectedFolder:o,title:d="Upload Files",children:m,onUploadComplete:u,hideFileSelection:p=!1,showTypeSelectionOnly:h=!1,allowFolders:f=!0}){const{client:b,typeRegistry:y}=Te(),v=Ae(),[x,w]=c([]),[N,k]=c([]),[C,S]=c(!1),[_,j]=c(null),[I,P]=c([]),[T,z]=c(!1),[A,D]=c(!1),[F,E]=c(0),[$,O]=c(Date.now()),[R,L]=c(void 0),[M,U]=c(null),[V,W]=c(d),[q,B]=c("");g(()=>{i&&b.store.collections.retrieve(i).then(L)},[i]),g(()=>{T?(W("Uploading Files"),B(`${Math.round(F)}% complete`)):A?(W("Upload Complete"),B("")):C?(W("File Analysis Results"),B(`${x.length} file${1!==x.length?"s":""}`)):x.length>0?(W(d),B("Checking for duplicates and updates")):(W(d),B(""))},[T,A,C,d,F,x.length]);const H=()=>R||o?t(ft,{className:"mb-4",status:"default",icon:e(ne,{className:"size-5"}),children:[e("div",{className:"flex items-center",children:e("span",{className:"font-medium",children:"Upload Location:"})}),t("div",{className:"text-sm mt-1",children:[R&&t("div",{className:"flex items-center",children:[e("span",{className:"mr-1",children:"Collection:"}),e("span",{className:"font-medium",children:R.name})]}),o&&t("div",{className:"flex items-center mt-1",children:[e("span",{className:"mr-1",children:"Folder:"}),e("span",{className:"font-medium",children:o})]})]})]}):null,[G,J]=c({toCreate:0,toUpdate:0,toSkip:0}),{checkDocumentProcessing:K}=eo(),Y=l(()=>y?.types||[],[y?.types]);g(()=>{r&&(k([]),S(!1),j(null),P([]),z(!1),D(!1),E(0),J({toCreate:0,toUpdate:0,toSkip:0}),U(null),W(d),B(""),a&&a.length>0?(w(a),ie(a)):w([]),O(Date.now()))},[r,a]);const se=()=>{w([]),k([]),S(!1),j(null),P([]),z(!1),D(!1),E(0),J({toCreate:0,toUpdate:0,toSkip:0}),U(null),W(d),B(""),O(Date.now()),s()},ae=e=>{e&&e.length>0&&(w(e),ie(e))},ie=async e=>{if(e.length)try{console.log(`Processing ${e.length} files to determine required actions...`);const t=await K(e,o,i);k(t);const n=t.filter(e=>e.action===Qi.CREATE).length,r=t.filter(e=>e.action===Qi.UPDATE).length,s=t.filter(e=>e.action===Qi.SKIP).length;J({toCreate:n,toUpdate:r,toSkip:s}),v({title:"Files analyzed",description:`${e.length} file(s): ${n} new, ${r} to update, ${s} to skip`,status:"info",duration:4e3}),S(!0)}catch(e){console.error("Error processing files:",e),v({title:"Error",description:"There was an error analyzing the files",status:"error",duration:5e3})}},oe=async()=>{if(!N.length)return;const e=_?.id||null,t=N.map(e=>({file:e.file,status:"pending",progress:0,action:e.action===Qi.CREATE?"create":e.action===Qi.UPDATE?"update":"skip"}));P(t),z(!0),D(!1);const n=N.filter(e=>e.action===Qi.SKIP),r=N.filter(e=>e.action===Qi.UPDATE),s=N.filter(e=>e.action===Qi.CREATE),a={success:!0,objectIds:[],uploadedFiles:[],skippedFiles:[],failedFiles:[]};for(const t of n)t.existingId&&(a.objectIds.push(t.existingId),a.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 o=async(t,n)=>{const r=[];for(let e=0;e<t.length;e+=50)r.push(t.slice(e,e+50));for(let s=0;s<r.length;s++){const o=r[s];if(console.log(`Processing ${n} batch ${s+1}/${r.length} (${o.length} files)`),t.length>50){v({title:`Processing files (${n})`,description:`Processed ${50*s}/${t.length} files...`,status:"info",duration:2e3})}let l=0;await Promise.all(o.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 b.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)),a.objectIds.push(t.existingId),a.uploadedFiles.push({id:t.existingId,name:t.name,type:e,status:"updated",location:t.location});else{const n=await b.store.objects.create({type:e||void 0,content:t.file,location:t.location||t.file.webkitRelativePath||t.name},{collection_id:i});P(e=>e.map(e=>e.file===t.file?{...e,status:"success",progress:100,id:n.id}:e)),a.objectIds.push(n.id),a.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:n.message||"Unknown error"}:e)),a.failedFiles.push({name:t.name,error:n.message||"Unknown error",status:"failed",location:t.location,type:e}),a.success=!1}l++,l%5!=0&&l!==o.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 E(r),e})}))}};r.length>0&&await o(r,"update"),s.length>0&&await o(s,"create"),P(e=>{const t=e.filter(e=>"pending"===e.status).map(e=>({...e,status:"error",progress:100,message:"Upload process interrupted"}));return t.length>0?(t.forEach(e=>{a.failedFiles.push({name:e.file.name,error:"Upload process interrupted",status:"failed",type:_?.id||null})}),a.success=!1,e.map(e=>"pending"===e.status?{...e,status:"error",progress:100,message:"Upload process interrupted"}:e)):e}),z(!1),D(!0);const l=a.uploadedFiles.filter(e=>"created"===e.status).length,c=a.uploadedFiles.filter(e=>"updated"===e.status).length,d=a.skippedFiles.length,m=a.failedFiles.length;let u="";l>0&&(u+=`${l} file${1!==l?"s":""} uploaded`),c>0&&(u+=u?", ":"",u+=`${c} file${1!==c?"s":""} updated`),d>0&&(u+=u?", ":"",u+=`${d} file${1!==d?"s":""} skipped`),m>0&&(u+=u?", ":"",u+=`${m} file${1!==m?"s":""} failed`),v({title:"Upload Complete",description:u,status:m>0?"warning":"success",duration:5e3}),U(a)},le=()=>t("div",{className:"mb-4",children:[t("label",{className:"block text-sm font-medium mb-2",children:["Content Type ",e("span",{className:"text-muted font-normal",children:"(Optional)"}),e(Ee,{description:"Select a content type to apply to the uploaded files. If left empty, Vertesia will automatically detect the type based on file content.",placement:"top",size:"xs",children:e(re,{className:"size-3 ml-2"})})]}),e(tt,{options:Y,value:_,optionLabel:e=>e?e.name:"Select a content type",placeholder:"Select a content type or leave empty for automatic detection",onChange:e=>j(void 0===e?null:e),filterBy:"name",isClearable:!0}),_?e(n,{}):e("div",{className:"p-2 rounded-md",children:t("div",{className:"flex items-center text-attention",children:[e(Q,{className:"size-4 mr-1"}),"Automatic Type Detection",e(Ee,{description:"Vertesia will analyze the content and select the most appropriate type. This is recommended for most uploads and ensures optimal processing.",placement:"top",size:"xs",children:e(re,{className:"size-3 ml-2"})})]})})]});return t(Ve,{isOpen:r,onClose:se,className:"mx-auto",disableCloseOnClickOutside:!0,children:[e(We,{description:q,children:V}),h?t(qe,{children:[m,H(),le()]}):0!==x.length||p?T||A?T?t(qe,{children:[H(),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:I.map((n,r)=>t("div",{className:"flex items-center py-2 border-b border-border last:border-b-0",children:[t("div",{className:"mr-3",children:["pending"===n.status&&e(ee,{className:"size-5 text-muted"}),"uploading"===n.status&&e(Ue,{size:"sm"}),"success"===n.status&&e(Q,{className:"size-5 text-success"}),"error"===n.status&&e(te,{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&&"Waiting...","uploading"===n.status&&"Uploading...","success"===n.status&&("create"===n.action?"Created":"update"===n.action?"Updated":"Skipped"),"error"===n.status&&n.message]})]})]},`${n.file.name}-${r}`))})]}):e(qe,{children:t("div",{className:"mb-4",children:[H(),e(jn,{files:I.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:o||void 0,collection:R?.name})]})}):e(qe,{children:C?t(n,{children:[H(),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(Z,{className:"size-5 text-primary"}),e("span",{className:"font-medium",children:"New"})]}),e("div",{className:"text-2xl font-semibold",children:G.toCreate})]}),t("div",{className:"flex flex-col items-center",children:[t("div",{className:"flex items-center gap-2",children:[e(Q,{className:"size-5 text-success"}),e("span",{className:"font-medium",children:"Update"})]}),e("div",{className:"text-2xl font-semibold",children:G.toUpdate})]}),t("div",{className:"flex flex-col items-center",children:[t("div",{className:"flex items-center gap-2",children:[e(X,{className:"size-5 text-mixer-attention/40"}),e("span",{className:"font-medium",children:"Skip"})]}),e("div",{className:"text-2xl font-semibold",children:G.toSkip})]})]})})}),le(),e(ft,{className:"mb-4",status:"info",children:G.toCreate+G.toUpdate>0?t("div",{className:"space-y-1",children:[t("p",{children:[G.toCreate+G.toUpdate," file",G.toCreate+G.toUpdate>1?"s are":" is"," ready to process"]}),e("p",{children:G.toSkip>0&&`${G.toSkip} file${G.toSkip>1?"s are":" is"} already in the system and will be skipped.`})]}):G.toSkip>0?t("span",{children:["All ",G.toSkip," file(s) already exist in the system and will be skipped. You can proceed to view the results."]}):e("span",{children:"No files to process."})})]}):t("div",{className:"flex flex-col items-center justify-center py-4",children:[e(Ue,{size:"lg",className:"mb-4"}),e("div",{className:"text-lg font-medium",children:"Analyzing files..."})]})}):t(qe,{className:"flex flex-col items-center justify-center p-8",children:[H(),e(_n,{onDrop:ae,message:"Drag and drop files here or click to select",buttonLabel:"Select Files",className:"w-full h-64",allowFolders:f}),m]}),(()=>{if(h)return t(Je,{children:[e(De,{variant:"ghost",onClick:se,children:"Cancel"}),e(De,{onClick:()=>{u&&u({success:!0,objectIds:[],uploadedFiles:[{name:"type-selection",type:_?.id||null,status:"created"}],skippedFiles:[],failedFiles:[]}),se()},children:_?`Use ${_.name}`:"Use Automatic Type Detection"})]});if(0===x.length&&!p)return e(Je,{children:e(De,{variant:"ghost",onClick:se,children:"Cancel"})});if(!T&&!A){const n=C;return t(Je,{children:[e(De,{variant:"ghost",onClick:se,children:"Cancel"}),e(De,{disabled:!n,onClick:oe,children:G.toCreate+G.toUpdate>0?"Upload":"Continue"})]})}return T?e(Je,{children:e(De,{variant:"ghost",disabled:!0,children:"Uploading..."})}):t(Je,{children:[e(De,{variant:"ghost",onClick:()=>{w([]),k([]),S(!1),j(null),P([]),z(!1),D(!1),E(0),J({toCreate:0,toUpdate:0,toSkip:0})},children:"Upload More"}),e(De,{onClick:()=>{u&&M&&u(M),se()},children:"Close"})]})})()]},$)}function no(e){const t="function"==typeof e?e:e.onUploadDone,{client:n,project:r,store:s}=Te(),a=Ji(),i=Ae(),{checkDocumentProcessing:o}=eo();return async(e,l,c)=>{const d={success:!1,objectIds:[],uploadedFiles:[],skippedFiles:[],failedFiles:[]};if(!r)return i({status:"error",title:"No project selected",duration:3e3}),d;if(!e||0===e.length)return i({status:"warning",title:"No files selected",duration:3e3}),d;const m=Array.from(e).filter(e=>e.size>0);if(0===m.length)return i({status:"error",title:"No valid files selected",description:"Please select files with valid content.",duration:5e3}),d;const u=[],p=[],h=[];console.log(`Processing ${m.length} files with smart file processing...`);const g=await o(m,null,c),f=g.filter(e=>e.action===Qi.CREATE).length,b=g.filter(e=>e.action===Qi.UPDATE).length,y=g.filter(e=>e.action===Qi.SKIP).length;i({title:"Files analyzed",description:`${m.length} file(s): ${f} new, ${b} to update, ${y} to skip`,status:"info",duration:4e3});for(const e of g.filter(e=>e.action===Qi.SKIP&&e.existingId))u.push({id:e.existingId,name:e.name,type:l,status:"skipped",location:e.location});const v=g.filter(e=>(e.action===Qi.CREATE||e.action===Qi.UPDATE)&&e.file);if(v.length>0){console.log(`Processing ${v.length} files (${v.filter(e=>e.action===Qi.CREATE).length} create, ${v.filter(e=>e.action===Qi.UPDATE).length} update)...`);const e=50,t=[];for(let n=0;n<v.length;n+=e)t.push(v.slice(n,n+e));for(let r=0;r<t.length;r++){const a=t[r],o=r*e;console.log(`Processing batch ${r+1}/${t.length} (${a.length} files)`),v.length>e&&i({title:"Processing files",description:`Processed ${o}/${v.length} files...`,status:"info",duration:2e3});const m=await Promise.all(a.map(async e=>{try{if(e.action===Qi.UPDATE&&e.existingId){const t=await n.store.objects.update(e.existingId,{type:l||void 0,content:e.file,location:e.location,name:e.name},{createRevision:!0,revisionLabel:"upload on "+(new Date).toISOString()});return p.push({id:e.existingId,name:e.name,type:l,status:"updated",location:e.location}),d.objectIds.push(e.existingId),{success:!0,id:t.id,name:e.name,action:"update"}}{const t=c?{collection_id:c}:void 0,n=await s.objects.create({type:l||void 0,content:e.file,location:e.location||e.file.webkitRelativePath||e.name},t);p.push({id:n.id,name:e.name,type:l,status:"created",location:e.location})}}catch(t){console.error(`Failed to process file ${e.name}:`,t),h.push({name:e.name,error:t.message||"Unknown error",status:"failed",location:e.location,type:l}),i({status:"error",title:`Processing failed for ${e.name}`,description:t.message,duration:4e3})}})),u=p.filter(e=>"created"===e.status),g=p.filter(e=>"updated"===e.status),f=p.filter(e=>"failed"===e.status);console.log(`Batch ${r+1} results:`,{creates:u,updates:g,failures:f,total:m.length})}}const x=p.filter(e=>"created"===e.status).length,w=p.filter(e=>"updated"===e.status).length,N=p.filter(e=>"failed"===e.status).length,k=p.filter(e=>"skipped"===e.status).length;t&&(console.log("Upload complete:",{totalObjectIds:d.objectIds.length,uploadedFiles:x,updatedFiles:w,skippedFiles:k,failedFiles:N}),await t(d.objectIds));let C="";return x>0&&(C+=`${x} file${1!==x?"s":""} uploaded`),w>0&&(C+=C?", ":"",C+=`${w} file${1!==w?"s":""} updated`),k>0&&(C+=C?", ":"",C+=`${k} file${1!==k?"s":""} skipped (already existed)`),N>0&&(C+=C?", ":"",C+=`${N} file${1!==N?"s":""} failed`),C&&i({status:N>0?"warning":"success",title:C,duration:4e3}),a.search(),d}}!function(e){e.CREATE="create",e.SKIP="skip",e.UPDATE="update"}(Qi||(Qi={}));const ro=[{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 so({isGridView:t=!1,onUpload:n,collectionId:r,...s}){return n?e(ao,{...s,onUpload:n,isGridView:t,collectionId:r}):e(io,{...s,isGridView:t})}function ao({isGridView:n,onUpload:s,collectionId:a,skipTypeModal:i=!1,...o}){const[l,d]=c(!1),[m,u]=c([]),[p,h]=c(!1),[g,f]=c(null),[b,y]=c(!1),v=Ji(),x=Ae(),{checkDocumentProcessing:w}=eo(),N=async(e,t)=>{console.log("Files dropped on ObjectTable:",e.length,t),d(!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:"Files ready to process",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:"Error processing files",description:"There was an error checking for duplicate files",status:"error",duration:4e3}),f(null)}finally{if(d(!1),u(e),h(!1),i){console.log("Skipping type modal and calling onUpload directly",{filesLength:e.length,processedFilesLength:g?.length});const t=s(e,null,a);t&&"object"==typeof t&&(t.processedFiles=g)}else console.log("Setting typeSelectionOpen to true",{filesLength:e.length}),y(!0)}},k=e=>{const t=[...m];u([]),f(null),y(!1),t.length>0&&void 0!==e&&(d(!0),console.log("Starting upload with",{typeId:e,filesCount:t.length,hasProcessingResults:!!g,collectionId:a}),s(t,e,a).finally(()=>{d(!1),v.search()}))},C=e=>{e.preventDefault(),e.stopPropagation(),h(!0)};return t("div",{className:"min-h-[400px] relative",onDragOver:C,onDragEnter:C,onDragLeave:e=>{e.preventDefault(),e.stopPropagation(),e.currentTarget.contains(e.relatedTarget)||h(!1)},onDrop:e=>{if(e.preventDefault(),e.stopPropagation(),h(!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:r("bg-white dark:bg-gray-800 opacity-40 absolute inset-0 z-50 flex justify-center items-center",l?"block":"hidden"),children:e(Ue,{size:"xl"})}),e(io,{...o,isGridView:n}),e("div",{className:r("absolute inset-0 pointer-events-none",p?"z-40":"-z-10"),children:e("div",{className:"w-full h-full relative",children:e(_n,{onDrop:N,message:"Drop files or folders here to upload",className:r("absolute inset-0 bg-white/90 dark:bg-gray-800/90 pointer-events-auto",p?"flex":"hidden"),buttonLabel:"Select Files or Folders",allowFolders:!0})})}),e(to,{isOpen:b&&m.length>0,onClose:()=>{u([]),f(null),y(!1),k(void 0)},files:m,collectionId:a,selectedFolder:null,title:"Upload Files",onUploadComplete:e=>{if(e){if(e.failedFiles&&e.failedFiles.length>0&&x({title:"Upload Issues",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:"Upload Complete",description:`${t>0?`${t} created`:""}${t>0&&n>0?", ":""}${n>0?`${n} updated`:""}${r>0?`, ${r} skipped`:""}`,status:"success",duration:5e3})}v.search()}u([]),f(null),y(!1),e&&e.success&&e.objectIds.length>0?k(null):k(void 0)}})]})}function io({objects:t,layout:n=ro,isLoading:r,onRowClick:s,onSelectionChange:a,previewObject:i,selectedObject:o,isGridView:c}){const d=Oi(),m=(e,n)=>{if(d){const r=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 s=r+1;s<n;s++)e.push(t[s]);d.addAll(e)}else{const e=function(e,t,n){const r=e.length;for(let s=t+1;s<r;s++)if(n.isSelected(e[s].id))return s;return-1}(t,n,d);if(e>-1&&e>n+1){const r=[];for(let s=n+1;s<e;s++)r.push(t[s]);d.addAll(r)}}}}else d.remove(e.id);a&&a(d)}},u=e=>{if(d){e.target.checked?d.addAll(t):d.removeAll()}},p=l(()=>(n.length>0?n:ro).map(e=>new Wi(e,i)),[n,i]);return e(c?Bi:qi,{objects:t,isLoading:r,columns:p,onRowClick:s,previewObject:i,selectedObject:o,selection:d,toggleAll:u,onSelectionChange:m})}function oo({children:t,limit:n,parent:r,typeId:s,facets:a,name:i,collectionId:o}){const{store:c}=Te(),d=l(()=>{let e;a?e=a:(e=[{name:"status",field:"status"},{name:"location",field:"location"}],s||e.unshift({name:"type",field:"type"}));const t=new Hi(c,n).withFacets(e);return t.collectionId=o,t.query.type=s,t.query.parent=r,t.query.name=i,t},[s,n,o]);return e(Gi.Provider,{value:d,children:t})}const lo=[{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 co({onChange:t}){return e(oo,{children:e(mo,{onRowClick:e=>{t(e||void 0)}})})}function mo({onRowClick:n}){const[r,a]=c(!1),[i,o]=c("grid"===localStorage.getItem("vertesia.content_store.lastDisplayedView")),{search:l,isLoading:d,error:m,objects:p,hasMore:h}=Yi(),f=u(null);bt(f,()=>{r&&h&&!d&&(a(!1),l.loadMore(!0).finally(()=>{a(!0)}))},{threshold:.1,deps:[r,h,d]}),g(()=>{l.search().finally(()=>{a(!0)})},[]);const b=Ki(),y=Ji();return m?e(Oe,{title:"Search failed",children:m.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(wi,{facets:b,search:y}),t("div",{className:"flex items-center gap-2",children:[e(De,{variant:"outline",onClick:()=>{a(!1),l.search().then(()=>a(!0))},alt:"Refresh",children:e(Y,{size:16})}),e(Yr,{onUpdate:o})]})]}),t("div",{className:"@container flex-1 overflow-y-auto",children:[e(so,{objects:p||[],isLoading:!1,layout:lo,onRowClick:n,isGridView:i}),e("div",{ref:f,className:"h-4 w-full"}),e("div",{className:s("bg-white dark:bg-gray-800 opacity-80 absolute inset-0 z-50 flex justify-center items-center rounded",d?"block":"hidden"),children:e(Ue,{size:"xl"})})]})]})}function uo({isOpen:n,onClose:r}){return t(Ve,{onClose:()=>r(),isOpen:!!n,className:"min-w-[60vw]",children:[e(We,{children:"Select Content"}),e(qe,{className:"pt-0 overflow-y-auto max-h-[80vh] min-h-[80vh]",children:n&&e(co,{onChange:r})})]})}const po=/store:([a-f0-9]+)/;function ho({object:n}){const{client:s}=Te(),{off:a,on:i,isOn:o}=yt(),[l,d]=c(null!=n.value?String(n.value):""),[m,u]=c(void 0),p=()=>{d(""),n.value="",u(void 0)};return g(()=>{if(!l||m)return;const e=l.match(po);e&&s.objects.get(e[1]).then(e=>{u(e)}).catch(()=>{p()})},[l]),t("div",{children:[t("div",{className:"relative",children:[e("input",{value:l,onChange:e=>{const t=e.target.value;d(t),n.value=t},className:r(vt.INPUT,"pr-10 w-full")}),m&&e("div",{className:"absolute inset-y-0 right-10 flex items-center justify-center ",children:e(De,{onClick:p,variant:"unstyled",className:"hover:text-red-500 hover:bg-gray-100 dark:hover:bg-gray-600",children:e(C,{className:"size-5"})})}),e("div",{className:"absolute inset-y-0 right-0 flex items-center justify-center",children:e(De,{onClick:i,variant:"unstyled",className:"hover:bg-gray-100 dark:hover:bg-gray-600",children:e(se,{className:"size-5"})})}),e(uo,{value:l,isOpen:o,onClose:e=>{if(e){const t="store:"+e.id;d(t),u(e||void 0),n.value=t}a()}})]}),m&&e("div",{className:"p-1 semibold text-sm text-gray-600 dark:text-slate-300",children:m.properties?.title||m.name})]})}function go({objectId:n,isOpen:r,onClose:s}){const a=bn(),{client:i,store:o}=Te(),[l,d]=c(null),[m,u]=c(!1),[p,h]=c(!1),[f,b]=c(),[y,v]=c(),[x,N]=c("preview"),S=Ae();g(()=>{n&&r?(u(!0),o.objects.retrieve(n,"+embeddings").then(e=>{d(e),e.text?b(e.text):_(e.id);const t=e.content;t&&t.source&&t.type&&t.type.startsWith("image/")&&I(e)}).catch(e=>{console.error("Error loading object:",e),S({title:"Error",description:"Failed to load document",status:"error",duration:3e3})}).finally(()=>{u(!1)})):(d(null),b(void 0),v(void 0))},[n,r,o.objects]);const _=async e=>{h(!0);try{const t=await o.objects.getObjectText(e);b(t.text)}catch(e){console.error("Error loading text:",e)}finally{h(!1)}},I=async e=>{try{"found"===(await i.objects.getRendition(e.id,{format:Yt.jpeg,generate_if_missing:!1})).status&&console.log("Found rendition");const t=await i.files.getDownloadUrl(e.content.source);v(t.url)}catch(e){console.error("Error loading image:",e)}},P=()=>{l&&(a(`/legal/objects/${l.id}`),s())},T=f&&(f.startsWith("#")||f.includes("\n#")||f.includes("\n*")),z=l?.content?.type&&l.content.type.startsWith("image/"),A="application/pdf"===l?.content?.type;return r?t("div",{className:"fixed inset-y-0 right-0 w-2/5 dark:bg-slate-900 shadow-xl z-50 flex flex-col transition-transform duration-300 transform "+(r?"translate-x-0":"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(ae,{className:"h-5 w-5 text-indigo-600 mr-2"}),e("h2",{className:"text-lg font-semibold text-gray-800 dark:text-gray-200 truncate",children:m?"Loading document...":l?.name||"Document Preview"})]}),t("div",{className:"flex items-center space-x-2",children:[t(De,{variant:"ghost",size:"sm",onClick:P,className:"flex items-center gap-1 text-indigo-600 hover:text-indigo-800",children:[e(k,{className:"h-4 w-4"}),e("span",{children:"Full View"})]}),e(De,{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(C,{className:"h-5 w-5"})})]})]}),m?e("div",{className:"flex-1 flex items-center justify-center",children:t("div",{className:"text-center",children:[e(Ue,{size:"lg",className:"text-indigo-600 dark:text-indigo-400 mb-2"}),e("p",{className:"text-gray-600 dark:text-gray-400",children:"Loading document..."})]})}):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("button",{className:"py-2 px-4 font-medium border-b-2 "+("preview"===x?"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:()=>N("preview"),children:t("div",{className:"flex items-center gap-1",children:[e(O,{className:"h-4 w-4"}),e("span",{children:"Preview"})]})}),e("button",{className:"py-2 px-4 font-medium border-b-2 "+("properties"===x?"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:()=>N("properties"),children:t("div",{className:"flex items-center gap-1",children:[e(re,{className:"h-4 w-4"}),e("span",{children:"Properties"})]})})]})}),t("div",{className:"flex-1 overflow-auto p-4",children:["preview"===x&&t("div",{className:"h-full",children:[p?e("div",{className:"flex items-center justify-center h-40",children:e(Ue,{size:"md",className:"text-indigo-600 dark:text-indigo-400"})}):f?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(vn,{children:f})}):e("pre",{className:"text-wrap whitespace-pre-wrap dark:text-gray-200",children:f})}):null,z&&e("div",{className:"mt-4",children:e("div",y?{className:"border border-gray-200 dark:border-gray-700 rounded-md p-2 bg-white dark:bg-gray-800",children:e("img",{src:y,alt:l?.name,className:"mx-auto max-h-[70vh] object-contain"})}:{className:"flex items-center justify-center h-40",children:e(Ue,{size:"md",className:"text-indigo-600 dark:text-indigo-400"})})}),A&&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(ae,{className:"h-16 w-16 text-indigo-300 dark:text-indigo-400 mb-4"}),t("p",{className:"text-gray-600 dark:text-gray-400 text-center mb-4",children:["PDF document preview is available in full view. TODO"," "]}),e(De,{onClick:P,className:"bg-indigo-600 hover:bg-indigo-700 text-white",children:"Open Full Document View"})]}),!z&&!f&&!A&&!p&&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(ae,{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:"No preview available for this document type."})]})]}),"properties"===x&&l&&t("div",{className:"h-full",children:[l.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(Cn,{value:l.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(re,{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:"No properties available for this document."})]}),t("div",{className:"mt-4",children:[e("h3",{className:"text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2",children:"Document Information"}),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:"ID"}),e("div",{className:"font-medium dark:text-gray-200",children:l.id}),e("div",{className:"text-gray-500 dark:text-gray-400",children:"Type"}),e("div",{className:"font-medium dark:text-gray-200",children:l.type?.name||"Unknown"}),e("div",{className:"text-gray-500 dark:text-gray-400",children:"Content Type"}),e("div",{className:"font-medium dark:text-gray-200",children:l.content?.type||"N/A"}),e("div",{className:"text-gray-500",children:"Size"}),e("div",{className:"font-medium",children:l.content&&"size"in l.content?fo(l.content.size):"Unknown"}),e("div",{className:"text-gray-500",children:"Created"}),e("div",{className:"font-medium",children:l.created_at?new Date(l.created_at).toLocaleString():"N/A"}),e("div",{className:"text-gray-500",children:"Updated"}),e("div",{className:"font-medium",children:l.updated_at?new Date(l.updated_at).toLocaleString():"N/A"})]})})]})]})]})]}),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:l?.content?.source&&t(De,{onClick:()=>{l?.content?.source&&i.files.getDownloadUrl(l.content.source).then(e=>{window.open(e.url,"_blank")}).catch(e=>{console.error("Error getting download URL:",e),S({title:"Error",description:"Failed to download file",status:"error",duration:3e3})})},variant:"outline",className:"text-indigo-600 border-indigo-300 hover:bg-indigo-50",children:[e(w,{className:"h-4 w-4 mr-2"}),"Download"]})}),t(De,{onClick:P,className:"bg-indigo-600 hover:bg-indigo-700 text-white",children:["Open Full Document",e(j,{className:"h-4 w-4 ml-2"})]})]})]}):null}function fo(e){if(0===e)return"0 Bytes";const t=Math.floor(Math.log(e)/Math.log(1024));return parseFloat((e/Math.pow(1024,t)).toFixed(2))+" "+["Bytes","KB","MB","GB","TB"][t]}const bo=Object.values(an),yo=Object.values(on);function vo({onChange:n,isLoading:r,refresh:s,searchTypes:a}){const{client:i,project:o}=Te(),l=Ae(),[d,m]=c(void 0),[u,p]=c(void 0),h=!(!o||!u?.embeddings.text&&!u?.embeddings.image),[f,b]=c(void 0),[y,v]=c(!1),[x,w]=c(a||bo),[N,k]=c(100);g(()=>{a&&w(a)},[a]);const C={};let S=!1,_=!1;x.forEach(e=>{e===an.full_text?S=!0:_=!0,yo.includes(e)&&(C[e]=!0)}),g(()=>{m(void 0),b(void 0)},[s]),g(()=>{o&&i.projects.retrieve(o.id).then(e=>{p(e.configuration)})},[o]),g(()=>{f&&l({title:f,status:"success",duration:2e3})},[f]),g(()=>{d&&0!==d.length||n(void 0)},[d]);const j=()=>{if(!h||!d)return;n({vector:_?{text:d,config:C}:void 0,full_text:S?d:void 0,limit:N}),b("Searching...")},I=e=>t=>{w(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(Ge,{placeholder:"Type what you are looking for, or select a filter",value:d,onChange:m,onKeyDown:e=>{"Enter"===e.key&&j()},className:"min-w-[200px]"}),e(De,{variant:"ghost",onClick:()=>v(!0),alt:"Semantic search settings",className:"ml-1",children:e(ie,{size:18})}),t(Ve,{isOpen:y,onClose:()=>v(!1),children:[e(We,{children:"Search Types"}),e(qe,{children:t("div",{className:"flex flex-col gap-2",children:[t("label",{className:"flex items-center gap-2",children:[e(xt,{checked:x.includes(an.full_text),onCheckedChange:I(an.full_text)}),e("span",{children:"Full Text"})]}),e("div",{className:"font-semibold mt-2 mb-1",children:"Embeddings"}),yo.map(n=>t("label",{className:"flex items-center gap-2",children:[e(xt,{checked:x.includes(n),onCheckedChange:I(n)}),e("span",{children:n.charAt(0).toUpperCase()+n.slice(1)})]},n)),t("div",{className:"mt-3",children:[e("span",{className:"mr-2",children:"Limit"}),e(wt,{type:"number",min:1,value:N,onChange:e=>k(Number(e??100)),style:{width:80}})]})]})}),e(Je,{children:e(De,{variant:"outline",onClick:()=>v(!1),children:"Close"})})]}),e(De,{variant:"secondary",isLoading:r,onClick:j,isDisabled:!h,alt:"Semantic search",children:"Search"})]})}const xo=[{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 wo({onUploadDone:t=async()=>{},layout:n}){const r=Ji(),s=Ae(),a=no(async e=>{await t(e),setTimeout(()=>{console.log("Delayed refresh after upload to ensure backend consistency"),r.search().then(()=>{s({title:"Document list refreshed",description:"The document list has been updated with your uploaded files.",status:"info",duration:3e3})}).catch(e=>{console.error("Failed to refresh search results:",e)})},1e3)});return e(No,{layout:n,onUpload:(e,t)=>{const n=r.collectionId;return a(e,t,n)}})}function No({layout:n,onUpload:r,allowFilter:s=!0,allowSearch:a=!0}){const i=Ji(),[o,l]=c(!1),[d,m]=c(null),{typeRegistry:p}=Te(),{search:h,isLoading:f,error:b,objects:y,hasMore:v}=Yi(),[x,w]=c(p?n||(N=p,((k=h.query.type)?N.getTypeLayout(k):xo)??xo):xo);var N,k;const[C,S]=c(0),[_,j]=c(0),[I,P]=c("grid"===localStorage.getItem(Yr.LAST_DISPLAYED_VIEW)),[T,z]=c([]),A=u(null);g(()=>{o||0!==y.length||(j(0),h._updateRunningState(!0),h.search().then(()=>{l(!0)}).catch(e=>{console.error("Initial search failed:",e),h._updateRunningState(!1)}))},[]),g(()=>{y.length<_&&j(y.length)},[y.length,_]),bt(A,()=>{o&&y.length>0&&y.length!=_&&(l(!1),h.loadMore().finally(()=>{j(y.length),l(!0)}))},{deps:[o,y.length]});const D=Ki(),F=Ji(),E=vi(D),$=xi(F),O=new URL(window.location.href),R=O.searchParams.get("filters");if(R)try{const e=R.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?O.searchParams.set("filters",e):O.searchParams.delete("filters"),window.history.replaceState(window.history.state||{},"",O.toString())}}catch(b){console.error("Failed to clean start/end filters from URL:",b)}const L=bn();return t("div",{className:"flex flex-col gap-y-2",children:[e(Co,{object:d,onClose:()=>m(null)}),b&&e(Oe,{title:"Error",children:b.message}),e(ko,{isLoading:f,refreshTrigger:C,allowFilter:s,allowSearch:a,filterGroups:E,filters:T,handleFilterChange:e=>{const t="function"==typeof e?e(T):e;z(t),$(t)},handleVectorSearch:e=>{if(e&&e.vector){if(h.query.vector=e.vector,h.query.full_text=e.full_text,h.query.weights=e.weights,h.query.score_aggregation=e.score_aggregation,h.query.dynamic_scaling=e.dynamic_scaling,void 0!==e.limit&&(h.limit=e.limit,h.query.limit=e.limit),!x.find(e=>"Search Score"===e.name)){const e=[...x,{name:"Search Score",field:"score",render:e=>e.score?.toFixed(4)||"0.0000"}];w(e)}h.search().then(()=>l(!0))}else e&&e.full_text?(h.query.full_text=e.full_text,void 0!==e.limit&&(h.limit=e.limit,h.query.limit=e.limit),h.search().then(()=>l(!0))):void 0===e&&o&&(delete h.query.vector,delete h.query.full_text,h.search().then(()=>l(!0)))},handleRefetch:()=>{h.search().then(()=>l(!0))},setIsGridView:P}),e(so,{objects:y,isLoading:!y.length&&f,layout:x,onRowClick:e=>{L(`/objects/${e.id}`)},previewObject:e=>{const t=y.find(t=>t.id===e)||null;m(t)},selectedObject:d,onUpload:r,isGridView:I,collectionId:i.collectionId}),e("div",v?{ref:A,className:"w-full flex justify-center",children:e(Ue,{size:"xl"})}:{className:"text-muted text-center text-sm py-1",children:`All ${y.length} objects loaded.`})]})}function ko(n){const{isLoading:r,refreshTrigger:s,allowFilter:a,allowSearch:i,filterGroups:o,filters:l,handleFilterChange:c,handleVectorSearch:d,handleRefetch:m,setIsGridView:u}=n;return t("div",{className:"sticky top-0 z-10 bg-background py-2 flex justify-between items-center",children:[a&&t(ct,{filterGroups:o,filters:l,setFilters:c,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:[i&&e(vo,{onChange:d,isLoading:r,refresh:s,className:"w-full"}),e(dt,{})]})}),t("div",{className:"flex gap-2 items-center pt-2",children:[e(mt,{}),e(ut,{})]})]}),!a&&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:i&&e(vo,{onChange:d,isLoading:r,refresh:s})})}),t("div",{className:"flex gap-1 items-center",children:[e(De,{variant:"outline",onClick:m,alt:"Refresh",children:e(Y,{size:16})}),e(Yr,{onUpdate:u})]})]})}function Co({object:n,onClose:r}){const{store:s}=Te(),a=Ae(),i=bn(),{downloadFromContentSource:o}=la({client:s,toast:a});return n?t(Nt,{title:n.properties?.title||n.name,isOpen:!0,onClose:r,children:[t("div",{className:"flex items-center gap-x-2",children:[e(De,{variant:"ghost",size:"sm",title:"Open Object",onClick:()=>i(`/objects/${n.id}`),children:e(S,{className:"size-4"})}),n.content?.source&&e(De,{variant:"ghost",size:"sm",title:"Download",onClick:()=>o(n.content.source,n.name||n.content?.name),children:e(w,{className:"size-4"})})]}),e(kt,{className:"my-2"}),e("div",{className:"pt-2",children:e(Na,{object:n,loadText:!0},n.id)})]}):null}var So;function _o({isExporting:n,isOpen:r,onClose:s}){return t(Ve,{onClose:()=>s(void 0),isOpen:r,children:[e(We,{children:"Export Object Properties"}),t(qe,{children:[!n&&e(jo,{onClose:s}),n&&e(Io,{})]})]})}function jo({onClose:n}){const[r,s]=c(void 0),[a,i]=c(void 0),o=["Export selected objects","Export all objects"];return t(qe,{className:"min-h-[104px] pt-0 flex flex-col gap-y-4",children:[e("div",{className:"h-1/3",children:e(tt,{options:o,value:a,onChange:i,placeholder:"Choose what to export",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(tt,{options:Object.values(So),value:r,onChange:s,placeholder:"Choose a format",className:"h-full w-full text-sm",filterBy:"name",isClearable:!0}),e(De,{className:"w-full",isDisabled:!r||!a,onClick:()=>{n(r,a==o[1])},children:"Export Properties"})]})]})}function Io({}){return e(qe,{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:"EXPORT IS IN PROGRESS"}),e("p",{className:"pt-2 grid justify-items-center",children:"PLEASE WAIT"})]}),e(Ue,{size:"lg"})]})})}function Po({collection:t}){const n=Ae(),{client:r,typeRegistry:s}=Te(),a=function(e,t){let n=e.table_layout;if(n&&n.length>0)return n;e.type&&t&&(n=t?.getTypeLayout(ln(e.type)));return n&&n.length>0?n:void 0}(t,s);return t.dynamic?e(No,{layout:a}):e(wo,{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:a})}!function(e){e.CSV="CSV",e.JSON="JSON"}(So||(So={}));const To=n=>null===n?"None":t("div",{children:[e("div",{className:"text-sm",children:n.name}),e("div",{className:"text-xs text-gray-500",children:n.description})]});function zo({className:t,defaultValue:n,onChange:r,isClearable:s,multiple:a}){const i=Te(),[o,l]=c(!1),[d,m]=c(),[u,p]=c([]);g(()=>{if(!o&&(l(!0),i.typeRegistry&&n)){if(a&&Array.isArray(n)){const e=i.typeRegistry.types.filter(e=>n.includes(e.id));p(e)}const e=i.typeRegistry.types.find(e=>e.id===n);e&&m(e)}},[i.typeRegistry,n,a]);const h=e=>{p(e),r(e)};return e("div",a?{className:"flex flex-col gap-4 content-between",children:e(tt,{options:i.typeRegistry?.types||[],value:u,onChange:h,placeholder:"Choose Content Types...",optionLabel:To,className:t||"text-sm bg-background",filterBy:"name",isClearable:s||!1,multiple:!0})}:{className:"flex flex-col gap-4 content-between",children:e(tt,{options:i.typeRegistry?.types||[],value:d,onChange:e=>{m(e||void 0),r(e)},placeholder:"Choose a Content Type...",optionLabel:To,className:t||"text-sm bg-background",filterBy:"name",isClearable:s||!1})})}function Ao({onClose:n,redirect:r=!0,onAddToCollection:s}){const a=bn(),i=Ae(),[o,l]=c(!1),{client:d}=Te(),[m,u]=c({dynamic:!1,name:"",description:""});function p(e,t){u({...m,[e]:t})}return t("form",{onSubmit:e=>e.preventDefault(),children:[t(qe,{children:[e(He,{label:"Name",required:!0,children:e(Ge,{type:"text",value:m.name||"",onChange:e=>p("name",e)})}),e(He,{label:"Description",className:"mt-2",children:e(Ct,{value:m.description||"",onChange:e=>p("description",e.target.value)})}),e(He,{label:"Dynamic Collection",className:"mt-2",direction:"row",description:"Dynamically fetch content for the collection based on a query. If not enabled, then content must be added by users or agents.",children:e(St,{value:m.dynamic||!1,onChange:e=>p("dynamic",e)})}),!m.dynamic&&e(He,{label:"Allowed Content Types",className:"mt-4",description:"Optionally select which content types can be added to the collection. If not set, then all content types are allowed.",children:e(zo,{defaultValue:m.allowed_types||null,onChange:e=>{Array.isArray(e)?p("allowed_types",e.map(e=>e.id)):p("allowed_types",e?[e.id]:[])},isClearable:!0,multiple:!0})}),e(He,{label:"Type",className:"mt-2",description:"Optionally select a content type to assign custom properties and data to the collection.",children:e(zo,{defaultValue:m.type||null,onChange:e=>{Array.isArray(e)?p("type",e.length>0?e[0].id:null):p("type",e?.id||null)},isClearable:!0})})]}),e(Je,{children:e(De,{isDisabled:o,onClick:()=>{m?.name&&m.name.trim()?(m.name=m.name.trim(),m.description&&(m.description=m.description.trim()),null==m.dynamic&&(m.dynamic=!1),l(!0),d.store.collections.create(m).then(e=>{n(),i({title:"Collection created",description:`Collection "${e.name}" created successfully`,status:"success",duration:3e3}),r&&a(`/collections/${e.id}`),s&&s(e.id)}).catch(e=>{i({title:"Failed to create collection",description:e.message,status:"error",duration:5e3})}).finally(()=>l(!1))):i({title:"Name is required",description:"Please provide a name for the collection",status:"error",duration:5e3})},children:"Create Collection"})})]})}function Do({isOpen:n,onClose:r}){return t(Ve,{onClose:r,isOpen:n,children:[e(We,{children:"Create a Collection"}),e(Ao,{onClose:r})]})}function Fo({}){const{client:r}=Te(),s=Ae(),[a,i]=c(),[o,l]=c(!0),[d,m]=c(!1),{data:u,error:p,refetch:h}=$e(()=>r.store.collections.search({}),[]);if(g(()=>{(u||p)&&l(!1)},[u,p]),p)return e(Oe,{title:"Collections fetch failed",children:p.message});return t(n,{children:[u&&(u.length>0?t(st,{className:"w-full",children:[e("thead",{children:t("tr",{children:[e("th",{children:"Name"}),e("th",{children:"Type"}),e("th",{children:"Created"}),e("th",{})]})}),e(pt,{columns:4,isLoading:o,children:u.map(n=>t(_t,{children:[e("td",{children:t("div",{className:"flex items-center gap-2",children:[Eo(n.dynamic),e(yn,{href:`/collections/${n.id}`,children:n.name})]})}),e("td",{children:n.type?.name||"-"}),e("td",{children:fn(n.created_at).fromNow()}),e("td",{className:"text-right",children:e(De,{variant:"destructive",size:"sm",onClick:()=>i(n.id),children:e(oe,{className:"size-4"})})})]},n.id))})]}):e(jt,{title:"No Collections",buttonLabel:"New Collections",onClick:()=>m(!0),children:"Get started by creating a new Collections."})),e(Do,{isOpen:d,onClose:()=>m(!1)}),e(It,{isOpen:!!a,title:"Delete Collection",content:"Are you sure you want to delete this collection? This action cannot be undone.",onConfirm:async()=>{if(a)try{await r.store.collections.delete(a),s({title:"Collection deleted",status:"success",duration:3e3}),h()}catch(e){console.error("Failed to delete collection:",e),s({title:"Failed to delete collection",description:e.message||"An error occurred",status:"error",duration:5e3})}finally{i(void 0)}},onCancel:()=>i(void 0)})]})}function Eo(t){const n=t?"Dynamic Collection":"Static Collection",r=e(t?le:ce,{className:"size-5"});return e(Ee,{description:n,className:"mr-2",children:r})}function $o({objects:n,isLoading:r}){const s=bn();return t(st,{className:"w-full",children:[e(Pt,{children:t("tr",{children:[e("th",{children:"Name"}),e("th",{children:"Strict Mode"}),e("th",{children:"Semantic Chunking"}),e("th",{children:"Updated At"})]})}),e(pt,{isLoading:r&&(!n||0===n.length),columns:4,children:n?.map(n=>t("tr",{onClick:()=>s(`/types/${n.id}`),className:"cursor-pointer hover:bg-muted",children:[e("td",{children:n.name}),e("td",{children:n.strict_mode?"Yes":"No"}),e("td",{children:n.is_chunkable?"Yes":"No"}),e("td",{children:fn(n.updated_at).fromNow()})]},n.id))})]})}fn.extend(On),fn.extend(On);class Oo{client;limit;result=new ht({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 Ro=d(void 0);function Lo(){return m(Ro)}function Mo(){const e=Lo();return{...gt(e.result),search:e}}function Uo(){return Lo().objects.length}function Vo({title:n,isOpen:r,onClose:s,okLabel:a,initialPayload:i}){const o=Ae(),[l,d]=c(i?.name),[m,u]=c(i?.description),[p,h]=c(i?.strict_mode??!1);return t(Ve,{isOpen:r,onClose:()=>s(),children:[e(We,{children:n}),e(qe,{className:"pt-0",children:t("div",{className:"h-full flex flex-col gap-4 content-between",children:[t("div",{children:[e("label",{className:"block text-sm font-medium text-muted",children:"Name"}),e(Ge,{value:l,onChange:d})]}),t("div",{children:[e("label",{className:"block text-sm font-medium text-muted",children:"Description"}),e(Ct,{value:m,onChange:e=>u(e.target.value)})]})]})}),e(Je,{children:t("div",{className:"flex justify-end gap-4",children:[e(De,{variant:"secondary",onClick:()=>s(),children:"Cancel"}),e(De,{variant:"primary",onClick:()=>(()=>{if(!l)return void o({status:"error",title:"Name is required",duration:5e3});s({name:l,description:m,strict_mode:p}).then(()=>s()),d(void 0),u(void 0),h(!1)})(),children:a})]})})]})}var Wo;function qo({isDirty:n=!1}){const r=Te(),{store:s}=r,a=Ae(),[i,o]=c(!1),{search:l,isLoading:d,error:m,objects:p}=Mo(),[h,f]=c(""),b=Tt(h,500),y=u(null);bt(y,()=>{i&&l.loadMore()},{deps:[i]}),g(()=>{l.search().then(()=>o(!0))},[]),g(()=>{l.query.name=h,l.search().then(()=>o(!0))},[b]);const[v,x]=c(void 0);g(()=>{l.query.chunkable=v?"Yes"==v:void 0,l.search().then(()=>o(!0))},[v]),g(()=>{n&&i&&l.search().then(()=>o(!0))},[n]);const[w,N]=c(!1);if(m)return e(Oe,{title:"Failed to fetch ObjectTypes",children:m.message});return t("div",{className:"flex flex-col gap-4 h-full",children:[t("div",{className:"flex flex-shrink-0 gap-4",children:[e(Ge,{placeholder:"Filter by Name",value:h,onChange:f}),e(tt,{className:"w-60",isClearable:!0,options:Object.values(Wo),value:v,onChange:e=>{x(e)},placeholder:"Is Chunkable"})]}),t("div",{className:"flex-1 overflow-y-auto",children:[d||0!==p?.length?e($o,{objects:p,isLoading:d}):e(jt,{title:"No Type",buttonLabel:"Create Type",onClick:()=>{N(!0)},children:"Get started by creating a new Type."}),e(Vo,{okLabel:"Create",title:"Create Type",isOpen:w,onClose:async e=>e?s.types.create(e).then(async()=>{a({status:"success",title:"Type created",duration:2e3}),r.reloadTypes(),l.search().then(()=>o(!0))}).catch(e=>{a({status:"error",title:"Error creating type",description:e.message,duration:5e3})}):(N(!1),Promise.resolve())})]})]})}function Bo({objectType:n,onSchemaUpdate:r,readonly:s=!1}){const{store:a}=Te(),i=Ae(),{theme:o}=Ye(),[d,m]=c(!1),p=In(n.object_schema),h=u(void 0),[g,f]=c(!1),b=l(()=>function(e){if(!e)return"";return JSON.stringify(e,null,2)}(p.schema),[p]),y=()=>{if(h.current){const e=h.current.getValue();try{const t=function(e){if(!e?.trim())return;return JSON.parse(e.trim())}(e);Ho(t),p.replaceSchema(t)}catch(e){return i({status:"error",title:"Invalid JSON Schema",description:e.message,duration:5e3}),!1}}return!0},v=t("div",{className:"flex gap-2 items-center",children:[e("div",{className:"text-base font-semibold",children:"Schema Editor"}),!s&&e("div",{children:e(De,{variant:"outline",size:"sm",onClick:()=>{g&&!y()||f(e=>!e)},children:g?"Edit Schema":"Edit Json"})})]});return e(zt,{title:v,className:"bg-background! h-[calc(100vh-197px)]",action:s?void 0:e(De,{isLoading:d,variant:"outline",size:"sm",onClick:()=>{g&&!y()||(m(!0),a.types.update(n.id,{object_schema:p.schema}).then(()=>{r(p),i({status:"success",title:"Schema updated",description:"The schema has been updated successfully",duration:2e3})}).catch(e=>{i({status:"error",title:"Failed to update schema",description:e.message,duration:5e3})}).finally(()=>{m(!1)}))},children:"Save Changes"}),children:g?e(kn,{value:b,language:"json",editorRef:h,theme:"dark"===o?"vs-dark":"vs",options:{readOnly:s}}):e(Pn,{schema:p,readonly:s})})}!function(e){e.true="Yes",e.false="No"}(Wo||(Wo={}));const Ho=e=>{try{new Wn({strict:!1}).compile(e)}catch(e){throw new Error(`Invalid JSON Schema definition: ${e.message}`)}};function Go({children:t,limit:n,name:r,chunkable:s}){const{store:a}=Te(),i=l(()=>{const e=new Oo(a,n);return e.query.name=r,e.query.chunkable=s,e},[n]);return e(Ro.Provider,{value:i,children:t})}function Jo({isOpen:n,onClose:r,title:s="Select Content Type",children:a,initialSelectedType:i=null,allowNone:o=!0}){const{typeRegistry:l}=Te(),[d,m]=c(i),u=l?.types||[],p=()=>{r(void 0)};return t(Ve,{isOpen:n,onClose:p,className:"w-full max-w-xl mx-auto",children:[e(We,{children:s}),t(qe,{children:[a,t("div",{className:"mb-4 mt-4",children:[t("label",{className:"block text-sm font-medium mb-2",children:["Content Type ",o&&e("span",{className:"text-gray-500 font-normal",children:"(Optional)"})]}),e(tt,o?{options:u,value:d,optionLabel:e=>e?e.name:"Select a content type",placeholder:"Select a content type or leave empty for automatic detection",onChange:e=>m(e||null),filterBy:"name",isClearable:!0}:{options:u,value:d,optionLabel:e=>e?e.name:"Select a content type",placeholder:"Select a content type",onChange:e=>m(e||null),filterBy:"name"})]}),!d&&t("div",{className:"flex items-center text-attention",children:[e(Q,{className:"size-4 mr-1"}),"Automatic Type Detection",e(Ee,{description:"Vertesia will analyze the content and select the most appropriate type. This is recommended for most uploads and ensures optimal processing.",placement:"top",size:"xs",children:e(re,{className:"size-3 ml-2"})})]})]}),t(Je,{children:[e(De,{variant:"ghost",onClick:p,alt:"Cancel",children:"Cancel"}),e(De,{onClick:()=>{r(d?.id??null),m(null)},alt:"Confirm selection",children:"Confirm"})]})]})}function Ko({objectType:t,onLayoutUpdate:n,readonly:r=!1}){const s=Ae(),{theme:a}=Ye(),[i,o]=c(!1),{store:d}=Te(),m=u(void 0),p=l(()=>Yo(t.table_layout),[t.table_layout]),h=(e,t)=>{s({status:"error",title:e,description:t,duration:5e3})};return e(zt,{title:"Table Layout Editor",className:"bg-background! h-[calc(100vh-197px)]",action:r?void 0:e(De,{isLoading:i,variant:"outline",size:"sm",onClick:()=>{if(!m.current)return;const e=m.current.getValue();let r;if(e)try{r=JSON.parse(e)}catch(e){return h("Invalid JSON",e.message)}else r=null;return Array.isArray(r)?r.some(e=>!e||!e.name||!e.field)?h("Invalid JSON","A table layout entry must contain the following properties:] {field, name, converter?}"):(o(!0),void d.types.update(t.id,{table_layout:r}).then(e=>{s({status:"success",title:"Table Layout updated",description:"The table layout has been updated successfully",duration:2e3}),n(e.table_layout)}).catch(e=>{s({status:"error",title:"Failed to update table layout",description:e.message,duration:5e3})}).finally(()=>{o(!1)})):h("Invalid JSON","The table layout must be an array")},children:"Save Changes"}),children:e(kn,{value:p,language:"json",editorRef:m,theme:"dark"===a?"vs-dark":"vs",options:{readOnly:r}})})}function Yo(e){return e?JSON.stringify(e,null,2):"[\n\n]"}function Zo({refetch:r,collection:s}){const a=s.type?.id,i=u(void 0),o=Ae(),{theme:d}=Ye(),{client:m}=Te(),[p,h]=c(!1),[g,f]=c({name:s.name,description:s.description||"",query:s.query?JSON.stringify(s.query,null,2):"",tags:s.tags||[],type:s.type?.id||"",allowed_types:s.allowed_types||[]}),b=l(()=>Yo(s.table_layout),[s.table_layout]),y=(e,t)=>{f({...g,[e]:t})};return t("div",{className:"flex flex-col gap-4 py-2",children:[t(zt,{title:"Configuration",action:e(De,{size:"lg",isDisabled:p,onClick:()=>{let e;try{e=g.query?JSON.parse(g.query):void 0}catch(e){return void o({title:"Invalid Query JSON",description:e.message,status:"error",duration:5e3})}const t={name:g.name,description:g.description,query:e,tags:g.tags,type:g.type,allowed_types:g.allowed_types};let n;if(t.name||(n="Name is required"),t.type||(t.type=null),n)o({title:"Validation failed",description:n,status:"error",duration:5e3});else{if(i.current){const e=i.current.getValue();if(e)try{t.table_layout=JSON.parse(e)}catch(e){return void o({title:"Invalid Table Layout",description:e.message,status:"error",duration:5e3})}else t.table_layout=null}h(!0),m.store.collections.update(s.id,t).then(()=>{r(),o({title:"Collection updated",description:"Collection has been updated successfully",status:"success",duration:3e3})}).catch(e=>{o({title:"Failed to update collection",description:e.message,status:"error",duration:5e3})}).finally(()=>{h(!1)})}},children:"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:"Created By"}),t("div",{className:"gap-2 flex items-center",children:[e(Ln,{userRef:s.created_by,showTitle:!0}),t("span",{children:["at ",fn(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:"Updated By"}),t("div",{className:"gap-2 flex items-center",children:[e(Ln,{userRef:s.updated_by,showTitle:!0}),t("span",{children:["at ",fn(s.updated_at).format("YYYY-MM-DD HH:mm:ss")]})]})]})]}),e(He,{label:"Name",required:!0,children:e(Ge,{value:g.name,onChange:e=>y("name",e)})}),e(He,{label:"Description",children:e(Ct,{value:g.description,onChange:e=>y("description",e.target.value)})}),!s.dynamic&&e(He,{label:"Allowed Content Types",description:"Select which content types can be added to the collection. If not set, then all content types are allowed.",children:e(zo,{defaultValue:g.allowed_types||null,onChange:e=>{Array.isArray(e)?y("allowed_types",e.map(e=>e.id)):y("allowed_types",e?[e.id]:[])},isClearable:!0,multiple:!0})}),s.dynamic&&e(He,{label:"Query",description:"Define the query to dynamically fetch content for the collection.",children:e(Ct,{className:vt.INPUT,value:g.query,onChange:e=>y("query",e.target.value)})}),e(He,{label:"Table Layout",description:"Define a custom layout for displaying the collection in tables.",className:"h-[200px]",children:e(kn,{className:"border-1 rounded-md border-border",value:b,language:"json",editorRef:i,theme:"dark"===d?"vs-dark":"vs"})}),e(He,{label:"Type",description:"Select a content type to assign custom properties and data to the collection.",children:e(zo,{defaultValue:g.type||null,onChange:e=>{Array.isArray(e)?y("type",e.length>0?e[0].id:null):y("type",e?.id||null)},isClearable:!0})})]}),a&&e(Qo,{typeId:a,collection:s}),!s.dynamic&&t(n,{children:[e(Mn,{collection:s}),e(Un,{collection:s})]})]})}function Qo({typeId:t,collection:n}){const[r,s]=c({}),a=Ae(),{client:i}=Te(),[o,d]=c(!1),{data:m,error:u}=$e(()=>i.store.types.retrieve(t),[t]),p=m?.object_schema||{},h=l(()=>new Tn(p,n.properties||{}),[p,n.properties]);if(u)return e(Oe,{title:"Failed to load type",children:u.message});if(!m)return null;return e(zt,{title:"Properties",action:e(De,{size:"lg",isLoading:o,type:"submit",onClick:()=>(e=>{if(!e||!Object.keys(e).length)return;const t={properties:e||{}};d(!0),i.store.collections.update(n.id,t).then(()=>{a({title:"Collection properties updated",description:"Collection has been updated successfully",status:"success",duration:3e3})}).catch(e=>{a({title:"Failed to update collection properties",description:e.message,status:"error",duration:5e3})}).finally(()=>{d(!1)})})(r),children:"Save"}),children:e(zn,{object:h,onChange:e=>{e instanceof Tn&&s(e.value)}})})}function Xo({onChange:n,value:r,disabled:s=!1,placeholder:a="Select a collection",searchPlaceholder:i="Search collections",filterOut:o,allowDynamic:d=!0,multiple:m=!1}){const{client:u}=Te(),[h,g]=c(""),[f,b]=c(!1),[y,x]=c(!1),w=Tt(h,300),N=p(async e=>{b(!0);const t=e.trim(),n=await u.store.collections.search({dynamic:!!d&&void 0,name:y&&t||void 0});return b(!1),!y&&n.length>=1e3&&x(!0),o&&o.length>0?n.filter(e=>!o.includes(e.id)):n},[u,d,o,y]),{data:k,error:C}=$e(()=>N(y?w:""),[y?w:"",N]),S=l(()=>k?m&&Array.isArray(r)?k.filter(e=>r.includes(e.id)):m||"string"!=typeof r?m?[]:void 0:k.find(e=>e.id===r):m?[]:void 0,[k,r,m]),_=p(e=>{if(m){const t=Array.isArray(r)?r:[];if(t.includes(e.id)){const r=t.filter(t=>t!==e.id),s=k?.filter(e=>r.includes(e.id))||[];n(r,s)}else{const r=[...t,e.id],s=k?.filter(e=>r.includes(e.id))||[];n(r,s)}}else n(e.id,e)},[n,r,k,m]),j=p(()=>{n(void 0,void 0)},[n]),I=p(e=>{g(e)},[]),P=h.trim().length>0,T=l(()=>{if(!k)return[];if(y)return k;if(!P)return k;const e=h.toLowerCase();return k.filter(t=>t.name.toLowerCase().includes(e))},[k,y,P,h]),z=S&&P;if(C)return e(Oe,{title:"Collection fetch failed",children:C.message});return t(at,{children:[e(it,{asChild:!0,children:t(De,{variant:"outline",role:"combobox","aria-haspopup":"listbox",className:ze("w-full justify-between min-w-0"),disabled:s,children:[e("span",{className:"truncate flex-1 text-left min-w-0",children:m&&Array.isArray(S)&&S.length>0?1===S.length?S[0].name:`${S.length} collections selected`:m||!S||Array.isArray(S)?a:S.name}),e(se,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e(ot,{className:"mt-2 mb-2 w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:t(At,{shouldFilter:!1,children:[t("div",{className:"flex justify-between items-center border-b px-3","cmdk-input-wrapper":"",children:[e(Dt,{placeholder:i,value:h,onValueChange:I,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"}),f&&e("div",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"})]}),e(Ft,{children:f?"Searching...":P?"No collections found.":"No collections available."}),t(Et,{className:"max-h-[300px] overflow-auto",children:[z&&!m&&e($t,{value:"__clear__",onSelect:j,className:"text-muted-foreground",children:"Clear selection"}),T.map(n=>{const s=m&&Array.isArray(r)?r.includes(n.id):r===n.id;return t($t,{value:n.id,onSelect:()=>_(n),className:"flex items-center justify-between",children:[e("span",{className:"truncate",children:n.name}),s&&e(v,{className:"ml-2 h-4 w-4 shrink-0"})]},n.id)})]})]})})]})}function el({collection:t}){const{client:n}=Te(),[r,s]=c(void 0),[a,i]=c(t.shared_properties||[]),o=Ae();g(()=>{t.type?.id&&n.store.types.retrieve(t.type.id).then(s)},[t.type?.id]);const l=r?Object.keys(r.object_schema?.properties||{}):[];return e(zt,{title:"Shared Properties",description:"Add properties to share across all members in the collection. This feature requires to enable shared property synchronization on the project.",action:e(De,{size:"lg",isLoading:!1,onClick:()=>{n.store.collections.update(t.id,{shared_properties:a}).then(()=>{o({title:"Updated shared properties",status:"success"})}).catch(e=>{o({title:"Failed to update shared properties",description:e.message,status:"error"})})},children:"Save"}),children:e("div",{className:"",children:e(Ot,{value:a,onChange:e=>{i(e)},options:l,placeholder:"Select properties to share"})})})}function tl({collection:t}){const{client:n}=Te(),[r,s]=c(t.skip_head_sync??!1),[a,i]=c(!1),o=Ae();return e(zt,{title:"Synchronize Member Heads",description:"When a new HEAD version of a member is created the colleciton will be updated to point to the new HEAD.",children:e(St,{disabled:a,value:!r,onChange:e=>{const r=!e;i(!0),n.store.collections.update(t.id,{skip_head_sync:r}).then(()=>{o({title:"Updated skip head sync setting",status:"success"}),s(r)}).catch(e=>{o({title:"Failed to update skip head sync",description:e.message,status:"error"})}).finally(()=>{i(!1)})},children:"Enable synchronizing member heads"})})}function nl({action:n,objectIds:r,children:s}){const{store:a}=Te(),i=Ae(),[o,l]=c(!1),d=p(()=>(l(!0),Promise.resolve(!0)),[]);Nl(n.id,d);return t("div",{children:[s,e(Jo,{isOpen:o,onClose:e=>{l(!1),void 0!==e&&a.runOperation({name:"change_type",ids:r,params:{typeId:e}}).then(e=>{i({status:"success",title:"Change Type",description:`Change the type of ${r.length} objects is ${"in_progress"===e.status?"in progress":"completed"}`,duration:2e3})}).catch(e=>{i({status:"error",title:"Error changing type",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 rl={id:"changeType",name:"Change Content Type",description:"Change the Content Type of the selected documents",confirm:!1,component:nl};function sl({action:r,callback:s,children:a}){const[i,o]=c(!1),l=r.confirmationText||`Are you sure you want to ${r.name}?`,d=p(e=>r.confirm?(o(!0),Promise.resolve(!0)):s(e),[r.confirm,s]),m=Nl(r.id,d);return t(n,{children:[a,e(It,{onConfirm:()=>{o(!1),s({...m.params,action:r})},onCancel:()=>o(!1),title:"Are you sure?",content:l,isOpen:i})]})}function al({action:t,objectIds:n,children:r}){const s=wl(),a=Ae(),{client:i}=Te(),o=Ji(),l=bn(),c=p(()=>{if(!n||!n.length)return a({status:"error",title:"No objects selected",description:"Please select objects to delete",duration:3e3}),Promise.resolve(!1);function e(e,t){if(e.length<=t)return e;const n=e.lastIndexOf("."),r=-1!==n?e.substring(n):"";return`${(-1!==n?e.substring(0,n):e).substring(0,t-r.length-3)}...${r}`}return Promise.all(n.map(e=>i.store.objects.delete(e))).then(t=>{const r=t.length>1?"s":"";if(a({status:"success",title:`${t.length} object${r} deleted`,description:`Objects ${e(t.map(e=>e.id).join(", "),100)} have been deleted`,duration:2e3}),o){s.params?.selection?.removeAll();const e=JSON.parse(JSON.stringify(o.facets));n.length===e._value.total&&o.resetFacets(),o.search()}else l("/objects")}).catch(e=>{a({status:"error",title:"Error deleting objects",description:e.message,duration:5e3})})},[n]);return e(sl,{action:t,callback:c,children:r})}const il={id:"delete",name:"Delete",description:"Delete the selected objects",confirm:!0,confirmationText:"Are you sure you want to delete all the selected objects? This action cannot be undone.",component:al,destructive:!0},ol={id:"deleteFromCollections",name:"Delete Objects",description:"Delete the selected objects",confirm:!0,confirmationText:"Are you sure you want to delete the selected objects?\nThis is not removable from collections.",component:al,destructive:!0};function ll({action:t,objectIds:n}){const{store:r}=Te(),s=Ae(),[a,i]=c(!1),[o,l]=c(!1),d=p(()=>(i(!0),Promise.resolve(!0)),[]),m=Nl(t.id,d);return e(_o,{isExporting:o,isOpen:a,onClose:(e,t)=>{if(e&&(t||n.length>0)){l(!0);const a=m.params?.search?.query||{},o=m.params?.search?.result?.value?.objects?.map(e=>e.id)||void 0,c=async e=>r.objects.list({query:{parent:e}}).then(e=>e.map(e=>e.id));(async()=>t?o?a.vector?o:[]:0===n.length?[]:(await c(n[0])).concat(n):n)().then(o=>{r.objects.exportProperties({objectIds:o,type:e,query:t&&!a.vector?a:{type:a.type}}).then(r=>{let a;if(e===So.CSV)a=new Blob([r.data],{type:r.type});else if(e===So.JSON)a=new Blob([JSON.stringify(r.data)],{type:r.type});else{const e=r.data;a=new Blob([new Uint8Array(e.data)],{type:r.type})}const i=window.URL.createObjectURL(a),o=document.createElement("a");o.download=r.name,o.href=i,o.click(),s({status:"success",title:"Export Properties",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:"Error Export Properties",description:e.message,duration:5e3})}).finally(()=>{l(!1),i(!1)})})}else i(!1)}})}const cl={id:"exportProperties",name:"Export Properties",description:"Export all Object Properties",confirm:!1,component:ll};function dl({action:t,objectIds:n,collectionId:r}){const s=wl(),a=Ae(),{client:i}=Te(),o=Ji(),l=p(()=>n&&n.length?r?i.store.collections.deleteMembers(r,n).then(()=>{const e=n.length>1?"s":"";a({status:"success",title:`${n.length} object${e} removed from collection`,description:"Objects have been removed from the collection",duration:2e3}),o&&(s.params?.selection?.removeAll(),o.search())}).catch(e=>{a({status:"error",title:"Error removing objects from collection",description:e.message,duration:5e3})}):(a({status:"error",title:"No collection context",description:"Cannot remove objects: no collection specified",duration:3e3}),Promise.resolve(!1)):(a({status:"error",title:"No objects selected",description:"Please select objects to remove from collection",duration:3e3}),Promise.resolve(!1)),[n,r]);return e(sl,{action:t,callback:l})}const ml={id:"removeFromCollection",name:"Remove from Collection",description:"Remove the selected objects from this collection",confirm:!0,confirmationText:"Are you sure you want to remove the selected objects from this collection?",component:dl,destructive:!0};function ul({action:t,objectIds:n,collectionId:r}){const s=Ae(),{client:a}=Te(),[i,o]=c(!1),l=p(()=>(o(!0),Promise.resolve(!0)),[]);return Nl(t.id,l),e(hl,{isOpen:i,onClose:e=>{if(o(!1),e)return a.store.workflows.rules.execute(e,n,{collection_id:r}).then(()=>{s({title:"Workflow started",status:"success",duration:3e3})}).catch(e=>{s({title:"Error starting workflow",status:"error",description:e.message,duration:9e3})})}})}const pl={id:"startWorkflow",name:"Start Workflow",description:"Start an workflow on the selected objects",confirm:!1,hideInList:!0,component:ul};function hl({isOpen:n,onClose:r}){return t(Ve,{onClose:()=>r(void 0),isOpen:n,className:"",children:[e(We,{children:"Start a Workflow by Rule"}),e(fl,{onClose:r})]})}function gl(n){return{label:t("div",{children:[e("div",{children:n.name}),e("div",{className:"text-sm text-muted",children:n.description})]}),reverse:!0}}function fl({onClose:n}){const[r,s]=c(void 0),a=wl();return t("div",{children:[t(qe,{children:[e("div",{className:"pb-2",children:"Choose a workflow rule to start:"}),e("div",{className:"max-h-[420px] overflow-y-scroll border-border border rounded-md",children:e(Rt,{options:a.wfRules,optionLayout:gl,onChange:e=>{s(e)},value:r})})]}),t(Je,{children:[e(De,{variant:"secondary",onClick:()=>n(),children:"Cancel"}),e(De,{onClick:()=>{r&&n(r.id)},isDisabled:!r,children:"Start"})]})]})}class bl{params;allActions=[cl,rl,pl,Sl,il,ml,ol];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)}async loadWorkflows(){return this.params.client.workflows.rules.list().then(e=>{this.wfRules=e.map(e=>({id:e.id,name:e.name,description:e.description,confirm:!1,isWorkflow:!0,component:ul})).sort((e,t)=>e.name.localeCompare(t.name))}),this.wfRules}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 yl=d(void 0);function vl({children:n}){const r=$i(),s=Ae(),{client:a}=Te(),i=Ji(),{data:o,error:c}=$e(()=>a.workflows.rules.list().then(e=>e.map(e=>({id:e.id,name:e.name,description:e.description,confirm:!1,isWorkflow:!0,component:ul})).sort((e,t)=>e.name.localeCompare(t.name))),[]),d=l(()=>{const e=new bl({selection:r,toast:s,client:a,search:i});return e.wfRules=o,e},[r,o]);return c?e(Oe,{title:"Failed to fetch workflows",children:c.message}):d&&t(yl.Provider,{value:d,children:[e(xl,{}),n]})}function xl({}){const t=wl(),n=t.params.selection,r=n.getObjectId(),s=n.isSingleSelection()&&r?[r]:n.getObjectIds();return e("div",{style:{display:"none"},children:t.allActions.map(t=>e(t.component,{action:t,objectIds:s,collectionId:n.collectionId},t.id))})}function wl(){const e=m(yl);if(!e)throw new Error("You cannot use useActionContext outside an ActionProvider");return e}function Nl(e,t){const n=wl();return g(()=>n.registerCallback(e,t),[n,e,t]),n}function kl(e){const t=wl();return g(()=>(t.startWorkflow=e,()=>{t.startWorkflow=void 0}),[e,t]),t}function Cl({action:t,objectIds:n}){const[r,s]=c(!1),a=p(()=>(n.length>0&&s(!0),Promise.resolve(!0)),[n]);return Nl(t.id,a),r&&e(Ze,{children:e(_l,{objectIds:n,isOpen:r,onClose:()=>{s(!1)}})})}const Sl={id:"addToCollection",name:"Add to Collection",description:"Add documents to a collection",confirm:!1,component:Cl};function _l({isOpen:n,onClose:r,objectIds:s}){return t(Ve,{isOpen:n,onClose:r,className:"max-w-lg w-full min-w-0 overflow-hidden",children:[e(We,{className:"flex flex-col min-w-0 overflow-hidden",children:"Add to a Collection"}),e(Lt,{className:"min-w-0 overflow-hidden",children:"Add the selected objects to an existing collection or create a new one."}),e("div",{className:"min-w-0 max-w-full overflow-hidden",children:e(jl,{onClose:r,objectIds:s})})]})}function jl({onClose:n,objectIds:r}){const s=Ae(),{client:a}=Te(),[i,o]=c(),l=({collectionId:e})=>{e&&r?.length&&a.store.collections.addMembers(e,r).then(()=>{s({title:"Add to collection success",status:"success",description:`Added ${r.length} objects to the selected collection`,duration:3e3}),n()}).catch(()=>{s({title:"Add to collection failure",status:"error",description:"Failed to add the selected objects to the collection",duration:5e3})})},d=[{name:"select",label:"Select Collection",content:t("div",{className:"p-4 min-w-0 max-w-full overflow-hidden",children:[e(Mt,{level:5,children:"Choose from existing collections"}),e(qe,{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(Xo,{onChange:(e,t)=>{"string"==typeof e||void 0===e?o(e):Array.isArray(e)&&e.length>0?o(e[0]):o(void 0)},value:i})})}),e(Je,{children:e(De,{isDisabled:!i,onClick:()=>i&&l({collectionId:i}),children:"Add to Collection"})})]})},{name:"create",label:"Create new",content:e("div",{className:"p-4",children:e(Ao,{onClose:n,onAddToCollection:e=>l({collectionId:e}),redirect:!1})})}];return t(Ut,{defaultValue:"select",tabs:d,fullWidth:!0,children:[e(Vt,{}),e(Wt,{})]})}function Il(){const n=$i(),r=n.size(),s=r>1?"s":"",a=n?.hasSelection(),i=n?.isSingleSelection();return e(vl,{children:t("div",{className:"flex items-center gap-x-2",children:[a&&!i&&t("div",{className:"flex items-center gap-x-1 shrink-0",children:[t("div",{className:"text-sm nowrap",children:[r," document",s," selected"]}),e(De,{title:"Clear selection",variant:"ghost",onClick:()=>{n?.removeAll()},children:e(C,{className:"size-4"})})]}),e(Dl,{selection:n,children:e(De,{variant:"ghost",alt:"More action",size:"sm",children:e(de,{size:16})})}),a&&e(Pl,{selection:n})]})})}function Pl({}){return e(zl,{})}function Tl({collectionId:r,allowFolders:s=!0}){const[a,i]=c([]),[o,l]=c(!1);return t(n,{children:[e(De,{onClick:()=>l(!0),children:"Upload"}),e(to,{collectionId:r??"",isOpen:o,onClose:()=>{l(!1),i([])},files:a,title:"Upload Files",onUploadComplete:e=>{e&&e.success&&i([])},allowFolders:s})]})}function zl(){const t=wl();return t.params.selection.hasSelection()&&e(De,{onClick:()=>t.run(pl.id),children:"Start Workflow"})}function Al(e){return{label:e.name,className:r("flex-1 px-2 py-2 hover:bg-accent nowrap",e.destructive?"text-destructive":"")}}function Dl({selection:n,children:r}){const s=wl();return t(at,{hover:!0,children:[e(it,{children:r}),e(ot,{className:"p-0 w-50",align:"end",sideOffset:6,children:e(Fl,{executeAction:e=>{s.run(e.id)},selection:n})})]})}function Fl({executeAction:t,selection:n}){const r=wl(),s=n?.hasSelection()?r.actions.filter(e=>!e.hideInList):[cl];return e("div",{className:"rounded-md shadow-md py-2",children:e("div",{className:"px-1 text-sm",children:e(Rt,{options:s,optionLayout:Al,onChange:e=>{t(e)},noCheck:!0})})})}const El=["className","cardClassName","headerClassName","contentClassName","timestampClassName","senderClassName","iconClassName","detailsClassName","artifactsClassName","proseClassName"];function $l(e,t,...n){const r={};for(const s of El)r[s]=ze(e[s],t[s],...n.map(e=>e?.[s]));return r}const Ol={[Jt.ANSWER]:{borderColor:"border-l-info",iconColor:"text-info",sender:"Agent",Icon:me},[Jt.COMPLETE]:{borderColor:"border-l-success",iconColor:"text-success",sender:"Completed",Icon:P},[Jt.IDLE]:{borderColor:"border-l-info",iconColor:"text-info",sender:"Ready",Icon:pe},[Jt.REQUEST_INPUT]:{borderColor:"border-l-attention",iconColor:"text-attention",sender:"Input",Icon:ue},[Jt.QUESTION]:{borderColor:"border-l-muted",iconColor:"text-muted",sender:"User",Icon:ue},[Jt.THOUGHT]:{borderColor:"border-l-purple-500",iconColor:"text-purple-600 dark:text-purple-400",sender:"Agent",Icon:me},[Jt.ERROR]:{borderColor:"border-l-destructive",iconColor:"text-destructive",sender:"Error",Icon:T},[Jt.UPDATE]:{borderColor:"border-l-success",iconColor:"text-success",sender:"Update",Icon:re},[Jt.PLAN]:{borderColor:"border-l-attention",iconColor:"text-attention",sender:"Plan",Icon:A},[Jt.TERMINATED]:{borderColor:"border-l-muted",iconColor:"text-muted",sender:"Terminated",Icon:P},[Jt.WARNING]:{borderColor:"border-l-attention",iconColor:"text-attention",sender:"Warning",Icon:T},[Jt.SYSTEM]:{borderColor:"border-l-muted",iconColor:"text-muted",sender:"System",Icon:re},[Jt.STREAMING_CHUNK]:{borderColor:"border-l-info",iconColor:"text-info",sender:"Agent",Icon:me},[Jt.BATCH_PROGRESS]:{borderColor:"border-l-blue-500",iconColor:"text-blue-600 dark:text-blue-400",sender:"Batch",Icon:z},default:{borderColor:"border-l-muted",iconColor:"text-muted",sender:"Agent",Icon:me}};const Rl=h(function({message:n,showPulsatingCircle:r=!1,onSendMessage:s,className:a,cardClassName:i,headerClassName:o,contentClassName:d,timestampClassName:m,senderClassName:p,iconClassName:h,detailsClassName:f,artifactsClassName:b,proseClassName:y,messageStyleOverrides:v,StoreLinkComponent:x,CollectionLinkComponent:N}){const[k,C]=c(!1),{client:S}=Te(),_=Ae(),j=lr(),{openImage:P}=Pr(),T=u(S);T.current=S;const z=u(j);z.current=j;const{renderContent:A,isDownloading:D}=la({client:S,toast:_}),F=l(()=>{const e=Ol[n.type]||Ol.default,t=v?.default,r=v?.[n.type];return{...e,...t,...r,...$l(e,{className:a,cardClassName:i,headerClassName:o,contentClassName:d,timestampClassName:m,senderClassName:p,iconClassName:h,detailsClassName:f,artifactsClassName:b,proseClassName:y},t,r)}},[n.type,v,a,i,o,d,m,p,h,f,b,y]),E=l(()=>{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()*$r.length);e=e.replace(/%thinking_message%/g,$r[t])}return e},[n.message]),$=l(()=>E?function(e,t,n){if("string"!=typeof e)return e;if(t===Jt.THOUGHT||"string"==typeof n&&(n.toLowerCase().includes("thinking about")||n.toLowerCase().includes("i'm thinking")||n.toLowerCase().includes("💭"))){let t=e;return/\d+\.\s+.+/.test(t)&&(t=t.replace(/(\d+\.\s+.+?)(?=\s+\d+\.\s+|$)/g,"$1\n\n"),t=t.replace(/(\d+\.\s+.+\n)([^\d\n][^:])/g,"$1 $2")),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+/g,"\n- ")),t}return/\d+\.\s+.+/.test(e)&&!e.includes("\n\n")?e.replace(/(\d+\.\s+.+?)(?=\s+\d+\.\s+|$)/g,"$1\n\n"):e}(E,n.type,"string"==typeof n.message?n.message:void 0):"",[E,n.type,n.message]),O=async e=>{const t="string"==typeof E?E:"";if(!t.trim())return void _({status:"error",title:"No content to export",duration:2e3});const r=`Message ${fn(n.timestamp).format("YYYY-MM-DD HH-mm-ss")}`;await A(t,{format:e,title:r,artifactRunId:W})},R="string"==typeof E&&E.trim().length>0,L=l(()=>({a:({node:t,ref:n,...r})=>{const s=r.href||"";if(s.includes("/store/objects")){if(x){const t=s.split("/store/objects/")[1]||"";return e(x,{href:s,documentId:t,children:r.children})}return e(yn,{href:s,topLevelNav:!0,children:r.children})}if(s.includes("/store/collections")){if(N){const t=s.split("/store/collections/")[1]||"";return e(N,{href:s,collectionId:t,children:r.children})}return e(yn,{href:s,topLevelNav:!0,children:r.children})}return e("a",{...r,target:"_blank",rel:"noopener noreferrer"})},img:({node:t,ref:n,...r})=>e("img",{...r,className:"max-w-full h-auto rounded-lg shadow-md my-3 cursor-pointer hover:shadow-lg transition-shadow",loading:"lazy",onClick:()=>r.src&&P(r.src,r.alt)})}),[P,x,N]),M=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 e("div",{className:ze("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.proseClassName),style:{overflowWrap:"anywhere"},children:e(vn,{artifactRunId:r,onProposalSelect:e=>s?.(e),onProposalSubmit:e=>s?.(e),components:L,children:t})})},[U,V]=c([]),W=n.workflow_run_id,q=n.details,B=q?.outputFiles??q?.files,H=Array.isArray(B)?B.join(","):"";g(()=>{(async()=>{if(!W||!Array.isArray(B)||0===B.length)return void V([]);const e=T.current,t=z.current;try{const n=await Promise.all(B.map(async n=>{if("string"!=typeof n||!n.trim())return null;const r=n.trim(),s=r.startsWith("artifact:")?r.slice(9):r,a=s.split(".").pop()?.toLowerCase()||"",i=new Set(["png","jpg","jpeg","gif","webp","bmp","svg"]).has(a),o=i?"inline":"attachment";try{const n=cr(W,s,o);let a;if(t)a=await t.getOrFetch(n,async()=>(await e.files.getArtifactDownloadUrl(W,s,o)).url);else{a=(await e.files.getArtifactDownloadUrl(W,s,o)).url}return{displayName:r,artifactPath:s,url:a,isImage:i}}catch(e){return console.error(`Failed to resolve artifact URL for ${s}`,e),null}}));V(n.filter(e=>!!e))}catch(e){console.error("Error loading artifact URLs from message details",e),V([])}})()},[W,H]);const G=Lr(n),{Icon:J}=F;return e("div",{className:ze("w-full max-w-full",F.className),children:t("div",{className:ze("border-l-4 bg-white dark:bg-gray-900 mb-4 w-full max-w-full overflow-hidden",F.borderColor,F.cardClassName),"data-workstream-id":G,children:[t("div",{className:ze("flex items-center justify-between px-4 py-1.5",F.headerClassName),children:[t("div",{className:"flex items-center gap-1.5",children:[e("div",{className:ze(r?"animate-fadeIn":"",F.iconClassName),children:r?e(Nr,{size:"sm",color:"blue"}):e(J,{className:`size-4 ${F.iconColor}`})}),e("span",{className:ze("text-xs font-medium text-muted",F.senderClassName),children:F.sender}),"main"!==G&&"all"!==G&&e(lt,{variant:"default",className:"text-xs text-muted ml-1",children:G})]}),t("div",{className:"flex items-center gap-1.5 print:hidden",children:[e("span",{className:ze("text-[11px] text-muted/70",F.timestampClassName),children:fn(n.timestamp).format("HH:mm:ss")}),e(De,{variant:"ghost",size:"xs",onClick:()=>{const e=E||"",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(()=>{_({status:"success",title:"Copied to clipboard",duration:2e3})})},className:"text-muted/50 hover:text-muted h-5 w-5 p-0",title:"Copy message",children:e(I,{className:"size-3"})}),R&&t(qt,{trigger:e(De,{variant:"ghost",size:"xs",className:"text-muted/50 hover:text-muted h-5 w-5 p-0",title:"Export message",disabled:D,children:e(w,{className:"size-3 "+(D?"animate-pulse":"")})}),children:[e(Bt,{onClick:()=>O(Qt.pdf),children:"Export as PDF"}),e(Bt,{onClick:()=>O(Qt.docx),children:"Export as Word"})]})]})]}),t("div",{className:ze("px-4 pb-3 bg-white dark:bg-gray-900 overflow-hidden",F.contentClassName),children:[n.type===Jt.REQUEST_INPUT&&n.details?.ux?(()=>{const t=n.details.ux;return e(Fr,{question:"string"==typeof E?E:"",options:t.options,variant:t.variant,multiSelect:t.multiSelect,allowFreeResponse:t.allowFreeResponse,placeholder:t.placeholder,onSelect:e=>s?.(e),onMultiSelect:e=>s?.(e.join(", ")),onSubmit:e=>s?.(e),hideBorder:!0})})():E&&e("div",{className:"message-content break-words w-full",style:{overflowWrap:"anywhere",wordBreak:"break-word"},children:M($||E)}),U.length>0&&t("div",{className:ze("mt-3 text-xs",F.artifactsClassName),children:[e("div",{className:"font-medium text-muted mb-1",children:"Artifacts"}),U.some(e=>e.isImage)&&e("div",{className:"mb-2 flex flex-wrap gap-3",children:U.filter(e=>e.isImage).map(({displayName:n,artifactPath:r,url:s})=>t("div",{className:"max-w-xs cursor-pointer",onClick:()=>P(s,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})]},`${r}-preview`))}),e("div",{className:"flex flex-wrap gap-2 print:hidden",children:U.map(({displayName:t,artifactPath:n,url:r})=>e(De,{variant:"outline",size:"xs",className:"px-2 py-1 text-xs",onClick:()=>window.open(r,"_blank"),title:n,children:t},n+r))})]}),n.details&&t("div",{className:ze("mt-2 print:hidden",F.detailsClassName),children:[t("button",{onClick:()=>C(!k),className:"text-[11px] text-muted flex items-center",children:[k?"Hide":"Show"," details",e("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-3 w-3 ml-1 transition-transform "+(k?"rotate-180":""),fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),k&&e("div",{className:"mt-1 p-1.5 bg-muted border border-mixer-muted/40 rounded text-sm",children:"string"==typeof n.details?M(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.showPulsatingCircle===t.showPulsatingCircle&&e.onSendMessage===t.onSendMessage&&e.messageStyleOverrides===t.messageStyleOverrides&&El.every(n=>e[n]===t[n]));const Ll=o.memo(function({text:n,workstreamId:r,revealSpeed:s=300,isComplete:a=!1,timestamp:i,className:o,cardClassName:d,headerClassName:m,contentClassName:h,proseClassName:f,senderClassName:b,iconClassName:y}){const[v,x]=c(0),[w,N]=c(""),k=u(null),C=u(n.length),S=u(0),_=u(i||Date.now()),j=u(n),P=u(0),T=u(performance.now()),z=u(s),A=u(0);g(()=>{const e=performance.now(),t=n.length-P.current,r=e-T.current;if(t>0&&r>30){const e=t/r*1e3,n=.2;z.current=z.current*(1-n)+e*n,z.current=Math.max(50,Math.min(2e3,z.current))}P.current=n.length,T.current=e},[n.length]),C.current=n.length,j.current=n;const D=p(()=>{let e=performance.now();const t=n=>{const r=n-e;e=n;const s=C.current-S.current;if(s<=0)return A.current=0,void(k.current=null);let i;if(a)i=Math.max(500,2*z.current);else if(s<20)i=.85*z.current;else if(s<100)i=z.current;else if(s<500){const e=(s-100)/400;i=z.current*(1+.5*e)}else i=2*z.current;const o=i*r/1e3+A.current,l=Math.floor(o);A.current=o-l,l>0&&(S.current=Math.min(S.current+l,C.current),x(S.current)),k.current=requestAnimationFrame(t)};k.current=requestAnimationFrame(t)},[a]);g(()=>(n.length>S.current&&!k.current&&D(),()=>{k.current&&(cancelAnimationFrame(k.current),k.current=null)}),[n.length,D]),g(()=>{a&&S.current<n.length&&(k.current&&(cancelAnimationFrame(k.current),k.current=null),D())},[a,n.length,D]);const F=u(null),E=u(0);g(()=>{(v>=C.current||a)&&(N(j.current.slice(0,v)),E.current=v)},[v,a]);const $=v<n.length&&!a;g(()=>{if($)return F.current||(F.current=window.setInterval(()=>{const e=S.current;e>E.current&&(N(j.current.slice(0,e)),E.current=e)},33)),()=>{F.current&&(clearInterval(F.current),F.current=null)};F.current&&(clearInterval(F.current),F.current=null)},[$]);const O=Ae(),R=l(()=>fn(_.current).format("HH:mm:ss"),[]),L=v<n.length,M=l(()=>{const e=w||n.slice(0,v);return L?e+"│":e},[w,n,v,L]);return n?e("div",{className:ze("w-full max-w-full",o),children:t("div",{className:ze("border-l-4 bg-white dark:bg-gray-900 mb-4 border-l-purple-500 w-full max-w-full overflow-hidden",d),"data-workstream-id":r,children:[t("div",{className:ze("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:ze("animate-fadeIn",y),children:L?e("span",{className:"size-2 rounded-full bg-blue-500 animate-pulse inline-block"}):e(me,{className:"size-4 text-purple-600 dark:text-purple-400"})}),e("span",{className:ze("text-xs font-medium text-muted",b),children:"Agent"}),r&&"main"!==r&&t("span",{className:"text-xs text-muted",children:["• Task ",r]})]}),t("div",{className:"flex items-center gap-2 text-muted",children:[e("span",{className:"text-[11px]",children:R}),e(De,{variant:"ghost",size:"xs",onClick:()=>{navigator.clipboard.writeText(n).then(()=>{O({status:"success",title:"Copied to clipboard",duration:2e3})})},className:"size-6 p-0 hover:bg-gray-100 dark:hover:bg-gray-800",title:"Copy message",children:e(I,{className:"size-3"})})]})]}),t("div",{className:ze("px-3 pb-2 streaming-content",L&&"streaming-active",h),children:[e("div",{className:ze("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(vn,{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}),Ml=new Set(["tool","tool_run_id","activity_group_id","event_class","tool_iteration","tool_status","tools","streamed","files","outputFiles"]);function Ul(e){return e?Object.entries(e).filter(([e,t])=>!Ml.has(e)&&null!=t&&""!==t):[]}function Vl(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/^./,e=>e.toUpperCase())}function Wl(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 ql=e=>/\.(png|jpg|jpeg|gif|webp|svg)(\?|$)/i.test(e);function Bl({files:n,className:r}){const{openImage:s}=Pr();return n&&0!==n.length?e("div",{className:ze("mt-2 flex flex-wrap gap-2",r),children:n.map((n,r)=>{const a=n.split("/").pop()?.split("?")[0]||"file";return ql(n)?e("div",{className:"cursor-pointer",onClick:()=>s(n,a),title:"Click to enlarge",children:e("img",{src:n,alt:a,className:"max-w-[300px] max-h-[200px] rounded border hover:opacity-80 transition-opacity hover:shadow-lg"})},r):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:["📎 ",a]},r)})}):null}const Hl=e=>{if(!e)return;const t=e.files??e.outputFiles;return Array.isArray(t)?t:void 0},Gl=e=>{const t=e.details;if(t?.tool)return t.tool;switch(e.type){case Jt.UPDATE:return"update";case Jt.WARNING:return"warning";case Jt.ERROR:return"error";case Jt.SYSTEM:return"system";default:return"activity"}};function Jl({message:n,isExpanded:r,onToggle:s,artifactRunId:a,classNames:i={}}){const[o,l]=c([]),d=Ae(),{client:m}=Te(),p=lr(),h=u(m);h.current=m;const f=u(p);f.current=p;const b=n.details,y=Gl(n),v=Hl(b),x="string"==typeof n.message?n.message:"";g(()=>{if(!v||0===v.length||!a)return void l([]);let e=!1;return(async()=>{const t=h.current,n=f.current,r=await Promise.all(v.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,s=r.split(".").pop()?.toLowerCase()||"",i=new Set(["png","jpg","jpeg","gif","webp","bmp","svg"]).has(s)?"inline":"attachment";try{const e=cr(a,r,i);if(n)return await n.getOrFetch(e,async()=>(await t.files.getArtifactDownloadUrl(a,r,i)).url);return(await t.files.getArtifactDownloadUrl(a,r,i)).url}catch(e){return console.error(`Failed to resolve artifact URL for ${r}`,e),null}}));e||l(r.filter(e=>!!e))})(),()=>{e=!0}},[v,a]);const w=o.filter(e=>ql(e)),N=o.filter(e=>!ql(e));return t("div",{className:ze("border-b border-gray-100 dark:border-gray-800 last:border-b-0",i.itemClassName),children:[t("div",{className:ze("flex items-start justify-between px-3 py-2 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors",i.itemHeaderClassName),onClick: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:e(r?_:j,{className:"size-3 text-muted"})}),e("div",{className:"flex-1 min-w-0",children:x?e("span",{className:"text-xs text-foreground line-clamp-2",children:x}):t("span",{className:"text-xs text-muted italic",children:["Activity: ",y]})})]}),t("div",{className:"flex items-center gap-2 flex-shrink-0",children:[!r&&e("span",{className:ze("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",i.toolBadgeClassName),children:y}),e(De,{variant:"ghost",size:"xs",onClick:e=>{e.stopPropagation(),(()=>{const e=[x,b?"\n\nDetails:\n"+JSON.stringify(b,null,2):""].join("").trim();navigator.clipboard.writeText(e).then(()=>{d({status:"success",title:"Copied to clipboard",duration:2e3})})})()},className:"text-muted opacity-0 group-hover:opacity-100 transition-opacity",title:"Copy message",children:e(I,{className:"size-3"})})]})]}),w.length>0&&e("div",{className:"px-3 pb-1.5",children:e(Bl,{files:w})}),r&&(()=>{const r=b?.tool_status,s=Ul(b);return t("div",{className:ze("px-4 py-2 bg-gray-50/50 dark:bg-gray-800/30",i.itemContentClassName),children:[t("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[e("span",{className:ze("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",i.toolBadgeClassName),children:y}),r&&e("span",{className:ze("text-[10px] px-1.5 py-0.5 rounded-md border font-medium",Wl(r)),children:r}),e("span",{className:"text-[10px] text-muted/70",children:fn(n.timestamp).format("HH:mm:ss")})]}),s.length>0&&e("div",{className:"mb-2 space-y-0.5",children:s.map(([n,r])=>t("div",{className:"flex gap-1.5 text-xs",children:[t("span",{className:"text-muted font-medium flex-shrink-0",children:[Vl(n),":"]}),e("span",{className:"text-foreground break-all",children:"object"==typeof r?JSON.stringify(r):String(r)})]},n))}),x&&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(vn,{artifactRunId:a,children:x})}),N.length>0&&e(Bl,{files:N}),b&&Object.keys(b).length>1&&t("details",{className:"mt-2 text-xs border rounded p-1.5 bg-muted/30",onClick:e=>e.stopPropagation(),children:[e("summary",{className:"cursor-pointer text-muted",children:"Raw details"}),e("pre",{className:"mt-2 p-2 bg-muted rounded text-xs overflow-x-auto font-mono whitespace-pre-wrap",children:JSON.stringify(b,null,2)})]})]})})()]})}function Kl({files:t,artifactRunId:n}){const[r,s]=c([]),{client:a}=Te(),i=lr(),o=u(a);o.current=a;const l=u(i);return l.current=i,g(()=>{if(!t||0===t.length||!n)return void s([]);let e=!1;return(async()=>{const r=o.current,a=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,s=t.split(".").pop()?.toLowerCase()||"";if(new Set(["png","jpg","jpeg","gif","webp","bmp","svg"]).has(s))return null;if(t.startsWith("http://")||t.startsWith("https://"))return t;try{const e=cr(n,t,"attachment");if(a)return await a.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||s(i.filter(e=>!!e))})(),()=>{e=!0}},[t,n]),0===r.length?null:e("div",{className:"pl-4 pr-2 pb-1.5",children:e(Bl,{files:r})})}function Yl({messages:t,artifactRunId:n}){const[r,s]=c([]),{client:a}=Te(),i=lr(),o=u(a);o.current=a;const l=u(i);return l.current=i,g(()=>{if(!n||0===t.length)return void s([]);const e=t[t.length-1].details,r=Hl(e);if(!r||0===r.length)return void s([]);let a=!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 s=r.startsWith("artifact:")?r.slice(9):r,a=s.split(".").pop()?.toLowerCase()||"";if(!new Set(["png","jpg","jpeg","gif","webp","bmp","svg"]).has(a))return null;if(s.startsWith("http://")||s.startsWith("https://"))return s;try{const r=cr(n,s,"inline");if(t)return await t.getOrFetch(r,async()=>(await e.files.getArtifactDownloadUrl(n,s,"inline")).url);return(await e.files.getArtifactDownloadUrl(n,s,"inline")).url}catch(e){return console.error(`Failed to resolve artifact URL for ${s}`,e),null}}));a||s(i.filter(e=>!!e))})(),()=>{a=!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(Bl,{files:r})})}const Zl=h(function({messages:n,showPulsatingCircle:r=!1,toolRunId:s,toolStatus:a,rootClassName:i,headerClassName:o,senderClassName:l,toolSummaryClassName:d,toolBadgeClassName:m,itemClassName:p,itemHeaderClassName:h,itemContentClassName:f}){const[b,y]=c(!0),[v,x]=c(new Set),[w,N]=c(new Set),k=u(n.length),C=Ae(),S=n.find(e=>e.workflow_run_id)?.workflow_run_id??n[0]?.workflow_run_id;g(()=>{const e=k.current,t=n.length;if(t>e){const n=new Set;for(let r=e;r<t;r++)n.add(r);N(n);const r=setTimeout(()=>{N(new Set)},500);return k.current=t,()=>clearTimeout(r)}k.current=t},[n.length]);const z=n[0],A=n[n.length-1],D=z.timestamp,F=A.timestamp,E=n.map(e=>Gl(e)),$=1===new Set(E).size?`${n.length}× ${E[0]}`:`${n.length} activity updates`,O=e=>{x(t=>{const n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})};return t("div",{className:ze("border-l-4 overflow-hidden bg-white dark:bg-gray-900 mb-4","completed"===a?"border-l-success":"error"===a?"border-l-destructive":"warning"===a?"border-l-attention":"border-l-purple-500",i),children:[t("div",{className:ze("flex items-center justify-between px-4 py-1.5 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors",o),onClick:()=>y(!b),children:[t("div",{className:"flex items-center gap-1",children:[r?e(Nr,{size:"sm",color:"blue"}):"running"===a?e("span",{className:"size-2 rounded-full bg-blue-500 inline-block"}):"completed"===a?e(P,{className:"size-4 text-success"}):"error"===a?e(T,{className:"size-4 text-destructive"}):"warning"===a?e(B,{className:"size-4 text-attention"}):e(me,{className:"size-4 text-purple-600 dark:text-purple-400"}),e("span",{className:ze("text-xs font-medium text-muted",l),children:"Agent"}),e("span",{className:ze("text-xs text-purple-600 dark:text-purple-400 font-medium",d),children:$}),e(b?j:_,{className:"size-3 text-muted"})]}),t("div",{className:"flex items-center gap-1",children:[t("span",{className:"text-[11px] text-muted/70",children:[fn(D).format("HH:mm:ss"),n.length>1&&` - ${fn(F).format("HH:mm:ss")}`]}),e(De,{variant:"ghost",size:"xs",onClick:e=>{e.stopPropagation(),(()=>{const e=n.map(e=>{const t=e.details;return`[${Gl(e)}] ${e.message||""}\n${t?JSON.stringify(t,null,2):""}`}).join("\n\n---\n\n");navigator.clipboard.writeText(e).then(()=>{C({status:"success",title:"Copied all tool calls to clipboard",duration:2e3})})})()},className:"text-muted/50 hover:text-muted h-5 w-5 p-0",title:"Copy all tool calls",children:e(I,{className:"size-3"})})]})]}),e(Yl,{messages:n,artifactRunId:S}),b&&e("div",{className:"px-3 py-0.5 space-y-0",children:n.map((r,s)=>{const a=r.details,i=Gl(r),o="string"==typeof r.message?r.message:"",l=w.has(s),c=v.has(s),d=Hl(a);return t("div",{className:ze("border-b border-gray-100 dark:border-gray-800 last:border-b-0",p),style:{opacity:l?0:1,transform:l?"translateX(-10px)":"translateX(0)",transition:"opacity 0.3s ease-out, transform 0.3s ease-out",transitionDelay:100*(s-(n.length-w.size))+"ms",animation:l?"slideInFade 0.4s ease-out forwards":"none",animationDelay:100*(s-(n.length-w.size))+"ms"},children:[t("div",{className:ze("flex items-start gap-2 py-1.5 text-xs cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800/50",h),onClick:()=>O(s),title:o,children:[e("div",{className:"flex-shrink-0 pt-0.5",children:e(c?_:j,{className:"size-3 text-muted"})}),e("div",{className:"flex-1 min-w-0",children:o?e("span",{className:"text-foreground line-clamp-2",children:o}):t("span",{className:"text-muted italic",children:["Activity: ",i]})}),!c&&e("span",{className:ze("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 flex-shrink-0",m),children:i})]}),e(Kl,{files:d,artifactRunId:S}),c&&(()=>{const n=a?.tool_status,s=Ul(a);return t("div",{className:ze("pl-5 pr-3 pb-2 text-sm",f),children:[t("div",{className:"flex items-center gap-2 mb-1.5 flex-wrap",children:[e("span",{className:ze("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",m),children:i}),n&&e("span",{className:ze("text-[10px] px-1.5 py-0.5 rounded-md border font-medium",Wl(n)),children:n}),e("span",{className:"text-[10px] text-muted/70",children:fn(r.timestamp).format("HH:mm:ss")})]}),s.length>0&&e("div",{className:"mb-1.5 space-y-0.5",children:s.map(([n,r])=>t("div",{className:"flex gap-1.5 text-xs",children:[t("span",{className:"text-muted font-medium flex-shrink-0",children:[Vl(n),":"]}),e("span",{className:"text-foreground break-all",children:"object"==typeof r?JSON.stringify(r):String(r)})]},n))}),o&&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(vn,{artifactRunId:S,children:o})}),a&&Object.keys(a).length>1&&t("details",{className:"mt-1.5 text-xs",children:[e("summary",{className:"text-muted cursor-pointer",children:"Raw details"}),e("pre",{className:"mt-1 p-2 bg-muted rounded text-xs overflow-x-auto",children:JSON.stringify(a,null,2)})]})]})})()]},`${r.timestamp}-${s}`)})}),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 "}),!b&&e("div",{className:"group",children:n.map((t,n)=>e(Jl,{message:t,isExpanded:v.has(n),onToggle:()=>O(n),artifactRunId:S,classNames:{toolBadgeClassName:m,itemClassName:p,itemHeaderClassName:h,itemContentClassName:f}},`${t.timestamp}-${n}`))})]})},(e,t)=>e.messages.length===t.messages.length&&(e.showPulsatingCircle===t.showPulsatingCircle&&(e.toolRunId===t.toolRunId&&(e.toolStatus===t.toolStatus&&(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[0]?.timestamp===t.messages[0]?.timestamp&&e.messages[e.messages.length-1]?.timestamp===t.messages[t.messages.length-1]?.timestamp)))))))))))));function Ql({workstreams:n,activeWorkstream:r,onSelectWorkstream:s,count:a,completionStatus:i}){const o=new Map;o.set("all","All Messages"),o.set("main","Main"),n.forEach((e,t)=>{"all"!==t&&"main"!==t&&"research_france"!==t&&"statistics"!==t&&o.set(t,e)}),n=o;const l=Array.from(n.entries()).sort(([e],[t])=>"all"===e?-1:"all"===t?1:"main"===e?-1:"main"===t?1:e.localeCompare(t)),c=l.length>2;return e("div",c?{className:"flex overflow-x-auto space-x-1 mb-1 bg-muted border-b border-muted/20 sticky top-0 z-10",children:l.map(([n,o])=>t("button",{className:ze("px-2 py-1 text-xs font-medium whitespace-nowrap transition-colors flex items-center gap-1.5",r===n?"bg-info text-info border-b-2 border-info":"text-muted hover:bg-muted border-b-2 border-transparent"),onClick:()=>s(n),title:o.length>20?o:void 0,children:[o.length>20?o.substring(0,18)+"...":o,a&&a.has(n)&&a.get(n)>0&&t("div",{className:"flex items-center space-x-1",children:[e("span",{className:ze("inline-flex items-center justify-center p-1 text-xs rounded-full",r===n?"bg-info text-info":"bg-muted text-muted"),children:a.get(n)}),i&&"all"!==n&&(i.get(n)?e(P,{className:"size-3 text-success"}):e(pe,{className:"size-3 text-attention"}))]})]},n))}:{className:"py-0.5"})}function Xl(e,t){return"all"===t?[...e]:"main"===t?e.filter(e=>"main"===Lr(e)):e.filter(e=>Lr(e)===t)}const ec=(e,t)=>e.includes("%thinking_message%")?e.replace(/%thinking_message%/g,$r[t]):e,tc=e=>e.type===Jt.BATCH_PROGRESS&&!!e.details?.batch_id,nc=(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 s="number"==typeof e.timestamp?e.timestamp:new Date(e.timestamp).getTime();return("number"==typeof t.timestamp?t.timestamp:new Date(t.timestamp).getTime())-s<2e3};class rc extends f{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-l-4 border-l-destructive bg-destructive/10 px-4 py-2 my-2 rounded-r",children:[e("p",{className:"text-sm text-destructive font-medium",children:"Failed to render message"}),e("p",{className:"text-xs text-muted mt-1 truncate",children:this.state.error?.message||"Unknown error"})]}):this.props.children}}const sc=o.memo(function({messages:r,bottomRef:s,viewMode:a="stacked",isCompleted:i=!1,streamingMessages:d=new Map,onSendMessage:m,thinkingMessageIndex:h=0,messageItemClassNames:f,messageStyleOverrides:b,toolCallGroupClassNames:y,hideToolCallsInViewMode:v,streamingMessageClassNames:x,batchProgressPanelClassNames:w,hideWorkstreamTabs:N,workingIndicatorClassName:k,messageListClassName:C,StoreLinkComponent:S,CollectionLinkComponent:_,prependFriendlyMessage:j}){const I=u(null),[P,T]=c("all"),z=u(0),A=u(null),D=d.size>0,F=l(()=>{let e=0;return d.forEach(t=>{e+=t.text?.length||0}),Math.floor(e/200)},[d]),E=p(()=>{s.current&&(s.current.scrollIntoView({behavior:D?"instant":"smooth"}),z.current=Date.now()),A.current=null},[s,D]);g(()=>{const e=Date.now()-z.current;if(e>=100)E();else if(null===A.current){const t=100-e;A.current=window.setTimeout(E,t)}return()=>{null!==A.current&&(clearTimeout(A.current),A.current=null)}},[r.length,d.size,F,E]);const $=o.useMemo(()=>{const e=[...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())),t=[];for(const n of e){const e=t[t.length-1];e&&nc(e,n)||t.push(n)}return t},[r]),O=o.useMemo(()=>{const e=function(e){const t=new Map;return t.set("all","All Messages"),t.set("main","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),console.log(`Found workstream: ${e.workstream_id}`))}),t.size<=2&&!t.has("main")&&t.set("main","Main"),console.log("Final workstreams map:",t),t}($);return e},[$]),R=o.useMemo(()=>{const e=new Map;e.set("all",$.length);const t=Xl($,"main");return e.set("main",t.length),$.forEach(t=>{const n=Lr(t);"main"!==n&&e.set(n,(e.get(n)||0)+1)}),e},[$]),L=o.useMemo(()=>"all"===P?$:Xl($,P),[$,P]),{importantMessages:M,recentThinking:U}=o.useMemo(()=>{const e=d.size>0;return{importantMessages:L.filter(e=>e.type===Jt.ANSWER||e.type===Jt.QUESTION||e.type===Jt.COMPLETE||e.type===Jt.IDLE||e.type===Jt.REQUEST_INPUT||e.type===Jt.TERMINATED||e.type===Jt.ERROR||e.type===Jt.THOUGHT&&(e.details?.tool||e.details?.tools||e.details?.streamed)),recentThinking:i||e?[]:L.filter(e=>e.type===Jt.UPDATE||e.type===Jt.PLAN||e.type===Jt.THOUGHT&&!e.details?.tool&&!e.details?.tools&&!e.details?.streamed).slice(-1)}},[L,i,d.size]),{completeStreaming:V,incompleteStreaming:W}=o.useMemo(()=>{const e=new Map,t=[],n=L.length>0?Math.max(...L.map(e=>"number"==typeof e.timestamp?e.timestamp:new Date(e.timestamp).getTime())):-1/0;return d.forEach((r,s)=>{if(P&&"all"!==P){const e=r.workstreamId||"main";if(P!==e)return}const a=r.startTimestamp<=n;r.isComplete||a?e.set(s,r):r.text&&t.push({id:s,data:r})}),{completeStreaming:e,incompleteStreaming:t}},[d,P,L]),q=o.useMemo(()=>Jr(Hr(L,V,P)),[L,V,P]),B=o.useMemo(()=>Jr(Hr(M,V,P)),[M,V,P]),H=l(()=>!i&&(d.size>0||U.length>0||!L.some(e=>e.type===Jt.COMPLETE||e.type===Jt.IDLE||e.type===Jt.TERMINATED)),[i,d.size,U.length,L]),G=l(()=>{const e=new Map,t=new Map;$.forEach(e=>{const n=Lr(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[r.length-1];e.set(n,[Jt.COMPLETE,Jt.IDLE,Jt.REQUEST_INPUT,Jt.TERMINATED].includes(t.type))}return e},[$]);return t("div",{ref:I,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",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 need more separation and better styling */\n .vprose table {\n margin-top: 0.875rem;\n margin-bottom: 0.875rem;\n border-collapse: collapse;\n width: 100%;\n }\n .vprose th,\n .vprose td {\n padding: 0.5rem 0.625rem;\n border: 1px solid var(--gray-6, #e5e7eb);\n text-align: left;\n }\n .vprose thead th {\n background-color: var(--gray-3, #f3f4f6);\n font-weight: 600;\n color: var(--gray-11, #6b7280);\n font-size: 0.75rem;\n text-transform: uppercase;\n letter-spacing: 0.05em;\n }\n .vprose tbody tr:hover {\n background-color: var(--gray-2, #f9fafb);\n }\n /* Dark mode table styles */\n .dark .vprose th,\n .dark .vprose td {\n border-color: var(--gray-7, #374151);\n }\n .dark .vprose thead th {\n background-color: var(--gray-4, #1f2937);\n color: var(--gray-11, #9ca3af);\n }\n .dark .vprose tbody tr:hover {\n background-color: var(--gray-3, #111827);\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 "}),e("div",{className:ze("sticky top-0 z-10",N&&"hidden"),children:e(Ql,{workstreams:O,activeWorkstream:P,onSelectWorkstream:T,count:R,completionStatus:G})}),0===L.length?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:"all"===P?"Waiting for agent response...":"No messages in this workstream yet..."})}):t("div",{className:ze("flex-1 flex flex-col justify-start pb-4 space-y-2 w-full max-w-full",C),children:[j&&e(Rl,{...f,messageStyleOverrides:b,message:{type:Jt.QUESTION,message:j,timestamp:L[0]?.timestamp??Date.now(),workflow_run_id:"",workstream_id:"main"}},j),t(n,"stacked"===a?{children:[q.map((t,n)=>{const r=n===q.length-1;if("tool_group"===t.type){const s=t.messages[t.messages.length-1],o="completed"===t.toolStatus||"error"===t.toolStatus||"warning"===t.toolStatus,l=!i&&r&&!Rr.includes(s.type)&&!o;return v?.includes(a)?null:e(rc,{children:e(Zl,{messages:t.messages,showPulsatingCircle:l,toolRunId:t.toolRunId,toolStatus:t.toolStatus,...y})},`group-${t.toolRunId||t.firstTimestamp}-${n}`)}if("streaming"===t.type)return e(Ll,{text:t.text,workstreamId:t.workstreamId,isComplete:t.isComplete,timestamp:t.startTimestamp,...x},`streaming-${t.streamingId}-${n}`);{const s=t.message,a=!i&&r&&!Rr.includes(s.type);return tc(s)?e(rc,{children:e(zr,{message:s,batchData:s.details,isRunning:!s.details.completed_at,...w})},`batch-${s.details.batch_id}-${s.timestamp}-${n}`):e(rc,{children:e(Rl,{message:s,showPulsatingCircle:a,onSendMessage:m,...f,messageStyleOverrides:b,StoreLinkComponent:S,CollectionLinkComponent:_})},`${s.timestamp}-${n}`)}}),W.map(({id:t,data:n})=>e(Ll,{text:n.text,workstreamId:n.workstreamId,isComplete:!1,timestamp:n.startTimestamp,...x},`streaming-incomplete-${t}`)),H&&0===W.length&&t("div",{className:ze("flex items-center gap-2 pl-3 py-1.5 border-l-2 border-l-purple-500",k),children:[e(Nr,{size:"sm",color:"blue"}),e("span",{className:"text-xs text-muted",children:"Working..."})]})]}:{children:[B.map((t,n)=>{const r=n===B.length-1;if("tool_group"===t.type){const s=t.messages[t.messages.length-1],o="completed"===t.toolStatus||"error"===t.toolStatus||"warning"===t.toolStatus,l=!i&&0===U.length&&r&&!Rr.includes(s.type)&&!o;return v?.includes(a)?null:e(rc,{children:e(Zl,{messages:t.messages,showPulsatingCircle:l,toolRunId:t.toolRunId,toolStatus:t.toolStatus,...y})},`group-${t.toolRunId||t.firstTimestamp}-${n}`)}if("streaming"===t.type)return e(Ll,{text:t.text,workstreamId:t.workstreamId,isComplete:t.isComplete,timestamp:t.startTimestamp,...x},`streaming-${t.streamingId}-${n}`);{const s=t.message,a=!i&&0===U.length&&r&&!Rr.includes(s.type);return tc(s)?e(rc,{children:e(zr,{message:s,batchData:s.details,isRunning:!s.details.completed_at,...w})},`batch-${s.details.batch_id}-${s.timestamp}-${n}`):e(rc,{children:e(Rl,{message:s,showPulsatingCircle:a,onSendMessage:m,...f,messageStyleOverrides:b,StoreLinkComponent:S,CollectionLinkComponent:_})},`${s.timestamp}-${n}`)}}),U.map((t,n)=>e(Ll,{text:ec(t.message||"",h),workstreamId:Lr(t),isComplete:n<U.length-1,timestamp:t.timestamp,...x},`thinking-${t.timestamp}-${n}`)),W.map(({id:t,data:n})=>e(Ll,{text:n.text,workstreamId:n.workstreamId,isComplete:!1,timestamp:n.startTimestamp,...x},`streaming-incomplete-${t}`)),H&&0===U.length&&0===W.length&&t("div",{className:ze("flex items-center gap-2 pl-3 py-1.5 border-l-2 border-l-purple-500",k),children:[e(Nr,{size:"sm",color:"blue"}),e("span",{className:"text-xs text-muted",children:"Working..."})]})]}),e("div",{ref:s,className:"h-2"})]})]})});class ac{vertesia;updateState;_interactive=!0;_debug_mode=!1;_checkpoint_tokens;_visibility;_user_channels;_collection;_start=!1;_preserveRunValues=!1;_interaction;_environment;_model="";_tool_names=[];_data;_mode="start";_scheduledWorkflowConfig;_interactionParamsSchema;_inputValidator;constructor(e,t){this.vertesia=e,this.updateState=t}onStateChanged(){const e=this.clone();this.updateState(e)}clone(){const e=new ac(this.vertesia,this.updateState);return e._interactionParamsSchema=this._interactionParamsSchema,e._interaction=this._interaction,e._data=this._data,e._environment=this._environment,e._model=this._model,e._tool_names=[...this._tool_names],e._interactive=this._interactive,e._debug_mode=this._debug_mode,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._preserveRunValues=this._preserveRunValues,e._mode=this._mode,e._scheduledWorkflowConfig=this._scheduledWorkflowConfig,e}set mode(e){e!==this._mode&&(this._mode=e,this.onStateChanged())}get mode(){return this._mode}set scheduledWorkflowConfig(e){this._scheduledWorkflowConfig=e,this.onStateChanged()}get scheduledWorkflowConfig(){return this._scheduledWorkflowConfig}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 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 search_scope(){return this._collection?cn.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,s=e.config?.model,a=await(r?this.vertesia.environments.retrieve(e.config?.environment):Promise.resolve(void 0));this.interactionParamsSchema=e.interactionParamsSchema??null,this.interaction=n,this._tool_names=e.tool_names||[],this._data=e.data,this._interactive=e.interactive,this._debug_mode=e.debug_mode??!1,this._checkpoint_tokens=e.checkpoint_tokens,this._user_channels=e.user_channels,this.collection=e.collection_id??void 0,this.environment=a,s&&(this._model=s),this.onStateChanged()}get interaction(){return this._interaction}set interaction(e){if(e?.id!==this._interaction?.id){if(this._interaction=e,this.interactionParamsSchema=e?dn(e.prompts):void 0,this._inputValidator=void 0,e&&!this._preserveRunValues&&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&&mn(t,e.provider)?this._model=t:this._model=e?.default_model&&mn(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 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())}get start(){return this._start}get preserveRunValues(){return this._preserveRunValues}set preserveRunValues(e){this._preserveRunValues=e}get interactionParamsSchema(){return this._interactionParamsSchema}set interactionParamsSchema(e){this._interactionParamsSchema!==e&&(this._interactionParamsSchema=e,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._checkpoint_tokens=void 0,this._visibility=void 0,this._user_channels=void 0,this._collection=void 0,this._preserveRunValues=!1,this._model="",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 Vn({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 ic=d(void 0);function oc({children:t}){const{client:n}=Te(),[r,s]=c();return g(()=>{s(new ac(n,s))},[]),r&&e(ic.Provider,{value:r,children:t})}function lc(){const e=m(ic);if(!e)throw new Error("usePayloadBuilder must be used within a PayloadProvider");return e}function cc({title:n,onClose:r,isModal:s,run:a,viewMode:i,onViewModeChange:o,showPlanPanel:l,hasPlan:c=!1,onTogglePlanPanel:d,onDownload:m,onCopyRunId:u,resetWorkflow:p,onExportPdf:h,isReceivingChunks:g=!1,className:f}){return e(oc,{children:t("div",{className:ze("flex flex-wrap items-end justify-between py-1.5 px-2 border-b shadow-sm flex-shrink-0",f),children:[t("div",{className:"flex flex-wrap items-center space-x-2",children:[t("div",{className:"flex items-center space-x-1",children:[e(me,{className:"size-5 text-muted"}),e("span",{className:"font-medium",children:n})]}),t("span",{className:"text-xs text-muted ml-1 flex items-center gap-1.5",children:["(Run ID: ",a.runId.substring(0,8),"...)",e("span",{className:ze("w-2 h-2 rounded-full transition-colors duration-200",g?"bg-purple-500 shadow-[0_0_6px_2px_rgba(168,85,247,0.6)]":"bg-gray-400")})]})]}),t("div",{className:"flex justify-end items-center space-x-2 ml-auto",children:[t("div",{className:"flex items-center space-x-1 bg-muted rounded p-0.5 mt-2 lg:mt-0",children:[e(De,{variant:"stacked"===i?"outline":"ghost",size:"xs",className:"rounded-l-md",onClick:()=>o("stacked"),children:"Details"}),e(De,{variant:"sliding"===i?"outline":"ghost",size:"xs",className:"rounded-r-md",onClick:()=>o("sliding"),children:"Summary"})]}),t("div",{className:"relative",children:[c&&!l&&e("span",{className:"absolute -top-1 -right-1 w-2.5 h-2.5 bg-primary rounded-full border border-border z-10"}),t(De,{size:"sm",variant:l?"primary":"secondary",onClick:d,className:"transition-all duration-200 rounded-md",title:"Toggle plan panel",children:[e(he,{className:"size-4 mr-1.5"}),e("span",{className:"font-medium text-xs",children:l?"Hide Plan":"Show Plan"})]})]}),e(dc,{run:a,isModal:s,onClose:r,onDownload:m,onCopyRunId:u,resetWorkflow:p,onExportPdf:h}),r&&!s&&e(De,{size:"xs",variant:"ghost",onClick:r,children:e(ge,{className:"size-4"})})]})]})})}function dc({run:n,isModal:r,onClose:s,onDownload:a,onCopyRunId:i,resetWorkflow:o,onExportPdf:l}){const c=Ae(),{client:d}=Te(),m=lc();return t(at,{hover:!0,children:[e(it,{children:e(De,{size:"xs",variant:"ghost",title:"More actions",children:e(fe,{className:"size-4"})})}),e(ot,{className:"w-48",align:"end",children:e("div",{className:"rounded-md shadow-lg z-50",children:e("div",{className:"py-1 min-w-36",children:e(At,{children:e(Ht,{children:t(Et,{children:[e("div",{className:"flex items-center px-3 py-1.5 text-xs text-gray-700 dark:text-gray-300",children:e("span",{className:"text-muted",children:"Actions"})}),r&&t($t,{className:"text-xs",onSelect:()=>{return e=`/store/agent-runner?agentId=${n.runId}__${n.workflowId}`,window.open(e,"_blank"),e;var e},children:[e(S,{className:"size-3.5 mr-2 text-muted"})," Open in new tab"]}),t($t,{className:"text-xs",onSelect:()=>{i?i():(navigator.clipboard.writeText(n.runId),c({status:"success",title:"Run ID copied",duration:2e3}))},children:[e(I,{className:"size-3.5 mr-2 text-muted"})," Copy Run ID"]}),t($t,{className:"text-xs",onSelect:()=>{a?a():async function(e,t){return e.files.getDownloadUrl(`agents/${t}/conversation.json`).then(e=>e.url)}(d,n.runId).then(e=>window.open(e,"_blank"))},children:[e(be,{className:"size-3.5 mr-2 text-muted"})," Download Conversation"]}),l&&t($t,{className:"text-xs",onSelect:l,children:[e(be,{className:"size-3.5 mr-2 text-muted"})," Export as PDF"]}),s&&r&&t($t,{className:"text-xs",onSelect:s,children:[e(ge,{className:"size-3.5 mr-2 text-muted"})," Close"]}),t($t,{className:"text-xs text-destructive",onSelect:()=>{(async e=>{try{return await d.store.workflows.terminate(e.workflowId,e.runId,"cancel"),c({status:"success",title:"Workflow cancelled",duration:2e3}),m.reset(),o?.(),!0}catch(e){return c({status:"error",title:"Failed to cancel workflow",duration:2e3}),!1}})(n)},children:[e(ge,{className:"size-3.5 mr-2 text-destructive"})," Cancel Workflow"]})]})})})})})})]})}function mc({onSend:n,onStop:r,disabled:s=!1,isSending:a=!1,isStopping:i=!1,isStreaming:o=!1,isCompleted:l=!1,activeTaskCount:d=0,placeholder:m="Type your message...",onFilesSelected:h,uploadedFiles:f=[],onRemoveFile:b,acceptedFileTypes:y=".pdf,.doc,.docx,.txt,.csv,.xlsx,.xls,.png,.jpg,.jpeg,.gif,.webp",maxFiles:v=5,processingFiles:x,hasProcessingFiles:w=!1,renderDocumentSearch:N,selectedDocuments:k=[],onRemoveDocument:C,hideObjectLinking:S=!1,hideFileUpload:_=!1,className:j}){const I=u(null),P=u(null),[T,z]=c(""),[A,D]=c(!1),[F,E]=c(!1),[$,O]=c(!1);g(()=>{!s&&l&&I.current?.focus()},[s,l]);const R=p(e=>{if(!h)return;const t=Array.from(e),n=v-f.length,r=t.slice(0,n);r.length>0&&h(r)},[h,v,f.length]),L=p(e=>{e.preventDefault(),e.stopPropagation(),h&&O(!0)},[h]),M=p(e=>{e.preventDefault(),e.stopPropagation(),O(!1)},[]),U=p(e=>{e.preventDefault(),e.stopPropagation(),O(!1),e.dataTransfer?.files&&e.dataTransfer.files.length>0&&R(e.dataTransfer.files)},[R]),V=p(e=>{if(!h)return;const t=e.clipboardData?.items;if(!t)return;const n=[];for(let e=0;e<t.length;e++){const r=t[e];if("file"===r.kind){const e=r.getAsFile();if(e)if(!r.type.startsWith("image/")||e.name&&"image.png"!==e.name)n.push(e);else{const t=r.type.split("/")[1]||"png",s=new File([e],`pasted-image-${Date.now()}.${t}`,{type:e.type});n.push(s)}}}n.length>0&&R(n)},[h,R]),W=p(e=>{e.target.files&&e.target.files.length>0&&(R(e.target.files),e.target.value="")},[R]),q=p(()=>{P.current?.click()},[]),B=p(()=>E(!1),[]),H=p(e=>E(!1),[]),G=()=>{const e=T.trim();!e||s||a||(n(e),z(""))},J=()=>{r&&!i&&r()},K=u(0),Y=p(()=>{const e=I.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]);g(()=>{Y()},[T,Y]);const Q=f.length>0||k.length>0||x&&x.size>0;return t("div",{className:ze("p-3 border-t border-muted flex-shrink-0 transition-all fixed lg:sticky bottom-0 left-0 right-0 lg:left-auto lg:right-auto w-full bg-background z-10",$&&"bg-blue-50 dark:bg-blue-900/20 border-blue-400",j),style:{minHeight:"120px"},onDragOver:L,onDragLeave:M,onDrop:U,children:[$&&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(Z,{className:"size-5"}),"Drop files to upload"]})}),h&&e("input",{ref:P,type:"file",multiple:!0,accept:y,onChange:W,className:"hidden"}),Q&&!_&&t("div",{className:"flex flex-col gap-2 mb-3",children:[(f.length>0||x&&x.size>0)&&t("div",{children:[t("div",{className:"flex items-center gap-1 mb-1",children:[e("span",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:"Uploaded Files"}),e(Ee,{description:"Files uploaded to this conversation remain available throughout. The agent can access them anytime.",placement:"top",size:"md",children:e(ye,{className:"size-3 text-gray-400 dark:text-gray-500"})})]}),t("div",{className:"flex flex-wrap gap-2",children:[x&&Array.from(x.values()).map(n=>t("div",{className:ze("flex items-center gap-1.5 px-2 py-1 rounded-md text-sm",n.status===un.ERROR?"bg-destructive/10 text-destructive":n.status===un.READY?"bg-success/10 text-success":"bg-attention/10 text-attention"),children:[e(ve,{className:ze("size-3.5",(n.status===un.UPLOADING||n.status===un.PROCESSING)&&"animate-pulse")}),e("span",{className:"max-w-[120px] truncate",children:n.name}),e("span",{className:"text-xs opacity-70",children:n.status===un.UPLOADING?"Uploading...":n.status===un.PROCESSING?"Processing...":n.status===un.ERROR?"Error":n.status===un.READY?"Ready":n.status})]},n.id)),f.map(n=>t("div",{className:"flex items-center gap-1.5 px-2 py-1 bg-success/10 text-success rounded-md text-sm",children:[e(ve,{className:"size-3.5"}),e("span",{className:"max-w-[120px] truncate",children:n.name}),b&&e("button",{onClick:()=>b(n.id),className:"ml-1 p-0.5 hover:bg-success/20 rounded",children:e(ge,{className:"size-3"})})]},n.id))]})]}),k.length>0&&t("div",{children:[t("div",{className:"flex items-center gap-1 mb-1",children:[e("span",{className:"text-xs font-medium text-blue-600 dark:text-blue-400",children:"Document Attachments"}),e(Ee,{description:"Documents from the store attached to this message. The agent can re-fetch them by ID anytime, or re-attach to include content directly.",placement:"top",size:"md",children:e(ye,{className:"size-3 text-blue-400 dark:text-blue-500"})})]}),e("div",{className:"flex flex-wrap gap-2",children:k.map(n=>t("div",{className:"flex items-center gap-1.5 px-2 py-1 bg-blue-100 dark:bg-blue-900/30 rounded-md text-sm text-blue-700 dark:text-blue-300",children:[e(ve,{className:"size-3.5"}),e("span",{className:"max-w-[120px] truncate",children:n.name}),C&&e("button",{onClick:()=>C(n.id),className:"ml-1 p-0.5 hover:bg-blue-200 dark:hover:bg-blue-800 rounded",children:e(ge,{className:"size-3"})})]},n.id))})]})]}),(h||N)&&t("div",{className:"flex gap-2 mb-2",children:[h&&t(De,{variant:"outline",size:"sm",onClick:q,disabled:s||f.length>=v,className:"text-xs",children:[e(Z,{className:"size-3.5 mr-1.5"}),"Upload"]}),N&&t(De,{variant:"outline",size:"sm",onClick:()=>E(!0),disabled:s,className:"text-xs",children:[e(ve,{className:"size-3.5 mr-1.5"}),"Search Documents"]})]}),t("div",{className:"flex items-end space-x-2",children:[t("div",{className:"flex flex-1 items-end space-x-1",children:[e(Ct,{ref:I,value:T,onKeyDown:e=>{if("Enter"===e.key&&!e.shiftKey){e.preventDefault();T.trim().length>0&&G()}if("Escape"===e.key&&o&&r){const e=Date.now();e-K.current<500?(J(),K.current=0):K.current=e}},onChange:e=>z(e.target.value),onPaste:V,disabled:s,placeholder:o?"Agent is working... (Esc Esc to stop)":h?"Ask anything... (drop or paste files)":m,rows:2,style:{minHeight:"60px",maxHeight:"200px"}}),!S&&e(De,{variant:"ghost",className:"rounded-full",disabled:!l,onClick:()=>D(!0),alt:"Link Object",children:e(xe,{className:"size-4"})})]}),o&&r&&!T.trim()?t(De,{onClick:J,disabled:i,className:"px-4 py-2.5 bg-red-600 hover:bg-red-700 text-white",title:"Stop the agent",children:[i?e(Ue,{size:"sm",className:"mr-2"}):e(we,{className:"size-4 mr-2"})," ",e("span",{children:"Stop"})]}):t(De,{onClick:G,disabled:s||a||!T.trim()||w,className:"px-4 py-2.5",title:w?"Wait for files to finish processing":void 0,children:[a?e(Ue,{size:"sm",className:"mr-2"}):e(Ne,{className:"size-4 mr-2"}),e("span",{children:w?"Processing...":"Send"})]})]}),e("div",{className:"text-xs text-muted mt-2 text-center",children:d>0?t("div",{className:"flex items-center justify-center",children:[e(ke,{className:"h-3 w-3 mr-1 text-attention"}),t("span",{children:["Agent has ",d," active workstream",1!==d?"s":""," running"]})]}):o?"Agent is working... Press Esc twice or click Stop to interrupt":s?"Agent is processing, you can continue once it completes...":"Enter to send • Shift+Enter for new line"}),t(Ve,{isOpen:A,onClose:()=>D(!1),className:"min-w-[60vw]",children:[e(We,{children:"Link Object"}),e(qe,{className:"pb-6",children:e(co,{onChange:e=>{const t=`[${e.properties?.title||e.name||"Object"}](store:${e.id})`,n=T||"",r=I.current?.selectionStart||n.length,s=n.substring(0,r)+t+n.substring(r);z(s),D(!1),setTimeout(()=>{if(I.current){I.current.focus();const e=r+t.length;I.current.setSelectionRange(e,e)}},100)}})})]}),N?.({isOpen:F,onClose:B,onSelect:H})]})}const uc=o.memo(function({plan:r,workstreamStatus:s,isOpen:a,onClose:i,plans:o=[],activePlanIndex:l=0,onChangePlan:c=()=>{}}){return a?t("div",{className:"h-full shadow-xl border border-muted/20 overflow-hidden",children:[t("div",{className:"flex items-center justify-between p-3 border-b border-muted/20",children:[e("h3",{className:"font-bold text-base",children:"Plan"}),t(De,{variant:"ghost",onClick:i,children:[e(C,{className:"size-4"}),e("span",{className:"sr-only",children:"Close"})]})]}),t("div",{className:"p-3 overflow-y-auto",style:{height:"calc(100% - 44px)",maxHeight:"calc(100vh - 150px)"},children:[t("div",{className:"mb-3 p-2 bg-info rounded-md border border-info",children:[e("div",{className:"text-xs font-medium text-info mb-1",children:"Task Progress"}),e("div",{className:"flex items-center gap-2",children:(()=>{const a=r.plan||[],i=a.length;let o=0;i>0&&a.forEach(e=>{if(e&&e.id){const t=e.id.toString();"completed"===s.get(t)&&o++}});const l=i>0?Math.round(o/i*100):0;return t(n,{children:[e("div",{className:"w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2.5",children:e("div",{className:"bg-info h-2.5 rounded-full transition-all duration-300",style:{width:`${l}%`}})}),e("span",{className:"text-xs text-foreground font-medium whitespace-nowrap",children:i>0?`${o}/${i}`:"0/0"})]})})()})]}),o.length>1&&t("div",{className:"mb-3 flex items-center justify-between",children:[e(De,{variant:"ghost",onClick:()=>c(Math.min(o.length-1,l+1)),disabled:l>=o.length-1,children:"Older Plan"}),e("div",{className:"text-xs text-muted",children:o[l]?.timestamp?new Date(o[l].timestamp).toLocaleTimeString():"Unknown time"}),e(De,{variant:"ghost",onClick:()=>c(Math.max(0,l-1)),disabled:l<=0,children:"Newer Plan"})]}),t("div",{className:"rounded-md border border-muted/30",children:[e("div",{className:"p-2 border-b border-muted/30 bg-muted",children:e("div",{className:"font-medium text-xs",children:"Step-by-Step Plan"})}),e("div",{className:"divide-y divide-muted/20 max-h-[calc(100vh-350px)] overflow-y-auto",children:r.plan&&r.plan.length>0?r.plan.map((n,r)=>{const a=n.id?n.id.toString():`task-${r}`,i=n.goal||`Task ${r+1}`;let o=n.status||"pending";s.has(a)&&(o=s.get(a));let l=Ce,c="text-muted";return"in_progress"===o?(l=pe,c="text-info"):"completed"===o&&(l=P,c="text-success"),t("div",{className:"flex p-3 my-1",children:[e("div",{className:"mr-2 mt-0.5 flex-shrink-0 text-muted",children:a}),t("div",{className:"w-full",children:[e("div",{className:"text-sm font-medium mb-2 text-muted",children:i}),t("div",{className:"mt-1 flex justify-end items-center",children:[e("div",{className:`mr-2 mt-0.5 flex-shrink-0 ${c}`,children:e(l,{className:"size-3.5"})}),e(lt,{variant:"completed"===o?"success":"in_progress"===o?"info":"default",children:"completed"===o?"Completed":"in_progress"===o?"In Progress":"Pending"})]})]})]},r)}):t("div",{className:"p-3 text-center text-muted italic",children:[e(T,{className:"size-4 mx-auto mb-2 text-attention"}),e("p",{className:"text-xs",children:"No plan has been detected yet"}),e("p",{className:"text-xs mt-1",children:"Plans will appear here when the agent creates one"})]})})]}),(()=>{const n=new Set((r.plan||[]).filter(e=>e&&e.id).map(e=>e.id.toString())),a=Array.from(s.entries()).filter(([e])=>"main"!==e&&!n.has(e));return a.length>0?t("div",{className:"mt-3 rounded-md border border-gray-200 dark:border-gray-800",children:[e("div",{className:"p-2 border-b border-gray-200 dark:border-gray-800 bg-gray-50 dark:bg-gray-900/50",children:e("div",{className:"font-medium text-xs",children:"Workstreams"})}),e("div",{className:"p-3",children:e("div",{className:"grid grid-cols-1 gap-2",children:a.map(([n,r])=>{let s=Ce,a="text-gray-400",i="bg-gray-100 dark:bg-gray-800",o="Pending";return"in_progress"===r?(s=pe,a="text-info",i="bg-info/20",o="In Progress"):"completed"===r&&(s=P,a="text-success",i="bg-success/20",o="Completed"),t("div",{className:ze("flex items-center p-1.5 rounded",i),children:[e("div",{className:`mr-1.5 ${a}`,children:e(s,{className:"h-3.5 w-3.5"})}),e("div",{className:"flex-1",children:e("span",{className:"text-xs font-medium text-gray-800 dark:text-gray-300",children:n})}),e("span",{className:"text-xs font-medium",children:o})]},n)})})})]}):null})()]})]}):null}),pc=h(function({code:t}){const n=l(()=>{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(br,{spec:n}):null}),hc=h(function({code:t}){const n=l(()=>{try{return{library:"vega-lite",spec:JSON.parse(t)}}catch{return null}},[t]);return n?e(br,{spec:n}):null}),gc={chart:pc,"vega-lite":hc,vegalite:hc,"fusion-fragment":hn};function fc({url:t,code:n}){const[r,s]=c(null);return g(()=>{import(t).then(e=>{s(()=>e.default)}).catch(e=>{console.error("Failed to load remote widget component from ",t,e)})},[t]),r?e(r,{code:n}):null}function bc({children:t}){const{client:n}=Te(),[r,s]=c(gc);return g(()=>{(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=pn(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 s=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,s]of Object.entries(r))n.push({name:t,component:t=>e(fc,{url:s.url,code:t.code})});return n}).catch(()=>(console.error("Failed to fetch skill widgets from ",t),null)))),a={};for(const e of s.flat())e&&(a[e.name]=e.component);return a})(n).then(e=>{s({...gc,...e})})},[]),e(An,{components:r,children:t})}function yc({documents:n,activeId:r,onSelect:s,onClose:a}){return 0===n.length?null:e("div",{className:"flex items-center gap-1 overflow-x-auto px-2 py-1.5 border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50",children:n.map(n=>{const i=n.id===r;return t("button",{onClick:()=>s(n.id),className:ze("group flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-md transition-colors whitespace-nowrap max-w-[200px]",i?"bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 shadow-sm":"text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700/50"),children:[e("span",{className:"truncate",children:n.title}),e("span",{role:"button",onClick:e=>{e.stopPropagation(),a(n.id)},className:ze("shrink-0 p-0.5 rounded hover:bg-gray-200 dark:hover:bg-gray-600",i?"opacity-60 hover:opacity-100":"opacity-0 group-hover:opacity-60 hover:!opacity-100"),children:e(ge,{className:"size-3"})})]},n.id)})})}const vc=o.memo(function({isOpen:n,onClose:r,documents:s,activeDocumentId:a,onSelectDocument:i,onCloseDocument:o,refreshKey:l,runId:d}){const{client:m}=Te(),[u,h]=c(null),[f,b]=c(!1),[y,v]=c(null),[x,w]=c(null),N=p(async e=>{b(!0),v(null);try{const[t,n]=await Promise.all([m.store.objects.getObjectText(e),m.store.objects.retrieve(e)]);h(t.text),w(n.name)}catch(e){const t=e instanceof Error?e.message:"Failed to load document";v(t),h(null)}finally{b(!1)}},[m]);return g(()=>{a&&n&&N(a)},[a,l,n,N]),n&&0!==s.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(ve,{className:"size-4 text-muted shrink-0"}),e("h3",{className:"font-bold text-sm truncate",children:x||"Document"})]}),t(De,{variant:"ghost",size:"sm",onClick:r,children:[e(C,{className:"size-4"}),e("span",{className:"sr-only",children:"Close"})]})]}),e("div",{className:"shrink-0",children:e(yc,{documents:s,activeId:a,onSelect:i,onClose:o})}),e("div",{className:"flex-1 overflow-y-auto px-4 py-4",children:f?t("div",{className:"flex items-center justify-center py-12",children:[e(Se,{className:"size-5 animate-spin text-muted"}),e("span",{className:"ml-2 text-sm text-muted",children:"Loading document..."})]}):y?e("div",{className:"p-4 rounded-md bg-destructive/10 text-destructive text-sm",children:y}):u?e("div",{className:"prose prose-sm dark:prose-invert max-w-none",children:e(vn,{artifactRunId:d,children:u})}):t("div",{className:"flex flex-col items-center justify-center py-12 text-muted",children:[e(ve,{className:"size-8 mb-2"}),e("span",{className:"text-sm",children:"No content available"})]})})]}):null});function xc(e,t){const[n,r]=c([]),[s,a]=c(!1),[i,o]=c(null),[l,d]=c(new Map),[m,h]=c(new Map),f=u(new Map),b=u(null),[y,v]=c(!1),x=u(null),w=p(()=>{f.current.size>0&&(h(new Map(f.current)),v(!0),x.current&&clearTimeout(x.current),x.current=setTimeout(()=>v(!1),50)),b.current=null},[]);g(()=>{a(!function(e){if(!e.length)return!0;const t=new Map;if(e.forEach(e=>{const n=Lr(e);t.has(n)||t.set(n,[]),t.get(n).push(e)}),console.log("[isInProgress] Workstreams found:",Array.from(t.keys())),1===t.size&&!t.has("main")){const e=t.keys().next().value||"unknown";console.log(`[isInProgress] Only one workstream found (${e}), treating as main`);const n=t.get(e),r=n[n.length-1];return console.log(`[isInProgress] Last message type in only workstream: ${r.type}`),Rr.includes(r.type)?(console.log("[isInProgress] Only workstream is completed"),!1):(console.log("[isInProgress] Only workstream is still in progress"),!0)}if(t.has("main")){const e=t.get("main");if(0===e.length)return console.log("[isInProgress] Main workstream exists but has no messages, still in progress"),!0;const n=e[e.length-1];return console.log(`[isInProgress] Last message type in main workstream: ${n.type}`),Rr.includes(n.type)?(console.log("[isInProgress] Main workstream is completed"),!1):(console.log("[isInProgress] Main workstream is still in progress"),!0)}console.log("[isInProgress] Multiple workstreams but no main, checking if any are still active");for(const[e,n]of t.entries())if(n.length>0){const t=n[n.length-1];if(!Rr.includes(t.type))return console.log(`[isInProgress] Workstream ${e} is still active`),!0}return console.log("[isInProgress] All workstreams are completed"),!1}(n))},[n]),g(()=>(r([]),o(null),h(new Map),d(new Map),e.store.workflows.getRunDetails(t.runId,t.workflowId).then(e=>{o(e.status)}).catch(e=>{console.error("Failed to check workflow status:",e)}),e.store.workflows.streamMessages(t.workflowId,t.runId,e=>{if(e.type===Jt.STREAMING_CHUNK){const t=e.details,n=t?.activity_id||t?.streaming_id;if(!n)return;const r=f.current.get(n)||{text:"",workstreamId:e.workstream_id,startTimestamp:Date.now(),activityId:t?.activity_id},s=r.text+(e.message||"");return f.current.set(n,{text:s,workstreamId:e.workstream_id,isComplete:t.is_final,startTimestamp:r.startTimestamp,activityId:t?.activity_id}),void(null===b.current&&(b.current=requestAnimationFrame(w)))}if(e.type===Jt.SYSTEM){const t=e.details;if("file_processing"===t?.system_type&&t.files)return void d(e=>{const n=new Map(e);for(const e of t.files)n.set(e.id,e);return n})}if((e.type===Jt.THOUGHT||e.type===Jt.ANSWER)&&e.details?.activity_id){const t=e.details.activity_id;f.current.delete(t),h(e=>{if(e.has(t)){const n=new Map(e);return n.delete(t),n}return e})}e.type!==Jt.COMPLETE&&e.type!==Jt.IDLE||f.current.size>0&&w(),e.message&&r(t=>{if(t.find(t=>t.timestamp===e.timestamp))return t;if(e.type===Jt.QUESTION&&!e.details?._optimistic){const n=t.filter(e=>!(e.type===Jt.QUESTION&&e.details?._optimistic));return Or(n,e),[...n]}return Or(t,e),[...t]})}),()=>{r([]),null!==b.current&&(cancelAnimationFrame(b.current),b.current=null),f.current.clear()}),[t.runId,e.store.workflows,w]);const N=p(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})},[]),k=p(e=>{r(t=>t.filter(t=>!e(t)))},[]);return{messages:n,streamingMessages:m,isCompleted:s,debugChunkFlash:y,addOptimisticMessage:N,removeOptimisticMessages:k,workflowStatus:i,serverFileUpdates:l}}function wc(t){const{run:n,startWorkflow:r}=t;if(n){const r="runId"in n?n:{runId:n.run_id,workflowId:n.workflow_id};return e(bc,{children:e(Cc,{...t,run:r})})}return r?e(kc,{...t}):e(Nc,{})}function Nc(){return t(ft,{status:"info",icon:e(me,{className:"size-16 text-muted mb-4"}),children:[e("div",{className:"text-base font-medium text-muted",children:"No agent currently running"}),e("div",{className:"mt-3 text-sm text-muted",children:"Select an interaction and click Start to start an agent"})]})}function kc({initialMessage:n,startWorkflow:r,onClose:s,isModal:a=!1,fullWidth:i=!1,placeholder:o="Type your message...",startButtonText:l="Start Agent",title:d="Start New Conversation",getAttachedDocs:m,onAttachmentsSent:h,acceptedFileTypes:f=".pdf,.doc,.docx,.txt,.csv,.xlsx,.xls,.png,.jpg,.jpeg,.gif,.webp",maxFiles:b=5}){const{client:y}=Te(),[v,x]=c(""),[w,N]=c(!1),[k,C]=c(),S=Ae(),_=u(null),j=u(null),[I,P]=c([]),[T,z]=c(!1),A=u(0),D=p(e=>{e.preventDefault(),e.stopPropagation(),A.current++,e.dataTransfer?.types?.includes("Files")&&z(!0)},[]),F=p(e=>{e.preventDefault(),e.stopPropagation()},[]),E=p(e=>{e.preventDefault(),e.stopPropagation(),A.current--,0===A.current&&z(!1)},[]),$=p(e=>{if(e.preventDefault(),e.stopPropagation(),A.current=0,z(!1),e.dataTransfer?.files&&e.dataTransfer.files.length>0){const t=Array.from(e.dataTransfer.files);P(e=>[...e,...t].slice(0,b))}},[b]),O=p(e=>{if(e.target.files&&e.target.files.length>0){const t=Array.from(e.target.files);P(e=>[...e,...t].slice(0,b))}e.target.value=""},[b]),R=p(e=>{P(t=>t.filter((t,n)=>n!==e))},[]);g(()=>{_.current&&_.current.focus()},[]);const L=async()=>{if(!r)return;const e=v.trim();if(e&&!w){N(!0);try{sessionStorage.removeItem("plan-panel-shown"),S({title:I.length>0?"Starting agent and uploading files...":"Starting agent...",status:"info",duration:3e3});const t=m?.()||[];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.length>0){const e=I.map(e=>e.name).join(", ");n=[n,"",`[System: ${I.length} file(s) are being uploaded: ${e}. Please wait for the "Files Ready" notification before processing them.]`].join("\n")}const s=await r(n);if(s){const e=[];if(I.length>0){for(const t of I)try{const n=`files/${t.name}`;await y.files.uploadArtifact(s.run_id,n,t),await y.store.workflows.sendSignal(s.workflow_id,s.run_id,"FileUploaded",{id:`file-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,name:t.name,content_type:t.type||"application/octet-stream",reference:`artifact:${n}`,artifact_path:n}),e.push(t.name)}catch(e){console.error(`Failed to upload staged file ${t.name}:`,e)}if(e.length>0)try{await y.store.workflows.sendSignal(s.workflow_id,s.run_id,"UserInput",{message:`[Files Ready] All ${e.length} file(s) have been uploaded and are now available: ${e.join(", ")}. You can now process them.`,metadata:{type:"files_ready",files:e}})}catch(e){console.error("Failed to send files ready signal:",e)}P([])}h?.(),C({runId:s.run_id,workflowId:s.workflow_id}),x(""),S({title:"Agent started",status:"success",duration:3e3})}}catch(e){S({title:"Error starting workflow",status:"error",duration:3e3,description:e instanceof Error?e.message:"Unknown error"})}finally{N(!1)}}},M=p(()=>{const e=_.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]);return g(()=>{M()},[v,M]),k?e(Cc,{onClose:s,isModal:a,initialMessage:n,placeholder:o,run:k,title:d}):t("div",{className:"flex flex-col h-full bg-white dark:bg-gray-900 overflow-hidden border-0 relative "+(T?"ring-2 ring-blue-400 ring-inset":""),onDragEnter:D,onDragOver:F,onDragLeave:E,onDrop:$,children:[T&&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(Z,{className:"size-6"}),"Drop files to stage for upload"]})}),e("input",{ref:j,type:"file",multiple:!0,accept:f,onChange:O,className:"hidden"}),t("div",{className:"flex items-center justify-between py-2 px-3 border-b border-gray-100 dark:border-gray-800 bg-white dark:bg-gray-900",children:[t("div",{className:"flex items-center space-x-2",children:[e("div",{className:"p-1",children:e(_e,{className:"size-3.5 text-muted"})}),e("span",{className:"font-medium text-sm text-gray-700 dark:text-gray-300",children:d})]}),s&&!a&&e(De,{size:"xs",variant:"ghost",onClick:s,title:"Close",className:"text-slate-500 hover:text-slate-700",children:e(ge,{className:"size-4"})})]}),t("div",{className:"flex-1 overflow-y-auto px-4 py-6 bg-white dark:bg-gray-900 flex flex-col "+(i?"items-start justify-start":"items-center justify-center"),children:[n&&e("div",{className:"px-4 py-3 mb-4 bg-blue-50/80 dark:bg-blue-900/30 border-l-2 border-blue-400 dark:border-blue-500 text-blue-700 dark:text-blue-300 "+(i?"w-full":"max-w-md"),children:n}),t("div",{className:"bg-white dark:bg-slate-800 p-4 border-l-2 border-blue-400 dark:border-blue-500 "+(i?"w-full":"max-w-md"),children:[e("div",{className:"text-base text-slate-600 dark:text-slate-300 font-medium",children:"Enter a message to start a conversation"}),t("div",{className:"mt-3 text-sm text-slate-500 dark:text-slate-400",children:["Type your question below and press Enter or click ",l," ","to begin"]})]})]}),t("div",{className:"py-3 px-3 border-t border-gray-100 dark:border-gray-800 bg-white dark:bg-gray-900",children:[I.length>0&&e("div",{className:"flex flex-wrap gap-2 mb-3",children:I.map((n,r)=>t("div",{className:"flex items-center gap-1.5 px-2 py-1 bg-attention/10 text-attention rounded-md text-sm",children:[e(ve,{className:"size-3.5"}),e("span",{className:"max-w-[120px] truncate",children:n.name}),e("span",{className:"text-xs opacity-70",children:"Staged"}),e("button",{onClick:()=>R(r),className:"ml-1 p-0.5 hover:bg-attention/20 rounded",children:e(ge,{className:"size-3"})})]},`${n.name}-${r}`))}),e("div",{className:"flex gap-2 mb-2",children:t(De,{variant:"outline",size:"sm",onClick:()=>j.current?.click(),disabled:w||I.length>=b,className:"text-xs",children:[e(Z,{className:"size-3.5 mr-1.5"}),"Upload"]})}),t("div",{className:"flex items-end gap-2",children:[e("div",{className:"flex-1",children:e("textarea",{ref:_,value:v,onChange:e=>x(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),L())},placeholder:o,disabled:w,rows:2,className:"w-full py-2.5 px-3 text-sm border border-gray-200 dark:border-gray-700 dark:bg-gray-800 dark:text-white focus:border-gray-300 dark:focus:border-gray-600 focus:outline-none focus:ring-1 focus:ring-gray-300 dark:focus:ring-gray-600 rounded-md resize-none overflow-hidden",style:{minHeight:"60px",maxHeight:"200px"}})}),t(De,{onClick:L,disabled:!v.trim()||w,className:"px-3 py-2.5 bg-gray-800 dark:bg-gray-700 hover:bg-gray-700 dark:hover:bg-gray-600 text-white text-xs rounded-md transition-colors",children:[w?e(Ue,{size:"sm",className:"mr-1.5"}):e(Ne,{className:"size-3.5 mr-1.5"}),l]})]}),e("div",{className:"text-xs text-gray-400 dark:text-gray-500 mt-2 text-center",children:I.length>0?`${I.length} file${I.length>1?"s":""} staged - will upload when conversation starts`:"Enter to send • Shift+Enter for new line"})]})]})}function Cc({run:n,title:r,interactive:s=!0,onClose:a,isModal:i=!1,fullWidth:o=!1,placeholder:d="Type your message...",resetWorkflow:m,uploadedFiles:h,onRemoveFile:f,acceptedFileTypes:b,maxFiles:y,renderDocumentSearch:v,selectedDocuments:x,onRemoveDocument:w,hideObjectLinking:N,hideHeader:k,hideMessageInput:C,hidePlanPanel:S,hideWorkstreamTabs:_,hideFileUpload:j,hideDocumentPanel:I,getAttachedDocs:P,onAttachmentsSent:T,isUploading:z=!1,getMessageContext:A,className:D,inputContainerClassName:F,inputClassName:E,fusionData:$,fileUploadRef:O,onProcessingFilesChange:R,onPlansChange:L,onWorkstreamStatusChange:M,viewMode:U,onViewModeChange:V,onShowInputChange:W,stopRef:q,onStoppingChange:B,messageItemClassNames:H,messageStyleOverrides:G,toolCallGroupClassNames:J,hideToolCallsInViewMode:K,streamingMessageClassNames:Y,batchProgressPanelClassNames:Q,workingIndicatorClassName:X,messageListClassName:ee,StoreLinkComponent:te,CollectionLinkComponent:ne,prependFriendlyMessage:re}){const{client:se}=Te(),ae=Ae(),{messages:ie,streamingMessages:oe,isCompleted:le,debugChunkFlash:ce,addOptimisticMessage:de,removeOptimisticMessages:me,workflowStatus:ue,serverFileUpdates:pe}=xc(se,n),{plans:he,activePlanIndex:ge,setActivePlanIndex:fe,workstreamStatusMap:be,showInput:ye,showSlidingPanel:ve,setShowSlidingPanel:xe}=function(e,t,n=!1){const[r,s]=c([]),[a,i]=c(0),[o,l]=c(new Map),[d,m]=c(t),[h,f]=c(!n),b=u(-1),y=u(new Set);g(()=>{0===e.length&&(s([]),i(0),l(new Map),f(!1),b.current=-1,y.current.clear())},[0===e.length]),g(()=>{if(0===e.length)return;const t=b.current+1;if(t>=e.length)return void v(e);let n=!1;const r=[],a=[];for(let s=t;s<e.length;s++){const t=e[s];if(t.type===Jt.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 s="number"==typeof t.timestamp?t.timestamp:new Date(t.timestamp).getTime();if(!y.current.has(s)){y.current.add(s),n=!0,r.push({plan:e,timestamp:s});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")}}),a.push({timestamp:s,statusMap:t})}}}catch(e){console.error("Failed to parse plan from message:",e)}}b.current=e.length-1,n&&r.length>0&&(s(e=>[...[...r].reverse(),...e]),i(0),f(!0),a.length>0&&l(e=>{const t=new Map(e);for(const e of a)t.set(e.timestamp,e.statusMap);return t})),v(e)},[e,t]),g(()=>{if(1===r.length&&!h&&!sessionStorage.getItem("plan-panel-shown")){const e=setTimeout(()=>{f(!0),sessionStorage.setItem("plan-panel-shown","true")},500);return()=>clearTimeout(e)}},[r.length,h]),g(()=>{0===r.length&&f(!1)},[r.length]);const v=p(e=>{const n=e[e.length-1];n&&(n.type===Jt.TERMINATED?m(!1):m(!!t||n.type===Jt.REQUEST_INPUT))},[t]);return{plans:r,activePlanIndex:a,setActivePlanIndex:i,workstreamStatusMap:o,showInput:d,showSlidingPanel:h,setShowSlidingPanel:f}}(ie,s,i),{openDocuments:we,activeDocumentId:Ne,isDocPanelOpen:ke,docRefreshKey:Ce,closeDocPanel:Se,closeDocument:_e,selectDocument:je,openDocInPanel:Ie}=function(e){const[t,n]=c([]),[r,s]=c(null),[a,i]=c(!1),[o,l]=c(0),d=u(-1);return g(()=>{0===e.length&&(n([]),s(null),i(!1),l(0),d.current=-1)},[0===e.length]),g(()=>{const t=d.current+1;if(!(t>=e.length)){for(let r=t;r<e.length;r++){const t=e[r];if(t.type===Jt.UPDATE&&t.details){const e=t.details;if("document_created"===e.event_class||"document_updated"===e.event_class){const t=e.document_id,r=e.title;t&&(n(e=>e.some(e=>e.id===t)?e:[...e,{id:t,title:r||"Document"}]),s(t),i(!0),"document_updated"===e.event_class&&l(e=>e+1))}}}d.current=e.length-1}},[e]),{openDocuments:t,activeDocumentId:r,isDocPanelOpen:a,docRefreshKey:o,closeDocPanel:p(()=>{i(!1)},[]),closeDocument:p(e=>{n(t=>{const n=t.filter(t=>t.id!==e);return 0===n.length?(i(!1),s(null)):s(t=>t===e?n[0].id:t),n})},[]),selectDocument:p(e=>{s(e)},[]),openDocInPanel:p(e=>{n(t=>t.some(t=>t.id===e)?t:[...t,{id:e,title:"Document"}]),s(e),i(!0)},[])}}(ie),{processingFiles:Pe,hasProcessingFiles:Fe,handleFileUpload:Ee}=function(e,t,n,r){const[s,a]=c(new Map);g(()=>{a(new Map)},[t.runId]);const i=l(()=>{const e=new Map(s);return n.forEach((t,n)=>{e.set(n,t)}),e},[s,n]),o=l(()=>Array.from(i.values()).some(e=>e.status===un.UPLOADING||e.status===un.PROCESSING),[i]),d=p(async n=>{for(const s of n){const n=`file-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,i=`files/${s.name}`,o={id:n,name:s.name,content_type:s.type||"application/octet-stream",size:s.size,status:un.UPLOADING,started_at:Date.now()};a(e=>new Map(e).set(n,o));try{await e.files.uploadArtifact(t.runId,i,s),a(e=>{const t=new Map(e),r=t.get(n);return r&&(r.status=un.PROCESSING,r.artifact_path=i,r.reference=`artifact:${i}`),t}),await e.store.workflows.sendSignal(t.workflowId,t.runId,"FileUploaded",{id:n,name:s.name,content_type:s.type||"application/octet-stream",reference:`artifact:${i}`,artifact_path:i})}catch(e){a(t=>{const r=new Map(t),s=r.get(n);return s&&(s.status=un.ERROR,s.error=e instanceof Error?e.message:"Upload failed",s.completed_at=Date.now()),r}),r({status:"error",title:"Upload Failed",description:e instanceof Error?e.message:"Failed to upload file",duration:3e3})}}},[e,t,r]);return{processingFiles:i,hasProcessingFiles:o,handleFileUpload:d}}(se,n,pe,ae),$e=u(null),Oe=u(null),[Re,Le]=c(!1),[Me,Ue]=c("sliding"),Be=U??Me,He=p(e=>{V?V(e):Ue(e)},[V]),[Ge,Ke]=c(!1),[Ye,Ze]=c(0),[Qe,Xe]=c(!1),et=u(0),tt=u(Re);tt.current=Re;const nt=u(Fe);nt.current=Fe;const rt=l(()=>{const e=ie[ie.length-1];return e?.type===Jt.TERMINATED?"TERMINATED":ue},[ie,ue]),st=l(()=>{const e=he[ge]||{plan:{plan:[]},timestamp:0},t=be.get(e.timestamp)||new Map;return{plan:e.plan,workstreamStatus:t}},[he,ge,be]),at=p(()=>{xe(e=>(e||sessionStorage.setItem("plan-panel-shown","true"),!e))},[xe]),it=p(e=>{fe(e)},[fe]),ot=p(()=>{xe(!1)},[xe]),lt=p(({documentId:t,children:n})=>e("button",{className:"text-info underline cursor-pointer hover:text-info/80",onClick:()=>Ie(t),children:n}),[Ie]),ct=te??lt;g(()=>{if(!le){const e=setInterval(()=>{Ze(()=>Math.floor(Math.random()*($r.length-1)))},4e3);return()=>clearInterval(e)}},[le]),g(()=>(O&&(O.current=Ee),()=>{O&&(O.current=null)}),[O,Ee]),g(()=>{R?.(Pe)},[Pe,R]),g(()=>{L?.(he,ge)},[he,ge,L]),g(()=>{M?.(be)},[be,M]),g(()=>{0!==ie.length&&(ye?rt&&"RUNNING"!==rt?W?.(!1):null!==rt&&W?.(!0):W?.(!1))},[ye,rt,ie.length,W]);const dt=p(e=>{const t=e.trim();if(!t||tt.current)return;if(nt.current)return void ae({status:"warning",title:"Files Still Processing",description:"Please wait for all files to finish processing before sending",duration:3e3});Le(!0);const r=P?.()||[],s=A?.()||{};let a=t;if(r.length>0&&!/store:\S+/.test(t)){a=[t,"","Attachments:",...r.map(e=>`[${e.name}](/store/objects/${e.id})`)].join("\n")}const i=`msg-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,o={timestamp:Date.now(),workflow_run_id:n.runId,type:Jt.QUESTION,message:a,workstream_id:"main",details:{_optimistic:!0,_messageId:i}};de(o);const l={...r.length>0?{attached_docs:r.map(e=>e.id)}:{},...s,_messageId:i};se.store.workflows.sendSignal(n.workflowId,n.runId,"UserInput",{message:a,metadata:l}).then(()=>{T?.()}).catch(e=>{me(e=>e.details?._messageId===i),ae({status:"error",title:"Failed to Send Message",description:e instanceof Error?e.message:"Unknown error",duration:3e3})}).finally(()=>{Le(!1)})},[n.runId,n.workflowId,se,ae,P,A,T,de,me]),mt=p(e=>{e.preventDefault(),e.stopPropagation(),et.current++,n&&e.dataTransfer?.types?.includes("Files")&&Xe(!0)},[n]),ut=p(e=>{e.preventDefault(),e.stopPropagation()},[]),pt=p(e=>{e.preventDefault(),e.stopPropagation(),et.current--,0===et.current&&Xe(!1)},[]),ht=p(e=>{if(e.preventDefault(),e.stopPropagation(),et.current=0,Xe(!1),n&&e.dataTransfer?.files&&e.dataTransfer.files.length>0){const t=Array.from(e.dataTransfer.files);Ee(t)}},[n,Ee]),gt=p(async()=>{if(!Ge){Ke(!0);try{await se.store.workflows.sendSignal(n.workflowId,n.runId,"Stop",{message:"User requested stop"}),ae({status:"info",title:"Agent Interrupted",description:"Type your message to give new instructions",duration:3e3})}catch(e){ae({status:"error",title:"Failed to Interrupt",description:e instanceof Error?e.message:"Unknown error",duration:3e3})}finally{Ke(!1)}}},[Ge,se,n.workflowId,n.runId,ae]);g(()=>(q&&(q.current=le?null:gt),()=>{q&&(q.current=null)}),[q,le,gt]),g(()=>{B?.(Ge)},[Ge,B]);const bt=r||n.workflowId.split(":")[2]||"Agent Conversation",[yt,vt]=c(!1),xt=l(()=>st.plan.plan?.reduce((e,t)=>(t.id&&t.goal&&e.set(t.id.toString(),t.goal),e),new Map),[st.plan]),wt=e(or,{children:e(Tr,{children:t("div",{className:ze("flex flex-col lg:flex-row gap-2 h-full relative overflow-hidden",Qe&&"ring-2 ring-blue-400 ring-inset",D),onDragEnter:mt,onDragOver:ut,onDragLeave:pt,onDrop:ht,children:[Qe&&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(Z,{className:"size-6"}),"Drop files to upload"]})}),t("div",{ref:Oe,className:ze("flex flex-col min-h-0 border-0",ve||ke?"w-full lg:w-3/5 flex-1 min-h-[50vh]":o?"flex-1 w-full":"flex-1 mx-auto "+(i?"":"max-w-4xl")),children:[!k&&e("div",{className:"flex-shrink-0",children:e(cc,{title:bt,isCompleted:le,onClose:a,isModal:i,run:n,viewMode:Be,onViewModeChange:He,showPlanPanel:ve,hasPlan:he.length>0,onTogglePlanPanel:at,onDownload:async()=>{try{const e=await async function(e,t){return e.files.getDownloadUrl(`agents/${t}/conversation.json`).then(e=>e.url)}(se,n.runId);e&&window.open(e,"_blank")}catch(e){console.error("Failed to download conversation",e),ae({status:"error",title:"Failed to download conversation",duration:3e3})}},onCopyRunId:()=>{navigator.clipboard.writeText(n.runId),ae({status:"success",title:"Run ID copied",duration:2e3})},resetWorkflow:m,onExportPdf:()=>{Oe.current?vt(!0):ae({status:"error",title:"PDF export failed",description:"No conversation content available to export",duration:3e3})},isReceivingChunks:ce})}),0!==ie.length||le?e(sc,{messages:ie,bottomRef:$e,isCompleted:le,plan:st.plan,workstreamStatus:st.workstreamStatus,showPlanPanel:ve,onTogglePlanPanel:at,plans:he,activePlanIndex:ge,onChangePlan:it,taskLabels:xt,streamingMessages:oe,onSendMessage:dt,thinkingMessageIndex:Ye,messageItemClassNames:H,messageStyleOverrides:G,toolCallGroupClassNames:J,hideToolCallsInViewMode:K,streamingMessageClassNames:Y,batchProgressPanelClassNames:Q,viewMode:Be,hideWorkstreamTabs:_,workingIndicatorClassName:X,messageListClassName:ee,StoreLinkComponent:ct,CollectionLinkComponent:ne,prependFriendlyMessage:re}):e("div",{className:"flex-1 flex flex-col items-center justify-center h-full text-center py-6",children:t("div",{className:"p-5 max-w-md border border-info rounded-lg shadow-sm",children:[t("div",{className:"flex items-center space-x-3 mb-3",children:[e(Nr,{size:"sm",color:"blue"}),e("div",{className:"text-sm text-muted font-medium",children:$r[Ye]})]}),e("div",{className:"mt-4 flex justify-center",children:e(wr,{color:"blue",className:"mt-1"})})]})}),!C&&e("div",{className:"flex-shrink-0",style:{paddingBottom:"env(safe-area-inset-bottom, 0px)"},children:rt&&"RUNNING"!==rt?t(ft,{status:"COMPLETED"===rt?"success":"done",icon:null,className:"m-2",children:["This Workflow is ",rt]}):ye&&e(mc,{onSend:dt,onStop:gt,disabled:z,isSending:Re||z,isStopping:Ge,isStreaming:!le,isCompleted:le,activeTaskCount:(()=>{if(!ie.length)return 0;const e=new Map;ie.forEach(t=>{const n=Lr(t);"main"!==n&&"all"!==n&&(e.has(n)||e.set(n,[]),e.get(n).push(t))});let t=0;for(const[n,r]of e.entries())if(r.length>0){const e=r[r.length-1];[Jt.COMPLETE,Jt.IDLE].includes(e.type)||t++}return t})(),placeholder:d,onFilesSelected:Ee,uploadedFiles:h,onRemoveFile:f,acceptedFileTypes:b,maxFiles:y,processingFiles:Pe,hasProcessingFiles:Fe,renderDocumentSearch:v,selectedDocuments:x,onRemoveDocument:w,hideObjectLinking:N,hideFileUpload:j,className:F,inputClassName:E})})]}),!S&&ve&&e("div",{className:"w-full lg:w-1/3 min-h-[50vh] lg:h-full border-t lg:border-t-0 lg:border-l",children:e(uc,{plan:st.plan,workstreamStatus:st.workstreamStatus,isOpen:ve,onClose:ot,plans:he,activePlanIndex:ge,onChangePlan:it})}),!I&&ke&&we.length>0&&e("div",{className:ze("w-full lg:w-2/5 min-h-[50vh] lg:h-full border-t lg:border-t-0 lg:border-l",ve&&"lg:w-1/3"),children:e(vc,{isOpen:ke,onClose:Se,documents:we,activeDocumentId:Ne,onSelectDocument:je,onCloseDocument:_e,refreshKey:Ce,runId:n.runId})}),t(Ve,{isOpen:yt,onClose:()=>vt(!1),children:[e(We,{children:"Export conversation as PDF"}),t(qe,{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(Je,{align:"right",children:[e(De,{variant:"ghost",size:"sm",onClick:()=>vt(!1),children:"Cancel"}),e(De,{size:"sm",onClick:()=>{if(!Oe.current)return void ae({status:"error",title:"PDF export failed",description:"No conversation content available to export",duration:3e3});const e=`${bt} - ${n.runId}`,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 s=r.document;return s.open(),s.write(`<!doctype html><html><head><title>${t}</title></head><body></body></html>`),s.close(),s.title=t,document.querySelectorAll('link[rel="stylesheet"], style').forEach(e=>{s.head.appendChild(e.cloneNode(!0))}),s.body.innerHTML=e.innerHTML,r.focus(),r.print(),setTimeout(()=>{n.parentNode?.removeChild(n)},1e3),!0}(Oe.current,e);t?(ae({status:"success",title:"PDF export ready",description:"Use your browser's Print dialog to save as PDF",duration:4e3}),vt(!1)):ae({status:"error",title:"PDF export failed",description:"Unable to open print preview",duration:4e3})},children:"Open print dialog"})]})]})]})})});return $?e(gn,{data:$,sendMessage:dt,ChartComponent:br,artifactRunId:n.runId,children:wt}):wt}function Sc({messages:t}){const n=o.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,n)=>e(Rl,{message:t,showPulsatingCircle:!1},`${t.timestamp}-${n}`))})}function _c({messages:t,bottomRef:n,className:r,messagesClassName:s,emptyClassName:a}){const i=o.useRef(null);g(()=>{n.current&&n.current.scrollIntoView({behavior:"smooth"})},[t,n]);const l=o.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===l.length?e("div",{className:`flex items-center justify-center h-full text-center py-8 ${a||""}`,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 ${s||""}`,children:e(Sc,{messages:l,isCompleted:!1})})})}function jc({children:t,fallback:n}){return Ic?e(Ic,{fallback:n,children:t}):e(qn,{FallbackComponent:n,children:t})}let Ic=null;function Pc(e){Ic=e}function Tc({children:t}){return e(jc,{fallback:zc,children:t})}function zc({error:n}){return t(ft,{status:"error",title:"Sorry, something went wrong...",children:[t("div",{className:"mb-4",children:["Our team has been notified and will be quickly working on resolving it. If you'd like to escalate or simply contact us, please email us at ",e("a",{className:"text-info",href:"mailto:support@vertesiahq.com",children:"support@vertesiahq.com"}),"."]}),n?.message&&e("code",{className:"w-full mt-4 text-sm text-muted break-words",children:n.message})]})}function Ac({children:t}){return e(jc,{fallback:Dc,children:t})}function Dc({error:n}){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:n?.message})]})})}function Fc({children:t}){return e(jc,{fallback:Ec,children:t})}function Ec({error:n}){return console.log("WidgetError",n),t("div",{className:"text-sm",children:["Sorry, this area cannot be loaded or rendered.",n?.message&&e("pre",{children:n.message})]})}function $c({className:n,children:s,title:a,description:i,actions:o,breadcrumbs:l,isCompact:c=!1,useDynamicBreadcrumbs:d=!0}){const m=bn();function u(e){return e.replace(/[-_]/g," ").split(" ").map(e=>Bn(e)).join(" ")}const p=e=>{const t=e?.href||"";if(!t)return"Page";const n=t.split("#")[0].split("?")[0].split("/").filter(e=>e.length>0);if(3===n.length){if(e.title!==document.title&&e.title)return e.title;return`${u(n[1])} Detail (...${n[2].slice(-6)})`}return n.length>=2?u(n[n.length-1]):1===n.length?u(n[0]):"Page"},h=(()=>{const e=[];if(d&&"undefined"!=typeof window&&window.history.state?.historyChain){const t=window.history.state.historyChain;t.forEach((n,r)=>{const s=t.length-r;e.push({label:p(n),href:n.href,onClick:()=>m(n.href,{stepsBack:s})})})}return l&&l.length>0&&l.forEach(t=>{const n="string"==typeof t?.props?.children?t.props.children:"Page";e.push(t?.props?.href?{href:t?.props?.href,label:n,onClick:()=>m(t.props.href,{replace:t.props.clearBreadcrumbs})}:{label:n})}),e})();return t("div",{className:r(c?"pb-0":"pb-2","p-4 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",children:[e("nav",{className:"flex-1 flex justify-start text-xs",children:h.length>0&&e(Gt,{path:h,separator:e(j,{className:"w-3.5 h-3.5"}),maxItems:4})}),t("div",{className:"flex gap-2 items-center",children:[e("h1",{className:"text-xl font-semibold break-all",children:a}),i&&e(Ee,{description:i,children:e(re,{className:"size-4 text-muted"})})]})]}),e("div",{className:"flex gap-x-2 shrink-0",children:o})]}),s&&e("div",{className:"w-full flex items-center",children:s})]})}function Oc({}){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:"Page Not Found"})]})}function Rc(...e){const t=Array.from(e);return t.__AnyOf__=!0,t}function Lc(...e){return Array.from(e)}function Mc(e){return!0===e.__AnyOf__}class Uc{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 s=new Set;for(const e of n){const t=r[e];if(t)for(const e of t)s.add(e)}this.permissions=s}hasPermission(e){if("string"==typeof e)return this.permissions.has(e);if(Mc(e))return e.some(e=>this.permissions.has(e));for(const t of e)if(!this.permissions.has(t))return!1;return!0}}const Vc=d(void 0);function Wc(){const e=m(Vc);if(!e)throw new Error("UserPermissionContext cannot be used outside UserPermissionProvider");return e}function qc({children:t}){const n=Te(),{data:r,error:s,isLoading:a}=$e(()=>n.user?n.client.iam.roles.list():Promise.resolve(void 0),[n.user]),i=l(()=>n.authToken&&r&&!a?new Uc(n,r):void 0,[n,r,a]);return s?e(Oe,{title:"Failed to fetch role mappings",children:s.message}):i&&e(Vc.Provider,{value:i,children:t})}function Bc({permission:t,isDisabled:n,title:r,children:s,...a}){return Wc().hasPermission(t)||(n=!0,r="You do not have permission to perform this action"),e(De,{isDisabled:n,title:r,...a,children:s})}function Hc({permission:t,...n}){return Wc().hasPermission(t)?e(Hn,{...n}):null}function Gc({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:"ml-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{Yn as ActivitiesDoc,Qn as ActivityDoc,Sl as AddToCollectionAction,Cl as AddToCollectionActionComponent,xr as AgentChart,Di as AgentRunnerFacetsNav,Lc as AllOf,wr as AnimatedThinkingDots,Rc as AnyOf,ci as ApiKeyAvatar,Fr as AskUserWidget,Po as BrowseCollectionView,rl as ChangeTypeAction,nl as ChangeTypeActionComponent,Ti as CollectionsFacetsNav,Fo as CollectionsTable,Er as ConfirmationWidget,Yr as ContentDispositionButton,qo as ContentObjectTypesSearch,$o as ContentObjectTypesTable,Na as ContentOverview,Ao as CreateCollectionForm,Do as CreateCollectionModal,Vo as CreateOrUpdateTypeModal,il as DeleteObjectsAction,al as DeleteObjectsActionComponent,ol as DeleteObjectsFromCollectionsAction,Bi as DocumentGridView,La as DocumentIcon,Ra as DocumentIconSkeleton,ho as DocumentInput,go as DocumentPreviewPanel,Hi as DocumentSearch,oo as DocumentSearchProvider,No as DocumentSearchResults,wo as DocumentSearchResultsWithDropZone,Fi as DocumentSelection,Ri as DocumentSelectionProvider,so as DocumentTable,Wi as DocumentTableColumn,qi as DocumentTableView,to as DocumentUploadModal,wi as DocumentsFacetsNav,Zo as EditCollectionView,ui as EnvironmentFacet,cl as ExportPropertiesAction,ll as ExportPropertiesComponent,_o as ExportPropertiesModal,So as ExportTypes,Qi as FileUploadAction,$c as GenericPageNavHeader,cc as Header,Ci as InteractionsFacetsNav,jr as JumpingDots,Ol as MESSAGE_STYLES,$s as MagicPdfView,Rl as MessageItem,_c as MessagesContainer,wc as ModernAgentConversation,Oc as NotFoundView,Bo as ObjectSchemaEditor,Oo as ObjectTypeSearch,Ro as ObjectTypeSearchContext,Go as ObjectTypeSearchProvider,bl as ObjectsActionContext,vl as ObjectsActionContextProvider,Tc as PanelErrorBoundary,ac as PayloadBuilder,oc as PayloadBuilderProvider,ic as PayloadContext,is as PdfDocumentRenderer,Qr as PdfPageRenderer,cs as PdfPageSlider,as as PdfThumbnailList,ji as PromptsFacetsNav,ia as PropertiesEditorModal,Nr as PulsatingCircle,Cr as PulsingMessageLoader,ml as RemoveFromCollectionAction,dl as RemoveFromCollectionActionComponent,Ac as RowErrorBoundary,gi as RunsFacetsNav,aa as SaveVersionConfirmModal,Gi as SearchContext,Bc as SecureButton,Hc as SecureSidebarItem,Xo as SelectCollection,zo as SelectContentType,Jo as SelectContentTypeModal,co as SelectDocument,uo as SelectDocumentModal,Il as SelectionActions,es as SharedPdfProvider,el as SharedPropsEditor,rs as SimplePdfPage,Rs as SimplePdfViewer,bc as SkillWidgetProvider,pl as StartWorkflowAction,ul as StartWorkflowComponent,Ll as StreamingMessage,Va as StringFacet,Wa as StringListFacet,tl as SyncMemberHeadsToggle,Ko as TableLayoutEditor,Sr as ThinkingBar,$r as ThinkingMessages,Ba as TypeFacet,kr as TypedDots,Tl as UploadObjectsButton,Gc as UserAvatar,ai as UserInfo,qc as UserPermissionProvider,Uc as UserPermissions,Vc as UserPermissionsContext,Ha as VStringFacet,Ga as VTypeFacet,mi as VUserFacet,br as VegaLiteChart,jc as VertesiaErrorBoundary,_r as WavyThinking,Fc as WidgetErrorBoundary,yi as WorkflowExecutionsFacetsNav,Eo as collectionIcon,na as getWorkflowStatusColor,ra as getWorkflowStatusName,Mc as isAnyOf,Hs as isCsv,Gs as isImage,Js as isPdf,Ys as isPreviewableAsPdf,vr as isRechartsSpec,yr as isVegaLiteSpec,Ks as isVideo,ta as printElementToPdf,ea as retrieveRendition,Pc as setErrorBoundaryComponent,Ls as shortId,Ms as shortenString,Yo as stringifyTableLayout,zi as useAgentRunnerFilterGroups,Ai as useAgentRunnerFilterHandler,Ii as useCollectionsFilterGroups,Pi as useCollectionsFilterHandler,vi as useDocumentFilterGroups,xi as useDocumentFilterHandler,Ji as useDocumentSearch,Zi as useDocumentSearchCount,$i as useDocumentSelection,no as useDocumentUploadHandler,la as useDownloadFile,Xa as useFetchApiKeyInfo,Qa as useFetchGroupInfo,Za as useFetchUserInfo,Ni as useInteractionsFilterGroups,ki as useInteractionsFilterHandler,Nl as useObjectsActionCallback,wl as useObjectsActionContext,Oi as useOptionalDocumentSelection,lc as usePayloadBuilder,Si as usePromptsFilterGroups,_i as usePromptsFilterHandler,pi as useRunsFilterGroups,hi as useRunsFilterHandler,Lo as useSearch,Uo as useSearchCount,ts as useSharedPdf,eo as useSmartFileUploadProcessing,kl as useStartWorkflowCallback,Wc as useUserPermissions,Ki as useWatchDocumentSearchFacets,Yi as useWatchDocumentSearchResult,Mo as useWatchSearchResult,fi as useWorkflowExecutionsFilterGroups,bi as useWorkflowExecutionsFilterHandler};
|
|
1
|
+
import{jsx as e,jsxs as t,Fragment as n}from"react/jsx-runtime";import r,{clsx as s}from"clsx";import{AnimatePresence as a,motion as i}from"motion/react";import o,{useMemo as l,useState as c,createContext as d,useContext as m,useRef as u,useCallback as p,memo as h,useEffect as g,Component as f}from"react";import*as b from"@radix-ui/react-dialog";import{Loader2 as y,Check as v,Copy as x,Download as w,Minimize2 as N,Maximize2 as k,X as C,ExternalLink as S,ChevronDown as _,ChevronRight as j,CopyIcon as I,CheckCircle as P,AlertCircle as T,Layers as z,MessageSquare as A,HelpCircle as D,Send as F,XCircle as E,TableProperties as $,LayoutGrid as O,ChevronsUp as R,ChevronsDown as L,Minus as M,Plus as U,Maximize as V,Image as W,ScanSearch as q,AlertTriangle as B,SquarePen as H,FileSearch as G,Eye as J,Users as K,RefreshCw as Y,UploadIcon as Z,CheckCircleIcon as Q,AlertCircleIcon as X,FileIcon as ee,XCircleIcon as te,FolderIcon as ne,Info as re,ChevronsUpDown as se,FileText as ae,Settings as ie,Trash2 as oe,Search as le,FolderClosed as ce,EllipsisVertical as de,Bot as me,User as ue,Clock as pe,ClipboardList as he,XIcon as ge,MoreVertical as fe,DownloadCloudIcon as be,HelpCircleIcon as ye,FileTextIcon as ve,PaperclipIcon as xe,StopCircleIcon as we,SendIcon as Ne,Activity as ke,Circle as Ce,Loader2Icon as Se,Cpu as _e}from"lucide-react";import je from"papaparse";import{VegaEmbed as Ie}from"react-vega";import{twMerge as Pe}from"tailwind-merge";import{useUserSession as Te}from"@vertesia/ui/session";import{cn as ze,useToast as Ae,Button as De,Center as Fe,VTooltip as Ee,useFetch as $e,ErrorBox as Oe,ResizablePanelGroup as Re,ResizablePanel as Le,ResizableHandle as Me,Spinner as Ue,Modal as Ve,ModalTitle as We,ModalBody as qe,RadioGroup as Be,FormItem as He,Input as Ge,ModalFooter as Je,RadioOptionAdapter as Ke,useTheme as Ye,Portal as Ze,Card as Qe,Separator as Xe,CardContent as et,SelectBox as tt,InputList as nt,Avatar as rt,Table as st,Popover as at,PopoverTrigger as it,PopoverContent as ot,Badge as lt,FilterProvider as ct,FilterBtn as dt,FilterBar as mt,FilterClear as ut,TBody as pt,SharedState as ht,useWatchSharedState as gt,MessageBox as ft,useIntersectionObserver as bt,useFlag as yt,Styles as vt,Checkbox as xt,NumberInput as wt,SidePanel as Nt,Divider as kt,Textarea as Ct,Switch as St,TR as _t,EmptyCollection as jt,ConfirmModal as It,THead as Pt,useDebounce as Tt,Panel as zt,Command as At,CommandInput as Dt,CommandEmpty as Ft,CommandGroup as Et,CommandItem as $t,TagsInput as Ot,SelectList as Rt,DialogDescription as Lt,Heading as Mt,Tabs as Ut,TabsBar as Vt,TabsPanel as Wt,Dropdown as qt,MenuItem as Bt,CommandList as Ht,Breadcrumbs as Gt}from"@vertesia/ui/core";import{AgentMessageType as Jt,PDF_RENDITION_NAME as Kt,ImageRenditionFormat as Yt,WorkflowExecutionStatus as Zt,MarkdownRenditionFormat as Qt,ContentObjectStatus as Xt,ContentNature as en,POSTER_RENDITION_NAME as tn,AUDIO_RENDITION_NAME as nn,PrincipalType as rn,InteractionStatus as sn,SearchTypes as an,SupportedEmbeddingTypes as on,getContentTypeRefId as ln,AgentSearchScope as cn,mergeInCodePromptSchemas as dn,supportsToolUse as mn,FileProcessingStatus as un,normalizeToolCollection as pn}from"@vertesia/common";import{FusionFragmentHandler as hn,FusionFragmentProvider as gn}from"@vertesia/fusion-ux";import fn from"dayjs";import{useNavigate as bn,NavLink as yn}from"@vertesia/ui/router";import{MarkdownRenderer as vn,Popover as xn,XMLViewer as wn,JSONCode as Nn,MonacoEditor as kn,JSONDisplay as Cn,Progress as Sn,DropZone as _n,UploadSummary as jn,useSchema as In,SchemaEditor as Pn,ManagedObject as Tn,GeneratedForm as zn,CodeBlockRendererProvider as An}from"@vertesia/ui/widgets";import{pdfjs as Dn,Document as Fn,Page as En}from"react-pdf";import $n from"dayjs/plugin/localizedFormat";import On from"dayjs/plugin/relativeTime";import{Md5 as Rn}from"ts-md5";import{UserInfo as Ln,SyncMemberHeadsToggle as Mn,SharedPropsEditor as Un}from"@vertesia/ui/features";import Vn,{Ajv as Wn}from"ajv";import{ErrorBoundary as qn}from"react-error-boundary";import{capitalize as Bn}from"lodash-es";import{SidebarItem as Hn}from"@vertesia/ui/layout";function Gn({children:t,secondary:n=!1}){return e("span",{className:n?"bg-secondary text-primary":"text-foreground bg-muted",children:t})}function Jn(e){return e?"array"===e.name?Jn(e.innerType):e:void 0}function Kn({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(Gn,{children:"optional"}),e(Gn,{children:n.type.value})]})}function Yn({activities:t}){return e("div",{className:"flex flex-col gap-y-4 divide-y divide-gray-200",children:t.map(t=>e(Qn,{activity:t},t.name))})}function Zn({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(Gn,{children:n})})]})}function Qn({activity:n,headingClass:r,headingRef:s}){return t("div",{className:r,id:n.name,ref:s,children:[e("div",{className:"text-xl font-semibold pt-8",children:n.title}),e("div",{className:"pb-4",children:e(Gn,{children:n.name})}),n.doc&&e("div",{className:"text-gray-700 pb-2",children:n.doc}),t("div",{className:"pb-4",children:[e(Zn,{code:n.paramsType,children:"Parameters"}),e("div",{className:"divide-y divide-gray-100",children:n.params.map(t=>e(Xn,{property:t},t.name))})]}),t("div",{className:"pb-4",children:[e(Zn,{children:"Returns"}),e("div",{children:n.returnType?n.returnType.value:"void"})]})]})}function Xn({property:n,className:s}){const a=l(()=>{const t=Jn(n.type.innerType)??n.type;return"object"===t.name&&t.members?e(tr,{members:t.members}):"enum"===t.name&&t.enum?e(er,{values:t.enum}):null},[n.type.innerType]);return t("div",{className:r("py-2",s),children:[e(Kn,{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 er({values:t}){return e("div",{className:"flex flex-wrap items-center gap-2",children:t.map((t,n)=>e(Gn,{secondary:!0,children:t},n))})}function tr({members:n}){return e(rr,{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(sr,{isOpen:n}),e("div",n?{children:"Hide child properties"}:{children:"Show child properties"})]}),body:e(nr,{properties:n})})}function nr({properties:t}){return e("div",{className:"border-l-2 border-l-blue-200 flex flex-col divide-y divide-gray-100 border-t border-t-gray-200",children:t.map(t=>e(Xn,{property:t,className:"px-4 py-2"},t.name))})}function rr({button:n,body:s,className:o,isInitiallyOpen:l}){const[d,m]=c(l||!1);return t("div",{className:r(d?"block":"inline-block",o),children:[e("button",{className:"p-0 m-0 bg-transparent",onClick:()=>m(!d),children:e(a,{children:n(d)})}),e(a,{children:d&&e(i.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:s})})]})}function sr({isOpen:t}){return e(a,{propagate:!0,mode:"wait",children:e(i.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 ar(...e){return Pe(s(e))}const ir=d(null);function or({children:t}){const n=u(new Map),r=u(new Map),s=p(e=>n.current.get(e),[]),a=p((e,t)=>{n.current.set(e,t)},[]),i=p(async(e,t)=>{const s=n.current.get(e);if(s)return s;const a=r.current.get(e);if(a)return a;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},[]),l=o.useMemo(()=>({getUrl:s,setUrl:a,getOrFetch:i}),[s,a,i]);return e(ir.Provider,{value:l,children:t})}function lr(){return m(ir)}function cr(e,t,n="inline"){return`artifact:${e}:${t}:${n}`}function dr(e){return`file:${e}`}function mr({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 ur({isOpen:n,onClose:r,title:s,description:a,children:i}){return e(b.Root,{open:n,onOpenChange:e=>!e&&r(),children:t(b.Portal,{children:[e(b.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(b.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:r,children:[e(b.Close,{asChild:!0,children:e("button",{onClick:r,className:"absolute top-3 right-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":"Close fullscreen",children:e(C,{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:i}),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(b.Title,{className:"text-base font-semibold text-gray-900 dark:text-gray-100",children:s||"Dashboard"}),a&&e(b.Description,{className:"text-sm text-gray-500 dark:text-gray-400 mt-0.5",children:a})]})})]})]})})}const pr={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 hr(e,t){if(!e||!e.encoding)return!1;for(const n of t)for(const t of Object.values(e.encoding))if(t&&"object"==typeof t&&t.field===n)return!0;if(Array.isArray(e.layer))for(const n of e.layer)if(hr(n,t))return!0;return!1}function gr(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 fr(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 s of r)if(s in e){const r=e[s];Array.isArray(r)?r.forEach((e,r)=>{n.push(...fr(e,[...t,s,String(r)]))}):"object"==typeof r&&null!==r&&n.push(...fr(r,[...t,s]))}return n}const br=h(function({spec:r,artifactRunId:s}){const{title:a,description:i,spec:o,options:d}=r,[m,h]=c(!1),[f,b]=c(!1),[C,S]=c(null),[_,j]=c(!1),I=u(null),P=u(null),T=u(null),{client:z}=Te(),A=lr(),D=u(z);D.current=z;const F=u(A);F.current=A;const[E,$]=c(null),[O,R]=c(!1),[L,M]=c(null),U=d?.mode||"chart",V="dashboard"===U,W=d?.enableFullscreen??V,q=d?.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)}(o,U);g(()=>{const e=fr(o);if(0===e.length)return $(o),R(!1),void M(null);let t=!1;R(!0),M(null);return(async()=>{const n=new Map,r=D.current,a=F.current;for(const i of e)try{const e=i.path.join(".");let t;if(s&&!i.artifactPath.startsWith("agents/")){const e=cr(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=dr(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=je.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||M(`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 s=n;for(let e=0;e<t.length-1&&void 0!==s[t[e]];e++)s=s[t[e]];const a=t[t.length-1];s[a]&&"object"==typeof s[a]&&(delete s[a].url,s[a].values=r)}return n}(o,n);$(e),R(!1)}})(),()=>{t=!0}},[o,s]);const[B,H]=c(!1),G=u(!1);g(()=>{const e=()=>{const e=document.documentElement.classList.contains("dark");e!==G.current&&(G.current=e,H(e))};e();const t=new MutationObserver(e);return t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),()=>t.disconnect()},[]);const[J,K]=c(0),Y=u(0);g(()=>{if(!T.current)return;let e;const t=new ResizeObserver(t=>{clearTimeout(e),e=setTimeout(()=>{const e=t[0]?.contentRect.width;e&&e!==Y.current&&(Y.current=e,K(e))},100)});t.observe(T.current);const n=T.current.clientWidth;return Y.current=n,K(n),()=>{clearTimeout(e),t.disconnect()}},[]);const Z=l(()=>fr(o).length>0,[o]),Q=l(()=>{if(Z&&!E)return null;let e=E||o;return e?(d?.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&&"object"==typeof n&&n.name&&n.name in t&&(n.value=t[n.name])};Array.isArray(n.params)&&r(n.params);const s=e=>{if(Array.isArray(e))for(const t of e)if(t&&Array.isArray(t.params)&&r(t.params),t.vconcat&&s(t.vconcat),t.hconcat&&s(t.hconcat),t.concat&&s(t.concat),Array.isArray(t.layer))for(const e of t.layer)e&&Array.isArray(e.params)&&r(e.params)};if(n.vconcat&&s(n.vconcat),n.hconcat&&s(n.hconcat),n.concat&&s(n.concat),Array.isArray(n.layer))for(const e of n.layer)e&&Array.isArray(e.params)&&r(e.params);return n}(e,d.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:s}of r){const r=s.select?.fields||[],a="legend"===s.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(hr(t,r)||a&&gr(t,r)){o=e;break}}const l=i[o];l.params||(l.params=[]),l.params.push(s),t.params=t.params.filter(t=>t.name!==e)}return Array.isArray(t.params)&&0===t.params.length&&delete t.params,t}(e)):null},[E,o,Z,d?.parameterValues]),X=p((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),s=Math.floor((t-r)/n);return{...e,hconcat:e.hconcat.map(e=>X(e,s))}}if(e.vconcat&&Array.isArray(e.vconcat))return{...e,vconcat:e.vconcat.map(e=>X(e,t))};if(e.concat&&Array.isArray(e.concat)){const n=e.columns??e.concat.length,r=(e.spacing??10)*(n-1),s=Math.floor((t-r)/n);return{...e,concat:e.concat.map(e=>X(e,s))}}const n=e.width;return"container"===n||"number"==typeof n&&n>t?{...e,width:t}:e},[]),ee=p((e,t=!1)=>{if(!Q)return null;const n=function(e){const t={background:"transparent",view:{stroke:"transparent"},range:{category:pr.categorical,diverging:pr.diverging,heatmap:pr.purples,ramp:pr.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}}}(B),r=t?"undefined"!=typeof window?Math.min(window.innerWidth-80,1400):1200:J>0?J-24:500,s="vconcat"in Q||"hconcat"in Q||"concat"in Q,i=s?{type:"pad",contains:"padding"}:{type:"fit",contains:"padding"};let o=Q;s&&r&&(o=X(Q,r));const l=o.width,c=s?void 0:"container"===l?r:l??r,{width:d,...m}=o;return{$schema:"https://vega.github.io/schema/vega-lite/v6.json",...!s&&c?{width:c}:{},height:t?void 0:e,autosize:i,...s?o:m,...a&&!Q.title?{title:a}:{},config:{...n,...Q.config}}},[Q,a,B,J,X]),te=p(async()=>{const e=_?P.current:I.current;if(e&&!f)try{(await e.toCanvas(2)).toBlob(async e=>{e&&(await navigator.clipboard.write([new ClipboardItem({"image/png":e})]),b(!0),setTimeout(()=>b(!1),2e3))},"image/png")}catch(e){console.error("Failed to copy chart:",e)}},[f,_]),ne=p(async()=>{const e=_?P.current:I.current;if(e&&!m){h(!0);try{const t=await e.toImageURL("png",2),n=document.createElement("a");n.download=`${a||"chart"}.png`,n.href=t,n.click()}catch(e){console.error("Failed to export chart:",e)}finally{h(!1)}}},[a,m,_]),re=p(e=>{I.current=e,S(null)},[]),se=p(e=>{P.current=e},[]),ae=p(e=>{console.error("Vega-Lite rendering error:",e),S(e instanceof Error?e.message:"Unknown error")},[]),ie=p(()=>{j(e=>!e)},[]);g(()=>{S(null)},[o]);const oe=({className:n})=>t("div",{className:ar("flex items-center gap-2",n),children:[t("button",{onClick:te,disabled:f,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:"Copy to clipboard",children:[e(f?v:x,{className:"w-3 h-3"}),f?"Copied":"Copy"]}),t("button",{onClick:ne,disabled:m,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:"Export as PNG",children:[e(w,{className:"w-3 h-3"}),m?"Exporting...":"Export"]}),W&&t("button",{onClick:ie,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:_?"Exit fullscreen":"Fullscreen",children:[e(_?N:k,{className:"w-3 h-3"}),_?"Exit":"Fullscreen"]})]});if(O||Z&&!E)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:a||"Chart"})}),e("div",{className:"flex items-center justify-center bg-gray-50 dark:bg-gray-800 rounded",style:{width:"100%",height:q},children:t("div",{className:"flex items-center gap-2 text-gray-500 dark:text-gray-400",children:[e(y,{className:"w-5 h-5 animate-spin"}),e("span",{className:"text-sm",children:"Loading data from artifacts..."})]})})]})});if(L)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:a||"Chart"})}),e("div",{style:{width:"100%",height:q},children:e(mr,{error:L,chartTitle:a})})]})});if(C)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:a||"Chart"})}),e("div",{style:{width:"100%",height:q},children:e(mr,{error:C,chartTitle:a})})]})});const le=ee(q),ce=ee(0,!0);return le?("undefined"!=typeof window&&localStorage.getItem("DEBUG_VEGA_RENDERS")&&console.log("VegaLite rendering with spec:",{title:a,hasData:!!le.data?.values,dataLength:le.data?.values?.length}),t(n,{children:[e("div",{className:ar("bg-white dark:bg-gray-900 rounded-lg border border-gray-200 dark:border-gray-800 shadow-sm",V&&"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:a||(V?"Dashboard":"Chart")}),V&&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(oe,{})]}),i&&e("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:i}),e("div",{ref:T,className:"bg-white dark:bg-gray-900 rounded overflow-hidden",style:{width:"100%",height:q,minWidth:0},children:e(Ie,{spec:le,onEmbed:e=>re(e.view),onError:ae,options:{renderer:d?.renderer||"canvas",actions:!1}})})]})}),t(ur,{isOpen:_,onClose:()=>j(!1),title:a||(V?"Dashboard":"Chart"),description:i,children:[e("div",{className:"w-full h-full min-h-[calc(100vh-200px)]",children:ce&&e(Ie,{spec:ce,onEmbed:e=>se(e.view),onError:ae,options:{renderer:d?.renderer||"canvas",actions:!1}})}),e("div",{className:"absolute bottom-6 right-6",children:e(oe,{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 yr(e){return"vega-lite"===e.library&&"object"==typeof e.spec}function vr(e){return"recharts"===e.library||void 0===e.library}const xr=h(function({spec:n,artifactRunId:r}){return yr(n)?e(br,{spec:n,artifactRunId:r}):function(e){return"string"==typeof e.$schema&&e.$schema.includes("vega")}(n)?e(br,{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 wr({className:n,inline:r=!1,color:s="blue"}){const a={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"}[s];return t("div",{className:ze("flex items-center gap-1.5",r?"inline-flex":"",n),children:[e("div",{className:`w-2 h-2 bg-gradient-to-r ${a} rounded-full animate-[bounce_1.2s_ease-in-out_infinite]`}),e("div",{className:`w-2 h-2 bg-gradient-to-r ${a} rounded-full animate-[bounce_1.2s_ease-in-out_0.2s_infinite]`}),e("div",{className:`w-2 h-2 bg-gradient-to-r ${a} rounded-full animate-[bounce_1.2s_ease-in-out_0.4s_infinite]`})]})}function Nr({className:n,size:r="md",color:s="blue"}){const a={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:ze("relative flex",n),children:[e("span",{className:ze("animate-ping absolute inline-flex h-full w-full rounded-full opacity-60",a[s])}),e("span",{className:ze("animate-pulse absolute inline-flex h-[80%] w-[80%] rounded-full opacity-80",a[s]),style:{left:"10%",top:"10%",animationDuration:"2s"}}),e("span",{className:ze("relative inline-flex rounded-full",a[s],{sm:"w-3 h-3",md:"w-5 h-5",lg:"w-7 h-7"}[r])})]})}function kr({className:t,color:n="blue"}){const[r,s]=c(".");return g(()=>{const e=setInterval(()=>{s(e=>"."===e?"..":".."===e?"...":".")},500);return()=>clearInterval(e)},[]),e("span",{className:ze({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 Cr({message:n,className:r,color:s="blue"}){const a={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:ze("flex items-center gap-2 py-1",r),children:[t("div",{className:"flex space-x-1",children:[e("div",{className:`w-1.5 h-1.5 ${a[s].dot} rounded-full animate-bounce`}),e("div",{className:`w-1.5 h-1.5 ${a[s].dot} rounded-full animate-bounce`,style:{animationDelay:"0.2s"}}),e("div",{className:`w-1.5 h-1.5 ${a[s].dot} rounded-full animate-bounce`,style:{animationDelay:"0.4s"}})]}),e("div",{className:`${a[s].text} font-medium text-xs`,children:n})]})}function Sr({className:n,color:r="blue",width:s="md",message:a}){const[i,o]=c(15),[l,d]=c("increasing"),[m,p]=c(.4),h=u(null),f=u(!0);g(()=>{const e=h.current;if(!e)return;const t=new IntersectionObserver(([e])=>{f.current=e.isIntersecting},{threshold:0});return t.observe(e),()=>t.disconnect()},[]);return g(()=>{let e,t=Date.now();const n=()=>{if(!f.current)return void(e=requestAnimationFrame(n));const r=Date.now(),s=r-t;t=r,o(e=>{const t=m*(s/16);let n="increasing"===l?e+t:e-t;return n>=85?(d("decreasing"),p(.3+.2*Math.random()),85):n<=15?(d("increasing"),p(.3+.2*Math.random()),15):(Math.random()>.99&&p(e=>Math.max(.2,Math.min(.5,e+(.1*Math.random()-.05)))),n)}),e=requestAnimationFrame(n)};return e=requestAnimationFrame(n),()=>{cancelAnimationFrame(e)}},[l,m]),t("div",{ref:h,className:ze("flex flex-col gap-1",n),children:[a&&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:a}),e("div",{className:ze("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"}[s]),children:e("div",{className:ze("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:`${i}%`,transition:"width 150ms cubic-bezier(0.4, 0.0, 0.2, 1)"}})})]})}function _r({className:t,color:n="blue",size:r="md"}){const[s,a]=c(Array(7).fill(50)),i=u(null),o=u(!0);g(()=>{const e=i.current;if(!e)return;const t=new IntersectionObserver(([e])=>{o.current=e.isIntersecting},{threshold:0});return t.observe(e),()=>t.disconnect()},[]);const l={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 g(()=>{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 s=()=>{if(!o.current)return void(e=requestAnimationFrame(s));r+=.02;const i=Array(7).fill(0).map((e,s)=>10+40*(Math.sin(r*t[s]+n[s])+1));a(i),e=requestAnimationFrame(s)};return e=requestAnimationFrame(s),()=>{cancelAnimationFrame(e)}},[]),e("div",{ref:i,className:ze("flex items-end justify-center",l[r].width,l[r].height,l[r].gap,t),children:s.map((t,s)=>e("div",{className:ze(l[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}},s))})}function jr({className:n,inline:r=!1}){return t("div",{className:ze("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"}})]})}const Ir=d(null);function Pr(){const e=m(Ir);return e||{openImage:e=>window.open(e,"_blank"),closeImage:()=>{}}}function Tr({children:n}){const[r,s]=c(null),a=p((e,t)=>{s({src:e,alt:t})},[]),i=p(()=>{s(null)},[]);return t(Ir.Provider,{value:{openImage:a,closeImage:i},children:[n,r&&e("div",{className:"fixed inset-0 z-[100] flex items-center justify-center bg-black/80 backdrop-blur-sm",onClick:i,children:t("div",{className:"relative max-w-[90vw] max-h-[90vh]",children:[e("img",{src:r.src,alt:r.alt||"Enlarged view",className:"max-w-full max-h-[90vh] object-contain rounded-lg shadow-2xl"}),e("button",{className:"absolute top-2 right-2 text-white bg-black/50 rounded-full p-2 hover:bg-black/70 transition-colors",onClick:i,title:"Close",children:e(C,{className:"size-6"})}),e("a",{href:r.src,target:"_blank",rel:"noopener noreferrer",className:"absolute bottom-2 right-2 text-white bg-black/50 rounded-full p-2 hover:bg-black/70 transition-colors",onClick:e=>e.stopPropagation(),title:"Open in new tab",children:e(S,{className:"size-5"})})]})})]})}const zr=h(function({message:n,batchData:r,isRunning:s=!1,className:a,headerClassName:i,senderClassName:o,progressBarClassName:l,itemListClassName:d,itemClassName:m,summaryClassName:u}){const[p,h]=c(!1),g=Ae(),{tool_name:f,total:b,completed:v,succeeded:x,failed:w,items:N,started_at:k,completed_at:C}=r,S=b>0?v/b*100:0,A=w>0,D=v===b&&!s,F=s||!D?"running":w===b?"error":w>0?"warning":"completed",E=((C?C-k:Date.now()-k)/1e3).toFixed(1);return t("div",{className:ze("border-l-4 shadow-md overflow-hidden bg-white dark:bg-gray-900 mb-5","completed"===F?"border-l-success":"error"===F?"border-l-destructive":"warning"===F?"border-l-attention":"border-l-blue-500",a),children:[t("div",{className:ze("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",i),onClick:()=>h(!p),children:[t("div",{className:"flex items-center gap-2",children:[s||!D?e(Nr,{size:"sm",color:"blue"}):"completed"===F?e(P,{className:"size-4 text-success"}):"error"===F||"warning"===F?e(T,{className:"size-4 text-destructive"}):e(z,{className:"size-4 text-purple-600"}),e("span",{className:ze("text-xs font-medium text-muted",o),children:"Batch"}),e("span",{className:"text-xs text-blue-600 dark:text-blue-400 font-medium",children:f}),t("span",{className:"text-xs text-muted",children:[v,"/",b]}),e(p?_:j,{className:"size-3 text-muted"})]}),t("div",{className:"flex items-center gap-2",children:[t("span",{className:"text-xs text-muted",children:[E,"s"]}),e("span",{className:"text-xs text-muted",children:fn(k).format("HH:mm:ss")}),e(De,{variant:"ghost",size:"xs",onClick:e=>{e.stopPropagation(),(()=>{const e=JSON.stringify(r,null,2);navigator.clipboard.writeText(e).then(()=>{g({status:"success",title:"Copied batch details to clipboard",duration:2e3})})})()},className:"text-muted",title:"Copy batch details",children:e(I,{className:"size-3"})})]})]}),e("div",{className:ze("px-4 py-2 bg-gray-50/50 dark:bg-gray-800/30",l),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 ${A?"bg-attention":D?"bg-success":"bg-blue-500"} transition-all duration-300 ease-out`,style:{width:`${S}%`}})}),t("div",{className:"flex items-center gap-2 text-xs",children:[x>0&&t("span",{className:"text-success flex items-center gap-1",children:[e(P,{className:"size-3"}),x]}),w>0&&t("span",{className:"text-destructive flex items-center gap-1",children:[e(T,{className:"size-3"}),w]}),s&&v<b&&t("span",{className:"text-blue-500 flex items-center gap-1",children:[e(y,{className:"size-3 animate-spin"}),b-v]})]})]})}),p&&N.length>0&&e("div",{className:ze("max-h-64 overflow-y-auto",d),children:N.map(n=>t("div",{className:ze("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",m),children:[t("div",{className:"w-4 flex-shrink-0",children:["success"===n.status&&e(P,{className:"size-3 text-success"}),"error"===n.status&&e(T,{className:"size-3 text-destructive"}),"running"===n.status&&e(y,{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?"Waiting...":"")}),void 0!==n.duration_ms&&t("span",{className:"text-muted flex-shrink-0",children:[(n.duration_ms/1e3).toFixed(1),"s"]})]},n.id))}),!p&&n.message&&e("div",{className:ze("px-4 py-2 text-xs text-muted",u),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))),Ar={default:{border:"border-l-attention",bg:"bg-amber-50 dark:bg-amber-900/20",icon:"text-attention"},warning:{border:"border-l-destructive",bg:"bg-red-50 dark:bg-red-900/20",icon:"text-destructive"},info:{border:"border-l-info",bg:"bg-blue-50 dark:bg-blue-900/20",icon:"text-info"},success:{border:"border-l-success",bg:"bg-green-50 dark:bg-green-900/20",icon:"text-success"}},Dr={default:D,warning:T,info:A,success:P};function Fr({question:n,description:r,options:s,onSelect:a,onMultiSelect:i,onSubmit:l,allowFreeResponse:c=!1,multiSelect:d=!1,placeholder:m="Type your response...",isLoading:u=!1,icon:p,variant:h="default",hideIcon:g=!1,hideBorder:f=!1,className:b,cardClassName:y,headerClassName:v,iconClassName:x,questionClassName:w,descriptionClassName:N,optionsClassName:k,buttonClassName:C,inputContainerClassName:S,inputClassName:_,submitButtonClassName:j}){const[I,P]=o.useState(""),[T,z]=o.useState(new Set),A=o.useRef(null),D=Ar[h],E=Dr[h],$=()=>{I.trim()&&l&&(l(I.trim()),P(""))},O=f?"":`border-l-4 ${D.border}`;return e("div",{className:`my-4 font-sans ${b||""}`,children:t("div",{className:`${O} ${D.bg} rounded-r-lg shadow-sm ${y||""}`,children:[e("div",{className:`px-4 py-3 ${v||""}`,children:t("div",{className:"flex items-start gap-3",children:[!g&&e("div",{className:`flex-shrink-0 mt-0.5 ${D.icon} ${x||""}`,children:p||e(E,{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 ${w||""}`,children:e(vn,{children:n})}),r&&e("p",{className:`mt-1 text-sm text-gray-600 dark:text-gray-400 ${N||""}`,children:r})]})]})}),s&&s.length>0&&e("div",{className:`px-4 pb-3 pt-1 ${k||""}`,children:d?t("div",{className:"space-y-2",children:[s.map(n=>t("label",{className:`flex items-start gap-3 px-4 py-3 rounded-lg cursor-pointer transition-colors\n ${T.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 ${u?"opacity-50 cursor-not-allowed":""}`,children:[e("input",{type:"checkbox",checked:T.has(n.id),onChange:()=>{return e=n.id,void z(t=>{const n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n});var e},disabled:u,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(De,{size:"sm",onClick:()=>{T.size>0&&i&&(i(Array.from(T)),z(new Set))},disabled:u||0===T.size,className:"flex items-center gap-2",children:[e(F,{className:"size-4"}),"Submit Selection",T.size>0?` (${T.size})`:""]})})]}):e("div",{className:"flex flex-col gap-2 w-full",children:s.map(n=>e("button",{onClick:()=>a?.(n.id),disabled:u,className:`w-full text-left 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 ${u?"opacity-50 cursor-not-allowed":"cursor-pointer"}\n ${C||""}`,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",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))})}),c&&e("div",{className:`px-4 pb-3 pt-1 ${S||""}`,children:t("div",{className:"flex gap-2",children:[e("input",{ref:A,type:"text",value:I,onChange:e=>P(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),$())},placeholder:m,disabled:u,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 ${_||""}`}),e(De,{size:"sm",onClick:$,disabled:u||!I.trim(),className:j,children:u?"...":"Send"})]})})]})})}function Er({question:t,description:n,onConfirm:r,onCancel:s,confirmLabel:a="Yes",cancelLabel:i="No",isLoading:o=!1,variant:l="default",className:c}){return e(Fr,{question:t,description:n,variant:l,isLoading:o,className:c,options:[{id:"confirm",label:a,icon:e(P,{className:"size-4"})},{id:"cancel",label:i,icon:e(E,{className:"size-4"})}],onSelect:e=>{"confirm"===e?r():s()}})}const $r=["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..."];function Or(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 Rr=[Jt.COMPLETE,Jt.IDLE,Jt.REQUEST_INPUT,Jt.TERMINATED];function Lr(e){return e.workstream_id?(e.type===Jt.COMPLETE&&console.log("[getWorkstreamId] COMPLETE message with workstream_id:",e.workstream_id),e.workstream_id):(e.type===Jt.COMPLETE&&console.log("[getWorkstreamId] COMPLETE message without workstream_id, defaulting to 'main'"),"main")}function Mr(e){return e.type===Jt.THOUGHT&&!!e.details?.tool}function Ur(e){return e.details?.tool_run_id}function Vr(e){return e.details?.tool_iteration}function Wr(e){return e.details?.tool_status}function qr(e){const t=e.details?.activity_group_id;if("string"==typeof t&&""!==t.trim())return t}function Br(e){return"number"==typeof e?e:new Date(e).getTime()}function Hr(e,t,n){const r=new Map,s=new Map,a=new Map,i=[];for(const t of e){const e=qr(t);if(t.type===Jt.REQUEST_INPUT||t.type===Jt.BATCH_PROGRESS)i.push(t);else if(e)r.has(e)||r.set(e,{messages:[],firstTimestamp:Br(t.timestamp)}),r.get(e).messages.push(t);else if(Mr(t)){const e=Vr(t),n=Ur(t);void 0!==e?(s.has(e)||s.set(e,{messages:[],firstTimestamp:Br(t.timestamp)}),s.get(e).messages.push(t)):n?(a.has(n)||a.set(n,{messages:[],firstTimestamp:Br(t.timestamp)}),a.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})}),s.forEach((e,t)=>{o.push({kind:"iteration_group",iteration:t,messages:e.messages,timestamp:e.firstTimestamp})}),a.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:Br(e.timestamp)});t.forEach((e,t)=>{if(e.text){if(n&&"all"!==n){const t=e.workstreamId||"main";if(n!==t)return}o.push({kind:"streaming",streamingId:t,data:e,timestamp:e.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?l.push({type:"single",message:c[0]}):l.push({type:"tool_group",messages:c,firstTimestamp:Br(c[0].timestamp)}),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)=>Br(e.timestamp)-Br(t.timestamp)),n=t.reduce((e,t)=>Wr(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)=>Br(e.timestamp)-Br(t.timestamp)),n=t.reduce((e,t)=>Wr(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)=>Br(e.timestamp)-Br(t.timestamp)),n=t.reduce((e,t)=>Wr(t)||e,void 0);l.push({type:"tool_group",messages:t,firstTimestamp:e.timestamp,toolRunId:e.toolRunId,toolStatus:n})}else Mr(e.message)?c.push(e.message):(d(),l.push({type:"single",message:e.message}));return d(),l}function Gr(e,t){const n={error:4,warning:3,running:2,completed:1};return(e?n[e]:0)>=(t?n[t]:0)?e??t:t}function Jr(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}),n=null)};for(const s of e)"tool_group"===s.type?n?(n.messages=[...n.messages,...s.messages],n.toolStatus=Gr(n.toolStatus,s.toolStatus),!n.toolRunId&&s.toolRunId&&(n.toolRunId=s.toolRunId)):n={messages:[...s.messages],firstTimestamp:s.firstTimestamp,toolRunId:s.toolRunId,toolStatus:s.toolStatus}:(r(),t.push(s));return r(),t}const Kr="vertesia.content_store.lastDisplayedView";function Yr({onUpdate:t}){const[n,r]=c("grid"===localStorage.getItem(Kr)),s=()=>{localStorage.setItem(Kr,"grid"),r(!0),t(!0)},a=()=>{localStorage.setItem(Kr,"table"),r(!1),t(!1)};return e(De,{variant:"outline",onClick:()=>{n?a():s()},alt:n?"Table View":"Thumbnail View",children:e(n?$:O,{})})}function Zr({className:t,size:n="md"}){return e("div",{className:`flex items-center justify-center ${t||""}`,children:e(y,{className:`${{sm:"w-4 h-4",md:"w-6 h-6",lg:"w-8 h-8"}[n]} animate-spin text-muted-foreground`})})}function Qr({pdfUrl:n,pageNumber:r,width:s,className:a,renderTextLayer:i=!1,renderAnnotationLayer:o=!1,onLoadSuccess:l,onError:d}){const[m,u]=c(!0),[p,h]=c(null);return p?e("div",{className:`flex items-center justify-center text-destructive text-sm ${a||""}`,children:"Failed to load PDF"}):t("div",{className:a,children:[m&&e(Zr,{className:"py-4",size:"md"}),e(Fn,{file:n,onLoadSuccess:({numPages:e})=>{u(!1),l?.(e)},onLoadError:e=>{u(!1),h(e),d?.(e)},loading:null,children:e(En,{pageNumber:r,width:s,renderTextLayer:i,renderAnnotationLayer:o,loading:e(Zr,{className:"py-4",size:"sm"})})})]})}Yr.LAST_DISPLAYED_VIEW=Kr,Dn.GlobalWorkerOptions.workerSrc=`//unpkg.com/pdfjs-dist@${Dn.version}/build/pdf.worker.min.mjs`;const Xr=d(null);function es({pdfUrl:t,urlLoading:n=!1,children:r,onLoadSuccess:s}){const[a,i]=c(0),[o,l]=c(!0),[d,m]=c(null),[u,p]=c(null),h={pdfUrl:t,numPages:a,loading:n||!t||o,error:d,pageDimensions:u};return d?e("div",{className:"flex items-center justify-center text-destructive text-sm py-4",children:"Failed to load PDF"}):e(Xr.Provider,{value:h,children:t?e(Fn,{file:t,onLoadSuccess:async e=>{i(e.numPages),s?.(e.numPages);try{const t=(await e.getPage(1)).getViewport({scale:1});p({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),m(e)},loading:e(Zr,{className:"py-4",size:"md"}),children:r((t,n)=>e(En,{pageNumber:t,width:n,renderTextLayer:!1,renderAnnotationLayer:!1,loading:e(Zr,{className:"py-4",size:"sm"})},t))}):e(Zr,{className:"py-4",size:"md"})})}function ts(){return m(Xr)}const ns=210/297;function rs({pageNumber:t,width:n,className:r}){const s=ts(),a=s?.pageDimensions?.aspectRatio??ns,i=n?Math.round(n/a):200;return e("div",s?.loading?{className:`flex items-center justify-center bg-muted ${r||""}`,style:{height:i,width:n||"100%"},children:e(Zr,{size:"md"})}:{className:r,children:e(En,{pageNumber:t,width:n,renderTextLayer:!1,renderAnnotationLayer:!1,loading:e(Zr,{className:"py-4",size:"sm"})})})}function ss({pageNumber:t,width:n,isSelected:r,onSelect:s,renderThumbnail:a,aspectRatio:i=ns,rootMargin:o="200px 0px"}){const l=u(null),[d,m]=c(!1);g(()=>{const e=l.current;if(!e)return;const t=new IntersectionObserver(e=>{const t=e[0];t?.isIntersecting&&m(!0)},{rootMargin:o,threshold:0});return t.observe(e),()=>t.disconnect()},[o]);const p=n?Math.round(n/i):200,h=d?e(En,{pageNumber:t,width:n,renderTextLayer:!1,renderAnnotationLayer:!1,loading:e("div",{className:"flex items-center justify-center bg-muted",style:{height:p},children:e(Zr,{size:"sm"})})}):e("div",{className:"flex items-center justify-center bg-muted",style:{height:p,width:n||"100%"},children:e("span",{className:"text-muted-foreground text-xs",children:t})});return e("div",{ref:l,children:a({pageNumber:t,isSelected:r,pageElement:h,onSelect:s})})}function as({pdfUrl:r,urlLoading:s=!1,pageCount:a,currentPage:i,thumbnailWidth:o,onPageSelect:l,renderThumbnail:d,scrollContainerRef:m,onAspectRatioChange:h,onItemHeightChange:f,calculateItemHeight:b,onPageCountChange:y}){const[v,x]=c(null),[w,N]=c({start:0,end:Math.min(15,a)}),[k,C]=c(null),S=u(null),_=p(e=>{x(e)},[]),j=p(async e=>{y?.(e.numPages);try{const t=(await e.getPage(1)).getViewport({scale:1}),n=t.width/t.height;C(n),h?.(n)}catch(e){console.error("Failed to get page dimensions:",e),C(ns),h?.(ns)}},[h,y]),I=k??ns,P=o?Math.round(o/I):200,T=b?b(P):P+16+24+8;g(()=>{T>0&&null!==k&&f?.(T)},[T,k,f]);if(g(()=>{const e=m?.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}(S.current);if(!e)return;const t=()=>{const t=e.scrollTop,n=e.clientHeight,r=Math.floor(t/T),s=Math.ceil((t+n)/T),i=Math.max(0,r-5),o=Math.min(a,s+5);N(e=>e.start!==i||e.end!==o?{start:i,end:o}:e)};return t(),e.addEventListener("scroll",t,{passive:!0}),()=>e.removeEventListener("scroll",t)},[T,a,m]),v)return e("div",{className:"flex items-center justify-center text-destructive text-sm py-4",children:"Failed to load PDF"});if(s||!r)return e(Zr,{className:"py-4",size:"md"});const z=w.start*T,A=(a-w.end)*T,D=null!==k;return e("div",{ref:S,children:e(Fn,{file:r,onLoadSuccess:j,onLoadError:_,loading:e(Zr,{className:"py-4",size:"md"}),children:D?t(n,{children:[z>0&&e("div",{style:{height:z}}),Array.from({length:w.end-w.start},(t,n)=>{const r=w.start+n+1;return e("div",{"data-page-index":r-1,style:{height:T,overflow:"hidden"},children:e(ss,{pageNumber:r,width:o,isSelected:r===i,onSelect:()=>l(r),renderThumbnail:d,aspectRatio:I})},r)}),A>0&&e("div",{style:{height:A}})]}):e(Zr,{className:"py-4",size:"md"})})})}function is({pdfUrl:n,pageNumber:r,width:s,height:a,className:i,renderTextLayer:o=!1,renderAnnotationLayer:l=!1,onPageChange:d}){const[m,u]=c(0),[p,h]=c(!0),[f,b]=c(null);g(()=>{m>0&&d?.(r,m)},[r,m,d]);return f?e("div",{className:`flex items-center justify-center text-destructive ${i||""}`,children:t("span",{children:["Failed to load PDF: ",f.message]})}):t("div",{className:i,children:[p&&e(Zr,{className:"py-8",size:"lg"}),e(Fn,{file:n,onLoadSuccess:({numPages:e})=>{u(e),h(!1)},onLoadError:e=>{h(!1),b(e)},loading:null,children:e(En,{pageNumber:Math.min(r,m||1),width:s,height:a,renderTextLayer:o,renderAnnotationLayer:l,loading:e(Zr,{className:"py-8",size:"md"})})})]})}const os=210/297,ls=[50,75,100,125,150,200,300];function cs({pdfUrl:s,pdfUrlLoading:a=!1,pageCount:i,currentPage:o,onChange:l,onPageCountChange:d,className:m,compact:h=!1,headerExtra:f}){const b=u(null),y=u(null),[v,x]=c(void 0),[w,N]=c(100),[k,C]=c(os),[S,_]=c(null),j=u(null),I=v?Math.round(v*w/100):void 0,P=p(()=>{let e=ls.findIndex(e=>e>=w);-1===e&&(e=ls.length-1);const t=Math.min(e+1,ls.length-1);N(ls[t])},[w]),T=p(()=>{let e=ls.findIndex(e=>e>=w);-1===e&&(e=ls.length-1);const t=Math.max(e-1,0);N(ls[t])},[w]),z=p(()=>{N(100)},[]),A=p(e=>e+(h?28:48),[h]),D=(e,t)=>{const n=e?Math.round(e/t):200;return A(n)};g(()=>{const e=y.current;if(!e)return;let t=null;const n=()=>e.clientWidth-16-16-4,r=()=>{const t=n();if(t<=0)return;const r=j.current;if(r&&r>0){const n=e.scrollTop,s=Math.round(n/r),a=D(t,k),i=s*a;x(t),requestAnimationFrame(()=>{e.scrollTo({top:i,behavior:"instant"})}),j.current=a}else x(t),j.current=D(t,k)},s=n();s>0&&(x(s),j.current=D(s,k));const a=new ResizeObserver(()=>{t&&clearTimeout(t),t=setTimeout(r,150)});return a.observe(e),()=>{t&&clearTimeout(t),a.disconnect()}},[k]);const F=u(!1),E=u(null),$=u(w);g(()=>{$.current!==w&&($.current=w,E.current={targetPage:o},F.current=!0)},[w,o]),g(()=>{const e=y.current,t=E.current;if(t&&e&&S){E.current=null;const n=(t.targetPage-1)*S;requestAnimationFrame(()=>{e.scrollTo({top:n,behavior:"instant"}),requestAnimationFrame(()=>{F.current=!1})})}},[S]);const O=u(!1);g(()=>{const e=y.current;if(e&&S&&!O.current)if(o>1){O.current=!0,F.current=!0;const t=(o-1)*S;e.scrollTo({top:t,behavior:"instant"}),requestAnimationFrame(()=>{F.current=!1})}else O.current=!0},[S,o]);const M=u(o);g(()=>{const e=y.current;if(e&&S&&M.current!==o){M.current=o,F.current=!0;const t=(o-1)*S;e.scrollTo({top:t,behavior:"instant"}),requestAnimationFrame(()=>{F.current=!1})}},[o,S]),g(()=>{const e=y.current;if(!e||!S)return;let t=null;const n=()=>{F.current||(t&&clearTimeout(t),t=setTimeout(()=>{const t=e.scrollTop,n=Math.round(t/S)+1,r=Math.max(1,Math.min(n,i));r!==o&&(M.current=r,l(r))},50))};return e.addEventListener("scroll",n,{passive:!0}),()=>{t&&clearTimeout(t),e.removeEventListener("scroll",n)}},[S,i,o,l]);return t("div",{ref:b,className:r("flex flex-col items-stretch",h?"gap-y-1":"gap-y-2",m),children:[t("div",{className:r("relative flex items-center justify-center px-2",h?"h-6":"h-9"),children:[e(De,{variant:"ghost",size:"xs",onClick:()=>{o>1&&l(o-1)},alt:"Previous page",children:e(R,{className:"size-4"})}),t("div",{className:"absolute left-2 flex items-center gap-x-1",children:[e(ms,{zoom:w,onZoomIn:P,onZoomOut:T,onFitToView:z,canZoomIn:w<ls[ls.length-1],canZoomOut:w>ls[0]}),f&&t(n,{children:[e("div",{className:"w-px h-4 bg-border mx-1"}),f]})]}),e("div",{className:"absolute right-2",children:e(ds,{currentPage:o,totalPages:i,onChange:l})})]}),e("div",{ref:y,className:r("flex flex-col items-center flex-1 overflow-y-auto px-2",h?"gap-1":"gap-2"),children:e(as,{pdfUrl:s,urlLoading:a,pageCount:i,currentPage:o,thumbnailWidth:I,onPageSelect:l,onPageCountChange:d,scrollContainerRef:y,onAspectRatioChange:C,onItemHeightChange:_,calculateItemHeight:A,renderThumbnail:({pageNumber:n,isSelected:s,pageElement:a,onSelect:i})=>t("div",{className:r("hover:bg-muted rounded-md w-full",h?"p-1":"p-2"),children:[e("div",{className:r("relative border-[2px] cursor-pointer overflow-hidden",s?"border-primary":"border-border"),onClick:i,children:a}),e(Fe,{className:r("text-muted-foreground font-semibold",h?"text-xs pt-0.5":"text-sm pt-1"),children:n})]},n)})}),e("div",{className:r("flex items-center justify-center",h?"h-6":"h-9"),children:e(De,{variant:"ghost",size:"xs",onClick:()=>{o<i&&l(o+1)},alt:"Next page",children:e(L,{className:"size-4"})})})]})}function ds({currentPage:n,totalPages:r,onChange:s}){const a=u(null),[i,o]=c(String(n));g(()=>{o(String(n))},[n]);const l=()=>{const e=parseInt(i,10);!isNaN(e)&&e>=1&&e<=r?s(e):o(String(n))};return t("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e("span",{children:"Page"}),e("input",{ref:a,type:"text",value:i,onChange:e=>o(e.target.value),onKeyDown:e=>{"Enter"===e.key?(l(),a.current?.blur()):"Escape"===e.key&&(o(String(n)),a.current?.blur())},onBlur:()=>{l()},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 ms({zoom:n,onZoomIn:s,onZoomOut:a,onFitToView:i,canZoomIn:o,canZoomOut:l}){return t("div",{className:"flex items-center gap-x-0.5",children:[e(Ee,{description:"Zoom out",placement:"bottom",size:"xs",children:e("button",{className:r("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:a,disabled:!l,children:e(M,{className:"size-4"})})}),t("span",{className:"text-xs text-muted-foreground min-w-[32px] text-center",children:[n,"%"]}),e(Ee,{description:"Zoom in",placement:"bottom",size:"xs",children:e("button",{className:r("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:s,disabled:!o,children:e(U,{className:"size-4"})})}),e(Ee,{description:"Fit to width",placement:"bottom",size:"xs",children:e("button",{className:r("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(V,{className:"size-4"})})})]})}const us="magic-pdf";var ps;!function(e){e.original="original",e.instrumented="instrumented"}(ps||(ps={}));class hs{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 s=this.pending.get(n);if(s)return s;const a=this.fetchImageUrl(e,t);this.pending.set(n,a);try{const e=await a;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=`${us}/${this.objectId}/pages`;switch(t){case ps.original:return`${n}/page-${e}.original.jpg`;case ps.instrumented:return`${n}/page-${e}.instrumented.jpg`}}}class gs{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=`${us}/${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 fs{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,s=[];let a;for(;null!==(a=r.exec(e));)s.push({page:parseInt(a[1],10),index:a.index+a[0].length});for(let r=0;r<s.length;r++){const a=s[r],i=a.page-1;if(i<0||i>=t)continue;const o=a.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 bs=d(void 0);function ys({children:t,object:n}){const{client:r}=Te(),s=n.metadata.page_count||10,a="markdown"===n.metadata?.content_processor?.type,[i,o]=c(()=>{const e=new fs(s);a&&n.text&&e.initFromContent(n.text);const t=n.text?ws(n.text):"";return{count:s,layoutProvider:new gs(r,n.id,s),markdownProvider:e,imageProvider:new hs(r,n.id,s),xml:t,xmlPages:n.text?xs(t):[],pdfUrl:"",pdfUrlLoading:!0}});return g(()=>{if(a){const e=n.metadata,t=e?.renditions?.find(e=>e.name===Kt),s="application/pdf"===n.content?.type,a=t?.content?.source||(s?n.content?.source:void 0);a?r.store.objects.getDownloadUrl(a,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}))},[n.id,r,a,s]),e(bs.Provider,{value:i,children:t})}function vs(){const e=o.useContext(bs);if(!e)throw new Error("useMagicPdfContext must be used within a MagicPdfProvider");return e}function xs(e){const t=(new DOMParser).parseFromString(ws(e),"text/xml").getElementsByTagName("page"),n=new XMLSerializer;return Array.from(t).map(e=>n.serializeToString(e))}function ws(e){return e.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,"").replace(/<\?xml.*?\?>/g,"")}const Ns=[50,75,100,125,150,200,300],ks=11/8.5;function Cs({className:n,currentPage:s,onChange:a}){const[i,o]=c(ps.instrumented),[l,d]=c(ks),[m,h]=c(new Map),[f,b]=c(100),y=u(new Set),v=u(null),x=u(null),w=u(!1),{imageProvider:N,count:k}=vs(),C=p(()=>{let e=Ns.findIndex(e=>e>=f);-1===e&&(e=Ns.length-1);const t=Math.min(e+1,Ns.length-1);b(Ns[t])},[f]),S=p(()=>{let e=Ns.findIndex(e=>e>=f);-1===e&&(e=Ns.length-1);const t=Math.max(e-1,0);b(Ns[t])},[f]),_=p(()=>{b(100)},[]);g(()=>{N.getPageImageUrl(1,i).then(e=>{const t=new window.Image;t.onload=()=>{t.width>0&&t.height>0&&d(t.height/t.width)},t.src=e}).catch(()=>{})},[N,i]);const j=u(i);g(()=>{let e=!1;j.current!==i&&(j.current=i,y.current=new Set,h(new Map));const t=function(e,t){const n=[e];let r=1;for(;n.length<t;){const s=e+r,a=e-r;s<=t&&n.push(s),a>=1&&n.push(a),r++}return n}(s,k);return t.forEach(t=>(async t=>{if(!e&&!y.current.has(t))try{const n=await N.getPageImageUrl(t,i);e||(y.current.add(t),h(e=>new Map(e).set(t,n)))}catch{}})(t)),()=>{e=!0}},[s,k,i,N]);const I=u(f);g(()=>{if(I.current!==f&&x.current){I.current=f,w.current=!0;const e=x.current.querySelector(`[data-page="${s}"]`);e?requestAnimationFrame(()=>{e.scrollIntoView({behavior:"instant",block:"center"}),requestAnimationFrame(()=>{w.current=!1})}):w.current=!1}},[f,s]);const P=u(s);g(()=>{if(P.current!==s&&x.current){P.current=s,w.current=!0;const e=x.current.querySelector(`[data-page="${s}"]`);e&&e.scrollIntoView({behavior:"instant",block:"nearest"}),requestAnimationFrame(()=>{w.current=!1})}},[s]),g(()=>{const e=x.current;if(!e)return;let t=null;const n=()=>{w.current||(t&&clearTimeout(t),t=setTimeout(()=>{const t=e.getBoundingClientRect(),n=t.top+t.height/2;let r=s,i=1/0;for(let t=1;t<=k;t++){const s=e.querySelector(`[data-page="${t}"]`);if(s){const e=s.getBoundingClientRect(),a=e.top+e.height/2,o=Math.abs(a-n);o<i&&(i=o,r=t)}}r!==s&&(P.current=r,a(r))},50))};return e.addEventListener("scroll",n,{passive:!0}),()=>{t&&clearTimeout(t),e.removeEventListener("scroll",n)}},[k,s,a]);return t("div",{ref:v,className:r("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(De,{variant:"ghost",size:"xs",onClick:()=>{s>1&&a(s-1)},alt:"Previous page",children:e(R,{className:"size-4"})}),t("div",{className:"absolute left-2 flex items-center gap-x-1",children:[e(Ss,{type:ps.original,currentType:i,onClick:()=>o(ps.original),icon:e(W,{className:"size-4"}),tooltip:"Original images"}),e(Ss,{type:ps.instrumented,currentType:i,onClick:()=>o(ps.instrumented),icon:e(q,{className:"size-4"}),tooltip:"Instrumented images"}),e("div",{className:"w-px h-4 bg-border mx-1"}),e(_s,{zoom:f,onZoomIn:C,onZoomOut:S,onFitToView:_,canZoomIn:f<Ns[Ns.length-1],canZoomOut:f>Ns[0]})]}),e("div",{className:"absolute right-2",children:e(Is,{currentPage:s,totalPages:k,onChange:a})})]}),e("div",{ref:x,className:"flex flex-col items-center gap-2 flex-1 overflow-y-auto px-2",children:Array.from({length:k},(t,n)=>e(js,{currentPage:s,pageNumber:n+1,aspectRatio:l,zoom:f,url:m.get(n+1),onSelect:()=>a(n+1)},n))}),e("div",{className:"flex items-center justify-center h-9",children:e(De,{variant:"ghost",size:"xs",onClick:()=>{s<k&&a(s+1)},alt:"Next page",children:e(L,{className:"size-4"})})})]})}function Ss({type:t,currentType:n,onClick:s,icon:a,tooltip:i}){return e(Ee,{description:i,placement:"bottom",size:"xs",children:e("button",{className:r("p-1 rounded cursor-pointer transition-colors",t===n?"text-primary bg-primary/10":"text-muted-foreground hover:text-foreground hover:bg-muted"),onClick:s,children:a})})}function _s({zoom:n,onZoomIn:s,onZoomOut:a,onFitToView:i,canZoomIn:o,canZoomOut:l}){return t("div",{className:"flex items-center gap-x-0.5",children:[e(Ee,{description:"Zoom out",placement:"bottom",size:"xs",children:e("button",{className:r("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:a,disabled:!l,children:e(M,{className:"size-4"})})}),t("span",{className:"text-xs text-muted-foreground min-w-[32px] text-center",children:[n,"%"]}),e(Ee,{description:"Zoom in",placement:"bottom",size:"xs",children:e("button",{className:r("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:s,disabled:!o,children:e(U,{className:"size-4"})})}),e(Ee,{description:"Fit to width",placement:"bottom",size:"xs",children:e("button",{className:r("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(V,{className:"size-4"})})})]})}function js({pageNumber:n,currentPage:s,aspectRatio:a,zoom:i,url:o,onSelect:l}){return t("div",{className:"p-2 hover:bg-muted rounded-md flex flex-col items-center","data-page":n,style:{width:`${i}%`},children:[e("div",{className:r("relative border-[2px] cursor-pointer overflow-hidden flex items-center justify-center bg-muted/50 w-full",n===s?"border-primary":"border-border"),style:{aspectRatio:`1 / ${a}`},onClick:l,children:o?e("img",{src:o,alt:`Page ${n}`,className:"w-full"}):e(y,{className:"w-6 h-6 animate-spin text-muted-foreground"})}),e(Fe,{className:"text-sm text-muted-foreground pt-1 font-semibold",children:n})]})}function Is({currentPage:n,totalPages:r,onChange:s}){const a=u(null),[i,o]=c(String(n));g(()=>{o(String(n))},[n]);const l=()=>{const e=parseInt(i,10);!isNaN(e)&&e>=1&&e<=r?s(e):o(String(n))};return t("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e("span",{children:"Page"}),e("input",{ref:a,type:"text",value:i,onChange:e=>o(e.target.value),onKeyDown:e=>{"Enter"===e.key?(l(),a.current?.blur()):"Escape"===e.key&&(o(String(n)),a.current?.blur())},onBlur:()=>{l()},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 Ps({object:n}){const{client:r}=Te(),s=e=>{(function(e,t,n){return e.files.getDownloadUrl(`${us}/${t}/${n}`).then(e=>e.url)})(r,n.id,e).then(e=>window.open(e,"_blank"))},a="p-2 cursor-pointer hover:bg-muted text-left text-sm";return"markdown"===(()=>{if("document"===n.metadata?.type){const e=n.metadata;return e.content_processor?.type||"xml"}return"xml"})()?e(De,{variant:"ghost",size:"xs",onClick:()=>s("document.md"),alt:"Download",children:e(w,{className:"size-4"})}):t(xn,{strategy:"absolute",placement:"bottom-start",zIndex:100,offset:8,children:[e(xn.Trigger,{click:!0,children:e(De,{variant:"ghost",size:"xs",alt:"Download",children:e(w,{className:"size-4"})})}),e(xn.Content,{children:t("div",{className:"rounded-md shadow-md border border-border bg-popover min-w-[200px] flex flex-col divide-y divide-border",children:[e("button",{className:a,onClick:()=>s("annotated.pdf"),children:"annotated.pdf"}),e("button",{className:a,onClick:()=>s("document.xml"),children:"document.xml"}),e("button",{className:a,onClick:()=>s("analyzed-pages.json"),children:"analyzed-pages.json"})]})})]})}function Ts({className:t}){return e("div",{className:`flex items-center justify-center ${t||""}`,children:e(y,{className:"w-6 h-6 animate-spin text-gray-400"})})}function zs({viewType:t,pageNumber:n}){switch(t){case"json":return e(Ds,{pageNumber:n});case"markdown":return e(Fs,{pageNumber:n});default:return e(As,{pageNumber:n})}}function As({pageNumber:t}){const{xmlPages:n}=vs();return e("div",{className:"px-4 py-2",children:e(wn,{xml:n[t-1],collapsible:!0})})}function Ds({pageNumber:t}){const[n,r]=c(null),[s,a]=c(!0),[i,o]=c(null),{layoutProvider:l}=vs();return g(()=>{a(!0),o(null),l.getPageLayout(t).then(e=>{r(e?JSON.parse(e):null),a(!1)}).catch(e=>{console.error(e),o(e.message||"Failed to load layout"),a(!1)})},[t,l]),s?e("div",{className:"px-4 py-8",children:e(Ts,{})}):i?e("div",{className:"px-4 py-2 text-red-500 text-sm",children:i}):n?e(Nn,{className:"w-full",data:n}):null}function Fs({pageNumber:n}){const[r,s]=c(null),[a,i]=c(!0),[o,l]=c(null),{markdownProvider:d}=vs();return g(()=>{i(!0),l(null),d.getPageMarkdown(n).then(e=>{s(e),i(!1)}).catch(e=>{console.error(e),l(e.message||"Failed to load markdown"),i(!1)})},[n,d]),a?t("div",{className:"h-full flex flex-col items-center justify-center gap-2",children:[e(Ts,{}),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(vn,{children:r}):e("div",{children:"No markdown content available"})})}class Es extends f{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(Oe,{title:"Failed to load PDF viewer",children:this.state.error?.message||"An unexpected error occurred"}),this.props.onClose&&e(De,{variant:"outline",onClick:this.props.onClose,children:"Close"})]})}):this.props.children}}function $s({objectId:n,onClose:r}){const{client:s}=Te(),{data:a,error:i}=$e(()=>s.store.objects.retrieve(n,"+text"),[n]);return i?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(Oe,{title:"Fetching document failed",children:i.message}),r&&e(De,{variant:"outline",onClick:r,children:"Close"})]})}):a?e(Es,{onClose:r,children:e("div",{className:"fixed inset-0 bg-background z-50 flex items-center justify-center",children:e(ys,{object:a,children:e(Os,{object:a,onClose:r})})})}):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:r&&e(De,{variant:"ghost",size:"xs",onClick:r,alt:"Close",children:e(C,{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 Os({object:n,onClose:r}){const{count:s,pdfUrl:a,pdfUrlLoading:i}=vs(),[o,l]=c(1),d=(()=>{if("document"===n.metadata?.type){const e=n.metadata,t=e.content_processor?.type;if("markdown"===t)return"markdown"}return"xml"})();return t(Re,"xml"===d?{direction:"horizontal",className:"absolute inset-0",children:[e(Le,{defaultSize:50,minSize:20,maxSize:80,className:"bg-muted",children:e(Cs,{className:"h-full",currentPage:o,onChange:l})}),e(Me,{className:"w-[4px] bg-border cursor-ew-resize"}),t(Le,{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(Ps,{object:n})}),t("span",{className:"text-xs text-muted-foreground",children:["Page ",o," / ",s]}),e("div",{className:"flex items-center gap-x-2",children:!!r&&e(De,{variant:"ghost",size:"xs",onClick:r,alt:"Close",children:e(C,{className:"size-4"})})})]}),e("div",{className:"flex-1 overflow-auto px-2",children:e(zs,{pageNumber:o,viewType:"xml"})})]})]}:{direction:"horizontal",className:"absolute inset-0",children:[e(Le,{defaultSize:50,minSize:20,maxSize:80,className:"bg-muted",children:e(cs,{pdfUrl:a,pdfUrlLoading:i,pageCount:s,className:"h-full",currentPage:o,onChange:l})}),e(Me,{className:"w-[4px] bg-border cursor-ew-resize"}),t(Le,{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(Ps,{object:n})}),t("span",{className:"text-xs text-muted-foreground",children:["Page ",o," / ",s]}),e("div",{className:"flex items-center gap-x-2",children:!!r&&e(De,{variant:"ghost",size:"xs",onClick:r,alt:"Close",children:e(C,{className:"size-4"})})})]}),e("div",{className:"flex-1 overflow-auto px-2",children:e(zs,{pageNumber:o,viewType:"markdown"})})]})]})}function Rs({object:n,url:r,source:s,className:a}){const{client:i}=Te(),[o,l]=c(1),[d,m]=c(r||""),[u,p]=c(!r),[h,f]=c(0),[b,y]=c(!1);g(()=>{if(r)return m(r),void p(!1);const e=s||n?.content?.source;e?(p(!0),i.files.getDownloadUrl(e).then(e=>{m(e.url)}).catch(e=>{console.error("Failed to get PDF URL:",e)}).finally(()=>{p(!1)})):p(!1)},[r,s,n?.content?.source,i]),g(()=>{const e=n?.metadata,t=e?.pages||e?.page_count||0;t>0&&f(t)},[n?.metadata]);const v=e=>{f(e)};return u?e("div",{className:"flex items-center justify-center h-full",children:e(Ue,{size:"lg"})}):d?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(De,{variant:"ghost",size:"xs",onClick:()=>y(!1),alt:"Close fullscreen",children:e(C,{className:"size-4"})})}),e(cs,{pdfUrl:d,pdfUrlLoading:u,pageCount:h||100,currentPage:o,onChange:l,onPageCountChange:v,className:"flex-1 min-h-0"})]}):e("div",{className:"relative h-full flex flex-col",children:e(cs,{pdfUrl:d,pdfUrlLoading:u,pageCount:h||100,currentPage:o,onChange:l,onPageCountChange:v,className:a,compact:!0,headerExtra:e(Ee,{description:"Fullscreen",placement:"bottom",size:"xs",children:e("button",{className:"p-1 rounded cursor-pointer transition-colors text-muted-foreground hover:text-foreground hover:bg-muted",onClick:()=>y(!0),children:e(k,{className:"size-4"})})})})}):e("div",{className:"flex items-center justify-center h-full text-muted",children:"No PDF available"})}function Ls(e,t=7){return e?"~"+e.slice(-t):""}function Ms(e,t){return e.length>t?e.substring(0,t)+"...":e}const Us="text/csv",Vs="image/",Ws="application/pdf",qs="video/",Bs=["application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/msword","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.ms-powerpoint"],Hs=e=>e===Us||Us.includes(e),Gs=e=>e.startsWith(Vs)||Vs.includes(e),Js=e=>e===Ws||Ws.includes(e),Ks=e=>e.startsWith(qs)||qs.includes(e),Ys=e=>Bs.includes(e),Zs=import.meta.env,Qs={max_hw:Zs?.VITE_RENDITION_HW||256,format:Yt.jpeg,generate_if_missing:!0},Xs="vertesia.content_store.renditionId";async function ea(e,t,n,r,s){if(!t?.content?.type||!(Gs(t.content.type)||Ks(t.content.type)||Js(t.content.type)))return void s("No preview available");s("Preparing preview...");const a=(new Date).getTime()/1e3,i=localStorage.getItem(`${Xs}_${t.id}_${Qs.max_hw}`),o=localStorage.getItem(`${Xs}_${t.id}_${Qs.max_hw}_time`);if(i?.length&&o&&Math.abs(a-parseInt(o))<=900)return n(i),r(`${t.name} Rendition`),s("ready"),i;s("Preparing preview..."),e.objects.getRendition(t.id,Qs).then(a=>{if("generating"===a.status)s("Preparing preview..."),n(""),r(""),setTimeout(()=>ea(e,t,n,r,s),6e4);else{if("failed"===a.status)return s("No preview available"),n(""),void r("");{if(!a?.renditions?.length)return s("No preview available"),n(""),void r("");const e=a.renditions[0];localStorage.setItem(`${Xs}_${t.id}_${Qs.max_hw}`,e),localStorage.setItem(`${Xs}_${t.id}_${Qs.max_hw}_time`,((new Date).getTime()/1e3).toString()),n(e),r(`${t.name} Rendition`),s("ready"),console.log(`Rendition for document ${t.id} retrieved successfully: ${e}`)}}}).catch(e=>{s("No preview available"),console.warn("Failed to retrieve rendition:",e),n(""),r("")})}function ta(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 s=r.document;s.open(),s.write(`<!doctype html><html><head><title>${t}</title></head><body></body></html>`),s.close(),s.title=t;document.querySelectorAll('link[rel="stylesheet"], style').forEach(e=>{s.head.appendChild(e.cloneNode(!0))});const a=s.createElement("style");return a.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',s.head.appendChild(a),s.body.innerHTML=e.innerHTML,r.focus(),r.print(),setTimeout(()=>{n.parentNode?.removeChild(n)},1e3),!0}function na(e){switch(e){case Zt.RUNNING:return"text-info";case Zt.COMPLETED:return"text-success";case Zt.FAILED:return"text-destructive";case Zt.TERMINATED:case Zt.CANCELED:return"text-attention";default:return"text-muted"}}function ra(e){switch(e){case Zt.RUNNING:return"Running";case Zt.COMPLETED:return"Completed";case Zt.FAILED:return"Failed";case Zt.CONTINUED_AS_NEW:return"Continued As New";case Zt.TERMINATED:return"Terminated";case Zt.TIMED_OUT:return"Timed Out";case Zt.CANCELED:return"Canceled";default:return"Unknown"}}class sa extends Ke{labelOf(e){return e.label}idOf(e){return e.id}renderOption(n){return t("div",{children:[e("div",{className:"font-medium",children:n.label}),e("p",{className:"text-sm text-gray-500 dark:text-gray-400 mt-1",children:n.description})]})}}function aa({isOpen:n,onClose:r,onConfirm:s,isLoading:a,uploadedFileName:i}){const o=[{id:"update",label:"Update current version",description:i?"Replace the content file and modify properties directly in the current revision.":"Modify the properties directly in the current revision."},{id:"new-version",label:"Create new version",description:i?"Create a new revision with the replacement file while preserving the original.":"Create a new revision with these property changes while preserving the original."}],l=i?o[1]:o[0],[d,m]=c(l),[u,p]=c(""),h=new sa;g(()=>{n&&(m(l),p(""))},[n,i]);const f="new-version"===d?.id;return t(Ve,{isOpen:n,onClose:r,className:"sm:max-w-md",children:[e(We,{children:"Save Changes"}),e(qe,{children:t("div",{className:"space-y-4",children:[i&&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:["You're about to replace the content file with: ",e("span",{className:"font-bold",children:i})]})}),e("p",{className:"text-sm text-mixer-muted/5",children:"How would you like to save these changes?"}),e(Be,{adapter:h,options:o,value:d,onChange:e=>{m(e)},gap:"gap-4"}),f&&e(He,{label:"Version Label (Optional)",description:"Optional label for the new version.",className:"mt-3 pl-8",children:e(Ge,{value:u,onChange:p,placeholder:"e.g., v1.2, approved, post-review",className:"w-full"})})]})}),t(Je,{children:[e(De,{variant:"secondary",onClick:r,disabled:a,children:"Cancel"}),e(De,{variant:"primary",onClick:async()=>{await s(f,f?u:void 0)},isLoading:a,children:"Save"})]})]})}function ia({isOpen:r,onClose:s,object:a,refetch:i}){const{client:o,store:l}=Te(),d=Ae(),{theme:m}=Ye(),p=bn(),[h,f]=c(!1),[b,y]=c(""),[v,x]=c(!1),[w,N]=c(null),k=u(void 0),[C,S]=c(null),[_,j]=c(null);g(()=>{r&&(y(JSON.stringify(a.properties||{},null,2)),a.type?.id&&async function(e){try{const t=await l.types.retrieve(e);t.object_schema&&S(t.object_schema)}catch(e){console.error("Failed to fetch JSON schema:",e)}}(a.type.id))},[r,a]);return t(n,{children:[t(Ve,{isOpen:r,onClose:s,className:"sm:max-w-[90%] md:max-w-[80%] lg:max-w-[75%] xl:max-w-[70%]",children:[e(We,{children:"Edit Properties"}),t(qe,{children:[t("div",{className:"mb-2 text-sm text-gray-500",children:[a.type?.name?t("span",{children:["Editing properties for object type: ",e("strong",{children:a.type.name})]}):e("span",{children:"Editing properties for generic document"}),C&&e("span",{className:"ml-2 text-green-600",children:"(JSON schema validation enabled)"})]}),e("div",{className:"h-[75vh] border rounded-md overflow-hidden",children:e(kn,{value:b,language:"json",editorRef:k,onChange:e=>{return t=e.state.doc.toString(),void y(t);var t},beforeMount:e=>{C&&e.languages.json.jsonDefaults.setDiagnosticsOptions({validate:!0,schemas:[{uri:"http://myserver/object-schema.json",fileMatch:["*"],schema:C}]})},theme:"dark"===m?"vs-dark":"vs"})})]}),t(Je,{children:[e(De,{variant:"secondary",onClick:s,children:"Cancel"}),e(De,{variant:"primary",onClick:function(){if(!k.current)return;const e=k.current.getValue();try{const t=JSON.parse(e);N(t),x(!0)}catch(e){d({status:"error",title:"Invalid JSON",description:"Please fix the JSON syntax errors before saving.",duration:5e3})}},children:"Save Changes"})]})]}),e(aa,{isOpen:v,onClose:function(){x(!1)},onConfirm:async function(e,t){try{f(!0);const n=w||JSON.parse(b);if(e){const e=await o.objects.update(a.id,{properties:n},{createRevision:!0,revisionLabel:t});e.id!==a.id&&j(e.id),d({status:"success",title:"New version created",description:"A new version with updated properties has been created.",duration:2e3}),x(!1),s(),e.id!==a.id&&setTimeout(()=>{p(`/objects/${e.id}`),d({status:"info",title:"Viewing New Version",description:t?`Now viewing version '${t}'`:"Now viewing the new version",duration:3e3})},100)}else await l.objects.update(a.id,{properties:n}),d({status:"success",title:"Properties updated",description:"The object properties have been updated successfully.",duration:2e3}),i&&await i(),x(!1),s()}catch(e){d({status:"error",title:"Error updating properties",description:e.message||"An error occurred while updating the properties.",duration:5e3}),f(!1)}},isLoading:h})]})}const oa=131072;function la({client:e,toast:t}){const[n,r]=c(!1),s=p(async(n,s)=>{if(n){r(!0);try{ca((await e.files.getDownloadUrlWithOptions({file:n,name:s})).url,s)}catch(e){t({status:"error",title:"Download failed",description:e instanceof Error?e.message:"Failed to get download URL",duration:5e3})}finally{r(!1)}}},[e,t]),a=p((e,t)=>{e&&ca(e,t)},[]),i=p(async(t,n)=>{const r="store"in e?e.store:e,s=await r.rendering.render(t);if(s.download_url)ca(s.download_url,n);else{if(!s.file_uri)throw new Error("No download URL or file URI in response");ca((await e.files.getDownloadUrlWithOptions({file:s.file_uri,name:n})).url,n)}},[e]);return{downloadFromContentSource:s,downloadFromUrl:a,renderDocument:p(async(e,n)=>{r(!0);try{const r=`${n.title||"document"}.${n.format}`;await i({object_id:e,format:n.format,title:n.title,pandoc_options:n.pandocOptions},r),t({status:"success",title:"Document exported",description:`Successfully exported to ${n.format.toUpperCase()}`,duration:2e3})}catch(e){t({status:"error",title:"Export failed",description:e instanceof Error?e.message:"Failed to export document",duration:5e3})}finally{r(!1)}},[i,t]),renderContent:p(async(e,n)=>{r(!0);try{const r=`${n.title||"export"}.${n.format}`;await i({content:e,format:n.format,title:n.title,artifact_run_id:n.artifactRunId,pandoc_options:n.pandocOptions},r),t({status:"success",title:"Content exported",description:`Successfully exported to ${n.format.toUpperCase()}`,duration:2e3})}catch(e){t({status:"error",title:"Export failed",description:e instanceof Error?e.message:"Failed to export content",duration:5e3})}finally{r(!1)}},[i,t]),isDownloading:n}}function ca(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),s=document.createElement("a");s.href=r,s.download=t||da(e),s.style.display="none",document.body.appendChild(s),s.click(),setTimeout(()=>{document.body.removeChild(s),URL.revokeObjectURL(r)},100)}).catch(()=>{const n=document.createElement("a");n.href=e,n.download=t||da(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 da(e){try{const t=new URL(e).pathname.split("/");return t[t.length-1]||"download"}catch{return"download"}}const ma=["image/jpeg","image/jpg","image/png","image/gif","image/webp","image/svg+xml"],ua=["video/mp4","video/webm"],pa=["audio/mp4","audio/m4a","audio/x-m4a","audio/mpeg","audio/ogg","audio/wav","audio/webm"],ha="h-[calc(100vh-208px)]",ga="h-[calc(100vh-228px)]",fa="h-[calc(100vh-218px)]",ba="max-h-[calc(100vh-268px)]";function ya(e){return e===Xt.created||e===Xt.processing}function va(e){return e.metadata?.content_processor?.type}function xa(e){return e?"":"hidden"}var wa;function Na({object:r,loadText:s,refetch:a}){const i=Ae(),o=async(e,t)=>{try{await navigator.clipboard.writeText(e),i({status:"success",title:("text"===t?"Content":"Properties")+" copied",description:`Successfully copied ${t} to clipboard`,duration:2e3})}catch(e){console.error(`Failed to copy ${t}:`,e),i({status:"error",title:"Copy failed",description:`Failed to copy ${t} to clipboard`,duration:5e3})}};return e(n,{children:t(Re,{direction:"horizontal",className:ha,children:[e(Le,{className:"min-w-[100px]",children:e(ka,{object:r,refetch:a??(()=>Promise.resolve()),handleCopyContent:o})}),e(Me,{withHandle:!0}),e(Le,{className:"min-w-[100px]",children:e(Ca,{object:r,loadText:s??!1,handleCopyContent:o,refetch:a})})]})})}function ka({object:r,refetch:s,handleCopyContent:a}){const[i,o]=c(!1),[l,d]=c(!1);return t(n,{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(De,{variant:""+(i?"ghost":"primary"),size:"sm",alt:"Preview properties",onClick:()=>o(!i),children:"Properties"}),e(De,{variant:""+(i?"primary":"ghost"),size:"sm",alt:"View in JSON format",onClick:()=>o(!i),children:"JSON"})]}),t("div",{className:"flex items-center gap-2",children:[r.properties&&e(De,{variant:"ghost",size:"sm",title:"Copy properties",onClick:()=>a(JSON.stringify(r.properties,null,2),"properties"),children:e(x,{className:"size-4"})}),e(De,{variant:"ghost",size:"sm",onClick:()=>{d(!0)},title:"Edit properties",className:"flex items-center gap-2",children:e(H,{className:"size-4"})})]})]}),r.properties?e("div",{className:`${ga} overflow-auto px-2`,children:e(Cn,{value:r.properties,viewCode:i})}):e("div",{className:`${ga} overflow-auto px-2`,children:e("div",{children:"No properties defined"})}),e(ia,{isOpen:l,onClose:()=>{d(!1)},object:r,refetch:s})]})}function Ca({object:n,loadText:r,handleCopyContent:s,refetch:a}){const i=n?.metadata?.type===en.Image,o=n?.metadata?.type===en.Video,l=n?.metadata?.type===en.Audio,d="application/pdf"===n?.content?.type,m=!!n?.content?.type&&Ys(n.content.type),h=ya(n?.status),f=!(!n.transcript||!o&&!l),b=n.metadata,y=b?.renditions?.find(e=>e.name===Kt),[v,x]=c(o?wa.Video:l?wa.Audio:i?wa.Image:wa.Text),{fullText:w,displayText:N,isLoading:k,isCropped:C}=function(e,t,n=!1){const{store:r}=Te(),[s,a]=c(t),[i,o]=c(()=>t&&t.length>oa?t.substring(0,oa):t),[l,d]=c(!1),[m,u]=c(()=>!!t&&t.length>oa),h=p(()=>{d(!0),r.objects.getObjectText(e).then(e=>{a(e.text),e.text&&e.text.length>oa?(o(e.text.substring(0,oa)),u(!0)):(o(e.text),u(!1))}).catch(e=>{console.error("Failed to load text",e),a(void 0),o(void 0),u(!1)}).finally(()=>{d(!1)})},[e,r]);return g(()=>{t&&t.length>oa?(a(t),o(t.substring(0,oa)),u(!0)):(a(t),o(t),u(!1)),n&&!t&&h()},[e,t,n,h]),{fullText:s,displayText:i,isLoading:l,isCropped:m,loadText:h}}(n.id,n.text,r),S=(d||m)&&h,{progress:_,status:j,outputFormat:I,isComplete:P}=function(e,t){const{client:n}=Te(),[r,s]=c(),[a,i]=c(),[o,l]=c(),[d,m]=c(!1);return g(()=>{if(!t)return;let r=!1;return function t(){r||n.objects.analyze(e).getStatus().then(e=>{s(e.progress),i(e.status),l(e.output_format??e.progress?.output_format),e.status===Zt.RUNNING?r||setTimeout(t,2e3):m(!0)}).catch(()=>{r||setTimeout(t,1e4)})}(),()=>{r=!0}},[t,e,n]),{progress:r,status:a,outputFormat:o,isComplete:d}}(n.id,S),{pdfUrl:T,isConverting:z,error:A,triggerConversion:D}=function(e,t){const{client:n}=Te(),[r,s]=c(),[a,i]=c(!1),[o,l]=c(),d=p(async()=>{if(!t||a)return;i(!0),l(void 0);const r=async t=>{try{const a=await n.objects.getRendition(e,{format:Qt.pdf,generate_if_missing:t,sign_url:!0,block_on_generation:!1});"generating"===a.status?setTimeout(()=>r(!1),5e3):"found"===a.status&&a.renditions?.length?(s(a.renditions[0]),i(!1)):"failed"===a.status&&(l("PDF conversion failed"),i(!1))}catch(e){console.error("Failed to convert Office document to PDF:",e),l("Failed to convert to PDF"),i(!1)}};await r(!0)},[e,t,a,n]);return{pdfUrl:r,isConverting:a,error:o,triggerConversion:d}}(n.id,m);g(()=>{P&&j===Zt.COMPLETED&&a?.()},[P,j,a]);const F=(d||m)&&h&&!P&&j===Zt.RUNNING,E=u(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:[i&&e(De,{variant:v===wa.Image?"primary":"ghost",size:"sm",alt:"View Image",onClick:()=>x(wa.Image),children:"Image"}),o&&e(De,{variant:v===wa.Video?"primary":"ghost",size:"sm",alt:"View Video",onClick:()=>x(wa.Video),children:"Video"}),l&&e(De,{variant:v===wa.Audio?"primary":"ghost",size:"sm",alt:"View Audio",onClick:()=>x(wa.Audio),children:"Audio"}),f&&e(De,{variant:v===wa.Transcript?"primary":"ghost",size:"sm",alt:"View Transcript",onClick:()=>x(wa.Transcript),children:"Transcript"}),e(De,{variant:v===wa.Text?"primary":"ghost",size:"sm",alt:"View Text",onClick:()=>x(wa.Text),children:"Text"}),d&&e(De,{variant:v===wa.Pdf?"primary":"ghost",size:"sm",alt:"View PDF",onClick:()=>x(wa.Pdf),children:"PDF"}),m&&e(De,{variant:v===wa.Pdf?"primary":"ghost",size:"sm",alt:"View as PDF",onClick:()=>{x(wa.Pdf),y||T||z||D()},disabled:z,children:z?e(Ue,{size:"sm"}):"PDF"})]}),e(Aa,{object:n})]}),v===wa.Text&&!F&&e(Sa,{object:n,text:N,fullText:w,handleCopyContent:s,textContainerRef:E}),v===wa.Pdf&&m&&(y||T)&&e(Da,{object:n,pdfRendition:y,officePdfUrl:T})]}),e("div",{className:xa(v===wa.Image),children:e(ja,{object:n})}),e("div",{className:xa(v===wa.Video),children:e(Ia,{object:n})}),e("div",{className:xa(v===wa.Audio),children:e(Pa,{object:n})}),f&&e("div",{className:xa(v===wa.Transcript),children:e(za,{object:n,handleCopyContent:s})}),d&&e("div",{className:xa(v===wa.Pdf),children:e(Fa,{object:n})}),m&&e("div",{className:xa(v===wa.Pdf),children:e(Ea,{pdfRendition:y,officePdfUrl:T,officePdfConverting:z,officePdfError:A,onConvert:D})}),F&&e("div",{className:xa(v===wa.Text),children:e($a,{progress:_,status:j,outputFormat:I})}),e("div",{className:xa(v===wa.Text&&!F&&k),children:e("div",{className:"flex justify-center items-center flex-1",children:e(Ue,{size:"lg"})})}),e("div",{className:xa(v===wa.Text&&!F&&!k),children:e(_a,{object:n,text:N,isTextCropped:C,textContainerRef:E})})]})}function Sa({object:r,text:s,fullText:a,handleCopyContent:i}){const{client:o}=Te(),l=Ae(),c=r.content,{renderDocument:d,isDownloading:m}=la({client:o,toast:l}),u=c&&c.type&&"text/markdown"===c.type,p=va(r),h=async e=>{m||(l({status:"info",title:`Preparing ${e.toUpperCase()}`,description:"Rendering your document...",duration:2e3}),await d(r.id,{format:e,title:r.name||"document"}))};return e(n,{children: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:[a&&t(n,{children:[e(De,{variant:"ghost",size:"sm",title:"Copy text",onClick:()=>i(a,"text"),children:e(x,{className:"size-4"})}),e(De,{variant:"ghost",size:"sm",title:"Download text",onClick:e=>{if(e.preventDefault(),e.stopPropagation(),!a)return;let t="txt",n="text/plain";"xml"===p?(t="xml",n="text/xml"):("markdown"===p||u)&&(t="md",n="text/markdown");const s=new Blob([a],{type:n}),i=URL.createObjectURL(s),o=`${r.name||"document"}.${t}`,l=document.createElement("a");l.href=i,l.download=o,l.style.display="none",setTimeout(()=>{l.click(),URL.revokeObjectURL(i)},0)},children:e(w,{className:"size-4"})})]}),u&&s&&t(n,{children:[t(De,{variant:"ghost",size:"sm",onClick:()=>h(Qt.docx),disabled:m,className:"flex items-center gap-2",children:[m?e(Ue,{size:"sm"}):e(w,{className:"size-4"}),"DOCX"]}),t(De,{variant:"ghost",size:"sm",onClick:()=>h(Qt.pdf),disabled:m,className:"flex items-center gap-2",children:[m?e(Ue,{size:"sm"}):e(w,{className:"size-4"}),"PDF"]})]})]})})})}!function(e){e.Text="text",e.Image="image",e.Video="video",e.Audio="audio",e.Pdf="pdf",e.Transcript="transcript"}(wa||(wa={}));const _a=h(({object:r,text:s,isTextCropped:a,textContainerRef:i})=>{const o=r.content,l=ya(r?.status),c="xml"===va(r),d=o&&o.type&&("text/markdown"===o.type||"text/plain"===o.type),m=!c&&(d||function(e){return!!e&&(e.includes("\n# ")||e.includes("\n## ")||e.includes("\n### ")||e.includes("\n* ")||e.includes("\n- ")||e.includes("\n+ ")||e.includes(")}(s));return s?t(n,{children:[a&&e("div",{className:"px-2 py-2 bg-attention/10 border-l-4 border-attention mx-2 mb-2 rounded",children:t("div",{className:"flex items-center gap-2 text-attention",children:[e(B,{className:"size-4"}),e("span",{className:"text-sm font-semibold",children:"Showing first 128K characters only"})]})}),e("div",{className:`max-w-7xl px-2 ${fa} overflow-auto`,ref:i,children:c?e("div",{className:"px-4 py-2",children:e(wn,{xml:s,collapsible:!0})}):m?e("div",{className:"vprose prose-sm p-1",children:e(vn,{components:{a:({node:t,...n})=>{const r=n.href||"";return r.includes("/store/objects/")?e(yn,{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,...s})=>{const a=/language-(\w+)/.exec(n||"");return e("code",{...s,className:a?"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:s})}):e("pre",{className:"text-wrap bg-muted text-muted p-2",children:s})})]}):e("div",{className:"px-2",children:e("div",{children:l?"Extracting content...":"No content"})})});function ja({object:t}){const{client:n}=Te(),[r,s]=c(),a=t.content,i=t.metadata&&t.metadata.type===en.Image;return g(()=>{if(i){s(void 0);(async()=>{const e=a?.type&&ma.includes(a.type);try{const r=await n.objects.getRendition(t.id,{format:Yt.jpeg,generate_if_missing:!1,sign_url:!0});if("found"===r.status&&r.renditions?.length)s(r.renditions[0]);else if(e){const e=await n.files.getDownloadUrl(t.content.source);s(e.url)}}catch(r){if(e){const e=await n.files.getDownloadUrl(t.content.source);s(e.url)}}})()}},[t.id,i,a?.type,a?.source,n]),e("div",{className:"mb-4 px-2",children:r?e("img",{src:r,alt:t.name,className:"w-full object-contain"}):e(Ue,{size:"md"})})}function Ia({object:n}){const{client:r}=Te(),[s,a]=c(),[i,o]=c(),[l,d]=c(!0),m=n.content,u=n.metadata?.type===en.Video,p=n.metadata,h=p?.renditions||[],f=h.find(e=>"video/mp4"===e.content.type)||h.find(e=>"video/webm"===e.content.type),b=m?.type&&ua.includes(m.type),y=h.find(e=>e.name===tn);return g(()=>{a(void 0),o(void 0),d(!0)},[n.id]),g(()=>{(async()=>{if(y?.content?.source)try{const e=await r.files.getDownloadUrl(y.content.source);o(e.url)}catch(e){console.error("Failed to load poster image",e)}})()},[y,r]),g(()=>{if(u&&(f?.content?.source||b)){(async()=>{try{let e;f?.content?.source?e=await r.files.getDownloadUrl(f.content.source):b&&m?.source&&(e=await r.files.getDownloadUrl(m.source)),e&&a(e.url)}catch(e){console.error("Failed to get video URL",e)}finally{d(!1)}})()}else d(!1)},[u,f,b,m?.source,r]),e("div",{className:"mb-4 px-2",children:f||b?l?e("div",{className:"flex justify-center items-center h-[400px]",children:e(Ue,{size:"md"})}):s?e("video",{src:s,poster:i,controls:!0,className:`w-full ${ba} object-contain`,children:"Your browser does not support the video tag."}):e("div",{className:"flex justify-center items-center h-[400px] text-muted",children:"Failed to load video"}):e("div",{className:"flex justify-center items-center h-[400px] text-muted",children:t("div",{className:"text-center",children:[e("p",{children:"No web-compatible video rendition available"}),e("p",{className:"text-sm mt-2",children:"MP4 or WebM format required"})]})})})}function Pa({object:n}){const{client:r}=Te(),[s,a]=c(),[i,o]=c(!0),l=n.content,d=n.metadata?.type===en.Audio,m=n.metadata,u=(m?.renditions||[]).find(e=>e.name===nn),p=l?.type&&pa.includes(l.type);return g(()=>{a(void 0),o(!0)},[n.id]),g(()=>{if(d&&(u?.content?.source||p)){(async()=>{try{let e;u?.content?.source?e=await r.files.getDownloadUrl(u.content.source):p&&l?.source&&(e=await r.files.getDownloadUrl(l.source)),e&&a(e.url)}catch(e){console.error("Failed to get audio URL",e)}finally{o(!1)}})()}else o(!1)},[d,u,p,l?.source,r]),e("div",{className:"mb-4 px-2",children:u||p?i?e("div",{className:"flex justify-center items-center h-[200px]",children:e(Ue,{size:"md"})}):s?t("div",{className:"flex flex-col items-center gap-4",children:[e("audio",{src:s,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: ",Ta(m.duration)]})]}):e("div",{className:"flex justify-center items-center h-[200px] text-muted",children:"Failed to load audio"}):e("div",{className:"flex justify-center items-center h-[200px] text-muted",children:t("div",{className:"text-center",children:[e("p",{children:"No web-compatible audio rendition available"}),e("p",{className:"text-sm mt-2",children:"MP3, M4A, OGG, WAV, or WebM format required"})]})})})}function Ta(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 za({object:n,handleCopyContent:r}){const s=n.transcript,a=s?.text,i=s?.segments,o=a||(i?i.map(e=>e.text).join(" "):""),l=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:o&&e(De,{variant:"ghost",size:"sm",title:"Copy transcript",onClick:()=>r(o,"text"),children:e(x,{className:"size-4"})})}),e("div",{className:`${fa} overflow-auto px-2`,children:i&&i.length>0?e("div",{className:"space-y-2",children:i.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:[l(n.start),n.end&&` - ${l(n.end)}`]}),e("span",{className:"flex-1",children:n.text})]},r))}):a?e("pre",{className:"text-wrap bg-muted text-muted p-2 whitespace-pre-wrap",children:a}):e("div",{className:"text-muted",children:"No transcript available"})})]})}function Aa({object:r}){const[s,a]=c(!1),i=va(r);return"xml"===i||"markdown"===i?t(n,{children:[e(De,{variant:"ghost",size:"sm",onClick:()=>a(!0),title:"Side by side view",children:e(G,{className:"size-4"})}),s&&e(Ze,{children:e($s,{objectId:r.id,onClose:()=>a(!1)})})]}):null}function Da({object:t,pdfRendition:n,officePdfUrl:r}){const{client:s}=Te(),a=Ae(),[i,o]=c(!1);return e("div",{className:"flex items-center gap-2",children:e(De,{variant:"ghost",size:"sm",onClick:async()=>{o(!0);try{let e=r;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),a({status:"error",title:"Download failed",description:"Failed to download the PDF file",duration:5e3})}finally{o(!1)}},disabled:i,title:"Download PDF",children:i?e(Ue,{size:"sm"}):e(w,{className:"size-4"})})})}function Fa({object:t}){return e("div",{className:fa,children:e(Rs,{object:t,className:"h-full"})})}function Ea({pdfRendition:n,officePdfUrl:r,officePdfConverting:s,officePdfError:a,onConvert:i}){return s?t("div",{className:"flex flex-col justify-center items-center flex-1 gap-2",children:[e(Ue,{size:"lg"}),e("span",{className:"text-muted",children:"Converting to PDF..."})]}):a?t("div",{className:"flex flex-col justify-center items-center flex-1 gap-2 text-destructive",children:[e(B,{className:"size-8"}),e("span",{children:a})]}):e("div",n?.content?.source?{className:fa,children:e(Rs,{source:n.content.source,className:"h-full"})}:r?{className:fa,children:e(Rs,{url:r,className:"h-full"})}:{className:"flex flex-col justify-center items-center flex-1 gap-2",children:e(De,{onClick:i,children:"Convert to PDF"})})}function $a({progress:r,status:s,outputFormat:a}){const i=na(s),o=ra(s),l="xml"===a,c=null==r?.percent||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(Oa,{name:l?"Analyze Layouts":"Analyze Page",progress:r.pages}),l&&t(n,{children:[e(Oa,{name:"Extract Tables",progress:r.tables}),e(Oa,{name:"Describe Images",progress:r.images}),e(Oa,{name:"Process Visually",progress:r.visuals})]})]}),t("div",{className:"pt-2 text-sm text-muted",children:["Progress: ",c,"%",e("span",{className:"px-2",children:"•"}),e("span",{className:i,children:o}),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(Sn,{percent:c})]}),!r&&t("div",{className:"flex items-center gap-2 text-muted",children:[e(Ue,{size:"sm"}),e("span",{children:"Loading processing status..."})]})]})}function Oa({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]})]})}function Ra({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(Qe,{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(Xe,{className:"bg-muted h-[2px]"}),t(et,{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 La({selection:n,document:r,onSelectionChange:s,onRowClick:a,previewObject:i,selectedObject:o}){const{client:l}=Te(),[d,m]=c(void 0),[u,p]=c(void 0),[h,f]=c(void 0);return g(()=>{r?.content&&ea(l,r,m,p,f)},[r]),t(Qe,{className:"relative flex flex-col border h-fit w-full "+(o?.id===r.id?"border-attention border-4":""),onClick:()=>a&&a(r),children:[n&&e("div",{className:"absolute top-2 left-2 z-10 flex flex-col items-center gap-1",children:e("input",{checked:n.isSelected(r.id),type:"checkbox",onChange:e=>{e.stopPropagation(),s(r,e)},onClick:e=>e.stopPropagation()})}),e("div",{className:"absolute top-1 right-1 z-10 flex flex-col items-center",children:e(De,{variant:"ghost",size:"sm",title:"Preivew Object",onClick:e=>{e.stopPropagation(),i?.(r.id)},children:e(J,{className:"size-4 "+("ready"===h?"text-muted":"text-white")})})}),d&&"ready"==h?e("img",{src:d,alt:u,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:h}),e(Xe,{className:"bg-gray-200 h-[2px]"}),t(et,{className:"p-2 flex flex-col",children:[t("div",{className:"flex flex-col overflow-hidden",children:[e(Ee,{placement:"top",description:r.properties?.title??r.name,children:e("h3",{className:"text-start font-medium leading-none truncate",children:r.properties?.title??r.name})}),r?.type?.name?e(Ee,{placement:"bottom",size:"xs",description:r?.type?.name,children:e("p",{className:"text-start text-xs text-muted truncate",children:r?.type?.name})}):e("p",{className:"text-xs text-muted",children:" "})]}),r.score&&t("div",{className:"text-xs text-muted w-full flex justify-end",children:["Score: ",r.score.toFixed(4)??"-"]})]})]})}function Ma(e){return`${e._id} (${e.count})`}function Ua(e){return`${e.name} (${e.count})`}function Va({search:t,buckets:n,name:r,placeholder:s,className:a}){const i=t.getFilterValue(r),o=n?.find(e=>JSON.stringify(e._id)===JSON.stringify(i));return e(tt,{filterBy:"_id",className:a,isClearable:!0,optionLabel:Ma,options:n,value:o,onChange:e=>{t.setFilterValue(r,e?._id)},by:"_id",placeholder:s})}function Wa({search:t,name:n,placeholder:r,className:s}){const[a,i]=c([]);return g(()=>{t.setFilterValue(n,a)},[a]),e(nt,{className:s,value:a,onChange:i,placeholder:r})}class qa{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 Ba=d({registry:void 0,isLoading:!1,load:()=>Promise.resolve(),reload:()=>Promise.resolve()});function Ha({children:t}){const{store:n,project:r}=Te(),[s,a]=c(),[i,o]=c(!1),l=u(!1),d=p(async()=>{if(r&&!l.current){l.current=!0,o(!0);try{const e=await n.types.catalog.list({layout:!0});a(new qa(e))}catch(e){console.error("Failed to fetch types",e)}finally{o(!1),l.current=!1}}},[n,r]),m=p(async()=>(l.current=!1,d()),[d]);return g(()=>{a(void 0),l.current=!1},[r]),e(Ba.Provider,{value:{registry:s,isLoading:i,load:d,reload:m},children:t})}function Ga(){const e=m(Ba);return g(()=>{e.registry||e.isLoading||e.load()},[e.registry,e.isLoading]),e}function Ja(e){return`${e.name} (${e.count})`}function Ka({search:t,buckets:n,placeholder:r="Filter by Type",className:s}){const[a,i]=c([]),{registry:o}=Ga(),l=t.getFilterValue("type");g(()=>{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 d=a?.find(e=>e._id===l);return e(tt,{filterBy:"name",className:s,isClearable:!0,optionLabel:Ja,options:a,value:d,onChange:e=>{t.setFilterValue("type",e?._id)},by:"_id",placeholder:r})}function Ya({buckets:e,name:t,placeholder:n,type:r,multiple:s}){return function({buckets:e,name:t,placeholder:n,type:r="select",multiple:s=!1}){return{name:t,options:e.map(e=>({label:Ma(e),value:e._id})),type:r,multiple:s,placeholder:`${n??`${t.charAt(0).toUpperCase()+t.slice(1)}`}`,allowCreate:!1}}({buckets:e,name:t,placeholder:n,type:r,multiple:s})}function Za({buckets:n,typeRegistry:r,type:s="select",multiple:a=!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:s,multiple:a,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:"ml-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)}}}const Qa={},Xa={},ei={};function ti(e){const{client:t}=Te();return $e(()=>{let n=Qa[e];return n||(n=t.users.retrieve(e).then(e=>e),Qa[e]=n),n},[e])}function ni(e){const{client:t}=Te();return $e(()=>{let n=Xa[e];return n||(n=t.iam.groups.retrieve(e).then(e=>e),Xa[e]=n),n},[e])}function ri(e){const{client:t}=Te();return $e(()=>{let n=ei[e];return n||(n=t.apikeys.retrieve(e).then(e=>e),ei[e]=n),n},[e])}function si(){return e("div",{className:"size-8"})}function ai({showTitle:n=!1,size:r="md"}){return e(hi,{title:"System User",description:"The system user is used to initialize built-in objects.",children:t("div",{className:"flex gap-2 items-center",children:[e(rt,{src:"/icon.svg",size:r}),n&&e("div",{className:"text-sm font-semibold pl-2",children:"System User"})]})})}function ii({accountId:r,showTitle:s=!1,size:a="md"}){const i=t(n,{children:[e("div",{children:"This user is used by robots like workflow workers."}),t("div",{className:"text-gray-800 dark:text-gray-500 text-sm",children:[e("span",{className:"font-semibold",children:"ID:"})," ",r]})]});return e(hi,{title:"Service Account",description:i,children:t("div",{className:"flex flex-row items-center gap-2",children:[e(rt,{src:"/cloud.svg",name:"SA",color:"bg-amber-500",className:"px-[5px] text-white",size:a}),s&&t("div",{className:"text-sm font-semibold pl-2 truncate",children:["Service Account : ",r]})]})})}function oi({agentId:r,onBehalfOfType:s,onBehalfOfId:a,showTitle:i=!1,size:o="md",isScheduleAgent:l=!1}){const c="user"===s&&a,d="apikey"===s&&a,m=ti(a||""),u=ri(a||""),p=c?m.data:void 0,h=d?u.data:void 0,g=p?"Agent on behalf of":h?"Agent on behalf of API key":"Service Account",f=l?`Schedule ${g}`:g,b=t("div",{className:"space-y-2",children:[p&&e(n,{children:t("div",{className:"flex items-center gap-2",children:[e(rt,{src:p.picture,name:p.name,size:"sm"}),t("div",{children:[e("div",{className:"font-medium",children:p.name||p.email}),p.email&&p.name&&e("div",{className:"text-xs text-muted-foreground",children:p.email})]})]})}),h&&e(n,{children:t("div",{children:[e("div",{className:"font-medium",children:h.name}),t("div",{className:"text-xs text-muted-foreground",children:["Key ID: ",h.id]})]})}),!p&&!h&&t(n,{children:[e("div",{children:"This user is used by robots like workflow workers."}),t("div",{className:"text-gray-800 dark:text-gray-500 text-sm",children:[e("span",{className:"font-semibold",children:"ID:"})," ",r]})]})]});return e(hi,{title:f,description:b,children:t("div",{className:"flex items-center gap-2",children:[t("div",{className:"flex items-center -space-x-2",children:[e(rt,{src:"/cloud.svg",color:"bg-amber-500",className:"px-[5px] text-white border-2 border-white dark:border-gray-800",size:o}),p&&e(rt,{src:p.picture,name:p.name,size:o,className:"border-2 border-white dark:border-gray-800"}),h&&e(rt,{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:p?`Agent (${p.name||p.email})`:h?`Agent (${h.name})`:g})]})})}function li({title:t="Error",error:n,showTitle:r=!1,size:s="md"}){return e(di,{title:t,message:"string"==typeof n?n:n.message,color:"bg-red-500",showTitle:r,size:s})}function ci({userRef:t,showTitle:n=!1,size:r="md"}){if(!t)return e(di,{title:"Unknown User",message:"User information is not available.",showTitle:n,size:r});const s=t.split(":"),a=s[0];switch(a){case rn.User:return e(ui,{userId:s[1],showTitle:n,size:r});case rn.Group:return e(mi,{userId:s[1],showTitle:n,size:r});case"system":return e(ai,{showTitle:n,size:r});case rn.ServiceAccount:return e(ii,{accountId:s.slice(1).join(":"),showTitle:n,size:r});case rn.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(oi,{agentId:t,onBehalfOfType:a,onBehalfOfId:i,showTitle:n,size:r})}case rn.Schedule:{const t=s[1],a=s[2],i=s[3];return e(oi,{agentId:t,onBehalfOfType:a,onBehalfOfId:i,showTitle:n,size:r,isScheduleAgent:!0})}case rn.ApiKey:return e(pi,{keyId:s[1],size:r,showTitle:n});default:return e(li,{title:"Unknown User",error:`Invalid user ref type: ${a}`,showTitle:n,size:r})}}function di({title:n,message:r,color:s,size:a="md",showTitle:i=!1}){return e(hi,{title:n,description:r,children:t("div",{className:"flex flex-row items-center gap-2",children:[e(rt,{color:s,size:a}),i&&e("div",{className:"text-sm font-semibold pl-1",children:n})]})})}function mi({userId:n,showTitle:r=!1,size:s="md"}){const{data:a,error:i}=ni(n);if(i)return e(li,{title:"Failed to fetch group",error:i,showTitle:r,size:s});if(!a)return e(si,{});const o=t("div",{className:"space-y-1",children:[a.description&&e("div",{className:"text-sm",children:a.description}),t("div",{className:"text-xs text-muted-foreground",children:["Group ID: ",a.id]}),a.tags&&a.tags.length>0&&e("div",{className:"flex flex-wrap gap-1",children:a.tags.map(t=>e("span",{className:"px-1.5 py-0.5 bg-muted rounded text-xs",children:t},t))})]});return e(hi,{title:a.name||"Unnamed Group",description:o,children:t("div",{className:"flex flex-row items-center gap-2",children:[e(K,{className:"size-6 text-indigo-500",size:s}),r&&e("div",{className:"text-sm font-semibold pl-2",children:a.name||"Unnamed Group"})]})})}function ui({userId:n,showTitle:r=!1,size:s="md"}){const{data:a,error:i}=ti(n);if(i)return e(li,{title:"Failed to fetch user",error:i,showTitle:r,size:s});if(!a)return e(si,{});const o=e("div",{className:"truncate",title:a.email,children:a.email});return e(hi,{title:a.name||a.email||a.username||"unknown",description:o,children:t("div",{className:"flex flex-row items-center gap-2",children:[e(rt,{src:a.picture,name:a.name,color:"bg-indigo-500",size:s}),r&&e("div",{className:"text-sm font-semibold pl-2",children:a.name||a.email||a.username||"unknown"})]})})}function pi({keyId:n,showTitle:r=!1,size:s="md"}){const{client:a}=Te(),{data:i,error:o}=$e(()=>a.apikeys.retrieve(n),[]);if(o)return e(li,{title:"Failed to fetch the apikey",error:o,showTitle:r,size:s});if(!i)return e(si,{});const l=e(rt,{name:"PK",color:"bg-pink-500",size:s}),c=t(st,{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:"Key:"}),e("td",{className:"truncate max-w-0",children:i?.name})]}),t("tr",{children:[e("td",{className:"font-semibold w-20",children:"Account:"}),e("td",{className:"truncate max-w-0",children:i?.account})]}),t("tr",{children:[e("td",{className:"font-semibold w-20",children:"Project:"}),e("td",{className:"truncate max-w-0",children:i?.project.name})]})]});return e(hi,{title:"Private Key",description:c,children:t("div",{className:"flex flex-row items-center gap-2",children:[l,r&&e("div",{className:"text-sm font-semibold",children:i?.name||i?.account||i?.project.name||"unknown"})]})})}function hi({title:n,description:r,children:s}){return t(at,{hover:!0,children:[e(it,{className:"cursor-pointer flex items-center inline-block",children:e("div",{children:s})}),e(ot,{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 gi({buckets:n,name:r,placeholder:s}){return function({buckets:n,name:r,placeholder:s}){const a=n.map(e=>({value:e._id,label:`(${e.count})`}));return{name:r,placeholder:s||`${r.charAt(0).toUpperCase()+r.slice(1)}`,options:a,labelRenderer:r=>{if("Unknown User"===r||!r){const e=n.find(e=>e._id===r);return`Unknown User (${e?.count||0})`}const s=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(ci,{userRef:r,showTitle:!0,size:"sm"})}),t("span",{className:"text-muted-foreground flex-shrink-0",children:["(",s?.count||0,")"]})]})}}}({buckets:n,name:r,placeholder:s})}function fi({search:t,buckets:n,placeholder:r="All Environments",className:s}){const{client:a}=Te(),[i,o]=c([]),l=t.getFilterValue("environment");g(()=>{if(a){const e=n.map(async e=>{let t;return await a.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,a]);const d=i?.find(e=>e._id===l);return e(tt,{filterBy:"name",className:s,isClearable:!0,optionLabel:Ua,options:i,value:d,onChange:e=>{t.setFilterValue("environment",e?._id)},by:"_id",placeholder:r})}function bi(n){const r=[];if(r.push({name:"run_ids",placeholder:"Run ID",type:"text",multiple:!1}),n.interactions){const s=function({buckets:n,name:r,placeholder:s}){return{name:r,placeholder:s,options:n.map(e=>({label:`(${e.count})`,value:e._id})),type:"select",labelRenderer:r=>{const s=n.find(e=>e._id===r),a=s?.name||r;let i="success";if(s?.status)switch(s.status){case sn.published:i="success";break;case sn.archived:i="destructive";break;default:i="attention"}const o=s?.version&&s?.status?`v${s.version} ${s.status}`:s?.status||(s?.version?`v${s.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:a}),o&&e(lt,{variant:i,className:"text-xs w-fit",children:o})]}),t("span",{className:"ml-2 text-xs shrink-0",children:["(",s?.count||0,")"]})]})},filterBy:(e,t)=>{const r=n.find(t=>t._id===e);return(r?.name||e).toLowerCase().includes(t.toLowerCase())}}}({buckets:n.interactions||[],name:"interaction",placeholder:"Interactions"});r.push(s)}if(n.environments){const s=function({buckets:n,name:r}){const s=n.map(e=>({label:`(${e.count})`,value:e._id}));return{name:"environment",placeholder:r.charAt(0).toUpperCase()+r.slice(1),options:s,type:"select",labelRenderer:r=>{const s=n.find(e=>e._id===r);return t("div",{className:"w-full flex items-center",children:[e("span",{className:"text-sm truncate",children:s?.name||r}),t("span",{className:"ml-2 text-xs",children:["(",s?.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(s)}if(r.push({name:"tags",placeholder:"Tags",type:"stringList",multiple:!0}),n.models){const e=Ya({buckets:n.models||[],name:"model"});r.push(e)}if(n.statuses){const e=Ya({buckets:n.statuses||[],name:"status"});r.push(e)}if(n.finish_reason){const e=Ya({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=gi({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});return r.push({name:"workflow_run_ids",placeholder:"Workflow Run ID",type:"text",multiple:!1}),r}function yi(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;r="stringList"===t.type?t.value.map(e=>"string"==typeof e?e:e.value):t.multiple?Array.isArray(t.value)?t.value.map(e=>"object"==typeof e&&e.value?e.value:e):["object"==typeof t.value&&t.value.value?t.value.value:t.value]:Array.isArray(t.value)&&t.value[0]&&"object"==typeof t.value[0]?t.value[0].value:Array.isArray(t.value)&&t.value[0]?t.value[0]:t.value,"run_ids"!==n&&"workflow_run_ids"!==n||Array.isArray(r)||(r=[r]),e.query[n]=r}}),e.search()):e.clearFilters(!0,!1)}}function vi({facets:n,search:r}){const[s,a]=c([]),i=bi(n),o=yi(r);return t(ct,{filterGroups:i,filters:s,setFilters:e=>{const t="function"==typeof e?e(s):e;a(t),o(t)},children:[t("div",{className:"flex justify-between mb-1",children:[e(dt,{}),e(De,{onClick:()=>{r.search()},variant:"outline",title:"Refresh",children:e(Y,{className:"size-5"})})]}),t("div",{className:"flex gap-2 items-center",children:[e(mt,{}),e(ut,{})]})]})}function xi(e){const t=[];if(t.push({placeholder:"Workflow or Run ID",name:"name",type:"text",options:[]}),e.status){const n=Ya({buckets:e.status||[],name:"status",placeholder:"Status"});t.push(n)}if(e.initiated_by){const n=gi({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 wi(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(r="stringList"===t.type?t.value.map(e=>"string"==typeof e?e:e.value):t.multiple?Array.isArray(t.value)?t.value.map(e=>"object"==typeof e&&e.value?e.value:e):["object"==typeof t.value&&t.value.value?t.value.value:t.value]:Array.isArray(t.value)&&t.value[0]&&"object"==typeof t.value[0]?t.value[0].value:Array.isArray(t.value)&&t.value[0]?t.value[0]:t.value,"name"===n)e.query.search_term=r,e.query.name=r;else if("has_reported_errors"===n){const t=Array.isArray(r)?r[0]:r;"true"!==t&&"false"!==t||(e.query[n]="true"===t)}else e.query[n]=r}}),e.search()):e.clearFilters()}}function Ni({facets:n,search:r}){const[s,a]=c([]),i=xi(n),o=wi(r);return e(ct,{filterGroups:i,filters:s,setFilters:e=>{const t="function"==typeof e?e(s):e;a(t),o(t)},children:t("div",{className:"flex gap-2 items-center",children:[e(dt,{}),e(mt,{}),e(ut,{})]})})}function ki(e){const{registry:t}=Ga(),n=[];if(n.push({placeholder:"ID",name:"id",type:"text",options:[]}),n.push({placeholder:"Name",name:"name",type:"text",options:[]}),e.type){const r=Za({buckets:e.type||[],typeRegistry:t,type:"select",multiple:!0});n.push(r)}if(e.status){const t=Ya({buckets: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:e.tags.map(e=>({label:e,value:e}))}),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 Ci(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="object"==typeof t.value[0]?t.value[0].value:t.value[0];r={gte:e,lte:e}}else if(2===t.value.length){r={gte:"object"==typeof t.value[0]?t.value[0].value:t.value[0],lte:"object"==typeof t.value[1]?t.value[1].value:t.value[1]}}}else if(t.multiple)if(Array.isArray(t.value))r=t.value.map(e=>"object"==typeof e&&e.value?e.value:e);else{r=["object"==typeof t.value&&t.value.value?t.value.value:t.value]}else r=Array.isArray(t.value)&&t.value[0]&&"object"==typeof t.value[0]?t.value[0].value:Array.isArray(t.value)&&t.value[0]?t.value[0]:t.value;"name"===n?e.query.name=r:"id"===n?e.query.id=r:e.query[n]=r}}),e.search()):e.clearFilters()}}function Si({facets:n,search:r}){const[s,a]=c([]),i=ki(n),o=Ci(r);return e(ct,{filterGroups:i,filters:s,setFilters:e=>{const t="function"==typeof e?e(s):e;a(t),o(t)},children:t("div",{className:"flex gap-2 items-center",children:[e(dt,{}),e(mt,{}),e(ut,{})]})})}function _i(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 ji(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;r="stringList"===t.type?t.value.map(e=>"string"==typeof e?e:e.value):t.multiple?Array.isArray(t.value)?t.value.map(e=>"object"==typeof e&&e.value?e.value:e):["object"==typeof t.value&&t.value.value?t.value.value:t.value]:Array.isArray(t.value)&&t.value[0]&&"object"==typeof t.value[0]?t.value[0].value:Array.isArray(t.value)&&t.value[0]?t.value[0]:t.value,e.query[n]=r}}),e.search(!0)):e.clearFilters(!0,!0)}}function Ii({facets:n,search:r}){const[s,a]=c([]),i=_i(),o=ji(r);return e(ct,{filterGroups:i,filters:s,setFilters:e=>{const t="function"==typeof e?e(s):e;a(t),o(t)},children:t("div",{className:"flex gap-2 items-center",children:[e(dt,{}),e(mt,{}),e(ut,{})]})})}function Pi(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 Ti(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;r="stringList"===t.type?t.value.map(e=>"string"==typeof e?e:e.value):t.multiple?Array.isArray(t.value)?t.value.map(e=>"object"==typeof e&&e.value?e.value:e):["object"==typeof t.value&&t.value.value?t.value.value:t.value]:Array.isArray(t.value)&&t.value[0]&&"object"==typeof t.value[0]?t.value[0].value:Array.isArray(t.value)&&t.value[0]?t.value[0]:t.value,e.query[n]=r}}),e.search()):e.clearFilters(!0,!1)}}function zi({facets:n,search:r}){const[s,a]=c([]),i=Pi(n),o=Ti(r);return e(ct,{filterGroups:i,filters:s,setFilters:e=>{const t="function"==typeof e?e(s):e;a(t),o(t)},children:t("div",{className:"flex gap-2 items-center",children:[e(dt,{}),e(mt,{}),e(ut,{})]})})}function Ai(e){const{registry:t}=Ga(),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 Di(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;r="stringList"===t.type?t.value.map(e=>"string"==typeof e?e:e.value):t.multiple?Array.isArray(t.value)?t.value.map(e=>"object"==typeof e&&e.value?e.value:e):["object"==typeof t.value&&t.value.value?t.value.value:t.value]:Array.isArray(t.value)&&t.value[0]&&"object"==typeof t.value[0]?t.value[0].value:Array.isArray(t.value)&&t.value[0]?t.value[0]:t.value,e.query[n]=r}}),e.search()):e.clearFilters(!0)}}function Fi({facets:n,search:r}){const[s,a]=c([]),i=Ai(),o=Di(r);return e(ct,{filterGroups:i,filters:s,setFilters:e=>{const t="function"==typeof e?e(s):e;a(t),o(t)},children:t("div",{className:"flex gap-2 items-center",children:[e(dt,{}),e(mt,{}),e(ut,{})]})})}function Ei(e){const t=[];if(e.statuses){const n=Ya({buckets:e.statuses||[],name:"status",placeholder:"Status"});t.push(n)}if(e.initiated_by){const n=gi({buckets:e.initiated_by||[],name:"initiated_by",placeholder:"Initiated By"});t.push(n)}t.push({name:"start",placeholder:"Started After",type:"date",multiple:!1});return t.push({name:"end",placeholder:"Started Before",type:"date",multiple:!1}),t}function $i(e){return t=>{e.clearFilters(!1,!1),t.forEach(t=>{if(t.value&&t.value.length>0){const n=t.name;let r;r=t.multiple?Array.isArray(t.value)?t.value.map(e=>"object"==typeof e&&e.value?e.value:e):["object"==typeof t.value&&t.value.value?t.value.value:t.value]:Array.isArray(t.value)&&t.value[0]&&"object"==typeof t.value[0]?t.value[0].value:Array.isArray(t.value)&&t.value[0]?t.value[0]:t.value,e.query[n]=r}}),e.search()}}function Oi({facets:n,search:r}){const[s,a]=c([]),i=Ei(n),o=$i(r);return e(ct,{filterGroups:i,filters:s,setFilters:e=>{const t="function"==typeof e?e(s):e;a(t),o(t)},children:t("div",{className:"flex justify-between mb-1",children:[t("div",{className:"flex gap-2 items-center",children:[e(dt,{}),e(mt,{}),e(ut,{})]}),e(De,{onClick:()=>{r.search()},variant:"outline",title:"Refresh",children:e(Y,{className:"size-5"})})]})})}class Ri{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 Ri(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 Li=d(void 0);function Mi(){const e=m(Li);if(!e)throw new Error("useObjectSelection must be used within a ObjectSelectionProvider");return e}function Ui(){return m(Li)}function Vi({value:t,collectionId:n,children:r}){const[s,a]=c();return g(()=>{const e=new Ri(t,n,{},a);a(e)},[t]),s&&e(Li.Provider,{value:s,children:r})}fn.extend(On),fn.extend($n);const Wi={string(t,n){let r=[];if(t){const e=t.get("slice");e&&r.push(t=>t.slice(parseInt(e)));const n=t.get("max_length");n&&r.push(e=>e.slice(0,parseInt(n))),t.has("upper")&&r.push(e=>e.toUpperCase()),t.has("lower")&&r.push(e=>e.toLowerCase()),t.has("capitalize")&&r.push(e=>e[0].toUpperCase()+e.substring(1)),t.has("ellipsis")&&r.push(e=>e+"...")}return(t,n)=>{let s;if(t){if(s=String(t),r.length>0)for(const e of r)s=e(s)}else s="";return e("td",{children:s},n)}},fileSize:(t,n)=>(t,n)=>{let r="";if(t){const e=Number(t);if(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/Math.pow(1024,n)).toFixed(2)} ${t[n]}`}}}return e("td",{children:r},n)},number(t,n){let r,s;t&&(r=t.get("currency")||void 0,s=t.get("decimals")||void 0);const a=s?parseInt(s):2;return(t,n)=>{let s=new Intl.NumberFormat("en-US",{style:r?"currency":"decimal",currency:r,maximumFractionDigits:a}).format(t);return e("td",{children:s},n)}},objectId(n,r){let s=[],a=!1;if(n){const e=n.get("slice");e&&(a=!0,s.push(t=>t.slice(parseInt(e))))}return(n,i)=>{const o=s.reduce((e,t)=>t(e),n.id);return t("td",{className:"flex justify-between items-center gap-2",children:[a?"~":"",o,e(De,{variant:"ghost",alt:"Preview Object",onClick:e=>{e.stopPropagation(),r?.(n.id)},children:e(J,{className:"size-4"})})]},i)}},objectName(t,n){let r="title";return t&&(r=t.get("title")||"title"),(t,n)=>e("td",{children:t.properties?.[r]||t.name||Ls(t.id)},n)},objectLink(n,r){const s=[];return s.push(e=>e.slice(-7)),(n,a)=>{const i=s.reduce((e,t)=>t(e),n.id);return t("td",{className:"flex justify-between items-center gap-2 max-w-48",children:["~",i,e(De,{variant:"ghost",alt:"Preview Object",onClick:e=>{e.stopPropagation(),r?.(n.id)},children:e(J,{className:"size-4"})})]},a)}},typeLink:(t,n)=>(t,n)=>e("td",{children:t?.name||"n/a"},n),date(t,n){let r="format",s="LLL";if(t){const e=t.get("localized");if(e)s=e;else{const e=t.get("relative");e&&(r=e,s=void 0)}}return(t,n)=>e("td",{children:fn(t)[r](s)},n)}},qi=Wi.string();function Bi(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(n=n[t[e]],!n)return;return n[t[r]]}function Hi(e){return e&&"."!==e?e.split("."):[]}class Gi{layout;renderer=qi;path;fallbackPath;previewObject;constructor(e,t){if(this.layout=e,this.path=Hi(e.field||""),this.fallbackPath=e.fallback?Hi(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=Wi[e](r)}else this.renderer=Wi[t]()}}get name(){return this.layout.name}resolveValue(e){let t=Bi(e,this.path);return void 0===t&&this.fallbackPath&&(t=Bi(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",children:this.layout.render(t)},n);const r=this.layout.type||"string",s=r.indexOf("?")>0?r.substring(0,r.indexOf("?")):r;if(("objectId"===s||"objectLink"===s)&&this.previewObject){const e=r.indexOf("?"),a=e>0?new URLSearchParams(r.substring(e+1)):void 0;return Wi[s](a,e=>{this.previewObject(t.id)})(t,n)}return this.renderer(this.resolveValue(t),n)}}function Ji({objects:n,selection:r,isLoading:s,columns:a,onRowClick:i,selectedObject:o,toggleAll:l,onSelectionChange:c}){return t(st,{className:"w-full border-t",children:[e("thead",{children:t("tr",{children:[r&&e("th",{children:e("input",{type:"checkbox",onChange:l})}),a.map(t=>e("th",{children:t.name},t.name))]})}),t(pt,{isLoading:s,columns:a.length+1,children:[n?.map(n=>t("tr",{className:"cursor-pointer hover:bg-muted group "+(o?.id===n.id?"bg-muted":""),onClick:()=>{i&&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=>c(n,e)})}),a.map((e,t)=>e.render(n,t))]},n.id)),0===n.length&&e("tr",{children:e("td",{colSpan:a.length+(r?1:0),className:"text-center",children:"No objects. Just drag and drop documents or images here to create content objects."})})]})]})}function Ki({objects:r,selection:s,isLoading:a,onSelectionChange:i,onRowClick:o,previewObject:l,selectedObject:c}){return t(n,{children:[e(Ra,{isLoading:a}),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(La,{document:t,selection:s,onSelectionChange:i,onRowClick:o,previewObject:l,selectedObject:c},t.id))})]})}class Yi{client;limit;collectionId;facets=new ht({});result=new ht({objects:[],isLoading:!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:s,score_aggregation:a,dynamic_scaling:i,limit:o}=this.query;this.query={parent:t,...void 0!==n&&{full_text:n},...void 0!==r&&{vector:r},...void 0!==s&&{weights:s},...void 0!==a&&{score_aggregation:a},...void 0!==i&&{dynamic_scaling:i},...void 0!==o&&{limit:o}},e&&this.search()}getFacetBuckets(e){return this.facets.value[e]?.buckets||[]}resetFacets(){this.query={}}reset(e=!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 s={limit:t,offset:n,query:e,facets:r?this.facetSpecs:void 0};return this.collectionId?this.client.collections.searchMembers(this.collectionId,s):this.client.objects.search(s)}_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})}_search(e=!1,t=!1){if(this.isRunning&&e)return Promise.resolve(!1);this.result.value={isLoading:!0,objects:e?this.objects:[],hasMore:!e||this.result.value.hasMore};const n=this.limit,r=e?this.objects.length:0;return this._searchRequest(this.query,n,r,!t).then(async r=>{const s=r.results||[],a=r.facets||{};return this.result.value={isLoading:!1,objects:e?this.objects.concat(s):s,hasMore:s.length===n},!t&&a&&Object.keys(a).length>0&&(this.facets.value=a),!0}).catch(e=>{throw this.result.value={error:e,isLoading:!1,objects:this.objects,hasMore:this.result.value.hasMore},e})}search(e=!1){return this.isRunning&&this.objects.length>0?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 Zi=d(void 0);function Qi(){return m(Zi)}function Xi(){return gt(Qi().facets)}function eo(){const e=Qi();return{...gt(e.result),search:e}}function to(){const e=Qi();return gt(e.facets).total}var no;async function ro(e){try{const t=await e.arrayBuffer(),n=new Rn;n.appendByteArray(new Uint8Array(t));const r=n.end();return r?.toString()}catch(e){return void console.error("Error calculating file hash:",e)}}function so(){const{client:e}=Te(),t=Ae();return{checkDocumentProcessing:async(n,r,s)=>{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 s=e.slice(r,r+5),a=await Promise.all(s.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 ro(e),name:e.name,size:e.size,location:n}}));n.push(...a)}return n}(n,r),a=async()=>{const n=t.map(e=>e.hash).filter(Boolean);if(0===n.length)return;const r={"content.etag":{$in:n}};let a;if(s){const t={query:{match:r},select:"id content.etag"};a=(await e.store.collections.searchMembers(s,t)).results}else{const t={query:r,select:"id content.etag"};a=await e.store.objects.find(t)}for(const e of a){const n=t.find(t=>t.hash===e.content?.etag);n&&(n.existingId=e.id,n.action=no.SKIP)}},i=async()=>{const n=t.filter(e=>e.action!==no.SKIP),r=n.map(e=>e.location),a=Array.from(new Set(r)),i=[];for(const t of a){const r={"content.name":{$in:n.filter(e=>e.location===t).map(e=>e.name)},location:t||"/"};if(s){const t=e.store.collections.searchMembers(s,{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=no.UPDATE)}console.log(`Reconciled ${t.filter(e=>e.action===no.UPDATE).length}`)};return await a(),await i(),t.forEach(e=>{e.action||(e.action=no.CREATE)}),console.log("Document processing check results:",{totalFiles:n.length,toCreate:t.filter(e=>e.action===no.CREATE).length,toUpdate:t.filter(e=>e.action===no.UPDATE).length,toSkip:t.filter(e=>e.action===no.SKIP).length}),t}catch(e){throw t({title:"Error in file upload processing check",status:"error",description:e.message}),console.log("Error in file upload processing check",e),new Error("Error in file upload processing check: "+e.message)}}}}function ao({isOpen:r,onClose:s,files:a,collectionId:i,selectedFolder:o,title:d="Upload Files",children:m,onUploadComplete:u,hideFileSelection:p=!1,showTypeSelectionOnly:h=!1,allowFolders:f=!0}){const{client:b}=Te(),{registry:y}=Ga(),v=Ae(),[x,w]=c([]),[N,k]=c([]),[C,S]=c(!1),[_,j]=c(null),[I,P]=c([]),[T,z]=c(!1),[A,D]=c(!1),[F,E]=c(0),[$,O]=c(Date.now()),[R,L]=c(void 0),[M,U]=c(null),[V,W]=c(d),[q,B]=c("");g(()=>{i&&b.store.collections.retrieve(i).then(L)},[i]),g(()=>{T?(W("Uploading Files"),B(`${Math.round(F)}% complete`)):A?(W("Upload Complete"),B("")):C?(W("File Analysis Results"),B(`${x.length} file${1!==x.length?"s":""}`)):x.length>0?(W(d),B("Checking for duplicates and updates")):(W(d),B(""))},[T,A,C,d,F,x.length]);const H=()=>R||o?t(ft,{className:"mb-4",status:"default",icon:e(ne,{className:"size-5"}),children:[e("div",{className:"flex items-center",children:e("span",{className:"font-medium",children:"Upload Location:"})}),t("div",{className:"text-sm mt-1",children:[R&&t("div",{className:"flex items-center",children:[e("span",{className:"mr-1",children:"Collection:"}),e("span",{className:"font-medium",children:R.name})]}),o&&t("div",{className:"flex items-center mt-1",children:[e("span",{className:"mr-1",children:"Folder:"}),e("span",{className:"font-medium",children:o})]})]})]}):null,[G,J]=c({toCreate:0,toUpdate:0,toSkip:0}),{checkDocumentProcessing:K}=so(),Y=l(()=>y?.types||[],[y?.types]);g(()=>{r&&(k([]),S(!1),j(null),P([]),z(!1),D(!1),E(0),J({toCreate:0,toUpdate:0,toSkip:0}),U(null),W(d),B(""),a&&a.length>0?(w(a),ie(a)):w([]),O(Date.now()))},[r,a]);const se=()=>{w([]),k([]),S(!1),j(null),P([]),z(!1),D(!1),E(0),J({toCreate:0,toUpdate:0,toSkip:0}),U(null),W(d),B(""),O(Date.now()),s()},ae=e=>{e&&e.length>0&&(w(e),ie(e))},ie=async e=>{if(e.length)try{console.log(`Processing ${e.length} files to determine required actions...`);const t=await K(e,o,i);k(t);const n=t.filter(e=>e.action===no.CREATE).length,r=t.filter(e=>e.action===no.UPDATE).length,s=t.filter(e=>e.action===no.SKIP).length;J({toCreate:n,toUpdate:r,toSkip:s}),v({title:"Files analyzed",description:`${e.length} file(s): ${n} new, ${r} to update, ${s} to skip`,status:"info",duration:4e3}),S(!0)}catch(e){console.error("Error processing files:",e),v({title:"Error",description:"There was an error analyzing the files",status:"error",duration:5e3})}},oe=async()=>{if(!N.length)return;const e=_?.id||null,t=N.map(e=>({file:e.file,status:"pending",progress:0,action:e.action===no.CREATE?"create":e.action===no.UPDATE?"update":"skip"}));P(t),z(!0),D(!1);const n=N.filter(e=>e.action===no.SKIP),r=N.filter(e=>e.action===no.UPDATE),s=N.filter(e=>e.action===no.CREATE),a={success:!0,objectIds:[],uploadedFiles:[],skippedFiles:[],failedFiles:[]};for(const t of n)t.existingId&&(a.objectIds.push(t.existingId),a.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 o=async(t,n)=>{const r=[];for(let e=0;e<t.length;e+=50)r.push(t.slice(e,e+50));for(let s=0;s<r.length;s++){const o=r[s];if(console.log(`Processing ${n} batch ${s+1}/${r.length} (${o.length} files)`),t.length>50){v({title:`Processing files (${n})`,description:`Processed ${50*s}/${t.length} files...`,status:"info",duration:2e3})}let l=0;await Promise.all(o.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 b.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)),a.objectIds.push(t.existingId),a.uploadedFiles.push({id:t.existingId,name:t.name,type:e,status:"updated",location:t.location});else{const n=await b.store.objects.create({type:e||void 0,content:t.file,location:t.location||t.file.webkitRelativePath||t.name},{collection_id:i});P(e=>e.map(e=>e.file===t.file?{...e,status:"success",progress:100,id:n.id}:e)),a.objectIds.push(n.id),a.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:n.message||"Unknown error"}:e)),a.failedFiles.push({name:t.name,error:n.message||"Unknown error",status:"failed",location:t.location,type:e}),a.success=!1}l++,l%5!=0&&l!==o.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 E(r),e})}))}};r.length>0&&await o(r,"update"),s.length>0&&await o(s,"create"),P(e=>{const t=e.filter(e=>"pending"===e.status).map(e=>({...e,status:"error",progress:100,message:"Upload process interrupted"}));return t.length>0?(t.forEach(e=>{a.failedFiles.push({name:e.file.name,error:"Upload process interrupted",status:"failed",type:_?.id||null})}),a.success=!1,e.map(e=>"pending"===e.status?{...e,status:"error",progress:100,message:"Upload process interrupted"}:e)):e}),z(!1),D(!0);const l=a.uploadedFiles.filter(e=>"created"===e.status).length,c=a.uploadedFiles.filter(e=>"updated"===e.status).length,d=a.skippedFiles.length,m=a.failedFiles.length;let u="";l>0&&(u+=`${l} file${1!==l?"s":""} uploaded`),c>0&&(u+=u?", ":"",u+=`${c} file${1!==c?"s":""} updated`),d>0&&(u+=u?", ":"",u+=`${d} file${1!==d?"s":""} skipped`),m>0&&(u+=u?", ":"",u+=`${m} file${1!==m?"s":""} failed`),v({title:"Upload Complete",description:u,status:m>0?"warning":"success",duration:5e3}),U(a)},le=()=>t("div",{className:"mb-4",children:[t("label",{className:"block text-sm font-medium mb-2",children:["Content Type ",e("span",{className:"text-muted font-normal",children:"(Optional)"}),e(Ee,{description:"Select a content type to apply to the uploaded files. If left empty, Vertesia will automatically detect the type based on file content.",placement:"top",size:"xs",children:e(re,{className:"size-3 ml-2"})})]}),e(tt,{options:Y,value:_,optionLabel:e=>e?e.name:"Select a content type",placeholder:"Select a content type or leave empty for automatic detection",onChange:e=>j(void 0===e?null:e),filterBy:"name",isClearable:!0}),_?e(n,{}):e("div",{className:"p-2 rounded-md",children:t("div",{className:"flex items-center text-attention",children:[e(Q,{className:"size-4 mr-1"}),"Automatic Type Detection",e(Ee,{description:"Vertesia will analyze the content and select the most appropriate type. This is recommended for most uploads and ensures optimal processing.",placement:"top",size:"xs",children:e(re,{className:"size-3 ml-2"})})]})})]});return t(Ve,{isOpen:r,onClose:se,className:"mx-auto",disableCloseOnClickOutside:!0,children:[e(We,{description:q,children:V}),h?t(qe,{children:[m,H(),le()]}):0!==x.length||p?T||A?T?t(qe,{children:[H(),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:I.map((n,r)=>t("div",{className:"flex items-center py-2 border-b border-border last:border-b-0",children:[t("div",{className:"mr-3",children:["pending"===n.status&&e(ee,{className:"size-5 text-muted"}),"uploading"===n.status&&e(Ue,{size:"sm"}),"success"===n.status&&e(Q,{className:"size-5 text-success"}),"error"===n.status&&e(te,{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&&"Waiting...","uploading"===n.status&&"Uploading...","success"===n.status&&("create"===n.action?"Created":"update"===n.action?"Updated":"Skipped"),"error"===n.status&&n.message]})]})]},`${n.file.name}-${r}`))})]}):e(qe,{children:t("div",{className:"mb-4",children:[H(),e(jn,{files:I.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:o||void 0,collection:R?.name})]})}):e(qe,{children:C?t(n,{children:[H(),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(Z,{className:"size-5 text-primary"}),e("span",{className:"font-medium",children:"New"})]}),e("div",{className:"text-2xl font-semibold",children:G.toCreate})]}),t("div",{className:"flex flex-col items-center",children:[t("div",{className:"flex items-center gap-2",children:[e(Q,{className:"size-5 text-success"}),e("span",{className:"font-medium",children:"Update"})]}),e("div",{className:"text-2xl font-semibold",children:G.toUpdate})]}),t("div",{className:"flex flex-col items-center",children:[t("div",{className:"flex items-center gap-2",children:[e(X,{className:"size-5 text-mixer-attention/40"}),e("span",{className:"font-medium",children:"Skip"})]}),e("div",{className:"text-2xl font-semibold",children:G.toSkip})]})]})})}),le(),e(ft,{className:"mb-4",status:"info",children:G.toCreate+G.toUpdate>0?t("div",{className:"space-y-1",children:[t("p",{children:[G.toCreate+G.toUpdate," file",G.toCreate+G.toUpdate>1?"s are":" is"," ready to process"]}),e("p",{children:G.toSkip>0&&`${G.toSkip} file${G.toSkip>1?"s are":" is"} already in the system and will be skipped.`})]}):G.toSkip>0?t("span",{children:["All ",G.toSkip," file(s) already exist in the system and will be skipped. You can proceed to view the results."]}):e("span",{children:"No files to process."})})]}):t("div",{className:"flex flex-col items-center justify-center py-4",children:[e(Ue,{size:"lg",className:"mb-4"}),e("div",{className:"text-lg font-medium",children:"Analyzing files..."})]})}):t(qe,{className:"flex flex-col items-center justify-center p-8",children:[H(),e(_n,{onDrop:ae,message:"Drag and drop files here or click to select",buttonLabel:"Select Files",className:"w-full h-64",allowFolders:f}),m]}),(()=>{if(h)return t(Je,{children:[e(De,{variant:"ghost",onClick:se,children:"Cancel"}),e(De,{onClick:()=>{u&&u({success:!0,objectIds:[],uploadedFiles:[{name:"type-selection",type:_?.id||null,status:"created"}],skippedFiles:[],failedFiles:[]}),se()},children:_?`Use ${_.name}`:"Use Automatic Type Detection"})]});if(0===x.length&&!p)return e(Je,{children:e(De,{variant:"ghost",onClick:se,children:"Cancel"})});if(!T&&!A){const n=C;return t(Je,{children:[e(De,{variant:"ghost",onClick:se,children:"Cancel"}),e(De,{disabled:!n,onClick:oe,children:G.toCreate+G.toUpdate>0?"Upload":"Continue"})]})}return T?e(Je,{children:e(De,{variant:"ghost",disabled:!0,children:"Uploading..."})}):t(Je,{children:[e(De,{variant:"ghost",onClick:()=>{w([]),k([]),S(!1),j(null),P([]),z(!1),D(!1),E(0),J({toCreate:0,toUpdate:0,toSkip:0})},children:"Upload More"}),e(De,{onClick:()=>{u&&M&&u(M),se()},children:"Close"})]})})()]},$)}function io(e){const t="function"==typeof e?e:e.onUploadDone,{client:n,project:r,store:s}=Te(),a=Qi(),i=Ae(),{checkDocumentProcessing:o}=so();return async(e,l,c)=>{const d={success:!1,objectIds:[],uploadedFiles:[],skippedFiles:[],failedFiles:[]};if(!r)return i({status:"error",title:"No project selected",duration:3e3}),d;if(!e||0===e.length)return i({status:"warning",title:"No files selected",duration:3e3}),d;const m=Array.from(e).filter(e=>e.size>0);if(0===m.length)return i({status:"error",title:"No valid files selected",description:"Please select files with valid content.",duration:5e3}),d;const u=[],p=[],h=[];console.log(`Processing ${m.length} files with smart file processing...`);const g=await o(m,null,c),f=g.filter(e=>e.action===no.CREATE).length,b=g.filter(e=>e.action===no.UPDATE).length,y=g.filter(e=>e.action===no.SKIP).length;i({title:"Files analyzed",description:`${m.length} file(s): ${f} new, ${b} to update, ${y} to skip`,status:"info",duration:4e3});for(const e of g.filter(e=>e.action===no.SKIP&&e.existingId))u.push({id:e.existingId,name:e.name,type:l,status:"skipped",location:e.location});const v=g.filter(e=>(e.action===no.CREATE||e.action===no.UPDATE)&&e.file);if(v.length>0){console.log(`Processing ${v.length} files (${v.filter(e=>e.action===no.CREATE).length} create, ${v.filter(e=>e.action===no.UPDATE).length} update)...`);const e=50,t=[];for(let n=0;n<v.length;n+=e)t.push(v.slice(n,n+e));for(let r=0;r<t.length;r++){const a=t[r],o=r*e;console.log(`Processing batch ${r+1}/${t.length} (${a.length} files)`),v.length>e&&i({title:"Processing files",description:`Processed ${o}/${v.length} files...`,status:"info",duration:2e3});const m=await Promise.all(a.map(async e=>{try{if(e.action===no.UPDATE&&e.existingId){const t=await n.store.objects.update(e.existingId,{type:l||void 0,content:e.file,location:e.location,name:e.name},{createRevision:!0,revisionLabel:"upload on "+(new Date).toISOString()});return p.push({id:e.existingId,name:e.name,type:l,status:"updated",location:e.location}),d.objectIds.push(e.existingId),{success:!0,id:t.id,name:e.name,action:"update"}}{const t=c?{collection_id:c}:void 0,n=await s.objects.create({type:l||void 0,content:e.file,location:e.location||e.file.webkitRelativePath||e.name},t);p.push({id:n.id,name:e.name,type:l,status:"created",location:e.location})}}catch(t){console.error(`Failed to process file ${e.name}:`,t),h.push({name:e.name,error:t.message||"Unknown error",status:"failed",location:e.location,type:l}),i({status:"error",title:`Processing failed for ${e.name}`,description:t.message,duration:4e3})}})),u=p.filter(e=>"created"===e.status),g=p.filter(e=>"updated"===e.status),f=p.filter(e=>"failed"===e.status);console.log(`Batch ${r+1} results:`,{creates:u,updates:g,failures:f,total:m.length})}}const x=p.filter(e=>"created"===e.status).length,w=p.filter(e=>"updated"===e.status).length,N=p.filter(e=>"failed"===e.status).length,k=p.filter(e=>"skipped"===e.status).length;t&&(console.log("Upload complete:",{totalObjectIds:d.objectIds.length,uploadedFiles:x,updatedFiles:w,skippedFiles:k,failedFiles:N}),await t(d.objectIds));let C="";return x>0&&(C+=`${x} file${1!==x?"s":""} uploaded`),w>0&&(C+=C?", ":"",C+=`${w} file${1!==w?"s":""} updated`),k>0&&(C+=C?", ":"",C+=`${k} file${1!==k?"s":""} skipped (already existed)`),N>0&&(C+=C?", ":"",C+=`${N} file${1!==N?"s":""} failed`),C&&i({status:N>0?"warning":"success",title:C,duration:4e3}),a.search(),d}}!function(e){e.CREATE="create",e.SKIP="skip",e.UPDATE="update"}(no||(no={}));const oo=[{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 lo({isGridView:t=!1,onUpload:n,collectionId:r,...s}){return n?e(co,{...s,onUpload:n,isGridView:t,collectionId:r}):e(mo,{...s,isGridView:t})}function co({isGridView:n,onUpload:s,collectionId:a,skipTypeModal:i=!1,...o}){const[l,d]=c(!1),[m,u]=c([]),[p,h]=c(!1),[g,f]=c(null),[b,y]=c(!1),v=Qi(),x=Ae(),{checkDocumentProcessing:w}=so(),N=async(e,t)=>{console.log("Files dropped on ObjectTable:",e.length,t),d(!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:"Files ready to process",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:"Error processing files",description:"There was an error checking for duplicate files",status:"error",duration:4e3}),f(null)}finally{if(d(!1),u(e),h(!1),i){console.log("Skipping type modal and calling onUpload directly",{filesLength:e.length,processedFilesLength:g?.length});const t=s(e,null,a);t&&"object"==typeof t&&(t.processedFiles=g)}else console.log("Setting typeSelectionOpen to true",{filesLength:e.length}),y(!0)}},k=e=>{const t=[...m];u([]),f(null),y(!1),t.length>0&&void 0!==e&&(d(!0),console.log("Starting upload with",{typeId:e,filesCount:t.length,hasProcessingResults:!!g,collectionId:a}),s(t,e,a).finally(()=>{d(!1),v.search()}))},C=e=>{e.preventDefault(),e.stopPropagation(),h(!0)};return t("div",{className:"min-h-[400px] relative",onDragOver:C,onDragEnter:C,onDragLeave:e=>{e.preventDefault(),e.stopPropagation(),e.currentTarget.contains(e.relatedTarget)||h(!1)},onDrop:e=>{if(e.preventDefault(),e.stopPropagation(),h(!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:r("bg-white dark:bg-gray-800 opacity-40 absolute inset-0 z-50 flex justify-center items-center",l?"block":"hidden"),children:e(Ue,{size:"xl"})}),e(mo,{...o,isGridView:n}),e("div",{className:r("absolute inset-0 pointer-events-none",p?"z-40":"-z-10"),children:e("div",{className:"w-full h-full relative",children:e(_n,{onDrop:N,message:"Drop files or folders here to upload",className:r("absolute inset-0 bg-white/90 dark:bg-gray-800/90 pointer-events-auto",p?"flex":"hidden"),buttonLabel:"Select Files or Folders",allowFolders:!0})})}),e(ao,{isOpen:b&&m.length>0,onClose:()=>{u([]),f(null),y(!1),k(void 0)},files:m,collectionId:a,selectedFolder:null,title:"Upload Files",onUploadComplete:e=>{if(e){if(e.failedFiles&&e.failedFiles.length>0&&x({title:"Upload Issues",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:"Upload Complete",description:`${t>0?`${t} created`:""}${t>0&&n>0?", ":""}${n>0?`${n} updated`:""}${r>0?`, ${r} skipped`:""}`,status:"success",duration:5e3})}v.search()}u([]),f(null),y(!1),e&&e.success&&e.objectIds.length>0?k(null):k(void 0)}})]})}function mo({objects:t,layout:n=oo,isLoading:r,onRowClick:s,onSelectionChange:a,previewObject:i,selectedObject:o,isGridView:c}){const d=Ui(),m=(e,n)=>{if(d){const r=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 s=r+1;s<n;s++)e.push(t[s]);d.addAll(e)}else{const e=function(e,t,n){const r=e.length;for(let s=t+1;s<r;s++)if(n.isSelected(e[s].id))return s;return-1}(t,n,d);if(e>-1&&e>n+1){const r=[];for(let s=n+1;s<e;s++)r.push(t[s]);d.addAll(r)}}}}else d.remove(e.id);a&&a(d)}},u=e=>{if(d){e.target.checked?d.addAll(t):d.removeAll()}},p=l(()=>(n.length>0?n:oo).map(e=>new Gi(e,i)),[n,i]);return e(c?Ki:Ji,{objects:t,isLoading:r,columns:p,onRowClick:s,previewObject:i,selectedObject:o,selection:d,toggleAll:u,onSelectionChange:m})}function uo({children:t,limit:n,parent:r,typeId:s,facets:a,name:i,collectionId:o}){const{store:c}=Te(),d=l(()=>{let e;a?e=a:(e=[{name:"status",field:"status"},{name:"location",field:"location"}],s||e.unshift({name:"type",field:"type"}));const t=new Yi(c,n).withFacets(e);return t.collectionId=o,t.query.type=s,t.query.parent=r,t.query.name=i,t},[s,n,o]);return e(Zi.Provider,{value:d,children:t})}const po=[{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 ho({onChange:t}){return e(uo,{children:e(go,{onRowClick:e=>{t(e||void 0)}})})}function go({onRowClick:n}){const[r,a]=c(!1),[i,o]=c("grid"===localStorage.getItem("vertesia.content_store.lastDisplayedView")),{search:l,isLoading:d,error:m,objects:p,hasMore:h}=eo(),f=u(null);bt(f,()=>{r&&h&&!d&&(a(!1),l.loadMore(!0).finally(()=>{a(!0)}))},{threshold:.1,deps:[r,h,d]}),g(()=>{l.search().finally(()=>{a(!0)})},[]);const b=Xi(),y=Qi();return m?e(Oe,{title:"Search failed",children:m.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(Si,{facets:b,search:y}),t("div",{className:"flex items-center gap-2",children:[e(De,{variant:"outline",onClick:()=>{a(!1),l.search().then(()=>a(!0))},alt:"Refresh",children:e(Y,{size:16})}),e(Yr,{onUpdate:o})]})]}),t("div",{className:"@container flex-1 overflow-y-auto",children:[e(lo,{objects:p||[],isLoading:!1,layout:po,onRowClick:n,isGridView:i}),e("div",{ref:f,className:"h-4 w-full"}),e("div",{className:s("bg-white dark:bg-gray-800 opacity-80 absolute inset-0 z-50 flex justify-center items-center rounded",d?"block":"hidden"),children:e(Ue,{size:"xl"})})]})]})}function fo({isOpen:n,onClose:r}){return t(Ve,{onClose:()=>r(),isOpen:!!n,className:"min-w-[60vw]",children:[e(We,{children:"Select Content"}),e(qe,{className:"pt-0 overflow-y-auto max-h-[80vh] min-h-[80vh]",children:n&&e(ho,{onChange:r})})]})}const bo=/store:([a-f0-9]+)/;function yo({object:n}){const{client:s}=Te(),{off:a,on:i,isOn:o}=yt(),[l,d]=c(null!=n.value?String(n.value):""),[m,u]=c(void 0),p=()=>{d(""),n.value="",u(void 0)};return g(()=>{if(!l||m)return;const e=l.match(bo);e&&s.objects.get(e[1]).then(e=>{u(e)}).catch(()=>{p()})},[l]),t("div",{children:[t("div",{className:"relative",children:[e("input",{value:l,onChange:e=>{const t=e.target.value;d(t),n.value=t},className:r(vt.INPUT,"pr-10 w-full")}),m&&e("div",{className:"absolute inset-y-0 right-10 flex items-center justify-center ",children:e(De,{onClick:p,variant:"unstyled",className:"hover:text-red-500 hover:bg-gray-100 dark:hover:bg-gray-600",children:e(C,{className:"size-5"})})}),e("div",{className:"absolute inset-y-0 right-0 flex items-center justify-center",children:e(De,{onClick:i,variant:"unstyled",className:"hover:bg-gray-100 dark:hover:bg-gray-600",children:e(se,{className:"size-5"})})}),e(fo,{value:l,isOpen:o,onClose:e=>{if(e){const t="store:"+e.id;d(t),u(e||void 0),n.value=t}a()}})]}),m&&e("div",{className:"p-1 semibold text-sm text-gray-600 dark:text-slate-300",children:m.properties?.title||m.name})]})}function vo({objectId:n,isOpen:r,onClose:s}){const a=bn(),{client:i,store:o}=Te(),[l,d]=c(null),[m,u]=c(!1),[p,h]=c(!1),[f,b]=c(),[y,v]=c(),[x,N]=c("preview"),S=Ae();g(()=>{n&&r?(u(!0),o.objects.retrieve(n,"+embeddings").then(e=>{d(e),e.text?b(e.text):_(e.id);const t=e.content;t&&t.source&&t.type&&t.type.startsWith("image/")&&I(e)}).catch(e=>{console.error("Error loading object:",e),S({title:"Error",description:"Failed to load document",status:"error",duration:3e3})}).finally(()=>{u(!1)})):(d(null),b(void 0),v(void 0))},[n,r,o.objects]);const _=async e=>{h(!0);try{const t=await o.objects.getObjectText(e);b(t.text)}catch(e){console.error("Error loading text:",e)}finally{h(!1)}},I=async e=>{try{"found"===(await i.objects.getRendition(e.id,{format:Yt.jpeg,generate_if_missing:!1})).status&&console.log("Found rendition");const t=await i.files.getDownloadUrl(e.content.source);v(t.url)}catch(e){console.error("Error loading image:",e)}},P=()=>{l&&(a(`/legal/objects/${l.id}`),s())},T=f&&(f.startsWith("#")||f.includes("\n#")||f.includes("\n*")),z=l?.content?.type&&l.content.type.startsWith("image/"),A="application/pdf"===l?.content?.type;return r?t("div",{className:"fixed inset-y-0 right-0 w-2/5 dark:bg-slate-900 shadow-xl z-50 flex flex-col transition-transform duration-300 transform "+(r?"translate-x-0":"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(ae,{className:"h-5 w-5 text-indigo-600 mr-2"}),e("h2",{className:"text-lg font-semibold text-gray-800 dark:text-gray-200 truncate",children:m?"Loading document...":l?.name||"Document Preview"})]}),t("div",{className:"flex items-center space-x-2",children:[t(De,{variant:"ghost",size:"sm",onClick:P,className:"flex items-center gap-1 text-indigo-600 hover:text-indigo-800",children:[e(k,{className:"h-4 w-4"}),e("span",{children:"Full View"})]}),e(De,{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(C,{className:"h-5 w-5"})})]})]}),m?e("div",{className:"flex-1 flex items-center justify-center",children:t("div",{className:"text-center",children:[e(Ue,{size:"lg",className:"text-indigo-600 dark:text-indigo-400 mb-2"}),e("p",{className:"text-gray-600 dark:text-gray-400",children:"Loading document..."})]})}):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("button",{className:"py-2 px-4 font-medium border-b-2 "+("preview"===x?"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:()=>N("preview"),children:t("div",{className:"flex items-center gap-1",children:[e(O,{className:"h-4 w-4"}),e("span",{children:"Preview"})]})}),e("button",{className:"py-2 px-4 font-medium border-b-2 "+("properties"===x?"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:()=>N("properties"),children:t("div",{className:"flex items-center gap-1",children:[e(re,{className:"h-4 w-4"}),e("span",{children:"Properties"})]})})]})}),t("div",{className:"flex-1 overflow-auto p-4",children:["preview"===x&&t("div",{className:"h-full",children:[p?e("div",{className:"flex items-center justify-center h-40",children:e(Ue,{size:"md",className:"text-indigo-600 dark:text-indigo-400"})}):f?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(vn,{children:f})}):e("pre",{className:"text-wrap whitespace-pre-wrap dark:text-gray-200",children:f})}):null,z&&e("div",{className:"mt-4",children:e("div",y?{className:"border border-gray-200 dark:border-gray-700 rounded-md p-2 bg-white dark:bg-gray-800",children:e("img",{src:y,alt:l?.name,className:"mx-auto max-h-[70vh] object-contain"})}:{className:"flex items-center justify-center h-40",children:e(Ue,{size:"md",className:"text-indigo-600 dark:text-indigo-400"})})}),A&&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(ae,{className:"h-16 w-16 text-indigo-300 dark:text-indigo-400 mb-4"}),t("p",{className:"text-gray-600 dark:text-gray-400 text-center mb-4",children:["PDF document preview is available in full view. TODO"," "]}),e(De,{onClick:P,className:"bg-indigo-600 hover:bg-indigo-700 text-white",children:"Open Full Document View"})]}),!z&&!f&&!A&&!p&&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(ae,{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:"No preview available for this document type."})]})]}),"properties"===x&&l&&t("div",{className:"h-full",children:[l.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(Cn,{value:l.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(re,{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:"No properties available for this document."})]}),t("div",{className:"mt-4",children:[e("h3",{className:"text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2",children:"Document Information"}),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:"ID"}),e("div",{className:"font-medium dark:text-gray-200",children:l.id}),e("div",{className:"text-gray-500 dark:text-gray-400",children:"Type"}),e("div",{className:"font-medium dark:text-gray-200",children:l.type?.name||"Unknown"}),e("div",{className:"text-gray-500 dark:text-gray-400",children:"Content Type"}),e("div",{className:"font-medium dark:text-gray-200",children:l.content?.type||"N/A"}),e("div",{className:"text-gray-500",children:"Size"}),e("div",{className:"font-medium",children:l.content&&"size"in l.content?xo(l.content.size):"Unknown"}),e("div",{className:"text-gray-500",children:"Created"}),e("div",{className:"font-medium",children:l.created_at?new Date(l.created_at).toLocaleString():"N/A"}),e("div",{className:"text-gray-500",children:"Updated"}),e("div",{className:"font-medium",children:l.updated_at?new Date(l.updated_at).toLocaleString():"N/A"})]})})]})]})]})]}),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:l?.content?.source&&t(De,{onClick:()=>{l?.content?.source&&i.files.getDownloadUrl(l.content.source).then(e=>{window.open(e.url,"_blank")}).catch(e=>{console.error("Error getting download URL:",e),S({title:"Error",description:"Failed to download file",status:"error",duration:3e3})})},variant:"outline",className:"text-indigo-600 border-indigo-300 hover:bg-indigo-50",children:[e(w,{className:"h-4 w-4 mr-2"}),"Download"]})}),t(De,{onClick:P,className:"bg-indigo-600 hover:bg-indigo-700 text-white",children:["Open Full Document",e(j,{className:"h-4 w-4 ml-2"})]})]})]}):null}function xo(e){if(0===e)return"0 Bytes";const t=Math.floor(Math.log(e)/Math.log(1024));return parseFloat((e/Math.pow(1024,t)).toFixed(2))+" "+["Bytes","KB","MB","GB","TB"][t]}const wo=Object.values(an),No=Object.values(on);function ko({onChange:n,isLoading:r,refresh:s,searchTypes:a}){const{client:i,project:o}=Te(),l=Ae(),[d,m]=c(void 0),[u,p]=c(void 0),h=!(!o||!u?.embeddings.text&&!u?.embeddings.image),[f,b]=c(void 0),[y,v]=c(!1),[x,w]=c(a||wo),[N,k]=c(100);g(()=>{a&&w(a)},[a]);const C={};let S=!1,_=!1;x.forEach(e=>{e===an.full_text?S=!0:_=!0,No.includes(e)&&(C[e]=!0)}),g(()=>{m(void 0),b(void 0)},[s]),g(()=>{o&&i.projects.retrieve(o.id).then(e=>{p(e.configuration)})},[o]),g(()=>{f&&l({title:f,status:"success",duration:2e3})},[f]),g(()=>{d&&0!==d.length||n(void 0)},[d]);const j=()=>{if(!h||!d)return;n({vector:_?{text:d,config:C}:void 0,full_text:S?d:void 0,limit:N}),b("Searching...")},I=e=>t=>{w(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(Ge,{placeholder:"Type what you are looking for, or select a filter",value:d,onChange:m,onKeyDown:e=>{"Enter"===e.key&&j()},className:"min-w-[200px]"}),e(De,{variant:"ghost",onClick:()=>v(!0),alt:"Semantic search settings",className:"ml-1",children:e(ie,{size:18})}),t(Ve,{isOpen:y,onClose:()=>v(!1),children:[e(We,{children:"Search Types"}),e(qe,{children:t("div",{className:"flex flex-col gap-2",children:[t("label",{className:"flex items-center gap-2",children:[e(xt,{checked:x.includes(an.full_text),onCheckedChange:I(an.full_text)}),e("span",{children:"Full Text"})]}),e("div",{className:"font-semibold mt-2 mb-1",children:"Embeddings"}),No.map(n=>t("label",{className:"flex items-center gap-2",children:[e(xt,{checked:x.includes(n),onCheckedChange:I(n)}),e("span",{children:n.charAt(0).toUpperCase()+n.slice(1)})]},n)),t("div",{className:"mt-3",children:[e("span",{className:"mr-2",children:"Limit"}),e(wt,{type:"number",min:1,value:N,onChange:e=>k(Number(e??100)),style:{width:80}})]})]})}),e(Je,{children:e(De,{variant:"outline",onClick:()=>v(!1),children:"Close"})})]}),e(De,{variant:"secondary",isLoading:r,onClick:j,isDisabled:!h,alt:"Semantic search",children:"Search"})]})}const Co=[{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 So({onUploadDone:t=async()=>{},layout:n}){const r=Qi(),s=Ae(),a=io(async e=>{await t(e),setTimeout(()=>{console.log("Delayed refresh after upload to ensure backend consistency"),r.search().then(()=>{s({title:"Document list refreshed",description:"The document list has been updated with your uploaded files.",status:"info",duration:3e3})}).catch(e=>{console.error("Failed to refresh search results:",e)})},1e3)});return e(_o,{layout:n,onUpload:(e,t)=>{const n=r.collectionId;return a(e,t,n)}})}function _o({layout:n,onUpload:r,allowFilter:s=!0,allowSearch:a=!0}){const i=Qi(),[o,l]=c(!1),[d,m]=c(null),{registry:p}=Ga(),{search:h,isLoading:f,error:b,objects:y,hasMore:v}=eo(),[x,w]=c(p?n||(N=p,((k=h.query.type)?N.getTypeLayout(k):Co)??Co):Co);var N,k;const[C,S]=c(0),[_,j]=c(0),[I,P]=c("grid"===localStorage.getItem(Yr.LAST_DISPLAYED_VIEW)),[T,z]=c([]),A=u(null);g(()=>{o||0!==y.length||(j(0),h._updateRunningState(!0),h.search().then(()=>{l(!0)}).catch(e=>{console.error("Initial search failed:",e),h._updateRunningState(!1)}))},[]),g(()=>{y.length<_&&j(y.length)},[y.length,_]),bt(A,()=>{o&&y.length>0&&y.length!=_&&(l(!1),h.loadMore().finally(()=>{j(y.length),l(!0)}))},{deps:[o,y.length]});const D=Xi(),F=Qi(),E=ki(D),$=Ci(F),O=new URL(window.location.href),R=O.searchParams.get("filters");if(R)try{const e=R.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?O.searchParams.set("filters",e):O.searchParams.delete("filters"),window.history.replaceState(window.history.state||{},"",O.toString())}}catch(b){console.error("Failed to clean start/end filters from URL:",b)}const L=bn();return t("div",{className:"flex flex-col gap-y-2",children:[e(Io,{object:d,onClose:()=>m(null)}),b&&e(Oe,{title:"Error",children:b.message}),e(jo,{isLoading:f,refreshTrigger:C,allowFilter:s,allowSearch:a,filterGroups:E,filters:T,handleFilterChange:e=>{const t="function"==typeof e?e(T):e;z(t),$(t)},handleVectorSearch:e=>{if(e&&e.vector){if(h.query.vector=e.vector,h.query.full_text=e.full_text,h.query.weights=e.weights,h.query.score_aggregation=e.score_aggregation,h.query.dynamic_scaling=e.dynamic_scaling,void 0!==e.limit&&(h.limit=e.limit,h.query.limit=e.limit),!x.find(e=>"Search Score"===e.name)){const e=[...x,{name:"Search Score",field:"score",render:e=>e.score?.toFixed(4)||"0.0000"}];w(e)}h.search().then(()=>l(!0))}else e&&e.full_text?(h.query.full_text=e.full_text,void 0!==e.limit&&(h.limit=e.limit,h.query.limit=e.limit),h.search().then(()=>l(!0))):void 0===e&&o&&(delete h.query.vector,delete h.query.full_text,h.search().then(()=>l(!0)))},handleRefetch:()=>{h.search().then(()=>l(!0))},setIsGridView:P}),e(lo,{objects:y,isLoading:!y.length&&f,layout:x,onRowClick:e=>{L(`/objects/${e.id}`)},previewObject:e=>{const t=y.find(t=>t.id===e)||null;m(t)},selectedObject:d,onUpload:r,isGridView:I,collectionId:i.collectionId}),e("div",v?{ref:A,className:"w-full flex justify-center",children:e(Ue,{size:"xl"})}:{className:"text-muted text-center text-sm py-1",children:`All ${y.length} objects loaded.`})]})}function jo(n){const{isLoading:r,refreshTrigger:s,allowFilter:a,allowSearch:i,filterGroups:o,filters:l,handleFilterChange:c,handleVectorSearch:d,handleRefetch:m,setIsGridView:u}=n;return t("div",{className:"sticky top-0 z-10 bg-background py-2 flex justify-between items-center",children:[a&&t(ct,{filterGroups:o,filters:l,setFilters:c,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:[i&&e(ko,{onChange:d,isLoading:r,refresh:s,className:"w-full"}),e(dt,{})]})}),t("div",{className:"flex gap-2 items-center pt-2",children:[e(mt,{}),e(ut,{})]})]}),!a&&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:i&&e(ko,{onChange:d,isLoading:r,refresh:s})})}),t("div",{className:"flex gap-1 items-center",children:[e(De,{variant:"outline",onClick:m,alt:"Refresh",children:e(Y,{size:16})}),e(Yr,{onUpdate:u})]})]})}function Io({object:n,onClose:r}){const{store:s}=Te(),a=Ae(),i=bn(),{downloadFromContentSource:o}=la({client:s,toast:a});return n?t(Nt,{title:n.properties?.title||n.name,isOpen:!0,onClose:r,children:[t("div",{className:"flex items-center gap-x-2",children:[e(De,{variant:"ghost",size:"sm",title:"Open Object",onClick:()=>i(`/objects/${n.id}`),children:e(S,{className:"size-4"})}),n.content?.source&&e(De,{variant:"ghost",size:"sm",title:"Download",onClick:()=>o(n.content.source,n.name||n.content?.name),children:e(w,{className:"size-4"})})]}),e(kt,{className:"my-2"}),e("div",{className:"pt-2",children:e(Na,{object:n,loadText:!0},n.id)})]}):null}var Po;function To({isExporting:n,isOpen:r,onClose:s}){return t(Ve,{onClose:()=>s(void 0),isOpen:r,children:[e(We,{children:"Export Object Properties"}),t(qe,{children:[!n&&e(zo,{onClose:s}),n&&e(Ao,{})]})]})}function zo({onClose:n}){const[r,s]=c(void 0),[a,i]=c(void 0),o=["Export selected objects","Export all objects"];return t(qe,{className:"min-h-[104px] pt-0 flex flex-col gap-y-4",children:[e("div",{className:"h-1/3",children:e(tt,{options:o,value:a,onChange:i,placeholder:"Choose what to export",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(tt,{options:Object.values(Po),value:r,onChange:s,placeholder:"Choose a format",className:"h-full w-full text-sm",filterBy:"name",isClearable:!0}),e(De,{className:"w-full",isDisabled:!r||!a,onClick:()=>{n(r,a==o[1])},children:"Export Properties"})]})]})}function Ao({}){return e(qe,{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:"EXPORT IS IN PROGRESS"}),e("p",{className:"pt-2 grid justify-items-center",children:"PLEASE WAIT"})]}),e(Ue,{size:"lg"})]})})}function Do({collection:t}){const n=Ae(),{client:r}=Te(),{registry:s}=Ga(),a=function(e,t){let n=e.table_layout;if(n&&n.length>0)return n;e.type&&t&&(n=t?.getTypeLayout(ln(e.type)));return n&&n.length>0?n:void 0}(t,s);return t.dynamic?e(_o,{layout:a}):e(So,{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:a})}!function(e){e.CSV="CSV",e.JSON="JSON"}(Po||(Po={}));const Fo=n=>null===n?"None":t("div",{children:[e("div",{className:"text-sm",children:n.name}),e("div",{className:"text-xs text-gray-500",children:n.description})]});function Eo({className:t,defaultValue:n,onChange:r,isClearable:s,multiple:a}){const{registry:i}=Ga(),[o,l]=c(!1),[d,m]=c(),[u,p]=c([]);g(()=>{if(!o&&(l(!0),i&&n)){if(a&&Array.isArray(n)){const e=i.types.filter(e=>n.includes(e.id));p(e)}const e=i.types.find(e=>e.id===n);e&&m(e)}},[i,n,a]);const h=e=>{p(e),r(e)};return e("div",a?{className:"flex flex-col gap-4 content-between",children:e(tt,{options:i?.types||[],value:u,onChange:h,placeholder:"Choose Content Types...",optionLabel:Fo,className:t||"text-sm bg-background",filterBy:"name",isClearable:s||!1,multiple:!0})}:{className:"flex flex-col gap-4 content-between",children:e(tt,{options:i?.types||[],value:d,onChange:e=>{m(e||void 0),r(e)},placeholder:"Choose a Content Type...",optionLabel:Fo,className:t||"text-sm bg-background",filterBy:"name",isClearable:s||!1})})}function $o({onClose:n,redirect:r=!0,onAddToCollection:s}){const a=bn(),i=Ae(),[o,l]=c(!1),{client:d}=Te(),[m,u]=c({dynamic:!1,name:"",description:""});function p(e,t){u({...m,[e]:t})}return t("form",{onSubmit:e=>e.preventDefault(),children:[t(qe,{children:[e(He,{label:"Name",required:!0,children:e(Ge,{type:"text",value:m.name||"",onChange:e=>p("name",e)})}),e(He,{label:"Description",className:"mt-2",children:e(Ct,{value:m.description||"",onChange:e=>p("description",e.target.value)})}),e(He,{label:"Dynamic Collection",className:"mt-2",direction:"row",description:"Dynamically fetch content for the collection based on a query. If not enabled, then content must be added by users or agents.",children:e(St,{value:m.dynamic||!1,onChange:e=>p("dynamic",e)})}),!m.dynamic&&e(He,{label:"Allowed Content Types",className:"mt-4",description:"Optionally select which content types can be added to the collection. If not set, then all content types are allowed.",children:e(Eo,{defaultValue:m.allowed_types||null,onChange:e=>{Array.isArray(e)?p("allowed_types",e.map(e=>e.id)):p("allowed_types",e?[e.id]:[])},isClearable:!0,multiple:!0})}),e(He,{label:"Type",className:"mt-2",description:"Optionally select a content type to assign custom properties and data to the collection.",children:e(Eo,{defaultValue:m.type||null,onChange:e=>{Array.isArray(e)?p("type",e.length>0?e[0].id:null):p("type",e?.id||null)},isClearable:!0})})]}),e(Je,{children:e(De,{isDisabled:o,onClick:()=>{m?.name&&m.name.trim()?(m.name=m.name.trim(),m.description&&(m.description=m.description.trim()),null==m.dynamic&&(m.dynamic=!1),l(!0),d.store.collections.create(m).then(e=>{n(),i({title:"Collection created",description:`Collection "${e.name}" created successfully`,status:"success",duration:3e3}),r&&a(`/collections/${e.id}`),s&&s(e.id)}).catch(e=>{i({title:"Failed to create collection",description:e.message,status:"error",duration:5e3})}).finally(()=>l(!1))):i({title:"Name is required",description:"Please provide a name for the collection",status:"error",duration:5e3})},children:"Create Collection"})})]})}function Oo({isOpen:n,onClose:r}){return t(Ve,{onClose:r,isOpen:n,children:[e(We,{children:"Create a Collection"}),e($o,{onClose:r})]})}function Ro({}){const{client:r}=Te(),s=Ae(),[a,i]=c(),[o,l]=c(!0),[d,m]=c(!1),{data:u,error:p,refetch:h}=$e(()=>r.store.collections.search({}),[]);if(g(()=>{(u||p)&&l(!1)},[u,p]),p)return e(Oe,{title:"Collections fetch failed",children:p.message});return t(n,{children:[u&&(u.length>0?t(st,{className:"w-full",children:[e("thead",{children:t("tr",{children:[e("th",{children:"Name"}),e("th",{children:"Type"}),e("th",{children:"Created"}),e("th",{})]})}),e(pt,{columns:4,isLoading:o,children:u.map(n=>t(_t,{children:[e("td",{children:t("div",{className:"flex items-center gap-2",children:[Lo(n.dynamic),e(yn,{href:`/collections/${n.id}`,children:n.name})]})}),e("td",{children:n.type?.name||"-"}),e("td",{children:fn(n.created_at).fromNow()}),e("td",{className:"text-right",children:e(De,{variant:"destructive",size:"sm",onClick:()=>i(n.id),children:e(oe,{className:"size-4"})})})]},n.id))})]}):e(jt,{title:"No Collections",buttonLabel:"New Collections",onClick:()=>m(!0),children:"Get started by creating a new Collections."})),e(Oo,{isOpen:d,onClose:()=>m(!1)}),e(It,{isOpen:!!a,title:"Delete Collection",content:"Are you sure you want to delete this collection? This action cannot be undone.",onConfirm:async()=>{if(a)try{await r.store.collections.delete(a),s({title:"Collection deleted",status:"success",duration:3e3}),h()}catch(e){console.error("Failed to delete collection:",e),s({title:"Failed to delete collection",description:e.message||"An error occurred",status:"error",duration:5e3})}finally{i(void 0)}},onCancel:()=>i(void 0)})]})}function Lo(t){const n=t?"Dynamic Collection":"Static Collection",r=e(t?le:ce,{className:"size-5"});return e(Ee,{description:n,className:"mr-2",children:r})}function Mo({objects:n,isLoading:r}){const s=bn();return t(st,{className:"w-full",children:[e(Pt,{children:t("tr",{children:[e("th",{children:"Name"}),e("th",{children:"Strict Mode"}),e("th",{children:"Semantic Chunking"}),e("th",{children:"Updated At"})]})}),e(pt,{isLoading:r&&(!n||0===n.length),columns:4,children:n?.map(n=>t("tr",{onClick:()=>s(`/types/${n.id}`),className:"cursor-pointer hover:bg-muted",children:[e("td",{children:n.name}),e("td",{children:n.strict_mode?"Yes":"No"}),e("td",{children:n.is_chunkable?"Yes":"No"}),e("td",{children:fn(n.updated_at).fromNow()})]},n.id))})]})}fn.extend(On),fn.extend(On);class Uo{client;limit;result=new ht({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 Vo=d(void 0);function Wo(){return m(Vo)}function qo(){const e=Wo();return{...gt(e.result),search:e}}function Bo(){return Wo().objects.length}function Ho({title:n,isOpen:r,onClose:s,okLabel:a,initialPayload:i}){const o=Ae(),[l,d]=c(i?.name),[m,u]=c(i?.description),[p,h]=c(i?.strict_mode??!1);return t(Ve,{isOpen:r,onClose:()=>s(),children:[e(We,{children:n}),e(qe,{className:"pt-0",children:t("div",{className:"h-full flex flex-col gap-4 content-between",children:[t("div",{children:[e("label",{className:"block text-sm font-medium text-muted",children:"Name"}),e(Ge,{value:l,onChange:d})]}),t("div",{children:[e("label",{className:"block text-sm font-medium text-muted",children:"Description"}),e(Ct,{value:m,onChange:e=>u(e.target.value)})]})]})}),e(Je,{children:t("div",{className:"flex justify-end gap-4",children:[e(De,{variant:"secondary",onClick:()=>s(),children:"Cancel"}),e(De,{variant:"primary",onClick:()=>(()=>{if(!l)return void o({status:"error",title:"Name is required",duration:5e3});s({name:l,description:m,strict_mode:p}).then(()=>s()),d(void 0),u(void 0),h(!1)})(),children:a})]})})]})}var Go;function Jo({isDirty:n=!1}){const{store:r}=Te(),{reload:s}=Ga(),a=Ae(),[i,o]=c(!1),{search:l,isLoading:d,error:m,objects:p}=qo(),[h,f]=c(""),b=Tt(h,500),y=u(null);bt(y,()=>{i&&l.loadMore()},{deps:[i]}),g(()=>{l.search().then(()=>o(!0))},[]),g(()=>{l.query.name=h,l.search().then(()=>o(!0))},[b]);const[v,x]=c(void 0);g(()=>{l.query.chunkable=v?"Yes"==v:void 0,l.search().then(()=>o(!0))},[v]),g(()=>{n&&i&&l.search().then(()=>o(!0))},[n]);const[w,N]=c(!1);if(m)return e(Oe,{title:"Failed to fetch ObjectTypes",children:m.message});return t("div",{className:"flex flex-col gap-4 h-full",children:[t("div",{className:"flex flex-shrink-0 gap-4",children:[e(Ge,{placeholder:"Filter by Name",value:h,onChange:f}),e(tt,{className:"w-60",isClearable:!0,options:Object.values(Go),value:v,onChange:e=>{x(e)},placeholder:"Is Chunkable"})]}),t("div",{className:"flex-1 overflow-y-auto",children:[d||0!==p?.length?e(Mo,{objects:p,isLoading:d}):e(jt,{title:"No Type",buttonLabel:"Create Type",onClick:()=>{N(!0)},children:"Get started by creating a new Type."}),e(Ho,{okLabel:"Create",title:"Create Type",isOpen:w,onClose:async e=>e?r.types.create(e).then(async()=>{a({status:"success",title:"Type created",duration:2e3}),s(),l.search().then(()=>o(!0))}).catch(e=>{a({status:"error",title:"Error creating type",description:e.message,duration:5e3})}):(N(!1),Promise.resolve())})]})]})}function Ko({objectType:n,onSchemaUpdate:r,readonly:s=!1}){const{store:a}=Te(),i=Ae(),{theme:o}=Ye(),[d,m]=c(!1),p=In(n.object_schema),h=u(void 0),[g,f]=c(!1),b=l(()=>function(e){if(!e)return"";return JSON.stringify(e,null,2)}(p.schema),[p]),y=()=>{if(h.current){const e=h.current.getValue();try{const t=function(e){if(!e?.trim())return;return JSON.parse(e.trim())}(e);Yo(t),p.replaceSchema(t)}catch(e){return i({status:"error",title:"Invalid JSON Schema",description:e.message,duration:5e3}),!1}}return!0},v=t("div",{className:"flex gap-2 items-center",children:[e("div",{className:"text-base font-semibold",children:"Schema Editor"}),!s&&e("div",{children:e(De,{variant:"outline",size:"sm",onClick:()=>{g&&!y()||f(e=>!e)},children:g?"Edit Schema":"Edit Json"})})]});return e(zt,{title:v,className:"bg-background! h-[calc(100vh-197px)]",action:s?void 0:e(De,{isLoading:d,variant:"outline",size:"sm",onClick:()=>{g&&!y()||(m(!0),a.types.update(n.id,{object_schema:p.schema}).then(()=>{r(p),i({status:"success",title:"Schema updated",description:"The schema has been updated successfully",duration:2e3})}).catch(e=>{i({status:"error",title:"Failed to update schema",description:e.message,duration:5e3})}).finally(()=>{m(!1)}))},children:"Save Changes"}),children:g?e(kn,{value:b,language:"json",editorRef:h,theme:"dark"===o?"vs-dark":"vs",options:{readOnly:s}}):e(Pn,{schema:p,readonly:s})})}!function(e){e.true="Yes",e.false="No"}(Go||(Go={}));const Yo=e=>{try{new Wn({strict:!1}).compile(e)}catch(e){throw new Error(`Invalid JSON Schema definition: ${e.message}`)}};function Zo({children:t,limit:n,name:r,chunkable:s}){const{store:a}=Te(),i=l(()=>{const e=new Uo(a,n);return e.query.name=r,e.query.chunkable=s,e},[n]);return e(Vo.Provider,{value:i,children:t})}function Qo({isOpen:n,onClose:r,title:s="Select Content Type",children:a,initialSelectedType:i=null,allowNone:o=!0}){const{registry:l}=Ga(),[d,m]=c(i),u=l?.types||[],p=()=>{r(void 0)};return t(Ve,{isOpen:n,onClose:p,className:"w-full max-w-xl mx-auto",children:[e(We,{children:s}),t(qe,{children:[a,t("div",{className:"mb-4 mt-4",children:[t("label",{className:"block text-sm font-medium mb-2",children:["Content Type ",o&&e("span",{className:"text-gray-500 font-normal",children:"(Optional)"})]}),e(tt,o?{options:u,value:d,optionLabel:e=>e?e.name:"Select a content type",placeholder:"Select a content type or leave empty for automatic detection",onChange:e=>m(e||null),filterBy:"name",isClearable:!0}:{options:u,value:d,optionLabel:e=>e?e.name:"Select a content type",placeholder:"Select a content type",onChange:e=>m(e||null),filterBy:"name"})]}),!d&&t("div",{className:"flex items-center text-attention",children:[e(Q,{className:"size-4 mr-1"}),"Automatic Type Detection",e(Ee,{description:"Vertesia will analyze the content and select the most appropriate type. This is recommended for most uploads and ensures optimal processing.",placement:"top",size:"xs",children:e(re,{className:"size-3 ml-2"})})]})]}),t(Je,{children:[e(De,{variant:"ghost",onClick:p,alt:"Cancel",children:"Cancel"}),e(De,{onClick:()=>{r(d?.id??null),m(null)},alt:"Confirm selection",children:"Confirm"})]})]})}function Xo({objectType:t,onLayoutUpdate:n,readonly:r=!1}){const s=Ae(),{theme:a}=Ye(),[i,o]=c(!1),{store:d}=Te(),m=u(void 0),p=l(()=>el(t.table_layout),[t.table_layout]),h=(e,t)=>{s({status:"error",title:e,description:t,duration:5e3})};return e(zt,{title:"Table Layout Editor",className:"bg-background! h-[calc(100vh-197px)]",action:r?void 0:e(De,{isLoading:i,variant:"outline",size:"sm",onClick:()=>{if(!m.current)return;const e=m.current.getValue();let r;if(e)try{r=JSON.parse(e)}catch(e){return h("Invalid JSON",e.message)}else r=null;return Array.isArray(r)?r.some(e=>!e||!e.name||!e.field)?h("Invalid JSON","A table layout entry must contain the following properties:] {field, name, converter?}"):(o(!0),void d.types.update(t.id,{table_layout:r}).then(e=>{s({status:"success",title:"Table Layout updated",description:"The table layout has been updated successfully",duration:2e3}),n(e.table_layout)}).catch(e=>{s({status:"error",title:"Failed to update table layout",description:e.message,duration:5e3})}).finally(()=>{o(!1)})):h("Invalid JSON","The table layout must be an array")},children:"Save Changes"}),children:e(kn,{value:p,language:"json",editorRef:m,theme:"dark"===a?"vs-dark":"vs",options:{readOnly:r}})})}function el(e){return e?JSON.stringify(e,null,2):"[\n\n]"}function tl({refetch:r,collection:s}){const a=s.type?.id,i=u(void 0),o=Ae(),{theme:d}=Ye(),{client:m}=Te(),[p,h]=c(!1),[g,f]=c({name:s.name,description:s.description||"",query:s.query?JSON.stringify(s.query,null,2):"",tags:s.tags||[],type:s.type?.id||"",allowed_types:s.allowed_types||[]}),b=l(()=>el(s.table_layout),[s.table_layout]),y=(e,t)=>{f({...g,[e]:t})};return t("div",{className:"flex flex-col gap-4 py-2",children:[t(zt,{title:"Configuration",action:e(De,{size:"lg",isDisabled:p,onClick:()=>{let e;try{e=g.query?JSON.parse(g.query):void 0}catch(e){return void o({title:"Invalid Query JSON",description:e.message,status:"error",duration:5e3})}const t={name:g.name,description:g.description,query:e,tags:g.tags,type:g.type,allowed_types:g.allowed_types};let n;if(t.name||(n="Name is required"),t.type||(t.type=null),n)o({title:"Validation failed",description:n,status:"error",duration:5e3});else{if(i.current){const e=i.current.getValue();if(e)try{t.table_layout=JSON.parse(e)}catch(e){return void o({title:"Invalid Table Layout",description:e.message,status:"error",duration:5e3})}else t.table_layout=null}h(!0),m.store.collections.update(s.id,t).then(()=>{r(),o({title:"Collection updated",description:"Collection has been updated successfully",status:"success",duration:3e3})}).catch(e=>{o({title:"Failed to update collection",description:e.message,status:"error",duration:5e3})}).finally(()=>{h(!1)})}},children:"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:"Created By"}),t("div",{className:"gap-2 flex items-center",children:[e(Ln,{userRef:s.created_by,showTitle:!0}),t("span",{children:["at ",fn(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:"Updated By"}),t("div",{className:"gap-2 flex items-center",children:[e(Ln,{userRef:s.updated_by,showTitle:!0}),t("span",{children:["at ",fn(s.updated_at).format("YYYY-MM-DD HH:mm:ss")]})]})]})]}),e(He,{label:"Name",required:!0,children:e(Ge,{value:g.name,onChange:e=>y("name",e)})}),e(He,{label:"Description",children:e(Ct,{value:g.description,onChange:e=>y("description",e.target.value)})}),!s.dynamic&&e(He,{label:"Allowed Content Types",description:"Select which content types can be added to the collection. If not set, then all content types are allowed.",children:e(Eo,{defaultValue:g.allowed_types||null,onChange:e=>{Array.isArray(e)?y("allowed_types",e.map(e=>e.id)):y("allowed_types",e?[e.id]:[])},isClearable:!0,multiple:!0})}),s.dynamic&&e(He,{label:"Query",description:"Define the query to dynamically fetch content for the collection.",children:e(Ct,{className:vt.INPUT,value:g.query,onChange:e=>y("query",e.target.value)})}),e(He,{label:"Table Layout",description:"Define a custom layout for displaying the collection in tables.",className:"h-[200px]",children:e(kn,{className:"border-1 rounded-md border-border",value:b,language:"json",editorRef:i,theme:"dark"===d?"vs-dark":"vs"})}),e(He,{label:"Type",description:"Select a content type to assign custom properties and data to the collection.",children:e(Eo,{defaultValue:g.type||null,onChange:e=>{Array.isArray(e)?y("type",e.length>0?e[0].id:null):y("type",e?.id||null)},isClearable:!0})})]}),a&&e(nl,{typeId:a,collection:s}),!s.dynamic&&t(n,{children:[e(Mn,{collection:s}),e(Un,{collection:s})]})]})}function nl({typeId:t,collection:n}){const[r,s]=c({}),a=Ae(),{client:i}=Te(),[o,d]=c(!1),{data:m,error:u}=$e(()=>i.store.types.retrieve(t),[t]),p=m?.object_schema||{},h=l(()=>new Tn(p,n.properties||{}),[p,n.properties]);if(u)return e(Oe,{title:"Failed to load type",children:u.message});if(!m)return null;return e(zt,{title:"Properties",action:e(De,{size:"lg",isLoading:o,type:"submit",onClick:()=>(e=>{if(!e||!Object.keys(e).length)return;const t={properties:e||{}};d(!0),i.store.collections.update(n.id,t).then(()=>{a({title:"Collection properties updated",description:"Collection has been updated successfully",status:"success",duration:3e3})}).catch(e=>{a({title:"Failed to update collection properties",description:e.message,status:"error",duration:5e3})}).finally(()=>{d(!1)})})(r),children:"Save"}),children:e(zn,{object:h,onChange:e=>{e instanceof Tn&&s(e.value)}})})}function rl({onChange:n,value:r,disabled:s=!1,placeholder:a="Select a collection",searchPlaceholder:i="Search collections",filterOut:o,allowDynamic:d=!0,multiple:m=!1}){const{client:u}=Te(),[h,g]=c(""),[f,b]=c(!1),[y,x]=c(!1),w=Tt(h,300),N=p(async e=>{b(!0);const t=e.trim(),n=await u.store.collections.search({dynamic:!!d&&void 0,name:y&&t||void 0});return b(!1),!y&&n.length>=1e3&&x(!0),o&&o.length>0?n.filter(e=>!o.includes(e.id)):n},[u,d,o,y]),{data:k,error:C}=$e(()=>N(y?w:""),[y?w:"",N]),S=l(()=>k?m&&Array.isArray(r)?k.filter(e=>r.includes(e.id)):m||"string"!=typeof r?m?[]:void 0:k.find(e=>e.id===r):m?[]:void 0,[k,r,m]),_=p(e=>{if(m){const t=Array.isArray(r)?r:[];if(t.includes(e.id)){const r=t.filter(t=>t!==e.id),s=k?.filter(e=>r.includes(e.id))||[];n(r,s)}else{const r=[...t,e.id],s=k?.filter(e=>r.includes(e.id))||[];n(r,s)}}else n(e.id,e)},[n,r,k,m]),j=p(()=>{n(void 0,void 0)},[n]),I=p(e=>{g(e)},[]),P=h.trim().length>0,T=l(()=>{if(!k)return[];if(y)return k;if(!P)return k;const e=h.toLowerCase();return k.filter(t=>t.name.toLowerCase().includes(e))},[k,y,P,h]),z=S&&P;if(C)return e(Oe,{title:"Collection fetch failed",children:C.message});return t(at,{children:[e(it,{asChild:!0,children:t(De,{variant:"outline",role:"combobox","aria-haspopup":"listbox",className:ze("w-full justify-between min-w-0"),disabled:s,children:[e("span",{className:"truncate flex-1 text-left min-w-0",children:m&&Array.isArray(S)&&S.length>0?1===S.length?S[0].name:`${S.length} collections selected`:m||!S||Array.isArray(S)?a:S.name}),e(se,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e(ot,{className:"mt-2 mb-2 w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:t(At,{shouldFilter:!1,children:[t("div",{className:"flex justify-between items-center border-b px-3","cmdk-input-wrapper":"",children:[e(Dt,{placeholder:i,value:h,onValueChange:I,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"}),f&&e("div",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"})]}),e(Ft,{children:f?"Searching...":P?"No collections found.":"No collections available."}),t(Et,{className:"max-h-[300px] overflow-auto",children:[z&&!m&&e($t,{value:"__clear__",onSelect:j,className:"text-muted-foreground",children:"Clear selection"}),T.map(n=>{const s=m&&Array.isArray(r)?r.includes(n.id):r===n.id;return t($t,{value:n.id,onSelect:()=>_(n),className:"flex items-center justify-between",children:[e("span",{className:"truncate",children:n.name}),s&&e(v,{className:"ml-2 h-4 w-4 shrink-0"})]},n.id)})]})]})})]})}function sl({collection:t}){const{client:n}=Te(),[r,s]=c(void 0),[a,i]=c(t.shared_properties||[]),o=Ae();g(()=>{t.type?.id&&n.store.types.retrieve(t.type.id).then(s)},[t.type?.id]);const l=r?Object.keys(r.object_schema?.properties||{}):[];return e(zt,{title:"Shared Properties",description:"Add properties to share across all members in the collection. This feature requires to enable shared property synchronization on the project.",action:e(De,{size:"lg",isLoading:!1,onClick:()=>{n.store.collections.update(t.id,{shared_properties:a}).then(()=>{o({title:"Updated shared properties",status:"success"})}).catch(e=>{o({title:"Failed to update shared properties",description:e.message,status:"error"})})},children:"Save"}),children:e("div",{className:"",children:e(Ot,{value:a,onChange:e=>{i(e)},options:l,placeholder:"Select properties to share"})})})}function al({collection:t}){const{client:n}=Te(),[r,s]=c(t.skip_head_sync??!1),[a,i]=c(!1),o=Ae();return e(zt,{title:"Synchronize Member Heads",description:"When a new HEAD version of a member is created the colleciton will be updated to point to the new HEAD.",children:e(St,{disabled:a,value:!r,onChange:e=>{const r=!e;i(!0),n.store.collections.update(t.id,{skip_head_sync:r}).then(()=>{o({title:"Updated skip head sync setting",status:"success"}),s(r)}).catch(e=>{o({title:"Failed to update skip head sync",description:e.message,status:"error"})}).finally(()=>{i(!1)})},children:"Enable synchronizing member heads"})})}function il({action:n,objectIds:r,children:s}){const{store:a}=Te(),i=Ae(),[o,l]=c(!1),d=p(()=>(l(!0),Promise.resolve(!0)),[]);_l(n.id,d);return t("div",{children:[s,e(Qo,{isOpen:o,onClose:e=>{l(!1),void 0!==e&&a.runOperation({name:"change_type",ids:r,params:{typeId:e}}).then(e=>{i({status:"success",title:"Change Type",description:`Change the type of ${r.length} objects is ${"in_progress"===e.status?"in progress":"completed"}`,duration:2e3})}).catch(e=>{i({status:"error",title:"Error changing type",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 ol={id:"changeType",name:"Change Content Type",description:"Change the Content Type of the selected documents",confirm:!1,component:il};function ll({action:r,callback:s,children:a}){const[i,o]=c(!1),l=r.confirmationText||`Are you sure you want to ${r.name}?`,d=p(e=>r.confirm?(o(!0),Promise.resolve(!0)):s(e),[r.confirm,s]),m=_l(r.id,d);return t(n,{children:[a,e(It,{onConfirm:()=>{o(!1),s({...m.params,action:r})},onCancel:()=>o(!1),title:"Are you sure?",content:l,isOpen:i})]})}function cl({action:t,objectIds:n,children:r}){const s=Sl(),a=Ae(),{client:i}=Te(),o=Qi(),l=bn(),c=p(()=>{if(!n||!n.length)return a({status:"error",title:"No objects selected",description:"Please select objects to delete",duration:3e3}),Promise.resolve(!1);function e(e,t){if(e.length<=t)return e;const n=e.lastIndexOf("."),r=-1!==n?e.substring(n):"";return`${(-1!==n?e.substring(0,n):e).substring(0,t-r.length-3)}...${r}`}return Promise.all(n.map(e=>i.store.objects.delete(e))).then(t=>{const r=t.length>1?"s":"";if(a({status:"success",title:`${t.length} object${r} deleted`,description:`Objects ${e(t.map(e=>e.id).join(", "),100)} have been deleted`,duration:2e3}),o){s.params?.selection?.removeAll();const e=JSON.parse(JSON.stringify(o.facets));n.length===e._value.total&&o.resetFacets(),o.search()}else l("/objects")}).catch(e=>{a({status:"error",title:"Error deleting objects",description:e.message,duration:5e3})})},[n]);return e(ll,{action:t,callback:c,children:r})}const dl={id:"delete",name:"Delete",description:"Delete the selected objects",confirm:!0,confirmationText:"Are you sure you want to delete all the selected objects? This action cannot be undone.",component:cl,destructive:!0},ml={id:"deleteFromCollections",name:"Delete Objects",description:"Delete the selected objects",confirm:!0,confirmationText:"Are you sure you want to delete the selected objects?\nThis is not removable from collections.",component:cl,destructive:!0};function ul({action:t,objectIds:n}){const{store:r}=Te(),s=Ae(),[a,i]=c(!1),[o,l]=c(!1),d=p(()=>(i(!0),Promise.resolve(!0)),[]),m=_l(t.id,d);return e(To,{isExporting:o,isOpen:a,onClose:(e,t)=>{if(e&&(t||n.length>0)){l(!0);const a=m.params?.search?.query||{},o=m.params?.search?.result?.value?.objects?.map(e=>e.id)||void 0,c=async e=>r.objects.list({query:{parent:e}}).then(e=>e.map(e=>e.id));(async()=>t?o?a.vector?o:[]:0===n.length?[]:(await c(n[0])).concat(n):n)().then(o=>{r.objects.exportProperties({objectIds:o,type:e,query:t&&!a.vector?a:{type:a.type}}).then(r=>{let a;if(e===Po.CSV)a=new Blob([r.data],{type:r.type});else if(e===Po.JSON)a=new Blob([JSON.stringify(r.data)],{type:r.type});else{const e=r.data;a=new Blob([new Uint8Array(e.data)],{type:r.type})}const i=window.URL.createObjectURL(a),o=document.createElement("a");o.download=r.name,o.href=i,o.click(),s({status:"success",title:"Export Properties",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:"Error Export Properties",description:e.message,duration:5e3})}).finally(()=>{l(!1),i(!1)})})}else i(!1)}})}const pl={id:"exportProperties",name:"Export Properties",description:"Export all Object Properties",confirm:!1,component:ul};function hl({action:t,objectIds:n,collectionId:r}){const s=Sl(),a=Ae(),{client:i}=Te(),o=Qi(),l=p(()=>n&&n.length?r?i.store.collections.deleteMembers(r,n).then(()=>{const e=n.length>1?"s":"";a({status:"success",title:`${n.length} object${e} removed from collection`,description:"Objects have been removed from the collection",duration:2e3}),o&&(s.params?.selection?.removeAll(),o.search())}).catch(e=>{a({status:"error",title:"Error removing objects from collection",description:e.message,duration:5e3})}):(a({status:"error",title:"No collection context",description:"Cannot remove objects: no collection specified",duration:3e3}),Promise.resolve(!1)):(a({status:"error",title:"No objects selected",description:"Please select objects to remove from collection",duration:3e3}),Promise.resolve(!1)),[n,r]);return e(ll,{action:t,callback:l})}const gl={id:"removeFromCollection",name:"Remove from Collection",description:"Remove the selected objects from this collection",confirm:!0,confirmationText:"Are you sure you want to remove the selected objects from this collection?",component:hl,destructive:!0};function fl({action:t,objectIds:n,collectionId:r}){const s=Ae(),{client:a}=Te(),[i,o]=c(!1),l=p(()=>(o(!0),Promise.resolve(!0)),[]);return _l(t.id,l),e(yl,{isOpen:i,onClose:e=>{if(o(!1),e)return a.store.workflows.rules.execute(e,n,{collection_id:r}).then(()=>{s({title:"Workflow started",status:"success",duration:3e3})}).catch(e=>{s({title:"Error starting workflow",status:"error",description:e.message,duration:9e3})})}})}const bl={id:"startWorkflow",name:"Start Workflow",description:"Start an workflow on the selected objects",confirm:!1,hideInList:!0,component:fl};function yl({isOpen:n,onClose:r}){return t(Ve,{onClose:()=>r(void 0),isOpen:n,className:"",children:[e(We,{children:"Start a Workflow by Rule"}),e(xl,{onClose:r})]})}function vl(n){return{label:t("div",{children:[e("div",{children:n.name}),e("div",{className:"text-sm text-muted",children:n.description})]}),reverse:!0}}function xl({onClose:n}){const[r,s]=c(void 0),a=Sl();return t("div",{children:[t(qe,{children:[e("div",{className:"pb-2",children:"Choose a workflow rule to start:"}),e("div",{className:"max-h-[420px] overflow-y-scroll border-border border rounded-md",children:e(Rt,{options:a.wfRules,optionLayout:vl,onChange:e=>{s(e)},value:r})})]}),t(Je,{children:[e(De,{variant:"secondary",onClick:()=>n(),children:"Cancel"}),e(De,{onClick:()=>{r&&n(r.id)},isDisabled:!r,children:"Start"})]})]})}class wl{params;allActions=[pl,ol,bl,Pl,dl,gl,ml];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)}async loadWorkflows(){return this.params.client.workflows.rules.list().then(e=>{this.wfRules=e.map(e=>({id:e.id,name:e.name,description:e.description,confirm:!1,isWorkflow:!0,component:fl})).sort((e,t)=>e.name.localeCompare(t.name))}),this.wfRules}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 Nl=d(void 0);function kl({children:n}){const r=Mi(),s=Ae(),{client:a}=Te(),i=Qi(),{data:o,error:c}=$e(()=>a.workflows.rules.list().then(e=>e.map(e=>({id:e.id,name:e.name,description:e.description,confirm:!1,isWorkflow:!0,component:fl})).sort((e,t)=>e.name.localeCompare(t.name))),[]),d=l(()=>{const e=new wl({selection:r,toast:s,client:a,search:i});return e.wfRules=o,e},[r,o]);return c?e(Oe,{title:"Failed to fetch workflows",children:c.message}):d&&t(Nl.Provider,{value:d,children:[e(Cl,{}),n]})}function Cl({}){const t=Sl(),n=t.params.selection,r=n.getObjectId(),s=n.isSingleSelection()&&r?[r]:n.getObjectIds();return e("div",{style:{display:"none"},children:t.allActions.map(t=>e(t.component,{action:t,objectIds:s,collectionId:n.collectionId},t.id))})}function Sl(){const e=m(Nl);if(!e)throw new Error("You cannot use useActionContext outside an ActionProvider");return e}function _l(e,t){const n=Sl();return g(()=>n.registerCallback(e,t),[n,e,t]),n}function jl(e){const t=Sl();return g(()=>(t.startWorkflow=e,()=>{t.startWorkflow=void 0}),[e,t]),t}function Il({action:t,objectIds:n}){const[r,s]=c(!1),a=p(()=>(n.length>0&&s(!0),Promise.resolve(!0)),[n]);return _l(t.id,a),r&&e(Ze,{children:e(Tl,{objectIds:n,isOpen:r,onClose:()=>{s(!1)}})})}const Pl={id:"addToCollection",name:"Add to Collection",description:"Add documents to a collection",confirm:!1,component:Il};function Tl({isOpen:n,onClose:r,objectIds:s}){return t(Ve,{isOpen:n,onClose:r,className:"max-w-lg w-full min-w-0 overflow-hidden",children:[e(We,{className:"flex flex-col min-w-0 overflow-hidden",children:"Add to a Collection"}),e(Lt,{className:"min-w-0 overflow-hidden",children:"Add the selected objects to an existing collection or create a new one."}),e("div",{className:"min-w-0 max-w-full overflow-hidden",children:e(zl,{onClose:r,objectIds:s})})]})}function zl({onClose:n,objectIds:r}){const s=Ae(),{client:a}=Te(),[i,o]=c(),l=({collectionId:e})=>{e&&r?.length&&a.store.collections.addMembers(e,r).then(()=>{s({title:"Add to collection success",status:"success",description:`Added ${r.length} objects to the selected collection`,duration:3e3}),n()}).catch(()=>{s({title:"Add to collection failure",status:"error",description:"Failed to add the selected objects to the collection",duration:5e3})})},d=[{name:"select",label:"Select Collection",content:t("div",{className:"p-4 min-w-0 max-w-full overflow-hidden",children:[e(Mt,{level:5,children:"Choose from existing collections"}),e(qe,{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(rl,{onChange:(e,t)=>{"string"==typeof e||void 0===e?o(e):Array.isArray(e)&&e.length>0?o(e[0]):o(void 0)},value:i})})}),e(Je,{children:e(De,{isDisabled:!i,onClick:()=>i&&l({collectionId:i}),children:"Add to Collection"})})]})},{name:"create",label:"Create new",content:e("div",{className:"p-4",children:e($o,{onClose:n,onAddToCollection:e=>l({collectionId:e}),redirect:!1})})}];return t(Ut,{defaultValue:"select",tabs:d,fullWidth:!0,children:[e(Vt,{}),e(Wt,{})]})}function Al(){const n=Mi(),r=n.size(),s=r>1?"s":"",a=n?.hasSelection(),i=n?.isSingleSelection();return e(kl,{children:t("div",{className:"flex items-center gap-x-2",children:[a&&!i&&t("div",{className:"flex items-center gap-x-1 shrink-0",children:[t("div",{className:"text-sm nowrap",children:[r," document",s," selected"]}),e(De,{title:"Clear selection",variant:"ghost",onClick:()=>{n?.removeAll()},children:e(C,{className:"size-4"})})]}),e(Ol,{selection:n,children:e(De,{variant:"ghost",alt:"More action",size:"sm",children:e(de,{size:16})})}),a&&e(Dl,{selection:n})]})})}function Dl({}){return e(El,{})}function Fl({collectionId:r,allowFolders:s=!0}){const[a,i]=c([]),[o,l]=c(!1);return t(n,{children:[e(De,{onClick:()=>l(!0),children:"Upload"}),e(ao,{collectionId:r??"",isOpen:o,onClose:()=>{l(!1),i([])},files:a,title:"Upload Files",onUploadComplete:e=>{e&&e.success&&i([])},allowFolders:s})]})}function El(){const t=Sl();return t.params.selection.hasSelection()&&e(De,{onClick:()=>t.run(bl.id),children:"Start Workflow"})}function $l(e){return{label:e.name,className:r("flex-1 px-2 py-2 hover:bg-accent nowrap",e.destructive?"text-destructive":"")}}function Ol({selection:n,children:r}){const s=Sl();return t(at,{hover:!0,children:[e(it,{children:r}),e(ot,{className:"p-0 w-50",align:"end",sideOffset:6,children:e(Rl,{executeAction:e=>{s.run(e.id)},selection:n})})]})}function Rl({executeAction:t,selection:n}){const r=Sl(),s=n?.hasSelection()?r.actions.filter(e=>!e.hideInList):[pl];return e("div",{className:"rounded-md shadow-md py-2",children:e("div",{className:"px-1 text-sm",children:e(Rt,{options:s,optionLayout:$l,onChange:e=>{t(e)},noCheck:!0})})})}const Ll=["className","cardClassName","headerClassName","contentClassName","timestampClassName","senderClassName","iconClassName","detailsClassName","artifactsClassName","proseClassName"];function Ml(e,t,...n){const r={};for(const s of Ll)r[s]=ze(e[s],t[s],...n.map(e=>e?.[s]));return r}const Ul={[Jt.ANSWER]:{borderColor:"border-l-info",iconColor:"text-info",sender:"Agent",Icon:me},[Jt.COMPLETE]:{borderColor:"border-l-success",iconColor:"text-success",sender:"Completed",Icon:P},[Jt.IDLE]:{borderColor:"border-l-info",iconColor:"text-info",sender:"Ready",Icon:pe},[Jt.REQUEST_INPUT]:{borderColor:"border-l-attention",iconColor:"text-attention",sender:"Input",Icon:ue},[Jt.QUESTION]:{borderColor:"border-l-muted",iconColor:"text-muted",sender:"User",Icon:ue},[Jt.THOUGHT]:{borderColor:"border-l-purple-500",iconColor:"text-purple-600 dark:text-purple-400",sender:"Agent",Icon:me},[Jt.ERROR]:{borderColor:"border-l-destructive",iconColor:"text-destructive",sender:"Error",Icon:T},[Jt.UPDATE]:{borderColor:"border-l-success",iconColor:"text-success",sender:"Update",Icon:re},[Jt.PLAN]:{borderColor:"border-l-attention",iconColor:"text-attention",sender:"Plan",Icon:A},[Jt.TERMINATED]:{borderColor:"border-l-muted",iconColor:"text-muted",sender:"Terminated",Icon:P},[Jt.WARNING]:{borderColor:"border-l-attention",iconColor:"text-attention",sender:"Warning",Icon:T},[Jt.SYSTEM]:{borderColor:"border-l-muted",iconColor:"text-muted",sender:"System",Icon:re},[Jt.STREAMING_CHUNK]:{borderColor:"border-l-info",iconColor:"text-info",sender:"Agent",Icon:me},[Jt.BATCH_PROGRESS]:{borderColor:"border-l-blue-500",iconColor:"text-blue-600 dark:text-blue-400",sender:"Batch",Icon:z},default:{borderColor:"border-l-muted",iconColor:"text-muted",sender:"Agent",Icon:me}};const Vl=h(function({message:n,showPulsatingCircle:r=!1,onSendMessage:s,className:a,cardClassName:i,headerClassName:o,contentClassName:d,timestampClassName:m,senderClassName:p,iconClassName:h,detailsClassName:f,artifactsClassName:b,proseClassName:y,messageStyleOverrides:v,StoreLinkComponent:x,CollectionLinkComponent:N}){const[k,C]=c(!1),{client:S}=Te(),_=Ae(),j=lr(),{openImage:P}=Pr(),T=u(S);T.current=S;const z=u(j);z.current=j;const{renderContent:A,isDownloading:D}=la({client:S,toast:_}),F=l(()=>{const e=Ul[n.type]||Ul.default,t=v?.default,r=v?.[n.type];return{...e,...t,...r,...Ml(e,{className:a,cardClassName:i,headerClassName:o,contentClassName:d,timestampClassName:m,senderClassName:p,iconClassName:h,detailsClassName:f,artifactsClassName:b,proseClassName:y},t,r)}},[n.type,v,a,i,o,d,m,p,h,f,b,y]),E=l(()=>{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()*$r.length);e=e.replace(/%thinking_message%/g,$r[t])}return e},[n.message]),$=l(()=>E?function(e,t,n){if("string"!=typeof e)return e;if(t===Jt.THOUGHT||"string"==typeof n&&(n.toLowerCase().includes("thinking about")||n.toLowerCase().includes("i'm thinking")||n.toLowerCase().includes("💭"))){let t=e;return/\d+\.\s+.+/.test(t)&&(t=t.replace(/(\d+\.\s+.+?)(?=\s+\d+\.\s+|$)/g,"$1\n\n"),t=t.replace(/(\d+\.\s+.+\n)([^\d\n][^:])/g,"$1 $2")),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+/g,"\n- ")),t}return/\d+\.\s+.+/.test(e)&&!e.includes("\n\n")?e.replace(/(\d+\.\s+.+?)(?=\s+\d+\.\s+|$)/g,"$1\n\n"):e}(E,n.type,"string"==typeof n.message?n.message:void 0):"",[E,n.type,n.message]),O=async e=>{const t="string"==typeof E?E:"";if(!t.trim())return void _({status:"error",title:"No content to export",duration:2e3});const r=`Message ${fn(n.timestamp).format("YYYY-MM-DD HH-mm-ss")}`;await A(t,{format:e,title:r,artifactRunId:W})},R="string"==typeof E&&E.trim().length>0,L=l(()=>({a:({node:t,ref:n,...r})=>{const s=r.href||"";if(s.includes("/store/objects")){if(x){const t=s.split("/store/objects/")[1]||"";return e(x,{href:s,documentId:t,children:r.children})}return e(yn,{href:s,topLevelNav:!0,children:r.children})}if(s.includes("/store/collections")){if(N){const t=s.split("/store/collections/")[1]||"";return e(N,{href:s,collectionId:t,children:r.children})}return e(yn,{href:s,topLevelNav:!0,children:r.children})}return e("a",{...r,target:"_blank",rel:"noopener noreferrer"})},img:({node:t,ref:n,...r})=>e("img",{...r,className:"max-w-full h-auto rounded-lg shadow-md my-3 cursor-pointer hover:shadow-lg transition-shadow",loading:"lazy",onClick:()=>r.src&&P(r.src,r.alt)})}),[P,x,N]),M=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 e("div",{className:ze("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.proseClassName),style:{overflowWrap:"anywhere"},children:e(vn,{artifactRunId:r,onProposalSelect:e=>s?.(e),onProposalSubmit:e=>s?.(e),components:L,children:t})})},[U,V]=c([]),W=n.workflow_run_id,q=n.details,B=q?.outputFiles??q?.files,H=Array.isArray(B)?B.join(","):"";g(()=>{(async()=>{if(!W||!Array.isArray(B)||0===B.length)return void V([]);const e=T.current,t=z.current;try{const n=await Promise.all(B.map(async n=>{if("string"!=typeof n||!n.trim())return null;const r=n.trim(),s=r.startsWith("artifact:")?r.slice(9):r,a=s.split(".").pop()?.toLowerCase()||"",i=new Set(["png","jpg","jpeg","gif","webp","bmp","svg"]).has(a),o=i?"inline":"attachment";try{const n=cr(W,s,o);let a;if(t)a=await t.getOrFetch(n,async()=>(await e.files.getArtifactDownloadUrl(W,s,o)).url);else{a=(await e.files.getArtifactDownloadUrl(W,s,o)).url}return{displayName:r,artifactPath:s,url:a,isImage:i}}catch(e){return console.error(`Failed to resolve artifact URL for ${s}`,e),null}}));V(n.filter(e=>!!e))}catch(e){console.error("Error loading artifact URLs from message details",e),V([])}})()},[W,H]);const G=Lr(n),{Icon:J}=F;return e("div",{className:ze("w-full max-w-full",F.className),children:t("div",{className:ze("border-l-4 bg-white dark:bg-gray-900 mb-4 w-full max-w-full overflow-hidden",F.borderColor,F.cardClassName),"data-workstream-id":G,children:[t("div",{className:ze("flex items-center justify-between px-4 py-1.5",F.headerClassName),children:[t("div",{className:"flex items-center gap-1.5",children:[e("div",{className:ze(r?"animate-fadeIn":"",F.iconClassName),children:r?e(Nr,{size:"sm",color:"blue"}):e(J,{className:`size-4 ${F.iconColor}`})}),e("span",{className:ze("text-xs font-medium text-muted",F.senderClassName),children:F.sender}),"main"!==G&&"all"!==G&&e(lt,{variant:"default",className:"text-xs text-muted ml-1",children:G})]}),t("div",{className:"flex items-center gap-1.5 print:hidden",children:[e("span",{className:ze("text-[11px] text-muted/70",F.timestampClassName),children:fn(n.timestamp).format("HH:mm:ss")}),e(De,{variant:"ghost",size:"xs",onClick:()=>{const e=E||"",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(()=>{_({status:"success",title:"Copied to clipboard",duration:2e3})})},className:"text-muted/50 hover:text-muted h-5 w-5 p-0",title:"Copy message",children:e(I,{className:"size-3"})}),R&&t(qt,{trigger:e(De,{variant:"ghost",size:"xs",className:"text-muted/50 hover:text-muted h-5 w-5 p-0",title:"Export message",disabled:D,children:e(w,{className:"size-3 "+(D?"animate-pulse":"")})}),children:[e(Bt,{onClick:()=>O(Qt.pdf),children:"Export as PDF"}),e(Bt,{onClick:()=>O(Qt.docx),children:"Export as Word"})]})]})]}),t("div",{className:ze("px-4 pb-3 bg-white dark:bg-gray-900 overflow-hidden",F.contentClassName),children:[n.type===Jt.REQUEST_INPUT&&n.details?.ux?(()=>{const t=n.details.ux;return e(Fr,{question:"string"==typeof E?E:"",options:t.options,variant:t.variant,multiSelect:t.multiSelect,allowFreeResponse:t.allowFreeResponse,placeholder:t.placeholder,onSelect:e=>s?.(e),onMultiSelect:e=>s?.(e.join(", ")),onSubmit:e=>s?.(e),hideBorder:!0})})():E&&e("div",{className:"message-content break-words w-full",style:{overflowWrap:"anywhere",wordBreak:"break-word"},children:M($||E)}),U.length>0&&t("div",{className:ze("mt-3 text-xs",F.artifactsClassName),children:[e("div",{className:"font-medium text-muted mb-1",children:"Artifacts"}),U.some(e=>e.isImage)&&e("div",{className:"mb-2 flex flex-wrap gap-3",children:U.filter(e=>e.isImage).map(({displayName:n,artifactPath:r,url:s})=>t("div",{className:"max-w-xs cursor-pointer",onClick:()=>P(s,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})]},`${r}-preview`))}),e("div",{className:"flex flex-wrap gap-2 print:hidden",children:U.map(({displayName:t,artifactPath:n,url:r})=>e(De,{variant:"outline",size:"xs",className:"px-2 py-1 text-xs",onClick:()=>window.open(r,"_blank"),title:n,children:t},n+r))})]}),n.details&&t("div",{className:ze("mt-2 print:hidden",F.detailsClassName),children:[t("button",{onClick:()=>C(!k),className:"text-[11px] text-muted flex items-center",children:[k?"Hide":"Show"," details",e("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-3 w-3 ml-1 transition-transform "+(k?"rotate-180":""),fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),k&&e("div",{className:"mt-1 p-1.5 bg-muted border border-mixer-muted/40 rounded text-sm",children:"string"==typeof n.details?M(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.showPulsatingCircle===t.showPulsatingCircle&&e.onSendMessage===t.onSendMessage&&e.messageStyleOverrides===t.messageStyleOverrides&&Ll.every(n=>e[n]===t[n]));const Wl=o.memo(function({text:n,workstreamId:r,revealSpeed:s=300,isComplete:a=!1,timestamp:i,className:o,cardClassName:d,headerClassName:m,contentClassName:h,proseClassName:f,senderClassName:b,iconClassName:y}){const[v,x]=c(0),[w,N]=c(""),k=u(null),C=u(n.length),S=u(0),_=u(i||Date.now()),j=u(n),P=u(0),T=u(performance.now()),z=u(s),A=u(0);g(()=>{const e=performance.now(),t=n.length-P.current,r=e-T.current;if(t>0&&r>30){const e=t/r*1e3,n=.2;z.current=z.current*(1-n)+e*n,z.current=Math.max(50,Math.min(2e3,z.current))}P.current=n.length,T.current=e},[n.length]),C.current=n.length,j.current=n;const D=p(()=>{let e=performance.now();const t=n=>{const r=n-e;e=n;const s=C.current-S.current;if(s<=0)return A.current=0,void(k.current=null);let i;if(a)i=Math.max(500,2*z.current);else if(s<20)i=.85*z.current;else if(s<100)i=z.current;else if(s<500){const e=(s-100)/400;i=z.current*(1+.5*e)}else i=2*z.current;const o=i*r/1e3+A.current,l=Math.floor(o);A.current=o-l,l>0&&(S.current=Math.min(S.current+l,C.current),x(S.current)),k.current=requestAnimationFrame(t)};k.current=requestAnimationFrame(t)},[a]);g(()=>(n.length>S.current&&!k.current&&D(),()=>{k.current&&(cancelAnimationFrame(k.current),k.current=null)}),[n.length,D]),g(()=>{a&&S.current<n.length&&(k.current&&(cancelAnimationFrame(k.current),k.current=null),D())},[a,n.length,D]);const F=u(null),E=u(0);g(()=>{(v>=C.current||a)&&(N(j.current.slice(0,v)),E.current=v)},[v,a]);const $=v<n.length&&!a;g(()=>{if($)return F.current||(F.current=window.setInterval(()=>{const e=S.current;e>E.current&&(N(j.current.slice(0,e)),E.current=e)},33)),()=>{F.current&&(clearInterval(F.current),F.current=null)};F.current&&(clearInterval(F.current),F.current=null)},[$]);const O=Ae(),R=l(()=>fn(_.current).format("HH:mm:ss"),[]),L=v<n.length,M=l(()=>{const e=w||n.slice(0,v);return L?e+"│":e},[w,n,v,L]);return n?e("div",{className:ze("w-full max-w-full",o),children:t("div",{className:ze("border-l-4 bg-white dark:bg-gray-900 mb-4 border-l-purple-500 w-full max-w-full overflow-hidden",d),"data-workstream-id":r,children:[t("div",{className:ze("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:ze("animate-fadeIn",y),children:L?e("span",{className:"size-2 rounded-full bg-blue-500 animate-pulse inline-block"}):e(me,{className:"size-4 text-purple-600 dark:text-purple-400"})}),e("span",{className:ze("text-xs font-medium text-muted",b),children:"Agent"}),r&&"main"!==r&&t("span",{className:"text-xs text-muted",children:["• Task ",r]})]}),t("div",{className:"flex items-center gap-2 text-muted",children:[e("span",{className:"text-[11px]",children:R}),e(De,{variant:"ghost",size:"xs",onClick:()=>{navigator.clipboard.writeText(n).then(()=>{O({status:"success",title:"Copied to clipboard",duration:2e3})})},className:"size-6 p-0 hover:bg-gray-100 dark:hover:bg-gray-800",title:"Copy message",children:e(I,{className:"size-3"})})]})]}),t("div",{className:ze("px-3 pb-2 streaming-content",L&&"streaming-active",h),children:[e("div",{className:ze("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(vn,{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}),ql=new Set(["tool","tool_run_id","activity_group_id","event_class","tool_iteration","tool_status","tools","streamed","files","outputFiles"]);function Bl(e){return e?Object.entries(e).filter(([e,t])=>!ql.has(e)&&null!=t&&""!==t):[]}function Hl(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/^./,e=>e.toUpperCase())}function Gl(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 Jl=e=>/\.(png|jpg|jpeg|gif|webp|svg)(\?|$)/i.test(e);function Kl({files:n,className:r}){const{openImage:s}=Pr();return n&&0!==n.length?e("div",{className:ze("mt-2 flex flex-wrap gap-2",r),children:n.map((n,r)=>{const a=n.split("/").pop()?.split("?")[0]||"file";return Jl(n)?e("div",{className:"cursor-pointer",onClick:()=>s(n,a),title:"Click to enlarge",children:e("img",{src:n,alt:a,className:"max-w-[300px] max-h-[200px] rounded border hover:opacity-80 transition-opacity hover:shadow-lg"})},r):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:["📎 ",a]},r)})}):null}const Yl=e=>{if(!e)return;const t=e.files??e.outputFiles;return Array.isArray(t)?t:void 0},Zl=e=>{const t=e.details;if(t?.tool)return t.tool;switch(e.type){case Jt.UPDATE:return"update";case Jt.WARNING:return"warning";case Jt.ERROR:return"error";case Jt.SYSTEM:return"system";default:return"activity"}};function Ql({message:n,isExpanded:r,onToggle:s,artifactRunId:a,classNames:i={}}){const[o,l]=c([]),d=Ae(),{client:m}=Te(),p=lr(),h=u(m);h.current=m;const f=u(p);f.current=p;const b=n.details,y=Zl(n),v=Yl(b),x="string"==typeof n.message?n.message:"";g(()=>{if(!v||0===v.length||!a)return void l([]);let e=!1;return(async()=>{const t=h.current,n=f.current,r=await Promise.all(v.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,s=r.split(".").pop()?.toLowerCase()||"",i=new Set(["png","jpg","jpeg","gif","webp","bmp","svg"]).has(s)?"inline":"attachment";try{const e=cr(a,r,i);if(n)return await n.getOrFetch(e,async()=>(await t.files.getArtifactDownloadUrl(a,r,i)).url);return(await t.files.getArtifactDownloadUrl(a,r,i)).url}catch(e){return console.error(`Failed to resolve artifact URL for ${r}`,e),null}}));e||l(r.filter(e=>!!e))})(),()=>{e=!0}},[v,a]);const w=o.filter(e=>Jl(e)),N=o.filter(e=>!Jl(e));return t("div",{className:ze("border-b border-gray-100 dark:border-gray-800 last:border-b-0",i.itemClassName),children:[t("div",{className:ze("flex items-start justify-between px-3 py-2 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors",i.itemHeaderClassName),onClick: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:e(r?_:j,{className:"size-3 text-muted"})}),e("div",{className:"flex-1 min-w-0",children:x?e("span",{className:"text-xs text-foreground line-clamp-2",children:x}):t("span",{className:"text-xs text-muted italic",children:["Activity: ",y]})})]}),t("div",{className:"flex items-center gap-2 flex-shrink-0",children:[!r&&e("span",{className:ze("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",i.toolBadgeClassName),children:y}),e(De,{variant:"ghost",size:"xs",onClick:e=>{e.stopPropagation(),(()=>{const e=[x,b?"\n\nDetails:\n"+JSON.stringify(b,null,2):""].join("").trim();navigator.clipboard.writeText(e).then(()=>{d({status:"success",title:"Copied to clipboard",duration:2e3})})})()},className:"text-muted opacity-0 group-hover:opacity-100 transition-opacity",title:"Copy message",children:e(I,{className:"size-3"})})]})]}),w.length>0&&e("div",{className:"px-3 pb-1.5",children:e(Kl,{files:w})}),r&&(()=>{const r=b?.tool_status,s=Bl(b);return t("div",{className:ze("px-4 py-2 bg-gray-50/50 dark:bg-gray-800/30",i.itemContentClassName),children:[t("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[e("span",{className:ze("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",i.toolBadgeClassName),children:y}),r&&e("span",{className:ze("text-[10px] px-1.5 py-0.5 rounded-md border font-medium",Gl(r)),children:r}),e("span",{className:"text-[10px] text-muted/70",children:fn(n.timestamp).format("HH:mm:ss")})]}),s.length>0&&e("div",{className:"mb-2 space-y-0.5",children:s.map(([n,r])=>t("div",{className:"flex gap-1.5 text-xs",children:[t("span",{className:"text-muted font-medium flex-shrink-0",children:[Hl(n),":"]}),e("span",{className:"text-foreground break-all",children:"object"==typeof r?JSON.stringify(r):String(r)})]},n))}),x&&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(vn,{artifactRunId:a,children:x})}),N.length>0&&e(Kl,{files:N}),b&&Object.keys(b).length>1&&t("details",{className:"mt-2 text-xs border rounded p-1.5 bg-muted/30",onClick:e=>e.stopPropagation(),children:[e("summary",{className:"cursor-pointer text-muted",children:"Raw details"}),e("pre",{className:"mt-2 p-2 bg-muted rounded text-xs overflow-x-auto font-mono whitespace-pre-wrap",children:JSON.stringify(b,null,2)})]})]})})()]})}function Xl({files:t,artifactRunId:n}){const[r,s]=c([]),{client:a}=Te(),i=lr(),o=u(a);o.current=a;const l=u(i);return l.current=i,g(()=>{if(!t||0===t.length||!n)return void s([]);let e=!1;return(async()=>{const r=o.current,a=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,s=t.split(".").pop()?.toLowerCase()||"";if(new Set(["png","jpg","jpeg","gif","webp","bmp","svg"]).has(s))return null;if(t.startsWith("http://")||t.startsWith("https://"))return t;try{const e=cr(n,t,"attachment");if(a)return await a.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||s(i.filter(e=>!!e))})(),()=>{e=!0}},[t,n]),0===r.length?null:e("div",{className:"pl-4 pr-2 pb-1.5",children:e(Kl,{files:r})})}function ec({messages:t,artifactRunId:n}){const[r,s]=c([]),{client:a}=Te(),i=lr(),o=u(a);o.current=a;const l=u(i);return l.current=i,g(()=>{if(!n||0===t.length)return void s([]);const e=t[t.length-1].details,r=Yl(e);if(!r||0===r.length)return void s([]);let a=!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 s=r.startsWith("artifact:")?r.slice(9):r,a=s.split(".").pop()?.toLowerCase()||"";if(!new Set(["png","jpg","jpeg","gif","webp","bmp","svg"]).has(a))return null;if(s.startsWith("http://")||s.startsWith("https://"))return s;try{const r=cr(n,s,"inline");if(t)return await t.getOrFetch(r,async()=>(await e.files.getArtifactDownloadUrl(n,s,"inline")).url);return(await e.files.getArtifactDownloadUrl(n,s,"inline")).url}catch(e){return console.error(`Failed to resolve artifact URL for ${s}`,e),null}}));a||s(i.filter(e=>!!e))})(),()=>{a=!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(Kl,{files:r})})}const tc=h(function({messages:n,showPulsatingCircle:r=!1,toolRunId:s,toolStatus:a,rootClassName:i,headerClassName:o,senderClassName:l,toolSummaryClassName:d,toolBadgeClassName:m,itemClassName:p,itemHeaderClassName:h,itemContentClassName:f}){const[b,y]=c(!0),[v,x]=c(new Set),[w,N]=c(new Set),k=u(n.length),C=Ae(),S=n.find(e=>e.workflow_run_id)?.workflow_run_id??n[0]?.workflow_run_id;g(()=>{const e=k.current,t=n.length;if(t>e){const n=new Set;for(let r=e;r<t;r++)n.add(r);N(n);const r=setTimeout(()=>{N(new Set)},500);return k.current=t,()=>clearTimeout(r)}k.current=t},[n.length]);const z=n[0],A=n[n.length-1],D=z.timestamp,F=A.timestamp,E=n.map(e=>Zl(e)),$=1===new Set(E).size?`${n.length}× ${E[0]}`:`${n.length} activity updates`,O=e=>{x(t=>{const n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})};return t("div",{className:ze("border-l-4 overflow-hidden bg-white dark:bg-gray-900 mb-4","completed"===a?"border-l-success":"error"===a?"border-l-destructive":"warning"===a?"border-l-attention":"border-l-purple-500",i),children:[t("div",{className:ze("flex items-center justify-between px-4 py-1.5 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors",o),onClick:()=>y(!b),children:[t("div",{className:"flex items-center gap-1",children:[r?e(Nr,{size:"sm",color:"blue"}):"running"===a?e("span",{className:"size-2 rounded-full bg-blue-500 inline-block"}):"completed"===a?e(P,{className:"size-4 text-success"}):"error"===a?e(T,{className:"size-4 text-destructive"}):"warning"===a?e(B,{className:"size-4 text-attention"}):e(me,{className:"size-4 text-purple-600 dark:text-purple-400"}),e("span",{className:ze("text-xs font-medium text-muted",l),children:"Agent"}),e("span",{className:ze("text-xs text-purple-600 dark:text-purple-400 font-medium",d),children:$}),e(b?j:_,{className:"size-3 text-muted"})]}),t("div",{className:"flex items-center gap-1",children:[t("span",{className:"text-[11px] text-muted/70",children:[fn(D).format("HH:mm:ss"),n.length>1&&` - ${fn(F).format("HH:mm:ss")}`]}),e(De,{variant:"ghost",size:"xs",onClick:e=>{e.stopPropagation(),(()=>{const e=n.map(e=>{const t=e.details;return`[${Zl(e)}] ${e.message||""}\n${t?JSON.stringify(t,null,2):""}`}).join("\n\n---\n\n");navigator.clipboard.writeText(e).then(()=>{C({status:"success",title:"Copied all tool calls to clipboard",duration:2e3})})})()},className:"text-muted/50 hover:text-muted h-5 w-5 p-0",title:"Copy all tool calls",children:e(I,{className:"size-3"})})]})]}),e(ec,{messages:n,artifactRunId:S}),b&&e("div",{className:"px-3 py-0.5 space-y-0",children:n.map((r,s)=>{const a=r.details,i=Zl(r),o="string"==typeof r.message?r.message:"",l=w.has(s),c=v.has(s),d=Yl(a);return t("div",{className:ze("border-b border-gray-100 dark:border-gray-800 last:border-b-0",p),style:{opacity:l?0:1,transform:l?"translateX(-10px)":"translateX(0)",transition:"opacity 0.3s ease-out, transform 0.3s ease-out",transitionDelay:100*(s-(n.length-w.size))+"ms",animation:l?"slideInFade 0.4s ease-out forwards":"none",animationDelay:100*(s-(n.length-w.size))+"ms"},children:[t("div",{className:ze("flex items-start gap-2 py-1.5 text-xs cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800/50",h),onClick:()=>O(s),title:o,children:[e("div",{className:"flex-shrink-0 pt-0.5",children:e(c?_:j,{className:"size-3 text-muted"})}),e("div",{className:"flex-1 min-w-0",children:o?e("span",{className:"text-foreground line-clamp-2",children:o}):t("span",{className:"text-muted italic",children:["Activity: ",i]})}),!c&&e("span",{className:ze("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 flex-shrink-0",m),children:i})]}),e(Xl,{files:d,artifactRunId:S}),c&&(()=>{const n=a?.tool_status,s=Bl(a);return t("div",{className:ze("pl-5 pr-3 pb-2 text-sm",f),children:[t("div",{className:"flex items-center gap-2 mb-1.5 flex-wrap",children:[e("span",{className:ze("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",m),children:i}),n&&e("span",{className:ze("text-[10px] px-1.5 py-0.5 rounded-md border font-medium",Gl(n)),children:n}),e("span",{className:"text-[10px] text-muted/70",children:fn(r.timestamp).format("HH:mm:ss")})]}),s.length>0&&e("div",{className:"mb-1.5 space-y-0.5",children:s.map(([n,r])=>t("div",{className:"flex gap-1.5 text-xs",children:[t("span",{className:"text-muted font-medium flex-shrink-0",children:[Hl(n),":"]}),e("span",{className:"text-foreground break-all",children:"object"==typeof r?JSON.stringify(r):String(r)})]},n))}),o&&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(vn,{artifactRunId:S,children:o})}),a&&Object.keys(a).length>1&&t("details",{className:"mt-1.5 text-xs",children:[e("summary",{className:"text-muted cursor-pointer",children:"Raw details"}),e("pre",{className:"mt-1 p-2 bg-muted rounded text-xs overflow-x-auto",children:JSON.stringify(a,null,2)})]})]})})()]},`${r.timestamp}-${s}`)})}),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 "}),!b&&e("div",{className:"group",children:n.map((t,n)=>e(Ql,{message:t,isExpanded:v.has(n),onToggle:()=>O(n),artifactRunId:S,classNames:{toolBadgeClassName:m,itemClassName:p,itemHeaderClassName:h,itemContentClassName:f}},`${t.timestamp}-${n}`))})]})},(e,t)=>e.messages.length===t.messages.length&&(e.showPulsatingCircle===t.showPulsatingCircle&&(e.toolRunId===t.toolRunId&&(e.toolStatus===t.toolStatus&&(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[0]?.timestamp===t.messages[0]?.timestamp&&e.messages[e.messages.length-1]?.timestamp===t.messages[t.messages.length-1]?.timestamp)))))))))))));function nc({workstreams:n,activeWorkstream:r,onSelectWorkstream:s,count:a,completionStatus:i}){const o=new Map;o.set("all","All Messages"),o.set("main","Main"),n.forEach((e,t)=>{"all"!==t&&"main"!==t&&"research_france"!==t&&"statistics"!==t&&o.set(t,e)}),n=o;const l=Array.from(n.entries()).sort(([e],[t])=>"all"===e?-1:"all"===t?1:"main"===e?-1:"main"===t?1:e.localeCompare(t)),c=l.length>2;return e("div",c?{className:"flex overflow-x-auto space-x-1 mb-1 bg-muted border-b border-muted/20 sticky top-0 z-10",children:l.map(([n,o])=>t("button",{className:ze("px-2 py-1 text-xs font-medium whitespace-nowrap transition-colors flex items-center gap-1.5",r===n?"bg-info text-info border-b-2 border-info":"text-muted hover:bg-muted border-b-2 border-transparent"),onClick:()=>s(n),title:o.length>20?o:void 0,children:[o.length>20?o.substring(0,18)+"...":o,a&&a.has(n)&&a.get(n)>0&&t("div",{className:"flex items-center space-x-1",children:[e("span",{className:ze("inline-flex items-center justify-center p-1 text-xs rounded-full",r===n?"bg-info text-info":"bg-muted text-muted"),children:a.get(n)}),i&&"all"!==n&&(i.get(n)?e(P,{className:"size-3 text-success"}):e(pe,{className:"size-3 text-attention"}))]})]},n))}:{className:"py-0.5"})}function rc(e,t){return"all"===t?[...e]:"main"===t?e.filter(e=>"main"===Lr(e)):e.filter(e=>Lr(e)===t)}const sc=(e,t)=>e.includes("%thinking_message%")?e.replace(/%thinking_message%/g,$r[t]):e,ac=e=>e.type===Jt.BATCH_PROGRESS&&!!e.details?.batch_id,ic=(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 s="number"==typeof e.timestamp?e.timestamp:new Date(e.timestamp).getTime();return("number"==typeof t.timestamp?t.timestamp:new Date(t.timestamp).getTime())-s<2e3};class oc extends f{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-l-4 border-l-destructive bg-destructive/10 px-4 py-2 my-2 rounded-r",children:[e("p",{className:"text-sm text-destructive font-medium",children:"Failed to render message"}),e("p",{className:"text-xs text-muted mt-1 truncate",children:this.state.error?.message||"Unknown error"})]}):this.props.children}}const lc=o.memo(function({messages:r,bottomRef:s,viewMode:a="stacked",isCompleted:i=!1,streamingMessages:d=new Map,onSendMessage:m,thinkingMessageIndex:h=0,messageItemClassNames:f,messageStyleOverrides:b,toolCallGroupClassNames:y,hideToolCallsInViewMode:v,streamingMessageClassNames:x,batchProgressPanelClassNames:w,hideWorkstreamTabs:N,workingIndicatorClassName:k,messageListClassName:C,StoreLinkComponent:S,CollectionLinkComponent:_,prependFriendlyMessage:j}){const I=u(null),[P,T]=c("all"),z=u(0),A=u(null),D=d.size>0,F=l(()=>{let e=0;return d.forEach(t=>{e+=t.text?.length||0}),Math.floor(e/200)},[d]),E=p(()=>{s.current&&(s.current.scrollIntoView({behavior:D?"instant":"smooth"}),z.current=Date.now()),A.current=null},[s,D]);g(()=>{const e=Date.now()-z.current;if(e>=100)E();else if(null===A.current){const t=100-e;A.current=window.setTimeout(E,t)}return()=>{null!==A.current&&(clearTimeout(A.current),A.current=null)}},[r.length,d.size,F,E]);const $=o.useMemo(()=>{const e=[...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())),t=[];for(const n of e){const e=t[t.length-1];e&&ic(e,n)||t.push(n)}return t},[r]),O=o.useMemo(()=>{const e=function(e){const t=new Map;return t.set("all","All Messages"),t.set("main","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),console.log(`Found workstream: ${e.workstream_id}`))}),t.size<=2&&!t.has("main")&&t.set("main","Main"),console.log("Final workstreams map:",t),t}($);return e},[$]),R=o.useMemo(()=>{const e=new Map;e.set("all",$.length);const t=rc($,"main");return e.set("main",t.length),$.forEach(t=>{const n=Lr(t);"main"!==n&&e.set(n,(e.get(n)||0)+1)}),e},[$]),L=o.useMemo(()=>"all"===P?$:rc($,P),[$,P]),{importantMessages:M,recentThinking:U}=o.useMemo(()=>{const e=d.size>0;return{importantMessages:L.filter(e=>e.type===Jt.ANSWER||e.type===Jt.QUESTION||e.type===Jt.COMPLETE||e.type===Jt.IDLE||e.type===Jt.REQUEST_INPUT||e.type===Jt.TERMINATED||e.type===Jt.ERROR||e.type===Jt.THOUGHT&&(e.details?.tool||e.details?.tools||e.details?.streamed)),recentThinking:i||e?[]:L.filter(e=>e.type===Jt.UPDATE||e.type===Jt.PLAN||e.type===Jt.THOUGHT&&!e.details?.tool&&!e.details?.tools&&!e.details?.streamed).slice(-1)}},[L,i,d.size]),{completeStreaming:V,incompleteStreaming:W}=o.useMemo(()=>{const e=new Map,t=[],n=L.length>0?Math.max(...L.map(e=>"number"==typeof e.timestamp?e.timestamp:new Date(e.timestamp).getTime())):-1/0;return d.forEach((r,s)=>{if(P&&"all"!==P){const e=r.workstreamId||"main";if(P!==e)return}const a=r.startTimestamp<=n;r.isComplete||a?e.set(s,r):r.text&&t.push({id:s,data:r})}),{completeStreaming:e,incompleteStreaming:t}},[d,P,L]),q=o.useMemo(()=>Jr(Hr(L,V,P)),[L,V,P]),B=o.useMemo(()=>Jr(Hr(M,V,P)),[M,V,P]),H=l(()=>!i&&(d.size>0||U.length>0||!L.some(e=>e.type===Jt.COMPLETE||e.type===Jt.IDLE||e.type===Jt.TERMINATED)),[i,d.size,U.length,L]),G=l(()=>{const e=new Map,t=new Map;$.forEach(e=>{const n=Lr(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[r.length-1];e.set(n,[Jt.COMPLETE,Jt.IDLE,Jt.REQUEST_INPUT,Jt.TERMINATED].includes(t.type))}return e},[$]);return t("div",{ref:I,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",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 need more separation and better styling */\n .vprose table {\n margin-top: 0.875rem;\n margin-bottom: 0.875rem;\n border-collapse: collapse;\n width: 100%;\n }\n .vprose th,\n .vprose td {\n padding: 0.5rem 0.625rem;\n border: 1px solid var(--gray-6, #e5e7eb);\n text-align: left;\n }\n .vprose thead th {\n background-color: var(--gray-3, #f3f4f6);\n font-weight: 600;\n color: var(--gray-11, #6b7280);\n font-size: 0.75rem;\n text-transform: uppercase;\n letter-spacing: 0.05em;\n }\n .vprose tbody tr:hover {\n background-color: var(--gray-2, #f9fafb);\n }\n /* Dark mode table styles */\n .dark .vprose th,\n .dark .vprose td {\n border-color: var(--gray-7, #374151);\n }\n .dark .vprose thead th {\n background-color: var(--gray-4, #1f2937);\n color: var(--gray-11, #9ca3af);\n }\n .dark .vprose tbody tr:hover {\n background-color: var(--gray-3, #111827);\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 "}),e("div",{className:ze("sticky top-0 z-10",N&&"hidden"),children:e(nc,{workstreams:O,activeWorkstream:P,onSelectWorkstream:T,count:R,completionStatus:G})}),0===L.length?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:"all"===P?"Waiting for agent response...":"No messages in this workstream yet..."})}):t("div",{className:ze("flex-1 flex flex-col justify-start pb-4 space-y-2 w-full max-w-full",C),children:[j&&e(Vl,{...f,messageStyleOverrides:b,message:{type:Jt.QUESTION,message:j,timestamp:L[0]?.timestamp??Date.now(),workflow_run_id:"",workstream_id:"main"}},j),t(n,"stacked"===a?{children:[q.map((t,n)=>{const r=n===q.length-1;if("tool_group"===t.type){const s=t.messages[t.messages.length-1],o="completed"===t.toolStatus||"error"===t.toolStatus||"warning"===t.toolStatus,l=!i&&r&&!Rr.includes(s.type)&&!o;return v?.includes(a)?null:e(oc,{children:e(tc,{messages:t.messages,showPulsatingCircle:l,toolRunId:t.toolRunId,toolStatus:t.toolStatus,...y})},`group-${t.toolRunId||t.firstTimestamp}-${n}`)}if("streaming"===t.type)return e(Wl,{text:t.text,workstreamId:t.workstreamId,isComplete:t.isComplete,timestamp:t.startTimestamp,...x},`streaming-${t.streamingId}-${n}`);{const s=t.message,a=!i&&r&&!Rr.includes(s.type);return ac(s)?e(oc,{children:e(zr,{message:s,batchData:s.details,isRunning:!s.details.completed_at,...w})},`batch-${s.details.batch_id}-${s.timestamp}-${n}`):e(oc,{children:e(Vl,{message:s,showPulsatingCircle:a,onSendMessage:m,...f,messageStyleOverrides:b,StoreLinkComponent:S,CollectionLinkComponent:_})},`${s.timestamp}-${n}`)}}),W.map(({id:t,data:n})=>e(Wl,{text:n.text,workstreamId:n.workstreamId,isComplete:!1,timestamp:n.startTimestamp,...x},`streaming-incomplete-${t}`)),H&&0===W.length&&t("div",{className:ze("flex items-center gap-2 pl-3 py-1.5 border-l-2 border-l-purple-500",k),children:[e(Nr,{size:"sm",color:"blue"}),e("span",{className:"text-xs text-muted",children:"Working..."})]})]}:{children:[B.map((t,n)=>{const r=n===B.length-1;if("tool_group"===t.type){const s=t.messages[t.messages.length-1],o="completed"===t.toolStatus||"error"===t.toolStatus||"warning"===t.toolStatus,l=!i&&0===U.length&&r&&!Rr.includes(s.type)&&!o;return v?.includes(a)?null:e(oc,{children:e(tc,{messages:t.messages,showPulsatingCircle:l,toolRunId:t.toolRunId,toolStatus:t.toolStatus,...y})},`group-${t.toolRunId||t.firstTimestamp}-${n}`)}if("streaming"===t.type)return e(Wl,{text:t.text,workstreamId:t.workstreamId,isComplete:t.isComplete,timestamp:t.startTimestamp,...x},`streaming-${t.streamingId}-${n}`);{const s=t.message,a=!i&&0===U.length&&r&&!Rr.includes(s.type);return ac(s)?e(oc,{children:e(zr,{message:s,batchData:s.details,isRunning:!s.details.completed_at,...w})},`batch-${s.details.batch_id}-${s.timestamp}-${n}`):e(oc,{children:e(Vl,{message:s,showPulsatingCircle:a,onSendMessage:m,...f,messageStyleOverrides:b,StoreLinkComponent:S,CollectionLinkComponent:_})},`${s.timestamp}-${n}`)}}),U.map((t,n)=>e(Wl,{text:sc(t.message||"",h),workstreamId:Lr(t),isComplete:n<U.length-1,timestamp:t.timestamp,...x},`thinking-${t.timestamp}-${n}`)),W.map(({id:t,data:n})=>e(Wl,{text:n.text,workstreamId:n.workstreamId,isComplete:!1,timestamp:n.startTimestamp,...x},`streaming-incomplete-${t}`)),H&&0===U.length&&0===W.length&&t("div",{className:ze("flex items-center gap-2 pl-3 py-1.5 border-l-2 border-l-purple-500",k),children:[e(Nr,{size:"sm",color:"blue"}),e("span",{className:"text-xs text-muted",children:"Working..."})]})]}),e("div",{ref:s,className:"h-2"})]})]})});class cc{vertesia;updateState;_interactive=!0;_debug_mode=!1;_checkpoint_tokens;_visibility;_user_channels;_collection;_start=!1;_preserveRunValues=!1;_interaction;_environment;_model="";_tool_names=[];_data;_mode="start";_scheduledWorkflowConfig;_interactionParamsSchema;_inputValidator;constructor(e,t){this.vertesia=e,this.updateState=t}onStateChanged(){const e=this.clone();this.updateState(e)}clone(){const e=new cc(this.vertesia,this.updateState);return e._interactionParamsSchema=this._interactionParamsSchema,e._interaction=this._interaction,e._data=this._data,e._environment=this._environment,e._model=this._model,e._tool_names=[...this._tool_names],e._interactive=this._interactive,e._debug_mode=this._debug_mode,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._preserveRunValues=this._preserveRunValues,e._mode=this._mode,e._scheduledWorkflowConfig=this._scheduledWorkflowConfig,e}set mode(e){e!==this._mode&&(this._mode=e,this.onStateChanged())}get mode(){return this._mode}set scheduledWorkflowConfig(e){this._scheduledWorkflowConfig=e,this.onStateChanged()}get scheduledWorkflowConfig(){return this._scheduledWorkflowConfig}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 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 search_scope(){return this._collection?cn.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,s=e.config?.model,a=await(r?this.vertesia.environments.retrieve(e.config?.environment):Promise.resolve(void 0));this.interactionParamsSchema=e.interactionParamsSchema??null,this.interaction=n,this._tool_names=e.tool_names||[],this._data=e.data,this._interactive=e.interactive,this._debug_mode=e.debug_mode??!1,this._checkpoint_tokens=e.checkpoint_tokens,this._user_channels=e.user_channels,this.collection=e.collection_id??void 0,this.environment=a,s&&(this._model=s),this.onStateChanged()}get interaction(){return this._interaction}set interaction(e){if(e?.id!==this._interaction?.id){if(this._interaction=e,this.interactionParamsSchema=e?dn(e.prompts):void 0,this._inputValidator=void 0,e&&!this._preserveRunValues&&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&&mn(t,e.provider)?this._model=t:this._model=e?.default_model&&mn(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 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())}get start(){return this._start}get preserveRunValues(){return this._preserveRunValues}set preserveRunValues(e){this._preserveRunValues=e}get interactionParamsSchema(){return this._interactionParamsSchema}set interactionParamsSchema(e){this._interactionParamsSchema!==e&&(this._interactionParamsSchema=e,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._checkpoint_tokens=void 0,this._visibility=void 0,this._user_channels=void 0,this._collection=void 0,this._preserveRunValues=!1,this._model="",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 Vn({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 dc=d(void 0);function mc({children:t}){const{client:n}=Te(),[r,s]=c();return g(()=>{s(new cc(n,s))},[]),r&&e(dc.Provider,{value:r,children:t})}function uc(){const e=m(dc);if(!e)throw new Error("usePayloadBuilder must be used within a PayloadProvider");return e}function pc({title:n,onClose:r,isModal:s,run:a,viewMode:i,onViewModeChange:o,showPlanPanel:l,hasPlan:c=!1,onTogglePlanPanel:d,onDownload:m,onCopyRunId:u,resetWorkflow:p,onExportPdf:h,isReceivingChunks:g=!1,className:f}){return e(mc,{children:t("div",{className:ze("flex flex-wrap items-end justify-between py-1.5 px-2 border-b shadow-sm flex-shrink-0",f),children:[t("div",{className:"flex flex-wrap items-center space-x-2",children:[t("div",{className:"flex items-center space-x-1",children:[e(me,{className:"size-5 text-muted"}),e("span",{className:"font-medium",children:n})]}),t("span",{className:"text-xs text-muted ml-1 flex items-center gap-1.5",children:["(Run ID: ",a.runId.substring(0,8),"...)",e("span",{className:ze("w-2 h-2 rounded-full transition-colors duration-200",g?"bg-purple-500 shadow-[0_0_6px_2px_rgba(168,85,247,0.6)]":"bg-gray-400")})]})]}),t("div",{className:"flex justify-end items-center space-x-2 ml-auto",children:[t("div",{className:"flex items-center space-x-1 bg-muted rounded p-0.5 mt-2 lg:mt-0",children:[e(De,{variant:"stacked"===i?"outline":"ghost",size:"xs",className:"rounded-l-md",onClick:()=>o("stacked"),children:"Details"}),e(De,{variant:"sliding"===i?"outline":"ghost",size:"xs",className:"rounded-r-md",onClick:()=>o("sliding"),children:"Summary"})]}),t("div",{className:"relative",children:[c&&!l&&e("span",{className:"absolute -top-1 -right-1 w-2.5 h-2.5 bg-primary rounded-full border border-border z-10"}),t(De,{size:"sm",variant:l?"primary":"secondary",onClick:d,className:"transition-all duration-200 rounded-md",title:"Toggle plan panel",children:[e(he,{className:"size-4 mr-1.5"}),e("span",{className:"font-medium text-xs",children:l?"Hide Plan":"Show Plan"})]})]}),e(hc,{run:a,isModal:s,onClose:r,onDownload:m,onCopyRunId:u,resetWorkflow:p,onExportPdf:h}),r&&!s&&e(De,{size:"xs",variant:"ghost",onClick:r,children:e(ge,{className:"size-4"})})]})]})})}function hc({run:n,isModal:r,onClose:s,onDownload:a,onCopyRunId:i,resetWorkflow:o,onExportPdf:l}){const c=Ae(),{client:d}=Te(),m=uc();return t(at,{hover:!0,children:[e(it,{children:e(De,{size:"xs",variant:"ghost",title:"More actions",children:e(fe,{className:"size-4"})})}),e(ot,{className:"w-48",align:"end",children:e("div",{className:"rounded-md shadow-lg z-50",children:e("div",{className:"py-1 min-w-36",children:e(At,{children:e(Ht,{children:t(Et,{children:[e("div",{className:"flex items-center px-3 py-1.5 text-xs text-gray-700 dark:text-gray-300",children:e("span",{className:"text-muted",children:"Actions"})}),r&&t($t,{className:"text-xs",onSelect:()=>{return e=`/store/agent-runner?agentId=${n.runId}__${n.workflowId}`,window.open(e,"_blank"),e;var e},children:[e(S,{className:"size-3.5 mr-2 text-muted"})," Open in new tab"]}),t($t,{className:"text-xs",onSelect:()=>{i?i():(navigator.clipboard.writeText(n.runId),c({status:"success",title:"Run ID copied",duration:2e3}))},children:[e(I,{className:"size-3.5 mr-2 text-muted"})," Copy Run ID"]}),t($t,{className:"text-xs",onSelect:()=>{a?a():async function(e,t){return e.files.getDownloadUrl(`agents/${t}/conversation.json`).then(e=>e.url)}(d,n.runId).then(e=>window.open(e,"_blank"))},children:[e(be,{className:"size-3.5 mr-2 text-muted"})," Download Conversation"]}),l&&t($t,{className:"text-xs",onSelect:l,children:[e(be,{className:"size-3.5 mr-2 text-muted"})," Export as PDF"]}),s&&r&&t($t,{className:"text-xs",onSelect:s,children:[e(ge,{className:"size-3.5 mr-2 text-muted"})," Close"]}),t($t,{className:"text-xs text-destructive",onSelect:()=>{(async e=>{try{return await d.store.workflows.terminate(e.workflowId,e.runId,"cancel"),c({status:"success",title:"Workflow cancelled",duration:2e3}),m.reset(),o?.(),!0}catch(e){return c({status:"error",title:"Failed to cancel workflow",duration:2e3}),!1}})(n)},children:[e(ge,{className:"size-3.5 mr-2 text-destructive"})," Cancel Workflow"]})]})})})})})})]})}function gc({onSend:n,onStop:r,disabled:s=!1,isSending:a=!1,isStopping:i=!1,isStreaming:o=!1,isCompleted:l=!1,activeTaskCount:d=0,placeholder:m="Type your message...",onFilesSelected:h,uploadedFiles:f=[],onRemoveFile:b,acceptedFileTypes:y=".pdf,.doc,.docx,.txt,.csv,.xlsx,.xls,.png,.jpg,.jpeg,.gif,.webp",maxFiles:v=5,processingFiles:x,hasProcessingFiles:w=!1,renderDocumentSearch:N,selectedDocuments:k=[],onRemoveDocument:C,hideObjectLinking:S=!1,hideFileUpload:_=!1,className:j}){const I=u(null),P=u(null),[T,z]=c(""),[A,D]=c(!1),[F,E]=c(!1),[$,O]=c(!1);g(()=>{!s&&l&&I.current?.focus()},[s,l]);const R=p(e=>{if(!h)return;const t=Array.from(e),n=v-f.length,r=t.slice(0,n);r.length>0&&h(r)},[h,v,f.length]),L=p(e=>{e.preventDefault(),e.stopPropagation(),h&&O(!0)},[h]),M=p(e=>{e.preventDefault(),e.stopPropagation(),O(!1)},[]),U=p(e=>{e.preventDefault(),e.stopPropagation(),O(!1),e.dataTransfer?.files&&e.dataTransfer.files.length>0&&R(e.dataTransfer.files)},[R]),V=p(e=>{if(!h)return;const t=e.clipboardData?.items;if(!t)return;const n=[];for(let e=0;e<t.length;e++){const r=t[e];if("file"===r.kind){const e=r.getAsFile();if(e)if(!r.type.startsWith("image/")||e.name&&"image.png"!==e.name)n.push(e);else{const t=r.type.split("/")[1]||"png",s=new File([e],`pasted-image-${Date.now()}.${t}`,{type:e.type});n.push(s)}}}n.length>0&&R(n)},[h,R]),W=p(e=>{e.target.files&&e.target.files.length>0&&(R(e.target.files),e.target.value="")},[R]),q=p(()=>{P.current?.click()},[]),B=p(()=>E(!1),[]),H=p(e=>E(!1),[]),G=()=>{const e=T.trim();!e||s||a||(n(e),z(""))},J=()=>{r&&!i&&r()},K=u(0),Y=p(()=>{const e=I.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]);g(()=>{Y()},[T,Y]);const Q=f.length>0||k.length>0||x&&x.size>0;return t("div",{className:ze("p-3 border-t border-muted flex-shrink-0 transition-all fixed lg:sticky bottom-0 left-0 right-0 lg:left-auto lg:right-auto w-full bg-background z-10",$&&"bg-blue-50 dark:bg-blue-900/20 border-blue-400",j),style:{minHeight:"120px"},onDragOver:L,onDragLeave:M,onDrop:U,children:[$&&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(Z,{className:"size-5"}),"Drop files to upload"]})}),h&&e("input",{ref:P,type:"file",multiple:!0,accept:y,onChange:W,className:"hidden"}),Q&&!_&&t("div",{className:"flex flex-col gap-2 mb-3",children:[(f.length>0||x&&x.size>0)&&t("div",{children:[t("div",{className:"flex items-center gap-1 mb-1",children:[e("span",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:"Uploaded Files"}),e(Ee,{description:"Files uploaded to this conversation remain available throughout. The agent can access them anytime.",placement:"top",size:"md",children:e(ye,{className:"size-3 text-gray-400 dark:text-gray-500"})})]}),t("div",{className:"flex flex-wrap gap-2",children:[x&&Array.from(x.values()).map(n=>t("div",{className:ze("flex items-center gap-1.5 px-2 py-1 rounded-md text-sm",n.status===un.ERROR?"bg-destructive/10 text-destructive":n.status===un.READY?"bg-success/10 text-success":"bg-attention/10 text-attention"),children:[e(ve,{className:ze("size-3.5",(n.status===un.UPLOADING||n.status===un.PROCESSING)&&"animate-pulse")}),e("span",{className:"max-w-[120px] truncate",children:n.name}),e("span",{className:"text-xs opacity-70",children:n.status===un.UPLOADING?"Uploading...":n.status===un.PROCESSING?"Processing...":n.status===un.ERROR?"Error":n.status===un.READY?"Ready":n.status})]},n.id)),f.map(n=>t("div",{className:"flex items-center gap-1.5 px-2 py-1 bg-success/10 text-success rounded-md text-sm",children:[e(ve,{className:"size-3.5"}),e("span",{className:"max-w-[120px] truncate",children:n.name}),b&&e("button",{onClick:()=>b(n.id),className:"ml-1 p-0.5 hover:bg-success/20 rounded",children:e(ge,{className:"size-3"})})]},n.id))]})]}),k.length>0&&t("div",{children:[t("div",{className:"flex items-center gap-1 mb-1",children:[e("span",{className:"text-xs font-medium text-blue-600 dark:text-blue-400",children:"Document Attachments"}),e(Ee,{description:"Documents from the store attached to this message. The agent can re-fetch them by ID anytime, or re-attach to include content directly.",placement:"top",size:"md",children:e(ye,{className:"size-3 text-blue-400 dark:text-blue-500"})})]}),e("div",{className:"flex flex-wrap gap-2",children:k.map(n=>t("div",{className:"flex items-center gap-1.5 px-2 py-1 bg-blue-100 dark:bg-blue-900/30 rounded-md text-sm text-blue-700 dark:text-blue-300",children:[e(ve,{className:"size-3.5"}),e("span",{className:"max-w-[120px] truncate",children:n.name}),C&&e("button",{onClick:()=>C(n.id),className:"ml-1 p-0.5 hover:bg-blue-200 dark:hover:bg-blue-800 rounded",children:e(ge,{className:"size-3"})})]},n.id))})]})]}),(h||N)&&t("div",{className:"flex gap-2 mb-2",children:[h&&t(De,{variant:"outline",size:"sm",onClick:q,disabled:s||f.length>=v,className:"text-xs",children:[e(Z,{className:"size-3.5 mr-1.5"}),"Upload"]}),N&&t(De,{variant:"outline",size:"sm",onClick:()=>E(!0),disabled:s,className:"text-xs",children:[e(ve,{className:"size-3.5 mr-1.5"}),"Search Documents"]})]}),t("div",{className:"flex items-end space-x-2",children:[t("div",{className:"flex flex-1 items-end space-x-1",children:[e(Ct,{ref:I,value:T,onKeyDown:e=>{if("Enter"===e.key&&!e.shiftKey){e.preventDefault();T.trim().length>0&&G()}if("Escape"===e.key&&o&&r){const e=Date.now();e-K.current<500?(J(),K.current=0):K.current=e}},onChange:e=>z(e.target.value),onPaste:V,disabled:s,placeholder:o?"Agent is working... (Esc Esc to stop)":h?"Ask anything... (drop or paste files)":m,rows:2,style:{minHeight:"60px",maxHeight:"200px"}}),!S&&e(De,{variant:"ghost",className:"rounded-full",disabled:!l,onClick:()=>D(!0),alt:"Link Object",children:e(xe,{className:"size-4"})})]}),o&&r&&!T.trim()?t(De,{onClick:J,disabled:i,className:"px-4 py-2.5 bg-red-600 hover:bg-red-700 text-white",title:"Stop the agent",children:[i?e(Ue,{size:"sm",className:"mr-2"}):e(we,{className:"size-4 mr-2"})," ",e("span",{children:"Stop"})]}):t(De,{onClick:G,disabled:s||a||!T.trim()||w,className:"px-4 py-2.5",title:w?"Wait for files to finish processing":void 0,children:[a?e(Ue,{size:"sm",className:"mr-2"}):e(Ne,{className:"size-4 mr-2"}),e("span",{children:w?"Processing...":"Send"})]})]}),e("div",{className:"text-xs text-muted mt-2 text-center",children:d>0?t("div",{className:"flex items-center justify-center",children:[e(ke,{className:"h-3 w-3 mr-1 text-attention"}),t("span",{children:["Agent has ",d," active workstream",1!==d?"s":""," running"]})]}):o?"Agent is working... Press Esc twice or click Stop to interrupt":s?"Agent is processing, you can continue once it completes...":"Enter to send • Shift+Enter for new line"}),t(Ve,{isOpen:A,onClose:()=>D(!1),className:"min-w-[60vw]",children:[e(We,{children:"Link Object"}),e(qe,{className:"pb-6",children:e(ho,{onChange:e=>{const t=`[${e.properties?.title||e.name||"Object"}](store:${e.id})`,n=T||"",r=I.current?.selectionStart||n.length,s=n.substring(0,r)+t+n.substring(r);z(s),D(!1),setTimeout(()=>{if(I.current){I.current.focus();const e=r+t.length;I.current.setSelectionRange(e,e)}},100)}})})]}),N?.({isOpen:F,onClose:B,onSelect:H})]})}const fc=o.memo(function({plan:r,workstreamStatus:s,isOpen:a,onClose:i,plans:o=[],activePlanIndex:l=0,onChangePlan:c=()=>{}}){return a?t("div",{className:"h-full shadow-xl border border-muted/20 overflow-hidden",children:[t("div",{className:"flex items-center justify-between p-3 border-b border-muted/20",children:[e("h3",{className:"font-bold text-base",children:"Plan"}),t(De,{variant:"ghost",onClick:i,children:[e(C,{className:"size-4"}),e("span",{className:"sr-only",children:"Close"})]})]}),t("div",{className:"p-3 overflow-y-auto",style:{height:"calc(100% - 44px)",maxHeight:"calc(100vh - 150px)"},children:[t("div",{className:"mb-3 p-2 bg-info rounded-md border border-info",children:[e("div",{className:"text-xs font-medium text-info mb-1",children:"Task Progress"}),e("div",{className:"flex items-center gap-2",children:(()=>{const a=r.plan||[],i=a.length;let o=0;i>0&&a.forEach(e=>{if(e&&e.id){const t=e.id.toString();"completed"===s.get(t)&&o++}});const l=i>0?Math.round(o/i*100):0;return t(n,{children:[e("div",{className:"w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2.5",children:e("div",{className:"bg-info h-2.5 rounded-full transition-all duration-300",style:{width:`${l}%`}})}),e("span",{className:"text-xs text-foreground font-medium whitespace-nowrap",children:i>0?`${o}/${i}`:"0/0"})]})})()})]}),o.length>1&&t("div",{className:"mb-3 flex items-center justify-between",children:[e(De,{variant:"ghost",onClick:()=>c(Math.min(o.length-1,l+1)),disabled:l>=o.length-1,children:"Older Plan"}),e("div",{className:"text-xs text-muted",children:o[l]?.timestamp?new Date(o[l].timestamp).toLocaleTimeString():"Unknown time"}),e(De,{variant:"ghost",onClick:()=>c(Math.max(0,l-1)),disabled:l<=0,children:"Newer Plan"})]}),t("div",{className:"rounded-md border border-muted/30",children:[e("div",{className:"p-2 border-b border-muted/30 bg-muted",children:e("div",{className:"font-medium text-xs",children:"Step-by-Step Plan"})}),e("div",{className:"divide-y divide-muted/20 max-h-[calc(100vh-350px)] overflow-y-auto",children:r.plan&&r.plan.length>0?r.plan.map((n,r)=>{const a=n.id?n.id.toString():`task-${r}`,i=n.goal||`Task ${r+1}`;let o=n.status||"pending";s.has(a)&&(o=s.get(a));let l=Ce,c="text-muted";return"in_progress"===o?(l=pe,c="text-info"):"completed"===o&&(l=P,c="text-success"),t("div",{className:"flex p-3 my-1",children:[e("div",{className:"mr-2 mt-0.5 flex-shrink-0 text-muted",children:a}),t("div",{className:"w-full",children:[e("div",{className:"text-sm font-medium mb-2 text-muted",children:i}),t("div",{className:"mt-1 flex justify-end items-center",children:[e("div",{className:`mr-2 mt-0.5 flex-shrink-0 ${c}`,children:e(l,{className:"size-3.5"})}),e(lt,{variant:"completed"===o?"success":"in_progress"===o?"info":"default",children:"completed"===o?"Completed":"in_progress"===o?"In Progress":"Pending"})]})]})]},r)}):t("div",{className:"p-3 text-center text-muted italic",children:[e(T,{className:"size-4 mx-auto mb-2 text-attention"}),e("p",{className:"text-xs",children:"No plan has been detected yet"}),e("p",{className:"text-xs mt-1",children:"Plans will appear here when the agent creates one"})]})})]}),(()=>{const n=new Set((r.plan||[]).filter(e=>e&&e.id).map(e=>e.id.toString())),a=Array.from(s.entries()).filter(([e])=>"main"!==e&&!n.has(e));return a.length>0?t("div",{className:"mt-3 rounded-md border border-gray-200 dark:border-gray-800",children:[e("div",{className:"p-2 border-b border-gray-200 dark:border-gray-800 bg-gray-50 dark:bg-gray-900/50",children:e("div",{className:"font-medium text-xs",children:"Workstreams"})}),e("div",{className:"p-3",children:e("div",{className:"grid grid-cols-1 gap-2",children:a.map(([n,r])=>{let s=Ce,a="text-gray-400",i="bg-gray-100 dark:bg-gray-800",o="Pending";return"in_progress"===r?(s=pe,a="text-info",i="bg-info/20",o="In Progress"):"completed"===r&&(s=P,a="text-success",i="bg-success/20",o="Completed"),t("div",{className:ze("flex items-center p-1.5 rounded",i),children:[e("div",{className:`mr-1.5 ${a}`,children:e(s,{className:"h-3.5 w-3.5"})}),e("div",{className:"flex-1",children:e("span",{className:"text-xs font-medium text-gray-800 dark:text-gray-300",children:n})}),e("span",{className:"text-xs font-medium",children:o})]},n)})})})]}):null})()]})]}):null}),bc=h(function({code:t}){const n=l(()=>{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(br,{spec:n}):null}),yc=h(function({code:t}){const n=l(()=>{try{return{library:"vega-lite",spec:JSON.parse(t)}}catch{return null}},[t]);return n?e(br,{spec:n}):null}),vc={chart:bc,"vega-lite":yc,vegalite:yc,"fusion-fragment":hn};function xc({url:t,code:n}){const[r,s]=c(null);return g(()=>{import(t).then(e=>{s(()=>e.default)}).catch(e=>{console.error("Failed to load remote widget component from ",t,e)})},[t]),r?e(r,{code:n}):null}function wc({children:t}){const{client:n}=Te(),[r,s]=c(vc);return g(()=>{(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=pn(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 s=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,s]of Object.entries(r))n.push({name:t,component:t=>e(xc,{url:s.url,code:t.code})});return n}).catch(()=>(console.error("Failed to fetch skill widgets from ",t),null)))),a={};for(const e of s.flat())e&&(a[e.name]=e.component);return a})(n).then(e=>{s({...vc,...e})})},[]),e(An,{components:r,children:t})}function Nc({documents:n,activeId:r,onSelect:s,onClose:a}){return 0===n.length?null:e("div",{className:"flex items-center gap-1 overflow-x-auto px-2 py-1.5 border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50",children:n.map(n=>{const i=n.id===r;return t("button",{onClick:()=>s(n.id),className:ze("group flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-md transition-colors whitespace-nowrap max-w-[200px]",i?"bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 shadow-sm":"text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700/50"),children:[e("span",{className:"truncate",children:n.title}),e("span",{role:"button",onClick:e=>{e.stopPropagation(),a(n.id)},className:ze("shrink-0 p-0.5 rounded hover:bg-gray-200 dark:hover:bg-gray-600",i?"opacity-60 hover:opacity-100":"opacity-0 group-hover:opacity-60 hover:!opacity-100"),children:e(ge,{className:"size-3"})})]},n.id)})})}const kc=o.memo(function({isOpen:n,onClose:r,documents:s,activeDocumentId:a,onSelectDocument:i,onCloseDocument:o,refreshKey:l,runId:d}){const{client:m}=Te(),[u,h]=c(null),[f,b]=c(!1),[y,v]=c(null),[x,w]=c(null),N=p(async e=>{b(!0),v(null);try{const[t,n]=await Promise.all([m.store.objects.getObjectText(e),m.store.objects.retrieve(e)]);h(t.text),w(n.name)}catch(e){const t=e instanceof Error?e.message:"Failed to load document";v(t),h(null)}finally{b(!1)}},[m]);return g(()=>{a&&n&&N(a)},[a,l,n,N]),n&&0!==s.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(ve,{className:"size-4 text-muted shrink-0"}),e("h3",{className:"font-bold text-sm truncate",children:x||"Document"})]}),t(De,{variant:"ghost",size:"sm",onClick:r,children:[e(C,{className:"size-4"}),e("span",{className:"sr-only",children:"Close"})]})]}),e("div",{className:"shrink-0",children:e(Nc,{documents:s,activeId:a,onSelect:i,onClose:o})}),e("div",{className:"flex-1 overflow-y-auto px-4 py-4",children:f?t("div",{className:"flex items-center justify-center py-12",children:[e(Se,{className:"size-5 animate-spin text-muted"}),e("span",{className:"ml-2 text-sm text-muted",children:"Loading document..."})]}):y?e("div",{className:"p-4 rounded-md bg-destructive/10 text-destructive text-sm",children:y}):u?e("div",{className:"prose prose-sm dark:prose-invert max-w-none",children:e(vn,{artifactRunId:d,children:u})}):t("div",{className:"flex flex-col items-center justify-center py-12 text-muted",children:[e(ve,{className:"size-8 mb-2"}),e("span",{className:"text-sm",children:"No content available"})]})})]}):null});function Cc(e,t){const[n,r]=c([]),[s,a]=c(!1),[i,o]=c(null),[l,d]=c(new Map),[m,h]=c(new Map),f=u(new Map),b=u(null),[y,v]=c(!1),x=u(null),w=p(()=>{f.current.size>0&&(h(new Map(f.current)),v(!0),x.current&&clearTimeout(x.current),x.current=setTimeout(()=>v(!1),50)),b.current=null},[]);g(()=>{a(!function(e){if(!e.length)return!0;const t=new Map;if(e.forEach(e=>{const n=Lr(e);t.has(n)||t.set(n,[]),t.get(n).push(e)}),console.log("[isInProgress] Workstreams found:",Array.from(t.keys())),1===t.size&&!t.has("main")){const e=t.keys().next().value||"unknown";console.log(`[isInProgress] Only one workstream found (${e}), treating as main`);const n=t.get(e),r=n[n.length-1];return console.log(`[isInProgress] Last message type in only workstream: ${r.type}`),Rr.includes(r.type)?(console.log("[isInProgress] Only workstream is completed"),!1):(console.log("[isInProgress] Only workstream is still in progress"),!0)}if(t.has("main")){const e=t.get("main");if(0===e.length)return console.log("[isInProgress] Main workstream exists but has no messages, still in progress"),!0;const n=e[e.length-1];return console.log(`[isInProgress] Last message type in main workstream: ${n.type}`),Rr.includes(n.type)?(console.log("[isInProgress] Main workstream is completed"),!1):(console.log("[isInProgress] Main workstream is still in progress"),!0)}console.log("[isInProgress] Multiple workstreams but no main, checking if any are still active");for(const[e,n]of t.entries())if(n.length>0){const t=n[n.length-1];if(!Rr.includes(t.type))return console.log(`[isInProgress] Workstream ${e} is still active`),!0}return console.log("[isInProgress] All workstreams are completed"),!1}(n))},[n]),g(()=>(r([]),o(null),h(new Map),d(new Map),e.store.workflows.getRunDetails(t.runId,t.workflowId).then(e=>{o(e.status)}).catch(e=>{console.error("Failed to check workflow status:",e)}),e.store.workflows.streamMessages(t.workflowId,t.runId,e=>{if(e.type===Jt.STREAMING_CHUNK){const t=e.details,n=t?.activity_id||t?.streaming_id;if(!n)return;const r=f.current.get(n)||{text:"",workstreamId:e.workstream_id,startTimestamp:Date.now(),activityId:t?.activity_id},s=r.text+(e.message||"");return f.current.set(n,{text:s,workstreamId:e.workstream_id,isComplete:t.is_final,startTimestamp:r.startTimestamp,activityId:t?.activity_id}),void(null===b.current&&(b.current=requestAnimationFrame(w)))}if(e.type===Jt.SYSTEM){const t=e.details;if("file_processing"===t?.system_type&&t.files)return void d(e=>{const n=new Map(e);for(const e of t.files)n.set(e.id,e);return n})}if((e.type===Jt.THOUGHT||e.type===Jt.ANSWER)&&e.details?.activity_id){const t=e.details.activity_id;f.current.delete(t),h(e=>{if(e.has(t)){const n=new Map(e);return n.delete(t),n}return e})}e.type!==Jt.COMPLETE&&e.type!==Jt.IDLE||f.current.size>0&&w(),e.message&&r(t=>{if(t.find(t=>t.timestamp===e.timestamp))return t;if(e.type===Jt.QUESTION&&!e.details?._optimistic){const n=t.filter(e=>!(e.type===Jt.QUESTION&&e.details?._optimistic));return Or(n,e),[...n]}return Or(t,e),[...t]})}),()=>{r([]),null!==b.current&&(cancelAnimationFrame(b.current),b.current=null),f.current.clear()}),[t.runId,e.store.workflows,w]);const N=p(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})},[]),k=p(e=>{r(t=>t.filter(t=>!e(t)))},[]);return{messages:n,streamingMessages:m,isCompleted:s,debugChunkFlash:y,addOptimisticMessage:N,removeOptimisticMessages:k,workflowStatus:i,serverFileUpdates:l}}function Sc(t){const{run:n,startWorkflow:r}=t;if(n){const r="runId"in n?n:{runId:n.run_id,workflowId:n.workflow_id};return e(wc,{children:e(Ic,{...t,run:r})})}return r?e(jc,{...t}):e(_c,{})}function _c(){return t(ft,{status:"info",icon:e(me,{className:"size-16 text-muted mb-4"}),children:[e("div",{className:"text-base font-medium text-muted",children:"No agent currently running"}),e("div",{className:"mt-3 text-sm text-muted",children:"Select an interaction and click Start to start an agent"})]})}function jc({initialMessage:n,startWorkflow:r,onClose:s,isModal:a=!1,fullWidth:i=!1,placeholder:o="Type your message...",startButtonText:l="Start Agent",title:d="Start New Conversation",getAttachedDocs:m,onAttachmentsSent:h,acceptedFileTypes:f=".pdf,.doc,.docx,.txt,.csv,.xlsx,.xls,.png,.jpg,.jpeg,.gif,.webp",maxFiles:b=5}){const{client:y}=Te(),[v,x]=c(""),[w,N]=c(!1),[k,C]=c(),S=Ae(),_=u(null),j=u(null),[I,P]=c([]),[T,z]=c(!1),A=u(0),D=p(e=>{e.preventDefault(),e.stopPropagation(),A.current++,e.dataTransfer?.types?.includes("Files")&&z(!0)},[]),F=p(e=>{e.preventDefault(),e.stopPropagation()},[]),E=p(e=>{e.preventDefault(),e.stopPropagation(),A.current--,0===A.current&&z(!1)},[]),$=p(e=>{if(e.preventDefault(),e.stopPropagation(),A.current=0,z(!1),e.dataTransfer?.files&&e.dataTransfer.files.length>0){const t=Array.from(e.dataTransfer.files);P(e=>[...e,...t].slice(0,b))}},[b]),O=p(e=>{if(e.target.files&&e.target.files.length>0){const t=Array.from(e.target.files);P(e=>[...e,...t].slice(0,b))}e.target.value=""},[b]),R=p(e=>{P(t=>t.filter((t,n)=>n!==e))},[]);g(()=>{_.current&&_.current.focus()},[]);const L=async()=>{if(!r)return;const e=v.trim();if(e&&!w){N(!0);try{sessionStorage.removeItem("plan-panel-shown"),S({title:I.length>0?"Starting agent and uploading files...":"Starting agent...",status:"info",duration:3e3});const t=m?.()||[];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.length>0){const e=I.map(e=>e.name).join(", ");n=[n,"",`[System: ${I.length} file(s) are being uploaded: ${e}. Please wait for the "Files Ready" notification before processing them.]`].join("\n")}const s=await r(n);if(s){const e=[];if(I.length>0){for(const t of I)try{const n=`files/${t.name}`;await y.files.uploadArtifact(s.run_id,n,t),await y.store.workflows.sendSignal(s.workflow_id,s.run_id,"FileUploaded",{id:`file-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,name:t.name,content_type:t.type||"application/octet-stream",reference:`artifact:${n}`,artifact_path:n}),e.push(t.name)}catch(e){console.error(`Failed to upload staged file ${t.name}:`,e)}if(e.length>0)try{await y.store.workflows.sendSignal(s.workflow_id,s.run_id,"UserInput",{message:`[Files Ready] All ${e.length} file(s) have been uploaded and are now available: ${e.join(", ")}. You can now process them.`,metadata:{type:"files_ready",files:e}})}catch(e){console.error("Failed to send files ready signal:",e)}P([])}h?.(),C({runId:s.run_id,workflowId:s.workflow_id}),x(""),S({title:"Agent started",status:"success",duration:3e3})}}catch(e){S({title:"Error starting workflow",status:"error",duration:3e3,description:e instanceof Error?e.message:"Unknown error"})}finally{N(!1)}}},M=p(()=>{const e=_.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]);return g(()=>{M()},[v,M]),k?e(Ic,{onClose:s,isModal:a,initialMessage:n,placeholder:o,run:k,title:d}):t("div",{className:"flex flex-col h-full bg-white dark:bg-gray-900 overflow-hidden border-0 relative "+(T?"ring-2 ring-blue-400 ring-inset":""),onDragEnter:D,onDragOver:F,onDragLeave:E,onDrop:$,children:[T&&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(Z,{className:"size-6"}),"Drop files to stage for upload"]})}),e("input",{ref:j,type:"file",multiple:!0,accept:f,onChange:O,className:"hidden"}),t("div",{className:"flex items-center justify-between py-2 px-3 border-b border-gray-100 dark:border-gray-800 bg-white dark:bg-gray-900",children:[t("div",{className:"flex items-center space-x-2",children:[e("div",{className:"p-1",children:e(_e,{className:"size-3.5 text-muted"})}),e("span",{className:"font-medium text-sm text-gray-700 dark:text-gray-300",children:d})]}),s&&!a&&e(De,{size:"xs",variant:"ghost",onClick:s,title:"Close",className:"text-slate-500 hover:text-slate-700",children:e(ge,{className:"size-4"})})]}),t("div",{className:"flex-1 overflow-y-auto px-4 py-6 bg-white dark:bg-gray-900 flex flex-col "+(i?"items-start justify-start":"items-center justify-center"),children:[n&&e("div",{className:"px-4 py-3 mb-4 bg-blue-50/80 dark:bg-blue-900/30 border-l-2 border-blue-400 dark:border-blue-500 text-blue-700 dark:text-blue-300 "+(i?"w-full":"max-w-md"),children:n}),t("div",{className:"bg-white dark:bg-slate-800 p-4 border-l-2 border-blue-400 dark:border-blue-500 "+(i?"w-full":"max-w-md"),children:[e("div",{className:"text-base text-slate-600 dark:text-slate-300 font-medium",children:"Enter a message to start a conversation"}),t("div",{className:"mt-3 text-sm text-slate-500 dark:text-slate-400",children:["Type your question below and press Enter or click ",l," ","to begin"]})]})]}),t("div",{className:"py-3 px-3 border-t border-gray-100 dark:border-gray-800 bg-white dark:bg-gray-900",children:[I.length>0&&e("div",{className:"flex flex-wrap gap-2 mb-3",children:I.map((n,r)=>t("div",{className:"flex items-center gap-1.5 px-2 py-1 bg-attention/10 text-attention rounded-md text-sm",children:[e(ve,{className:"size-3.5"}),e("span",{className:"max-w-[120px] truncate",children:n.name}),e("span",{className:"text-xs opacity-70",children:"Staged"}),e("button",{onClick:()=>R(r),className:"ml-1 p-0.5 hover:bg-attention/20 rounded",children:e(ge,{className:"size-3"})})]},`${n.name}-${r}`))}),e("div",{className:"flex gap-2 mb-2",children:t(De,{variant:"outline",size:"sm",onClick:()=>j.current?.click(),disabled:w||I.length>=b,className:"text-xs",children:[e(Z,{className:"size-3.5 mr-1.5"}),"Upload"]})}),t("div",{className:"flex items-end gap-2",children:[e("div",{className:"flex-1",children:e("textarea",{ref:_,value:v,onChange:e=>x(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),L())},placeholder:o,disabled:w,rows:2,className:"w-full py-2.5 px-3 text-sm border border-gray-200 dark:border-gray-700 dark:bg-gray-800 dark:text-white focus:border-gray-300 dark:focus:border-gray-600 focus:outline-none focus:ring-1 focus:ring-gray-300 dark:focus:ring-gray-600 rounded-md resize-none overflow-hidden",style:{minHeight:"60px",maxHeight:"200px"}})}),t(De,{onClick:L,disabled:!v.trim()||w,className:"px-3 py-2.5 bg-gray-800 dark:bg-gray-700 hover:bg-gray-700 dark:hover:bg-gray-600 text-white text-xs rounded-md transition-colors",children:[w?e(Ue,{size:"sm",className:"mr-1.5"}):e(Ne,{className:"size-3.5 mr-1.5"}),l]})]}),e("div",{className:"text-xs text-gray-400 dark:text-gray-500 mt-2 text-center",children:I.length>0?`${I.length} file${I.length>1?"s":""} staged - will upload when conversation starts`:"Enter to send • Shift+Enter for new line"})]})]})}function Ic({run:n,title:r,interactive:s=!0,onClose:a,isModal:i=!1,fullWidth:o=!1,placeholder:d="Type your message...",resetWorkflow:m,uploadedFiles:h,onRemoveFile:f,acceptedFileTypes:b,maxFiles:y,renderDocumentSearch:v,selectedDocuments:x,onRemoveDocument:w,hideObjectLinking:N,hideHeader:k,hideMessageInput:C,hidePlanPanel:S,hideWorkstreamTabs:_,hideFileUpload:j,hideDocumentPanel:I,getAttachedDocs:P,onAttachmentsSent:T,isUploading:z=!1,getMessageContext:A,className:D,inputContainerClassName:F,inputClassName:E,fusionData:$,fileUploadRef:O,onProcessingFilesChange:R,onPlansChange:L,onWorkstreamStatusChange:M,viewMode:U,onViewModeChange:V,onShowInputChange:W,stopRef:q,onStoppingChange:B,messageItemClassNames:H,messageStyleOverrides:G,toolCallGroupClassNames:J,hideToolCallsInViewMode:K,streamingMessageClassNames:Y,batchProgressPanelClassNames:Q,workingIndicatorClassName:X,messageListClassName:ee,StoreLinkComponent:te,CollectionLinkComponent:ne,prependFriendlyMessage:re}){const{client:se}=Te(),ae=Ae(),{messages:ie,streamingMessages:oe,isCompleted:le,debugChunkFlash:ce,addOptimisticMessage:de,removeOptimisticMessages:me,workflowStatus:ue,serverFileUpdates:pe}=Cc(se,n),{plans:he,activePlanIndex:ge,setActivePlanIndex:fe,workstreamStatusMap:be,showInput:ye,showSlidingPanel:ve,setShowSlidingPanel:xe}=function(e,t,n=!1){const[r,s]=c([]),[a,i]=c(0),[o,l]=c(new Map),[d,m]=c(t),[h,f]=c(!n),b=u(-1),y=u(new Set);g(()=>{0===e.length&&(s([]),i(0),l(new Map),f(!1),b.current=-1,y.current.clear())},[0===e.length]),g(()=>{if(0===e.length)return;const t=b.current+1;if(t>=e.length)return void v(e);let n=!1;const r=[],a=[];for(let s=t;s<e.length;s++){const t=e[s];if(t.type===Jt.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 s="number"==typeof t.timestamp?t.timestamp:new Date(t.timestamp).getTime();if(!y.current.has(s)){y.current.add(s),n=!0,r.push({plan:e,timestamp:s});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")}}),a.push({timestamp:s,statusMap:t})}}}catch(e){console.error("Failed to parse plan from message:",e)}}b.current=e.length-1,n&&r.length>0&&(s(e=>[...[...r].reverse(),...e]),i(0),f(!0),a.length>0&&l(e=>{const t=new Map(e);for(const e of a)t.set(e.timestamp,e.statusMap);return t})),v(e)},[e,t]),g(()=>{if(1===r.length&&!h&&!sessionStorage.getItem("plan-panel-shown")){const e=setTimeout(()=>{f(!0),sessionStorage.setItem("plan-panel-shown","true")},500);return()=>clearTimeout(e)}},[r.length,h]),g(()=>{0===r.length&&f(!1)},[r.length]);const v=p(e=>{const n=e[e.length-1];n&&(n.type===Jt.TERMINATED?m(!1):m(!!t||n.type===Jt.REQUEST_INPUT))},[t]);return{plans:r,activePlanIndex:a,setActivePlanIndex:i,workstreamStatusMap:o,showInput:d,showSlidingPanel:h,setShowSlidingPanel:f}}(ie,s,i),{openDocuments:we,activeDocumentId:Ne,isDocPanelOpen:ke,docRefreshKey:Ce,closeDocPanel:Se,closeDocument:_e,selectDocument:je,openDocInPanel:Ie}=function(e){const[t,n]=c([]),[r,s]=c(null),[a,i]=c(!1),[o,l]=c(0),d=u(-1);return g(()=>{0===e.length&&(n([]),s(null),i(!1),l(0),d.current=-1)},[0===e.length]),g(()=>{const t=d.current+1;if(!(t>=e.length)){for(let r=t;r<e.length;r++){const t=e[r];if(t.type===Jt.UPDATE&&t.details){const e=t.details;if("document_created"===e.event_class||"document_updated"===e.event_class){const t=e.document_id,r=e.title;t&&(n(e=>e.some(e=>e.id===t)?e:[...e,{id:t,title:r||"Document"}]),s(t),i(!0),"document_updated"===e.event_class&&l(e=>e+1))}}}d.current=e.length-1}},[e]),{openDocuments:t,activeDocumentId:r,isDocPanelOpen:a,docRefreshKey:o,closeDocPanel:p(()=>{i(!1)},[]),closeDocument:p(e=>{n(t=>{const n=t.filter(t=>t.id!==e);return 0===n.length?(i(!1),s(null)):s(t=>t===e?n[0].id:t),n})},[]),selectDocument:p(e=>{s(e)},[]),openDocInPanel:p(e=>{n(t=>t.some(t=>t.id===e)?t:[...t,{id:e,title:"Document"}]),s(e),i(!0)},[])}}(ie),{processingFiles:Pe,hasProcessingFiles:Fe,handleFileUpload:Ee}=function(e,t,n,r){const[s,a]=c(new Map);g(()=>{a(new Map)},[t.runId]);const i=l(()=>{const e=new Map(s);return n.forEach((t,n)=>{e.set(n,t)}),e},[s,n]),o=l(()=>Array.from(i.values()).some(e=>e.status===un.UPLOADING||e.status===un.PROCESSING),[i]),d=p(async n=>{for(const s of n){const n=`file-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,i=`files/${s.name}`,o={id:n,name:s.name,content_type:s.type||"application/octet-stream",size:s.size,status:un.UPLOADING,started_at:Date.now()};a(e=>new Map(e).set(n,o));try{await e.files.uploadArtifact(t.runId,i,s),a(e=>{const t=new Map(e),r=t.get(n);return r&&(r.status=un.PROCESSING,r.artifact_path=i,r.reference=`artifact:${i}`),t}),await e.store.workflows.sendSignal(t.workflowId,t.runId,"FileUploaded",{id:n,name:s.name,content_type:s.type||"application/octet-stream",reference:`artifact:${i}`,artifact_path:i})}catch(e){a(t=>{const r=new Map(t),s=r.get(n);return s&&(s.status=un.ERROR,s.error=e instanceof Error?e.message:"Upload failed",s.completed_at=Date.now()),r}),r({status:"error",title:"Upload Failed",description:e instanceof Error?e.message:"Failed to upload file",duration:3e3})}}},[e,t,r]);return{processingFiles:i,hasProcessingFiles:o,handleFileUpload:d}}(se,n,pe,ae),$e=u(null),Oe=u(null),[Re,Le]=c(!1),[Me,Ue]=c("sliding"),Be=U??Me,He=p(e=>{V?V(e):Ue(e)},[V]),[Ge,Ke]=c(!1),[Ye,Ze]=c(0),[Qe,Xe]=c(!1),et=u(0),tt=u(Re);tt.current=Re;const nt=u(Fe);nt.current=Fe;const rt=l(()=>{const e=ie[ie.length-1];return e?.type===Jt.TERMINATED?"TERMINATED":ue},[ie,ue]),st=l(()=>{const e=he[ge]||{plan:{plan:[]},timestamp:0},t=be.get(e.timestamp)||new Map;return{plan:e.plan,workstreamStatus:t}},[he,ge,be]),at=p(()=>{xe(e=>(e||sessionStorage.setItem("plan-panel-shown","true"),!e))},[xe]),it=p(e=>{fe(e)},[fe]),ot=p(()=>{xe(!1)},[xe]),lt=p(({documentId:t,children:n})=>e("button",{className:"text-info underline cursor-pointer hover:text-info/80",onClick:()=>Ie(t),children:n}),[Ie]),ct=te??lt;g(()=>{if(!le){const e=setInterval(()=>{Ze(()=>Math.floor(Math.random()*($r.length-1)))},4e3);return()=>clearInterval(e)}},[le]),g(()=>(O&&(O.current=Ee),()=>{O&&(O.current=null)}),[O,Ee]),g(()=>{R?.(Pe)},[Pe,R]),g(()=>{L?.(he,ge)},[he,ge,L]),g(()=>{M?.(be)},[be,M]),g(()=>{0!==ie.length&&(ye?rt&&"RUNNING"!==rt?W?.(!1):null!==rt&&W?.(!0):W?.(!1))},[ye,rt,ie.length,W]);const dt=p(e=>{const t=e.trim();if(!t||tt.current)return;if(nt.current)return void ae({status:"warning",title:"Files Still Processing",description:"Please wait for all files to finish processing before sending",duration:3e3});Le(!0);const r=P?.()||[],s=A?.()||{};let a=t;if(r.length>0&&!/store:\S+/.test(t)){a=[t,"","Attachments:",...r.map(e=>`[${e.name}](/store/objects/${e.id})`)].join("\n")}const i=`msg-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,o={timestamp:Date.now(),workflow_run_id:n.runId,type:Jt.QUESTION,message:a,workstream_id:"main",details:{_optimistic:!0,_messageId:i}};de(o);const l={...r.length>0?{attached_docs:r.map(e=>e.id)}:{},...s,_messageId:i};se.store.workflows.sendSignal(n.workflowId,n.runId,"UserInput",{message:a,metadata:l}).then(()=>{T?.()}).catch(e=>{me(e=>e.details?._messageId===i),ae({status:"error",title:"Failed to Send Message",description:e instanceof Error?e.message:"Unknown error",duration:3e3})}).finally(()=>{Le(!1)})},[n.runId,n.workflowId,se,ae,P,A,T,de,me]),mt=p(e=>{e.preventDefault(),e.stopPropagation(),et.current++,n&&e.dataTransfer?.types?.includes("Files")&&Xe(!0)},[n]),ut=p(e=>{e.preventDefault(),e.stopPropagation()},[]),pt=p(e=>{e.preventDefault(),e.stopPropagation(),et.current--,0===et.current&&Xe(!1)},[]),ht=p(e=>{if(e.preventDefault(),e.stopPropagation(),et.current=0,Xe(!1),n&&e.dataTransfer?.files&&e.dataTransfer.files.length>0){const t=Array.from(e.dataTransfer.files);Ee(t)}},[n,Ee]),gt=p(async()=>{if(!Ge){Ke(!0);try{await se.store.workflows.sendSignal(n.workflowId,n.runId,"Stop",{message:"User requested stop"}),ae({status:"info",title:"Agent Interrupted",description:"Type your message to give new instructions",duration:3e3})}catch(e){ae({status:"error",title:"Failed to Interrupt",description:e instanceof Error?e.message:"Unknown error",duration:3e3})}finally{Ke(!1)}}},[Ge,se,n.workflowId,n.runId,ae]);g(()=>(q&&(q.current=le?null:gt),()=>{q&&(q.current=null)}),[q,le,gt]),g(()=>{B?.(Ge)},[Ge,B]);const bt=r||n.workflowId.split(":")[2]||"Agent Conversation",[yt,vt]=c(!1),xt=l(()=>st.plan.plan?.reduce((e,t)=>(t.id&&t.goal&&e.set(t.id.toString(),t.goal),e),new Map),[st.plan]),wt=e(or,{children:e(Tr,{children:t("div",{className:ze("flex flex-col lg:flex-row gap-2 h-full relative overflow-hidden",Qe&&"ring-2 ring-blue-400 ring-inset",D),onDragEnter:mt,onDragOver:ut,onDragLeave:pt,onDrop:ht,children:[Qe&&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(Z,{className:"size-6"}),"Drop files to upload"]})}),t("div",{ref:Oe,className:ze("flex flex-col min-h-0 border-0",ve||ke?"w-full lg:w-3/5 flex-1 min-h-[50vh]":o?"flex-1 w-full":"flex-1 mx-auto "+(i?"":"max-w-4xl")),children:[!k&&e("div",{className:"flex-shrink-0",children:e(pc,{title:bt,isCompleted:le,onClose:a,isModal:i,run:n,viewMode:Be,onViewModeChange:He,showPlanPanel:ve,hasPlan:he.length>0,onTogglePlanPanel:at,onDownload:async()=>{try{const e=await async function(e,t){return e.files.getDownloadUrl(`agents/${t}/conversation.json`).then(e=>e.url)}(se,n.runId);e&&window.open(e,"_blank")}catch(e){console.error("Failed to download conversation",e),ae({status:"error",title:"Failed to download conversation",duration:3e3})}},onCopyRunId:()=>{navigator.clipboard.writeText(n.runId),ae({status:"success",title:"Run ID copied",duration:2e3})},resetWorkflow:m,onExportPdf:()=>{Oe.current?vt(!0):ae({status:"error",title:"PDF export failed",description:"No conversation content available to export",duration:3e3})},isReceivingChunks:ce})}),0!==ie.length||le?e(lc,{messages:ie,bottomRef:$e,isCompleted:le,plan:st.plan,workstreamStatus:st.workstreamStatus,showPlanPanel:ve,onTogglePlanPanel:at,plans:he,activePlanIndex:ge,onChangePlan:it,taskLabels:xt,streamingMessages:oe,onSendMessage:dt,thinkingMessageIndex:Ye,messageItemClassNames:H,messageStyleOverrides:G,toolCallGroupClassNames:J,hideToolCallsInViewMode:K,streamingMessageClassNames:Y,batchProgressPanelClassNames:Q,viewMode:Be,hideWorkstreamTabs:_,workingIndicatorClassName:X,messageListClassName:ee,StoreLinkComponent:ct,CollectionLinkComponent:ne,prependFriendlyMessage:re}):e("div",{className:"flex-1 flex flex-col items-center justify-center h-full text-center py-6",children:t("div",{className:"p-5 max-w-md border border-info rounded-lg shadow-sm",children:[t("div",{className:"flex items-center space-x-3 mb-3",children:[e(Nr,{size:"sm",color:"blue"}),e("div",{className:"text-sm text-muted font-medium",children:$r[Ye]})]}),e("div",{className:"mt-4 flex justify-center",children:e(wr,{color:"blue",className:"mt-1"})})]})}),!C&&e("div",{className:"flex-shrink-0",style:{paddingBottom:"env(safe-area-inset-bottom, 0px)"},children:rt&&"RUNNING"!==rt?t(ft,{status:"COMPLETED"===rt?"success":"done",icon:null,className:"m-2",children:["This Workflow is ",rt]}):ye&&e(gc,{onSend:dt,onStop:gt,disabled:z,isSending:Re||z,isStopping:Ge,isStreaming:!le,isCompleted:le,activeTaskCount:(()=>{if(!ie.length)return 0;const e=new Map;ie.forEach(t=>{const n=Lr(t);"main"!==n&&"all"!==n&&(e.has(n)||e.set(n,[]),e.get(n).push(t))});let t=0;for(const[n,r]of e.entries())if(r.length>0){const e=r[r.length-1];[Jt.COMPLETE,Jt.IDLE].includes(e.type)||t++}return t})(),placeholder:d,onFilesSelected:Ee,uploadedFiles:h,onRemoveFile:f,acceptedFileTypes:b,maxFiles:y,processingFiles:Pe,hasProcessingFiles:Fe,renderDocumentSearch:v,selectedDocuments:x,onRemoveDocument:w,hideObjectLinking:N,hideFileUpload:j,className:F,inputClassName:E})})]}),!S&&ve&&e("div",{className:"w-full lg:w-1/3 min-h-[50vh] lg:h-full border-t lg:border-t-0 lg:border-l",children:e(fc,{plan:st.plan,workstreamStatus:st.workstreamStatus,isOpen:ve,onClose:ot,plans:he,activePlanIndex:ge,onChangePlan:it})}),!I&&ke&&we.length>0&&e("div",{className:ze("w-full lg:w-2/5 min-h-[50vh] lg:h-full border-t lg:border-t-0 lg:border-l",ve&&"lg:w-1/3"),children:e(kc,{isOpen:ke,onClose:Se,documents:we,activeDocumentId:Ne,onSelectDocument:je,onCloseDocument:_e,refreshKey:Ce,runId:n.runId})}),t(Ve,{isOpen:yt,onClose:()=>vt(!1),children:[e(We,{children:"Export conversation as PDF"}),t(qe,{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(Je,{align:"right",children:[e(De,{variant:"ghost",size:"sm",onClick:()=>vt(!1),children:"Cancel"}),e(De,{size:"sm",onClick:()=>{if(!Oe.current)return void ae({status:"error",title:"PDF export failed",description:"No conversation content available to export",duration:3e3});const e=`${bt} - ${n.runId}`,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 s=r.document;return s.open(),s.write(`<!doctype html><html><head><title>${t}</title></head><body></body></html>`),s.close(),s.title=t,document.querySelectorAll('link[rel="stylesheet"], style').forEach(e=>{s.head.appendChild(e.cloneNode(!0))}),s.body.innerHTML=e.innerHTML,r.focus(),r.print(),setTimeout(()=>{n.parentNode?.removeChild(n)},1e3),!0}(Oe.current,e);t?(ae({status:"success",title:"PDF export ready",description:"Use your browser's Print dialog to save as PDF",duration:4e3}),vt(!1)):ae({status:"error",title:"PDF export failed",description:"Unable to open print preview",duration:4e3})},children:"Open print dialog"})]})]})]})})});return $?e(gn,{data:$,sendMessage:dt,ChartComponent:br,artifactRunId:n.runId,children:wt}):wt}function Pc({messages:t}){const n=o.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,n)=>e(Vl,{message:t,showPulsatingCircle:!1},`${t.timestamp}-${n}`))})}function Tc({messages:t,bottomRef:n,className:r,messagesClassName:s,emptyClassName:a}){const i=o.useRef(null);g(()=>{n.current&&n.current.scrollIntoView({behavior:"smooth"})},[t,n]);const l=o.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===l.length?e("div",{className:`flex items-center justify-center h-full text-center py-8 ${a||""}`,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 ${s||""}`,children:e(Pc,{messages:l,isCompleted:!1})})})}function zc({children:t,fallback:n}){return Ac?e(Ac,{fallback:n,children:t}):e(qn,{FallbackComponent:n,children:t})}let Ac=null;function Dc(e){Ac=e}function Fc({children:t}){return e(zc,{fallback:Ec,children:t})}function Ec({error:n}){return t(ft,{status:"error",title:"Sorry, something went wrong...",children:[t("div",{className:"mb-4",children:["Our team has been notified and will be quickly working on resolving it. If you'd like to escalate or simply contact us, please email us at ",e("a",{className:"text-info",href:"mailto:support@vertesiahq.com",children:"support@vertesiahq.com"}),"."]}),n?.message&&e("code",{className:"w-full mt-4 text-sm text-muted break-words",children:n.message})]})}function $c({children:t}){return e(zc,{fallback:Oc,children:t})}function Oc({error:n}){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:n?.message})]})})}function Rc({children:t}){return e(zc,{fallback:Lc,children:t})}function Lc({error:n}){return console.log("WidgetError",n),t("div",{className:"text-sm",children:["Sorry, this area cannot be loaded or rendered.",n?.message&&e("pre",{children:n.message})]})}function Mc({className:n,children:s,title:a,description:i,actions:o,breadcrumbs:l,isCompact:c=!1,useDynamicBreadcrumbs:d=!0}){const m=bn();function u(e){return e.replace(/[-_]/g," ").split(" ").map(e=>Bn(e)).join(" ")}const p=e=>{const t=e?.href||"";if(!t)return"Page";const n=t.split("#")[0].split("?")[0].split("/").filter(e=>e.length>0);if(3===n.length){if(e.title!==document.title&&e.title)return e.title;return`${u(n[1])} Detail (...${n[2].slice(-6)})`}return n.length>=2?u(n[n.length-1]):1===n.length?u(n[0]):"Page"},h=(()=>{const e=[];if(d&&"undefined"!=typeof window&&window.history.state?.historyChain){const t=window.history.state.historyChain;t.forEach((n,r)=>{const s=t.length-r;e.push({label:p(n),href:n.href,onClick:()=>m(n.href,{stepsBack:s})})})}return l&&l.length>0&&l.forEach(t=>{const n="string"==typeof t?.props?.children?t.props.children:"Page";e.push(t?.props?.href?{href:t?.props?.href,label:n,onClick:()=>m(t.props.href,{replace:t.props.clearBreadcrumbs})}:{label:n})}),e})();return t("div",{className:r(c?"pb-0":"pb-2","p-4 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",children:[e("nav",{className:"flex-1 flex justify-start text-xs",children:h.length>0&&e(Gt,{path:h,separator:e(j,{className:"w-3.5 h-3.5"}),maxItems:4})}),t("div",{className:"flex gap-2 items-center",children:[e("h1",{className:"text-xl font-semibold break-all",children:a}),i&&e(Ee,{description:i,children:e(re,{className:"size-4 text-muted"})})]})]}),e("div",{className:"flex gap-x-2 shrink-0",children:o})]}),s&&e("div",{className:"w-full flex items-center",children:s})]})}function Uc({}){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:"Page Not Found"})]})}function Vc(...e){const t=Array.from(e);return t.__AnyOf__=!0,t}function Wc(...e){return Array.from(e)}function qc(e){return!0===e.__AnyOf__}class Bc{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 s=new Set;for(const e of n){const t=r[e];if(t)for(const e of t)s.add(e)}this.permissions=s}hasPermission(e){if("string"==typeof e)return this.permissions.has(e);if(qc(e))return e.some(e=>this.permissions.has(e));for(const t of e)if(!this.permissions.has(t))return!1;return!0}}const Hc=d(void 0);function Gc(){const e=m(Hc);if(!e)throw new Error("UserPermissionContext cannot be used outside UserPermissionProvider");return e}function Jc({children:t}){const n=Te(),{data:r,error:s,isLoading:a}=$e(()=>n.user?n.client.iam.roles.list():Promise.resolve(void 0),[n.user]),i=l(()=>n.authToken&&r&&!a?new Bc(n,r):void 0,[n,r,a]);return s?e(Oe,{title:"Failed to fetch role mappings",children:s.message}):i&&e(Hc.Provider,{value:i,children:t})}function Kc({permission:t,isDisabled:n,title:r,children:s,...a}){return Gc().hasPermission(t)||(n=!0,r="You do not have permission to perform this action"),e(De,{isDisabled:n,title:r,...a,children:s})}function Yc({permission:t,...n}){return Gc().hasPermission(t)?e(Hn,{...n}):null}function Zc({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:"ml-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{Yn as ActivitiesDoc,Qn as ActivityDoc,Pl as AddToCollectionAction,Il as AddToCollectionActionComponent,xr as AgentChart,Oi as AgentRunnerFacetsNav,Wc as AllOf,wr as AnimatedThinkingDots,Vc as AnyOf,pi as ApiKeyAvatar,Fr as AskUserWidget,Do as BrowseCollectionView,ol as ChangeTypeAction,il as ChangeTypeActionComponent,Fi as CollectionsFacetsNav,Ro as CollectionsTable,Er as ConfirmationWidget,Yr as ContentDispositionButton,Jo as ContentObjectTypesSearch,Mo as ContentObjectTypesTable,Na as ContentOverview,$o as CreateCollectionForm,Oo as CreateCollectionModal,Ho as CreateOrUpdateTypeModal,dl as DeleteObjectsAction,cl as DeleteObjectsActionComponent,ml as DeleteObjectsFromCollectionsAction,Ki as DocumentGridView,La as DocumentIcon,Ra as DocumentIconSkeleton,yo as DocumentInput,vo as DocumentPreviewPanel,Yi as DocumentSearch,uo as DocumentSearchProvider,_o as DocumentSearchResults,So as DocumentSearchResultsWithDropZone,Ri as DocumentSelection,Vi as DocumentSelectionProvider,lo as DocumentTable,Gi as DocumentTableColumn,Ji as DocumentTableView,ao as DocumentUploadModal,Si as DocumentsFacetsNav,tl as EditCollectionView,fi as EnvironmentFacet,pl as ExportPropertiesAction,ul as ExportPropertiesComponent,To as ExportPropertiesModal,Po as ExportTypes,no as FileUploadAction,Mc as GenericPageNavHeader,pc as Header,Ii as InteractionsFacetsNav,jr as JumpingDots,Ul as MESSAGE_STYLES,$s as MagicPdfView,Vl as MessageItem,Tc as MessagesContainer,Sc as ModernAgentConversation,Uc as NotFoundView,Ko as ObjectSchemaEditor,Uo as ObjectTypeSearch,Vo as ObjectTypeSearchContext,Zo as ObjectTypeSearchProvider,wl as ObjectsActionContext,kl as ObjectsActionContextProvider,Fc as PanelErrorBoundary,cc as PayloadBuilder,mc as PayloadBuilderProvider,dc as PayloadContext,is as PdfDocumentRenderer,Qr as PdfPageRenderer,cs as PdfPageSlider,as as PdfThumbnailList,zi as PromptsFacetsNav,ia as PropertiesEditorModal,Nr as PulsatingCircle,Cr as PulsingMessageLoader,gl as RemoveFromCollectionAction,hl as RemoveFromCollectionActionComponent,$c as RowErrorBoundary,vi as RunsFacetsNav,aa as SaveVersionConfirmModal,Zi as SearchContext,Kc as SecureButton,Yc as SecureSidebarItem,rl as SelectCollection,Eo as SelectContentType,Qo as SelectContentTypeModal,ho as SelectDocument,fo as SelectDocumentModal,Al as SelectionActions,es as SharedPdfProvider,sl as SharedPropsEditor,rs as SimplePdfPage,Rs as SimplePdfViewer,wc as SkillWidgetProvider,bl as StartWorkflowAction,fl as StartWorkflowComponent,Wl as StreamingMessage,Va as StringFacet,Wa as StringListFacet,al as SyncMemberHeadsToggle,Xo as TableLayoutEditor,Sr as ThinkingBar,$r as ThinkingMessages,Ka as TypeFacet,qa as TypeRegistry,Ha as TypeRegistryProvider,kr as TypedDots,Fl as UploadObjectsButton,Zc as UserAvatar,ci as UserInfo,Jc as UserPermissionProvider,Bc as UserPermissions,Hc as UserPermissionsContext,Ya as VStringFacet,Za as VTypeFacet,gi as VUserFacet,br as VegaLiteChart,zc as VertesiaErrorBoundary,_r as WavyThinking,Rc as WidgetErrorBoundary,Ni as WorkflowExecutionsFacetsNav,Lo as collectionIcon,na as getWorkflowStatusColor,ra as getWorkflowStatusName,qc as isAnyOf,Hs as isCsv,Gs as isImage,Js as isPdf,Ys as isPreviewableAsPdf,vr as isRechartsSpec,yr as isVegaLiteSpec,Ks as isVideo,ta as printElementToPdf,ea as retrieveRendition,Dc as setErrorBoundaryComponent,Ls as shortId,Ms as shortenString,el as stringifyTableLayout,Ei as useAgentRunnerFilterGroups,$i as useAgentRunnerFilterHandler,Ai as useCollectionsFilterGroups,Di as useCollectionsFilterHandler,ki as useDocumentFilterGroups,Ci as useDocumentFilterHandler,Qi as useDocumentSearch,to as useDocumentSearchCount,Mi as useDocumentSelection,io as useDocumentUploadHandler,la as useDownloadFile,ri as useFetchApiKeyInfo,ni as useFetchGroupInfo,ti as useFetchUserInfo,_i as useInteractionsFilterGroups,ji as useInteractionsFilterHandler,_l as useObjectsActionCallback,Sl as useObjectsActionContext,Ui as useOptionalDocumentSelection,uc as usePayloadBuilder,Pi as usePromptsFilterGroups,Ti as usePromptsFilterHandler,bi as useRunsFilterGroups,yi as useRunsFilterHandler,Wo as useSearch,Bo as useSearchCount,ts as useSharedPdf,so as useSmartFileUploadProcessing,jl as useStartWorkflowCallback,Ga as useTypeRegistry,Gc as useUserPermissions,Xi as useWatchDocumentSearchFacets,eo as useWatchDocumentSearchResult,qo as useWatchSearchResult,xi as useWorkflowExecutionsFilterGroups,wi as useWorkflowExecutionsFilterHandler};
|
|
2
2
|
//# sourceMappingURL=vertesia-ui-features.js.map
|