@vertesia/ui 0.79.2 → 0.79.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/lib/esm/core/components/SelectBox.js +1 -1
  2. package/lib/esm/core/components/SelectBox.js.map +1 -1
  3. package/lib/esm/core/components/index.js +1 -2
  4. package/lib/esm/core/components/index.js.map +1 -1
  5. package/lib/esm/core/components/shadcn/popover.js +1 -1
  6. package/lib/esm/core/components/shadcn/popover.js.map +1 -1
  7. package/lib/esm/core/hooks/CompositeState.js +1 -139
  8. package/lib/esm/core/hooks/CompositeState.js.map +1 -1
  9. package/lib/esm/env/index.js +1 -1
  10. package/lib/esm/env/index.js.map +1 -1
  11. package/lib/esm/features/agent/PayloadBuilder.js +55 -80
  12. package/lib/esm/features/agent/PayloadBuilder.js.map +1 -1
  13. package/lib/esm/features/agent/chat/ModernAgentOutput/AllMessagesMixed.js +1 -1
  14. package/lib/esm/features/agent/chat/ModernAgentOutput/AllMessagesMixed.js.map +1 -1
  15. package/lib/esm/features/agent/chat/ModernAgentOutput/Header.js +1 -1
  16. package/lib/esm/features/agent/chat/ModernAgentOutput/Header.js.map +1 -1
  17. package/lib/esm/features/agent/chat/ModernAgentOutput/WorkstreamTabs.js +2 -2
  18. package/lib/esm/features/agent/chat/ModernAgentOutput/WorkstreamTabs.js.map +1 -1
  19. package/lib/esm/features/store/collections/EditCollectionView.js +7 -18
  20. package/lib/esm/features/store/collections/EditCollectionView.js.map +1 -1
  21. package/lib/esm/features/store/collections/index.js +0 -2
  22. package/lib/esm/features/store/collections/index.js.map +1 -1
  23. package/lib/esm/features/store/objects/DocumentSearchResults.js +2 -10
  24. package/lib/esm/features/store/objects/DocumentSearchResults.js.map +1 -1
  25. package/lib/esm/features/store/objects/components/useDownloadObject.js +2 -2
  26. package/lib/esm/features/store/objects/components/useDownloadObject.js.map +1 -1
  27. package/lib/esm/features/user/UserInfo.js +0 -2
  28. package/lib/esm/features/user/UserInfo.js.map +1 -1
  29. package/lib/esm/session/UserSession.js +0 -1
  30. package/lib/esm/session/UserSession.js.map +1 -1
  31. package/lib/esm/session/UserSessionProvider.js +2 -9
  32. package/lib/esm/session/UserSessionProvider.js.map +1 -1
  33. package/lib/esm/session/auth/composable.js +67 -66
  34. package/lib/esm/session/auth/composable.js.map +1 -1
  35. package/lib/esm/shell/apps/AppProjectSelector.js +2 -2
  36. package/lib/esm/shell/apps/AppProjectSelector.js.map +1 -1
  37. package/lib/esm/widgets/form/Form.js +1 -1
  38. package/lib/esm/widgets/form/Form.js.map +1 -1
  39. package/lib/esm/widgets/form/ManagedObject.js +0 -4
  40. package/lib/esm/widgets/form/ManagedObject.js.map +1 -1
  41. package/lib/tsconfig.tsbuildinfo +1 -1
  42. package/lib/types/core/components/index.d.ts +1 -2
  43. package/lib/types/core/components/index.d.ts.map +1 -1
  44. package/lib/types/core/components/shadcn/popover.d.ts +0 -7
  45. package/lib/types/core/components/shadcn/popover.d.ts.map +1 -1
  46. package/lib/types/core/hooks/CompositeState.d.ts +6 -115
  47. package/lib/types/core/hooks/CompositeState.d.ts.map +1 -1
  48. package/lib/types/env/index.d.ts +1 -3
  49. package/lib/types/env/index.d.ts.map +1 -1
  50. package/lib/types/features/agent/PayloadBuilder.d.ts +19 -11
  51. package/lib/types/features/agent/PayloadBuilder.d.ts.map +1 -1
  52. package/lib/types/features/store/collections/EditCollectionView.d.ts.map +1 -1
  53. package/lib/types/features/store/collections/index.d.ts +0 -2
  54. package/lib/types/features/store/collections/index.d.ts.map +1 -1
  55. package/lib/types/features/store/objects/DocumentSearchResults.d.ts.map +1 -1
  56. package/lib/types/features/store/objects/components/useDownloadObject.d.ts +1 -1
  57. package/lib/types/features/store/objects/components/useDownloadObject.d.ts.map +1 -1
  58. package/lib/types/features/user/UserInfo.d.ts.map +1 -1
  59. package/lib/types/session/UserSession.d.ts.map +1 -1
  60. package/lib/types/session/UserSessionProvider.d.ts.map +1 -1
  61. package/lib/types/session/auth/composable.d.ts.map +1 -1
  62. package/lib/types/widgets/form/ManagedObject.d.ts.map +1 -1
  63. package/lib/vertesia-ui-core.js +1 -1
  64. package/lib/vertesia-ui-core.js.map +1 -1
  65. package/lib/vertesia-ui-env.js +1 -1
  66. package/lib/vertesia-ui-env.js.map +1 -1
  67. package/lib/vertesia-ui-features.js +1 -1
  68. package/lib/vertesia-ui-features.js.map +1 -1
  69. package/lib/vertesia-ui-router.js.map +1 -1
  70. package/lib/vertesia-ui-session.js +1 -1
  71. package/lib/vertesia-ui-session.js.map +1 -1
  72. package/lib/vertesia-ui-shell.js +1 -1
  73. package/lib/vertesia-ui-shell.js.map +1 -1
  74. package/lib/vertesia-ui-widgets.js +1 -1
  75. package/lib/vertesia-ui-widgets.js.map +1 -1
  76. package/package.json +4 -4
  77. package/lib/esm/core/components/TagsInput.js +0 -194
  78. package/lib/esm/core/components/TagsInput.js.map +0 -1
  79. package/lib/esm/features/store/collections/SharedPropsEditor.js +0 -40
  80. package/lib/esm/features/store/collections/SharedPropsEditor.js.map +0 -1
  81. package/lib/esm/features/store/collections/SyncMemberHeadsToggle.js +0 -35
  82. package/lib/esm/features/store/collections/SyncMemberHeadsToggle.js.map +0 -1
  83. package/lib/types/core/components/TagsInput.d.ts +0 -16
  84. package/lib/types/core/components/TagsInput.d.ts.map +0 -1
  85. package/lib/types/features/store/collections/SharedPropsEditor.d.ts +0 -7
  86. package/lib/types/features/store/collections/SharedPropsEditor.d.ts.map +0 -1
  87. package/lib/types/features/store/collections/SyncMemberHeadsToggle.d.ts +0 -7
  88. package/lib/types/features/store/collections/SyncMemberHeadsToggle.d.ts.map +0 -1
@@ -1,2 +1,2 @@
1
- import{jsx as e,jsxs as t,Fragment as n}from"react/jsx-runtime";import r from"clsx";import{AnimatePresence as s,motion as i}from"motion/react";import a,{useMemo as l,useState as o,useEffect as c,createContext as d,useContext as u,useRef as m,memo as h,useCallback as p,useLayoutEffect as f}from"react";import{cn as g,useToast as v,Badge as y,Button as b,Popover as x,PopoverTrigger as w,PopoverContent as N,Command as k,CommandList as C,CommandGroup as _,CommandItem as j,Modal as S,ModalTitle as T,ModalBody as P,RadioGroup as I,FormItem as A,Input as E,ModalFooter as $,RadioOptionAdapter as z,ResizablePanelGroup as O,ResizablePanel as D,ResizableHandle as U,Spinner as L,Card as F,Separator as R,CardContent as M,VTooltip as V,SelectBox as q,InputList as B,useFetch as W,Avatar as G,Table as H,FilterProvider as J,FilterBtn as K,FilterBar as Y,FilterClear as Q,TBody as X,SharedState as Z,useWatchSharedState as ee,VModal as te,VModalTitle as ne,VModalBody as re,MessageBox as se,VModalFooter as ie,VSelectBox as ae,useIntersectionObserver as le,ErrorBox as oe,useFlag as ce,Styles as de,Checkbox as ue,NumberInput as me,SidePanel as he,Divider as pe,Textarea as fe,Switch as ge,TR as ve,EmptyCollection as ye,ConfirmModal as be,useDebounce as xe,Panel as we,CommandInput as Ne,CommandEmpty as ke,TagsInput as Ce,SelectList as _e,Portal as je,DialogDescription as Se,Heading as Te,VTabs as Pe,VTabsBar as Ie,VTabsPanel as Ae,Breadcrumbs as Ee,Center as $e}from"@vertesia/ui/core";import{CopyIcon as ze,Bot as Oe,MessageSquare as De,Info as Ue,AlertCircle as Le,User as Fe,CheckCircle as Re,Clock as Me,ClipboardList as Ve,XIcon as qe,MoreVertical as Be,ExternalLink as We,DownloadCloudIcon as Ge,TableProperties as He,LayoutGrid as Je,AlertTriangle as Ke,Copy as Ye,SquarePen as Qe,Download as Xe,Eye as Ze,Users as et,RefreshCw as tt,UploadIcon as nt,CheckCircleIcon as rt,AlertCircleIcon as st,FileIcon as it,XCircleIcon as at,FolderIcon as lt,X as ot,ChevronsUpDown as ct,FileText as dt,Maximize2 as ut,ChevronRight as mt,Settings as ht,Trash2 as pt,Search as ft,FolderClosed as gt,Check as vt,EllipsisVertical as yt,PaperclipIcon as bt,SendIcon as xt,Activity as wt,Circle as Nt,Cpu as kt,CloudDownload as Ct,ChevronsUp as _t,ImageIcon as jt,InfoIcon as St,AtSignIcon as Tt,ChevronsDown as Pt}from"lucide-react";import{useUserSession as It}from"@vertesia/ui/session";import{AgentMessageType as At,AgentSearchScope as Et,mergeInCodePromptSchemas as $t,supportsToolUse as zt,ContentNature as Ot,POSTER_RENDITION_NAME as Dt,ImageRenditionFormat as Ut,PrincipalType as Lt,InteractionStatus as Ft,SearchTypes as Rt,SupportedEmbeddingTypes as Mt}from"@vertesia/common";import{NavLink as Vt,useNavigate as qt}from"@vertesia/ui/router";import Bt from"dayjs";import Wt from"react-markdown";import Gt from"remark-gfm";import Ht,{Ajv as Jt}from"ajv";import{MarkdownRenderer as Kt,JSONDisplay as Yt,DropZone as Qt,UploadSummary as Xt,useSchema as Zt,CodeMirrorEditor as en,SchemaEditor as tn,ManagedObject as nn,GeneratedForm as rn,Popover as sn,XMLViewer as an,JSONCode as ln}from"@vertesia/ui/widgets";import on from"@monaco-editor/react";import cn from"dayjs/plugin/localizedFormat";import dn from"dayjs/plugin/relativeTime";import{Md5 as un}from"ts-md5";import{json as mn}from"@codemirror/lang-json";import{UserInfo as hn,SyncMemberHeadsToggle as pn,SharedPropsEditor as fn}from"@vertesia/ui/features";import{basicSetup as gn}from"codemirror";import{ErrorBoundary as vn}from"react-error-boundary";import{capitalize as yn}from"lodash-es";import{SidebarItem as bn}from"@vertesia/ui/layout";function xn({children:t,secondary:n=!1}){return e("span",{className:n?"bg-secondary text-primary":"text-foreground bg-muted",children:t})}function wn(e){return e?"array"===e.name?wn(e.innerType):e:void 0}function Nn({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(xn,{children:"optional"}),e(xn,{children:n.type.value})]})}function kn({activities:t}){return e("div",{className:"flex flex-col gap-y-4 divide-y divide-gray-200",children:t.map((t=>e(_n,{activity:t},t.name)))})}function Cn({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(xn,{children:n})})]})}function _n({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(xn,{children:n.name})}),n.doc&&e("div",{className:"text-gray-700 pb-2",children:n.doc}),t("div",{className:"pb-4",children:[e(Cn,{code:n.paramsType,children:"Parameters"}),e("div",{className:"divide-y divide-gray-100",children:n.params.map((t=>e(jn,{property:t},t.name)))})]}),t("div",{className:"pb-4",children:[e(Cn,{children:"Returns"}),e("div",{children:n.returnType?n.returnType.value:"void"})]})]})}function jn({property:n,className:s}){const i=l((()=>{const t=wn(n.type.innerType)??n.type;return"object"===t.name&&t.members?e(Tn,{members:t.members}):"enum"===t.name&&t.enum?e(Sn,{values:t.enum}):null}),[n.type.innerType]);return t("div",{className:r("py-2",s),children:[e(Nn,{property:n}),n.doc&&e("div",{className:"text-gray-700 text-sm pt-2",children:n.doc}),i&&e("div",{className:"my-2 overflow-hidden",children:i})]})}function Sn({values:t}){return e("div",{className:"flex flex-wrap items-center gap-2",children:t.map(((t,n)=>e(xn,{secondary:!0,children:t},n)))})}function Tn({members:n}){return e(In,{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(An,{isOpen:n}),e("div",n?{children:"Hide child properties"}:{children:"Show child properties"})]}),body:e(Pn,{properties:n})})}function Pn({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(jn,{property:t,className:"px-4 py-2"},t.name)))})}function In({button:n,body:a,className:l,isInitiallyOpen:c}){const[d,u]=o(c||!1);return t("div",{className:r(d?"block":"inline-block",l),children:[e("button",{className:"p-0 m-0 bg-transparent",onClick:()=>u(!d),children:e(s,{children:n(d)})}),e(s,{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:a})})]})}function An({isOpen:t}){return e(s,{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 En({className:n,inline:r=!1}){return t("div",{className:g("flex items-center gap-1",r?"inline-flex":"",n),children:[e("div",{className:"w-2 h-2 bg-blue-500 rounded-full animate-[jumping_1s_infinite_ease-in-out] hover:bg-blue-600",style:{transform:"translateY(0)",animationRange:"0px -8px"}}),e("div",{className:"w-2 h-2 bg-blue-500 rounded-full animate-[jumping_1s_0.3s_infinite_ease-in-out] hover:bg-blue-600",style:{transform:"translateY(0)",animationRange:"0px -8px"}}),e("div",{className:"w-2 h-2 bg-blue-500 rounded-full animate-[jumping_1s_0.6s_infinite_ease-in-out] hover:bg-blue-600",style:{transform:"translateY(0)",animationRange:"0px -8px"}})]})}function $n({className:n,inline:r=!1,color:s="blue"}){const i={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:g("flex items-center gap-1.5",r?"inline-flex":"",n),children:[e("div",{className:`w-2 h-2 bg-gradient-to-r ${i} rounded-full animate-[bounce_1.2s_ease-in-out_infinite]`}),e("div",{className:`w-2 h-2 bg-gradient-to-r ${i} rounded-full animate-[bounce_1.2s_ease-in-out_0.2s_infinite]`}),e("div",{className:`w-2 h-2 bg-gradient-to-r ${i} rounded-full animate-[bounce_1.2s_ease-in-out_0.4s_infinite]`})]})}function zn({className:n,size:r="md",color:s="blue"}){const i={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:g("relative flex",n),children:[e("span",{className:g("animate-ping absolute inline-flex h-full w-full rounded-full opacity-60",i[s])}),e("span",{className:g("animate-pulse absolute inline-flex h-[80%] w-[80%] rounded-full opacity-80",i[s]),style:{left:"10%",top:"10%",animationDuration:"2s"}}),e("span",{className:g("relative inline-flex rounded-full",i[s],{sm:"w-3 h-3",md:"w-5 h-5",lg:"w-7 h-7"}[r])})]})}function On({className:t,color:n="blue"}){const[r,s]=o(".");return c((()=>{const e=setInterval((()=>{s((e=>"."===e?"..":".."===e?"...":"."))}),500);return()=>clearInterval(e)}),[]),e("span",{className:g({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 Dn({message:n,className:r,color:s="blue"}){const i={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:g("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 ${i[s].dot} rounded-full animate-bounce`}),e("div",{className:`w-1.5 h-1.5 ${i[s].dot} rounded-full animate-bounce`,style:{animationDelay:"0.2s"}}),e("div",{className:`w-1.5 h-1.5 ${i[s].dot} rounded-full animate-bounce`,style:{animationDelay:"0.4s"}})]}),e("div",{className:`${i[s].text} font-medium text-xs`,children:n})]})}function Un({className:n,color:r="blue",width:s="md",message:i}){const[a,l]=o(15),[d,u]=o("increasing"),[m,h]=o(.4);return c((()=>{let e,t=Date.now();const n=()=>{const r=Date.now(),s=r-t;t=r,l((e=>{const t=m*(s/16);let n="increasing"===d?e+t:e-t;return n>=85?(u("decreasing"),h(.3+.2*Math.random()),85):n<=15?(u("increasing"),h(.3+.2*Math.random()),15):(Math.random()>.99&&h((e=>Math.max(.2,Math.min(.5,e+(.1*Math.random()-.05))))),n)})),e=requestAnimationFrame(n)};return e=requestAnimationFrame(n),()=>{cancelAnimationFrame(e)}}),[d,m]),t("div",{className:g("flex flex-col gap-1",n),children:[i&&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:i}),e("div",{className:g("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:g("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:`${a}%`,transition:"width 150ms cubic-bezier(0.4, 0.0, 0.2, 1)"}})})]})}function Ln({className:t,color:n="blue",size:r="md"}){const[s,i]=o(Array(7).fill(50)),a={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"}},l={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 c((()=>{let e;const t=[1.2,1,1.5,.8,1.3,.9,1.1],n=[0,.5,1,1.5,2,2.5,3];let r=0;const a=()=>{r+=.02;const l=s.map(((e,s)=>10+40*(Math.sin(r*t[s]+n[s])+1)));i(l),e=requestAnimationFrame(a)};return e=requestAnimationFrame(a),()=>{cancelAnimationFrame(e)}}),[]),e("div",{className:g("flex items-end justify-center",a[r].width,a[r].height,a[r].gap,t),children:s.map(((t,s)=>e("div",{className:g(a[r].barWidth,"rounded-full transform-gpu",l[n]),style:{height:`${t}%`,transition:"height 100ms cubic-bezier(0.4, 0.0, 0.2, 1)",opacity:.9}},s)))})}const Fn=["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..."];const Rn=[At.COMPLETE,At.IDLE,At.REQUEST_INPUT,At.TERMINATED];function Mn(e){return e.workstream_id?(e.type===At.COMPLETE&&console.log("[getWorkstreamId] COMPLETE message with workstream_id:",e.workstream_id),e.workstream_id):(e.type===At.COMPLETE&&console.log("[getWorkstreamId] COMPLETE message without workstream_id, defaulting to 'main'"),"main")}function Vn({message:r,showPulsatingCircle:s=!1}){const[i,a]=o(!1),[l,d]=o(""),[u,m]=o(!1),{client:h}=It(),p=v(),f=(()=>{const t={containerClass:"bg-white border-l-4 border-l-muted/30 shadow-sm",iconComponent:e(Oe,{className:"size-4 text-muted"}),sender:""};switch(r.type){case At.ANSWER:return{...t,containerClass:"bg-white border-l-4 border-l-muted/30 shadow-sm",iconComponent:e(Oe,{className:"size-4 text-muted"}),sender:"Agent"};case At.COMPLETE:return{...t,containerClass:"bg-white border-l-4 border-l-success shadow-sm",iconComponent:e(Re,{className:"size-4 text-success"}),sender:"Completed"};case At.TERMINATED:return{...t,containerClass:"bg-white border-l-4 border-l-attention shadow-sm",iconComponent:e(Re,{className:"size-4 text-attention"}),sender:"Terminated"};case At.QUESTION:return{...t,iconComponent:e(Fe,{className:"size-4 text-muted"}),sender:"User"};case At.THOUGHT:return{...t,iconComponent:s?e(zn,{size:"sm",color:"blue"}):e(Oe,{className:"size-4 text-muted"}),sender:"Agent"};case At.ERROR:return{...t,iconComponent:e(Le,{className:"size-4 text-muted"}),sender:"System"};case At.UPDATE:return{...t,containerClass:"bg-white border-l-4 border-success shadow-sm",iconComponent:e(Ue,{className:"size-4 text-success"}),sender:"Update"};case At.PLAN:return{...t,iconComponent:e(De,{className:"size-4 text-muted"}),sender:"Agent"};default:return{...t,sender:"Agent"}}})(),g=()=>{let e="";if(r.message&&(e="object"==typeof r.message?JSON.stringify(r.message,null,2):r.message.trim?r.message.trim():String(r.message)),"string"==typeof e&&e.includes("%thinking_message%")){const t=Math.floor(Math.random()*Fn.length);e=e.replace(/%thinking_message%/g,Fn[t])}return e},x=r=>"object"==typeof r?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(r,null,2)}):e("div",{className:"vprose prose-sm",children:e(Wt,{remarkPlugins:[Gt],components:{a:({node:t,ref:n,...r})=>{const s=r.href||"";return s.includes("/store/objects")?e(Vt,{href:s,topLevelNav:!0,children:r.children}):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&&window.open(r.src,"_blank")}),code:({node:r,ref:s,className:i,children:a,...l})=>{const o=/language-(\w+)/.exec(i||""),c=!o,d=o?o[1]:"";return t(n,{children:[!c&&d&&e("div",{className:"code-language-indicator",children:d}),e("code",{...l,children:a})]})},p:({node:t,ref:n,...r})=>e("p",{...r}),strong:({node:t,ref:n,...r})=>e("strong",{...r}),em:({node:t,ref:n,...r})=>e("em",{...r}),pre:({node:t,ref:n,...r})=>e("pre",{...r}),h1:({node:t,ref:n,...r})=>e("h1",{...r}),h2:({node:t,ref:n,...r})=>e("h2",{...r}),h3:({node:t,ref:n,...r})=>e("h3",{...r}),li:({node:t,ref:n,...r})=>e("li",{...r}),ul:({node:t,ref:n,...r})=>e("ul",{...r}),ol:({node:t,ref:n,...r})=>e("ol",{...r}),blockquote:({node:t,ref:n,...r})=>e("blockquote",{...r}),hr:({node:t,ref:n,...r})=>e("hr",{...r}),table:({node:t,ref:n,...r})=>e("div",{className:"overflow-x-auto",children:e("table",{...r})}),th:({node:t,ref:n,...r})=>e("th",{...r}),td:({node:t,ref:n,...r})=>e("td",{...r})},children:r})}),w=g();c((()=>{(async()=>{if(w){m(!0);try{const e=await(async e=>{if("string"!=typeof e)return e;let t=e;t=t.replace(/\[([^\]]+)\]\((store|collection):([a-f\d]{24})\)/gi,((e,t,n,r)=>`[${t}](/store/${"store"===n?"objects":"collections"}/${r})`));const n=Array.from(t.matchAll(/!\[([^\]]*)\]\(image:([^)]+)\)/g)),r=await Promise.all(n.map((async e=>{const[t,n,r]=e;try{return{fullMatch:t,replacement:`![${n}](${(await h.files.getDownloadUrl(r)).url})`}}catch(e){return console.error(`Failed to get download URL for image: ${r}`,e),{fullMatch:t,replacement:t}}})));for(const{fullMatch:e,replacement:n}of r)t=t.replace(e,n);return t})((e=>{if("string"!=typeof e)return e;if(r.type===At.THOUGHT||"string"==typeof r.message&&(r.message.toLowerCase().includes("thinking about")||r.message.toLowerCase().includes("i'm thinking")||r.message.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})(w));d(e)}catch(e){console.error("Error processing message content:",e),d(w)}finally{m(!1)}}})()}),[w,h]);const N=Mn(r),k=(()=>{switch(r.type){case At.ANSWER:return"border-l-info bg-info";case At.COMPLETE:return"border-l-success bg-success";case At.IDLE:return"border-l-muted bg-muted";case At.REQUEST_INPUT:return"border-l-attention bg-attention";case At.QUESTION:return"border-l-muted bg-muted";case At.THOUGHT:return"border-l-accent dark:border-l-purple-500 bg-purple-50/50 dark:bg-purple-900/10";case At.ERROR:return"border-l-destructive bg-destructive";case At.UPDATE:return"border-l-success bg-success";case At.PLAN:return"border-l-attention bg-attention";case At.TERMINATED:return"border-l-muted bg-muted";default:return"border-l-indigo-500 dark:border-l-indigo-400 bg-indigo-50/50 dark:bg-indigo-900/10"}})();return t("div",{className:`border-l-4 shadow-md overflow-hidden bg-white dark:bg-gray-900 mb-5 ${k}`,"data-workstream-id":N,children:[t("div",{className:"flex items-center justify-between px-4 py-2 border-b border-gray-100/80 dark:border-gray-800/80 bg-white/50 dark:bg-gray-900/50 backdrop-blur-sm",children:[t("div",{className:"flex items-center gap-2",children:[e("div",{className:s?"animate-fadeIn":"",children:(()=>{const t=(()=>{switch(r.type){case At.ANSWER:return"text-info";case At.COMPLETE:return"text-success";case At.IDLE:return"text-muted";case At.REQUEST_INPUT:return"text-attention";case At.QUESTION:return"text-muted";case At.THOUGHT:return"text-purple-600 dark:text-purple-400";case At.ERROR:return"text-destructive";case At.UPDATE:return"text-success";case At.PLAN:return"text-attention";default:return"text-muted"}})(),n=t=>("number"==typeof r.timestamp?r.timestamp:new Date(r.timestamp).getTime())%2==0?e(zn,{size:"sm",color:t}):e($n,{color:t});switch(r.type){case At.ANSWER:return s?n("blue"):e(Oe,{className:`size-4 ${t}`});case At.COMPLETE:case At.TERMINATED:return e(Re,{className:`size-4 ${t}`});case At.IDLE:return e(Me,{className:`size-4 ${t}`});case At.REQUEST_INPUT:case At.QUESTION:return e(Fe,{className:`size-4 ${t}`});case At.THOUGHT:return s?n("purple"):e(Oe,{className:`size-4 ${t}`});case At.ERROR:return e(Le,{className:`size-4 ${t}`});case At.UPDATE:return s?n("green"):e(Ue,{className:`size-4 ${t}`});case At.PLAN:return s?n("amber"):e(De,{className:`size-4 ${t}`});default:return s?n("blue"):e(Oe,{className:`size-4 ${t}`})}})()}),e("span",{className:"text-xs font-medium text-muted ",children:f.sender}),"main"!==N&&"all"!==N&&e(y,{variant:"default",className:"text-xs text-muted",children:N})]}),t("div",{className:"flex items-center gap-2",children:[e("span",{className:"text-xs text-muted",children:Bt(r.timestamp).format("HH:mm:ss")}),e(b,{variant:"ghost",size:"xs",onClick:()=>{const e=g()||"",t="string"==typeof r.details?r.details:r.details?JSON.stringify(r.details,null,2):"",n=[e,t?"\n\nDetails:\n"+t:""].join("").trim();navigator.clipboard.writeText(n).then((()=>{p({status:"success",title:"Copied to clipboard",duration:2e3})}))},className:"text-muted",title:"Copy message",children:e(ze,{className:"size-3"})})]})]}),t("div",{className:"px-4 py-3 bg-white dark:bg-gray-900",children:[w&&e("div",{className:"message-content",children:u?t("div",{className:"flex items-center gap-2 text-sm text-gray-500",children:[e($n,{color:"blue"}),e("span",{children:"Loading images..."})]}):x(l||w)}),r.details&&t("div",{className:"mt-2",children:[t("button",{onClick:()=>a(!i),className:"text-xs text-muted flex items-center",children:[i?"Hide":"Show"," details",e("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-3 w-3 ml-1 transition-transform "+(i?"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"})})]}),i&&e("div",{className:"mt-2 p-2 bg-muted border border-mixer-muted/40 rounded text-sm",children:"string"==typeof r.details?x(r.details):e("pre",{className:"text-xs font-mono whitespace-pre-wrap overflow-x-auto bg-muted p-2 rounded text-muted ",children:JSON.stringify(r.details,null,2)})})]})]})]})}function qn({workstreams:n,activeWorkstream:r,onSelectWorkstream:s,count:i,completionStatus:a}){const l=new Map;l.set("all","All Messages"),l.set("main","Main"),n.forEach(((e,t)=>{"all"!==t&&"main"!==t&&"research_france"!==t&&"statistics"!==t&&l.set(t,e)})),n=l;const o=Array.from(n.entries()).sort((([e],[t])=>"all"===e?-1:"all"===t?1:"main"===e?-1:"main"===t?1:e.localeCompare(t))),c=o.length>2;return e("div",c?{className:"flex overflow-x-auto space-x-1 mb-2 bg-muted border-b-2 border-muted/20 sticky top-0 z-10",children:o.map((([n,l])=>t("button",{className:"px-2 py-1 text-xs font-medium whitespace-nowrap transition-colors flex items-center gap-1.5\n "+(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:l.length>20?l:void 0,children:[l.length>20?l.substring(0,18)+"...":l,i&&i.has(n)&&i.get(n)>0&&t("div",{className:"flex items-center space-x-1",children:[e("span",{className:"inline-flex items-center justify-center p-1 text-xs rounded-full\n "+(r===n?"bg-info text-info":"bg-muted text-muted"),children:i.get(n)}),a&&"all"!==n&&(a.get(n)?e(Re,{className:"size-3 text-success"}):e(Me,{className:"size-3 text-attention"}))]})]},n)))}:{className:"py-1"})}function Bn(e,t){return"all"===t?[...e]:"main"===t?e.filter((e=>"main"===Mn(e))):e.filter((e=>Mn(e)===t))}function Wn({messages:r,bottomRef:s,viewMode:i="stacked",isCompleted:d=!1}){const u=a.useRef(null),[m,h]=o("all");c((()=>{s.current&&s.current.scrollIntoView({behavior:"smooth"})}),[r,s]);const p=a.useMemo((()=>[...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())))),[r]),f=a.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}(p);return e}),[p]),g=a.useMemo((()=>{const e=new Map;e.set("all",p.length);const t=Bn(p,"main");return e.set("main",t.length),p.forEach((t=>{const n=Mn(t);"main"!==n&&e.set(n,(e.get(n)||0)+1)})),e}),[p]),v=a.useMemo((()=>"all"===m?p:Bn(p,m)),[p,m]),y=l((()=>{const e=new Map,t=new Map;p.forEach((e=>{const n=Mn(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,[At.COMPLETE,At.IDLE,At.REQUEST_INPUT,At.TERMINATED].includes(t.type))}return e}),[p]);return t("div",{ref:u,className:"flex-1 min-h-0 h-full overflow-y-auto px-4 sm:px-2 lg:px-4 flex flex-col relative","data-testid":"all-messages-mixed",children:[e("div",{className:"sticky top-0 z-10",children:e(qn,{workstreams:f,activeWorkstream:m,onSelectWorkstream:h,count:g,completionStatus:y})}),0===v.length?e("div",{className:"flex items-center justify-center h-full text-center py-8",children:e("div",{className:"flex items-center px-4 py-3 text-muted",children:"all"===m?"Waiting for agent response...":"No messages in this workstream yet..."})}):t("div",{className:"flex-1 flex flex-col justify-start pb-4 space-y-2",children:["stacked"===i?v.map(((t,n)=>{const r=!d&&n===v.length-1&&!Rn.includes(t.type);return e(Vn,{message:t,showPulsatingCircle:r},`${t.timestamp}-${n}`)})):e(n,{children:(()=>{const t=v.filter((e=>e.type===At.ANSWER||e.type===At.QUESTION||e.type===At.COMPLETE||e.type===At.TERMINATED)),n=d?null:v.filter((e=>e.type===At.THOUGHT||e.type===At.UPDATE||e.type===At.PLAN)).sort(((e,t)=>{const n="number"==typeof e.timestamp?e.timestamp:new Date(e.timestamp).getTime();return("number"==typeof t.timestamp?t.timestamp:new Date(t.timestamp).getTime())-n}))[0],r=[...t];return n&&r.push(n),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()))),r.map(((t,n)=>{const s=!d&&n===r.length-1&&!Rn.includes(t.type);return e(Vn,{message:t,showPulsatingCircle:s},`${t.timestamp}-${n}`)}))})()}),e("div",{ref:s,className:"h-4"})]})]})}class Gn{vertesia;updateState;_interactive=!0;_debug_mode=!1;_collection;_start=!1;_preserveRunValues=!1;_interaction;_environment;_model="";_tool_names=[];_data;_interactionParamsSchema;_inputValidator;constructor(e,t){this.vertesia=e,this.updateState=t}onStateChanged(){const e=this.clone();this.updateState(e)}clone(){const e=new Gn(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._inputValidator=this._inputValidator,e._start=this._start,e._collection=this._collection,e._preserveRunValues=this._preserveRunValues,e}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 collection(){return this._collection}set collection(e){e!==this._collection&&(this._collection=e,this.onStateChanged())}get search_scope(){return this._collection?Et.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,i=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.collection=e.collection_id??void 0,this.environment=i,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?$t(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&&zt(t,e.provider)?this._model=t:this._model=e?.default_model&&zt(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,this.onStateChanged())}reset(){if(this._start=!1,this._interactive=!0,this._debug_mode=!1,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 Ht({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 Hn=d(void 0);function Jn({children:t}){const{client:n}=It(),[r,s]=o();return c((()=>{s(new Gn(n,s))}),[]),r&&e(Hn.Provider,{value:r,children:t})}function Kn(){const e=u(Hn);if(!e)throw new Error("usePayloadBuilder must be used within a PayloadProvider");return e}function Yn({title:n,onClose:r,isModal:s,run:i,viewMode:a,onViewModeChange:l,showPlanPanel:o,hasPlan:c=!1,onTogglePlanPanel:d,onDownload:u,onCopyRunId:m,resetWorkflow:h}){return e(Jn,{children:t("div",{className:"flex flex-wrap items-end justify-between py-1.5 px-2 border-b shadow-sm flex-shrink-0",children:[t("div",{className:"flex flex-wrap items-center space-x-2",children:[t("div",{className:"flex items-center space-x-1",children:[e(Oe,{className:"size-5 text-muted"}),e("span",{className:"font-medium",children:n})]}),t("span",{className:"text-xs text-muted ml-1",children:["(Run ID: ",i.runId.substring(0,8),"...)"]})]}),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",children:[e(b,{variant:"stacked"===a?"outline":"ghost",size:"xs",className:"rounded-l-md",onClick:()=>l("stacked"),children:"Details"}),e(b,{variant:"sliding"===a?"outline":"ghost",size:"xs",className:"rounded-l-md",onClick:()=>l("sliding"),children:"Most Important"})]}),t("div",{className:"relative",children:[c&&!o&&e("span",{className:"absolute -top-1 -right-1 w-2.5 h-2.5 bg-primary rounded-full border border-border z-10"}),t(b,{size:"sm",variant:o?"primary":"secondary",onClick:d,className:"transition-all duration-200 rounded-md",title:"Toggle plan panel",children:[e(Ve,{className:"size-4 mr-1.5"}),e("span",{className:"font-medium text-xs",children:o?"Hide Plan":"Show Plan"})]})]}),e(Qn,{run:i,isModal:s,onClose:r,onDownload:u,onCopyRunId:m,resetWorkflow:h}),r&&!s&&e(b,{size:"xs",variant:"ghost",onClick:r,children:e(qe,{className:"size-4"})})]})]})})}function Qn({run:n,isModal:r,onClose:s,onDownload:i,onCopyRunId:a,resetWorkflow:l}){const o=v(),{client:c}=It(),d=Kn();return t(x,{hover:!0,children:[e(w,{children:e(b,{size:"xs",variant:"ghost",title:"More actions",children:e(Be,{className:"size-4"})})}),e(N,{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(k,{children:e(C,{children:t(_,{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(j,{className:"text-xs",onSelect:()=>{return e=`/store/agent-runner?agentId=${n.runId}__${n.workflowId}`,window.open(e,"_blank"),e;var e},children:[e(We,{className:"size-3.5 mr-2 text-muted"})," Open in new tab"]}),t(j,{className:"text-xs",onSelect:()=>{a?a():(navigator.clipboard.writeText(n.runId),o({status:"success",title:"Run ID copied",duration:2e3}))},children:[e(ze,{className:"size-3.5 mr-2 text-muted"})," Copy Run ID"]}),t(j,{className:"text-xs",onSelect:()=>{i?i():async function(e,t){return e.files.getDownloadUrl(`agents/${t}/conversation.json`).then((e=>e.url))}(c,n.runId).then((e=>window.open(e,"_blank")))},children:[e(Ge,{className:"size-3.5 mr-2 text-muted"})," Download Conversation"]}),s&&r&&t(j,{className:"text-xs",onSelect:s,children:[e(qe,{className:"size-3.5 mr-2 text-muted"})," Close"]}),t(j,{className:"text-xs text-destructive",onSelect:()=>{(async e=>{try{return await c.store.workflows.terminate(e.workflowId,e.runId,"cancel"),o({status:"success",title:"Workflow cancelled",duration:2e3}),d.reset(),l?.(),!0}catch(e){return o({status:"error",title:"Failed to cancel workflow",duration:2e3}),!1}})(n)},children:[e(qe,{className:"size-3.5 mr-2 text-destructive"})," Cancel Workflow"]})]})})})})})})]})}const Xn="vertesia.content_store.lastDisplayedView";function Zn({onUpdate:t}){const[n,r]=o("grid"===localStorage.getItem(Xn)),s=()=>{localStorage.setItem(Xn,"grid"),r(!0),t(!0)},i=()=>{localStorage.setItem(Xn,"table"),r(!1),t(!1)};return e(b,{variant:"outline",onClick:()=>{n?i():s()},alt:n?"Table View":"Thumbnail View",children:e(n?He:Je,{})})}Zn.LAST_DISPLAYED_VIEW=Xn;class er extends z{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 tr({isOpen:n,onClose:r,onConfirm:s,isLoading:i,uploadedFileName:a}){const l=[{id:"update",label:"Update current version",description:a?"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:a?"Create a new revision with the replacement file while preserving the original.":"Create a new revision with these property changes while preserving the original."}],d=a?l[1]:l[0],[u,m]=o(d),[h,p]=o(""),f=new er;c((()=>{n&&(m(d),p(""))}),[n,a]);const g="new-version"===u?.id;return t(S,{isOpen:n,onClose:r,className:"sm:max-w-md",children:[e(T,{children:"Save Changes"}),e(P,{children:t("div",{className:"space-y-4",children:[a&&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:a})]})}),e("p",{className:"text-sm text-mixer-muted/5",children:"How would you like to save these changes?"}),e(I,{adapter:f,options:l,value:u,onChange:e=>{m(e)},gap:"gap-4"}),g&&e(A,{label:"Version Label (Optional)",description:"Optional label for the new version.",className:"mt-3 pl-8",children:e(E,{value:h,onChange:p,placeholder:"e.g., v1.2, approved, post-review",className:"w-full"})})]})}),t($,{children:[e(b,{variant:"secondary",onClick:r,disabled:i,children:"Cancel"}),e(b,{variant:"primary",onClick:async()=>{await s(g,g?h:void 0)},isLoading:i,children:"Save"})]})]})}function nr({isOpen:r,onClose:s,object:i,refetch:a}){const{client:l,store:d}=It(),u=v(),h=qt(),[p,f]=o(!1),[g,y]=o(""),[x,w]=o(!1),[N,k]=o(null),C=m(null),_=m(null),[j,I]=o(null),[A,E]=o(null);function z(e,t){e.languages.json.jsonDefaults.setDiagnosticsOptions({validate:!0,schemas:[{uri:"http://myserver/object-schema.json",fileMatch:["*"],schema:t}]})}return c((()=>{r&&(y(JSON.stringify(i.properties||{},null,2)),i.type?.id&&async function(e){try{const t=await d.types.retrieve(e);t.object_schema&&(I(t.object_schema),_.current&&z(_.current,t.object_schema))}catch(e){console.error("Failed to fetch JSON schema:",e)}}(i.type.id))}),[r,i]),t(n,{children:[t(S,{isOpen:r,onClose:s,className:"sm:max-w-[90%] md:max-w-[80%] lg:max-w-[75%] xl:max-w-[70%]",children:[e(T,{children:"Edit Properties"}),t(P,{children:[t("div",{className:"mb-2 text-sm text-gray-500",children:[i.type?.name?t("span",{children:["Editing properties for object type: ",e("strong",{children:i.type.name})]}):e("span",{children:"Editing properties for generic document"}),j&&e("span",{className:"ml-2 text-green-600",children:"(JSON schema validation enabled)"})]}),e("div",{className:"h-[75vh] border border-gray-300 dark:border-gray-700 rounded-md",children:e(on,{height:"100%",language:"json",value:g,onChange:e=>y(e||""),onMount:function(e,t){C.current=e,_.current=t,j&&z(t,j)},options:{minimap:{enabled:!1},scrollBeyondLastLine:!1,formatOnPaste:!0,formatOnType:!0,automaticLayout:!0,wordWrap:"on"}})})]}),t($,{children:[e(b,{variant:"secondary",onClick:s,children:"Cancel"}),e(b,{variant:"primary",onClick:function(){if(!C.current)return;const e=C.current.getValue();try{const t=JSON.parse(e);k(t),w(!0)}catch(e){u({status:"error",title:"Invalid JSON",description:"Please fix the JSON syntax errors before saving.",duration:5e3})}},children:"Save Changes"})]})]}),e(tr,{isOpen:x,onClose:function(){w(!1)},onConfirm:async function(e,t){try{f(!0);const n=N||JSON.parse(g);if(e){const e=await l.objects.update(i.id,{properties:n},{createRevision:!0,revisionLabel:t});e.id!==i.id&&E(e.id),u({status:"success",title:"New version created",description:"A new version with updated properties has been created.",duration:2e3}),w(!1),s(),e.id!==i.id&&setTimeout((()=>{h(`/objects/${e.id}`),u({status:"info",title:"Viewing New Version",description:t?`Now viewing version '${t}'`:"Now viewing the new version",duration:3e3})}),100)}else await d.objects.update(i.id,{properties:n}),u({status:"success",title:"Properties updated",description:"The object properties have been updated successfully.",duration:2e3}),a&&await a(),w(!1),s()}catch(e){u({status:"error",title:"Error updating properties",description:e.message||"An error occurred while updating the properties.",duration:5e3}),f(!1)}},isLoading:p})]})}const rr=131072;var sr;function ir({object:r,loadText:s,refetch:i}){const a=v(),l=async(e,t)=>{try{await navigator.clipboard.writeText(e),a({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),a({status:"error",title:"Copy failed",description:`Failed to copy ${t} to clipboard`,duration:5e3})}};return e(n,{children:t(O,{direction:"horizontal",className:"h-[calc(100vh-200px)]",children:[e(D,{className:"min-w-[100px]",children:e(ar,{object:r,refetch:i??(()=>Promise.resolve()),handleCopyContent:l})}),e(U,{withHandle:!0}),e(D,{className:"min-w-[100px]",children:e(lr,{object:r,loadText:s??!1,handleCopyContent:l})})]})})}function ar({object:r,refetch:s,handleCopyContent:i}){const[a,l]=o(!1),[c,d]=o(!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(b,{variant:""+(a?"ghost":"primary"),size:"sm",alt:"Preview properties",onClick:()=>l(!a),children:"Properties"}),e(b,{variant:""+(a?"primary":"ghost"),size:"sm",alt:"View in JSON format",onClick:()=>l(!a),children:"JSON"})]}),t("div",{className:"flex items-center gap-2",children:[r.properties&&e(b,{variant:"ghost",size:"sm",title:"Copy properties",onClick:()=>i(JSON.stringify(r.properties,null,2),"properties"),children:e(Ye,{className:"size-4"})}),e(b,{variant:"ghost",size:"sm",onClick:()=>{d(!0)},title:"Edit properties",className:"flex items-center gap-2",children:e(Qe,{className:"size-4"})})]})]}),r.properties?e("div",{className:"h-[calc(100vh-220px)] overflow-auto px-2",children:e(Yt,{value:r.properties,viewCode:a})}):e("div",{className:"h-[calc(100vh-220px)] overflow-auto px-2",children:e("div",{children:"No properties defined"})}),e(nr,{isOpen:c,onClose:()=>{d(!1)},object:r,refetch:s})]})}function lr({object:r,loadText:s,handleCopyContent:i}){const{store:a}=It(),l=r?.metadata?.type===Ot.Image,d=r?.metadata?.type===Ot.Video,[u,m]=o(d?sr.Video:l?sr.Image:sr.Text),[h,p]=o(r.text),[f,g]=o(!1),[v,y]=o(!1);return c((()=>{s&&!h&&(g(!0),a.objects.getObjectText(r.id).then((e=>{if(e.text.length>rr){const t=e.text.substring(0,rr);p(t),y(!0)}else p(e.text),y(!1)})).catch((e=>{console.error("Failed to load text",e)})).finally((()=>{g(!1)})))}),[s]),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:[l&&e(b,{variant:u===sr.Image?"primary":"ghost",size:"sm",alt:"View Image",onClick:()=>m(sr.Image),children:"Image"}),d&&e(b,{variant:u===sr.Video?"primary":"ghost",size:"sm",alt:"View Video",onClick:()=>m(sr.Video),children:"Video"}),e(b,{variant:u===sr.Text?"primary":"ghost",size:"sm",alt:"View Text",onClick:()=>m(sr.Text),children:"Text"})]}),u===sr.Text&&e(or,{object:r,text:h,handleCopyContent:i})]}),u===sr.Image?e(dr,{object:r}):u===sr.Video?e(ur,{object:r}):f?e("div",{className:"flex justify-center items-center h-[calc(100vh-260px)]",children:e(L,{size:"lg"})}):e(cr,{object:r,text:h,isTextCropped:v})]})}function or({object:r,text:s,handleCopyContent:i}){const{client:a}=It(),l=v(),[c,d]=o(null),u=r.content,m=u&&u.type&&"text/markdown"===u.type,h=async e=>{if(!c){d(e),l({status:"info",title:`Preparing ${e.toUpperCase()}`,description:"Fetching your document...",duration:2e3});try{const t=await a.objects.getRendition(r.id,{format:e,generate_if_missing:!0,sign_url:!0});if("generating"===t.status)return l({status:"info",title:"Generating document",description:`Please wait while we prepare your ${e.toUpperCase()} file...`,duration:5e3}),void setTimeout((()=>h(e)),3e3);if("failed"===t.status)throw new Error("Document generation failed");if(t.renditions&&t.renditions.length>0){const n=t.renditions[0];if("pdf"===e)window.open(n,"_blank"),l({status:"success",title:"PDF opened",description:"PDF document opened in a new window",duration:2e3});else{const t=document.createElement("a");t.href=n,t.download=`${r.name||"document"}.${e}`,document.body.appendChild(t),t.click(),document.body.removeChild(t),l({status:"success",title:"Document exported",description:`Successfully exported to ${e.toUpperCase()} format`,duration:2e3})}}}catch(t){console.error(`Failed to export document as ${e}:`,t),l({status:"error",title:"Export failed",description:`Failed to export document to ${e.toUpperCase()} format`,duration:5e3})}finally{d(null)}}};return e("div",{className:"h-[41px] text-lg font-semibold flex justify-between items-center px-2",children:t("div",{className:"flex items-center gap-2",children:[s&&e(b,{variant:"ghost",size:"sm",title:"Copy text",className:"flex items-center gap-2",onClick:()=>i(s,"text"),children:e(Ye,{className:"size-4"})}),m&&s&&t(n,{children:[t(b,{variant:"ghost",size:"sm",onClick:()=>h("docx"),disabled:null!==c,className:"flex items-center gap-2",children:["docx"===c?e(L,{size:"sm"}):e(Xe,{className:"size-4"}),"DOCX"]}),t(b,{variant:"ghost",size:"sm",onClick:()=>h("pdf"),disabled:null!==c,className:"flex items-center gap-2",children:["pdf"===c?e(L,{size:"sm"}):e(Xe,{className:"size-4"}),"PDF"]})]})]})})}!function(e){e.Text="text",e.Image="image",e.Video="video"}(sr||(sr={}));const cr=h((({object:r,text:s,isTextCropped:i})=>{const a=r.content,l=a&&a.type&&("text/markdown"===a.type||"text/plain"===a.type),o=s&&(s.includes("\n# ")||s.includes("\n## ")||s.includes("\n### ")||s.includes("\n* ")||s.includes("\n- ")||s.includes("\n+ ")||s.includes("![")||s.includes("](")),c=l||o;return s?t(n,{children:[i&&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(Ke,{className:"size-4"}),e("span",{className:"text-sm font-semibold",children:"Showing first 128K characters only"})]})}),e("div",{className:"max-w-7xl px-2 h-[calc(100vh-210px)] overflow-auto",children:c?e("div",{className:"vprose prose-sm p-1",children:e(Kt,{components:{a:({node:t,...n})=>{const r=n.href||"";return r.includes("/store/objects/")?e(Vt,{topLevelNav:!0,href:r,className:"text-info",children:n.children}):e("a",{...n,"data-debug":"test",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 i=/language-(\w+)/.exec(n||"");return e("code",{...s,className:!i?"px-1.5 py-0.5 rounded":"text-muted",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:"No content"})})}));function dr({object:t}){const{client:n}=It(),[r,s]=o(),i=t.content,a=t.metadata&&t.metadata.type===Ot.Image;return c((()=>{if(a){(async()=>{const e=i?.type&&["image/jpeg","image/jpg","image/png","image/gif","image/webp","image/svg+xml"].includes(i.type);try{const r=await n.objects.getRendition(t.id,{format:Ut.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)}}})()}}),[]),e("div",{className:"mb-4 px-2",children:r?e("img",{src:r,alt:t.name,className:"w-full object-contain"}):e(L,{size:"md"})})}function ur({object:n}){const{client:r}=It(),[s,i]=o(),[a,l]=o(),[d,u]=o(!0),m=n.content,h=n.metadata?.type===Ot.Video,p=n.metadata,f=p?.renditions||[],g=f.find((e=>"video/mp4"===e.content.type))||f.find((e=>"video/webm"===e.content.type)),v=m?.type&&["video/mp4","video/webm"].includes(m.type),y=f.find((e=>e.name===Dt));return c((()=>{(async()=>{if(y?.content?.source)try{const e=await r.files.getDownloadUrl(y.content.source);l(e.url)}catch(e){console.error("Failed to load poster image",e)}})()}),[y,r]),c((()=>{if(h&&(g?.content?.source||v)){(async()=>{try{let e;g?.content?.source?e=await r.files.getDownloadUrl(g.content.source):v&&m?.source&&(e=await r.files.getDownloadUrl(m.source)),e&&i(e.url)}catch(e){console.error("Failed to get video URL",e)}finally{u(!1)}})()}else u(!1)}),[h,g,v,m?.source,r]),e("div",{className:"mb-4 px-2",children:g||v?d?e("div",{className:"flex justify-center items-center h-[400px]",children:e(L,{size:"md"})}):s?e("video",{src:s,poster:a,controls:!0,className:"w-full max-h-[calc(100vh-260px)] 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 mr(e,t=7){return e?"~"+e.slice(-t):""}function hr(e,t){return e.length>t?e.substring(0,t)+"...":e}const pr="text/csv",fr="image/",gr="application/pdf",vr="video/",yr=e=>e===pr||pr.includes(e),br=e=>e.startsWith(fr)||fr.includes(e),xr=e=>e===gr||gr.includes(e),wr=e=>e.startsWith(vr)||vr.includes(e),Nr=import.meta.env,kr={max_hw:Nr?.VITE_RENDITION_HW||256,format:Ut.jpeg,generate_if_missing:!0},Cr="vertesia.content_store.renditionId";async function _r(e,t,n,r,s){if(!t?.content?.type||!(br(t.content.type)||wr(t.content.type)||xr(t.content.type)))return void s("No preview available");s("Preparing preview...");const i=(new Date).getTime()/1e3,a=localStorage.getItem(`${Cr}_${t.id}_${kr.max_hw}`),l=localStorage.getItem(`${Cr}_${t.id}_${kr.max_hw}_time`);if(a?.length&&l&&Math.abs(i-parseInt(l))<=900)return n(a),r(`${t.name} Rendition`),s("ready"),a;s("Preparing preview..."),e.objects.getRendition(t.id,kr).then((i=>{if("generating"===i.status)s("Preparing preview..."),n(""),r(""),setTimeout((()=>_r(e,t,n,r,s)),6e4);else{if("failed"===i.status)return s("No preview available"),n(""),void r("");{if(!i?.renditions?.length)return s("No preview available"),n(""),void r("");const e=i.renditions[0];localStorage.setItem(`${Cr}_${t.id}_${kr.max_hw}`,e),localStorage.setItem(`${Cr}_${t.id}_${kr.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 jr({isLoading:n=!1,counts:r=6}){return n?e("div",{className:"flex flex-wrap gap-2 justify-between",children:Array(r).fill(0).map(((n,r)=>e("div",{className:"w-[15vw] animate-pulse",children:t(F,{className:"relative flex flex-col border h-fit",children:[e("div",{className:"h-48 bg-muted rounded-t-xl flex items-center justify-center text-muted",children:" "}),e(R,{className:"bg-muted h-[2px]"}),t(M,{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 Sr({selection:n,document:r,onSelectionChange:s,onRowClick:i,previewObject:a,selectedObject:l}){const{client:d}=It(),[u,m]=o(void 0),[h,p]=o(void 0),[f,g]=o(void 0);return c((()=>{r?.content&&_r(d,r,m,p,g)}),[r]),t(F,{className:"relative flex flex-col border h-fit "+(l?.id===r.id?"border-attention border-4":""),onClick:()=>i&&i(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(b,{variant:"ghost",size:"sm",title:"Preivew Object",onClick:e=>{e.stopPropagation(),a?.(r.id)},children:e(Ze,{className:"size-4 "+("ready"===f?"text-muted":"text-white")})})}),u&&"ready"==f?e("img",{src:u,alt:h,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:f}),e(R,{className:"bg-gray-200 h-[2px]"}),t(M,{className:"p-2 flex flex-col",children:[t("div",{className:"flex flex-col overflow-hidden",children:[e(V,{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(V,{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 Tr(e){return`${e._id} (${e.count})`}function Pr(e){return`${e.name} (${e.count})`}function Ir({search:t,buckets:n,name:r,placeholder:s,className:i}){const a=t.getFilterValue(r),l=n?.find((e=>JSON.stringify(e._id)===JSON.stringify(a)));return e(q,{filterBy:"_id",className:i,isClearable:!0,optionLabel:Tr,options:n,value:l,onChange:e=>{t.setFilterValue(r,e?._id)},by:"_id",placeholder:s})}function Ar({search:t,name:n,placeholder:r,className:s}){const[i,a]=o([]);return c((()=>{t.setFilterValue(n,i)}),[i]),e(B,{className:s,value:i,onChange:a,placeholder:r})}function Er(e){return`${e.name} (${e.count})`}function $r({search:t,buckets:n,placeholder:r="Filter by Type",className:s}){const[i,a]=o([]),{typeRegistry:l}=It(),d=t.getFilterValue("type");c((()=>{if(l){const e=n.map((e=>{let t;return null==e._id?(e._id="Document",t="Document"):(t=l.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))),a(e)}}),[n,l]);const u=i?.find((e=>e._id===d));return e(q,{filterBy:"name",className:s,isClearable:!0,optionLabel:Er,options:i,value:u,onChange:e=>{t.setFilterValue("type",e?._id)},by:"_id",placeholder:r})}function zr({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:Tr(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 Or({buckets:n,typeRegistry:r,type:s="select",multiple:i=!1}){const a=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)),a.set(n,{name:t,count:e.count})}));return{name:"types",placeholder:"Types",type:s,multiple:i,options:n.map((e=>{const t=e._id,n=t||"Document",r=a.get(n);return{value:t,label:r?`${r.name} (${r.count})`:`Unknown (${e.count})`}})),labelRenderer:n=>{const r=a.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=a.get(e);return n?n.name.toLowerCase().includes(t.toLowerCase()):(console.warn(`Type name not found for ${e}`),!1)}}}const Dr={},Ur={};function Lr(e){const{client:t}=It();return W((()=>{let n=Dr[e];return n||(n=t.users.retrieve(e).then((e=>e)),Dr[e]=n),n}),[e])}function Fr(e){const{client:t}=It();return W((()=>{let n=Ur[e];return n||(n=t.iam.groups.retrieve(e).then((e=>e)),Ur[e]=n),n}),[e])}function Rr(){return e("div",{className:"size-8"})}function Mr({showTitle:n=!1,size:r="md"}){return e(Kr,{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(G,{src:"/icon.svg",size:r}),n&&e("div",{className:"text-sm font-semibold pl-2",children:"System User"})]})})}function Vr({accountId:r,showTitle:s=!1,size:i="md"}){const a=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(Kr,{title:"Service Account",description:a,children:t("div",{className:"flex flex-row items-center gap-2",children:[e(G,{src:"/cloud.svg",name:"SA",color:"bg-amber-500",className:"px-[5px] text-white",size:i}),s&&t("div",{className:"text-sm font-semibold pl-2 truncate",children:["Service Account : ",r]})]})})}function qr({title:t="Error",error:n,showTitle:r=!1,size:s="md"}){return e(Wr,{title:t,message:"string"==typeof n?n:n.message,color:"bg-red-500",showTitle:r,size:s})}function Br({userRef:t,showTitle:n=!1,size:r="md"}){if(!t)return e(Wr,{title:"Unknown User",message:"User information is not available.",showTitle:n,size:r});const[s,i]=t?t.split(":"):["unknown"];switch(s){case Lt.User:return e(Hr,{userId:i,showTitle:n,size:r});case Lt.Group:return e(Gr,{userId:i,showTitle:n,size:r});case"system":return e(Mr,{showTitle:n,size:r});case Lt.ServiceAccount:case Lt.Agent:return e(Vr,{accountId:i,showTitle:n,size:r});case Lt.ApiKey:return e(Jr,{keyId:i,size:r,showTitle:n});default:return e(qr,{title:"Unknown User",error:`Invalid user ref type: ${s}`,showTitle:n,size:r})}}function Wr({title:n,message:r,color:s,size:i="md",showTitle:a=!1}){return e(Kr,{title:n,description:r,children:t("div",{className:"flex flex-row items-center gap-2",children:[e(G,{color:s,size:i}),a&&e("div",{className:"text-sm font-semibold pl-1",children:n})]})})}function Gr({userId:n,showTitle:r=!1,size:s="md"}){const{data:i,error:a}=Fr(n);if(a)return e(qr,{title:"Failed to fetch group",error:a,showTitle:r,size:s});if(!i)return e(Rr,{});const l=t("div",{className:"space-y-1",children:[i.description&&e("div",{className:"text-sm",children:i.description}),t("div",{className:"text-xs text-muted-foreground",children:["Group ID: ",i.id]}),i.tags&&i.tags.length>0&&e("div",{className:"flex flex-wrap gap-1",children:i.tags.map((t=>e("span",{className:"px-1.5 py-0.5 bg-muted rounded text-xs",children:t},t)))})]});return e(Kr,{title:i.name||"Unnamed Group",description:l,children:t("div",{className:"flex flex-row items-center gap-2",children:[e(et,{className:"size-6 text-indigo-500",size:s}),r&&e("div",{className:"text-sm font-semibold pl-2",children:i.name||"Unnamed Group"})]})})}function Hr({userId:n,showTitle:r=!1,size:s="md"}){const{data:i,error:a}=Lr(n);if(a)return e(qr,{title:"Failed to fetch user",error:a,showTitle:r,size:s});if(!i)return e(Rr,{});const l=e("div",{className:"truncate",title:i.email,children:i.email});return e(Kr,{title:i.name||i.email||i.username||"unknown",description:l,children:t("div",{className:"flex flex-row items-center gap-2",children:[e(G,{src:i.picture,name:i.name,color:"bg-indigo-500",size:s}),r&&e("div",{className:"text-sm font-semibold pl-2",children:i.name||i.email||i.username||"unknown"})]})})}function Jr({keyId:n,showTitle:r=!1,size:s="md"}){const{client:i}=It(),{data:a,error:l}=W((()=>i.apikeys.retrieve(n)),[]);if(l)return e(qr,{title:"Failed to fetch the apikey",error:l,showTitle:r,size:s});if(!a)return e(Rr,{});const o=e(G,{name:"PK",color:"bg-pink-500",size:s}),c=t(H,{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:a?.name})]}),t("tr",{children:[e("td",{className:"font-semibold w-20",children:"Account:"}),e("td",{className:"truncate max-w-0",children:a?.account})]}),t("tr",{children:[e("td",{className:"font-semibold w-20",children:"Project:"}),e("td",{className:"truncate max-w-0",children:a?.project.name})]})]});return e(Kr,{title:"Private Key",description:c,children:t("div",{className:"flex flex-row items-center gap-2",children:[o,r&&e("div",{className:"text-sm font-semibold",children:a?.name||a?.account||a?.project.name||"unknown"})]})})}function Kr({title:n,description:r,children:s}){return t(x,{hover:!0,children:[e(w,{className:"cursor-pointer flex items-center inline-block",children:e("div",{children:s})}),e(N,{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 Yr({buckets:n,name:r,placeholder:s}){return function({buckets:n,name:r,placeholder:s}){const i=n.map((e=>({value:e._id,label:`(${e.count})`})));return{name:r,placeholder:s||`${r.charAt(0).toUpperCase()+r.slice(1)}`,options:i,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(Br,{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 Qr({search:t,buckets:n,placeholder:r="All Environments",className:s}){const{client:i}=It(),[a,l]=o([]),d=t.getFilterValue("environment");c((()=>{if(i){const e=n.map((async e=>{let t;return await i.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))),l(e)}))}}),[n,i]);const u=a?.find((e=>e._id===d));return e(q,{filterBy:"name",className:s,isClearable:!0,optionLabel:Pr,options:a,value:u,onChange:e=>{t.setFilterValue("environment",e?._id)},by:"_id",placeholder:r})}function Xr(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)),i=s?.name||r;let a="success";if(s?.status)switch(s.status){case Ft.published:a="success";break;case Ft.archived:a="destructive";break;default:a="attention"}const l=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:i}),l&&e(y,{variant:a,className:"text-xs w-fit",children:l})]}),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: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=zr({buckets:n.models||[],name:"model"});r.push(e)}if(n.statuses){const e=zr({buckets:n.statuses||[],name:"status"});r.push(e)}if(n.finish_reason){const e=zr({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=Yr({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 Zr(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 es({facets:n,search:r}){const[s,i]=o([]),a=Xr(n),l=Zr(r);return t(J,{filterGroups:a,filters:s,setFilters:e=>{const t="function"==typeof e?e(s):e;i(t),l(t)},children:[t("div",{className:"flex justify-between mb-1",children:[e(K,{}),e(b,{onClick:()=>{r.search()},variant:"outline",title:"Refresh",children:e(tt,{className:"size-5"})})]}),t("div",{className:"flex gap-2 items-center",children:[e(Y,{}),e(Q,{})]})]})}function ts(e){const t=[];if(t.push({placeholder:"Workflow or Run ID",name:"name",type:"text",options:[]}),e.status){const n=zr({buckets:e.status||[],name:"status",placeholder:"Status"});t.push(n)}if(e.initiated_by){const n=Yr({buckets:e.initiated_by||[],name:"initiated_by",placeholder:"Initiated By"});t.push(n)}t.push({name:"start",placeholder:"Date After",type:"date",multiple:!1});return t.push({name:"end",placeholder:"Date Before",type:"date",multiple:!1}),t}function ns(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,"name"===n?(e.query.search_term=r,e.query.name=r):e.query[n]=r}})),e.search()):e.clearFilters()}}function rs({facets:n,search:r}){const[s,i]=o([]),a=ts(n),l=ns(r);return e(J,{filterGroups:a,filters:s,setFilters:e=>{const t="function"==typeof e?e(s):e;i(t),l(t)},children:t("div",{className:"flex gap-2 items-center",children:[e(K,{}),e(Y,{}),e(Q,{})]})})}function ss(e){const{typeRegistry:t}=It(),n=[];if(n.push({placeholder:"ID",name:"id",type:"text",options:[]}),n.push({placeholder:"Name",name:"name",type:"text",options:[]}),e.type){const r=Or({buckets:e.type||[],typeRegistry:t,type:"select",multiple:!0});n.push(r)}if(e.status){const t=zr({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 is(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 as({facets:n,search:r}){const[s,i]=o([]),a=ss(n),l=is(r);return e(J,{filterGroups:a,filters:s,setFilters:e=>{const t="function"==typeof e?e(s):e;i(t),l(t)},children:t("div",{className:"flex gap-2 items-center",children:[e(K,{}),e(Y,{}),e(Q,{})]})})}function ls(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 os(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 cs({facets:n,search:r}){const[s,i]=o([]),a=ls(),l=os(r);return e(J,{filterGroups:a,filters:s,setFilters:e=>{const t="function"==typeof e?e(s):e;i(t),l(t)},children:t("div",{className:"flex gap-2 items-center",children:[e(K,{}),e(Y,{}),e(Q,{})]})})}function ds(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 us(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 ms({facets:n,search:r}){const[s,i]=o([]),a=ds(n),l=us(r);return e(J,{filterGroups:a,filters:s,setFilters:e=>{const t="function"==typeof e?e(s):e;i(t),l(t)},children:t("div",{className:"flex gap-2 items-center",children:[e(K,{}),e(Y,{}),e(Q,{})]})})}function hs(e){const{typeRegistry:t}=It(),n=[];if(n.push({name:"name",placeholder:"Name",type:"text",multiple:!1}),t){const e={name:"types",placeholder:"Type",type:"select",multiple:!0,options:t.types.map((e=>({label:e.name,value:e.id})))};n.push(e)}return n}function ps(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 fs({facets:n,search:r}){const[s,i]=o([]),a=hs(),l=ps(r);return e(J,{filterGroups:a,filters:s,setFilters:e=>{const t="function"==typeof e?e(s):e;i(t),l(t)},children:t("div",{className:"flex gap-2 items-center",children:[e(K,{}),e(Y,{}),e(Q,{})]})})}class gs{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 gs(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 vs=d(void 0);function ys(){const e=u(vs);if(!e)throw new Error("useObjectSelection must be used within a ObjectSelectionProvider");return e}function bs(){return u(vs)}function xs({value:t,collectionId:n,children:r}){const[s,i]=o();return c((()=>{const e=new gs(t,n,{},i);i(e)}),[t]),s&&e(vs.Provider,{value:s,children:r})}Bt.extend(dn),Bt.extend(cn);const ws={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 i=s?parseInt(s):2;return(t,n)=>{let s=new Intl.NumberFormat("en-US",{style:r?"currency":"decimal",currency:r,maximumFractionDigits:i}).format(t);return e("td",{children:s},n)}},objectId(n,r){let s=[],i=!1;if(n){const e=n.get("slice");e&&(i=!0,s.push((t=>t.slice(parseInt(e)))))}return(n,a)=>{const l=s.reduce(((e,t)=>t(e)),n.id);return t("td",{className:"flex justify-between items-center gap-2",children:[i?"~":"",l,e(b,{variant:"ghost",alt:"Preview Object",onClick:e=>{e.stopPropagation(),r?.(n.id)},children:e(Ze,{className:"size-4"})})]},a)}},objectName(t,n){let r="title";return t&&(r=t.get("title")||"title"),(t,n)=>e("td",{children:t.properties?.[r]||t.name||mr(t.id)},n)},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:Bt(t)[r](s)},n)}},Ns=ws.string();function ks(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 Cs(e){return e&&"."!==e?e.split("."):[]}class _s{layout;renderer=Ns;path;fallbackPath;previewObject;constructor(e,t){if(this.layout=e,this.path=Cs(e.field||""),this.fallbackPath=e.fallback?Cs(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=ws[e](r)}else this.renderer=ws[t]()}}get name(){return this.layout.name}resolveValue(e){let t=ks(e,this.path);return void 0===t&&this.fallbackPath&&(t=ks(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";if("objectId"===(r.indexOf("?")>0?r.substring(0,r.indexOf("?")):r)&&this.previewObject){const e=r.indexOf("?"),s=e>0?new URLSearchParams(r.substring(e+1)):void 0;return ws.objectId(s,(e=>{this.previewObject(t.id)}))(t,n)}return this.renderer(this.resolveValue(t),n)}}function js({objects:n,selection:r,isLoading:s,columns:i,onRowClick:a,selectedObject:l,toggleAll:o,onSelectionChange:c}){return t(H,{className:"w-full border-t",children:[e("thead",{children:t("tr",{children:[r&&e("th",{children:e("input",{type:"checkbox",onChange:o})}),i.map((t=>e("th",{children:t.name},t.name)))]})}),t(X,{isLoading:s,columns:i.length+1,children:[n?.map((n=>t("tr",{className:"cursor-pointer hover:bg-muted group "+(l?.id===n.id?"bg-muted":""),onClick:()=>{a&&a(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)})}),i.map(((e,t)=>e.render(n,t)))]},n.id))),0===n.length&&e("tr",{children:e("td",{colSpan:i.length+(r?1:0),className:"text-center",children:"No objects. Just drag and drop documents or images here to create content objects."})})]})]})}function Ss({objects:r,selection:s,isLoading:i,onSelectionChange:a,onRowClick:l,previewObject:o,selectedObject:c}){return t(n,{children:[e(jr,{isLoading:i}),e("div",{className:"w-full gap-2 grid lg:grid-cols-6",children:r.map((t=>e(Sr,{document:t,selection:s,onSelectionChange:a,onRowClick:l,previewObject:o,selectedObject:c},t.id)))})]})}class Ts{client;limit;collectionId;facets=new Z({});result=new Z({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:i,dynamic_scaling:a,limit:l,all_revisions: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!==i&&{score_aggregation:i},...void 0!==a&&{dynamic_scaling:a},...void 0!==o&&{all_revisions:o},...void 0!==l&&{limit:l}},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||[],i=r.facets||{};return this.result.value={isLoading:!1,objects:e?this.objects.concat(s):s,hasMore:s.length===n},!t&&i&&Object.keys(i).length>0&&(this.facets.value=i),!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 Ps=d(void 0);function Is(){return u(Ps)}function As(){return ee(Is().facets)}function Es(){const e=Is();return{...ee(e.result),search:e}}function $s(){const e=Is();return ee(e.facets).total}var zs;async function Os(e){try{const t=await e.arrayBuffer(),n=new un;n.appendByteArray(new Uint8Array(t));const r=n.end();return r?.toString()}catch(e){return void console.error("Error calculating file hash:",e)}}function Ds(){const{client:e}=It(),t=v();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),i=await Promise.all(s.map((async e=>{let n=t||void 0;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 Os(e),name:e.name,size:e.size,location:n}})));n.push(...i)}return n}(n,r),i=async()=>{let n;const r={query:{match:{"content.etag":{$in:t.map((e=>e.hash))}}},select:"id content.etag"};n=s?(await e.store.collections.searchMembers(s,r)).results:(await e.store.objects.search(r)).results;for(const e of n){const n=t.find((t=>t.hash===e.content.etag));n&&(n.existingId=e.id,n.action=zs.SKIP)}},a=async()=>{const n=t.filter((e=>e.action!==zs.SKIP)),r=n.map((e=>e.location)),i=Array.from(new Set(r)),a=[];for(const t of i){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));a.push(t)}else{const t=e.store.objects.find({query:r,select:"id content.name location"});a.push(t)}}const l=(await Promise.all(a)).flat();console.log(`Found ${l.length} document to update`,l);for(const e of l){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=zs.UPDATE)}console.log(`Reconciled ${t.filter((e=>e.action===zs.UPDATE)).length}`)};return await i(),await a(),t.forEach((e=>{e.action||(e.action=zs.CREATE)})),console.log("Document processing check results:",{totalFiles:n.length,toCreate:t.filter((e=>e.action===zs.CREATE)).length,toUpdate:t.filter((e=>e.action===zs.UPDATE)).length,toSkip:t.filter((e=>e.action===zs.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 Us({isOpen:r,onClose:s,files:i,collectionId:a,selectedFolder:d,title:u="Upload Files",children:m,onUploadComplete:h,hideFileSelection:p=!1,showTypeSelectionOnly:f=!1}){const{client:g,typeRegistry:y}=It(),x=v(),[w,N]=o([]),[k,C]=o([]),[_,j]=o(!1),[S,T]=o(null),[P,I]=o([]),[A,E]=o(!1),[$,z]=o(!1),[O,D]=o(0),[U,F]=o(Date.now()),[R,M]=o(void 0),[q,B]=o(null),[W,G]=o(u),[H,J]=o("");c((()=>{a&&g.store.collections.retrieve(a).then(M)}),[a]),c((()=>{A?(G("Uploading Files"),J(`${Math.round(O)}% complete`)):$?(G("Upload Complete"),J("")):_?(G("File Analysis Results"),J(`${w.length} file${1!==w.length?"s":""}`)):w.length>0?(G(u),J("Checking for duplicates and updates")):(G(u),J(""))}),[A,$,_,u,O,w.length]);const K=()=>R||d?t(se,{className:"mb-4",status:"default",icon:e(lt,{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})]}),d&&t("div",{className:"flex items-center mt-1",children:[e("span",{className:"mr-1",children:"Folder:"}),e("span",{className:"font-medium",children:d})]})]})]}):null,[Y,Q]=o({toCreate:0,toUpdate:0,toSkip:0}),{checkDocumentProcessing:X}=Ds(),Z=l((()=>y?.types||[]),[y?.types]);c((()=>{r&&(C([]),j(!1),T(null),I([]),E(!1),z(!1),D(0),Q({toCreate:0,toUpdate:0,toSkip:0}),B(null),G(u),J(""),i&&i.length>0?(N(i),oe(i)):N([]),F(Date.now()))}),[r,i]);const ee=()=>{N([]),C([]),j(!1),T(null),I([]),E(!1),z(!1),D(0),Q({toCreate:0,toUpdate:0,toSkip:0}),B(null),G(u),J(""),F(Date.now()),s()},le=e=>{e&&e.length>0&&(N(e),oe(e))},oe=async e=>{if(e.length)try{console.log(`Processing ${e.length} files to determine required actions...`);const t=await X(e,d,a);C(t);const n=t.filter((e=>e.action===zs.CREATE)).length,r=t.filter((e=>e.action===zs.UPDATE)).length,s=t.filter((e=>e.action===zs.SKIP)).length;Q({toCreate:n,toUpdate:r,toSkip:s}),x({title:"Files analyzed",description:`${e.length} file(s): ${n} new, ${r} to update, ${s} to skip`,status:"info",duration:4e3}),j(!0)}catch(e){console.error("Error processing files:",e),x({title:"Error",description:"There was an error analyzing the files",status:"error",duration:5e3})}},ce=async()=>{if(!k.length)return;const e=S?.id||null,t=k.map((e=>({file:e.file,status:"pending",progress:0,action:e.action===zs.CREATE?"create":e.action===zs.UPDATE?"update":"skip"})));I(t),E(!0),z(!1);const n=k.filter((e=>e.action===zs.SKIP)),r=k.filter((e=>e.action===zs.UPDATE)),s=k.filter((e=>e.action===zs.CREATE)),i={success:!0,objectIds:[],uploadedFiles:[],skippedFiles:[],failedFiles:[]};for(const t of n)t.existingId&&(i.objectIds.push(t.existingId),i.skippedFiles.push({id:t.existingId,name:t.name,type:e,status:"skipped",location:t.location}),I((e=>e.map((e=>e.file===t.file?{...e,status:"success",progress:100,id:t.existingId}:e)))));const l=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 l=r[s];if(console.log(`Processing ${n} batch ${s+1}/${r.length} (${l.length} files)`),t.length>50){x({title:`Processing files (${n})`,description:`Processed ${50*s}/${t.length} files...`,status:"info",duration:2e3})}let o=0;await Promise.all(l.map((async t=>{try{if(I((e=>e.map((e=>e.file===t.file?{...e,status:"uploading",progress:20}:e)))),"update"===n&&t.existingId)await g.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()}),I((e=>e.map((e=>e.file===t.file?{...e,status:"success",progress:100,id:t.existingId}:e)))),i.objectIds.push(t.existingId),i.uploadedFiles.push({id:t.existingId,name:t.name,type:e,status:"updated",location:t.location});else{const n=await g.store.objects.create({type:e||void 0,content:t.file,location:t.location||t.file.webkitRelativePath||t.name},{collection_id:a});I((e=>e.map((e=>e.file===t.file?{...e,status:"success",progress:100,id:n.id}:e)))),i.objectIds.push(n.id),i.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),I((e=>e.map((e=>e.file===t.file?{...e,status:"error",progress:100,message:n.message||"Unknown error"}:e)))),i.failedFiles.push({name:t.name,error:n.message||"Unknown error",status:"failed",location:t.location,type:e}),i.success=!1}o++,o%5!=0&&o!==l.length||I((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 D(r),e}))})))}};r.length>0&&await l(r,"update"),s.length>0&&await l(s,"create"),I((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=>{i.failedFiles.push({name:e.file.name,error:"Upload process interrupted",status:"failed",type:S?.id||null})})),i.success=!1,e.map((e=>"pending"===e.status?{...e,status:"error",progress:100,message:"Upload process interrupted"}:e))):e})),E(!1),z(!0);const o=i.uploadedFiles.filter((e=>"created"===e.status)).length,c=i.uploadedFiles.filter((e=>"updated"===e.status)).length,d=i.skippedFiles.length,u=i.failedFiles.length;let m="";o>0&&(m+=`${o} file${1!==o?"s":""} uploaded`),c>0&&(m+=m?", ":"",m+=`${c} file${1!==c?"s":""} updated`),d>0&&(m+=m?", ":"",m+=`${d} file${1!==d?"s":""} skipped`),u>0&&(m+=m?", ":"",m+=`${u} file${1!==u?"s":""} failed`),x({title:"Upload Complete",description:m,status:u>0?"warning":"success",duration:5e3}),B(i)},de=()=>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(V,{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(Ue,{className:"size-3 ml-2"})})]}),e(ae,{options:Z,value:S,optionLabel:e=>e?e.name:"Select a content type",placeholder:"Select a content type or leave empty for automatic detection",onChange:e=>T(void 0===e?null:e),filterBy:"name",isClearable:!0}),S?e(n,{}):e("div",{className:"p-2 rounded-md",children:t("div",{className:"flex items-center text-attention",children:[e(rt,{className:"size-4 mr-1"}),"Automatic Type Detection",e(V,{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(Ue,{className:"size-3 ml-2"})})]})})]});return t(te,{isOpen:r,onClose:ee,className:"mx-auto",disableCloseOnClickOutside:!0,children:[e(ne,{description:H,children:W}),f?t(re,{children:[m,K(),de()]}):0!==w.length||p?A||$?A?t(re,{children:[K(),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:`${O}%`}})})}),e("div",{className:"max-h-96 overflow-y-auto",children:P.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(it,{className:"size-5 text-muted"}),"uploading"===n.status&&e(L,{size:"sm"}),"success"===n.status&&e(rt,{className:"size-5 text-success"}),"error"===n.status&&e(at,{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(re,{children:t("div",{className:"mb-4",children:[K(),e(Xt,{files:P.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:d||void 0,collection:R?.name})]})}):e(re,{children:_?t(n,{children:[K(),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(nt,{className:"size-5 text-primary"}),e("span",{className:"font-medium",children:"New"})]}),e("div",{className:"text-2xl font-semibold",children:Y.toCreate})]}),t("div",{className:"flex flex-col items-center",children:[t("div",{className:"flex items-center gap-2",children:[e(rt,{className:"size-5 text-success"}),e("span",{className:"font-medium",children:"Update"})]}),e("div",{className:"text-2xl font-semibold",children:Y.toUpdate})]}),t("div",{className:"flex flex-col items-center",children:[t("div",{className:"flex items-center gap-2",children:[e(st,{className:"size-5 text-mixer-attention/40"}),e("span",{className:"font-medium",children:"Skip"})]}),e("div",{className:"text-2xl font-semibold",children:Y.toSkip})]})]})})}),de(),e(se,{className:"mb-4",status:"info",children:Y.toCreate+Y.toUpdate>0?t("div",{className:"space-y-1",children:[t("p",{children:[Y.toCreate+Y.toUpdate," file",Y.toCreate+Y.toUpdate>1?"s are":" is"," ready to process"]}),e("p",{children:Y.toSkip>0&&`${Y.toSkip} file${Y.toSkip>1?"s are":" is"} already in the system and will be skipped.`})]}):Y.toSkip>0?t("span",{children:["All ",Y.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(L,{size:"lg",className:"mb-4"}),e("div",{className:"text-lg font-medium",children:"Analyzing files..."})]})}):t(re,{className:"flex flex-col items-center justify-center p-8",children:[K(),e(Qt,{onDrop:le,message:"Drag and drop files here or click to select",buttonLabel:"Select Files",className:"w-full h-64"}),m]}),(()=>{if(f)return t(ie,{children:[e(b,{variant:"ghost",onClick:ee,children:"Cancel"}),e(b,{onClick:()=>{h&&h({success:!0,objectIds:[],uploadedFiles:[{name:"type-selection",type:S?.id||null,status:"created"}],skippedFiles:[],failedFiles:[]}),ee()},children:S?`Use ${S.name}`:"Use Automatic Type Detection"})]});if(0===w.length&&!p)return e(ie,{children:e(b,{variant:"ghost",onClick:ee,children:"Cancel"})});if(!A&&!$){const n=_;return t(ie,{children:[e(b,{variant:"ghost",onClick:ee,children:"Cancel"}),e(b,{disabled:!n,onClick:ce,children:Y.toCreate+Y.toUpdate>0?"Upload":"Continue"})]})}return A?e(ie,{children:e(b,{variant:"ghost",disabled:!0,children:"Uploading..."})}):t(ie,{children:[e(b,{variant:"ghost",onClick:()=>{N([]),C([]),j(!1),T(null),I([]),E(!1),z(!1),D(0),Q({toCreate:0,toUpdate:0,toSkip:0})},children:"Upload More"}),e(b,{onClick:()=>{h&&q&&h(q),ee()},children:"Close"})]})})()]},U)}function Ls(e){const t="function"==typeof e?e:e.onUploadDone,{client:n,project:r,store:s}=It(),i=Is(),a=v(),{checkDocumentProcessing:l}=Ds();return async(e,o,c)=>{const d={success:!1,objectIds:[],uploadedFiles:[],skippedFiles:[],failedFiles:[]};if(!r)return a({status:"error",title:"No project selected",duration:3e3}),d;if(!e||0===e.length)return a({status:"warning",title:"No files selected",duration:3e3}),d;const u=Array.from(e).filter((e=>e.size>0));if(0===u.length)return a({status:"error",title:"No valid files selected",description:"Please select files with valid content.",duration:5e3}),d;const m=[],h=[],p=[];console.log(`Processing ${u.length} files with smart file processing...`);const f=await l(u,null,c),g=f.filter((e=>e.action===zs.CREATE)).length,v=f.filter((e=>e.action===zs.UPDATE)).length,y=f.filter((e=>e.action===zs.SKIP)).length;a({title:"Files analyzed",description:`${u.length} file(s): ${g} new, ${v} to update, ${y} to skip`,status:"info",duration:4e3});for(const e of f.filter((e=>e.action===zs.SKIP&&e.existingId)))m.push({id:e.existingId,name:e.name,type:o,status:"skipped",location:e.location});const b=f.filter((e=>(e.action===zs.CREATE||e.action===zs.UPDATE)&&e.file));if(b.length>0){console.log(`Processing ${b.length} files (${b.filter((e=>e.action===zs.CREATE)).length} create, ${b.filter((e=>e.action===zs.UPDATE)).length} update)...`);const e=50,t=[];for(let n=0;n<b.length;n+=e)t.push(b.slice(n,n+e));for(let r=0;r<t.length;r++){const i=t[r],l=r*e;console.log(`Processing batch ${r+1}/${t.length} (${i.length} files)`),b.length>e&&a({title:"Processing files",description:`Processed ${l}/${b.length} files...`,status:"info",duration:2e3});const u=await Promise.all(i.map((async e=>{try{if(e.action===zs.UPDATE&&e.existingId){const t=await n.store.objects.update(e.existingId,{type:o||void 0,content:e.file,location:e.location,name:e.name},{createRevision:!0,revisionLabel:"upload on "+(new Date).toISOString()});return h.push({id:e.existingId,name:e.name,type:o,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:o||void 0,content:e.file,location:e.location||e.file.webkitRelativePath||e.name},t);h.push({id:n.id,name:e.name,type:o,status:"created",location:e.location})}}catch(t){console.error(`Failed to process file ${e.name}:`,t),p.push({name:e.name,error:t.message||"Unknown error",status:"failed",location:e.location,type:o}),a({status:"error",title:`Processing failed for ${e.name}`,description:t.message,duration:4e3})}}))),m=h.filter((e=>"created"===e.status)),f=h.filter((e=>"updated"===e.status)),g=h.filter((e=>"failed"===e.status));console.log(`Batch ${r+1} results:`,{creates:m,updates:f,failures:g,total:u.length})}}const x=h.filter((e=>"created"===e.status)).length,w=h.filter((e=>"updated"===e.status)).length,N=h.filter((e=>"failed"===e.status)).length,k=h.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&&a({status:N>0?"warning":"success",title:C,duration:4e3}),i.search(),d}}!function(e){e.CREATE="create",e.SKIP="skip",e.UPDATE="update"}(zs||(zs={}));const Fs=[{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 Rs({isGridView:t=!1,onUpload:n,collectionId:r,...s}){return n?e(Ms,{...s,onUpload:n,isGridView:t,collectionId:r}):e(Vs,{...s,isGridView:t})}function Ms({isGridView:n,onUpload:s,collectionId:i,skipTypeModal:a=!1,...l}){const[c,d]=o(!1),[u,m]=o([]),[h,p]=o(!1),[f,g]=o(null),[y,b]=o(!1),x=Is(),w=v(),{checkDocumentProcessing:N}=Ds(),k=async(e,t)=>{console.log("Files dropped on ObjectTable:",e.length,t),d(!0);try{if(i){const t=await N(e,null,i);g(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;w({title:"Files ready to process",description:`${e.length} file(s): ${n} new, ${r} to update, ${s} to skip`,status:"info",duration:4e3})}else g(null)}catch(e){console.error("Error processing files:",e),w({title:"Error processing files",description:"There was an error checking for duplicate files",status:"error",duration:4e3}),g(null)}finally{if(d(!1),m(e),p(!1),a){console.log("Skipping type modal and calling onUpload directly",{filesLength:e.length,processedFilesLength:f?.length});const t=s(e,null,i);t&&"object"==typeof t&&(t.processedFiles=f)}else console.log("Setting typeSelectionOpen to true",{filesLength:e.length}),b(!0)}},C=e=>{const t=[...u];m([]),g(null),b(!1),t.length>0&&void 0!==e&&(d(!0),console.log("Starting upload with",{typeId:e,filesCount:t.length,hasProcessingResults:!!f,collectionId:i}),s(t,e,i).finally((()=>{d(!1),x.search()})))},_=e=>{e.preventDefault(),e.stopPropagation(),p(!0)};return t("div",{className:"min-h-[400px] relative",onDragOver:_,onDragEnter:_,onDragLeave:e=>{e.preventDefault(),e.stopPropagation(),e.currentTarget.contains(e.relatedTarget)||p(!1)},onDrop:e=>{if(e.preventDefault(),e.stopPropagation(),p(!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"}...`};k(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",c?"block":"hidden"),children:e(L,{size:"xl"})}),e(Vs,{...l,isGridView:n}),e("div",{className:r("absolute inset-0 pointer-events-none",h?"z-40":"-z-10"),children:e("div",{className:"w-full h-full relative",children:e(Qt,{onDrop:k,message:"Drop files or folders here to upload",className:r("absolute inset-0 bg-white/90 dark:bg-gray-800/90 pointer-events-auto",h?"flex":"hidden"),buttonLabel:"Select Files or Folders",allowFolders:!0})})}),e(Us,{isOpen:y&&u.length>0,onClose:()=>{m([]),g(null),b(!1),C(void 0)},files:u,collectionId:i,selectedFolder:null,title:"Upload Files",onUploadComplete:e=>{if(e){if(e.failedFiles&&e.failedFiles.length>0&&w({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)&&w({title:"Upload Complete",description:`${t>0?`${t} created`:""}${t>0&&n>0?", ":""}${n>0?`${n} updated`:""}${r>0?`, ${r} skipped`:""}`,status:"success",duration:5e3})}x.search()}m([]),g(null),b(!1),e&&e.success&&e.objectIds.length>0?C(null):C(void 0)}})]})}function Vs({objects:t,layout:n=Fs,isLoading:r,onRowClick:s,onSelectionChange:i,previewObject:a,selectedObject:o,isGridView:c}){const d=bs(),u=(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);i&&i(d)}},m=e=>{if(d){e.target.checked?d.addAll(t):d.removeAll()}},h=l((()=>(n.length>0?n:Fs).map((e=>new _s(e,a)))),[n,a]);return e(c?Ss:js,{objects:t,isLoading:r,columns:h,onRowClick:s,previewObject:a,selectedObject:o,selection:d,toggleAll:m,onSelectionChange:u})}function qs({children:t,limit:n,parent:r,typeId:s,facets:i,name:a,collectionId:o}){const{store:c}=It(),d=l((()=>{let e;i?e=i:(e=[{name:"status",field:"status"},{name:"location",field:"location"}],s||e.unshift({name:"type",field:"type"}));const t=new Ts(c,n).withFacets(e);return t.collectionId=o,t.query.type=s,t.query.parent=r,t.query.name=a,t}),[s,n,o]);return e(Ps.Provider,{value:d,children:t})}const Bs=[{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 Ws({onChange:t}){return e(qs,{children:e(Hs,{onRowClick:e=>{t(e||void 0)}})})}const Gs="vertesia.content_store.lastDisplayedView";function Hs({onRowClick:n}){const[r,s]=o(!1),[i,a]=o("grid"===localStorage.getItem(Gs)),{search:l,isLoading:d,error:u,objects:h}=Es(),p=m(null);le(p,(()=>{r&&l.loadMore(!0)}),{deps:[r]}),c((()=>{l.search().then((()=>s(!0)))}),[]);const f=As(),g=Is();return u?e(oe,{title:"Search failed",children:u.message}):t("div",{children:[t("div",{className:"flex justify-between items-center mb-4",children:[e(as,{facets:f,search:g}),t("div",{className:"flex items-center gap-2",children:[e(b,{variant:"outline",onClick:()=>{s(!1),l.search().then((()=>s(!0)))},alt:"Refresh",children:e(tt,{size:16})}),e(Zn,{onUpdate:a})]})]}),e(Rs,{objects:h||[],isLoading:!1,layout:Bs,onRowClick:n,isGridView:i}),e("div",{ref:p,className:"mt-10"}),d&&e("div",{className:"flex justify-center",children:e(L,{size:"xl"})})]})}function Js({isOpen:n,onClose:r}){return t(te,{onClose:()=>r(),isOpen:!!n,className:"min-w-[60vw]",children:[e(ne,{children:"Select Content"}),e(re,{className:"pt-0 overflow-y-auto max-h-[80vh] min-h-[80vh]",children:n&&e(Ws,{onChange:r})})]})}const Ks=/store:([a-f0-9]+)/;function Ys({object:n}){const{client:s}=It(),{off:i,on:a,isOn:l}=ce(),[d,u]=o(null!=n.value?String(n.value):""),[m,h]=o(void 0),p=()=>{u(""),n.value="",h(void 0)};return c((()=>{if(!d||m)return;const e=d.match(Ks);e&&s.objects.get(e[1]).then((e=>{h(e)})).catch((()=>{p()}))}),[d]),t("div",{children:[t("div",{className:"relative",children:[e("input",{value:d,onChange:e=>{const t=e.target.value;u(t),n.value=t},className:r(de.INPUT,"pr-10 w-full")}),m&&e("div",{className:"absolute inset-y-0 right-10 flex items-center justify-center ",children:e(b,{onClick:p,variant:"unstyled",className:"hover:text-red-500 hover:bg-gray-100 dark:hover:bg-gray-600",children:e(ot,{className:"size-5"})})}),e("div",{className:"absolute inset-y-0 right-0 flex items-center justify-center",children:e(b,{onClick:a,variant:"unstyled",className:"hover:bg-gray-100 dark:hover:bg-gray-600",children:e(ct,{className:"size-5"})})}),e(Js,{value:d,isOpen:l,onClose:e=>{if(e){const t="store:"+e.id;u(t),h(e||void 0),n.value=t}i()}})]}),m&&e("div",{className:"p-1 semibold text-sm text-gray-600 dark:text-slate-300",children:m.properties?.title||m.name})]})}function Qs(e,t,n,r){return()=>{n&&e.files.getDownloadUrlWithOptions({file:n,name:r}).then((e=>{window.open(e.url,"_blank")})).catch((e=>{t({status:"error",title:"Failed to get download URL",description:e.message,duration:5e3})}))}}function Xs({objectId:n,isOpen:r,onClose:s}){const i=qt(),{client:a,store:l}=It(),[d,u]=o(null),[m,h]=o(!1),[p,f]=o(!1),[g,y]=o(),[x,w]=o(),[N,k]=o("preview"),C=v();c((()=>{n&&r?(h(!0),l.objects.retrieve(n,"+embeddings").then((e=>{u(e),e.text?y(e.text):_(e.id);const t=e.content;t&&t.source&&t.type&&t.type.startsWith("image/")&&j(e)})).catch((e=>{console.error("Error loading object:",e),C({title:"Error",description:"Failed to load document",status:"error",duration:3e3})})).finally((()=>{h(!1)}))):(u(null),y(void 0),w(void 0))}),[n,r,l.objects]);const _=async e=>{f(!0);try{const t=await l.objects.getObjectText(e);y(t.text)}catch(e){console.error("Error loading text:",e)}finally{f(!1)}},j=async e=>{try{"found"===(await a.objects.getRendition(e.id,{format:Ut.jpeg,generate_if_missing:!1})).status&&console.log("Found rendition");const t=await a.files.getDownloadUrl(e.content.source);w(t.url)}catch(e){console.error("Error loading image:",e)}},S=()=>{d&&(i(`/legal/objects/${d.id}`),s())},T=g&&(g.startsWith("#")||g.includes("\n#")||g.includes("\n*")),P=d?.content?.type&&d.content.type.startsWith("image/"),I="application/pdf"===d?.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(dt,{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...":d?.name||"Document Preview"})]}),t("div",{className:"flex items-center space-x-2",children:[t(b,{variant:"ghost",size:"sm",onClick:S,className:"flex items-center gap-1 text-indigo-600 hover:text-indigo-800",children:[e(ut,{className:"h-4 w-4"}),e("span",{children:"Full View"})]}),e(b,{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(ot,{className:"h-5 w-5"})})]})]}),m?e("div",{className:"flex-1 flex items-center justify-center",children:t("div",{className:"text-center",children:[e(L,{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"===N?"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:()=>k("preview"),children:t("div",{className:"flex items-center gap-1",children:[e(Je,{className:"h-4 w-4"}),e("span",{children:"Preview"})]})}),e("button",{className:"py-2 px-4 font-medium border-b-2 "+("properties"===N?"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:()=>k("properties"),children:t("div",{className:"flex items-center gap-1",children:[e(Ue,{className:"h-4 w-4"}),e("span",{children:"Properties"})]})})]})}),t("div",{className:"flex-1 overflow-auto p-4",children:["preview"===N&&t("div",{className:"h-full",children:[p?e("div",{className:"flex items-center justify-center h-40",children:e(L,{size:"md",className:"text-indigo-600 dark:text-indigo-400"})}):g?e("div",{className:"shadow rounded-md p-4 border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800",children:T?e("div",{className:"prose prose-sm max-w-none prose-p:my-2 prose-pre:bg-gray-800 prose-pre:my-2 prose-headings:text-indigo-700 dark:prose-invert dark:prose-headings:text-indigo-300",children:e(Kt,{children:g})}):e("pre",{className:"text-wrap whitespace-pre-wrap dark:text-gray-200",children:g})}):null,P&&e("div",{className:"mt-4",children:e("div",x?{className:"border border-gray-200 dark:border-gray-700 rounded-md p-2 bg-white dark:bg-gray-800",children:e("img",{src:x,alt:d?.name,className:"mx-auto max-h-[70vh] object-contain"})}:{className:"flex items-center justify-center h-40",children:e(L,{size:"md",className:"text-indigo-600 dark:text-indigo-400"})})}),I&&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(dt,{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(b,{onClick:S,className:"bg-indigo-600 hover:bg-indigo-700 text-white",children:"Open Full Document View"})]}),!P&&!g&&!I&&!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(dt,{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"===N&&d&&t("div",{className:"h-full",children:[d.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(Yt,{value:d.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(Ue,{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:d.id}),e("div",{className:"text-gray-500 dark:text-gray-400",children:"Type"}),e("div",{className:"font-medium dark:text-gray-200",children:d.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:d.content?.type||"N/A"}),e("div",{className:"text-gray-500",children:"Size"}),e("div",{className:"font-medium",children:d.content&&"size"in d.content?Zs(d.content.size):"Unknown"}),e("div",{className:"text-gray-500",children:"Created"}),e("div",{className:"font-medium",children:d.created_at?new Date(d.created_at).toLocaleString():"N/A"}),e("div",{className:"text-gray-500",children:"Updated"}),e("div",{className:"font-medium",children:d.updated_at?new Date(d.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:d?.content?.source&&t(b,{onClick:()=>{d?.content?.source&&a.files.getDownloadUrl(d.content.source).then((e=>{window.open(e.url,"_blank")})).catch((e=>{console.error("Error getting download URL:",e),C({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(Xe,{className:"h-4 w-4 mr-2"}),"Download"]})}),t(b,{onClick:S,className:"bg-indigo-600 hover:bg-indigo-700 text-white",children:["Open Full Document",e(mt,{className:"h-4 w-4 ml-2"})]})]})]}):null}function Zs(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 ei=Object.values(Rt),ti=Object.values(Mt);function ni({onChange:n,isLoading:r,refresh:s,searchTypes:i}){const{client:a,project:l}=It(),d=v(),[u,m]=o(void 0),[h,p]=o(void 0),f=!(!l||!h?.embeddings.text&&!h?.embeddings.image),[g,y]=o(void 0),[x,w]=o(!1),[N,k]=o(i||ei),[C,_]=o(100);c((()=>{i&&k(i)}),[i]);const j={};let I=!1,A=!1;N.forEach((e=>{e===Rt.full_text?I=!0:A=!0,ti.includes(e)&&(j[e]=!0)})),c((()=>{m(void 0),y(void 0)}),[s]),c((()=>{l&&a.projects.retrieve(l.id).then((e=>{p(e.configuration)}))}),[l]),c((()=>{g&&d({title:g,status:"success",duration:2e3})}),[g]),c((()=>{u&&0!==u.length||n(void 0)}),[u]);const z=()=>{if(!f||!u)return;n({vector:A?{text:u,config:j}:void 0,full_text:I?u:void 0,limit:C}),y("Searching...")},O=e=>t=>{k(t?t=>Array.from(new Set([...t,e])):t=>t.filter((t=>t!==e)))};return t("div",{className:"flex gap-1 items-center w-1/2",children:[e(E,{placeholder:"Type what you are looking for, or select a filter",value:u,onChange:m,onKeyDown:e=>{"Enter"===e.key&&z()}}),e(b,{variant:"ghost",onClick:()=>w(!0),alt:"Semantic search settings",className:"ml-1",children:e(ht,{size:18})}),t(S,{isOpen:x,onClose:()=>w(!1),children:[e(T,{children:"Search Types"}),e(P,{children:t("div",{className:"flex flex-col gap-2",children:[t("label",{className:"flex items-center gap-2",children:[e(ue,{checked:N.includes(Rt.full_text),onCheckedChange:O(Rt.full_text)}),e("span",{children:"Full Text"})]}),e("div",{className:"font-semibold mt-2 mb-1",children:"Embeddings"}),ti.map((n=>t("label",{className:"flex items-center gap-2",children:[e(ue,{checked:N.includes(n),onCheckedChange:O(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(me,{type:"number",min:1,value:C,onChange:e=>_(Number(e)||1),style:{width:80}})]})]})}),e($,{children:e(b,{variant:"outline",onClick:()=>w(!1),children:"Close"})})]}),e(b,{variant:"secondary",isLoading:r,onClick:z,isDisabled:!f,alt:"Semantic search",children:"Search"})]})}const ri=[{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 si({onUploadDone:t=async()=>{},layout:n}){const r=Is(),s=v(),i=Ls((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(ii,{layout:n,onUpload:(e,t)=>{const n=r.collectionId;return i(e,t,n)}})}function ii({layout:n,onUpload:r,allowFilter:s=!0,allowSearch:i=!0}){const a=Is(),[l,d]=o(!1),[u,h]=o(null),{typeRegistry:p}=It(),{search:f,isLoading:g,error:v,objects:y,hasMore:b}=Es(),[x,w]=o(p?n||function(e,t){const n=t?e.getTypeLayout(t):ri;console.log("[DEBUG] getTableLayout called with type:",t),console.log("[DEBUG] Layout from registry:",n),console.log("[DEBUG] Using defaultLayout?",n===ri);const r=n??ri;return console.log("[DEBUG] Final layout:",r),console.log("[DEBUG] Has Status field?",r.some((e=>"status"===e.field))),r}(p,f.query.type):ri);console.log("[DEBUG] DocumentSearchResults - actualLayout:",x),console.log("[DEBUG] DocumentSearchResults - actualLayout has Status?",x.some((e=>"status"===e.field)));const[N,k]=o(0),[C,_]=o(0),[j,S]=o("grid"===localStorage.getItem(Zn.LAST_DISPLAYED_VIEW)),[T,P]=o([]),I=m(null);c((()=>{l||0!==y.length||(_(0),f._updateRunningState(!0),f.search().then((()=>{d(!0)})).catch((e=>{console.error("Initial search failed:",e),f._updateRunningState(!1)})))}),[]),c((()=>{y.length<C&&_(y.length)}),[y.length,C]),le(I,(()=>{l&&y.length>0&&y.length!=C&&(d(!1),f.loadMore().finally((()=>{_(y.length),d(!0)})))}),{deps:[l,y.length]});const A=As(),E=Is(),$=ss(A),z=is(E),O=new URL(window.location.href),D=O.searchParams.get("filters");if(D)try{const e=D.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(v){console.error("Failed to clean start/end filters from URL:",v)}const U=qt();return t("div",{className:"flex flex-col gap-y-2",children:[e(li,{object:u,onClose:()=>h(null)}),v&&e(oe,{title:"Error",children:v.message}),e(ai,{isLoading:g,refreshTrigger:N,allowFilter:s,allowSearch:i,filterGroups:$,filters:T,handleFilterChange:e=>{const t="function"==typeof e?e(T):e;P(t),z(t)},handleVectorSearch:e=>{if(e&&e.vector){if(f.query.vector=e.vector,f.query.full_text=e.full_text,f.query.weights=e.weights,f.query.score_aggregation=e.score_aggregation,f.query.dynamic_scaling=e.dynamic_scaling,!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)}f.search().then((()=>d(!0)))}else e&&e.full_text?(f.query.full_text=e.full_text,f.search().then((()=>d(!0)))):void 0===e&&l&&(delete f.query.vector,delete f.query.full_text,f.search().then((()=>d(!0))))},handleRefetch:()=>{f.search().then((()=>d(!0)))},setIsGridView:S}),e(Rs,{objects:y,isLoading:!y.length&&g,layout:x,onRowClick:e=>{U(`/objects/${e.id}`)},previewObject:e=>{const t=y.find((t=>t.id===e))||null;h(t)},selectedObject:u,onUpload:r,isGridView:j,collectionId:a.collectionId}),e("div",b?{ref:I,className:"w-full flex justify-center",children:e(L,{size:"xl"})}:{className:"text-muted text-center text-sm py-1",children:`All ${y.length} objects loaded.`})]})}function ai(n){const{isLoading:r,refreshTrigger:s,allowFilter:i,allowSearch:a,filterGroups:l,filters:o,handleFilterChange:c,handleVectorSearch:d,handleRefetch:u,setIsGridView:m}=n;return t("div",{className:"sticky top-0 z-10 bg-background py-2",children:[i&&t(J,{filterGroups:l,filters:o,setFilters:c,children:[t("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:[a&&e(ni,{onChange:d,isLoading:r,refresh:s,className:"w-full"}),e(K,{})]}),t("div",{className:"flex gap-1 items-center",children:[e(b,{variant:"outline",onClick:u,alt:"Refresh",children:e(tt,{size:16})}),e(Zn,{onUpdate:m})]})]}),t("div",{className:"flex gap-2 items-center pt-2",children:[e(Y,{}),e(Q,{})]})]}),!i&&t("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:a&&e(ni,{onChange:d,isLoading:r,refresh:s})}),t("div",{className:"flex gap-1 items-center",children:[e(b,{variant:"outline",onClick:u,alt:"Refresh",children:e(tt,{size:16})}),e(Zn,{onUpdate:m})]})]})]})}function li({object:n,onClose:r}){const{store:s}=It(),i=v(),a=qt(),l=Qs(s,i,n?.content?.source,n?.name||n?.content?.name);return n?t(he,{title:n.properties?.title||n.name,isOpen:!0,onClose:r,children:[t("div",{className:"flex items-center gap-x-2",children:[e(b,{variant:"ghost",size:"sm",title:"Open Object",onClick:()=>a(`/objects/${n.id}`),children:e(We,{className:"size-4"})}),n.content?.source&&e(b,{variant:"ghost",size:"sm",title:"Download",onClick:l,children:e(Xe,{className:"size-4"})})]}),e(pe,{className:"my-2"}),e("div",{className:"pt-2",children:e(ir,{object:n,loadText:!0},n.id)})]}):null}var oi;function ci({isExporting:n,isOpen:r,onClose:s}){return t(S,{onClose:()=>s(void 0),isOpen:r,className:"relative overflow-visible",children:[e(T,{children:"Export Object Properties"}),!n&&e(di,{onClose:s}),n&&e(ui,{})]})}function di({onClose:n}){const[r,s]=o(void 0),[i,a]=o(void 0),l=["Export selected objects","Export all objects"];return t(P,{className:"min-h-[104px] pt-0 flex flex-col gap-y-4",children:[e("div",{className:"h-1/3",children:e(q,{options:l,value:i,onChange:a,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(q,{options:Object.values(oi),value:r,onChange:s,placeholder:"Choose a format",className:"h-full w-full text-sm",filterBy:"name",isClearable:!0}),e(b,{className:"w-full",isDisabled:!r||!i,onClick:()=>{n(r,i==l[1])},children:"Export Properties"})]})]})}function ui({}){return e(P,{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(L,{size:"lg"})]})})}function mi({collection:t}){const n=v(),{client:r,typeRegistry:s}=It();Is().query.all_revisions=!0;const i=function(e,t){let n=e.table_layout;if(n&&n.length>0)return n;e.type&&t&&(n=t?.getTypeLayout(e.type.id));return n&&n.length>0?n:void 0}(t,s);return t.dynamic?e(ii,{layout:i}):e(si,{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:i})}!function(e){e.CSV="CSV",e.JSON="JSON"}(oi||(oi={}));const hi=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 pi({className:t,defaultValue:n,onChange:r,isClearable:s,multiple:i}){const a=It(),[l,d]=o(!1),[u,m]=o(),[h,p]=o([]);c((()=>{if(!l&&(d(!0),a.typeRegistry&&n)){if(i&&Array.isArray(n)){const e=a.typeRegistry.types.filter((e=>n.includes(e.id)));p(e)}const e=a.typeRegistry.types.find((e=>e.id===n));e&&m(e)}}),[a.typeRegistry,n,i]);const f=e=>{p(e),r(e)};return e("div",i?{className:"flex flex-col gap-4 content-between",children:e(ae,{options:a.typeRegistry?.types||[],value:h,onChange:f,placeholder:"Choose Content Types...",optionLabel:hi,className:t||"text-sm bg-background",filterBy:"name",isClearable:s||!1,multiple:!0})}:{className:"flex flex-col gap-4 content-between",children:e(ae,{options:a.typeRegistry?.types||[],value:u,onChange:e=>{m(e||void 0),r(e)},placeholder:"Choose a Content Type...",optionLabel:hi,className:t||"text-sm bg-background",filterBy:"name",isClearable:s||!1})})}function fi({onClose:n,redirect:r=!0,onAddToCollection:s}){const i=qt(),a=v(),[l,c]=o(!1),{client:d}=It(),[u,m]=o({dynamic:!1,name:"",description:""});function h(e,t){m({...u,[e]:t})}return t("form",{onSubmit:e=>e.preventDefault(),children:[t(re,{children:[e(A,{label:"Name",required:!0,children:e(E,{type:"text",value:u.name||"",onChange:e=>h("name",e)})}),e(A,{label:"Description",className:"mt-2",children:e(fe,{value:u.description||"",onChange:e=>h("description",e)})}),e(A,{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(ge,{value:u.dynamic||!1,onChange:e=>h("dynamic",e)})}),!u.dynamic&&e(A,{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(pi,{defaultValue:u.allowed_types||null,onChange:e=>{Array.isArray(e)?h("allowed_types",e.map((e=>e.id))):h("allowed_types",e?[e.id]:[])},isClearable:!0,multiple:!0})}),e(A,{label:"Type",className:"mt-2",description:"Optionally select a content type to assign custom properties and data to the collection.",children:e(pi,{defaultValue:u.type||null,onChange:e=>{Array.isArray(e)?h("type",e.length>0?e[0].id:null):h("type",e?.id||null)},isClearable:!0})})]}),e(ie,{children:e(b,{isDisabled:l,onClick:()=>{u?.name&&u.name.trim()?(u.name=u.name.trim(),u.description&&(u.description=u.description.trim()),null==u.dynamic&&(u.dynamic=!1),c(!0),d.store.collections.create(u).then((e=>{n(),a({title:"Collection created",description:`Collection "${e.name}" created successfully`,status:"success",duration:3e3}),r&&i(`/collections/${e.id}`),s&&s(e.id)})).catch((e=>{a({title:"Failed to create collection",description:e.message,status:"error",duration:5e3})})).finally((()=>c(!1)))):a({title:"Name is required",description:"Please provide a name for the collection",status:"error",duration:5e3})},children:"Create Collection"})})]})}function gi({isOpen:n,onClose:r}){return t(te,{onClose:r,isOpen:n,children:[e(ne,{children:"Create a Collection"}),e(fi,{onClose:r})]})}function vi({}){const{client:r}=It(),s=v(),[i,a]=o(),[l,d]=o(!0),[u,m]=o(!1),{data:h,error:p,refetch:f}=W((()=>r.store.collections.search({})),[]);if(c((()=>{(h||p)&&d(!1)}),[h,p]),p)return e(oe,{title:"Collections fetch failed",children:p.message});return t(n,{children:[h&&(h.length>0?t(H,{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(X,{columns:4,isLoading:l,children:h.map((n=>t(ve,{children:[e("td",{children:t("div",{className:"flex items-center gap-2",children:[yi(n.dynamic),e(Vt,{href:`/collections/${n.id}`,children:n.name})]})}),e("td",{children:n.type?.name||"-"}),e("td",{children:Bt(n.created_at).fromNow()}),e("td",{className:"text-right",children:e(b,{variant:"destructive",size:"sm",onClick:()=>a(n.id),children:e(pt,{className:"size-4"})})})]},n.id)))})]}):e(ye,{title:"No Collections",buttonLabel:"New Collections",onClick:()=>m(!0),children:"Get started by creating a new Collections."})),e(gi,{isOpen:u,onClose:()=>m(!1)}),e(be,{isOpen:!!i,title:"Delete Collection",content:"Are you sure you want to delete this collection? This action cannot be undone.",onConfirm:async()=>{if(i)try{await r.store.collections.delete(i),s({title:"Collection deleted",status:"success",duration:3e3}),f()}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{a(void 0)}},onCancel:()=>a(void 0)})]})}function yi(t){const n=t?"Dynamic Collection":"Static Collection",r=e(t?ft:gt,{className:"size-5"});return e(V,{description:n,className:"mr-2",children:r})}function bi({objects:n,isLoading:r}){const s=qt();return e("div",{children:t(H,{className:"w-full",children:[e("thead",{children:t("tr",{children:[e("th",{children:"Name"}),e("th",{children:"Strict Mode"}),e("th",{children:"Semantic Chunking"}),e("th",{children:"Updated At"})]})}),e(X,{isLoading:r,columns:3,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:Bt(n.updated_at).fromNow()})]},n.id)))})]})})}Bt.extend(dn),Bt.extend(dn);class xi{client;limit;result=new Z({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 wi=d(void 0);function Ni(){return u(wi)}function ki(){const e=Ni();return{...ee(e.result),search:e}}function Ci(){return Ni().objects.length}function _i({title:n,isOpen:r,onClose:s,okLabel:i,initialPayload:a}){const l=v(),[c,d]=o(a?.name),[u,m]=o(a?.description),[h,p]=o(a?.strict_mode??!1);return t(S,{isOpen:r,onClose:()=>s(),children:[e(T,{children:n}),e(P,{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(E,{value:c,onChange:d})]}),t("div",{children:[e("label",{className:"block text-sm font-medium text-muted",children:"Description"}),e(fe,{value:u,onChange:e=>m(e.target.value)})]})]})}),e($,{children:t("div",{className:"flex justify-end gap-4",children:[e(b,{variant:"secondary",onClick:()=>s(),children:"Cancel"}),e(b,{variant:"primary",onClick:()=>(()=>{if(!c)return void l({status:"error",title:"Name is required",duration:5e3});s({name:c,description:u,strict_mode:h}).then((()=>s())),d(void 0),m(void 0),p(!1)})(),children:i})]})})]})}var ji;function Si({isDirty:n=!1}){const r=It(),{store:s}=r,i=v(),[a,l]=o(!1),{search:d,isLoading:u,error:h,objects:p}=ki(),[f,g]=o(""),y=xe(f,500),b=m(null);le(b,(()=>{a&&d.loadMore()}),{deps:[a]}),c((()=>{d.search().then((()=>l(!0)))}),[]),c((()=>{d.query.name=f,d.search().then((()=>l(!0)))}),[y]);const[x,w]=o(void 0);c((()=>{d.query.chunkable=x?"Yes"==x:void 0,d.search().then((()=>l(!0)))}),[x]),c((()=>{n&&a&&d.search().then((()=>l(!0)))}),[n]);const[N,k]=o(!1);if(h)return e(oe,{title:"Failed to fetch ObjectTypes",children:h.message});return t("div",{className:"flex flex-col gap-4 h-full",children:[t("div",{className:"flex gap-4",children:[e(E,{placeholder:"Filter by Name",value:f,onChange:g}),e(q,{className:"w-60",isClearable:!0,options:Object.values(ji),value:x,onChange:e=>{w(e)},placeholder:"Is Chunkable"})]}),t("div",{className:"flex-1",children:[u||0!==p?.length?e(bi,{objects:p,isLoading:u}):e(ye,{title:"No Type",buttonLabel:"Create Type",onClick:()=>{k(!0)},children:"Get started by creating a new Type."}),e(_i,{okLabel:"Create",title:"Create Type",isOpen:N,onClose:async e=>e?s.types.create(e).then((async()=>{i({status:"success",title:"Type created",duration:2e3}),r.reloadTypes(),d.search().then((()=>l(!0)))})).catch((e=>{i({status:"error",title:"Error creating type",description:e.message,duration:5e3})})):(k(!1),Promise.resolve())})]})]})}!function(e){e.true="Yes",e.false="No"}(ji||(ji={}));const Ti=[gn,mn()];function Pi({objectType:n,onSchemaUpdate:r}){const{store:s}=It(),i=v(),[a,c]=o(!1),d=Zt(n.object_schema),u=m(void 0),[h,p]=o(!1),f=l((()=>function(e){if(!e)return"";return JSON.stringify(e,null,2)}(d.schema)),[d]),g=()=>{if(u.current){const e=u.current.getValue();try{const t=function(e){if(!e?.trim())return;return JSON.parse(e.trim())}(e);Ii(t),d.replaceSchema(t)}catch(e){return i({status:"error",title:"Invalid JSON Schema",description:e.message,duration:5e3}),!1}}return!0};return t("div",{className:"mx-2 my-2 rounded-2xl border border-solid shadow-md border-spacing-2",children:[t("div",{className:"flex items-center rounded-t-md border-b gap-x-2 py-2 pl-4 pr-2",children:[e("div",{className:"text-base font-semibold",children:"Schema Editor"}),e("div",{children:e(b,{variant:"outline",size:"sm",onClick:()=>{h&&!g()||p((e=>!e))},children:h?"Edit Schema":"Edit Json"})}),e("div",{className:"ml-auto flex gap-x-2",children:e(b,{isLoading:a,variant:"outline",size:"sm",onClick:()=>{h&&!g()||(c(!0),s.types.update(n.id,{object_schema:d.schema}).then((()=>{r(d),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((()=>{c(!1)})))},children:"Save Changes"})})]}),e("div",{className:"px-4 py-2",children:h?e(en,{value:f,extensions:Ti,editorRef:u}):e(tn,{schema:d})})]})}const Ii=e=>{try{new Jt({strict:!1}).compile(e)}catch(e){throw new Error(`Invalid JSON Schema definition: ${e.message}`)}};function Ai({children:t,limit:n,name:r,chunkable:s}){const{store:i}=It(),a=l((()=>{const e=new xi(i,n);return e.query.name=r,e.query.chunkable=s,e}),[n]);return e(wi.Provider,{value:a,children:t})}function Ei({isOpen:n,onClose:r,title:s="Select Content Type",children:i,initialSelectedType:a=null,confirmLabel:l="Select Type",allowNone:c=!0}){const{typeRegistry:d}=It(),[u,m]=o(a),h=d?.types||[],p=()=>{r(void 0)};return t(S,{isOpen:n,onClose:p,className:"w-full max-w-xl mx-auto",children:[e(T,{children:s}),t(P,{className:"p-6",children:[i,t("div",{className:"mb-4 mt-4",children:[t("label",{className:"block text-sm font-medium mb-2",children:["Content Type ",c&&e("span",{className:"text-gray-500 font-normal",children:"(Optional)"})]}),e(q,c?{options:h,value:u,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:h,value:u,optionLabel:e=>e?e.name:"Select a content type",placeholder:"Select a content type",onChange:e=>m(e||null),filterBy:"name"}),c&&t("div",{className:"mt-2 text-sm text-blue-600 flex items-center",children:[e(rt,{className:"h-4 w-4 mr-1"}),t("span",{children:[e("strong",{children:"Type selection is optional."})," Leave empty to let Vertesia choose the appropriate type"]})]})]}),u?t("div",{className:"text-sm text-gray-500 bg-gray-50 p-3 rounded-md mb-4",children:[e("div",{className:"font-medium",children:u.name}),u.description&&e("div",{className:"mt-1",children:u.description})]}):c&&t("div",{className:"text-sm text-blue-600 bg-blue-50 p-3 rounded-md mb-4",children:[e("div",{className:"font-medium",children:"Automatic Type Detection"}),t("div",{className:"mt-1",children:["Vertesia will analyze each file's content and automatically select the most appropriate type.",e("br",{}),e("span",{className:"mt-1 block font-medium",children:"This is recommended for most uploads."})]})]})]}),t($,{children:[e(b,{variant:"ghost",onClick:p,children:"Cancel"}),e(b,{onClick:()=>{r(u?.id??null)},children:u?`${l}: ${u.name}`:c?"Let Vertesia Choose":l})]})]})}const $i=[gn,mn()];function zi({objectType:n,onLayoutUpdate:r}){const s=v(),[i,a]=o(!1),{store:c}=It(),d=m(void 0),u=l((()=>Oi(n.table_layout)),[n.table_layout]),h=(e,t)=>{s({status:"error",title:e,description:t,duration:5e3})};return t("div",{className:"mx-2 my-2 rounded-2xl border border-solid shadow-xs",children:[t("div",{className:"flex items-center rounded-t-md border-b gap-x-2 py-2 pl-4 pr-2",children:[e("div",{className:"text-base font-semibold ",children:"Table Layout Editor"}),e("div",{className:"ml-auto flex gap-x-2",children:e(b,{isLoading:i,variant:"outline",size:"sm",onClick:()=>{if(!d.current)return;const e=d.current.getValue();let t;if(e)try{t=JSON.parse(e)}catch(e){return h("Invalid JSON",e.message)}else t=null;return Array.isArray(t)?t.some((e=>!e||!e.name||!e.field))?h("Invalid JSON","A table layout entry must contain the following properties:] {field, name, converter?}"):(a(!0),void c.types.update(n.id,{table_layout:t}).then((e=>{s({status:"success",title:"Table Layout updated",description:"The table layout has been updated successfully",duration:2e3}),r(e.table_layout)})).catch((e=>{s({status:"error",title:"Failed to update table layout",description:e.message,duration:5e3})})).finally((()=>{a(!1)}))):h("Invalid JSON","The table layout must be an array")},children:"Save Changes"})})]}),e("div",{className:"px-4 py-2",children:e(en,{value:u,extensions:$i,editorRef:d})})]})}function Oi(e){return e?JSON.stringify(e,null,2):"[\n\n]"}const Di=[gn,mn()];function Ui({refetch:r,collection:s}){const i=s.type?.id,a=m(void 0),c=v(),{client:d}=It(),[u,h]=o(!1),[p,f]=o({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||[]}),g=l((()=>Oi(s.table_layout)),[s.table_layout]),y=(e,t)=>{f({...p,[e]:t})};return t("div",{className:"flex flex-col gap-4 py-2",children:[t(we,{title:"Configuration",action:e(b,{size:"lg",isDisabled:u,onClick:()=>{let e;try{e=p.query?JSON.parse(p.query):void 0}catch(e){return void c({title:"Invalid Query JSON",description:e.message,status:"error",duration:5e3})}const t={name:p.name,description:p.description,query:e,tags:p.tags,type:p.type,allowed_types:p.allowed_types};let n;if(t.name||(n="Name is required"),t.type||(t.type=null),n)c({title:"Validation failed",description:n,status:"error",duration:5e3});else{if(a.current){const e=a.current.getValue();if(e)try{t.table_layout=JSON.parse(e)}catch(e){return void c({title:"Invalid Table Layout",description:e.message,status:"error",duration:5e3})}else t.table_layout=null}h(!0),d.store.collections.update(s.id,t).then((()=>{r(),c({title:"Collection updated",description:"Collection has been updated successfully",status:"success",duration:3e3})})).catch((e=>{c({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(hn,{userRef:s.created_by,showTitle:!0}),t("span",{children:["at ",Bt(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(hn,{userRef:s.updated_by,showTitle:!0}),t("span",{children:["at ",Bt(s.updated_at).format("YYYY-MM-DD HH:mm:ss")]})]})]})]}),e(A,{label:"Name",required:!0,children:e(E,{value:p.name,onChange:e=>y("name",e)})}),e(A,{label:"Description",children:e(fe,{value:p.description,onChange:e=>y("description",e)})}),!s.dynamic&&e(A,{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(pi,{defaultValue:p.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(A,{label:"Query",description:"Define the query to dynamically fetch content for the collection.",children:e(fe,{className:de.INPUT,value:p.query,onChange:e=>y("query",e)})}),e(A,{label:"Table Layout",description:"Define a custom layout for displaying the collection in tables.",children:e(en,{className:"border-1 rounded-md border-border",value:g,extensions:Di,editorRef:a})}),e(A,{label:"Type",description:"Select a content type to assign custom properties and data to the collection.",children:e(pi,{defaultValue:p.type||null,onChange:e=>{Array.isArray(e)?y("type",e.length>0?e[0].id:null):y("type",e?.id||null)},isClearable:!0})})]}),i&&e(Li,{typeId:i,collection:s}),!s.dynamic&&t(n,{children:[e(pn,{collection:s}),e(fn,{collection:s})]})]})}function Li({typeId:t,collection:n}){const[r,s]=o({}),i=v(),{client:a}=It(),[c,d]=o(!1),{data:u,error:m}=W((()=>a.store.types.retrieve(t)),[t]),h=u?.object_schema||{},p=l((()=>new nn(h,n.properties||{})),[h,n.properties]);if(m)return e(oe,{title:"Failed to load type",children:m.message});if(!u)return null;return e(we,{title:"Properties",action:e(b,{size:"lg",isLoading:c,type:"submit",onClick:()=>(e=>{if(!e||!Object.keys(e).length)return;const t={properties:e||{}};d(!0),a.store.collections.update(n.id,t).then((()=>{i({title:"Collection properties updated",description:"Collection has been updated successfully",status:"success",duration:3e3})})).catch((e=>{i({title:"Failed to update collection properties",description:e.message,status:"error",duration:5e3})})).finally((()=>{d(!1)}))})(r),children:"Save"}),children:e(rn,{object:p,onChange:e=>{e instanceof nn&&s(e.value)}})})}function Fi({onChange:n,value:r,disabled:s=!1,placeholder:i="Select a collection",searchPlaceholder:a="Search collections",filterOut:c,allowDynamic:d=!0,multiple:u=!1}){const{client:m}=It(),[h,f]=o(""),[v,y]=o(!1),[C,S]=o(!1),T=xe(h,300),P=p((async e=>{y(!0);const t=e.trim(),n=await m.store.collections.search({dynamic:!!d&&void 0,name:C&&t||void 0});return y(!1),!C&&n.length>=1e3&&S(!0),c&&c.length>0?n.filter((e=>!c.includes(e.id))):n}),[m,d,c,C]),{data:I,error:A}=W((()=>P(C?T:"")),[C?T:"",P]),E=l((()=>I?u&&Array.isArray(r)?I.filter((e=>r.includes(e.id))):u||"string"!=typeof r?u?[]:void 0:I.find((e=>e.id===r)):u?[]:void 0),[I,r,u]),$=p((e=>{if(u){const t=Array.isArray(r)?r:[];if(t.includes(e.id)){const r=t.filter((t=>t!==e.id)),s=I?.filter((e=>r.includes(e.id)))||[];n(r,s)}else{const r=[...t,e.id],s=I?.filter((e=>r.includes(e.id)))||[];n(r,s)}}else n(e.id,e)}),[n,r,I,u]),z=p((()=>{n(void 0,void 0)}),[n]),O=p((e=>{f(e)}),[]),D=h.trim().length>0,U=l((()=>{if(!I)return[];if(C)return I;if(!D)return I;const e=h.toLowerCase();return I.filter((t=>t.name.toLowerCase().includes(e)))}),[I,C,D,h]),L=E&&D;if(A)return e(oe,{title:"Collection fetch failed",children:A.message});return t(x,{children:[e(w,{asChild:!0,children:t(b,{variant:"outline",role:"combobox","aria-haspopup":"listbox",className:g("w-full justify-between min-w-0"),disabled:s,children:[e("span",{className:"truncate flex-1 text-left min-w-0",children:u&&Array.isArray(E)&&E.length>0?1===E.length?E[0].name:`${E.length} collections selected`:u||!E||Array.isArray(E)?i:E.name}),e(ct,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e(N,{className:"mt-2 mb-2 w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:t(k,{shouldFilter:!1,children:[t("div",{className:"flex justify-between items-center border-b px-3","cmdk-input-wrapper":"",children:[e(Ne,{placeholder:a,value:h,onValueChange:O,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"}),v&&e("div",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"})]}),e(ke,{children:v?"Searching...":D?"No collections found.":"No collections available."}),t(_,{className:"max-h-[300px] overflow-auto",children:[L&&!u&&e(j,{value:"__clear__",onSelect:z,className:"text-muted-foreground",children:"Clear selection"}),U.map((n=>{const s=u&&Array.isArray(r)?r.includes(n.id):r===n.id;return t(j,{value:n.id,onSelect:()=>$(n),className:"flex items-center justify-between",children:[e("span",{className:"truncate",children:n.name}),s&&e(vt,{className:"ml-2 h-4 w-4 shrink-0"})]},n.id)}))]})]})})]})}function Ri({collection:t}){const{client:n}=It(),[r,s]=o(void 0),[i,a]=o(t.shared_properties||[]),l=v();c((()=>{t.type?.id&&n.store.types.retrieve(t.type.id).then(s)}),[t.type?.id]);const d=r?Object.keys(r.object_schema?.properties||{}):[];return e(we,{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(b,{size:"lg",isLoading:!1,onClick:()=>{n.store.collections.update(t.id,{shared_properties:i}).then((()=>{l({title:"Updated shared properties",status:"success"})})).catch((e=>{l({title:"Failed to update shared properties",description:e.message,status:"error"})}))},children:"Save"}),children:e("div",{className:"",children:e(Ce,{value:i,onChange:e=>{a(e)},options:d,placeholder:"Select properties to share"})})})}function Mi({collection:t}){const{client:n}=It(),[r,s]=o(t.skip_head_sync??!1),[i,a]=o(!1),l=v();return e(we,{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(ge,{disabled:i,value:!r,onChange:e=>{const r=!e;a(!0),n.store.collections.update(t.id,{skip_head_sync:r}).then((()=>{l({title:"Updated skip head sync setting",status:"success"}),s(r)})).catch((e=>{l({title:"Failed to update skip head sync",description:e.message,status:"error"})})).finally((()=>{a(!1)}))},children:"Enable synchronizing member heads"})})}function Vi({action:n,objectIds:r,children:s}){const{store:i}=It(),a=v(),[l,c]=o(!1),d=p((()=>(c(!0),Promise.resolve(!0))),[]);oa(n.id,d);return t("div",{children:[s,e(Ei,{isOpen:l,onClose:e=>{c(!1),void 0!==e&&i.runOperation({name:"change_type",ids:r,params:{typeId:e}}).then((e=>{a({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=>{a({status:"error",title:"Error changing type",description:e.message,duration:5e3})}))},title:"Change Content Type",confirmLabel:"Change Type",children:t("div",{className:"text-sm flex flex-col gap-x-2",children:[t("p",{children:["Choose a new Content Type for the selected object",r.length>1?"s":" ","or let the system choose or generate a type based on the content."]}),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 qi={id:"changeType",name:"Change Content Type",description:"Change the Content Type of the selected documents",confirm:!1,component:Vi};function Bi({action:r,callback:s,children:i}){const[a,l]=o(!1),c=r.confirmationText||`Are you sure you want to ${r.name}?`,d=p((e=>r.confirm?(l(!0),Promise.resolve(!0)):s(e)),[r.confirm,s]),u=oa(r.id,d);return t(n,{children:[i,e(be,{onConfirm:()=>{l(!1),s({...u.params,action:r})},onCancel:()=>l(!1),title:"Are you sure?",content:c,isOpen:a})]})}function Wi({action:t,objectIds:n,children:r}){const s=la(),i=v(),{client:a}=It(),l=Is(),o=qt(),c=p((()=>{if(!n||!n.length)return i({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=>a.store.objects.delete(e)))).then((t=>{const r=t.length>1?"s":"";if(i({status:"success",title:`${t.length} object${r} deleted`,description:`Objects ${e(t.map((e=>e.id)).join(", "),100)} have been deleted`,duration:2e3}),l){s.params?.selection?.removeAll();const e=JSON.parse(JSON.stringify(l.facets));n.length===e._value.total&&l.resetFacets(),l.search()}else o("/objects")})).catch((e=>{i({status:"error",title:"Error deleting objects",description:e.message,duration:5e3})}))}),[n]);return e(Bi,{action:t,callback:c,children:r})}const Gi={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:Wi,destructive:!0},Hi={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:Wi,destructive:!0};function Ji({action:t,objectIds:n}){const{store:r}=It(),s=v(),[i,a]=o(!1),[l,c]=o(!1),d=p((()=>(a(!0),Promise.resolve(!0))),[]),u=oa(t.id,d);return e("div",{children:e(ci,{isExporting:l,isOpen:i,onClose:(e,t)=>{if(e&&(t||n.length>0)){c(!0);const i=u.params?.search?.query||{},l=u.params?.search?.result?.value?.objects?.map((e=>e.id))||void 0,o=async e=>r.objects.list({query:{parent:e}}).then((e=>e.map((e=>e.id))));(async()=>t?l?i.vector?l:[]:0===n.length?[]:(await o(n[0])).concat(n):n)().then((l=>{r.objects.exportProperties({objectIds:l,type:e,query:t&&!i.vector?i:{type:i.type}}).then((r=>{let i;if(e===oi.CSV)i=new Blob([r.data],{type:r.type});else if(e===oi.JSON)i=new Blob([JSON.stringify(r.data)],{type:r.type});else{const e=r.data;i=new Blob([new Uint8Array(e.data)],{type:r.type})}const a=window.URL.createObjectURL(i),l=document.createElement("a");l.download=r.name,l.href=a,l.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((()=>{c(!1),a(!1)}))}))}else a(!1)}})})}const Ki={id:"exportProperties",name:"Export Properties",description:"Export all Object Properties",confirm:!1,component:Ji};function Yi({action:t,objectIds:n,collectionId:r}){const s=la(),i=v(),{client:a}=It(),l=Is(),o=p((()=>n&&n.length?r?a.store.collections.deleteMembers(r,n).then((()=>{const e=n.length>1?"s":"";i({status:"success",title:`${n.length} object${e} removed from collection`,description:"Objects have been removed from the collection",duration:2e3}),l&&(s.params?.selection?.removeAll(),l.search())})).catch((e=>{i({status:"error",title:"Error removing objects from collection",description:e.message,duration:5e3})})):(i({status:"error",title:"No collection context",description:"Cannot remove objects: no collection specified",duration:3e3}),Promise.resolve(!1)):(i({status:"error",title:"No objects selected",description:"Please select objects to remove from collection",duration:3e3}),Promise.resolve(!1))),[n,r]);return e(Bi,{action:t,callback:o})}const Qi={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:Yi,destructive:!0};function Xi({action:t,objectIds:n,collectionId:r}){const s=v(),{client:i}=It(),[a,l]=o(!1),c=p((()=>(l(!0),Promise.resolve(!0))),[]);return oa(t.id,c),e(ea,{isOpen:a,onClose:e=>{if(l(!1),e)return i.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 Zi={id:"startWorkflow",name:"Start Workflow",description:"Start an workflow on the selected objects",confirm:!1,hideInList:!0,component:Xi};function ea({isOpen:n,onClose:r}){return t(te,{onClose:()=>r(void 0),isOpen:n,className:"",children:[e(ne,{children:"Start a Workflow by Rule"}),e(na,{onClose:r})]})}function ta(n){return{label:t("div",{children:[e("div",{children:n.name}),e("div",{className:"text-sm text-muted",children:n.description})]}),reverse:!0}}function na({onClose:n}){const[r,s]=o(void 0),i=la();return t("div",{children:[t(re,{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(_e,{options:i.wfRules,optionLayout:ta,onChange:e=>{s(e)},value:r})})]}),t(ie,{children:[e(b,{variant:"secondary",onClick:()=>n(),children:"Cancel"}),e(b,{onClick:()=>{r&&n(r.id)},isDisabled:!r,children:"Start"})]})]})}class ra{params;allActions=[Ki,qi,Zi,ua,Gi,Qi,Hi];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:Xi}))).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 sa=d(void 0);function ia({children:n}){const r=ys(),s=v(),{client:i}=It(),a=Is(),{data:o,error:c}=W((()=>i.workflows.rules.list().then((e=>e.map((e=>({id:e.id,name:e.name,description:e.description,confirm:!1,isWorkflow:!0,component:Xi}))).sort(((e,t)=>e.name.localeCompare(t.name)))))),[]),d=l((()=>{const e=new ra({selection:r,toast:s,client:i,search:a});return e.wfRules=o,e}),[r,o]);return c?e(oe,{title:"Failed to fetch workflows",children:c.message}):d&&t(sa.Provider,{value:d,children:[e(aa,{}),n]})}function aa({}){const t=la(),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 la(){const e=u(sa);if(!e)throw new Error("You cannot use useActionContext outside an ActionProvider");return e}function oa(e,t){const n=la();return c((()=>n.registerCallback(e,t)),[n,e,t]),n}function ca(e){const t=la();return c((()=>(t.startWorkflow=e,()=>{t.startWorkflow=void 0})),[e,t]),t}function da({action:t,objectIds:n}){const[r,s]=o(!1),i=p((()=>(n.length>0&&s(!0),Promise.resolve(!0))),[n]);return oa(t.id,i),r&&e(je,{children:e(ma,{objectIds:n,isOpen:r,onClose:()=>{s(!1)}})})}const ua={id:"addToCollection",name:"Add to Collection",description:"Add documents to a collection",confirm:!1,component:da};function ma({isOpen:n,onClose:r,objectIds:s}){return t(te,{isOpen:n,onClose:r,className:"max-w-lg w-full min-w-0 overflow-hidden",children:[e(ne,{className:"flex flex-col min-w-0 overflow-hidden",children:"Add to a Collection"}),e(Se,{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(ha,{onClose:r,objectIds:s})})]})}function ha({onClose:n,objectIds:r}){const s=v(),{client:i}=It(),[a,l]=o(),c=({collectionId:e})=>{e&&r?.length&&i.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(Te,{level:5,children:"Choose from existing collections"}),e(re,{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(Fi,{onChange:(e,t)=>{"string"==typeof e||void 0===e?l(e):Array.isArray(e)&&e.length>0?l(e[0]):l(void 0)},value:a})})}),e(ie,{children:e(b,{isDisabled:!a,onClick:()=>a&&c({collectionId:a}),children:"Add to Collection"})})]})},{name:"create",label:"Create new",content:e("div",{className:"p-4",children:e(fi,{onClose:n,onAddToCollection:e=>c({collectionId:e}),redirect:!1})})}];return t(Pe,{defaultValue:"select",tabs:d,fullWidth:!0,children:[e(Ie,{}),e(Ae,{})]})}function pa(){const n=ys(),r=n.size(),s=r>1?"s":"",i=n?.hasSelection(),a=n?.isSingleSelection();return e(ia,{children:t("div",{className:"flex items-center gap-x-2",children:[i&&!a&&t("div",{className:"flex items-center gap-x-1 shrink-0",children:[t("div",{className:"text-sm nowrap",children:[r," document",s," selected"]}),e(b,{title:"Clear selection",variant:"ghost",onClick:()=>{n?.removeAll()},children:e(ot,{className:"size-4"})})]}),e(ba,{selection:n,children:e(b,{variant:"ghost",alt:"More action",size:"sm",children:e(yt,{size:16})})}),i&&e(fa,{selection:n})]})})}function fa({}){return e(va,{})}function ga({collectionId:r}){const[s,i]=o([]),a=ys(),l=a?.hasSelection();return!l&&t(n,{children:[e(b,{onClick:()=>(()=>{const e=document.createElement("input");e.type="file",e.multiple=!0,e.accept="*",e?.click(),e.onchange=e=>{const t=e.target.files;t&&i(Array.from(t))}})(),children:"Upload"}),e(Us,{collectionId:r??"",isOpen:s.length>0,onClose:()=>i([]),files:s,title:"Upload Files",onUploadComplete:e=>{e&&e.success&&i([])},children:e("div",{className:"text-sm",children:"Select the associated Content Type, or let the system choose or generate the type based on the content."})})]})}function va(){const t=la();return t.params.selection.hasSelection()&&e(b,{onClick:()=>t.run(Zi.id),children:"Start Workflow"})}function ya(e){return{label:e.name,className:r("flex-1 px-2 py-2 hover:bg-accent nowrap",e.destructive?"text-destructive":"")}}function ba({selection:n,children:r}){const s=la();return t(x,{hover:!0,children:[e(w,{children:r}),e(N,{className:"p-0 w-50",align:"end",sideOffset:6,children:e(xa,{executeAction:e=>{s.run(e.id)},selection:n})})]})}function xa({executeAction:t,selection:n}){const r=la(),s=n?.hasSelection()?r.actions.filter((e=>!e.hideInList)):[Ki];return e("div",{className:"rounded-md shadow-md py-2",children:e("div",{className:"px-1 text-sm",children:e(_e,{options:s,optionLayout:ya,onChange:e=>{t(e)},noCheck:!0})})})}function wa({value:n,onChange:r,onSend:s,disabled:i=!1,isSending:a=!1,isCompleted:l=!1,activeTaskCount:d=0,placeholder:u="Type your message..."}){const h=m(null),[p,f]=o(!1);c((()=>{!i&&l&&h.current?.focus()}),[i,l]);return t("div",{className:"p-3 border-t border-muted flex-shrink-0",style:{minHeight:"90px"},children:[t("div",{className:"flex items-center space-x-2",children:[t("div",{className:"flex flex-1 space-x-1",children:[e(E,{ref:h,value:n,onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),s())},onChange:r,disabled:i||a,placeholder:u,className:"pr-12 py-2.5"}),e(b,{variant:"ghost",className:"rounded-full",disabled:!l,onClick:()=>f(!0),alt:"Link Object",children:e(bt,{className:"size-4"})})]}),t(b,{onClick:s,disabled:i||a||!n.trim(),className:"px-4 py-2.5",children:[a?e(L,{size:"sm",className:"mr-2"}):e(xt,{className:"size-4 mr-2"})," 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(wt,{className:"h-3 w-3 mr-1 text-attention"}),t("span",{children:["Agent has ",d," active workstream",1!==d?"s":""," running"]})]}):i?"Agent is processing, you can continue once it completes...":"You can send a message at any time"}),t(te,{isOpen:p,onClose:()=>f(!1),className:"min-w-[60vw]",children:[e(ne,{children:"Link Object"}),e(re,{className:"pb-6",children:e(Ws,{onChange:e=>{const t=`[${e.properties?.title||e.name||"Object"}](store:${e.id})`,s=n||"",i=h.current?.selectionStart||s.length,a=s.substring(0,i)+t+s.substring(i);r(a),f(!1),setTimeout((()=>{if(h.current){h.current.focus();const e=i+t.length;h.current.setSelectionRange(e,e)}}),100)}})})]})]})}function Na({plan:r,workstreamStatus:s,isOpen:i,onClose:a,plans:l=[],activePlanIndex:o=0,onChangePlan:c=()=>{}}){return i?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(b,{variant:"ghost",onClick:a,children:[e(ot,{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 i=r.plan||[],a=i.length;let l=0;a>0&&i.forEach((e=>{if(e&&e.id){const t=e.id.toString();"completed"===s.get(t)&&l++}}));const o=a>0?Math.round(l/a*100):0;return t(n,{children:[e("div",{className:"w-full bg-muted rounded-full h-2",children:e("div",{className:"bg-background h-2 rounded-full",style:{width:`${o}%`}})}),e("span",{className:"text-xs text-muted",children:a>0?`${l}/${a}`:"0/0"})]})})()})]}),l.length>1&&t("div",{className:"mb-3 flex items-center justify-between",children:[e(b,{variant:"ghost",onClick:()=>c(Math.min(l.length-1,o+1)),disabled:o>=l.length-1,children:"Older Plan"}),e("div",{className:"text-xs text-muted",children:l[o]?.timestamp?new Date(l[o].timestamp).toLocaleTimeString():"Unknown time"}),e(b,{variant:"ghost",onClick:()=>c(Math.max(0,o-1)),disabled:o<=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 i=n.id?n.id.toString():`task-${r}`,a=n.goal||`Task ${r+1}`;let l=n.status||"pending";s.has(i)&&(l=s.get(i));let o=Nt,c="text-muted";return"in_progress"===l?(o=Me,c="text-info"):"completed"===l&&(o=Re,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:i}),t("div",{className:"w-full",children:[e("div",{className:"text-sm font-medium mb-2 text-muted",children:a}),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(o,{className:"size-3.5"})}),e(y,{variant:"completed"===l?"success":"in_progress"===l?"info":"default",children:"completed"===l?"Completed":"in_progress"===l?"In Progress":"Pending"})]})]})]},r)})):t("div",{className:"p-3 text-center text-muted italic",children:[e(Le,{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()))),i=Array.from(s.entries()).filter((([e])=>"main"!==e&&!n.has(e)));return i.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:i.map((([n,r])=>{let s=Nt,i="text-gray-400",a="bg-gray-100 dark:bg-gray-800",l="Pending";return"in_progress"===r?(s=Me,i="text-info",a="bg-info/20",l="In Progress"):"completed"===r&&(s=Re,i="text-success",a="bg-success/20",l="Completed"),t("div",{className:`flex items-center p-1.5 rounded ${a}`,children:[e("div",{className:`mr-1.5 ${i}`,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:l})]},n)}))})})]}):null})()]})]}):null}function ka(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(ja,{...t,run:r})}return r?e(_a,{...t}):e(Ca,{})}function Ca(){return t(se,{status:"info",icon:e(Oe,{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 _a({initialMessage:n,startWorkflow:r,onClose:s,isModal:i=!1,placeholder:a="Type your message...",startButtonText:l="Start Agent",title:d="Start New Conversation"}){const[u,h]=o(""),[p,f]=o(!1),[g,y]=o(),x=v(),w=m(null);c((()=>{w.current&&w.current.focus()}),[]);const N=async()=>{if(!r)return;const e=u.trim();if(e&&!p){f(!0);try{sessionStorage.removeItem("plan-panel-shown"),x({title:"Starting agent...",status:"info",duration:3e3});const t=await r(e);t&&(y({runId:t.run_id,workflowId:t.workflow_id}),h(""),x({title:"Agent started",status:"success",duration:3e3}))}catch(e){x({title:"Error starting workflow",status:"error",duration:3e3,description:e instanceof Error?e.message:"Unknown error"})}finally{f(!1)}}};return g?e(ja,{onClose:s,isModal:i,initialMessage:n,placeholder:a,run:g,title:d}):t("div",{className:"flex flex-col h-full bg-white dark:bg-gray-900 overflow-hidden border-0",children:[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(kt,{className:"size-3.5 text-muted"})}),e("span",{className:"font-medium text-sm text-gray-700 dark:text-gray-300",children:d})]}),s&&!i&&e(b,{size:"xs",variant:"ghost",onClick:s,title:"Close",className:"text-slate-500 hover:text-slate-700",children:e(qe,{className:"size-4"})})]}),t("div",{className:"flex-1 overflow-y-auto px-4 py-6 bg-white dark:bg-gray-900 flex flex-col 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 max-w-md",children:n}),t("div",{className:"bg-white dark:bg-slate-800 p-4 max-w-md border-l-2 border-blue-400 dark:border-blue-500",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:[t("div",{className:"flex items-center gap-2",children:[e("div",{className:"flex-1",children:e("input",{ref:w,value:u,onChange:e=>h(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),N())},placeholder:a,disabled:p,className:"w-full py-2 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:ring-0 rounded-md"})}),t(b,{onClick:N,disabled:!u.trim()||p,className:"px-3 py-2 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:[p?e(L,{size:"sm",className:"mr-1.5"}):e(xt,{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:"Type a message to start the conversation"})]})]})}function ja({run:n,title:r,interactive:s=!0,onClose:i,isModal:a=!1,placeholder:d="Type your message...",resetWorkflow:u}){const{client:h}=It(),p=m(null),[f,g]=o([]),[y,b]=o(!1),[x,w]=o(""),[N,k]=o(!1),[C,_]=o("sliding"),[j,S]=o(!a),[T,P]=o([]),[I,A]=o(0),[E,$]=o(new Map),[z,O]=o(0),D=v(),[U,L]=o(s),[F,R]=o(null),M=l((()=>{const e=T[I]||{plan:{plan:[]},timestamp:0},t=E.get(e.timestamp)||new Map;return{plan:e.plan,workstreamStatus:t}}),[T,I,E]);c((()=>{if(!y){const e=setInterval((()=>{O((()=>Math.floor(Math.random()*(Fn.length-1))))}),4e3);return()=>clearInterval(e)}}),[y]);c((()=>(g([]),P([]),A(0),$(new Map),S(!1),R(null),(async()=>{try{const e=await h.store.workflows.getRunDetails(n.runId,n.workflowId);R(e.status)}catch(e){console.error("Failed to check workflow status:",e)}})(),h.store.workflows.streamMessages(n.workflowId,n.runId,(e=>{e.message&&g((t=>t.find((t=>t.timestamp===e.timestamp))?t:(function(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)}(t,e),[...t])))})),()=>{g([])})),[n.runId,h.store.workflows]),c((()=>{b(!function(e){if(!e.length)return!0;const t=new Map;if(e.forEach((e=>{const n=Mn(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}`),Rn.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}`),Rn.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(!Rn.includes(t.type))return console.log(`[isInProgress] Workstream ${e} is still active`),!0}return console.log("[isInProgress] All workstreams are completed"),!1}(f)),0===T.length&&S(!1)}),[f,T.length]),c((()=>{if(1===T.length&&!j&&!sessionStorage.getItem("plan-panel-shown")){const e=setTimeout((()=>{S(!0),sessionStorage.setItem("plan-panel-shown","true")}),500);return()=>clearTimeout(e)}f.forEach((e=>{if(e.type===At.PLAN)try{console.log("PLAN message received:",e.type);let t=null;if(e.details&&"object"==typeof e.details&&e.details.plan&&Array.isArray(e.details.plan)&&(console.log("Valid plan array found in message.details.plan"),t={plan:e.details.plan}),t){const n="number"==typeof e.timestamp?e.timestamp:new Date(e.timestamp).getTime();if(-1===T.findIndex((e=>e.timestamp===n))&&t){console.log("Adding new plan to plans array");const e={plan:t,timestamp:n};console.log("Adding plan to plans array:",e),P((t=>{const n=[e,...t];return console.log("New plans array:",n),n})),A(0),console.log("Setting showSlidingPanel to true"),S(!0);const r=new Map;r.set("main","in_progress"),Array.isArray(t.plan)&&t.plan.forEach((e=>{if(e&&"object"==typeof e&&e.id){const t=e.id.toString();r.set(t,e.status||"pending")}})),$((e=>{const t=new Map(e);return t.set(n,r),t}))}}}catch(e){console.error("Failed to parse plan from message:",e)}e.type===At.UPDATE&&e.details&&e.details.updates&&Array.isArray(e.details.updates)&&console.log("Ignoring UPDATE message with details.updates - waiting for PLAN message with full plan")}));const e=f[f.length-1];e&&(e.type===At.TERMINATED?(L(!1),R("TERMINATED")):L(!!s||e.type===At.REQUEST_INPUT))}),[f,T,I]);const V=r||n.workflowId.split(":")[2]||"Agent Conversation";return t("div",{className:"flex gap-2 h-full",children:[t("div",{className:"flex flex-col h-full min-h-0 border-0 "+(j?"lg:w-2/3 flex-1":"flex-1 mx-auto "+(a?"":"max-w-4xl")),children:[e(Yn,{title:V,isCompleted:y,onClose:i,isModal:a,run:n,viewMode:C,onViewModeChange:_,showPlanPanel:j,hasPlan:T.length>0,onTogglePlanPanel:()=>{S(!j),j||sessionStorage.setItem("plan-panel-shown","true")},onDownload:async()=>{try{const e=await async function(e,t){return e.files.getDownloadUrl(`agents/${t}/conversation.json`).then((e=>e.url))}(h,n.runId);e&&window.open(e,"_blank")}catch(e){console.error("Failed to download conversation",e),D({status:"error",title:"Failed to download conversation",duration:3e3})}},onCopyRunId:()=>{navigator.clipboard.writeText(n.runId),D({status:"success",title:"Run ID copied",duration:2e3})},resetWorkflow:u}),0!==f.length||y?e(Wn,{messages:f,bottomRef:p,viewMode:C,isCompleted:y,plan:M.plan,workstreamStatus:M.workstreamStatus,showPlanPanel:j,onTogglePlanPanel:()=>{console.log("Toggle plan panel called, current state:",j),S(!j)},plans:T,activePlanIndex:I,onChangePlan:e=>A(e),taskLabels:M.plan.plan?.reduce(((e,t)=>(t.id&&t.goal&&e.set(t.id.toString(),t.goal),e)),new Map)}):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(zn,{size:"sm",color:"blue"}),e("div",{className:"text-sm text-muted font-medium",children:Fn[z]})]}),e("div",{className:"mt-4 flex justify-center",children:e($n,{color:"blue",className:"mt-1"})})]})}),F&&("RUNNING"!==F?t(se,{status:"COMPLETED"===F?"success":"done",icon:null,className:"flex-shrink-0 m-2",children:["This Workflow is ",F]}):U&&e(wa,{value:x,onChange:w,onSend:()=>{const e=x.trim();e&&!N&&(k(!0),w(""),h.store.workflows.sendSignal(n.workflowId,n.runId,"UserInput",{message:e}).then((()=>{b(!1),D({status:"success",title:"Message Sent",duration:2e3})})).catch((e=>{D({status:"error",title:"Failed to Send Message",description:e instanceof Error?e.message:"Unknown error",duration:3e3})})).finally((()=>{k(!1)})))},disabled:!1,isSending:N,isCompleted:y,activeTaskCount:(()=>{if(!f.length)return 0;const e=new Map;f.forEach((t=>{const n=Mn(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];[At.COMPLETE,At.IDLE].includes(e.type)||t++}return t})(),placeholder:d}))]}),j&&e("div",{className:"h-full lg:w-1/3 border-l",children:e(Na,{plan:M.plan,workstreamStatus:M.workstreamStatus,isOpen:j,onClose:()=>S(!1),plans:T,activePlanIndex:I,onChangePlan:A})})]})}function Sa({children:t,fallback:n}){return Ta?e(Ta,{fallback:n,children:t}):e(vn,{FallbackComponent:n,children:t})}let Ta=null;function Pa(e){Ta=e}function Ia({children:t}){return e(Sa,{fallback:Aa,children:t})}function Aa({error:n}){return t(se,{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 Ea({children:t}){return e(Sa,{fallback:$a,children:t})}function $a({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 za({children:t}){return e(Sa,{fallback:Oa,children:t})}function Oa({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 Da({className:n,children:s,title:i,description:a,actions:l,breadcrumbs:o,isCompact:c=!1,useDynamicBreadcrumbs:d=!0}){const u=qt(),m=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){const e=n[1];return`${yn(e)} Detail`}return n.length>=2?yn(n[n.length-1]):1===n.length?yn(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:m(n),href:n.href,onClick:()=>window.history.go(-s)})}))}return o&&o.length>0&&o.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:()=>u(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(Ee,{path:h,separator:e(mt,{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:i}),a&&e(V,{description:a,children:e(Ue,{className:"size-4 text-muted"})})]})]}),e("div",{className:"flex gap-x-2 shrink-0",children:l})]}),s&&e("div",{className:"w-full flex items-center",children:s})]})}function Ua({}){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"})]})}class La{totalPages;layoutUrls=[];cache;constructor(e){this.totalPages=e,this.cache=new Array(e)}async loadUrls(e,t){const n=[];for(let r=0;r<this.totalPages;r++)n.push(Ha(e,t,r+1));const r=await Promise.all(n);this.layoutUrls=r.map((e=>e.url))}async getPageLayout(e){const t=e-1;let n=this.cache[t];if(void 0===n){const e=this.layoutUrls[t];n=await fetch(e,{method:"GET"}).then((e=>{if(e.ok)return e.text();throw new Error("Failed to fetch json layout: "+e.statusText)})),this.cache[t]=n}return n}}class Fa{totalPages;markdownUrls=[];cache;constructor(e){this.totalPages=e,this.cache=new Array(e)}async loadUrls(e,t){const n=[];for(let r=0;r<this.totalPages;r++)n.push(Ja(e,t,r+1));const r=await Promise.all(n);this.markdownUrls=r.map((e=>e.url))}async getPageMarkdown(e){const t=e-1;let n=this.cache[t];if(void 0===n){const e=this.markdownUrls[t];n=await fetch(e,{method:"GET"}).then((e=>{if(e.ok)return e.text();throw new Error("Failed to fetch markdown: "+e.statusText)})),this.cache[t]=n}return n}}const Ra=d(void 0);function Ma({children:t,object:n}){const{client:r}=It(),[s,i]=o();return c((()=>{const e=n.metadata.page_count||10;(async function(e,t,n){const r=[];for(let s=0;s<n;s++)r.push(qa(e,t.id,s+1));const s=await Promise.all(r),i=[];for(let r=0;r<n;r++)i.push(Ba(e,t.id,r+1));const a=await Promise.all(i),l=[];for(let r=0;r<n;r++)l.push(Wa(e,t.id,r+1));const o=await Promise.all(l),c=[];for(let r=0;r<n;r++)c.push(Ga(e,t.id,r+1));const d=await Promise.all(c),u=new La(n);await u.loadUrls(e,t.id);const m=new Fa(n);await m.loadUrls(e,t.id);const h=t.text?Qa(t.text):"";return{count:n,urls:s.map((e=>e.url)),originalUrls:d.map((e=>e.url)),annotatedUrls:a.map((e=>e.url)),instrumentedUrls:o.map((e=>e.url)),layoutProvider:u,markdownProvider:m,xml:h,xmlPages:t.text?Ya(h):[]}})(r,n,e).then(i)}),[n.id]),s&&e(Ra.Provider,{value:s,children:t})}function Va(e){return`magic-pdf/${e}`}function qa(e,t,n){return e.files.getDownloadUrl(function(e,t,n=".jpg"){return`${Va(e)}/pages/page-${t}${n}`}(t,n))}function Ba(e,t,n){return e.files.getDownloadUrl(function(e,t,n=".jpg"){return`${Va(e)}/pages/page-${t}-annotated${n}`}(t,n))}function Wa(e,t,n){return e.files.getDownloadUrl(function(e,t,n=".jpg"){return`${Va(e)}/pages/page-${t}.instrumented${n}`}(t,n))}function Ga(e,t,n){return e.files.getDownloadUrl(function(e,t,n=".jpg"){return`${Va(e)}/pages/page-${t}.original${n}`}(t,n))}function Ha(e,t,n){return e.files.getDownloadUrl(function(e,t){return`${Va(e)}/pages/page-${t}.layout.json`}(t,n))}function Ja(e,t,n){return e.files.getDownloadUrl(function(e,t){return`${Va(e)}/pages/page-${t}.md`}(t,n))}function Ka(){const e=a.useContext(Ra);if(!e)throw new Error("usePdfPagesInfo must be used within a PdfPageProvider");return e}function Ya(e){const t=(new DOMParser).parseFromString(Qa(e),"text/xml").getElementsByTagName("page"),n=new XMLSerializer;return Array.from(t).map((e=>n.serializeToString(e)))}function Qa(e){return e.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,"").replace(/<\?xml.*?\?>/g,"")}function Xa({object:r}){const{client:s}=It(),i=e=>{(function(e,t,n){return e.files.getDownloadUrl(`${Va(t)}/${n}`).then((e=>e.url))})(s,r.id,e).then((e=>window.open(e,"_blank")))},a=(()=>{if("document"===r.metadata?.type){const e=r.metadata;return e.content_processor?.type||"xml"}return"xml"})();return e("div",{className:"absolute bottom-[58px] right-[20px] w-[36px] h-[36px] cursor-pointer text-indigo-400 border-indigo-400 hover:border-indigo-500 hover:text-indigo-500 border-2 rounded-full shadow-xs flex items-center justify-center",children:t(sn,{strategy:"absolute",placement:"top-end",zIndex:100,offset:20,children:[e(sn.Trigger,{click:!0,children:e(Ct,{className:"size-6"})}),e(sn.Content,{children:e("div",{className:"rounded-md shadow-md border border-gray-100 bg-white dark:bg-slate-50 dark:border-slate-100 min-w-[200px] flex flex-col divide-y",children:"markdown"===a?e("button",{className:"p-2 cursor-pointer hover:bg-slate-50 dark:hover:bg-slate-100",onClick:()=>i("document.md"),children:"document.md"}):t(n,{children:[e("button",{className:"p-2 cursor-pointer hover:bg-slate-50 dark:hover:bg-slate-100",onClick:()=>i("annotated.pdf"),children:"annotated.pdf"}),e("button",{className:"p-2 cursor-pointer hover:bg-slate-50 dark:hover:bg-slate-100",onClick:()=>i("document.xml"),children:"document.xml"}),e("button",{className:"p-2 cursor-pointer hover:bg-slate-50 dark:hover:bg-slate-100",onClick:()=>i("analyzed-pages.json"),children:"analyzed-pages.json"})]})})})]})})}var Za;function el({className:s,currentPage:i,onChange:a,object:l}){const c=()=>{if("document"===l.metadata?.type){const e=l.metadata;return e.content_processor?.type||"xml"}return"xml"},[d,u]=o("markdown"===c()?Za.original:Za.default),h=m(null),{urls:p,originalUrls:f,annotatedUrls:g,instrumentedUrls:v}=Ka(),y=d===Za.instrumented?v:d===Za.annotated?g:d===Za.original?f:p;return t("div",{ref:h,className:r("flex flex-col items-stretch gap-y-2",s),children:[t("div",{className:"flex h-5 items-center justify-center relative",children:[e("button",{className:nl,onClick:()=>{i>1&&(a(i-1),h.current&&h.current.querySelector(`div[data-index="${i-1}"]`)?.scrollIntoView({behavior:"smooth",block:"end",inline:"center"}))},children:e(_t,{className:"w-5 h-5"})}),e("div",{className:"absolute right-3 flex gap-x-1",children:"markdown"===c()?t(n,{children:[e("button",{className:rl(Za.original,d),onClick:()=>u(Za.original),children:e(jt,{className:"w-5 h-5 mt-1"})}),e("button",{className:rl(Za.instrumented,d),onClick:()=>u(Za.instrumented),children:e(St,{className:"w-5 h-5 mt-1"})})]}):t(n,{children:[e("button",{className:rl(Za.default,d),onClick:()=>u(Za.default),children:e(jt,{className:"w-5 h-5 mt-1"})}),e("button",{className:rl(Za.instrumented,d),onClick:()=>u(Za.instrumented),children:e(St,{className:"w-5 h-5 mt-1"})}),e("button",{className:rl(Za.annotated,d),onClick:()=>u(Za.annotated),children:e(Tt,{className:"w-5 h-5 mt-1"})})]})})]}),e("div",{className:"flex flex-col items-center gap-2 flex-1 overflow-y-auto px-2",children:y.map(((t,n)=>e(tl,{url:t,currentPage:i,pageNumber:n+1,onSelect:()=>a(n+1)},n)))}),e("div",{className:"flex h-5 items-center justify-center relative",children:e("button",{className:nl,onClick:()=>{i<p.length&&(a(i+1),h.current&&h.current.querySelector(`div[data-index="${i+1}"]`)?.scrollIntoView({behavior:"smooth",block:"end",inline:"center"}))},children:e(Pt,{className:"size-5"})})})]})}function tl({url:n,pageNumber:s,currentPage:i,onSelect:a}){return t("div",{className:"p-2 hover:bg-gray-200 dark:hover:bg-slate-600 rounded-md","data-index":s-1,children:[e("div",{className:r("relative border-[2px] cursor-pointer",s===i?"border-blue-500 dark:border-pink-400":"border-gray-300"),onClick:a,children:e("img",{src:n,alt:`Page ${s}`})}),e($e,{className:"text-sm text-gray-500 dark:text-gray-400 pt-1 font-semibold align",children:s})]})}!function(e){e[e.default=0]="default",e[e.original=1]="original",e[e.instrumented=2]="instrumented",e[e.annotated=3]="annotated"}(Za||(Za={}));const nl="cursor-pointer text-gray-500 dark:text-gray-400 hover:text-blue-600 dark:hover:text-blue-500 hover:font-semibold";function rl(e,t){return e===t?"${BTN_CLASS} text-pink-600":`${nl}`}const sl={attributeKeyColor:"#FFD700",attributeValueColor:"#FF4500",tagColor:"#87CEFA",textColor:"#00FF00",separatorColor:"#FFD700",commentColor:"#BEBEBE",cdataColor:"#33CC66"};function il({viewType:t,pageNumber:n}){switch(t){case"json":return e(ll,{pageNumber:n});case"markdown":return e(ol,{pageNumber:n});default:return e(al,{pageNumber:n})}}function al({pageNumber:t}){const[n,r]=o(),{xmlPages:s}=Ka();return f((()=>{const e=window.matchMedia("(prefers-color-scheme: dark)"),t=e=>{r(e.matches?sl:void 0)};return e.addEventListener("change",t),e.matches&&r(sl),()=>{e.removeEventListener("change",t)}}),[]),e("div",{className:"px-4 py-2",children:e(an,{xml:s[t-1],collapsible:!0,theme:n})})}function ll({pageNumber:t}){const[n,r]=o(),{layoutProvider:s}=Ka();return c((()=>{s.getPageLayout(t).then((e=>r(e?JSON.parse(e):void 0))).catch((e=>{console.error(e),r(void 0)}))}),[t]),n&&e(ln,{className:"w-full",data:n})}function ol({pageNumber:t}){const[n,r]=o(),{markdownProvider:s}=Ka();return c((()=>{s.getPageMarkdown(t).then(r).catch((e=>{console.error(e),r(void 0)}))}),[t]),e("div",{className:"px-4 py-2 prose prose-sm max-w-none dark:prose-invert",children:n?e(Kt,{children:n}):e("div",{children:"No markdown content available"})})}function cl({objectId:t,onClose:n}){const{client:r}=It(),{data:s,error:i}=W((()=>r.store.objects.retrieve(t,"+text")),[t]);return i?e(oe,{title:"Fetching document failed",children:i.message}):s?e("div",{className:"fixed inset-0 bg-white dark:bg-slate-700 z-50 flex items-center justify-center",children:e(Ma,{object:s,children:e(dl,{object:s,onClose:n})})}):"Loading..."}function dl({object:r,onClose:s}){const[i,a]=o((()=>{if("document"===r.metadata?.type){const e=r.metadata,t=e.content_processor?.type;if("markdown"===t)return"markdown";if("xml"===t)return"xml"}return"xml"})()),[l,d]=o(1),u=(()=>{if("document"===r.metadata?.type){const e=r.metadata;return e.content_processor?.type||"xml"}return"xml"})(),h=m(null),p=m(null),f=m(null);var g;return c((()=>{if(g.handler.current&&g.left.current&&g.right.current){const e=g.handler.current,t=g.left.current,n=g.right.current,r=e=>{let r=e.clientX,s=t.offsetWidth,i=n.offsetLeft;const a=e=>{const a=e.clientX-r;t.style.width=`${s+a}px`,n.style.left=`${i+a}px`,e.target.classList.add("resizing")},l=e=>{e.target.classList.remove("resizing"),a(e),document.removeEventListener("mousemove",a),document.removeEventListener("mouseup",l)};document.addEventListener("mousemove",a),document.addEventListener("mouseup",l)};return e.addEventListener("mousedown",r),()=>{e.removeEventListener("mousedown",r)}}}),[(g={handler:h,left:p,right:f}).handler.current,g.left.current,g.right.current]),t(n,{children:[t("div",{ref:p,className:"absolute top-0 left-0 bottom-0 w-[50%] bg-gray-100 dark:bg-slate-800 flex items-stretch justify-stretch py-2",children:[e(el,{className:"flex-1",currentPage:l,onChange:d,object:r}),e("div",{ref:h,className:"w-[2px] p-[2px] m-0 bg-slate-300 cursor-ew-resize"})]}),e("div",{ref:f,className:"absolute top-0 left-[50%] right-0 bottom-0 flex items-stretch justify-stretch overflow-auto p-2",children:e(il,{pageNumber:l,viewType:i})}),e(Xa,{object:r}),"xml"===u&&e(ul,{type:i,onSwitch:a}),!!s&&e("div",{className:"absolute top-6 right-7 w-9 h-9 cursor-pointer text-red-400 border-red-400 hover:border-red-500 hover:text-red-500 border-2 rounded-full shadow-xs flex items-center justify-center",onClick:s,children:e(ot,{className:"size-6"})})]})}function ul({type:e="xml",onSwitch:n}){return t("div",{className:"absolute bottom-[16px] right-[20px] w-[36px] h-[36px] cursor-pointer text-indigo-400 border-indigo-400 hover:border-indigo-500 hover:text-indigo-500 border-2 rounded-full shadow-xs flex items-center justify-center",onClick:()=>{"xml"===e?n("json"):"json"===e?n("markdown"):"markdown"===e&&n("xml")},children:["xml"===e&&ml,"json"===e&&pl,"markdown"===e&&hl]})}const ml=e("svg",{width:"16px",height:"16px",viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg",fill:"currentColor",children:e("path",{"fill-rule":"evenodd","clip-rule":"evenodd",d:"M6 2.984V2h-.09c-.313 0-.616.062-.909.185a2.33 2.33 0 0 0-.775.53 2.23 2.23 0 0 0-.493.753v.001a3.542 3.542 0 0 0-.198.83v.002a6.08 6.08 0 0 0-.024.863c.012.29.018.58.018.869 0 .203-.04.393-.117.572v.001a1.504 1.504 0 0 1-.765.787 1.376 1.376 0 0 1-.558.115H2v.984h.09c.195 0 .38.04.556.121l.001.001c.178.078.329.184.455.318l.002.002c.13.13.233.285.307.465l.001.002c.078.18.117.368.117.566 0 .29-.006.58-.018.869-.012.296-.004.585.024.87v.001c.033.283.099.558.197.824v.001c.106.273.271.524.494.753.223.23.482.407.775.53.293.123.596.185.91.185H6v-.984h-.09c-.2 0-.387-.038-.563-.115a1.613 1.613 0 0 1-.457-.32 1.659 1.659 0 0 1-.309-.467c-.074-.18-.11-.37-.11-.573 0-.228.003-.453.011-.672.008-.228.008-.45 0-.665a4.639 4.639 0 0 0-.055-.64 2.682 2.682 0 0 0-.168-.609A2.284 2.284 0 0 0 3.522 8a2.284 2.284 0 0 0 .738-.955c.08-.192.135-.393.168-.602.033-.21.051-.423.055-.64.008-.22.008-.442 0-.666-.008-.224-.012-.45-.012-.678a1.47 1.47 0 0 1 .877-1.354 1.33 1.33 0 0 1 .563-.121H6zm4 10.032V14h.09c.313 0 .616-.062.909-.185.293-.123.552-.3.775-.53.223-.23.388-.48.493-.753v-.001c.1-.266.165-.543.198-.83v-.002c.028-.28.036-.567.024-.863-.012-.29-.018-.58-.018-.869 0-.203.04-.393.117-.572v-.001a1.502 1.502 0 0 1 .765-.787 1.38 1.38 0 0 1 .558-.115H14v-.984h-.09c-.196 0-.381-.04-.557-.121l-.001-.001a1.376 1.376 0 0 1-.455-.318l-.002-.002a1.415 1.415 0 0 1-.307-.465v-.002a1.405 1.405 0 0 1-.118-.566c0-.29.006-.58.018-.869a6.174 6.174 0 0 0-.024-.87v-.001a3.537 3.537 0 0 0-.197-.824v-.001a2.23 2.23 0 0 0-.494-.753 2.331 2.331 0 0 0-.775-.53 2.325 2.325 0 0 0-.91-.185H10v.984h.09c.2 0 .387.038.562.115.174.082.326.188.457.32.127.134.23.29.309.467.074.18.11.37.11.573 0 .228-.003.452-.011.672-.008.228-.008.45 0 .665.004.222.022.435.055.64.033.214.089.416.168.609a2.285 2.285 0 0 0 .738.955 2.285 2.285 0 0 0-.738.955 2.689 2.689 0 0 0-.168.602c-.033.21-.051.423-.055.64a9.15 9.15 0 0 0 0 .666c.008.224.012.45.012.678a1.471 1.471 0 0 1-.877 1.354 1.33 1.33 0 0 1-.563.121H10z"})}),hl=e("svg",{width:"16px",height:"16px",viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg",fill:"currentColor",children:e("path",{d:"M4.708 5.578L2.061 8.224l2.647 2.646-.708.708-3-3V7.87l3-3 .708.708zm7-.708L11 5.578l2.647 2.646L11 10.87l.708.708 3-3V7.87l-3-3zM4.908 13l.894.448 5-10L9.908 3l-5 10z"})}),pl=e("svg",{width:"16px",height:"16px",viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg",fill:"currentColor",children:e("path",{d:"M14.85 3H1.15C.52 3 0 3.52 0 4.15v7.69C0 12.48.52 13 1.15 13h13.69c.64 0 1.15-.52 1.15-1.15v-7.7C16 3.52 15.48 3 14.85 3zM9 11H7.5L5.5 9l-1 1.5H3V5h1.5l1 2 2-2H9v6zm2.99.5L9.5 8H11V5h1v3h1.5l-2.51 3.5z"})});function fl(...e){const t=Array.from(e);return t.__AnyOf__=!0,t}function gl(...e){return Array.from(e)}function vl(e){return!0===e.__AnyOf__}class yl{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(vl(e))return e.some((e=>this.permissions.has(e)));for(const t of e)if(!this.permissions.has(t))return!1;return!0}}const bl=d(void 0);function xl(){const e=u(bl);if(!e)throw new Error("UserPermissionContext cannot be used outside UserPermissionProvider");return e}function wl({children:t}){const n=It(),{data:r,error:s,isLoading:i}=W((()=>n.user?n.client.iam.roles.list():Promise.resolve(void 0)),[n.user]),a=l((()=>n.authToken&&r&&!i?new yl(n,r):void 0),[n,r,i]);return s?e(oe,{title:"Failed to fetch role mappings",children:s.message}):a&&e(bl.Provider,{value:a,children:t})}function Nl({permission:t,isDisabled:n,title:r,children:s,...i}){return xl().hasPermission(t)||(n=!0,r="You do not have permission to perform this action"),e(b,{isDisabled:n,title:r,...i,children:s})}function kl({permission:t,...n}){return xl().hasPermission(t)?e(bn,{...n}):null}function Cl({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{kn as ActivitiesDoc,_n as ActivityDoc,ua as AddToCollectionAction,da as AddToCollectionActionComponent,gl as AllOf,$n as AnimatedThinkingDots,fl as AnyOf,Jr as ApiKeyAvatar,mi as BrowseCollectionView,qi as ChangeTypeAction,Vi as ChangeTypeActionComponent,fs as CollectionsFacetsNav,vi as CollectionsTable,Zn as ContentDispositionButton,Si as ContentObjectTypesSearch,bi as ContentObjectTypesTable,ir as ContentOverview,fi as CreateCollectionForm,gi as CreateCollectionModal,_i as CreateOrUpdateTypeModal,Gi as DeleteObjectsAction,Wi as DeleteObjectsActionComponent,Hi as DeleteObjectsFromCollectionsAction,Ss as DocumentGridView,Sr as DocumentIcon,jr as DocumentIconSkeleton,Ys as DocumentInput,Xs as DocumentPreviewPanel,Ts as DocumentSearch,qs as DocumentSearchProvider,ii as DocumentSearchResults,si as DocumentSearchResultsWithDropZone,gs as DocumentSelection,xs as DocumentSelectionProvider,Rs as DocumentTable,_s as DocumentTableColumn,js as DocumentTableView,Us as DocumentUploadModal,as as DocumentsFacetsNav,Ui as EditCollectionView,Qr as EnvironmentFacet,Ki as ExportPropertiesAction,Ji as ExportPropertiesComponent,ci as ExportPropertiesModal,oi as ExportTypes,zs as FileUploadAction,Da as GenericPageNavHeader,cs as InteractionsFacetsNav,En as JumpingDots,cl as MagicPdfView,ka as ModernAgentConversation,Ua as NotFoundView,Pi as ObjectSchemaEditor,xi as ObjectTypeSearch,wi as ObjectTypeSearchContext,Ai as ObjectTypeSearchProvider,ra as ObjectsActionContext,ia as ObjectsActionContextProvider,Ia as PanelErrorBoundary,Gn as PayloadBuilder,Jn as PayloadBuilderProvider,Hn as PayloadContext,ms as PromptsFacetsNav,nr as PropertiesEditorModal,zn as PulsatingCircle,Dn as PulsingMessageLoader,Qi as RemoveFromCollectionAction,Yi as RemoveFromCollectionActionComponent,Ea as RowErrorBoundary,es as RunsFacetsNav,tr as SaveVersionConfirmModal,Ps as SearchContext,Nl as SecureButton,kl as SecureSidebarItem,Fi as SelectCollection,pi as SelectContentType,Ei as SelectContentTypeModal,Ws as SelectDocument,Js as SelectDocumentModal,pa as SelectionActions,Ri as SharedPropsEditor,Zi as StartWorkflowAction,Xi as StartWorkflowComponent,Ir as StringFacet,Ar as StringListFacet,Mi as SyncMemberHeadsToggle,zi as TableLayoutEditor,Un as ThinkingBar,Fn as ThinkingMessages,$r as TypeFacet,On as TypedDots,ga as UploadObjectsButton,Cl as UserAvatar,Br as UserInfo,wl as UserPermissionProvider,yl as UserPermissions,bl as UserPermissionsContext,zr as VStringFacet,Or as VTypeFacet,Yr as VUserFacet,Sa as VertesiaErrorBoundary,Ln as WavyThinking,za as WidgetErrorBoundary,rs as WorkflowExecutionsFacetsNav,yi as collectionIcon,vl as isAnyOf,yr as isCsv,br as isImage,xr as isPdf,wr as isVideo,_r as retrieveRendition,Pa as setErrorBoundaryComponent,mr as shortId,hr as shortenString,Oi as stringifyTableLayout,hs as useCollectionsFilterGroups,ps as useCollectionsFilterHandler,ss as useDocumentFilterGroups,is as useDocumentFilterHandler,Is as useDocumentSearch,$s as useDocumentSearchCount,ys as useDocumentSelection,Ls as useDocumentUploadHandler,Qs as useDownloadDocument,Fr as useFetchGroupInfo,Lr as useFetchUserInfo,ls as useInteractionsFilterGroups,os as useInteractionsFilterHandler,oa as useObjectsActionCallback,la as useObjectsActionContext,bs as useOptionalDocumentSelection,Kn as usePayloadBuilder,ds as usePromptsFilterGroups,us as usePromptsFilterHandler,Xr as useRunsFilterGroups,Zr as useRunsFilterHandler,Ni as useSearch,Ci as useSearchCount,Ds as useSmartFileUploadProcessing,ca as useStartWorkflowCallback,xl as useUserPermissions,As as useWatchDocumentSearchFacets,Es as useWatchDocumentSearchResult,ki as useWatchSearchResult,ts as useWorkflowExecutionsFilterGroups,ns as useWorkflowExecutionsFilterHandler};
1
+ import{jsx as e,jsxs as t,Fragment as n}from"react/jsx-runtime";import r from"clsx";import{AnimatePresence as s,motion as i}from"motion/react";import a,{useMemo as l,useState as o,useEffect as c,createContext as d,useContext as u,useRef as m,memo as h,useCallback as p,useLayoutEffect as f}from"react";import{cn as g,useToast as v,Badge as y,Button as b,Popover as x,PopoverTrigger as w,PopoverContent as N,Command as k,CommandList as C,CommandGroup as j,CommandItem as S,Modal as _,ModalTitle as T,ModalBody as P,RadioGroup as I,FormItem as A,Input as $,ModalFooter as E,RadioOptionAdapter as z,ResizablePanelGroup as O,ResizablePanel as D,ResizableHandle as U,Spinner as L,Card as F,Separator as R,CardContent as M,VTooltip as V,SelectBox as q,InputList as W,useFetch as B,Avatar as G,Table as J,FilterProvider as H,FilterBtn as K,FilterBar as Y,FilterClear as Q,TBody as X,SharedState as Z,useWatchSharedState as ee,VModal as te,VModalTitle as ne,VModalBody as re,MessageBox as se,VModalFooter as ie,VSelectBox as ae,useIntersectionObserver as le,ErrorBox as oe,useFlag as ce,Styles as de,Checkbox as ue,NumberInput as me,SidePanel as he,Divider as pe,Textarea as fe,Switch as ge,TR as ve,EmptyCollection as ye,ConfirmModal as be,useDebounce as xe,Panel as we,CommandInput as Ne,CommandEmpty as ke,SelectList as Ce,Portal as je,DialogDescription as Se,Heading as _e,VTabs as Te,VTabsBar as Pe,VTabsPanel as Ie,Breadcrumbs as Ae,Center as $e}from"@vertesia/ui/core";import{CopyIcon as Ee,Bot as ze,MessageSquare as Oe,Info as De,AlertCircle as Ue,User as Le,CheckCircle as Fe,Clock as Re,ClipboardList as Me,XIcon as Ve,MoreVertical as qe,ExternalLink as We,DownloadCloudIcon as Be,TableProperties as Ge,LayoutGrid as Je,AlertTriangle as He,Copy as Ke,SquarePen as Ye,Download as Qe,Eye as Xe,Users as Ze,RefreshCw as et,UploadIcon as tt,CheckCircleIcon as nt,AlertCircleIcon as rt,FileIcon as st,XCircleIcon as it,FolderIcon as at,X as lt,ChevronsUpDown as ot,FileText as ct,Maximize2 as dt,ChevronRight as ut,Settings as mt,Trash2 as ht,Search as pt,FolderClosed as ft,Check as gt,EllipsisVertical as vt,PaperclipIcon as yt,SendIcon as bt,Activity as xt,Circle as wt,Cpu as Nt,CloudDownload as kt,ChevronsUp as Ct,ImageIcon as jt,InfoIcon as St,AtSignIcon as _t,ChevronsDown as Tt}from"lucide-react";import{useUserSession as Pt}from"@vertesia/ui/session";import{AgentMessageType as It,mergePromptsSchema as At,supportsToolUse as $t,ContentNature as Et,POSTER_RENDITION_NAME as zt,ImageRenditionFormat as Ot,PrincipalType as Dt,InteractionStatus as Ut,SearchTypes as Lt,SupportedEmbeddingTypes as Ft}from"@vertesia/common";import{NavLink as Rt,useNavigate as Mt}from"@vertesia/ui/router";import Vt from"dayjs";import qt from"react-markdown";import Wt from"remark-gfm";import Bt,{Ajv as Gt}from"ajv";import{MarkdownRenderer as Jt,JSONDisplay as Ht,DropZone as Kt,UploadSummary as Yt,useSchema as Qt,CodeMirrorEditor as Xt,SchemaEditor as Zt,ManagedObject as en,GeneratedForm as tn,Popover as nn,XMLViewer as rn,JSONCode as sn}from"@vertesia/ui/widgets";import an from"@monaco-editor/react";import ln from"dayjs/plugin/localizedFormat";import on from"dayjs/plugin/relativeTime";import{Md5 as cn}from"ts-md5";import{json as dn}from"@codemirror/lang-json";import{basicSetup as un}from"codemirror";import{UserInfo as mn}from"@vertesia/ui/features";import{ErrorBoundary as hn}from"react-error-boundary";import{capitalize as pn}from"lodash-es";import{SidebarItem as fn}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 vn(e){return e?"array"===e.name?vn(e.innerType):e:void 0}function yn({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 bn({activities:t}){return e("div",{className:"flex flex-col gap-y-4 divide-y divide-gray-200",children:t.map((t=>e(wn,{activity:t},t.name)))})}function xn({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 wn({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(xn,{code:n.paramsType,children:"Parameters"}),e("div",{className:"divide-y divide-gray-100",children:n.params.map((t=>e(Nn,{property:t},t.name)))})]}),t("div",{className:"pb-4",children:[e(xn,{children:"Returns"}),e("div",{children:n.returnType?n.returnType.value:"void"})]})]})}function Nn({property:n,className:s}){const i=l((()=>{const t=vn(n.type.innerType)??n.type;return"object"===t.name&&t.members?e(Cn,{members:t.members}):"enum"===t.name&&t.enum?e(kn,{values:t.enum}):null}),[n.type.innerType]);return t("div",{className:r("py-2",s),children:[e(yn,{property:n}),n.doc&&e("div",{className:"text-gray-700 text-sm pt-2",children:n.doc}),i&&e("div",{className:"my-2 overflow-hidden",children:i})]})}function kn({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 Cn({members:n}){return e(Sn,{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(_n,{isOpen:n}),e("div",n?{children:"Hide child properties"}:{children:"Show child properties"})]}),body:e(jn,{properties:n})})}function jn({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(Nn,{property:t,className:"px-4 py-2"},t.name)))})}function Sn({button:n,body:a,className:l,isInitiallyOpen:c}){const[d,u]=o(c||!1);return t("div",{className:r(d?"block":"inline-block",l),children:[e("button",{className:"p-0 m-0 bg-transparent",onClick:()=>u(!d),children:e(s,{children:n(d)})}),e(s,{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:a})})]})}function _n({isOpen:t}){return e(s,{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 Tn({className:n,inline:r=!1}){return t("div",{className:g("flex items-center gap-1",r?"inline-flex":"",n),children:[e("div",{className:"w-2 h-2 bg-blue-500 rounded-full animate-[jumping_1s_infinite_ease-in-out] hover:bg-blue-600",style:{transform:"translateY(0)",animationRange:"0px -8px"}}),e("div",{className:"w-2 h-2 bg-blue-500 rounded-full animate-[jumping_1s_0.3s_infinite_ease-in-out] hover:bg-blue-600",style:{transform:"translateY(0)",animationRange:"0px -8px"}}),e("div",{className:"w-2 h-2 bg-blue-500 rounded-full animate-[jumping_1s_0.6s_infinite_ease-in-out] hover:bg-blue-600",style:{transform:"translateY(0)",animationRange:"0px -8px"}})]})}function Pn({className:n,inline:r=!1,color:s="blue"}){const i={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:g("flex items-center gap-1.5",r?"inline-flex":"",n),children:[e("div",{className:`w-2 h-2 bg-gradient-to-r ${i} rounded-full animate-[bounce_1.2s_ease-in-out_infinite]`}),e("div",{className:`w-2 h-2 bg-gradient-to-r ${i} rounded-full animate-[bounce_1.2s_ease-in-out_0.2s_infinite]`}),e("div",{className:`w-2 h-2 bg-gradient-to-r ${i} rounded-full animate-[bounce_1.2s_ease-in-out_0.4s_infinite]`})]})}function In({className:n,size:r="md",color:s="blue"}){const i={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:g("relative flex",n),children:[e("span",{className:g("animate-ping absolute inline-flex h-full w-full rounded-full opacity-60",i[s])}),e("span",{className:g("animate-pulse absolute inline-flex h-[80%] w-[80%] rounded-full opacity-80",i[s]),style:{left:"10%",top:"10%",animationDuration:"2s"}}),e("span",{className:g("relative inline-flex rounded-full",i[s],{sm:"w-3 h-3",md:"w-5 h-5",lg:"w-7 h-7"}[r])})]})}function An({className:t,color:n="blue"}){const[r,s]=o(".");return c((()=>{const e=setInterval((()=>{s((e=>"."===e?"..":".."===e?"...":"."))}),500);return()=>clearInterval(e)}),[]),e("span",{className:g({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 $n({message:n,className:r,color:s="blue"}){const i={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:g("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 ${i[s].dot} rounded-full animate-bounce`}),e("div",{className:`w-1.5 h-1.5 ${i[s].dot} rounded-full animate-bounce`,style:{animationDelay:"0.2s"}}),e("div",{className:`w-1.5 h-1.5 ${i[s].dot} rounded-full animate-bounce`,style:{animationDelay:"0.4s"}})]}),e("div",{className:`${i[s].text} font-medium text-xs`,children:n})]})}function En({className:n,color:r="blue",width:s="md",message:i}){const[a,l]=o(15),[d,u]=o("increasing"),[m,h]=o(.4);return c((()=>{let e,t=Date.now();const n=()=>{const r=Date.now(),s=r-t;t=r,l((e=>{const t=m*(s/16);let n="increasing"===d?e+t:e-t;return n>=85?(u("decreasing"),h(.3+.2*Math.random()),85):n<=15?(u("increasing"),h(.3+.2*Math.random()),15):(Math.random()>.99&&h((e=>Math.max(.2,Math.min(.5,e+(.1*Math.random()-.05))))),n)})),e=requestAnimationFrame(n)};return e=requestAnimationFrame(n),()=>{cancelAnimationFrame(e)}}),[d,m]),t("div",{className:g("flex flex-col gap-1",n),children:[i&&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:i}),e("div",{className:g("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:g("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:`${a}%`,transition:"width 150ms cubic-bezier(0.4, 0.0, 0.2, 1)"}})})]})}function zn({className:t,color:n="blue",size:r="md"}){const[s,i]=o(Array(7).fill(50)),a={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"}},l={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 c((()=>{let e;const t=[1.2,1,1.5,.8,1.3,.9,1.1],n=[0,.5,1,1.5,2,2.5,3];let r=0;const a=()=>{r+=.02;const l=s.map(((e,s)=>10+40*(Math.sin(r*t[s]+n[s])+1)));i(l),e=requestAnimationFrame(a)};return e=requestAnimationFrame(a),()=>{cancelAnimationFrame(e)}}),[]),e("div",{className:g("flex items-end justify-center",a[r].width,a[r].height,a[r].gap,t),children:s.map(((t,s)=>e("div",{className:g(a[r].barWidth,"rounded-full transform-gpu",l[n]),style:{height:`${t}%`,transition:"height 100ms cubic-bezier(0.4, 0.0, 0.2, 1)",opacity:.9}},s)))})}const On=["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..."];const Dn=[It.COMPLETE,It.IDLE,It.REQUEST_INPUT,It.TERMINATED];function Un(e){return e.workstream_id?(e.type===It.COMPLETE&&console.log("[getWorkstreamId] COMPLETE message with workstream_id:",e.workstream_id),e.workstream_id):(e.type===It.COMPLETE&&console.log("[getWorkstreamId] COMPLETE message without workstream_id, defaulting to 'main'"),"main")}function Ln({message:r,showPulsatingCircle:s=!1}){const[i,a]=o(!1),[l,d]=o(""),[u,m]=o(!1),{client:h}=Pt(),p=v(),f=(()=>{const t={containerClass:"bg-white border-l-4 border-l-muted/30 shadow-sm",iconComponent:e(ze,{className:"size-4 text-muted"}),sender:""};switch(r.type){case It.ANSWER:return{...t,containerClass:"bg-white border-l-4 border-l-muted/30 shadow-sm",iconComponent:e(ze,{className:"size-4 text-muted"}),sender:"Agent"};case It.COMPLETE:return{...t,containerClass:"bg-white border-l-4 border-l-success shadow-sm",iconComponent:e(Fe,{className:"size-4 text-success"}),sender:"Completed"};case It.TERMINATED:return{...t,containerClass:"bg-white border-l-4 border-l-attention shadow-sm",iconComponent:e(Fe,{className:"size-4 text-attention"}),sender:"Terminated"};case It.QUESTION:return{...t,iconComponent:e(Le,{className:"size-4 text-muted"}),sender:"User"};case It.THOUGHT:return{...t,iconComponent:s?e(In,{size:"sm",color:"blue"}):e(ze,{className:"size-4 text-muted"}),sender:"Agent"};case It.ERROR:return{...t,iconComponent:e(Ue,{className:"size-4 text-muted"}),sender:"System"};case It.UPDATE:return{...t,containerClass:"bg-white border-l-4 border-success shadow-sm",iconComponent:e(De,{className:"size-4 text-success"}),sender:"Update"};case It.PLAN:return{...t,iconComponent:e(Oe,{className:"size-4 text-muted"}),sender:"Agent"};default:return{...t,sender:"Agent"}}})(),g=()=>{let e="";if(r.message&&(e="object"==typeof r.message?JSON.stringify(r.message,null,2):r.message.trim?r.message.trim():String(r.message)),"string"==typeof e&&e.includes("%thinking_message%")){const t=Math.floor(Math.random()*On.length);e=e.replace(/%thinking_message%/g,On[t])}return e},x=r=>"object"==typeof r?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(r,null,2)}):e("div",{className:"vprose prose-sm",children:e(qt,{remarkPlugins:[Wt],components:{a:({node:t,ref:n,...r})=>{const s=r.href||"";return s.includes("/store/objects")?e(Rt,{href:s,topLevelNav:!0,children:r.children}):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&&window.open(r.src,"_blank")}),code:({node:r,ref:s,className:i,children:a,...l})=>{const o=/language-(\w+)/.exec(i||""),c=!o,d=o?o[1]:"";return t(n,{children:[!c&&d&&e("div",{className:"code-language-indicator",children:d}),e("code",{...l,children:a})]})},p:({node:t,ref:n,...r})=>e("p",{...r}),strong:({node:t,ref:n,...r})=>e("strong",{...r}),em:({node:t,ref:n,...r})=>e("em",{...r}),pre:({node:t,ref:n,...r})=>e("pre",{...r}),h1:({node:t,ref:n,...r})=>e("h1",{...r}),h2:({node:t,ref:n,...r})=>e("h2",{...r}),h3:({node:t,ref:n,...r})=>e("h3",{...r}),li:({node:t,ref:n,...r})=>e("li",{...r}),ul:({node:t,ref:n,...r})=>e("ul",{...r}),ol:({node:t,ref:n,...r})=>e("ol",{...r}),blockquote:({node:t,ref:n,...r})=>e("blockquote",{...r}),hr:({node:t,ref:n,...r})=>e("hr",{...r}),table:({node:t,ref:n,...r})=>e("div",{className:"overflow-x-auto",children:e("table",{...r})}),th:({node:t,ref:n,...r})=>e("th",{...r}),td:({node:t,ref:n,...r})=>e("td",{...r})},children:r})}),w=g();c((()=>{(async()=>{if(w){m(!0);try{const e=await(async e=>{if("string"!=typeof e)return e;let t=e;t=t.replace(/\[([^\]]+)\]\((store|collection):([a-f\d]{24})\)/gi,((e,t,n,r)=>`[${t}](/store/${"store"===n?"objects":"collections"}/${r})`));const n=Array.from(t.matchAll(/!\[([^\]]*)\]\(image:([^)]+)\)/g)),r=await Promise.all(n.map((async e=>{const[t,n,r]=e;try{return{fullMatch:t,replacement:`![${n}](${(await h.files.getDownloadUrl(r)).url})`}}catch(e){return console.error(`Failed to get download URL for image: ${r}`,e),{fullMatch:t,replacement:t}}})));for(const{fullMatch:e,replacement:n}of r)t=t.replace(e,n);return t})((e=>{if("string"!=typeof e)return e;if(r.type===It.THOUGHT||"string"==typeof r.message&&(r.message.toLowerCase().includes("thinking about")||r.message.toLowerCase().includes("i'm thinking")||r.message.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})(w));d(e)}catch(e){console.error("Error processing message content:",e),d(w)}finally{m(!1)}}})()}),[w,h]);const N=Un(r),k=(()=>{switch(r.type){case It.ANSWER:return"border-l-info bg-info";case It.COMPLETE:return"border-l-success bg-success";case It.IDLE:return"border-l-muted bg-muted";case It.REQUEST_INPUT:return"border-l-attention bg-attention";case It.QUESTION:return"border-l-muted bg-muted";case It.THOUGHT:return"border-l-accent dark:border-l-purple-500 bg-purple-50/50 dark:bg-purple-900/10";case It.ERROR:return"border-l-destructive bg-destructive";case It.UPDATE:return"border-l-success bg-success";case It.PLAN:return"border-l-attention bg-attention";case It.TERMINATED:return"border-l-muted bg-muted";default:return"border-l-indigo-500 dark:border-l-indigo-400 bg-indigo-50/50 dark:bg-indigo-900/10"}})();return t("div",{className:`border-l-4 shadow-md overflow-hidden bg-white dark:bg-gray-900 mb-5 ${k}`,"data-workstream-id":N,children:[t("div",{className:"flex items-center justify-between px-4 py-2 border-b border-gray-100/80 dark:border-gray-800/80 bg-white/50 dark:bg-gray-900/50 backdrop-blur-sm",children:[t("div",{className:"flex items-center gap-2",children:[e("div",{className:s?"animate-fadeIn":"",children:(()=>{const t=(()=>{switch(r.type){case It.ANSWER:return"text-info";case It.COMPLETE:return"text-success";case It.IDLE:return"text-muted";case It.REQUEST_INPUT:return"text-attention";case It.QUESTION:return"text-muted";case It.THOUGHT:return"text-purple-600 dark:text-purple-400";case It.ERROR:return"text-destructive";case It.UPDATE:return"text-success";case It.PLAN:return"text-attention";default:return"text-muted"}})(),n=t=>("number"==typeof r.timestamp?r.timestamp:new Date(r.timestamp).getTime())%2==0?e(In,{size:"sm",color:t}):e(Pn,{color:t});switch(r.type){case It.ANSWER:return s?n("blue"):e(ze,{className:`size-4 ${t}`});case It.COMPLETE:case It.TERMINATED:return e(Fe,{className:`size-4 ${t}`});case It.IDLE:return e(Re,{className:`size-4 ${t}`});case It.REQUEST_INPUT:case It.QUESTION:return e(Le,{className:`size-4 ${t}`});case It.THOUGHT:return s?n("purple"):e(ze,{className:`size-4 ${t}`});case It.ERROR:return e(Ue,{className:`size-4 ${t}`});case It.UPDATE:return s?n("green"):e(De,{className:`size-4 ${t}`});case It.PLAN:return s?n("amber"):e(Oe,{className:`size-4 ${t}`});default:return s?n("blue"):e(ze,{className:`size-4 ${t}`})}})()}),e("span",{className:"text-xs font-medium text-muted ",children:f.sender}),"main"!==N&&"all"!==N&&e(y,{variant:"default",className:"text-xs text-muted",children:N})]}),t("div",{className:"flex items-center gap-2",children:[e("span",{className:"text-xs text-muted",children:Vt(r.timestamp).format("HH:mm:ss")}),e(b,{variant:"ghost",size:"xs",onClick:()=>{const e=g()||"",t="string"==typeof r.details?r.details:r.details?JSON.stringify(r.details,null,2):"",n=[e,t?"\n\nDetails:\n"+t:""].join("").trim();navigator.clipboard.writeText(n).then((()=>{p({status:"success",title:"Copied to clipboard",duration:2e3})}))},className:"text-muted",title:"Copy message",children:e(Ee,{className:"size-3"})})]})]}),t("div",{className:"px-4 py-3 bg-white dark:bg-gray-900",children:[w&&e("div",{className:"message-content",children:u?t("div",{className:"flex items-center gap-2 text-sm text-gray-500",children:[e(Pn,{color:"blue"}),e("span",{children:"Loading images..."})]}):x(l||w)}),r.details&&t("div",{className:"mt-2",children:[t("button",{onClick:()=>a(!i),className:"text-xs text-muted flex items-center",children:[i?"Hide":"Show"," details",e("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-3 w-3 ml-1 transition-transform "+(i?"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"})})]}),i&&e("div",{className:"mt-2 p-2 bg-muted border border-mixer-muted/40 rounded text-sm",children:"string"==typeof r.details?x(r.details):e("pre",{className:"text-xs font-mono whitespace-pre-wrap overflow-x-auto bg-muted p-2 rounded text-muted ",children:JSON.stringify(r.details,null,2)})})]})]})]})}function Fn({workstreams:n,activeWorkstream:r,onSelectWorkstream:s,count:i,completionStatus:a}){const l=new Map;l.set("all","All Messages"),l.set("main","Main"),n.forEach(((e,t)=>{"all"!==t&&"main"!==t&&"research_france"!==t&&"statistics"!==t&&l.set(t,e)})),n=l;const o=Array.from(n.entries()).sort((([e],[t])=>"all"===e?-1:"all"===t?1:"main"===e?-1:"main"===t?1:e.localeCompare(t))),c=o.length>2;return e("div",c?{className:"flex overflow-x-auto space-x-1 mb-2 border-b-2 border-muted/20 sticky top-0 z-10 pt-1",children:o.map((([n,l])=>t("button",{className:"px-3 py-1.5 text-xs font-medium whitespace-nowrap transition-colors flex items-center gap-1.5\n "+(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:l.length>20?l:void 0,children:[l.length>20?l.substring(0,18)+"...":l,i&&i.has(n)&&i.get(n)>0&&t("div",{className:"flex items-center space-x-1",children:[e("span",{className:"inline-flex items-center justify-center size-4 text-xs rounded-full\n "+(r===n?"bg-info text-info":"bg-muted text-muted"),children:i.get(n)}),a&&"all"!==n&&(a.get(n)?e(Fe,{className:"size-3 text-success"}):e(Re,{className:"size-3 text-attention"}))]})]},n)))}:{className:"py-1"})}function Rn(e,t){return"all"===t?[...e]:"main"===t?e.filter((e=>"main"===Un(e))):e.filter((e=>Un(e)===t))}function Mn({messages:r,bottomRef:s,viewMode:i="stacked",isCompleted:d=!1}){const u=a.useRef(null),[m,h]=o("all");c((()=>{s.current&&s.current.scrollIntoView({behavior:"smooth"})}),[r,s]);const p=a.useMemo((()=>[...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())))),[r]),f=a.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}(p);return e}),[p]),g=a.useMemo((()=>{const e=new Map;e.set("all",p.length);const t=Rn(p,"main");return e.set("main",t.length),p.forEach((t=>{const n=Un(t);"main"!==n&&e.set(n,(e.get(n)||0)+1)})),e}),[p]),v=a.useMemo((()=>"all"===m?p:Rn(p,m)),[p,m]),y=l((()=>{const e=new Map,t=new Map;p.forEach((e=>{const n=Un(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,[It.COMPLETE,It.IDLE,It.REQUEST_INPUT,It.TERMINATED].includes(t.type))}return e}),[p]);return t("div",{ref:u,className:"flex-1 min-h-0 h-full overflow-y-auto py-2 px-4 sm:px-6 lg:px-8 flex flex-col relative","data-testid":"all-messages-mixed",children:[e("div",{className:"sticky top-0 z-10",children:e(Fn,{workstreams:f,activeWorkstream:m,onSelectWorkstream:h,count:g,completionStatus:y})}),0===v.length?e("div",{className:"flex items-center justify-center h-full text-center py-8",children:e("div",{className:"flex items-center px-4 py-3 text-muted",children:"all"===m?"Waiting for agent response...":"No messages in this workstream yet..."})}):t("div",{className:"flex-1 flex flex-col justify-start pb-4 space-y-2",children:["stacked"===i?v.map(((t,n)=>{const r=!d&&n===v.length-1&&!Dn.includes(t.type);return e(Ln,{message:t,showPulsatingCircle:r},`${t.timestamp}-${n}`)})):e(n,{children:(()=>{const t=v.filter((e=>e.type===It.ANSWER||e.type===It.QUESTION||e.type===It.COMPLETE||e.type===It.TERMINATED)),n=d?null:v.filter((e=>e.type===It.THOUGHT||e.type===It.UPDATE||e.type===It.PLAN)).sort(((e,t)=>{const n="number"==typeof e.timestamp?e.timestamp:new Date(e.timestamp).getTime();return("number"==typeof t.timestamp?t.timestamp:new Date(t.timestamp).getTime())-n}))[0],r=[...t];return n&&r.push(n),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()))),r.map(((t,n)=>{const s=!d&&n===r.length-1&&!Dn.includes(t.type);return e(Ln,{message:t,showPulsatingCircle:s},`${t.timestamp}-${n}`)}))})()}),e("div",{ref:s,className:"h-4"})]})]})}class Vn{vertesia;updateState;_interactive=!0;_debug_mode=!1;_collection;_start=!1;_preserveRunValues=!1;payload;_interactionParamsSchema;_inputValidator;constructor(e,t){this.vertesia=e,this.updateState=t,this.payload={config:{model:""},tool_names:[]}}onStateChanged(){const e=this.clone();this.updateState(e)}clone(){const e=new Vn(this.vertesia,this.updateState);return e._interactionParamsSchema=this._interactionParamsSchema,e.payload=this.payload,e._interactive=this._interactive,e._debug_mode=this._debug_mode,e._inputValidator=this._inputValidator,e._start=this._start,e._collection=this._collection,e._preserveRunValues=this._preserveRunValues,e}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 collection(){return this._collection}set collection(e){e!==this._collection&&(this._collection=e,this.onStateChanged())}get search_scope(){return this._collection?"collection":void 0}get interaction(){return this.payload.interaction}set interaction(e){e?.id!==this.payload.interaction?.id&&(this.payload.interaction=e,this._interactionParamsSchema=At(this.interaction),this._inputValidator=void 0,e&&!this._preserveRunValues&&(e.environment&&("string"==typeof e.environment?this.vertesia.environments.retrieve(e.environment).then((e=>this.environment=e)):this.payload.config.environment=e.environment),e.model?this.payload.config.model=e.model:this.payload.config.model=this.environment?.default_model&&$t(this.environment.default_model,this.environment.provider)?this.environment.default_model:void 0),this.onStateChanged())}get environment(){return this.payload.config.environment}set environment(e){if(e?.id!==this.payload.config.environment?.id){if(this.payload.config.environment=e,!this._preserveRunValues){const t=this.payload.interaction?.model;t&&e&&$t(t,e.provider)?this.payload.config.model=t:this.payload.config.model=e?.default_model&&$t(e.default_model,e.provider)?e.default_model:void 0}this.onStateChanged()}}get model(){return this.payload.config.model}set model(e){e!==this.payload.config.model&&(this.payload.config.model=e,this.onStateChanged())}get tool_names(){return this.payload.tool_names}set tool_names(e){this.payload.tool_names=e,this.onStateChanged()}get data(){return this.payload.data}set data(e){this.payload.data=e,this.onStateChanged()}get config(){return this.payload.config}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,this.onStateChanged())}reset(){if(this._start=!1,this._interactive=!0,this._debug_mode=!1,this._collection=void 0,this._preserveRunValues=!1,this.payload={config:{environment:void 0,model:""},tool_names:[],interaction:void 0,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 Bt({strict:!1});this._inputValidator={validate:e.compile(this._interactionParamsSchema),schema:this._interactionParamsSchema}}const e=this.payload.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 qn=d(void 0);function Wn({children:t}){const{client:n}=Pt(),[r,s]=o();return c((()=>{s(new Vn(n,s))}),[]),r&&e(qn.Provider,{value:r,children:t})}function Bn(){const e=u(qn);if(!e)throw new Error("usePayloadBuilder must be used within a PayloadProvider");return e}function Gn({title:n,onClose:r,isModal:s,run:i,viewMode:a,onViewModeChange:l,showPlanPanel:o,hasPlan:c=!1,onTogglePlanPanel:d,onDownload:u,onCopyRunId:m,resetWorkflow:h}){return e(Wn,{children:t("div",{className:"flex items-center justify-between py-1.5 px-2 border-b shadow-sm flex-shrink-0",children:[t("div",{className:"flex flex-wrap items-center space-x-2",children:[t("div",{className:"flex items-center space-x-1",children:[e(ze,{className:"size-5 text-muted"}),e("span",{className:"font-medium",children:n})]}),t("span",{className:"text-xs text-muted ml-1",children:["(Run ID: ",i.runId.substring(0,8),"...)"]})]}),t("div",{className:"flex items-center space-x-2",children:[t("div",{className:"flex items-center space-x-1 bg-muted rounded p-0.5",children:[e(b,{variant:"stacked"===a?"outline":"ghost",size:"xs",className:"rounded-l-md",onClick:()=>l("stacked"),children:"Details"}),e(b,{variant:"sliding"===a?"outline":"ghost",size:"xs",className:"rounded-l-md",onClick:()=>l("sliding"),children:"Most Important"})]}),t("div",{className:"relative",children:[c&&!o&&e("span",{className:"absolute -top-1 -right-1 w-2.5 h-2.5 bg-primary rounded-full border border-border z-10"}),t(b,{size:"sm",variant:o?"primary":"secondary",onClick:d,className:"transition-all duration-200 rounded-md",title:"Toggle plan panel",children:[e(Me,{className:"size-4 mr-1.5"}),e("span",{className:"font-medium text-xs",children:o?"Hide Plan":"Show Plan"})]})]}),e(Jn,{run:i,isModal:s,onClose:r,onDownload:u,onCopyRunId:m,resetWorkflow:h}),r&&!s&&e(b,{size:"xs",variant:"ghost",onClick:r,children:e(Ve,{className:"size-4"})})]})]})})}function Jn({run:n,isModal:r,onClose:s,onDownload:i,onCopyRunId:a,resetWorkflow:l}){const o=v(),{client:c}=Pt(),d=Bn();return t(x,{hover:!0,children:[e(w,{children:e(b,{size:"xs",variant:"ghost",title:"More actions",children:e(qe,{className:"size-4"})})}),e(N,{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(k,{children:e(C,{children:t(j,{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(S,{className:"text-xs",onSelect:()=>{return e=`/store/agent-runner?agentId=${n.runId}__${n.workflowId}`,window.open(e,"_blank"),e;var e},children:[e(We,{className:"size-3.5 mr-2 text-muted"})," Open in new tab"]}),t(S,{className:"text-xs",onSelect:()=>{a?a():(navigator.clipboard.writeText(n.runId),o({status:"success",title:"Run ID copied",duration:2e3}))},children:[e(Ee,{className:"size-3.5 mr-2 text-muted"})," Copy Run ID"]}),t(S,{className:"text-xs",onSelect:()=>{i?i():async function(e,t){return e.files.getDownloadUrl(`agents/${t}/conversation.json`).then((e=>e.url))}(c,n.runId).then((e=>window.open(e,"_blank")))},children:[e(Be,{className:"size-3.5 mr-2 text-muted"})," Download Conversation"]}),s&&r&&t(S,{className:"text-xs",onSelect:s,children:[e(Ve,{className:"size-3.5 mr-2 text-muted"})," Close"]}),t(S,{className:"text-xs text-destructive",onSelect:()=>{(async e=>{try{return await c.store.workflows.terminate(e.workflowId,e.runId,"cancel"),o({status:"success",title:"Workflow cancelled",duration:2e3}),d.reset(),l?.(),!0}catch(e){return o({status:"error",title:"Failed to cancel workflow",duration:2e3}),!1}})(n)},children:[e(Ve,{className:"size-3.5 mr-2 text-destructive"})," Cancel Workflow"]})]})})})})})})]})}const Hn="vertesia.content_store.lastDisplayedView";function Kn({onUpdate:t}){const[n,r]=o("grid"===localStorage.getItem(Hn)),s=()=>{localStorage.setItem(Hn,"grid"),r(!0),t(!0)},i=()=>{localStorage.setItem(Hn,"table"),r(!1),t(!1)};return e(b,{variant:"outline",onClick:()=>{n?i():s()},alt:n?"Table View":"Thumbnail View",children:e(n?Ge:Je,{})})}Kn.LAST_DISPLAYED_VIEW=Hn;class Yn extends z{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 Qn({isOpen:n,onClose:r,onConfirm:s,isLoading:i,uploadedFileName:a}){const l=[{id:"update",label:"Update current version",description:a?"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:a?"Create a new revision with the replacement file while preserving the original.":"Create a new revision with these property changes while preserving the original."}],d=a?l[1]:l[0],[u,m]=o(d),[h,p]=o(""),f=new Yn;c((()=>{n&&(m(d),p(""))}),[n,a]);const g="new-version"===u?.id;return t(_,{isOpen:n,onClose:r,className:"sm:max-w-md",children:[e(T,{children:"Save Changes"}),e(P,{children:t("div",{className:"space-y-4",children:[a&&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:a})]})}),e("p",{className:"text-sm text-mixer-muted/5",children:"How would you like to save these changes?"}),e(I,{adapter:f,options:l,value:u,onChange:e=>{m(e)},gap:"gap-4"}),g&&e(A,{label:"Version Label (Optional)",description:"Optional label for the new version.",className:"mt-3 pl-8",children:e($,{value:h,onChange:p,placeholder:"e.g., v1.2, approved, post-review",className:"w-full"})})]})}),t(E,{children:[e(b,{variant:"secondary",onClick:r,disabled:i,children:"Cancel"}),e(b,{variant:"primary",onClick:async()=>{await s(g,g?h:void 0)},isLoading:i,children:"Save"})]})]})}function Xn({isOpen:r,onClose:s,object:i,refetch:a}){const{client:l,store:d}=Pt(),u=v(),h=Mt(),[p,f]=o(!1),[g,y]=o(""),[x,w]=o(!1),[N,k]=o(null),C=m(null),j=m(null),[S,I]=o(null),[A,$]=o(null);function z(e,t){e.languages.json.jsonDefaults.setDiagnosticsOptions({validate:!0,schemas:[{uri:"http://myserver/object-schema.json",fileMatch:["*"],schema:t}]})}return c((()=>{r&&(y(JSON.stringify(i.properties||{},null,2)),i.type?.id&&async function(e){try{const t=await d.types.retrieve(e);t.object_schema&&(I(t.object_schema),j.current&&z(j.current,t.object_schema))}catch(e){console.error("Failed to fetch JSON schema:",e)}}(i.type.id))}),[r,i]),t(n,{children:[t(_,{isOpen:r,onClose:s,className:"sm:max-w-[90%] md:max-w-[80%] lg:max-w-[75%] xl:max-w-[70%]",children:[e(T,{children:"Edit Properties"}),t(P,{children:[t("div",{className:"mb-2 text-sm text-gray-500",children:[i.type?.name?t("span",{children:["Editing properties for object type: ",e("strong",{children:i.type.name})]}):e("span",{children:"Editing properties for generic document"}),S&&e("span",{className:"ml-2 text-green-600",children:"(JSON schema validation enabled)"})]}),e("div",{className:"h-[75vh] border border-gray-300 dark:border-gray-700 rounded-md",children:e(an,{height:"100%",language:"json",value:g,onChange:e=>y(e||""),onMount:function(e,t){C.current=e,j.current=t,S&&z(t,S)},options:{minimap:{enabled:!1},scrollBeyondLastLine:!1,formatOnPaste:!0,formatOnType:!0,automaticLayout:!0,wordWrap:"on"}})})]}),t(E,{children:[e(b,{variant:"secondary",onClick:s,children:"Cancel"}),e(b,{variant:"primary",onClick:function(){if(!C.current)return;const e=C.current.getValue();try{const t=JSON.parse(e);k(t),w(!0)}catch(e){u({status:"error",title:"Invalid JSON",description:"Please fix the JSON syntax errors before saving.",duration:5e3})}},children:"Save Changes"})]})]}),e(Qn,{isOpen:x,onClose:function(){w(!1)},onConfirm:async function(e,t){try{f(!0);const n=N||JSON.parse(g);if(e){const e=await l.objects.update(i.id,{properties:n},{createRevision:!0,revisionLabel:t});e.id!==i.id&&$(e.id),u({status:"success",title:"New version created",description:"A new version with updated properties has been created.",duration:2e3}),w(!1),s(),e.id!==i.id&&setTimeout((()=>{h(`/objects/${e.id}`),u({status:"info",title:"Viewing New Version",description:t?`Now viewing version '${t}'`:"Now viewing the new version",duration:3e3})}),100)}else await d.objects.update(i.id,{properties:n}),u({status:"success",title:"Properties updated",description:"The object properties have been updated successfully.",duration:2e3}),a&&await a(),w(!1),s()}catch(e){u({status:"error",title:"Error updating properties",description:e.message||"An error occurred while updating the properties.",duration:5e3}),f(!1)}},isLoading:p})]})}const Zn=131072;var er;function tr({object:r,loadText:s,refetch:i}){const a=v(),l=async(e,t)=>{try{await navigator.clipboard.writeText(e),a({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),a({status:"error",title:"Copy failed",description:`Failed to copy ${t} to clipboard`,duration:5e3})}};return e(n,{children:t(O,{direction:"horizontal",className:"h-[calc(100vh-200px)]",children:[e(D,{className:"min-w-[100px]",children:e(nr,{object:r,refetch:i??(()=>Promise.resolve()),handleCopyContent:l})}),e(U,{withHandle:!0}),e(D,{className:"min-w-[100px]",children:e(rr,{object:r,loadText:s??!1,handleCopyContent:l})})]})})}function nr({object:r,refetch:s,handleCopyContent:i}){const[a,l]=o(!1),[c,d]=o(!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(b,{variant:""+(a?"ghost":"primary"),size:"sm",alt:"Preview properties",onClick:()=>l(!a),children:"Properties"}),e(b,{variant:""+(a?"primary":"ghost"),size:"sm",alt:"View in JSON format",onClick:()=>l(!a),children:"JSON"})]}),t("div",{className:"flex items-center gap-2",children:[r.properties&&e(b,{variant:"ghost",size:"sm",title:"Copy properties",onClick:()=>i(JSON.stringify(r.properties,null,2),"properties"),children:e(Ke,{className:"size-4"})}),e(b,{variant:"ghost",size:"sm",onClick:()=>{d(!0)},title:"Edit properties",className:"flex items-center gap-2",children:e(Ye,{className:"size-4"})})]})]}),r.properties?e("div",{className:"h-[calc(100vh-220px)] overflow-auto px-2",children:e(Ht,{value:r.properties,viewCode:a})}):e("div",{className:"h-[calc(100vh-220px)] overflow-auto px-2",children:e("div",{children:"No properties defined"})}),e(Xn,{isOpen:c,onClose:()=>{d(!1)},object:r,refetch:s})]})}function rr({object:r,loadText:s,handleCopyContent:i}){const{store:a}=Pt(),l=r?.metadata?.type===Et.Image,d=r?.metadata?.type===Et.Video,[u,m]=o(d?er.Video:l?er.Image:er.Text),[h,p]=o(r.text),[f,g]=o(!1),[v,y]=o(!1);return c((()=>{s&&!h&&(g(!0),a.objects.getObjectText(r.id).then((e=>{if(e.text.length>Zn){const t=e.text.substring(0,Zn);p(t),y(!0)}else p(e.text),y(!1)})).catch((e=>{console.error("Failed to load text",e)})).finally((()=>{g(!1)})))}),[s]),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:[l&&e(b,{variant:u===er.Image?"primary":"ghost",size:"sm",alt:"View Image",onClick:()=>m(er.Image),children:"Image"}),d&&e(b,{variant:u===er.Video?"primary":"ghost",size:"sm",alt:"View Video",onClick:()=>m(er.Video),children:"Video"}),e(b,{variant:u===er.Text?"primary":"ghost",size:"sm",alt:"View Text",onClick:()=>m(er.Text),children:"Text"})]}),u===er.Text&&e(sr,{object:r,text:h,handleCopyContent:i})]}),u===er.Image?e(ar,{object:r}):u===er.Video?e(lr,{object:r}):f?e("div",{className:"flex justify-center items-center h-[calc(100vh-260px)]",children:e(L,{size:"lg"})}):e(ir,{object:r,text:h,isTextCropped:v})]})}function sr({object:r,text:s,handleCopyContent:i}){const{client:a}=Pt(),l=v(),[c,d]=o(null),u=r.content,m=u&&u.type&&"text/markdown"===u.type,h=async e=>{if(!c){d(e),l({status:"info",title:`Preparing ${e.toUpperCase()}`,description:"Fetching your document...",duration:2e3});try{const t=await a.objects.getRendition(r.id,{format:e,generate_if_missing:!0,sign_url:!0});if("generating"===t.status)return l({status:"info",title:"Generating document",description:`Please wait while we prepare your ${e.toUpperCase()} file...`,duration:5e3}),void setTimeout((()=>h(e)),3e3);if("failed"===t.status)throw new Error("Document generation failed");if(t.renditions&&t.renditions.length>0){const n=t.renditions[0];if("pdf"===e)window.open(n,"_blank"),l({status:"success",title:"PDF opened",description:"PDF document opened in a new window",duration:2e3});else{const t=document.createElement("a");t.href=n,t.download=`${r.name||"document"}.${e}`,document.body.appendChild(t),t.click(),document.body.removeChild(t),l({status:"success",title:"Document exported",description:`Successfully exported to ${e.toUpperCase()} format`,duration:2e3})}}}catch(t){console.error(`Failed to export document as ${e}:`,t),l({status:"error",title:"Export failed",description:`Failed to export document to ${e.toUpperCase()} format`,duration:5e3})}finally{d(null)}}};return e("div",{className:"h-[41px] text-lg font-semibold flex justify-between items-center px-2",children:t("div",{className:"flex items-center gap-2",children:[s&&e(b,{variant:"ghost",size:"sm",title:"Copy text",className:"flex items-center gap-2",onClick:()=>i(s,"text"),children:e(Ke,{className:"size-4"})}),m&&s&&t(n,{children:[t(b,{variant:"ghost",size:"sm",onClick:()=>h("docx"),disabled:null!==c,className:"flex items-center gap-2",children:["docx"===c?e(L,{size:"sm"}):e(Qe,{className:"size-4"}),"DOCX"]}),t(b,{variant:"ghost",size:"sm",onClick:()=>h("pdf"),disabled:null!==c,className:"flex items-center gap-2",children:["pdf"===c?e(L,{size:"sm"}):e(Qe,{className:"size-4"}),"PDF"]})]})]})})}!function(e){e.Text="text",e.Image="image",e.Video="video"}(er||(er={}));const ir=h((({object:r,text:s,isTextCropped:i})=>{const a=r.content,l=a&&a.type&&("text/markdown"===a.type||"text/plain"===a.type),o=s&&(s.includes("\n# ")||s.includes("\n## ")||s.includes("\n### ")||s.includes("\n* ")||s.includes("\n- ")||s.includes("\n+ ")||s.includes("![")||s.includes("](")),c=l||o;return s?t(n,{children:[i&&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(He,{className:"size-4"}),e("span",{className:"text-sm font-semibold",children:"Showing first 128K characters only"})]})}),e("div",{className:"max-w-7xl px-2 h-[calc(100vh-210px)] overflow-auto",children:c?e("div",{className:"vprose prose-sm p-1",children:e(Jt,{components:{a:({node:t,...n})=>{const r=n.href||"";return r.includes("/store/objects/")?e(Rt,{topLevelNav:!0,href:r,className:"text-info",children:n.children}):e("a",{...n,"data-debug":"test",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 i=/language-(\w+)/.exec(n||"");return e("code",{...s,className:!i?"px-1.5 py-0.5 rounded":"text-muted",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:"No content"})})}));function ar({object:t}){const{client:n}=Pt(),[r,s]=o(),i=t.content,a=t.metadata&&t.metadata.type===Et.Image;return c((()=>{if(a){(async()=>{const e=i?.type&&["image/jpeg","image/jpg","image/png","image/gif","image/webp","image/svg+xml"].includes(i.type);try{const r=await n.objects.getRendition(t.id,{format:Ot.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)}}})()}}),[]),e("div",{className:"mb-4 px-2",children:r?e("img",{src:r,alt:t.name,className:"w-full object-contain"}):e(L,{size:"md"})})}function lr({object:n}){const{client:r}=Pt(),[s,i]=o(),[a,l]=o(),[d,u]=o(!0),m=n.content,h=n.metadata?.type===Et.Video,p=n.metadata,f=p?.renditions||[],g=f.find((e=>"video/mp4"===e.content.type))||f.find((e=>"video/webm"===e.content.type)),v=m?.type&&["video/mp4","video/webm"].includes(m.type),y=f.find((e=>e.name===zt));return c((()=>{(async()=>{if(y?.content?.source)try{const e=await r.files.getDownloadUrl(y.content.source);l(e.url)}catch(e){console.error("Failed to load poster image",e)}})()}),[y,r]),c((()=>{if(h&&(g?.content?.source||v)){(async()=>{try{let e;g?.content?.source?e=await r.files.getDownloadUrl(g.content.source):v&&m?.source&&(e=await r.files.getDownloadUrl(m.source)),e&&i(e.url)}catch(e){console.error("Failed to get video URL",e)}finally{u(!1)}})()}else u(!1)}),[h,g,v,m?.source,r]),e("div",{className:"mb-4 px-2",children:g||v?d?e("div",{className:"flex justify-center items-center h-[400px]",children:e(L,{size:"md"})}):s?e("video",{src:s,poster:a,controls:!0,className:"w-full max-h-[calc(100vh-260px)] 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 or(e,t=7){return e?"~"+e.slice(-t):""}function cr(e,t){return e.length>t?e.substring(0,t)+"...":e}const dr="text/csv",ur="image/",mr="application/pdf",hr="video/",pr=e=>e===dr||dr.includes(e),fr=e=>e.startsWith(ur)||ur.includes(e),gr=e=>e===mr||mr.includes(e),vr=e=>e.startsWith(hr)||hr.includes(e),yr=import.meta.env,br={max_hw:yr?.VITE_RENDITION_HW||256,format:Ot.jpeg,generate_if_missing:!0},xr="vertesia.content_store.renditionId";async function wr(e,t,n,r,s){if(!t?.content?.type||!(fr(t.content.type)||vr(t.content.type)||gr(t.content.type)))return void s("No preview available");s("Preparing preview...");const i=(new Date).getTime()/1e3,a=localStorage.getItem(`${xr}_${t.id}_${br.max_hw}`),l=localStorage.getItem(`${xr}_${t.id}_${br.max_hw}_time`);if(a?.length&&l&&Math.abs(i-parseInt(l))<=900)return n(a),r(`${t.name} Rendition`),s("ready"),a;s("Preparing preview..."),e.objects.getRendition(t.id,br).then((i=>{if("generating"===i.status)s("Preparing preview..."),n(""),r(""),setTimeout((()=>wr(e,t,n,r,s)),6e4);else{if("failed"===i.status)return s("No preview available"),n(""),void r("");{if(!i?.renditions?.length)return s("No preview available"),n(""),void r("");const e=i.renditions[0];localStorage.setItem(`${xr}_${t.id}_${br.max_hw}`,e),localStorage.setItem(`${xr}_${t.id}_${br.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 Nr({isLoading:n=!1,counts:r=6}){return n?e("div",{className:"flex flex-wrap gap-2 justify-between",children:Array(r).fill(0).map(((n,r)=>e("div",{className:"w-[15vw] animate-pulse",children:t(F,{className:"relative flex flex-col border h-fit",children:[e("div",{className:"h-48 bg-muted rounded-t-xl flex items-center justify-center text-muted",children:" "}),e(R,{className:"bg-muted h-[2px]"}),t(M,{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 kr({selection:n,document:r,onSelectionChange:s,onRowClick:i,previewObject:a,selectedObject:l}){const{client:d}=Pt(),[u,m]=o(void 0),[h,p]=o(void 0),[f,g]=o(void 0);return c((()=>{r?.content&&wr(d,r,m,p,g)}),[r]),t(F,{className:"relative flex flex-col border h-fit "+(l?.id===r.id?"border-attention border-4":""),onClick:()=>i&&i(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(b,{variant:"ghost",size:"sm",title:"Preivew Object",onClick:e=>{e.stopPropagation(),a?.(r.id)},children:e(Xe,{className:"size-4 "+("ready"===f?"text-muted":"text-white")})})}),u&&"ready"==f?e("img",{src:u,alt:h,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:f}),e(R,{className:"bg-gray-200 h-[2px]"}),t(M,{className:"p-2 flex flex-col",children:[t("div",{className:"flex flex-col overflow-hidden",children:[e(V,{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(V,{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 Cr(e){return`${e._id} (${e.count})`}function jr(e){return`${e.name} (${e.count})`}function Sr({search:t,buckets:n,name:r,placeholder:s,className:i}){const a=t.getFilterValue(r),l=n?.find((e=>JSON.stringify(e._id)===JSON.stringify(a)));return e(q,{filterBy:"_id",className:i,isClearable:!0,optionLabel:Cr,options:n,value:l,onChange:e=>{t.setFilterValue(r,e?._id)},by:"_id",placeholder:s})}function _r({search:t,name:n,placeholder:r,className:s}){const[i,a]=o([]);return c((()=>{t.setFilterValue(n,i)}),[i]),e(W,{className:s,value:i,onChange:a,placeholder:r})}function Tr(e){return`${e.name} (${e.count})`}function Pr({search:t,buckets:n,placeholder:r="Filter by Type",className:s}){const[i,a]=o([]),{typeRegistry:l}=Pt(),d=t.getFilterValue("type");c((()=>{if(l){const e=n.map((e=>{let t;return null==e._id?(e._id="Document",t="Document"):(t=l.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))),a(e)}}),[n,l]);const u=i?.find((e=>e._id===d));return e(q,{filterBy:"name",className:s,isClearable:!0,optionLabel:Tr,options:i,value:u,onChange:e=>{t.setFilterValue("type",e?._id)},by:"_id",placeholder:r})}function Ir({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:Cr(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 Ar({buckets:n,typeRegistry:r,type:s="select",multiple:i=!1}){const a=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)),a.set(n,{name:t,count:e.count})}));return{name:"types",placeholder:"Types",type:s,multiple:i,options:n.map((e=>{const t=e._id,n=t||"Document",r=a.get(n);return{value:t,label:r?`${r.name} (${r.count})`:`Unknown (${e.count})`}})),labelRenderer:n=>{const r=a.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=a.get(e);return n?n.name.toLowerCase().includes(t.toLowerCase()):(console.warn(`Type name not found for ${e}`),!1)}}}const $r={},Er={};function zr(e){const{client:t}=Pt();return B((()=>{let n=$r[e];return n||(n=t.users.retrieve(e).then((e=>e)),$r[e]=n),n}),[e])}function Or(e){const{client:t}=Pt();return B((()=>{let n=Er[e];return n||(n=t.iam.groups.retrieve(e).then((e=>e)),Er[e]=n),n}),[e])}function Dr(){return e("div",{className:"size-8"})}function Ur({showTitle:n=!1,size:r="md"}){return e(Br,{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(G,{src:"/icon.svg",size:r}),n&&e("div",{className:"text-sm font-semibold pl-2",children:"System User"})]})})}function Lr({accountId:r,showTitle:s=!1,size:i="md"}){const a=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(Br,{title:"Service Account",description:a,children:t("div",{className:"flex flex-row items-center gap-2",children:[e(G,{src:"/cloud.svg",name:"SA",color:"bg-amber-500",className:"px-[5px] text-white",size:i}),s&&t("div",{className:"text-sm font-semibold pl-2 truncate",children:["Service Account : ",r]})]})})}function Fr({title:t="Error",error:n,showTitle:r=!1,size:s="md"}){return e(Mr,{title:t,message:"string"==typeof n?n:n.message,color:"bg-red-500",showTitle:r,size:s})}function Rr({userRef:t,showTitle:n=!1,size:r="md"}){if(!t)return e(Mr,{title:"Unknown User",message:"User information is not available.",showTitle:n,size:r});const[s,i]=t?t.split(":"):["unknown"];switch(s){case Dt.User:return e(qr,{userId:i,showTitle:n,size:r});case Dt.Group:return e(Vr,{userId:i,showTitle:n,size:r});case"system":return e(Ur,{showTitle:n,size:r});case Dt.ServiceAccount:return e(Lr,{accountId:i,showTitle:n,size:r});case Dt.ApiKey:return e(Wr,{keyId:i,size:r,showTitle:n});default:return e(Fr,{title:"Unknown User",error:`Invalid user ref type: ${s}`,showTitle:n,size:r})}}function Mr({title:n,message:r,color:s,size:i="md",showTitle:a=!1}){return e(Br,{title:n,description:r,children:t("div",{className:"flex flex-row items-center gap-2",children:[e(G,{color:s,size:i}),a&&e("div",{className:"text-sm font-semibold pl-1",children:n})]})})}function Vr({userId:n,showTitle:r=!1,size:s="md"}){const{data:i,error:a}=Or(n);if(a)return e(Fr,{title:"Failed to fetch group",error:a,showTitle:r,size:s});if(!i)return e(Dr,{});const l=t("div",{className:"space-y-1",children:[i.description&&e("div",{className:"text-sm",children:i.description}),t("div",{className:"text-xs text-muted-foreground",children:["Group ID: ",i.id]}),i.tags&&i.tags.length>0&&e("div",{className:"flex flex-wrap gap-1",children:i.tags.map((t=>e("span",{className:"px-1.5 py-0.5 bg-muted rounded text-xs",children:t},t)))})]});return e(Br,{title:i.name||"Unnamed Group",description:l,children:t("div",{className:"flex flex-row items-center gap-2",children:[e(Ze,{className:"size-6 text-indigo-500",size:s}),r&&e("div",{className:"text-sm font-semibold pl-2",children:i.name||"Unnamed Group"})]})})}function qr({userId:n,showTitle:r=!1,size:s="md"}){const{data:i,error:a}=zr(n);if(a)return e(Fr,{title:"Failed to fetch user",error:a,showTitle:r,size:s});if(!i)return e(Dr,{});const l=e("div",{className:"truncate",title:i.email,children:i.email});return e(Br,{title:i.name||i.email||i.username||"unknown",description:l,children:t("div",{className:"flex flex-row items-center gap-2",children:[e(G,{src:i.picture,name:i.name,color:"bg-indigo-500",size:s}),r&&e("div",{className:"text-sm font-semibold pl-2",children:i.name||i.email||i.username||"unknown"})]})})}function Wr({keyId:n,showTitle:r=!1,size:s="md"}){const{client:i}=Pt(),{data:a,error:l}=B((()=>i.apikeys.retrieve(n)),[]);if(l)return e(Fr,{title:"Failed to fetch the apikey",error:l,showTitle:r,size:s});if(!a)return e(Dr,{});const o=e(G,{name:"PK",color:"bg-pink-500",size:s}),c=t(J,{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:a?.name})]}),t("tr",{children:[e("td",{className:"font-semibold w-20",children:"Account:"}),e("td",{className:"truncate max-w-0",children:a?.account})]}),t("tr",{children:[e("td",{className:"font-semibold w-20",children:"Project:"}),e("td",{className:"truncate max-w-0",children:a?.project.name})]})]});return e(Br,{title:"Private Key",description:c,children:t("div",{className:"flex flex-row items-center gap-2",children:[o,r&&e("div",{className:"text-sm font-semibold",children:a?.name||a?.account||a?.project.name||"unknown"})]})})}function Br({title:n,description:r,children:s}){return t(x,{hover:!0,children:[e(w,{className:"cursor-pointer flex items-center inline-block",children:e("div",{children:s})}),e(N,{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 Gr({buckets:n,name:r,placeholder:s}){return function({buckets:n,name:r,placeholder:s}){const i=n.map((e=>({value:e._id,label:`(${e.count})`})));return{name:r,placeholder:s||`${r.charAt(0).toUpperCase()+r.slice(1)}`,options:i,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(Rr,{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 Jr({search:t,buckets:n,placeholder:r="All Environments",className:s}){const{client:i}=Pt(),[a,l]=o([]),d=t.getFilterValue("environment");c((()=>{if(i){const e=n.map((async e=>{let t;return await i.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))),l(e)}))}}),[n,i]);const u=a?.find((e=>e._id===d));return e(q,{filterBy:"name",className:s,isClearable:!0,optionLabel:jr,options:a,value:u,onChange:e=>{t.setFilterValue("environment",e?._id)},by:"_id",placeholder:r})}function Hr(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)),i=s?.name||r;let a="success";if(s?.status)switch(s.status){case Ut.published:a="success";break;case Ut.archived:a="destructive";break;default:a="attention"}const l=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:i}),l&&e(y,{variant:a,className:"text-xs w-fit",children:l})]}),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: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=Ir({buckets:n.models||[],name:"model"});r.push(e)}if(n.statuses){const e=Ir({buckets:n.statuses||[],name:"status"});r.push(e)}if(n.finish_reason){const e=Ir({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=Gr({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 Kr(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 Yr({facets:n,search:r}){const[s,i]=o([]),a=Hr(n),l=Kr(r);return t(H,{filterGroups:a,filters:s,setFilters:e=>{const t="function"==typeof e?e(s):e;i(t),l(t)},children:[t("div",{className:"flex justify-between mb-1",children:[e(K,{}),e(b,{onClick:()=>{r.search()},variant:"outline",title:"Refresh",children:e(et,{className:"size-5"})})]}),t("div",{className:"flex gap-2 items-center",children:[e(Y,{}),e(Q,{})]})]})}function Qr(e){const t=[];if(t.push({placeholder:"Workflow or Run ID",name:"name",type:"text",options:[]}),e.status){const n=Ir({buckets:e.status||[],name:"status",placeholder:"Status"});t.push(n)}if(e.initiated_by){const n=Gr({buckets:e.initiated_by||[],name:"initiated_by",placeholder:"Initiated By"});t.push(n)}t.push({name:"start",placeholder:"Date After",type:"date",multiple:!1});return t.push({name:"end",placeholder:"Date Before",type:"date",multiple:!1}),t}function Xr(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,"name"===n?(e.query.search_term=r,e.query.name=r):e.query[n]=r}})),e.search()):e.clearFilters()}}function Zr({facets:n,search:r}){const[s,i]=o([]),a=Qr(n),l=Xr(r);return e(H,{filterGroups:a,filters:s,setFilters:e=>{const t="function"==typeof e?e(s):e;i(t),l(t)},children:t("div",{className:"flex gap-2 items-center",children:[e(K,{}),e(Y,{}),e(Q,{})]})})}function es(e){const{typeRegistry:t}=Pt(),n=[];if(n.push({placeholder:"ID",name:"id",type:"text",options:[]}),n.push({placeholder:"Name",name:"name",type:"text",options:[]}),e.type){const r=Ar({buckets:e.type||[],typeRegistry:t,type:"select",multiple:!0});n.push(r)}if(e.status){const t=Ir({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 ts(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 ns({facets:n,search:r}){const[s,i]=o([]),a=es(n),l=ts(r);return e(H,{filterGroups:a,filters:s,setFilters:e=>{const t="function"==typeof e?e(s):e;i(t),l(t)},children:t("div",{className:"flex gap-2 items-center",children:[e(K,{}),e(Y,{}),e(Q,{})]})})}function rs(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 ss(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 is({facets:n,search:r}){const[s,i]=o([]),a=rs(),l=ss(r);return e(H,{filterGroups:a,filters:s,setFilters:e=>{const t="function"==typeof e?e(s):e;i(t),l(t)},children:t("div",{className:"flex gap-2 items-center",children:[e(K,{}),e(Y,{}),e(Q,{})]})})}function as(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 ls(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 os({facets:n,search:r}){const[s,i]=o([]),a=as(n),l=ls(r);return e(H,{filterGroups:a,filters:s,setFilters:e=>{const t="function"==typeof e?e(s):e;i(t),l(t)},children:t("div",{className:"flex gap-2 items-center",children:[e(K,{}),e(Y,{}),e(Q,{})]})})}function cs(e){const{typeRegistry:t}=Pt(),n=[];if(n.push({name:"name",placeholder:"Name",type:"text",multiple:!1}),t){const e={name:"types",placeholder:"Type",type:"select",multiple:!0,options:t.types.map((e=>({label:e.name,value:e.id})))};n.push(e)}return n}function ds(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 us({facets:n,search:r}){const[s,i]=o([]),a=cs(),l=ds(r);return e(H,{filterGroups:a,filters:s,setFilters:e=>{const t="function"==typeof e?e(s):e;i(t),l(t)},children:t("div",{className:"flex gap-2 items-center",children:[e(K,{}),e(Y,{}),e(Q,{})]})})}class ms{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 ms(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 hs=d(void 0);function ps(){const e=u(hs);if(!e)throw new Error("useObjectSelection must be used within a ObjectSelectionProvider");return e}function fs(){return u(hs)}function gs({value:t,collectionId:n,children:r}){const[s,i]=o();return c((()=>{const e=new ms(t,n,{},i);i(e)}),[t]),s&&e(hs.Provider,{value:s,children:r})}Vt.extend(on),Vt.extend(ln);const vs={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 i=s?parseInt(s):2;return(t,n)=>{let s=new Intl.NumberFormat("en-US",{style:r?"currency":"decimal",currency:r,maximumFractionDigits:i}).format(t);return e("td",{children:s},n)}},objectId(n,r){let s=[],i=!1;if(n){const e=n.get("slice");e&&(i=!0,s.push((t=>t.slice(parseInt(e)))))}return(n,a)=>{const l=s.reduce(((e,t)=>t(e)),n.id);return t("td",{className:"flex justify-between items-center gap-2",children:[i?"~":"",l,e(b,{variant:"ghost",alt:"Preview Object",onClick:e=>{e.stopPropagation(),r?.(n.id)},children:e(Xe,{className:"size-4"})})]},a)}},objectName(t,n){let r="title";return t&&(r=t.get("title")||"title"),(t,n)=>e("td",{children:t.properties?.[r]||t.name||or(t.id)},n)},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:Vt(t)[r](s)},n)}},ys=vs.string();function bs(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 xs(e){return e&&"."!==e?e.split("."):[]}class ws{layout;renderer=ys;path;fallbackPath;previewObject;constructor(e,t){if(this.layout=e,this.path=xs(e.field||""),this.fallbackPath=e.fallback?xs(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=vs[e](r)}else this.renderer=vs[t]()}}get name(){return this.layout.name}resolveValue(e){let t=bs(e,this.path);return void 0===t&&this.fallbackPath&&(t=bs(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";if("objectId"===(r.indexOf("?")>0?r.substring(0,r.indexOf("?")):r)&&this.previewObject){const e=r.indexOf("?"),s=e>0?new URLSearchParams(r.substring(e+1)):void 0;return vs.objectId(s,(e=>{this.previewObject(t.id)}))(t,n)}return this.renderer(this.resolveValue(t),n)}}function Ns({objects:n,selection:r,isLoading:s,columns:i,onRowClick:a,selectedObject:l,toggleAll:o,onSelectionChange:c}){return t(J,{className:"w-full border-t",children:[e("thead",{children:t("tr",{children:[r&&e("th",{children:e("input",{type:"checkbox",onChange:o})}),i.map((t=>e("th",{children:t.name},t.name)))]})}),t(X,{isLoading:s,columns:i.length+1,children:[n?.map((n=>t("tr",{className:"cursor-pointer hover:bg-muted group "+(l?.id===n.id?"bg-muted":""),onClick:()=>{a&&a(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)})}),i.map(((e,t)=>e.render(n,t)))]},n.id))),0===n.length&&e("tr",{children:e("td",{colSpan:i.length+(r?1:0),className:"text-center",children:"No objects. Just drag and drop documents or images here to create content objects."})})]})]})}function ks({objects:r,selection:s,isLoading:i,onSelectionChange:a,onRowClick:l,previewObject:o,selectedObject:c}){return t(n,{children:[e(Nr,{isLoading:i}),e("div",{className:"w-full gap-2 grid lg:grid-cols-6",children:r.map((t=>e(kr,{document:t,selection:s,onSelectionChange:a,onRowClick:l,previewObject:o,selectedObject:c},t.id)))})]})}class Cs{client;limit;collectionId;facets=new Z({});result=new Z({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:i,dynamic_scaling:a,limit:l,all_revisions: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!==i&&{score_aggregation:i},...void 0!==a&&{dynamic_scaling:a},...void 0!==o&&{all_revisions:o},...void 0!==l&&{limit:l}},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||[],i=r.facets||{};return this.result.value={isLoading:!1,objects:e?this.objects.concat(s):s,hasMore:s.length===n},!t&&i&&Object.keys(i).length>0&&(this.facets.value=i),!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 js=d(void 0);function Ss(){return u(js)}function _s(){return ee(Ss().facets)}function Ts(){const e=Ss();return{...ee(e.result),search:e}}function Ps(){const e=Ss();return ee(e.facets).total}var Is;async function As(e){try{const t=await e.arrayBuffer(),n=new cn;n.appendByteArray(new Uint8Array(t));const r=n.end();return r?.toString()}catch(e){return void console.error("Error calculating file hash:",e)}}function $s(){const{client:e}=Pt(),t=v();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),i=await Promise.all(s.map((async e=>{let n=t||void 0;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 As(e),name:e.name,size:e.size,location:n}})));n.push(...i)}return n}(n,r),i=async()=>{let n;const r={query:{match:{"content.etag":{$in:t.map((e=>e.hash))}}},select:"id content.etag"};n=s?(await e.store.collections.searchMembers(s,r)).results:(await e.store.objects.search(r)).results;for(const e of n){const n=t.find((t=>t.hash===e.content.etag));n&&(n.existingId=e.id,n.action=Is.SKIP)}},a=async()=>{const n=t.filter((e=>e.action!==Is.SKIP)),r=n.map((e=>e.location)),i=Array.from(new Set(r)),a=[];for(const t of i){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));a.push(t)}else{const t=e.store.objects.find({query:r,select:"id content.name location"});a.push(t)}}const l=(await Promise.all(a)).flat();console.log(`Found ${l.length} document to update`,l);for(const e of l){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=Is.UPDATE)}console.log(`Reconciled ${t.filter((e=>e.action===Is.UPDATE)).length}`)};return await i(),await a(),t.forEach((e=>{e.action||(e.action=Is.CREATE)})),console.log("Document processing check results:",{totalFiles:n.length,toCreate:t.filter((e=>e.action===Is.CREATE)).length,toUpdate:t.filter((e=>e.action===Is.UPDATE)).length,toSkip:t.filter((e=>e.action===Is.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 Es({isOpen:r,onClose:s,files:i,collectionId:a,selectedFolder:d,title:u="Upload Files",children:m,onUploadComplete:h,hideFileSelection:p=!1,showTypeSelectionOnly:f=!1}){const{client:g,typeRegistry:y}=Pt(),x=v(),[w,N]=o([]),[k,C]=o([]),[j,S]=o(!1),[_,T]=o(null),[P,I]=o([]),[A,$]=o(!1),[E,z]=o(!1),[O,D]=o(0),[U,F]=o(Date.now()),[R,M]=o(void 0),[q,W]=o(null),[B,G]=o(u),[J,H]=o("");c((()=>{a&&g.store.collections.retrieve(a).then(M)}),[a]),c((()=>{A?(G("Uploading Files"),H(`${Math.round(O)}% complete`)):E?(G("Upload Complete"),H("")):j?(G("File Analysis Results"),H(`${w.length} file${1!==w.length?"s":""}`)):w.length>0?(G(u),H("Checking for duplicates and updates")):(G(u),H(""))}),[A,E,j,u,O,w.length]);const K=()=>R||d?t(se,{className:"mb-4",status:"default",icon:e(at,{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})]}),d&&t("div",{className:"flex items-center mt-1",children:[e("span",{className:"mr-1",children:"Folder:"}),e("span",{className:"font-medium",children:d})]})]})]}):null,[Y,Q]=o({toCreate:0,toUpdate:0,toSkip:0}),{checkDocumentProcessing:X}=$s(),Z=l((()=>y?.types||[]),[y?.types]);c((()=>{r&&(C([]),S(!1),T(null),I([]),$(!1),z(!1),D(0),Q({toCreate:0,toUpdate:0,toSkip:0}),W(null),G(u),H(""),i&&i.length>0?(N(i),oe(i)):N([]),F(Date.now()))}),[r,i]);const ee=()=>{N([]),C([]),S(!1),T(null),I([]),$(!1),z(!1),D(0),Q({toCreate:0,toUpdate:0,toSkip:0}),W(null),G(u),H(""),F(Date.now()),s()},le=e=>{e&&e.length>0&&(N(e),oe(e))},oe=async e=>{if(e.length)try{console.log(`Processing ${e.length} files to determine required actions...`);const t=await X(e,d,a);C(t);const n=t.filter((e=>e.action===Is.CREATE)).length,r=t.filter((e=>e.action===Is.UPDATE)).length,s=t.filter((e=>e.action===Is.SKIP)).length;Q({toCreate:n,toUpdate:r,toSkip:s}),x({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),x({title:"Error",description:"There was an error analyzing the files",status:"error",duration:5e3})}},ce=async()=>{if(!k.length)return;const e=_?.id||null,t=k.map((e=>({file:e.file,status:"pending",progress:0,action:e.action===Is.CREATE?"create":e.action===Is.UPDATE?"update":"skip"})));I(t),$(!0),z(!1);const n=k.filter((e=>e.action===Is.SKIP)),r=k.filter((e=>e.action===Is.UPDATE)),s=k.filter((e=>e.action===Is.CREATE)),i={success:!0,objectIds:[],uploadedFiles:[],skippedFiles:[],failedFiles:[]};for(const t of n)t.existingId&&(i.objectIds.push(t.existingId),i.skippedFiles.push({id:t.existingId,name:t.name,type:e,status:"skipped",location:t.location}),I((e=>e.map((e=>e.file===t.file?{...e,status:"success",progress:100,id:t.existingId}:e)))));const l=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 l=r[s];if(console.log(`Processing ${n} batch ${s+1}/${r.length} (${l.length} files)`),t.length>50){x({title:`Processing files (${n})`,description:`Processed ${50*s}/${t.length} files...`,status:"info",duration:2e3})}let o=0;await Promise.all(l.map((async t=>{try{if(I((e=>e.map((e=>e.file===t.file?{...e,status:"uploading",progress:20}:e)))),"update"===n&&t.existingId)await g.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()}),I((e=>e.map((e=>e.file===t.file?{...e,status:"success",progress:100,id:t.existingId}:e)))),i.objectIds.push(t.existingId),i.uploadedFiles.push({id:t.existingId,name:t.name,type:e,status:"updated",location:t.location});else{const n=await g.store.objects.create({type:e||void 0,content:t.file,location:t.location||t.file.webkitRelativePath||t.name},{collection_id:a});I((e=>e.map((e=>e.file===t.file?{...e,status:"success",progress:100,id:n.id}:e)))),i.objectIds.push(n.id),i.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),I((e=>e.map((e=>e.file===t.file?{...e,status:"error",progress:100,message:n.message||"Unknown error"}:e)))),i.failedFiles.push({name:t.name,error:n.message||"Unknown error",status:"failed",location:t.location,type:e}),i.success=!1}o++,o%5!=0&&o!==l.length||I((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 D(r),e}))})))}};r.length>0&&await l(r,"update"),s.length>0&&await l(s,"create"),I((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=>{i.failedFiles.push({name:e.file.name,error:"Upload process interrupted",status:"failed",type:_?.id||null})})),i.success=!1,e.map((e=>"pending"===e.status?{...e,status:"error",progress:100,message:"Upload process interrupted"}:e))):e})),$(!1),z(!0);const o=i.uploadedFiles.filter((e=>"created"===e.status)).length,c=i.uploadedFiles.filter((e=>"updated"===e.status)).length,d=i.skippedFiles.length,u=i.failedFiles.length;let m="";o>0&&(m+=`${o} file${1!==o?"s":""} uploaded`),c>0&&(m+=m?", ":"",m+=`${c} file${1!==c?"s":""} updated`),d>0&&(m+=m?", ":"",m+=`${d} file${1!==d?"s":""} skipped`),u>0&&(m+=m?", ":"",m+=`${u} file${1!==u?"s":""} failed`),x({title:"Upload Complete",description:m,status:u>0?"warning":"success",duration:5e3}),W(i)},de=()=>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(V,{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(De,{className:"size-3 ml-2"})})]}),e(ae,{options:Z,value:_,optionLabel:e=>e?e.name:"Select a content type",placeholder:"Select a content type or leave empty for automatic detection",onChange:e=>T(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(nt,{className:"size-4 mr-1"}),"Automatic Type Detection",e(V,{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(De,{className:"size-3 ml-2"})})]})})]});return t(te,{isOpen:r,onClose:ee,className:"mx-auto",disableCloseOnClickOutside:!0,children:[e(ne,{description:J,children:B}),f?t(re,{children:[m,K(),de()]}):0!==w.length||p?A||E?A?t(re,{children:[K(),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:`${O}%`}})})}),e("div",{className:"max-h-96 overflow-y-auto",children:P.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(st,{className:"size-5 text-muted"}),"uploading"===n.status&&e(L,{size:"sm"}),"success"===n.status&&e(nt,{className:"size-5 text-success"}),"error"===n.status&&e(it,{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(re,{children:t("div",{className:"mb-4",children:[K(),e(Yt,{files:P.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:d||void 0,collection:R?.name})]})}):e(re,{children:j?t(n,{children:[K(),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(tt,{className:"size-5 text-primary"}),e("span",{className:"font-medium",children:"New"})]}),e("div",{className:"text-2xl font-semibold",children:Y.toCreate})]}),t("div",{className:"flex flex-col items-center",children:[t("div",{className:"flex items-center gap-2",children:[e(nt,{className:"size-5 text-success"}),e("span",{className:"font-medium",children:"Update"})]}),e("div",{className:"text-2xl font-semibold",children:Y.toUpdate})]}),t("div",{className:"flex flex-col items-center",children:[t("div",{className:"flex items-center gap-2",children:[e(rt,{className:"size-5 text-mixer-attention/40"}),e("span",{className:"font-medium",children:"Skip"})]}),e("div",{className:"text-2xl font-semibold",children:Y.toSkip})]})]})})}),de(),e(se,{className:"mb-4",status:"info",children:Y.toCreate+Y.toUpdate>0?t("div",{className:"space-y-1",children:[t("p",{children:[Y.toCreate+Y.toUpdate," file",Y.toCreate+Y.toUpdate>1?"s are":" is"," ready to process"]}),e("p",{children:Y.toSkip>0&&`${Y.toSkip} file${Y.toSkip>1?"s are":" is"} already in the system and will be skipped.`})]}):Y.toSkip>0?t("span",{children:["All ",Y.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(L,{size:"lg",className:"mb-4"}),e("div",{className:"text-lg font-medium",children:"Analyzing files..."})]})}):t(re,{className:"flex flex-col items-center justify-center p-8",children:[K(),e(Kt,{onDrop:le,message:"Drag and drop files here or click to select",buttonLabel:"Select Files",className:"w-full h-64"}),m]}),(()=>{if(f)return t(ie,{children:[e(b,{variant:"ghost",onClick:ee,children:"Cancel"}),e(b,{onClick:()=>{h&&h({success:!0,objectIds:[],uploadedFiles:[{name:"type-selection",type:_?.id||null,status:"created"}],skippedFiles:[],failedFiles:[]}),ee()},children:_?`Use ${_.name}`:"Use Automatic Type Detection"})]});if(0===w.length&&!p)return e(ie,{children:e(b,{variant:"ghost",onClick:ee,children:"Cancel"})});if(!A&&!E){const n=j;return t(ie,{children:[e(b,{variant:"ghost",onClick:ee,children:"Cancel"}),e(b,{disabled:!n,onClick:ce,children:Y.toCreate+Y.toUpdate>0?"Upload":"Continue"})]})}return A?e(ie,{children:e(b,{variant:"ghost",disabled:!0,children:"Uploading..."})}):t(ie,{children:[e(b,{variant:"ghost",onClick:()=>{N([]),C([]),S(!1),T(null),I([]),$(!1),z(!1),D(0),Q({toCreate:0,toUpdate:0,toSkip:0})},children:"Upload More"}),e(b,{onClick:()=>{h&&q&&h(q),ee()},children:"Close"})]})})()]},U)}function zs(e){const t="function"==typeof e?e:e.onUploadDone,{client:n,project:r,store:s}=Pt(),i=Ss(),a=v(),{checkDocumentProcessing:l}=$s();return async(e,o,c)=>{const d={success:!1,objectIds:[],uploadedFiles:[],skippedFiles:[],failedFiles:[]};if(!r)return a({status:"error",title:"No project selected",duration:3e3}),d;if(!e||0===e.length)return a({status:"warning",title:"No files selected",duration:3e3}),d;const u=Array.from(e).filter((e=>e.size>0));if(0===u.length)return a({status:"error",title:"No valid files selected",description:"Please select files with valid content.",duration:5e3}),d;const m=[],h=[],p=[];console.log(`Processing ${u.length} files with smart file processing...`);const f=await l(u,null,c),g=f.filter((e=>e.action===Is.CREATE)).length,v=f.filter((e=>e.action===Is.UPDATE)).length,y=f.filter((e=>e.action===Is.SKIP)).length;a({title:"Files analyzed",description:`${u.length} file(s): ${g} new, ${v} to update, ${y} to skip`,status:"info",duration:4e3});for(const e of f.filter((e=>e.action===Is.SKIP&&e.existingId)))m.push({id:e.existingId,name:e.name,type:o,status:"skipped",location:e.location});const b=f.filter((e=>(e.action===Is.CREATE||e.action===Is.UPDATE)&&e.file));if(b.length>0){console.log(`Processing ${b.length} files (${b.filter((e=>e.action===Is.CREATE)).length} create, ${b.filter((e=>e.action===Is.UPDATE)).length} update)...`);const e=50,t=[];for(let n=0;n<b.length;n+=e)t.push(b.slice(n,n+e));for(let r=0;r<t.length;r++){const i=t[r],l=r*e;console.log(`Processing batch ${r+1}/${t.length} (${i.length} files)`),b.length>e&&a({title:"Processing files",description:`Processed ${l}/${b.length} files...`,status:"info",duration:2e3});const u=await Promise.all(i.map((async e=>{try{if(e.action===Is.UPDATE&&e.existingId){const t=await n.store.objects.update(e.existingId,{type:o||void 0,content:e.file,location:e.location,name:e.name},{createRevision:!0,revisionLabel:"upload on "+(new Date).toISOString()});return h.push({id:e.existingId,name:e.name,type:o,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:o||void 0,content:e.file,location:e.location||e.file.webkitRelativePath||e.name},t);h.push({id:n.id,name:e.name,type:o,status:"created",location:e.location})}}catch(t){console.error(`Failed to process file ${e.name}:`,t),p.push({name:e.name,error:t.message||"Unknown error",status:"failed",location:e.location,type:o}),a({status:"error",title:`Processing failed for ${e.name}`,description:t.message,duration:4e3})}}))),m=h.filter((e=>"created"===e.status)),f=h.filter((e=>"updated"===e.status)),g=h.filter((e=>"failed"===e.status));console.log(`Batch ${r+1} results:`,{creates:m,updates:f,failures:g,total:u.length})}}const x=h.filter((e=>"created"===e.status)).length,w=h.filter((e=>"updated"===e.status)).length,N=h.filter((e=>"failed"===e.status)).length,k=h.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&&a({status:N>0?"warning":"success",title:C,duration:4e3}),i.search(),d}}!function(e){e.CREATE="create",e.SKIP="skip",e.UPDATE="update"}(Is||(Is={}));const Os=[{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 Ds({isGridView:t=!1,onUpload:n,collectionId:r,...s}){return n?e(Us,{...s,onUpload:n,isGridView:t,collectionId:r}):e(Ls,{...s,isGridView:t})}function Us({isGridView:n,onUpload:s,collectionId:i,skipTypeModal:a=!1,...l}){const[c,d]=o(!1),[u,m]=o([]),[h,p]=o(!1),[f,g]=o(null),[y,b]=o(!1),x=Ss(),w=v(),{checkDocumentProcessing:N}=$s(),k=async(e,t)=>{console.log("Files dropped on ObjectTable:",e.length,t),d(!0);try{if(i){const t=await N(e,null,i);g(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;w({title:"Files ready to process",description:`${e.length} file(s): ${n} new, ${r} to update, ${s} to skip`,status:"info",duration:4e3})}else g(null)}catch(e){console.error("Error processing files:",e),w({title:"Error processing files",description:"There was an error checking for duplicate files",status:"error",duration:4e3}),g(null)}finally{if(d(!1),m(e),p(!1),a){console.log("Skipping type modal and calling onUpload directly",{filesLength:e.length,processedFilesLength:f?.length});const t=s(e,null,i);t&&"object"==typeof t&&(t.processedFiles=f)}else console.log("Setting typeSelectionOpen to true",{filesLength:e.length}),b(!0)}},C=e=>{const t=[...u];m([]),g(null),b(!1),t.length>0&&void 0!==e&&(d(!0),console.log("Starting upload with",{typeId:e,filesCount:t.length,hasProcessingResults:!!f,collectionId:i}),s(t,e,i).finally((()=>{d(!1),x.search()})))},j=e=>{e.preventDefault(),e.stopPropagation(),p(!0)};return t("div",{className:"min-h-[400px] relative",onDragOver:j,onDragEnter:j,onDragLeave:e=>{e.preventDefault(),e.stopPropagation(),e.currentTarget.contains(e.relatedTarget)||p(!1)},onDrop:e=>{if(e.preventDefault(),e.stopPropagation(),p(!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"}...`};k(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",c?"block":"hidden"),children:e(L,{size:"xl"})}),e(Ls,{...l,isGridView:n}),e("div",{className:r("absolute inset-0 pointer-events-none",h?"z-40":"-z-10"),children:e("div",{className:"w-full h-full relative",children:e(Kt,{onDrop:k,message:"Drop files or folders here to upload",className:r("absolute inset-0 bg-white/90 dark:bg-gray-800/90 pointer-events-auto",h?"flex":"hidden"),buttonLabel:"Select Files or Folders",allowFolders:!0})})}),e(Es,{isOpen:y&&u.length>0,onClose:()=>{m([]),g(null),b(!1),C(void 0)},files:u,collectionId:i,selectedFolder:null,title:"Upload Files",onUploadComplete:e=>{if(e){if(e.failedFiles&&e.failedFiles.length>0&&w({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)&&w({title:"Upload Complete",description:`${t>0?`${t} created`:""}${t>0&&n>0?", ":""}${n>0?`${n} updated`:""}${r>0?`, ${r} skipped`:""}`,status:"success",duration:5e3})}x.search()}m([]),g(null),b(!1),e&&e.success&&e.objectIds.length>0?C(null):C(void 0)}})]})}function Ls({objects:t,layout:n=Os,isLoading:r,onRowClick:s,onSelectionChange:i,previewObject:a,selectedObject:o,isGridView:c}){const d=fs(),u=(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);i&&i(d)}},m=e=>{if(d){e.target.checked?d.addAll(t):d.removeAll()}},h=l((()=>(n.length>0?n:Os).map((e=>new ws(e,a)))),[n,a]);return e(c?ks:Ns,{objects:t,isLoading:r,columns:h,onRowClick:s,previewObject:a,selectedObject:o,selection:d,toggleAll:m,onSelectionChange:u})}function Fs({children:t,limit:n,parent:r,typeId:s,facets:i,name:a,collectionId:o}){const{store:c}=Pt(),d=l((()=>{let e;i?e=i:(e=[{name:"status",field:"status"},{name:"location",field:"location"}],s||e.unshift({name:"type",field:"type"}));const t=new Cs(c,n).withFacets(e);return t.collectionId=o,t.query.type=s,t.query.parent=r,t.query.name=a,t}),[s,n,o]);return e(js.Provider,{value:d,children:t})}const Rs=[{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 Ms({onChange:t}){return e(Fs,{children:e(qs,{onRowClick:e=>{t(e||void 0)}})})}const Vs="vertesia.content_store.lastDisplayedView";function qs({onRowClick:n}){const[r,s]=o(!1),[i,a]=o("grid"===localStorage.getItem(Vs)),{search:l,isLoading:d,error:u,objects:h}=Ts(),p=m(null);le(p,(()=>{r&&l.loadMore(!0)}),{deps:[r]}),c((()=>{l.search().then((()=>s(!0)))}),[]);const f=_s(),g=Ss();return u?e(oe,{title:"Search failed",children:u.message}):t("div",{children:[t("div",{className:"flex justify-between items-center mb-4",children:[e(ns,{facets:f,search:g}),t("div",{className:"flex items-center gap-2",children:[e(b,{variant:"outline",onClick:()=>{s(!1),l.search().then((()=>s(!0)))},alt:"Refresh",children:e(et,{size:16})}),e(Kn,{onUpdate:a})]})]}),e(Ds,{objects:h||[],isLoading:!1,layout:Rs,onRowClick:n,isGridView:i}),e("div",{ref:p,className:"mt-10"}),d&&e("div",{className:"flex justify-center",children:e(L,{size:"xl"})})]})}function Ws({isOpen:n,onClose:r}){return t(te,{onClose:()=>r(),isOpen:!!n,className:"min-w-[60vw]",children:[e(ne,{children:"Select Content"}),e(re,{className:"pt-0 overflow-y-auto max-h-[80vh] min-h-[80vh]",children:n&&e(Ms,{onChange:r})})]})}const Bs=/store:([a-f0-9]+)/;function Gs({object:n}){const{client:s}=Pt(),{off:i,on:a,isOn:l}=ce(),[d,u]=o(null!=n.value?String(n.value):""),[m,h]=o(void 0),p=()=>{u(""),n.value="",h(void 0)};return c((()=>{if(!d||m)return;const e=d.match(Bs);e&&s.objects.get(e[1]).then((e=>{h(e)})).catch((()=>{p()}))}),[d]),t("div",{children:[t("div",{className:"relative",children:[e("input",{value:d,onChange:e=>{const t=e.target.value;u(t),n.value=t},className:r(de.INPUT,"pr-10 w-full")}),m&&e("div",{className:"absolute inset-y-0 right-10 flex items-center justify-center ",children:e(b,{onClick:p,variant:"unstyled",className:"hover:text-red-500 hover:bg-gray-100 dark:hover:bg-gray-600",children:e(lt,{className:"size-5"})})}),e("div",{className:"absolute inset-y-0 right-0 flex items-center justify-center",children:e(b,{onClick:a,variant:"unstyled",className:"hover:bg-gray-100 dark:hover:bg-gray-600",children:e(ot,{className:"size-5"})})}),e(Ws,{value:d,isOpen:l,onClose:e=>{if(e){const t="store:"+e.id;u(t),h(e||void 0),n.value=t}i()}})]}),m&&e("div",{className:"p-1 semibold text-sm text-gray-600 dark:text-slate-300",children:m.properties?.title||m.name})]})}function Js(e,t,n){return()=>{n&&e.files.getDownloadUrl(n).then((e=>{window.open(e.url,"_blank")})).catch((e=>{t({status:"error",title:"Failed to get download URL",description:e.message,duration:5e3})}))}}function Hs({objectId:n,isOpen:r,onClose:s}){const i=Mt(),{client:a,store:l}=Pt(),[d,u]=o(null),[m,h]=o(!1),[p,f]=o(!1),[g,y]=o(),[x,w]=o(),[N,k]=o("preview"),C=v();c((()=>{n&&r?(h(!0),l.objects.retrieve(n,"+embeddings").then((e=>{u(e),e.text?y(e.text):j(e.id);const t=e.content;t&&t.source&&t.type&&t.type.startsWith("image/")&&S(e)})).catch((e=>{console.error("Error loading object:",e),C({title:"Error",description:"Failed to load document",status:"error",duration:3e3})})).finally((()=>{h(!1)}))):(u(null),y(void 0),w(void 0))}),[n,r,l.objects]);const j=async e=>{f(!0);try{const t=await l.objects.getObjectText(e);y(t.text)}catch(e){console.error("Error loading text:",e)}finally{f(!1)}},S=async e=>{try{"found"===(await a.objects.getRendition(e.id,{format:Ot.jpeg,generate_if_missing:!1})).status&&console.log("Found rendition");const t=await a.files.getDownloadUrl(e.content.source);w(t.url)}catch(e){console.error("Error loading image:",e)}},_=()=>{d&&(i(`/legal/objects/${d.id}`),s())},T=g&&(g.startsWith("#")||g.includes("\n#")||g.includes("\n*")),P=d?.content?.type&&d.content.type.startsWith("image/"),I="application/pdf"===d?.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(ct,{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...":d?.name||"Document Preview"})]}),t("div",{className:"flex items-center space-x-2",children:[t(b,{variant:"ghost",size:"sm",onClick:_,className:"flex items-center gap-1 text-indigo-600 hover:text-indigo-800",children:[e(dt,{className:"h-4 w-4"}),e("span",{children:"Full View"})]}),e(b,{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(lt,{className:"h-5 w-5"})})]})]}),m?e("div",{className:"flex-1 flex items-center justify-center",children:t("div",{className:"text-center",children:[e(L,{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"===N?"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:()=>k("preview"),children:t("div",{className:"flex items-center gap-1",children:[e(Je,{className:"h-4 w-4"}),e("span",{children:"Preview"})]})}),e("button",{className:"py-2 px-4 font-medium border-b-2 "+("properties"===N?"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:()=>k("properties"),children:t("div",{className:"flex items-center gap-1",children:[e(De,{className:"h-4 w-4"}),e("span",{children:"Properties"})]})})]})}),t("div",{className:"flex-1 overflow-auto p-4",children:["preview"===N&&t("div",{className:"h-full",children:[p?e("div",{className:"flex items-center justify-center h-40",children:e(L,{size:"md",className:"text-indigo-600 dark:text-indigo-400"})}):g?e("div",{className:"shadow rounded-md p-4 border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800",children:T?e("div",{className:"prose prose-sm max-w-none prose-p:my-2 prose-pre:bg-gray-800 prose-pre:my-2 prose-headings:text-indigo-700 dark:prose-invert dark:prose-headings:text-indigo-300",children:e(Jt,{children:g})}):e("pre",{className:"text-wrap whitespace-pre-wrap dark:text-gray-200",children:g})}):null,P&&e("div",{className:"mt-4",children:e("div",x?{className:"border border-gray-200 dark:border-gray-700 rounded-md p-2 bg-white dark:bg-gray-800",children:e("img",{src:x,alt:d?.name,className:"mx-auto max-h-[70vh] object-contain"})}:{className:"flex items-center justify-center h-40",children:e(L,{size:"md",className:"text-indigo-600 dark:text-indigo-400"})})}),I&&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(ct,{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(b,{onClick:_,className:"bg-indigo-600 hover:bg-indigo-700 text-white",children:"Open Full Document View"})]}),!P&&!g&&!I&&!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(ct,{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"===N&&d&&t("div",{className:"h-full",children:[d.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(Ht,{value:d.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(De,{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:d.id}),e("div",{className:"text-gray-500 dark:text-gray-400",children:"Type"}),e("div",{className:"font-medium dark:text-gray-200",children:d.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:d.content?.type||"N/A"}),e("div",{className:"text-gray-500",children:"Size"}),e("div",{className:"font-medium",children:d.content&&"size"in d.content?Ks(d.content.size):"Unknown"}),e("div",{className:"text-gray-500",children:"Created"}),e("div",{className:"font-medium",children:d.created_at?new Date(d.created_at).toLocaleString():"N/A"}),e("div",{className:"text-gray-500",children:"Updated"}),e("div",{className:"font-medium",children:d.updated_at?new Date(d.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:d?.content?.source&&t(b,{onClick:()=>{d?.content?.source&&a.files.getDownloadUrl(d.content.source).then((e=>{window.open(e.url,"_blank")})).catch((e=>{console.error("Error getting download URL:",e),C({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(Qe,{className:"h-4 w-4 mr-2"}),"Download"]})}),t(b,{onClick:_,className:"bg-indigo-600 hover:bg-indigo-700 text-white",children:["Open Full Document",e(ut,{className:"h-4 w-4 ml-2"})]})]})]}):null}function Ks(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 Ys=Object.values(Lt),Qs=Object.values(Ft);function Xs({onChange:n,isLoading:r,refresh:s,searchTypes:i}){const{client:a,project:l}=Pt(),d=v(),[u,m]=o(void 0),[h,p]=o(void 0),f=!(!l||!h?.embeddings.text&&!h?.embeddings.image),[g,y]=o(void 0),[x,w]=o(!1),[N,k]=o(i||Ys),[C,j]=o(100);c((()=>{i&&k(i)}),[i]);const S={};let I=!1,A=!1;N.forEach((e=>{e===Lt.full_text?I=!0:A=!0,Qs.includes(e)&&(S[e]=!0)})),c((()=>{m(void 0),y(void 0)}),[s]),c((()=>{l&&a.projects.retrieve(l.id).then((e=>{p(e.configuration)}))}),[l]),c((()=>{g&&d({title:g,status:"success",duration:2e3})}),[g]),c((()=>{u&&0!==u.length||n(void 0)}),[u]);const z=()=>{if(!f||!u)return;n({vector:A?{text:u,config:S}:void 0,full_text:I?u:void 0,limit:C}),y("Searching...")},O=e=>t=>{k(t?t=>Array.from(new Set([...t,e])):t=>t.filter((t=>t!==e)))};return t("div",{className:"flex gap-1 items-center w-1/2",children:[e($,{placeholder:"Type what you are looking for, or select a filter",value:u,onChange:m,onKeyDown:e=>{"Enter"===e.key&&z()}}),e(b,{variant:"ghost",onClick:()=>w(!0),alt:"Semantic search settings",className:"ml-1",children:e(mt,{size:18})}),t(_,{isOpen:x,onClose:()=>w(!1),children:[e(T,{children:"Search Types"}),e(P,{children:t("div",{className:"flex flex-col gap-2",children:[t("label",{className:"flex items-center gap-2",children:[e(ue,{checked:N.includes(Lt.full_text),onCheckedChange:O(Lt.full_text)}),e("span",{children:"Full Text"})]}),e("div",{className:"font-semibold mt-2 mb-1",children:"Embeddings"}),Qs.map((n=>t("label",{className:"flex items-center gap-2",children:[e(ue,{checked:N.includes(n),onCheckedChange:O(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(me,{type:"number",min:1,value:C,onChange:e=>j(Number(e)||1),style:{width:80}})]})]})}),e(E,{children:e(b,{variant:"outline",onClick:()=>w(!1),children:"Close"})})]}),e(b,{variant:"secondary",isLoading:r,onClick:z,isDisabled:!f,alt:"Semantic search",children:"Search"})]})}const Zs=[{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 ei({onUploadDone:t=async()=>{},layout:n}){const r=Ss(),s=v(),i=zs((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(ti,{layout:n,onUpload:(e,t)=>{const n=r.collectionId;return i(e,t,n)}})}function ti({layout:n,onUpload:r,allowFilter:s=!0,allowSearch:i=!0}){const a=Ss(),[l,d]=o(!1),[u,h]=o(null),{typeRegistry:p}=Pt(),{search:f,isLoading:g,error:v,objects:y,hasMore:b}=Ts(),[x,w]=o(p?n||(N=p,((k=f.query.type)?N.getTypeLayout(k):Zs)??Zs):Zs);var N,k;const[C,j]=o(0),[S,_]=o(0),[T,P]=o("grid"===localStorage.getItem(Kn.LAST_DISPLAYED_VIEW)),[I,A]=o([]),$=m(null);c((()=>{l||0!==y.length||(_(0),f._updateRunningState(!0),f.search().then((()=>{d(!0)})).catch((e=>{console.error("Initial search failed:",e),f._updateRunningState(!1)})))}),[]),c((()=>{y.length<S&&_(y.length)}),[y.length,S]),le($,(()=>{l&&y.length>0&&y.length!=S&&(d(!1),f.loadMore().finally((()=>{_(y.length),d(!0)})))}),{deps:[l,y.length]});const E=_s(),z=Ss(),O=es(E),D=ts(z),U=new URL(window.location.href),F=U.searchParams.get("filters");if(F)try{const e=F.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?U.searchParams.set("filters",e):U.searchParams.delete("filters"),window.history.replaceState(window.history.state||{},"",U.toString())}}catch(v){console.error("Failed to clean start/end filters from URL:",v)}const R=Mt();return t("div",{className:"flex flex-col gap-y-2",children:[e(ri,{object:u,onClose:()=>h(null)}),v&&e(oe,{title:"Error",children:v.message}),e(ni,{isLoading:g,refreshTrigger:C,allowFilter:s,allowSearch:i,filterGroups:O,filters:I,handleFilterChange:e=>{const t="function"==typeof e?e(I):e;A(t),D(t)},handleVectorSearch:e=>{if(e&&e.vector){if(f.query.vector=e.vector,f.query.full_text=e.full_text,f.query.weights=e.weights,f.query.score_aggregation=e.score_aggregation,f.query.dynamic_scaling=e.dynamic_scaling,!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)}f.search().then((()=>d(!0)))}else e&&e.full_text?(f.query.full_text=e.full_text,f.search().then((()=>d(!0)))):void 0===e&&l&&(delete f.query.vector,delete f.query.full_text,f.search().then((()=>d(!0))))},handleRefetch:()=>{f.search().then((()=>d(!0)))},setIsGridView:P}),e(Ds,{objects:y,isLoading:!y.length&&g,layout:x,onRowClick:e=>{R(`/objects/${e.id}`)},previewObject:e=>{const t=y.find((t=>t.id===e))||null;h(t)},selectedObject:u,onUpload:r,isGridView:T,collectionId:a.collectionId}),e("div",b?{ref:$,className:"w-full flex justify-center",children:e(L,{size:"xl"})}:{className:"text-muted text-center text-sm py-1",children:`All ${y.length} objects loaded.`})]})}function ni(n){const{isLoading:r,refreshTrigger:s,allowFilter:i,allowSearch:a,filterGroups:l,filters:o,handleFilterChange:c,handleVectorSearch:d,handleRefetch:u,setIsGridView:m}=n;return t("div",{className:"sticky top-0 z-10 bg-background py-2",children:[i&&t(H,{filterGroups:l,filters:o,setFilters:c,children:[t("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:[a&&e(Xs,{onChange:d,isLoading:r,refresh:s,className:"w-full"}),e(K,{})]}),t("div",{className:"flex gap-1 items-center",children:[e(b,{variant:"outline",onClick:u,alt:"Refresh",children:e(et,{size:16})}),e(Kn,{onUpdate:m})]})]}),t("div",{className:"flex gap-2 items-center pt-2",children:[e(Y,{}),e(Q,{})]})]}),!i&&t("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:a&&e(Xs,{onChange:d,isLoading:r,refresh:s})}),t("div",{className:"flex gap-1 items-center",children:[e(b,{variant:"outline",onClick:u,alt:"Refresh",children:e(et,{size:16})}),e(Kn,{onUpdate:m})]})]})]})}function ri({object:n,onClose:r}){const{store:s}=Pt(),i=v(),a=Mt(),l=Js(s,i,n?.content?.source);return n?t(he,{title:n.properties?.title||n.name,isOpen:!0,onClose:r,children:[t("div",{className:"flex items-center gap-x-2",children:[e(b,{variant:"ghost",size:"sm",title:"Open Object",onClick:()=>a(`/objects/${n.id}`),children:e(We,{className:"size-4"})}),n.content?.source&&e(b,{variant:"ghost",size:"sm",title:"Download",onClick:l,children:e(Qe,{className:"size-4"})})]}),e(pe,{className:"my-2"}),e("div",{className:"pt-2",children:e(tr,{object:n,loadText:!0},n.id)})]}):null}var si;function ii({isExporting:n,isOpen:r,onClose:s}){return t(_,{onClose:()=>s(void 0),isOpen:r,className:"relative overflow-visible",children:[e(T,{children:"Export Object Properties"}),!n&&e(ai,{onClose:s}),n&&e(li,{})]})}function ai({onClose:n}){const[r,s]=o(void 0),[i,a]=o(void 0),l=["Export selected objects","Export all objects"];return t(P,{className:"min-h-[104px] pt-0 flex flex-col gap-y-4",children:[e("div",{className:"h-1/3",children:e(q,{options:l,value:i,onChange:a,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(q,{options:Object.values(si),value:r,onChange:s,placeholder:"Choose a format",className:"h-full w-full text-sm",filterBy:"name",isClearable:!0}),e(b,{className:"w-full",isDisabled:!r||!i,onClick:()=>{n(r,i==l[1])},children:"Export Properties"})]})]})}function li({}){return e(P,{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(L,{size:"lg"})]})})}function oi({collection:t}){const n=v(),{client:r,typeRegistry:s}=Pt();Ss().query.all_revisions=!0;const i=function(e,t){let n=e.table_layout;if(n&&n.length>0)return n;e.type&&t&&(n=t?.getTypeLayout(e.type.id));return n&&n.length>0?n:void 0}(t,s);return t.dynamic?e(ti,{layout:i}):e(ei,{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:i})}!function(e){e.CSV="CSV",e.JSON="JSON"}(si||(si={}));const ci=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 di({className:t,defaultValue:n,onChange:r,isClearable:s,multiple:i}){const a=Pt(),[l,d]=o(!1),[u,m]=o(),[h,p]=o([]);c((()=>{if(!l&&(d(!0),a.typeRegistry&&n)){if(i&&Array.isArray(n)){const e=a.typeRegistry.types.filter((e=>n.includes(e.id)));p(e)}const e=a.typeRegistry.types.find((e=>e.id===n));e&&m(e)}}),[a.typeRegistry,n,i]);const f=e=>{p(e),r(e)};return e("div",i?{className:"flex flex-col gap-4 content-between",children:e(ae,{options:a.typeRegistry?.types||[],value:h,onChange:f,placeholder:"Choose Content Types...",optionLabel:ci,className:t||"text-sm bg-background",filterBy:"name",isClearable:s||!1,multiple:!0})}:{className:"flex flex-col gap-4 content-between",children:e(ae,{options:a.typeRegistry?.types||[],value:u,onChange:e=>{m(e||void 0),r(e)},placeholder:"Choose a Content Type...",optionLabel:ci,className:t||"text-sm bg-background",filterBy:"name",isClearable:s||!1})})}function ui({onClose:n,redirect:r=!0,onAddToCollection:s}){const i=Mt(),a=v(),[l,c]=o(!1),{client:d}=Pt(),[u,m]=o({dynamic:!1,name:"",description:""});function h(e,t){m({...u,[e]:t})}return t("form",{onSubmit:e=>e.preventDefault(),children:[t(re,{children:[e(A,{label:"Name",required:!0,children:e($,{type:"text",value:u.name||"",onChange:e=>h("name",e)})}),e(A,{label:"Description",className:"mt-2",children:e(fe,{value:u.description||"",onChange:e=>h("description",e)})}),e(A,{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(ge,{value:u.dynamic||!1,onChange:e=>h("dynamic",e)})}),!u.dynamic&&e(A,{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(di,{defaultValue:u.allowed_types||null,onChange:e=>{Array.isArray(e)?h("allowed_types",e.map((e=>e.id))):h("allowed_types",e?[e.id]:[])},isClearable:!0,multiple:!0})}),e(A,{label:"Type",className:"mt-2",description:"Optionally select a content type to assign custom properties and data to the collection.",children:e(di,{defaultValue:u.type||null,onChange:e=>{Array.isArray(e)?h("type",e.length>0?e[0].id:null):h("type",e?.id||null)},isClearable:!0})})]}),e(ie,{children:e(b,{isDisabled:l,onClick:()=>{u?.name&&u.name.trim()?(u.name=u.name.trim(),u.description&&(u.description=u.description.trim()),null==u.dynamic&&(u.dynamic=!1),c(!0),d.store.collections.create(u).then((e=>{n(),a({title:"Collection created",description:`Collection "${e.name}" created successfully`,status:"success",duration:3e3}),r&&i(`/collections/${e.id}`),s&&s(e.id)})).catch((e=>{a({title:"Failed to create collection",description:e.message,status:"error",duration:5e3})})).finally((()=>c(!1)))):a({title:"Name is required",description:"Please provide a name for the collection",status:"error",duration:5e3})},children:"Create Collection"})})]})}function mi({isOpen:n,onClose:r}){return t(te,{onClose:r,isOpen:n,children:[e(ne,{children:"Create a Collection"}),e(ui,{onClose:r})]})}function hi({}){const{client:r}=Pt(),s=v(),[i,a]=o(),[l,d]=o(!0),[u,m]=o(!1),{data:h,error:p,refetch:f}=B((()=>r.store.collections.search({})),[]);if(c((()=>{(h||p)&&d(!1)}),[h,p]),p)return e(oe,{title:"Collections fetch failed",children:p.message});return t(n,{children:[h&&(h.length>0?t(J,{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(X,{columns:4,isLoading:l,children:h.map((n=>t(ve,{children:[e("td",{children:t("div",{className:"flex items-center gap-2",children:[pi(n.dynamic),e(Rt,{href:`/collections/${n.id}`,children:n.name})]})}),e("td",{children:n.type?.name||"-"}),e("td",{children:Vt(n.created_at).fromNow()}),e("td",{className:"text-right",children:e(b,{variant:"destructive",size:"sm",onClick:()=>a(n.id),children:e(ht,{className:"size-4"})})})]},n.id)))})]}):e(ye,{title:"No Collections",buttonLabel:"New Collections",onClick:()=>m(!0),children:"Get started by creating a new Collections."})),e(mi,{isOpen:u,onClose:()=>m(!1)}),e(be,{isOpen:!!i,title:"Delete Collection",content:"Are you sure you want to delete this collection? This action cannot be undone.",onConfirm:async()=>{if(i)try{await r.store.collections.delete(i),s({title:"Collection deleted",status:"success",duration:3e3}),f()}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{a(void 0)}},onCancel:()=>a(void 0)})]})}function pi(t){const n=t?"Dynamic Collection":"Static Collection",r=e(t?pt:ft,{className:"size-5"});return e(V,{description:n,className:"mr-2",children:r})}function fi({objects:n,isLoading:r}){const s=Mt();return e("div",{children:t(J,{className:"w-full",children:[e("thead",{children:t("tr",{children:[e("th",{children:"Name"}),e("th",{children:"Strict Mode"}),e("th",{children:"Semantic Chunking"}),e("th",{children:"Updated At"})]})}),e(X,{isLoading:r,columns:3,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:Vt(n.updated_at).fromNow()})]},n.id)))})]})})}Vt.extend(on),Vt.extend(on);class gi{client;limit;result=new Z({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 vi=d(void 0);function yi(){return u(vi)}function bi(){const e=yi();return{...ee(e.result),search:e}}function xi(){return yi().objects.length}function wi({title:n,isOpen:r,onClose:s,okLabel:i,initialPayload:a}){const l=v(),[c,d]=o(a?.name),[u,m]=o(a?.description),[h,p]=o(a?.strict_mode??!1);return t(_,{isOpen:r,onClose:()=>s(),children:[e(T,{children:n}),e(P,{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($,{value:c,onChange:d})]}),t("div",{children:[e("label",{className:"block text-sm font-medium text-muted",children:"Description"}),e(fe,{value:u,onChange:e=>m(e.target.value)})]})]})}),e(E,{children:t("div",{className:"flex justify-end gap-4",children:[e(b,{variant:"secondary",onClick:()=>s(),children:"Cancel"}),e(b,{variant:"primary",onClick:()=>(()=>{if(!c)return void l({status:"error",title:"Name is required",duration:5e3});s({name:c,description:u,strict_mode:h}).then((()=>s())),d(void 0),m(void 0),p(!1)})(),children:i})]})})]})}var Ni;function ki({isDirty:n=!1}){const r=Pt(),{store:s}=r,i=v(),[a,l]=o(!1),{search:d,isLoading:u,error:h,objects:p}=bi(),[f,g]=o(""),y=xe(f,500),b=m(null);le(b,(()=>{a&&d.loadMore()}),{deps:[a]}),c((()=>{d.search().then((()=>l(!0)))}),[]),c((()=>{d.query.name=f,d.search().then((()=>l(!0)))}),[y]);const[x,w]=o(void 0);c((()=>{d.query.chunkable=x?"Yes"==x:void 0,d.search().then((()=>l(!0)))}),[x]),c((()=>{n&&a&&d.search().then((()=>l(!0)))}),[n]);const[N,k]=o(!1);if(h)return e(oe,{title:"Failed to fetch ObjectTypes",children:h.message});return t("div",{className:"flex flex-col gap-4 h-full",children:[t("div",{className:"flex gap-4",children:[e($,{placeholder:"Filter by Name",value:f,onChange:g}),e(q,{className:"w-60",isClearable:!0,options:Object.values(Ni),value:x,onChange:e=>{w(e)},placeholder:"Is Chunkable"})]}),t("div",{className:"flex-1",children:[u||0!==p?.length?e(fi,{objects:p,isLoading:u}):e(ye,{title:"No Type",buttonLabel:"Create Type",onClick:()=>{k(!0)},children:"Get started by creating a new Type."}),e(wi,{okLabel:"Create",title:"Create Type",isOpen:N,onClose:async e=>e?s.types.create(e).then((async()=>{i({status:"success",title:"Type created",duration:2e3}),r.reloadTypes(),d.search().then((()=>l(!0)))})).catch((e=>{i({status:"error",title:"Error creating type",description:e.message,duration:5e3})})):(k(!1),Promise.resolve())})]})]})}!function(e){e.true="Yes",e.false="No"}(Ni||(Ni={}));const Ci=[un,dn()];function ji({objectType:n,onSchemaUpdate:r}){const{store:s}=Pt(),i=v(),[a,c]=o(!1),d=Qt(n.object_schema),u=m(void 0),[h,p]=o(!1),f=l((()=>function(e){if(!e)return"";return JSON.stringify(e,null,2)}(d.schema)),[d]),g=()=>{if(u.current){const e=u.current.getValue();try{const t=function(e){if(!e?.trim())return;return JSON.parse(e.trim())}(e);Si(t),d.replaceSchema(t)}catch(e){return i({status:"error",title:"Invalid JSON Schema",description:e.message,duration:5e3}),!1}}return!0};return t("div",{className:"mx-2 my-2 rounded-2xl border border-solid shadow-md border-spacing-2",children:[t("div",{className:"flex items-center rounded-t-md border-b gap-x-2 py-2 pl-4 pr-2",children:[e("div",{className:"text-base font-semibold",children:"Schema Editor"}),e("div",{children:e(b,{variant:"outline",size:"sm",onClick:()=>{h&&!g()||p((e=>!e))},children:h?"Edit Schema":"Edit Json"})}),e("div",{className:"ml-auto flex gap-x-2",children:e(b,{isLoading:a,variant:"outline",size:"sm",onClick:()=>{h&&!g()||(c(!0),s.types.update(n.id,{object_schema:d.schema}).then((()=>{r(d),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((()=>{c(!1)})))},children:"Save Changes"})})]}),e("div",{className:"px-4 py-2",children:h?e(Xt,{value:f,extensions:Ci,editorRef:u}):e(Zt,{schema:d})})]})}const Si=e=>{try{new Gt({strict:!1}).compile(e)}catch(e){throw new Error(`Invalid JSON Schema definition: ${e.message}`)}};function _i({children:t,limit:n,name:r,chunkable:s}){const{store:i}=Pt(),a=l((()=>{const e=new gi(i,n);return e.query.name=r,e.query.chunkable=s,e}),[n]);return e(vi.Provider,{value:a,children:t})}function Ti({isOpen:n,onClose:r,title:s="Select Content Type",children:i,initialSelectedType:a=null,confirmLabel:l="Select Type",allowNone:c=!0}){const{typeRegistry:d}=Pt(),[u,m]=o(a),h=d?.types||[],p=()=>{r(void 0)};return t(_,{isOpen:n,onClose:p,className:"w-full max-w-xl mx-auto",children:[e(T,{children:s}),t(P,{className:"p-6",children:[i,t("div",{className:"mb-4 mt-4",children:[t("label",{className:"block text-sm font-medium mb-2",children:["Content Type ",c&&e("span",{className:"text-gray-500 font-normal",children:"(Optional)"})]}),e(q,c?{options:h,value:u,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:h,value:u,optionLabel:e=>e?e.name:"Select a content type",placeholder:"Select a content type",onChange:e=>m(e||null),filterBy:"name"}),c&&t("div",{className:"mt-2 text-sm text-blue-600 flex items-center",children:[e(nt,{className:"h-4 w-4 mr-1"}),t("span",{children:[e("strong",{children:"Type selection is optional."})," Leave empty to let Vertesia choose the appropriate type"]})]})]}),u?t("div",{className:"text-sm text-gray-500 bg-gray-50 p-3 rounded-md mb-4",children:[e("div",{className:"font-medium",children:u.name}),u.description&&e("div",{className:"mt-1",children:u.description})]}):c&&t("div",{className:"text-sm text-blue-600 bg-blue-50 p-3 rounded-md mb-4",children:[e("div",{className:"font-medium",children:"Automatic Type Detection"}),t("div",{className:"mt-1",children:["Vertesia will analyze each file's content and automatically select the most appropriate type.",e("br",{}),e("span",{className:"mt-1 block font-medium",children:"This is recommended for most uploads."})]})]})]}),t(E,{children:[e(b,{variant:"ghost",onClick:p,children:"Cancel"}),e(b,{onClick:()=>{r(u?.id??null)},children:u?`${l}: ${u.name}`:c?"Let Vertesia Choose":l})]})]})}const Pi=[un,dn()];function Ii({objectType:n,onLayoutUpdate:r}){const s=v(),[i,a]=o(!1),{store:c}=Pt(),d=m(void 0),u=l((()=>Ai(n.table_layout)),[n.table_layout]),h=(e,t)=>{s({status:"error",title:e,description:t,duration:5e3})};return t("div",{className:"mx-2 my-2 rounded-2xl border border-solid shadow-xs",children:[t("div",{className:"flex items-center rounded-t-md border-b gap-x-2 py-2 pl-4 pr-2",children:[e("div",{className:"text-base font-semibold ",children:"Table Layout Editor"}),e("div",{className:"ml-auto flex gap-x-2",children:e(b,{isLoading:i,variant:"outline",size:"sm",onClick:()=>{if(!d.current)return;const e=d.current.getValue();let t;if(e)try{t=JSON.parse(e)}catch(e){return h("Invalid JSON",e.message)}else t=null;return Array.isArray(t)?t.some((e=>!e||!e.name||!e.field))?h("Invalid JSON","A table layout entry must contain the following properties:] {field, name, converter?}"):(a(!0),void c.types.update(n.id,{table_layout:t}).then((e=>{s({status:"success",title:"Table Layout updated",description:"The table layout has been updated successfully",duration:2e3}),r(e.table_layout)})).catch((e=>{s({status:"error",title:"Failed to update table layout",description:e.message,duration:5e3})})).finally((()=>{a(!1)}))):h("Invalid JSON","The table layout must be an array")},children:"Save Changes"})})]}),e("div",{className:"px-4 py-2",children:e(Xt,{value:u,extensions:Pi,editorRef:d})})]})}function Ai(e){return e?JSON.stringify(e,null,2):"[\n\n]"}const $i=[un,dn()];function Ei({refetch:n,collection:r}){const s=r.type?.id,i=m(void 0),a=v(),{client:c}=Pt(),[d,u]=o(!1),[h,p]=o({name:r.name,description:r.description||"",query:r.query?JSON.stringify(r.query,null,2):"",tags:r.tags||[],type:r.type?.id||"",allowed_types:r.allowed_types||[]}),f=l((()=>Ai(r.table_layout)),[r.table_layout]),g=(e,t)=>{p({...h,[e]:t})};return t("div",{className:"flex flex-col gap-4 py-2",children:[t(we,{title:"Configuration",action:e(b,{size:"lg",isDisabled:d,onClick:()=>{let e;try{e=h.query?JSON.parse(h.query):void 0}catch(e){return void a({title:"Invalid Query JSON",description:e.message,status:"error",duration:5e3})}const t={name:h.name,description:h.description,query:e,tags:h.tags,type:h.type,allowed_types:h.allowed_types};let s;if(t.name||(s="Name is required"),t.type||(t.type=null),s)a({title:"Validation failed",description:s,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 a({title:"Invalid Table Layout",description:e.message,status:"error",duration:5e3})}else t.table_layout=null}u(!0),c.store.collections.update(r.id,t).then((()=>{n(),a({title:"Collection updated",description:"Collection has been updated successfully",status:"success",duration:3e3})})).catch((e=>{a({title:"Failed to update collection",description:e.message,status:"error",duration:5e3})})).finally((()=>{u(!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(mn,{userRef:r.created_by,showTitle:!0}),t("span",{children:["at ",Vt(r.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(mn,{userRef:r.updated_by,showTitle:!0}),t("span",{children:["at ",Vt(r.updated_at).format("YYYY-MM-DD HH:mm:ss")]})]})]})]}),e(A,{label:"Name",required:!0,children:e($,{value:h.name,onChange:e=>g("name",e)})}),e(A,{label:"Description",children:e(fe,{value:h.description,onChange:e=>g("description",e)})}),!r.dynamic&&e(A,{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(di,{defaultValue:h.allowed_types||null,onChange:e=>{Array.isArray(e)?g("allowed_types",e.map((e=>e.id))):g("allowed_types",e?[e.id]:[])},isClearable:!0,multiple:!0})}),r.dynamic&&e(A,{label:"Query",description:"Define the query to dynamically fetch content for the collection.",children:e(fe,{className:de.INPUT,value:h.query,onChange:e=>g("query",e)})}),e(A,{label:"Table Layout",description:"Define a custom layout for displaying the collection in tables.",children:e(Xt,{className:"border-1 rounded-md border-border",value:f,extensions:$i,editorRef:i})}),e(A,{label:"Type",description:"Select a content type to assign custom properties and data to the collection.",children:e(di,{defaultValue:h.type||null,onChange:e=>{Array.isArray(e)?g("type",e.length>0?e[0].id:null):g("type",e?.id||null)},isClearable:!0})})]}),s&&e(zi,{typeId:s,collection:r})]})}function zi({typeId:t,collection:n}){const r=v(),{client:s}=Pt(),[i,a]=o(!1),{data:c,error:d}=B((()=>s.store.types.retrieve(t)),[t]),u=c?.object_schema||{},m=l((()=>new en(u,n.properties||{})),[u,n.properties]);if(d)return e(oe,{title:"Failed to load type",children:d.message});if(!c)return null;return e(we,{title:"Properties",action:e(b,{size:"lg",isLoading:i,type:"submit",children:"Save"}),children:e(tn,{object:m,onSubmit:e=>{const t={properties:e||{}};a(!0),s.store.collections.update(n.id,t).then((()=>{r({title:"Collection properties updated",description:"Collection has been updated successfully",status:"success",duration:3e3})})).catch((e=>{r({title:"Failed to update collection properties",description:e.message,status:"error",duration:5e3})})).finally((()=>{a(!1)}))}})})}function Oi({onChange:n,value:r,disabled:s=!1,placeholder:i="Select a collection",searchPlaceholder:a="Search collections",filterOut:c,allowDynamic:d=!0,multiple:u=!1}){const{client:m}=Pt(),[h,f]=o(""),[v,y]=o(!1),[C,_]=o(!1),T=xe(h,300),P=p((async e=>{y(!0);const t=e.trim(),n=await m.store.collections.search({dynamic:!!d&&void 0,name:C&&t||void 0});return y(!1),!C&&n.length>=1e3&&_(!0),c&&c.length>0?n.filter((e=>!c.includes(e.id))):n}),[m,d,c,C]),{data:I,error:A}=B((()=>P(C?T:"")),[C?T:"",P]),$=l((()=>I?u&&Array.isArray(r)?I.filter((e=>r.includes(e.id))):u||"string"!=typeof r?u?[]:void 0:I.find((e=>e.id===r)):u?[]:void 0),[I,r,u]),E=p((e=>{if(u){const t=Array.isArray(r)?r:[];if(t.includes(e.id)){const r=t.filter((t=>t!==e.id)),s=I?.filter((e=>r.includes(e.id)))||[];n(r,s)}else{const r=[...t,e.id],s=I?.filter((e=>r.includes(e.id)))||[];n(r,s)}}else n(e.id,e)}),[n,r,I,u]),z=p((()=>{n(void 0,void 0)}),[n]),O=p((e=>{f(e)}),[]),D=h.trim().length>0,U=l((()=>{if(!I)return[];if(C)return I;if(!D)return I;const e=h.toLowerCase();return I.filter((t=>t.name.toLowerCase().includes(e)))}),[I,C,D,h]),L=$&&D;if(A)return e(oe,{title:"Collection fetch failed",children:A.message});return t(x,{children:[e(w,{asChild:!0,children:t(b,{variant:"outline",role:"combobox","aria-haspopup":"listbox",className:g("w-full justify-between min-w-0"),disabled:s,children:[e("span",{className:"truncate flex-1 text-left min-w-0",children:u&&Array.isArray($)&&$.length>0?1===$.length?$[0].name:`${$.length} collections selected`:u||!$||Array.isArray($)?i:$.name}),e(ot,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e(N,{className:"mt-2 mb-2 w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:t(k,{shouldFilter:!1,children:[t("div",{className:"flex justify-between items-center border-b px-3","cmdk-input-wrapper":"",children:[e(Ne,{placeholder:a,value:h,onValueChange:O,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"}),v&&e("div",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"})]}),e(ke,{children:v?"Searching...":D?"No collections found.":"No collections available."}),t(j,{className:"max-h-[300px] overflow-auto",children:[L&&!u&&e(S,{value:"__clear__",onSelect:z,className:"text-muted-foreground",children:"Clear selection"}),U.map((n=>{const s=u&&Array.isArray(r)?r.includes(n.id):r===n.id;return t(S,{value:n.id,onSelect:()=>E(n),className:"flex items-center justify-between",children:[e("span",{className:"truncate",children:n.name}),s&&e(gt,{className:"ml-2 h-4 w-4 shrink-0"})]},n.id)}))]})]})})]})}function Di({action:n,objectIds:r,children:s}){const{store:i}=Pt(),a=v(),[l,c]=o(!1),d=p((()=>(c(!0),Promise.resolve(!0))),[]);na(n.id,d);return t("div",{children:[s,e(Ti,{isOpen:l,onClose:e=>{c(!1),void 0!==e&&i.runOperation({name:"change_type",ids:r,params:{typeId:e}}).then((e=>{a({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=>{a({status:"error",title:"Error changing type",description:e.message,duration:5e3})}))},title:"Change Content Type",confirmLabel:"Change Type",children:t("div",{className:"text-sm flex flex-col gap-x-2",children:[t("p",{children:["Choose a new Content Type for the selected object",r.length>1?"s":" ","or let the system choose or generate a type based on the content."]}),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 Ui={id:"changeType",name:"Change Content Type",description:"Change the Content Type of the selected documents",confirm:!1,component:Di};function Li({action:r,callback:s,children:i}){const[a,l]=o(!1),c=r.confirmationText||`Are you sure you want to ${r.name}?`,d=p((e=>r.confirm?(l(!0),Promise.resolve(!0)):s(e)),[r.confirm,s]),u=na(r.id,d);return t(n,{children:[i,e(be,{onConfirm:()=>{l(!1),s({...u.params,action:r})},onCancel:()=>l(!1),title:"Are you sure?",content:c,isOpen:a})]})}function Fi({action:t,objectIds:n,children:r}){const s=ta(),i=v(),{client:a}=Pt(),l=Ss(),o=Mt(),c=p((()=>{if(!n||!n.length)return i({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=>a.store.objects.delete(e)))).then((t=>{const r=t.length>1?"s":"";if(i({status:"success",title:`${t.length} object${r} deleted`,description:`Objects ${e(t.map((e=>e.id)).join(", "),100)} have been deleted`,duration:2e3}),l){s.params?.selection?.removeAll();const e=JSON.parse(JSON.stringify(l.facets));n.length===e._value.total&&l.resetFacets(),l.search()}else o("/objects")})).catch((e=>{i({status:"error",title:"Error deleting objects",description:e.message,duration:5e3})}))}),[n]);return e(Li,{action:t,callback:c,children:r})}const Ri={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:Fi,destructive:!0},Mi={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:Fi,destructive:!0};function Vi({action:t,objectIds:n}){const{store:r}=Pt(),s=v(),[i,a]=o(!1),[l,c]=o(!1),d=p((()=>(a(!0),Promise.resolve(!0))),[]),u=na(t.id,d);return e("div",{children:e(ii,{isExporting:l,isOpen:i,onClose:(e,t)=>{if(e&&(t||n.length>0)){c(!0);const i=u.params?.search?.query||{},l=u.params?.search?.result?.value?.objects?.map((e=>e.id))||void 0,o=async e=>r.objects.list({query:{parent:e}}).then((e=>e.map((e=>e.id))));(async()=>t?l?i.vector?l:[]:0===n.length?[]:(await o(n[0])).concat(n):n)().then((l=>{r.objects.exportProperties({objectIds:l,type:e,query:t&&!i.vector?i:{type:i.type}}).then((r=>{let i;if(e===si.CSV)i=new Blob([r.data],{type:r.type});else if(e===si.JSON)i=new Blob([JSON.stringify(r.data)],{type:r.type});else{const e=r.data;i=new Blob([new Uint8Array(e.data)],{type:r.type})}const a=window.URL.createObjectURL(i),l=document.createElement("a");l.download=r.name,l.href=a,l.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((()=>{c(!1),a(!1)}))}))}else a(!1)}})})}const qi={id:"exportProperties",name:"Export Properties",description:"Export all Object Properties",confirm:!1,component:Vi};function Wi({action:t,objectIds:n,collectionId:r}){const s=ta(),i=v(),{client:a}=Pt(),l=Ss(),o=p((()=>n&&n.length?r?a.store.collections.deleteMembers(r,n).then((()=>{const e=n.length>1?"s":"";i({status:"success",title:`${n.length} object${e} removed from collection`,description:"Objects have been removed from the collection",duration:2e3}),l&&(s.params?.selection?.removeAll(),l.search())})).catch((e=>{i({status:"error",title:"Error removing objects from collection",description:e.message,duration:5e3})})):(i({status:"error",title:"No collection context",description:"Cannot remove objects: no collection specified",duration:3e3}),Promise.resolve(!1)):(i({status:"error",title:"No objects selected",description:"Please select objects to remove from collection",duration:3e3}),Promise.resolve(!1))),[n,r]);return e(Li,{action:t,callback:o})}const Bi={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:Wi,destructive:!0};function Gi({action:t,objectIds:n,collectionId:r}){const s=v(),{client:i}=Pt(),[a,l]=o(!1),c=p((()=>(l(!0),Promise.resolve(!0))),[]);return na(t.id,c),e(Hi,{isOpen:a,onClose:e=>{if(l(!1),e)return i.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 Ji={id:"startWorkflow",name:"Start Workflow",description:"Start an workflow on the selected objects",confirm:!1,hideInList:!0,component:Gi};function Hi({isOpen:n,onClose:r}){return t(te,{onClose:()=>r(void 0),isOpen:n,className:"",children:[e(ne,{children:"Start a Workflow by Rule"}),e(Yi,{onClose:r})]})}function Ki(n){return{label:t("div",{children:[e("div",{children:n.name}),e("div",{className:"text-sm text-muted",children:n.description})]}),reverse:!0}}function Yi({onClose:n}){const[r,s]=o(void 0),i=ta();return t("div",{children:[t(re,{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(Ce,{options:i.wfRules,optionLayout:Ki,onChange:e=>{s(e)},value:r})})]}),t(ie,{children:[e(b,{variant:"secondary",onClick:()=>n(),children:"Cancel"}),e(b,{onClick:()=>{r&&n(r.id)},isDisabled:!r,children:"Start"})]})]})}class Qi{params;allActions=[qi,Ui,Ji,ia,Ri,Bi,Mi];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:Gi}))).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 Xi=d(void 0);function Zi({children:n}){const r=ps(),s=v(),{client:i}=Pt(),a=Ss(),{data:o,error:c}=B((()=>i.workflows.rules.list().then((e=>e.map((e=>({id:e.id,name:e.name,description:e.description,confirm:!1,isWorkflow:!0,component:Gi}))).sort(((e,t)=>e.name.localeCompare(t.name)))))),[]),d=l((()=>{const e=new Qi({selection:r,toast:s,client:i,search:a});return e.wfRules=o,e}),[r,o]);return c?e(oe,{title:"Failed to fetch workflows",children:c.message}):d&&t(Xi.Provider,{value:d,children:[e(ea,{}),n]})}function ea({}){const t=ta(),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 ta(){const e=u(Xi);if(!e)throw new Error("You cannot use useActionContext outside an ActionProvider");return e}function na(e,t){const n=ta();return c((()=>n.registerCallback(e,t)),[n,e,t]),n}function ra(e){const t=ta();return c((()=>(t.startWorkflow=e,()=>{t.startWorkflow=void 0})),[e,t]),t}function sa({action:t,objectIds:n}){const[r,s]=o(!1),i=p((()=>(n.length>0&&s(!0),Promise.resolve(!0))),[n]);return na(t.id,i),r&&e(je,{children:e(aa,{objectIds:n,isOpen:r,onClose:()=>{s(!1)}})})}const ia={id:"addToCollection",name:"Add to Collection",description:"Add documents to a collection",confirm:!1,component:sa};function aa({isOpen:n,onClose:r,objectIds:s}){return t(te,{isOpen:n,onClose:r,className:"max-w-lg w-full min-w-0 overflow-hidden",children:[e(ne,{className:"flex flex-col min-w-0 overflow-hidden",children:"Add to a Collection"}),e(Se,{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(la,{onClose:r,objectIds:s})})]})}function la({onClose:n,objectIds:r}){const s=v(),{client:i}=Pt(),[a,l]=o(),c=({collectionId:e})=>{e&&r?.length&&i.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(_e,{level:5,children:"Choose from existing collections"}),e(re,{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(Oi,{onChange:(e,t)=>{"string"==typeof e||void 0===e?l(e):Array.isArray(e)&&e.length>0?l(e[0]):l(void 0)},value:a})})}),e(ie,{children:e(b,{isDisabled:!a,onClick:()=>a&&c({collectionId:a}),children:"Add to Collection"})})]})},{name:"create",label:"Create new",content:e("div",{className:"p-4",children:e(ui,{onClose:n,onAddToCollection:e=>c({collectionId:e}),redirect:!1})})}];return t(Te,{defaultValue:"select",tabs:d,fullWidth:!0,children:[e(Pe,{}),e(Ie,{})]})}function oa(){const n=ps(),r=n.size(),s=r>1?"s":"",i=n?.hasSelection(),a=n?.isSingleSelection();return e(Zi,{children:t("div",{className:"flex items-center gap-x-2",children:[i&&!a&&t("div",{className:"flex items-center gap-x-1 shrink-0",children:[t("div",{className:"text-sm nowrap",children:[r," document",s," selected"]}),e(b,{title:"Clear selection",variant:"ghost",onClick:()=>{n?.removeAll()},children:e(lt,{className:"size-4"})})]}),e(ha,{selection:n,children:e(b,{variant:"ghost",alt:"More action",size:"sm",children:e(vt,{size:16})})}),i&&e(ca,{selection:n})]})})}function ca({}){return e(ua,{})}function da({collectionId:r}){const[s,i]=o([]),a=ps(),l=a?.hasSelection();return!l&&t(n,{children:[e(b,{onClick:()=>(()=>{const e=document.createElement("input");e.type="file",e.multiple=!0,e.accept="*",e?.click(),e.onchange=e=>{const t=e.target.files;t&&i(Array.from(t))}})(),children:"Upload"}),e(Es,{collectionId:r??"",isOpen:s.length>0,onClose:()=>i([]),files:s,title:"Upload Files",onUploadComplete:e=>{e&&e.success&&i([])},children:e("div",{className:"text-sm",children:"Select the associated Content Type, or let the system choose or generate the type based on the content."})})]})}function ua(){const t=ta();return t.params.selection.hasSelection()&&e(b,{onClick:()=>t.run(Ji.id),children:"Start Workflow"})}function ma(e){return{label:e.name,className:r("flex-1 px-2 py-2 hover:bg-accent nowrap",e.destructive?"text-destructive":"")}}function ha({selection:n,children:r}){const s=ta();return t(x,{hover:!0,children:[e(w,{children:r}),e(N,{className:"p-0 w-50",align:"end",sideOffset:6,children:e(pa,{executeAction:e=>{s.run(e.id)},selection:n})})]})}function pa({executeAction:t,selection:n}){const r=ta(),s=n?.hasSelection()?r.actions.filter((e=>!e.hideInList)):[qi];return e("div",{className:"rounded-md shadow-md py-2",children:e("div",{className:"px-1 text-sm",children:e(Ce,{options:s,optionLayout:ma,onChange:e=>{t(e)},noCheck:!0})})})}function fa({value:n,onChange:r,onSend:s,disabled:i=!1,isSending:a=!1,isCompleted:l=!1,activeTaskCount:d=0,placeholder:u="Type your message..."}){const h=m(null),[p,f]=o(!1);c((()=>{!i&&l&&h.current?.focus()}),[i,l]);return t("div",{className:"p-3 border-t border-muted flex-shrink-0",style:{minHeight:"90px"},children:[t("div",{className:"flex items-center space-x-2",children:[t("div",{className:"flex flex-1 space-x-1",children:[e($,{ref:h,value:n,onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),s())},onChange:r,disabled:i||a,placeholder:u,className:"pr-12 py-2.5"}),e(b,{variant:"ghost",className:"rounded-full",disabled:!l,onClick:()=>f(!0),alt:"Link Object",children:e(yt,{className:"size-4"})})]}),t(b,{onClick:s,disabled:i||a||!n.trim(),className:"px-4 py-2.5",children:[a?e(L,{size:"sm",className:"mr-2"}):e(bt,{className:"size-4 mr-2"})," 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(xt,{className:"h-3 w-3 mr-1 text-attention"}),t("span",{children:["Agent has ",d," active workstream",1!==d?"s":""," running"]})]}):i?"Agent is processing, you can continue once it completes...":"You can send a message at any time"}),t(te,{isOpen:p,onClose:()=>f(!1),className:"min-w-[60vw]",children:[e(ne,{children:"Link Object"}),e(re,{className:"pb-6",children:e(Ms,{onChange:e=>{const t=`[${e.properties?.title||e.name||"Object"}](store:${e.id})`,s=n||"",i=h.current?.selectionStart||s.length,a=s.substring(0,i)+t+s.substring(i);r(a),f(!1),setTimeout((()=>{if(h.current){h.current.focus();const e=i+t.length;h.current.setSelectionRange(e,e)}}),100)}})})]})]})}function ga({plan:r,workstreamStatus:s,isOpen:i,onClose:a,plans:l=[],activePlanIndex:o=0,onChangePlan:c=()=>{}}){return i?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(b,{variant:"ghost",onClick:a,children:[e(lt,{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 i=r.plan||[],a=i.length;let l=0;a>0&&i.forEach((e=>{if(e&&e.id){const t=e.id.toString();"completed"===s.get(t)&&l++}}));const o=a>0?Math.round(l/a*100):0;return t(n,{children:[e("div",{className:"w-full bg-muted rounded-full h-2",children:e("div",{className:"bg-background h-2 rounded-full",style:{width:`${o}%`}})}),e("span",{className:"text-xs text-muted",children:a>0?`${l}/${a}`:"0/0"})]})})()})]}),l.length>1&&t("div",{className:"mb-3 flex items-center justify-between",children:[e(b,{variant:"ghost",onClick:()=>c(Math.min(l.length-1,o+1)),disabled:o>=l.length-1,children:"Older Plan"}),e("div",{className:"text-xs text-muted",children:l[o]?.timestamp?new Date(l[o].timestamp).toLocaleTimeString():"Unknown time"}),e(b,{variant:"ghost",onClick:()=>c(Math.max(0,o-1)),disabled:o<=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 i=n.id?n.id.toString():`task-${r}`,a=n.goal||`Task ${r+1}`;let l=n.status||"pending";s.has(i)&&(l=s.get(i));let o=wt,c="text-muted";return"in_progress"===l?(o=Re,c="text-info"):"completed"===l&&(o=Fe,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:i}),t("div",{className:"w-full",children:[e("div",{className:"text-sm font-medium mb-2 text-muted",children:a}),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(o,{className:"size-3.5"})}),e(y,{variant:"completed"===l?"success":"in_progress"===l?"info":"default",children:"completed"===l?"Completed":"in_progress"===l?"In Progress":"Pending"})]})]})]},r)})):t("div",{className:"p-3 text-center text-muted italic",children:[e(Ue,{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()))),i=Array.from(s.entries()).filter((([e])=>"main"!==e&&!n.has(e)));return i.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:i.map((([n,r])=>{let s=wt,i="text-gray-400",a="bg-gray-100 dark:bg-gray-800",l="Pending";return"in_progress"===r?(s=Re,i="text-info",a="bg-info/20",l="In Progress"):"completed"===r&&(s=Fe,i="text-success",a="bg-success/20",l="Completed"),t("div",{className:`flex items-center p-1.5 rounded ${a}`,children:[e("div",{className:`mr-1.5 ${i}`,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:l})]},n)}))})})]}):null})()]})]}):null}function va(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(xa,{...t,run:r})}return r?e(ba,{...t}):e(ya,{})}function ya(){return t(se,{status:"info",icon:e(ze,{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 ba({initialMessage:n,startWorkflow:r,onClose:s,isModal:i=!1,placeholder:a="Type your message...",startButtonText:l="Start Agent",title:d="Start New Conversation"}){const[u,h]=o(""),[p,f]=o(!1),[g,y]=o(),x=v(),w=m(null);c((()=>{w.current&&w.current.focus()}),[]);const N=async()=>{if(!r)return;const e=u.trim();if(e&&!p){f(!0);try{sessionStorage.removeItem("plan-panel-shown"),x({title:"Starting agent...",status:"info",duration:3e3});const t=await r(e);t&&(y({runId:t.run_id,workflowId:t.workflow_id}),h(""),x({title:"Agent started",status:"success",duration:3e3}))}catch(e){x({title:"Error starting workflow",status:"error",duration:3e3,description:e instanceof Error?e.message:"Unknown error"})}finally{f(!1)}}};return g?e(xa,{onClose:s,isModal:i,initialMessage:n,placeholder:a,run:g,title:d}):t("div",{className:"flex flex-col h-full bg-white dark:bg-gray-900 overflow-hidden border-0",children:[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(Nt,{className:"size-3.5 text-muted"})}),e("span",{className:"font-medium text-sm text-gray-700 dark:text-gray-300",children:d})]}),s&&!i&&e(b,{size:"xs",variant:"ghost",onClick:s,title:"Close",className:"text-slate-500 hover:text-slate-700",children:e(Ve,{className:"size-4"})})]}),t("div",{className:"flex-1 overflow-y-auto px-4 py-6 bg-white dark:bg-gray-900 flex flex-col 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 max-w-md",children:n}),t("div",{className:"bg-white dark:bg-slate-800 p-4 max-w-md border-l-2 border-blue-400 dark:border-blue-500",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:[t("div",{className:"flex items-center gap-2",children:[e("div",{className:"flex-1",children:e("input",{ref:w,value:u,onChange:e=>h(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),N())},placeholder:a,disabled:p,className:"w-full py-2 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:ring-0 rounded-md"})}),t(b,{onClick:N,disabled:!u.trim()||p,className:"px-3 py-2 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:[p?e(L,{size:"sm",className:"mr-1.5"}):e(bt,{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:"Type a message to start the conversation"})]})]})}function xa({run:n,title:r,interactive:s=!0,onClose:i,isModal:a=!1,placeholder:d="Type your message...",resetWorkflow:u}){const{client:h}=Pt(),p=m(null),[f,g]=o([]),[y,b]=o(!1),[x,w]=o(""),[N,k]=o(!1),[C,j]=o("sliding"),[S,_]=o(!a),[T,P]=o([]),[I,A]=o(0),[$,E]=o(new Map),[z,O]=o(0),D=v(),[U,L]=o(s),[F,R]=o(null),M=l((()=>{const e=T[I]||{plan:{plan:[]},timestamp:0},t=$.get(e.timestamp)||new Map;return{plan:e.plan,workstreamStatus:t}}),[T,I,$]);c((()=>{if(!y){const e=setInterval((()=>{O((()=>Math.floor(Math.random()*(On.length-1))))}),4e3);return()=>clearInterval(e)}}),[y]);c((()=>(g([]),P([]),A(0),E(new Map),_(!1),R(null),(async()=>{try{const e=await h.store.workflows.getRunDetails(n.runId,n.workflowId);R(e.status)}catch(e){console.error("Failed to check workflow status:",e)}})(),h.store.workflows.streamMessages(n.workflowId,n.runId,(e=>{e.message&&g((t=>t.find((t=>t.timestamp===e.timestamp))?t:(function(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)}(t,e),[...t])))})),()=>{g([])})),[n.runId,h.store.workflows]),c((()=>{b(!function(e){if(!e.length)return!0;const t=new Map;if(e.forEach((e=>{const n=Un(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}`),Dn.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}`),Dn.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(!Dn.includes(t.type))return console.log(`[isInProgress] Workstream ${e} is still active`),!0}return console.log("[isInProgress] All workstreams are completed"),!1}(f)),0===T.length&&_(!1)}),[f,T.length]),c((()=>{if(1===T.length&&!S&&!sessionStorage.getItem("plan-panel-shown")){const e=setTimeout((()=>{_(!0),sessionStorage.setItem("plan-panel-shown","true")}),500);return()=>clearTimeout(e)}f.forEach((e=>{if(e.type===It.PLAN)try{console.log("PLAN message received:",e.type);let t=null;if(e.details&&"object"==typeof e.details&&e.details.plan&&Array.isArray(e.details.plan)&&(console.log("Valid plan array found in message.details.plan"),t={plan:e.details.plan}),t){const n="number"==typeof e.timestamp?e.timestamp:new Date(e.timestamp).getTime();if(-1===T.findIndex((e=>e.timestamp===n))&&t){console.log("Adding new plan to plans array");const e={plan:t,timestamp:n};console.log("Adding plan to plans array:",e),P((t=>{const n=[e,...t];return console.log("New plans array:",n),n})),A(0),console.log("Setting showSlidingPanel to true"),_(!0);const r=new Map;r.set("main","in_progress"),Array.isArray(t.plan)&&t.plan.forEach((e=>{if(e&&"object"==typeof e&&e.id){const t=e.id.toString();r.set(t,e.status||"pending")}})),E((e=>{const t=new Map(e);return t.set(n,r),t}))}}}catch(e){console.error("Failed to parse plan from message:",e)}e.type===It.UPDATE&&e.details&&e.details.updates&&Array.isArray(e.details.updates)&&console.log("Ignoring UPDATE message with details.updates - waiting for PLAN message with full plan")}));const e=f[f.length-1];e&&(e.type===It.TERMINATED?(L(!1),R("TERMINATED")):L(!!s||e.type===It.REQUEST_INPUT))}),[f,T,I]);const V=r||n.workflowId.split(":")[2]||"Agent Conversation";return t("div",{className:"flex gap-2 h-full",children:[t("div",{className:"flex flex-col h-full min-h-0 border-0 "+(S?"lg:w-2/3 flex-1":"flex-1 mx-auto "+(a?"":"max-w-4xl")),children:[e(Gn,{title:V,isCompleted:y,onClose:i,isModal:a,run:n,viewMode:C,onViewModeChange:j,showPlanPanel:S,hasPlan:T.length>0,onTogglePlanPanel:()=>{_(!S),S||sessionStorage.setItem("plan-panel-shown","true")},onDownload:async()=>{try{const e=await async function(e,t){return e.files.getDownloadUrl(`agents/${t}/conversation.json`).then((e=>e.url))}(h,n.runId);e&&window.open(e,"_blank")}catch(e){console.error("Failed to download conversation",e),D({status:"error",title:"Failed to download conversation",duration:3e3})}},onCopyRunId:()=>{navigator.clipboard.writeText(n.runId),D({status:"success",title:"Run ID copied",duration:2e3})},resetWorkflow:u}),0!==f.length||y?e(Mn,{messages:f,bottomRef:p,viewMode:C,isCompleted:y,plan:M.plan,workstreamStatus:M.workstreamStatus,showPlanPanel:S,onTogglePlanPanel:()=>{console.log("Toggle plan panel called, current state:",S),_(!S)},plans:T,activePlanIndex:I,onChangePlan:e=>A(e),taskLabels:M.plan.plan?.reduce(((e,t)=>(t.id&&t.goal&&e.set(t.id.toString(),t.goal),e)),new Map)}):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(In,{size:"sm",color:"blue"}),e("div",{className:"text-sm text-muted font-medium",children:On[z]})]}),e("div",{className:"mt-4 flex justify-center",children:e(Pn,{color:"blue",className:"mt-1"})})]})}),F&&("RUNNING"!==F?t(se,{status:"COMPLETED"===F?"success":"done",icon:null,className:"flex-shrink-0 m-2",children:["This Workflow is ",F]}):U&&e(fa,{value:x,onChange:w,onSend:()=>{const e=x.trim();e&&!N&&(k(!0),w(""),h.store.workflows.sendSignal(n.workflowId,n.runId,"UserInput",{message:e}).then((()=>{b(!1),D({status:"success",title:"Message Sent",duration:2e3})})).catch((e=>{D({status:"error",title:"Failed to Send Message",description:e instanceof Error?e.message:"Unknown error",duration:3e3})})).finally((()=>{k(!1)})))},disabled:!1,isSending:N,isCompleted:y,activeTaskCount:(()=>{if(!f.length)return 0;const e=new Map;f.forEach((t=>{const n=Un(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];[It.COMPLETE,It.IDLE].includes(e.type)||t++}return t})(),placeholder:d}))]}),S&&e("div",{className:"h-full lg:w-1/3 border-l",children:e(ga,{plan:M.plan,workstreamStatus:M.workstreamStatus,isOpen:S,onClose:()=>_(!1),plans:T,activePlanIndex:I,onChangePlan:A})})]})}function wa({children:t,fallback:n}){return Na?e(Na,{fallback:n,children:t}):e(hn,{FallbackComponent:n,children:t})}let Na=null;function ka(e){Na=e}function Ca({children:t}){return e(wa,{fallback:ja,children:t})}function ja({error:n}){return t(se,{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 Sa({children:t}){return e(wa,{fallback:_a,children:t})}function _a({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 Ta({children:t}){return e(wa,{fallback:Pa,children:t})}function Pa({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 Ia({className:n,children:s,title:i,description:a,actions:l,breadcrumbs:o,isCompact:c=!1,useDynamicBreadcrumbs:d=!0}){const u=Mt(),m=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){const e=n[1];return`${pn(e)} Detail`}return n.length>=2?pn(n[n.length-1]):1===n.length?pn(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:m(n),href:n.href,onClick:()=>window.history.go(-s)})}))}return o&&o.length>0&&o.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:()=>u(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(Ae,{path:h,separator:e(ut,{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:i}),a&&e(V,{description:a,children:e(De,{className:"size-4 text-muted"})})]})]}),e("div",{className:"flex gap-x-2 shrink-0",children:l})]}),s&&e("div",{className:"w-full flex items-center",children:s})]})}function Aa({}){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"})]})}class $a{totalPages;layoutUrls=[];cache;constructor(e){this.totalPages=e,this.cache=new Array(e)}async loadUrls(e,t){const n=[];for(let r=0;r<this.totalPages;r++)n.push(Ma(e,t,r+1));const r=await Promise.all(n);this.layoutUrls=r.map((e=>e.url))}async getPageLayout(e){const t=e-1;let n=this.cache[t];if(void 0===n){const e=this.layoutUrls[t];n=await fetch(e,{method:"GET"}).then((e=>{if(e.ok)return e.text();throw new Error("Failed to fetch json layout: "+e.statusText)})),this.cache[t]=n}return n}}class Ea{totalPages;markdownUrls=[];cache;constructor(e){this.totalPages=e,this.cache=new Array(e)}async loadUrls(e,t){const n=[];for(let r=0;r<this.totalPages;r++)n.push(Va(e,t,r+1));const r=await Promise.all(n);this.markdownUrls=r.map((e=>e.url))}async getPageMarkdown(e){const t=e-1;let n=this.cache[t];if(void 0===n){const e=this.markdownUrls[t];n=await fetch(e,{method:"GET"}).then((e=>{if(e.ok)return e.text();throw new Error("Failed to fetch markdown: "+e.statusText)})),this.cache[t]=n}return n}}const za=d(void 0);function Oa({children:t,object:n}){const{client:r}=Pt(),[s,i]=o();return c((()=>{const e=n.metadata.page_count||10;(async function(e,t,n){const r=[];for(let s=0;s<n;s++)r.push(Ua(e,t.id,s+1));const s=await Promise.all(r),i=[];for(let r=0;r<n;r++)i.push(La(e,t.id,r+1));const a=await Promise.all(i),l=[];for(let r=0;r<n;r++)l.push(Fa(e,t.id,r+1));const o=await Promise.all(l),c=[];for(let r=0;r<n;r++)c.push(Ra(e,t.id,r+1));const d=await Promise.all(c),u=new $a(n);await u.loadUrls(e,t.id);const m=new Ea(n);await m.loadUrls(e,t.id);const h=t.text?Ba(t.text):"";return{count:n,urls:s.map((e=>e.url)),originalUrls:d.map((e=>e.url)),annotatedUrls:a.map((e=>e.url)),instrumentedUrls:o.map((e=>e.url)),layoutProvider:u,markdownProvider:m,xml:h,xmlPages:t.text?Wa(h):[]}})(r,n,e).then(i)}),[n.id]),s&&e(za.Provider,{value:s,children:t})}function Da(e){return`magic-pdf/${e}`}function Ua(e,t,n){return e.files.getDownloadUrl(function(e,t,n=".jpg"){return`${Da(e)}/pages/page-${t}${n}`}(t,n))}function La(e,t,n){return e.files.getDownloadUrl(function(e,t,n=".jpg"){return`${Da(e)}/pages/page-${t}-annotated${n}`}(t,n))}function Fa(e,t,n){return e.files.getDownloadUrl(function(e,t,n=".jpg"){return`${Da(e)}/pages/page-${t}.instrumented${n}`}(t,n))}function Ra(e,t,n){return e.files.getDownloadUrl(function(e,t,n=".jpg"){return`${Da(e)}/pages/page-${t}.original${n}`}(t,n))}function Ma(e,t,n){return e.files.getDownloadUrl(function(e,t){return`${Da(e)}/pages/page-${t}.layout.json`}(t,n))}function Va(e,t,n){return e.files.getDownloadUrl(function(e,t){return`${Da(e)}/pages/page-${t}.md`}(t,n))}function qa(){const e=a.useContext(za);if(!e)throw new Error("usePdfPagesInfo must be used within a PdfPageProvider");return e}function Wa(e){const t=(new DOMParser).parseFromString(Ba(e),"text/xml").getElementsByTagName("page"),n=new XMLSerializer;return Array.from(t).map((e=>n.serializeToString(e)))}function Ba(e){return e.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,"").replace(/<\?xml.*?\?>/g,"")}function Ga({object:r}){const{client:s}=Pt(),i=e=>{(function(e,t,n){return e.files.getDownloadUrl(`${Da(t)}/${n}`).then((e=>e.url))})(s,r.id,e).then((e=>window.open(e,"_blank")))},a=(()=>{if("document"===r.metadata?.type){const e=r.metadata;return e.content_processor?.type||"xml"}return"xml"})();return e("div",{className:"absolute bottom-[58px] right-[20px] w-[36px] h-[36px] cursor-pointer text-indigo-400 border-indigo-400 hover:border-indigo-500 hover:text-indigo-500 border-2 rounded-full shadow-xs flex items-center justify-center",children:t(nn,{strategy:"absolute",placement:"top-end",zIndex:100,offset:20,children:[e(nn.Trigger,{click:!0,children:e(kt,{className:"size-6"})}),e(nn.Content,{children:e("div",{className:"rounded-md shadow-md border border-gray-100 bg-white dark:bg-slate-50 dark:border-slate-100 min-w-[200px] flex flex-col divide-y",children:"markdown"===a?e("button",{className:"p-2 cursor-pointer hover:bg-slate-50 dark:hover:bg-slate-100",onClick:()=>i("document.md"),children:"document.md"}):t(n,{children:[e("button",{className:"p-2 cursor-pointer hover:bg-slate-50 dark:hover:bg-slate-100",onClick:()=>i("annotated.pdf"),children:"annotated.pdf"}),e("button",{className:"p-2 cursor-pointer hover:bg-slate-50 dark:hover:bg-slate-100",onClick:()=>i("document.xml"),children:"document.xml"}),e("button",{className:"p-2 cursor-pointer hover:bg-slate-50 dark:hover:bg-slate-100",onClick:()=>i("analyzed-pages.json"),children:"analyzed-pages.json"})]})})})]})})}var Ja;function Ha({className:s,currentPage:i,onChange:a,object:l}){const c=()=>{if("document"===l.metadata?.type){const e=l.metadata;return e.content_processor?.type||"xml"}return"xml"},[d,u]=o("markdown"===c()?Ja.original:Ja.default),h=m(null),{urls:p,originalUrls:f,annotatedUrls:g,instrumentedUrls:v}=qa(),y=d===Ja.instrumented?v:d===Ja.annotated?g:d===Ja.original?f:p;return t("div",{ref:h,className:r("flex flex-col items-stretch gap-y-2",s),children:[t("div",{className:"flex h-5 items-center justify-center relative",children:[e("button",{className:Ya,onClick:()=>{i>1&&(a(i-1),h.current&&h.current.querySelector(`div[data-index="${i-1}"]`)?.scrollIntoView({behavior:"smooth",block:"end",inline:"center"}))},children:e(Ct,{className:"w-5 h-5"})}),e("div",{className:"absolute right-3 flex gap-x-1",children:"markdown"===c()?t(n,{children:[e("button",{className:Qa(Ja.original,d),onClick:()=>u(Ja.original),children:e(jt,{className:"w-5 h-5 mt-1"})}),e("button",{className:Qa(Ja.instrumented,d),onClick:()=>u(Ja.instrumented),children:e(St,{className:"w-5 h-5 mt-1"})})]}):t(n,{children:[e("button",{className:Qa(Ja.default,d),onClick:()=>u(Ja.default),children:e(jt,{className:"w-5 h-5 mt-1"})}),e("button",{className:Qa(Ja.instrumented,d),onClick:()=>u(Ja.instrumented),children:e(St,{className:"w-5 h-5 mt-1"})}),e("button",{className:Qa(Ja.annotated,d),onClick:()=>u(Ja.annotated),children:e(_t,{className:"w-5 h-5 mt-1"})})]})})]}),e("div",{className:"flex flex-col items-center gap-2 flex-1 overflow-y-auto px-2",children:y.map(((t,n)=>e(Ka,{url:t,currentPage:i,pageNumber:n+1,onSelect:()=>a(n+1)},n)))}),e("div",{className:"flex h-5 items-center justify-center relative",children:e("button",{className:Ya,onClick:()=>{i<p.length&&(a(i+1),h.current&&h.current.querySelector(`div[data-index="${i+1}"]`)?.scrollIntoView({behavior:"smooth",block:"end",inline:"center"}))},children:e(Tt,{className:"size-5"})})})]})}function Ka({url:n,pageNumber:s,currentPage:i,onSelect:a}){return t("div",{className:"p-2 hover:bg-gray-200 dark:hover:bg-slate-600 rounded-md","data-index":s-1,children:[e("div",{className:r("relative border-[2px] cursor-pointer",s===i?"border-blue-500 dark:border-pink-400":"border-gray-300"),onClick:a,children:e("img",{src:n,alt:`Page ${s}`})}),e($e,{className:"text-sm text-gray-500 dark:text-gray-400 pt-1 font-semibold align",children:s})]})}!function(e){e[e.default=0]="default",e[e.original=1]="original",e[e.instrumented=2]="instrumented",e[e.annotated=3]="annotated"}(Ja||(Ja={}));const Ya="cursor-pointer text-gray-500 dark:text-gray-400 hover:text-blue-600 dark:hover:text-blue-500 hover:font-semibold";function Qa(e,t){return e===t?"${BTN_CLASS} text-pink-600":`${Ya}`}const Xa={attributeKeyColor:"#FFD700",attributeValueColor:"#FF4500",tagColor:"#87CEFA",textColor:"#00FF00",separatorColor:"#FFD700",commentColor:"#BEBEBE",cdataColor:"#33CC66"};function Za({viewType:t,pageNumber:n}){switch(t){case"json":return e(tl,{pageNumber:n});case"markdown":return e(nl,{pageNumber:n});default:return e(el,{pageNumber:n})}}function el({pageNumber:t}){const[n,r]=o(),{xmlPages:s}=qa();return f((()=>{const e=window.matchMedia("(prefers-color-scheme: dark)"),t=e=>{r(e.matches?Xa:void 0)};return e.addEventListener("change",t),e.matches&&r(Xa),()=>{e.removeEventListener("change",t)}}),[]),e("div",{className:"px-4 py-2",children:e(rn,{xml:s[t-1],collapsible:!0,theme:n})})}function tl({pageNumber:t}){const[n,r]=o(),{layoutProvider:s}=qa();return c((()=>{s.getPageLayout(t).then((e=>r(e?JSON.parse(e):void 0))).catch((e=>{console.error(e),r(void 0)}))}),[t]),n&&e(sn,{className:"w-full",data:n})}function nl({pageNumber:t}){const[n,r]=o(),{markdownProvider:s}=qa();return c((()=>{s.getPageMarkdown(t).then(r).catch((e=>{console.error(e),r(void 0)}))}),[t]),e("div",{className:"px-4 py-2 prose prose-sm max-w-none dark:prose-invert",children:n?e(Jt,{children:n}):e("div",{children:"No markdown content available"})})}function rl({objectId:t,onClose:n}){const{client:r}=Pt(),{data:s,error:i}=B((()=>r.store.objects.retrieve(t,"+text")),[t]);return i?e(oe,{title:"Fetching document failed",children:i.message}):s?e("div",{className:"fixed inset-0 bg-white dark:bg-slate-700 z-50 flex items-center justify-center",children:e(Oa,{object:s,children:e(sl,{object:s,onClose:n})})}):"Loading..."}function sl({object:r,onClose:s}){const[i,a]=o((()=>{if("document"===r.metadata?.type){const e=r.metadata,t=e.content_processor?.type;if("markdown"===t)return"markdown";if("xml"===t)return"xml"}return"xml"})()),[l,d]=o(1),u=(()=>{if("document"===r.metadata?.type){const e=r.metadata;return e.content_processor?.type||"xml"}return"xml"})(),h=m(null),p=m(null),f=m(null);var g;return c((()=>{if(g.handler.current&&g.left.current&&g.right.current){const e=g.handler.current,t=g.left.current,n=g.right.current,r=e=>{let r=e.clientX,s=t.offsetWidth,i=n.offsetLeft;const a=e=>{const a=e.clientX-r;t.style.width=`${s+a}px`,n.style.left=`${i+a}px`,e.target.classList.add("resizing")},l=e=>{e.target.classList.remove("resizing"),a(e),document.removeEventListener("mousemove",a),document.removeEventListener("mouseup",l)};document.addEventListener("mousemove",a),document.addEventListener("mouseup",l)};return e.addEventListener("mousedown",r),()=>{e.removeEventListener("mousedown",r)}}}),[(g={handler:h,left:p,right:f}).handler.current,g.left.current,g.right.current]),t(n,{children:[t("div",{ref:p,className:"absolute top-0 left-0 bottom-0 w-[50%] bg-gray-100 dark:bg-slate-800 flex items-stretch justify-stretch py-2",children:[e(Ha,{className:"flex-1",currentPage:l,onChange:d,object:r}),e("div",{ref:h,className:"w-[2px] p-[2px] m-0 bg-slate-300 cursor-ew-resize"})]}),e("div",{ref:f,className:"absolute top-0 left-[50%] right-0 bottom-0 flex items-stretch justify-stretch overflow-auto p-2",children:e(Za,{pageNumber:l,viewType:i})}),e(Ga,{object:r}),"xml"===u&&e(il,{type:i,onSwitch:a}),!!s&&e("div",{className:"absolute top-6 right-7 w-9 h-9 cursor-pointer text-red-400 border-red-400 hover:border-red-500 hover:text-red-500 border-2 rounded-full shadow-xs flex items-center justify-center",onClick:s,children:e(lt,{className:"size-6"})})]})}function il({type:e="xml",onSwitch:n}){return t("div",{className:"absolute bottom-[16px] right-[20px] w-[36px] h-[36px] cursor-pointer text-indigo-400 border-indigo-400 hover:border-indigo-500 hover:text-indigo-500 border-2 rounded-full shadow-xs flex items-center justify-center",onClick:()=>{"xml"===e?n("json"):"json"===e?n("markdown"):"markdown"===e&&n("xml")},children:["xml"===e&&al,"json"===e&&ol,"markdown"===e&&ll]})}const al=e("svg",{width:"16px",height:"16px",viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg",fill:"currentColor",children:e("path",{"fill-rule":"evenodd","clip-rule":"evenodd",d:"M6 2.984V2h-.09c-.313 0-.616.062-.909.185a2.33 2.33 0 0 0-.775.53 2.23 2.23 0 0 0-.493.753v.001a3.542 3.542 0 0 0-.198.83v.002a6.08 6.08 0 0 0-.024.863c.012.29.018.58.018.869 0 .203-.04.393-.117.572v.001a1.504 1.504 0 0 1-.765.787 1.376 1.376 0 0 1-.558.115H2v.984h.09c.195 0 .38.04.556.121l.001.001c.178.078.329.184.455.318l.002.002c.13.13.233.285.307.465l.001.002c.078.18.117.368.117.566 0 .29-.006.58-.018.869-.012.296-.004.585.024.87v.001c.033.283.099.558.197.824v.001c.106.273.271.524.494.753.223.23.482.407.775.53.293.123.596.185.91.185H6v-.984h-.09c-.2 0-.387-.038-.563-.115a1.613 1.613 0 0 1-.457-.32 1.659 1.659 0 0 1-.309-.467c-.074-.18-.11-.37-.11-.573 0-.228.003-.453.011-.672.008-.228.008-.45 0-.665a4.639 4.639 0 0 0-.055-.64 2.682 2.682 0 0 0-.168-.609A2.284 2.284 0 0 0 3.522 8a2.284 2.284 0 0 0 .738-.955c.08-.192.135-.393.168-.602.033-.21.051-.423.055-.64.008-.22.008-.442 0-.666-.008-.224-.012-.45-.012-.678a1.47 1.47 0 0 1 .877-1.354 1.33 1.33 0 0 1 .563-.121H6zm4 10.032V14h.09c.313 0 .616-.062.909-.185.293-.123.552-.3.775-.53.223-.23.388-.48.493-.753v-.001c.1-.266.165-.543.198-.83v-.002c.028-.28.036-.567.024-.863-.012-.29-.018-.58-.018-.869 0-.203.04-.393.117-.572v-.001a1.502 1.502 0 0 1 .765-.787 1.38 1.38 0 0 1 .558-.115H14v-.984h-.09c-.196 0-.381-.04-.557-.121l-.001-.001a1.376 1.376 0 0 1-.455-.318l-.002-.002a1.415 1.415 0 0 1-.307-.465v-.002a1.405 1.405 0 0 1-.118-.566c0-.29.006-.58.018-.869a6.174 6.174 0 0 0-.024-.87v-.001a3.537 3.537 0 0 0-.197-.824v-.001a2.23 2.23 0 0 0-.494-.753 2.331 2.331 0 0 0-.775-.53 2.325 2.325 0 0 0-.91-.185H10v.984h.09c.2 0 .387.038.562.115.174.082.326.188.457.32.127.134.23.29.309.467.074.18.11.37.11.573 0 .228-.003.452-.011.672-.008.228-.008.45 0 .665.004.222.022.435.055.64.033.214.089.416.168.609a2.285 2.285 0 0 0 .738.955 2.285 2.285 0 0 0-.738.955 2.689 2.689 0 0 0-.168.602c-.033.21-.051.423-.055.64a9.15 9.15 0 0 0 0 .666c.008.224.012.45.012.678a1.471 1.471 0 0 1-.877 1.354 1.33 1.33 0 0 1-.563.121H10z"})}),ll=e("svg",{width:"16px",height:"16px",viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg",fill:"currentColor",children:e("path",{d:"M4.708 5.578L2.061 8.224l2.647 2.646-.708.708-3-3V7.87l3-3 .708.708zm7-.708L11 5.578l2.647 2.646L11 10.87l.708.708 3-3V7.87l-3-3zM4.908 13l.894.448 5-10L9.908 3l-5 10z"})}),ol=e("svg",{width:"16px",height:"16px",viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg",fill:"currentColor",children:e("path",{d:"M14.85 3H1.15C.52 3 0 3.52 0 4.15v7.69C0 12.48.52 13 1.15 13h13.69c.64 0 1.15-.52 1.15-1.15v-7.7C16 3.52 15.48 3 14.85 3zM9 11H7.5L5.5 9l-1 1.5H3V5h1.5l1 2 2-2H9v6zm2.99.5L9.5 8H11V5h1v3h1.5l-2.51 3.5z"})});function cl(...e){const t=Array.from(e);return t.__AnyOf__=!0,t}function dl(...e){return Array.from(e)}function ul(e){return!0===e.__AnyOf__}class ml{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(ul(e))return e.some((e=>this.permissions.has(e)));for(const t of e)if(!this.permissions.has(t))return!1;return!0}}const hl=d(void 0);function pl(){const e=u(hl);if(!e)throw new Error("UserPermissionContext cannot be used outside UserPermissionProvider");return e}function fl({children:t}){const n=Pt(),{data:r,error:s,isLoading:i}=B((()=>n.user?n.client.iam.roles.list():Promise.resolve(void 0)),[n.user]),a=l((()=>n.authToken&&r&&!i?new ml(n,r):void 0),[n,r,i]);return s?e(oe,{title:"Failed to fetch role mappings",children:s.message}):a&&e(hl.Provider,{value:a,children:t})}function gl({permission:t,isDisabled:n,title:r,children:s,...i}){return pl().hasPermission(t)||(n=!0,r="You do not have permission to perform this action"),e(b,{isDisabled:n,title:r,...i,children:s})}function vl({permission:t,...n}){return pl().hasPermission(t)?e(fn,{...n}):null}function yl({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{bn as ActivitiesDoc,wn as ActivityDoc,ia as AddToCollectionAction,sa as AddToCollectionActionComponent,dl as AllOf,Pn as AnimatedThinkingDots,cl as AnyOf,Wr as ApiKeyAvatar,oi as BrowseCollectionView,Ui as ChangeTypeAction,Di as ChangeTypeActionComponent,us as CollectionsFacetsNav,hi as CollectionsTable,Kn as ContentDispositionButton,ki as ContentObjectTypesSearch,fi as ContentObjectTypesTable,tr as ContentOverview,ui as CreateCollectionForm,mi as CreateCollectionModal,wi as CreateOrUpdateTypeModal,Ri as DeleteObjectsAction,Fi as DeleteObjectsActionComponent,Mi as DeleteObjectsFromCollectionsAction,ks as DocumentGridView,kr as DocumentIcon,Nr as DocumentIconSkeleton,Gs as DocumentInput,Hs as DocumentPreviewPanel,Cs as DocumentSearch,Fs as DocumentSearchProvider,ti as DocumentSearchResults,ei as DocumentSearchResultsWithDropZone,ms as DocumentSelection,gs as DocumentSelectionProvider,Ds as DocumentTable,ws as DocumentTableColumn,Ns as DocumentTableView,Es as DocumentUploadModal,ns as DocumentsFacetsNav,Ei as EditCollectionView,Jr as EnvironmentFacet,qi as ExportPropertiesAction,Vi as ExportPropertiesComponent,ii as ExportPropertiesModal,si as ExportTypes,Is as FileUploadAction,Ia as GenericPageNavHeader,is as InteractionsFacetsNav,Tn as JumpingDots,rl as MagicPdfView,va as ModernAgentConversation,Aa as NotFoundView,ji as ObjectSchemaEditor,gi as ObjectTypeSearch,vi as ObjectTypeSearchContext,_i as ObjectTypeSearchProvider,Qi as ObjectsActionContext,Zi as ObjectsActionContextProvider,Ca as PanelErrorBoundary,Vn as PayloadBuilder,Wn as PayloadBuilderProvider,qn as PayloadContext,os as PromptsFacetsNav,Xn as PropertiesEditorModal,In as PulsatingCircle,$n as PulsingMessageLoader,Bi as RemoveFromCollectionAction,Wi as RemoveFromCollectionActionComponent,Sa as RowErrorBoundary,Yr as RunsFacetsNav,Qn as SaveVersionConfirmModal,js as SearchContext,gl as SecureButton,vl as SecureSidebarItem,Oi as SelectCollection,di as SelectContentType,Ti as SelectContentTypeModal,Ms as SelectDocument,Ws as SelectDocumentModal,oa as SelectionActions,Ji as StartWorkflowAction,Gi as StartWorkflowComponent,Sr as StringFacet,_r as StringListFacet,Ii as TableLayoutEditor,En as ThinkingBar,On as ThinkingMessages,Pr as TypeFacet,An as TypedDots,da as UploadObjectsButton,yl as UserAvatar,Rr as UserInfo,fl as UserPermissionProvider,ml as UserPermissions,hl as UserPermissionsContext,Ir as VStringFacet,Ar as VTypeFacet,Gr as VUserFacet,wa as VertesiaErrorBoundary,zn as WavyThinking,Ta as WidgetErrorBoundary,Zr as WorkflowExecutionsFacetsNav,pi as collectionIcon,ul as isAnyOf,pr as isCsv,fr as isImage,gr as isPdf,vr as isVideo,wr as retrieveRendition,ka as setErrorBoundaryComponent,or as shortId,cr as shortenString,Ai as stringifyTableLayout,cs as useCollectionsFilterGroups,ds as useCollectionsFilterHandler,es as useDocumentFilterGroups,ts as useDocumentFilterHandler,Ss as useDocumentSearch,Ps as useDocumentSearchCount,ps as useDocumentSelection,zs as useDocumentUploadHandler,Js as useDownloadDocument,Or as useFetchGroupInfo,zr as useFetchUserInfo,rs as useInteractionsFilterGroups,ss as useInteractionsFilterHandler,na as useObjectsActionCallback,ta as useObjectsActionContext,fs as useOptionalDocumentSelection,Bn as usePayloadBuilder,as as usePromptsFilterGroups,ls as usePromptsFilterHandler,Hr as useRunsFilterGroups,Kr as useRunsFilterHandler,yi as useSearch,xi as useSearchCount,$s as useSmartFileUploadProcessing,ra as useStartWorkflowCallback,pl as useUserPermissions,_s as useWatchDocumentSearchFacets,Ts as useWatchDocumentSearchResult,bi as useWatchSearchResult,Qr as useWorkflowExecutionsFilterGroups,Xr as useWorkflowExecutionsFilterHandler};
2
2
  //# sourceMappingURL=vertesia-ui-features.js.map