@vertesia/ui 0.80.0-dev-20251118 → 0.80.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +105 -0
- package/lib/esm/core/components/MenuList.js +2 -5
- package/lib/esm/core/components/MenuList.js.map +1 -1
- package/lib/esm/core/components/MessageBox.js +1 -1
- package/lib/esm/core/components/MessageBox.js.map +1 -1
- package/lib/esm/core/components/TagsInput.js +194 -0
- package/lib/esm/core/components/TagsInput.js.map +1 -0
- package/lib/esm/core/components/index.js +2 -1
- package/lib/esm/core/components/index.js.map +1 -1
- package/lib/esm/core/components/shadcn/dialog.js +16 -2
- package/lib/esm/core/components/shadcn/dialog.js.map +1 -1
- package/lib/esm/core/components/shadcn/filters/filter/SelectFilter.js +6 -9
- package/lib/esm/core/components/shadcn/filters/filter/SelectFilter.js.map +1 -1
- package/lib/esm/core/components/shadcn/filters/filterBar.js +1 -1
- package/lib/esm/core/components/shadcn/filters/filterBar.js.map +1 -1
- package/lib/esm/core/components/shadcn/popover.js +1 -1
- package/lib/esm/core/components/shadcn/popover.js.map +1 -1
- package/lib/esm/core/components/shadcn/selectBox.js +23 -5
- package/lib/esm/core/components/shadcn/selectBox.js.map +1 -1
- package/lib/esm/core/components/shadcn/tabs.js +3 -3
- package/lib/esm/core/components/shadcn/tabs.js.map +1 -1
- package/lib/esm/env/index.js +4 -1
- package/lib/esm/env/index.js.map +1 -1
- package/lib/esm/features/agent/chat/AgentChart.js +184 -0
- package/lib/esm/features/agent/chat/AgentChart.js.map +1 -0
- package/lib/esm/features/agent/chat/ModernAgentConversation.js +87 -10
- package/lib/esm/features/agent/chat/ModernAgentConversation.js.map +1 -1
- package/lib/esm/features/agent/chat/ModernAgentOutput/AllMessagesMixed.js +6 -2
- package/lib/esm/features/agent/chat/ModernAgentOutput/AllMessagesMixed.js.map +1 -1
- package/lib/esm/features/agent/chat/ModernAgentOutput/Header.js +4 -4
- package/lib/esm/features/agent/chat/ModernAgentOutput/Header.js.map +1 -1
- package/lib/esm/features/agent/chat/ModernAgentOutput/InlineSlidingPlanPanel.js +4 -1
- package/lib/esm/features/agent/chat/ModernAgentOutput/InlineSlidingPlanPanel.js.map +1 -1
- package/lib/esm/features/agent/chat/ModernAgentOutput/MessageInput.js +12 -4
- package/lib/esm/features/agent/chat/ModernAgentOutput/MessageInput.js.map +1 -1
- package/lib/esm/features/agent/chat/ModernAgentOutput/MessageItem.js +60 -56
- package/lib/esm/features/agent/chat/ModernAgentOutput/MessageItem.js.map +1 -1
- package/lib/esm/features/agent/chat/index.js +1 -0
- package/lib/esm/features/agent/chat/index.js.map +1 -1
- package/lib/esm/features/agent/createChartTool.js +354 -0
- package/lib/esm/features/agent/createChartTool.js.map +1 -0
- package/lib/esm/features/agent/examples.js +295 -0
- package/lib/esm/features/agent/examples.js.map +1 -0
- package/lib/esm/features/agent/index.js +2 -0
- package/lib/esm/features/agent/index.js.map +1 -1
- package/lib/esm/features/agent/visualization.js +165 -0
- package/lib/esm/features/agent/visualization.js.map +1 -0
- package/lib/esm/features/facets/CollectionsFacetsNav.js +5 -1
- package/lib/esm/features/facets/CollectionsFacetsNav.js.map +1 -1
- package/lib/esm/features/index.js +1 -0
- package/lib/esm/features/index.js.map +1 -1
- package/lib/esm/features/layout/GenericPageNavHeader.js +14 -4
- package/lib/esm/features/layout/GenericPageNavHeader.js.map +1 -1
- package/lib/esm/features/magic-pdf/AnnotatedImageSlider.js +268 -0
- package/lib/esm/features/magic-pdf/AnnotatedImageSlider.js.map +1 -0
- package/lib/esm/features/magic-pdf/DownloadPopover.js +11 -11
- package/lib/esm/features/magic-pdf/DownloadPopover.js.map +1 -1
- package/lib/esm/features/magic-pdf/ExtractedContentView.js +77 -0
- package/lib/esm/features/magic-pdf/ExtractedContentView.js.map +1 -0
- package/lib/esm/features/magic-pdf/MagicPdfProvider.js +242 -0
- package/lib/esm/features/magic-pdf/MagicPdfProvider.js.map +1 -0
- package/lib/esm/features/magic-pdf/MagicPdfView.js +41 -47
- package/lib/esm/features/magic-pdf/MagicPdfView.js.map +1 -1
- package/lib/esm/features/pdf-viewer/PdfPageRenderer.js +261 -0
- package/lib/esm/features/pdf-viewer/PdfPageRenderer.js.map +1 -0
- package/lib/esm/features/pdf-viewer/PdfPageSlider.js +276 -0
- package/lib/esm/features/pdf-viewer/PdfPageSlider.js.map +1 -0
- package/lib/esm/features/pdf-viewer/SimplePdfViewer.js +71 -0
- package/lib/esm/features/pdf-viewer/SimplePdfViewer.js.map +1 -0
- package/lib/esm/features/pdf-viewer/index.js +4 -0
- package/lib/esm/features/pdf-viewer/index.js.map +1 -0
- package/lib/esm/features/store/collections/EditCollectionView.js +19 -10
- package/lib/esm/features/store/collections/EditCollectionView.js.map +1 -1
- package/lib/esm/features/store/collections/SelectCollection.js +104 -39
- package/lib/esm/features/store/collections/SelectCollection.js.map +1 -1
- package/lib/esm/features/store/collections/SharedPropsEditor.js +39 -0
- package/lib/esm/features/store/collections/SharedPropsEditor.js.map +1 -0
- package/lib/esm/features/store/collections/SyncMemberHeadsToggle.js +35 -0
- package/lib/esm/features/store/collections/SyncMemberHeadsToggle.js.map +1 -0
- package/lib/esm/features/store/collections/index.js +2 -0
- package/lib/esm/features/store/collections/index.js.map +1 -1
- package/lib/esm/features/store/objects/DocumentSearchResults.js +0 -7
- package/lib/esm/features/store/objects/DocumentSearchResults.js.map +1 -1
- package/lib/esm/features/store/objects/components/ContentOverview.js +273 -83
- package/lib/esm/features/store/objects/components/ContentOverview.js.map +1 -1
- package/lib/esm/features/store/objects/components/useContentPanelHooks.js +153 -0
- package/lib/esm/features/store/objects/components/useContentPanelHooks.js.map +1 -0
- package/lib/esm/features/store/objects/layout/DocumentTableColumn.js +3 -3
- package/lib/esm/features/store/objects/layout/DocumentTableColumn.js.map +1 -1
- package/lib/esm/features/store/objects/layout/renderers.js +13 -0
- package/lib/esm/features/store/objects/layout/renderers.js.map +1 -1
- package/lib/esm/features/store/objects/upload/useSmartFileUploadProcessing.js +10 -9
- package/lib/esm/features/store/objects/upload/useSmartFileUploadProcessing.js.map +1 -1
- package/lib/esm/features/utils/index.js +2 -0
- package/lib/esm/features/utils/index.js.map +1 -1
- package/lib/esm/features/utils/mimeType.js +8 -0
- package/lib/esm/features/utils/mimeType.js.map +1 -1
- package/lib/esm/features/utils/print.js +181 -0
- package/lib/esm/features/utils/print.js.map +1 -0
- package/lib/esm/features/utils/workflowStatus.js +43 -0
- package/lib/esm/features/utils/workflowStatus.js.map +1 -0
- package/lib/esm/router/HistoryNavigator.js +22 -2
- package/lib/esm/router/HistoryNavigator.js.map +1 -1
- package/lib/esm/session/UserSessionProvider.js +2 -2
- package/lib/esm/session/UserSessionProvider.js.map +1 -1
- package/lib/esm/shell/apps/AppProjectSelector.js +2 -2
- package/lib/esm/shell/apps/AppProjectSelector.js.map +1 -1
- package/lib/esm/shell/login/UserInfo.js +2 -1
- package/lib/esm/shell/login/UserInfo.js.map +1 -1
- package/lib/esm/shell/login/UserSessionMenu.js +7 -1
- package/lib/esm/shell/login/UserSessionMenu.js.map +1 -1
- package/lib/esm/widgets/form/Form.js +6 -2
- package/lib/esm/widgets/form/Form.js.map +1 -1
- package/lib/esm/widgets/markdown/MarkdownRenderer.js +226 -4
- package/lib/esm/widgets/markdown/MarkdownRenderer.js.map +1 -1
- package/lib/esm/widgets/schema-editor/ManagedSchema.js +0 -3
- package/lib/esm/widgets/schema-editor/ManagedSchema.js.map +1 -1
- package/lib/esm/widgets/schema-editor/json-schema4-utils.js +1 -1
- package/lib/esm/widgets/schema-editor/json-schema4-utils.js.map +1 -1
- package/lib/esm/widgets/xml-viewer/components/XMLViewer.js +18 -9
- package/lib/esm/widgets/xml-viewer/components/XMLViewer.js.map +1 -1
- package/lib/esm/widgets/xml-viewer/constants/index.js +10 -0
- package/lib/esm/widgets/xml-viewer/constants/index.js.map +1 -1
- package/lib/tsconfig.tsbuildinfo +1 -1
- package/lib/types/core/components/MessageBox.d.ts.map +1 -1
- package/lib/types/core/components/TagsInput.d.ts +16 -0
- package/lib/types/core/components/TagsInput.d.ts.map +1 -0
- package/lib/types/core/components/index.d.ts +2 -1
- package/lib/types/core/components/index.d.ts.map +1 -1
- package/lib/types/core/components/shadcn/dialog.d.ts +2 -1
- package/lib/types/core/components/shadcn/dialog.d.ts.map +1 -1
- package/lib/types/core/components/shadcn/filters/filterBar.d.ts.map +1 -1
- package/lib/types/core/components/shadcn/popover.d.ts +7 -0
- package/lib/types/core/components/shadcn/popover.d.ts.map +1 -1
- package/lib/types/core/components/shadcn/selectBox.d.ts +5 -1
- package/lib/types/core/components/shadcn/selectBox.d.ts.map +1 -1
- package/lib/types/core/components/shadcn/tabs.d.ts +3 -1
- package/lib/types/core/components/shadcn/tabs.d.ts.map +1 -1
- package/lib/types/env/index.d.ts +2 -0
- package/lib/types/env/index.d.ts.map +1 -1
- package/lib/types/features/agent/chat/AgentChart.d.ts +48 -0
- package/lib/types/features/agent/chat/AgentChart.d.ts.map +1 -0
- package/lib/types/features/agent/chat/ModernAgentConversation.d.ts.map +1 -1
- package/lib/types/features/agent/chat/ModernAgentOutput/AllMessagesMixed.d.ts +3 -2
- package/lib/types/features/agent/chat/ModernAgentOutput/AllMessagesMixed.d.ts.map +1 -1
- package/lib/types/features/agent/chat/ModernAgentOutput/Header.d.ts +2 -1
- package/lib/types/features/agent/chat/ModernAgentOutput/Header.d.ts.map +1 -1
- package/lib/types/features/agent/chat/ModernAgentOutput/InlineSlidingPlanPanel.d.ts +4 -2
- package/lib/types/features/agent/chat/ModernAgentOutput/InlineSlidingPlanPanel.d.ts.map +1 -1
- package/lib/types/features/agent/chat/ModernAgentOutput/MessageInput.d.ts +2 -4
- package/lib/types/features/agent/chat/ModernAgentOutput/MessageInput.d.ts.map +1 -1
- package/lib/types/features/agent/chat/ModernAgentOutput/MessageItem.d.ts.map +1 -1
- package/lib/types/features/agent/chat/index.d.ts +1 -0
- package/lib/types/features/agent/chat/index.d.ts.map +1 -1
- package/lib/types/features/agent/createChartTool.d.ts +178 -0
- package/lib/types/features/agent/createChartTool.d.ts.map +1 -0
- package/lib/types/features/agent/examples.d.ts +59 -0
- package/lib/types/features/agent/examples.d.ts.map +1 -0
- package/lib/types/features/agent/index.d.ts +2 -0
- package/lib/types/features/agent/index.d.ts.map +1 -1
- package/lib/types/features/agent/visualization.d.ts +95 -0
- package/lib/types/features/agent/visualization.d.ts.map +1 -0
- package/lib/types/features/facets/CollectionsFacetsNav.d.ts.map +1 -1
- package/lib/types/features/index.d.ts +1 -0
- package/lib/types/features/index.d.ts.map +1 -1
- package/lib/types/features/layout/GenericPageNavHeader.d.ts.map +1 -1
- package/lib/types/features/magic-pdf/AnnotatedImageSlider.d.ts +13 -0
- package/lib/types/features/magic-pdf/AnnotatedImageSlider.d.ts.map +1 -0
- package/lib/types/features/magic-pdf/DownloadPopover.d.ts.map +1 -1
- package/lib/types/features/magic-pdf/ExtractedContentView.d.ts +8 -0
- package/lib/types/features/magic-pdf/ExtractedContentView.d.ts.map +1 -0
- package/lib/types/features/magic-pdf/MagicPdfProvider.d.ts +58 -0
- package/lib/types/features/magic-pdf/MagicPdfProvider.d.ts.map +1 -0
- package/lib/types/features/magic-pdf/MagicPdfView.d.ts +1 -1
- package/lib/types/features/magic-pdf/MagicPdfView.d.ts.map +1 -1
- package/lib/types/features/pdf-viewer/PdfPageRenderer.d.ts +83 -0
- package/lib/types/features/pdf-viewer/PdfPageRenderer.d.ts.map +1 -0
- package/lib/types/features/pdf-viewer/PdfPageSlider.d.ts +29 -0
- package/lib/types/features/pdf-viewer/PdfPageSlider.d.ts.map +1 -0
- package/lib/types/features/pdf-viewer/SimplePdfViewer.d.ts +19 -0
- package/lib/types/features/pdf-viewer/SimplePdfViewer.d.ts.map +1 -0
- package/lib/types/features/pdf-viewer/index.d.ts +4 -0
- package/lib/types/features/pdf-viewer/index.d.ts.map +1 -0
- package/lib/types/features/store/collections/EditCollectionView.d.ts.map +1 -1
- package/lib/types/features/store/collections/SelectCollection.d.ts +2 -1
- package/lib/types/features/store/collections/SelectCollection.d.ts.map +1 -1
- package/lib/types/features/store/collections/SharedPropsEditor.d.ts +7 -0
- package/lib/types/features/store/collections/SharedPropsEditor.d.ts.map +1 -0
- package/lib/types/features/store/collections/SyncMemberHeadsToggle.d.ts +7 -0
- package/lib/types/features/store/collections/SyncMemberHeadsToggle.d.ts.map +1 -0
- package/lib/types/features/store/collections/index.d.ts +2 -0
- package/lib/types/features/store/collections/index.d.ts.map +1 -1
- package/lib/types/features/store/objects/DocumentSearchResults.d.ts.map +1 -1
- package/lib/types/features/store/objects/components/ContentOverview.d.ts.map +1 -1
- package/lib/types/features/store/objects/components/useContentPanelHooks.d.ts +30 -0
- package/lib/types/features/store/objects/components/useContentPanelHooks.d.ts.map +1 -0
- package/lib/types/features/store/objects/layout/renderers.d.ts.map +1 -1
- package/lib/types/features/store/objects/upload/useSmartFileUploadProcessing.d.ts.map +1 -1
- package/lib/types/features/utils/index.d.ts +2 -0
- package/lib/types/features/utils/index.d.ts.map +1 -1
- package/lib/types/features/utils/mimeType.d.ts +1 -0
- package/lib/types/features/utils/mimeType.d.ts.map +1 -1
- package/lib/types/features/utils/print.d.ts +10 -0
- package/lib/types/features/utils/print.d.ts.map +1 -0
- package/lib/types/features/utils/workflowStatus.d.ts +10 -0
- package/lib/types/features/utils/workflowStatus.d.ts.map +1 -0
- package/lib/types/router/HistoryNavigator.d.ts +3 -0
- package/lib/types/router/HistoryNavigator.d.ts.map +1 -1
- package/lib/types/shell/login/UserInfo.d.ts.map +1 -1
- package/lib/types/shell/login/UserSessionMenu.d.ts.map +1 -1
- package/lib/types/widgets/form/Form.d.ts.map +1 -1
- package/lib/types/widgets/markdown/MarkdownRenderer.d.ts +5 -1
- package/lib/types/widgets/markdown/MarkdownRenderer.d.ts.map +1 -1
- package/lib/types/widgets/schema-editor/ManagedSchema.d.ts.map +1 -1
- package/lib/types/widgets/xml-viewer/components/XMLViewer.d.ts.map +1 -1
- package/lib/types/widgets/xml-viewer/constants/index.d.ts +10 -0
- package/lib/types/widgets/xml-viewer/constants/index.d.ts.map +1 -1
- package/lib/vertesia-ui-core.js +1 -1
- package/lib/vertesia-ui-core.js.map +1 -1
- package/lib/vertesia-ui-env.js +1 -1
- package/lib/vertesia-ui-env.js.map +1 -1
- package/lib/vertesia-ui-features.js +1 -1
- package/lib/vertesia-ui-features.js.map +1 -1
- package/lib/vertesia-ui-layout.js +1 -1
- package/lib/vertesia-ui-layout.js.map +1 -1
- package/lib/vertesia-ui-router.js +1 -1
- package/lib/vertesia-ui-router.js.map +1 -1
- package/lib/vertesia-ui-session.js +1 -1
- package/lib/vertesia-ui-session.js.map +1 -1
- package/lib/vertesia-ui-shell.js +1 -1
- package/lib/vertesia-ui-shell.js.map +1 -1
- package/lib/vertesia-ui-widgets.js +1 -1
- package/lib/vertesia-ui-widgets.js.map +1 -1
- package/package.json +173 -170
- package/src/core/components/MenuList.tsx +3 -6
- package/src/core/components/MessageBox.tsx +7 -2
- package/src/core/components/SelectBox.tsx +1 -1
- package/src/core/components/shadcn/dialog.tsx +19 -1
- package/src/core/components/shadcn/filters/filter/SelectFilter.tsx +31 -31
- package/src/core/components/shadcn/filters/filterBar.tsx +1 -0
- package/src/core/components/shadcn/selectBox.tsx +32 -6
- package/src/core/components/shadcn/tabs.tsx +3 -2
- package/src/env/index.ts +6 -1
- package/src/features/agent/CHART_INSTRUCTIONS.md +228 -0
- package/src/features/agent/chat/AgentChart.tsx +601 -0
- package/src/features/agent/chat/ModernAgentConversation.tsx +123 -11
- package/src/features/agent/chat/ModernAgentOutput/AllMessagesMixed.tsx +8 -2
- package/src/features/agent/chat/ModernAgentOutput/Header.tsx +12 -2
- package/src/features/agent/chat/ModernAgentOutput/InlineSlidingPlanPanel.tsx +6 -1
- package/src/features/agent/chat/ModernAgentOutput/MessageInput.tsx +15 -10
- package/src/features/agent/chat/ModernAgentOutput/MessageItem.tsx +122 -87
- package/src/features/agent/chat/index.ts +1 -0
- package/src/features/agent/createChartTool.ts +364 -0
- package/src/features/agent/examples.ts +321 -0
- package/src/features/agent/index.ts +2 -0
- package/src/features/agent/visualization.ts +227 -0
- package/src/features/facets/CollectionsFacetsNav.tsx +5 -1
- package/src/features/index.ts +1 -0
- package/src/features/layout/GenericPageNavHeader.tsx +15 -4
- package/src/features/magic-pdf/AnnotatedImageSlider.tsx +482 -0
- package/src/features/magic-pdf/DownloadPopover.tsx +45 -40
- package/src/features/magic-pdf/ExtractedContentView.tsx +132 -0
- package/src/features/magic-pdf/MagicPdfProvider.tsx +297 -0
- package/src/features/magic-pdf/MagicPdfView.tsx +184 -91
- package/src/features/pdf-viewer/PdfPageRenderer.tsx +612 -0
- package/src/features/pdf-viewer/PdfPageSlider.tsx +473 -0
- package/src/features/pdf-viewer/SimplePdfViewer.tsx +142 -0
- package/src/features/pdf-viewer/index.ts +3 -0
- package/src/features/store/collections/EditCollectionView.tsx +3 -5
- package/src/features/store/collections/SharedPropsEditor.tsx +1 -2
- package/src/features/store/objects/DocumentSearchResults.tsx +0 -7
- package/src/features/store/objects/components/ContentOverview.tsx +677 -210
- package/src/features/store/objects/components/useContentPanelHooks.ts +169 -0
- package/src/features/store/objects/layout/DocumentTableColumn.tsx +3 -3
- package/src/features/store/objects/layout/knowledge.md +1 -0
- package/src/features/store/objects/layout/renderers.tsx +25 -0
- package/src/features/store/objects/upload/useSmartFileUploadProcessing.ts +1 -3
- package/src/features/utils/index.ts +3 -1
- package/src/features/utils/mimeType.ts +10 -1
- package/src/features/utils/print.ts +189 -0
- package/src/features/utils/workflowStatus.ts +44 -0
- package/src/router/HistoryNavigator.ts +30 -2
- package/src/session/UserSessionProvider.tsx +2 -2
- package/src/shell/login/UserInfo.tsx +2 -0
- package/src/shell/login/UserSessionMenu.tsx +12 -1
- package/src/widgets/form/Form.tsx +8 -3
- package/src/widgets/markdown/MarkdownRenderer.tsx +350 -6
- package/src/widgets/schema-editor/ManagedSchema.ts +0 -3
- package/src/widgets/schema-editor/json-schema4-utils.ts +1 -1
- package/src/widgets/xml-viewer/components/XMLViewer.tsx +22 -10
- package/src/widgets/xml-viewer/constants/index.ts +11 -0
- package/lib/esm/features/magic-pdf/PageSlider.js +0 -70
- package/lib/esm/features/magic-pdf/PageSlider.js.map +0 -1
- package/lib/esm/features/magic-pdf/PdfPageProvider.js +0 -188
- package/lib/esm/features/magic-pdf/PdfPageProvider.js.map +0 -1
- package/lib/esm/features/magic-pdf/TextPageView.js +0 -62
- package/lib/esm/features/magic-pdf/TextPageView.js.map +0 -1
- package/lib/esm/features/magic-pdf/useResizeOnDrag.js +0 -34
- package/lib/esm/features/magic-pdf/useResizeOnDrag.js.map +0 -1
- package/lib/types/features/magic-pdf/PageSlider.d.ts +0 -9
- package/lib/types/features/magic-pdf/PageSlider.d.ts.map +0 -1
- package/lib/types/features/magic-pdf/PdfPageProvider.d.ts +0 -39
- package/lib/types/features/magic-pdf/PdfPageProvider.d.ts.map +0 -1
- package/lib/types/features/magic-pdf/TextPageView.d.ts +0 -8
- package/lib/types/features/magic-pdf/TextPageView.d.ts.map +0 -1
- package/lib/types/features/magic-pdf/useResizeOnDrag.d.ts +0 -9
- package/lib/types/features/magic-pdf/useResizeOnDrag.d.ts.map +0 -1
- package/src/features/magic-pdf/PageSlider.tsx +0 -142
- package/src/features/magic-pdf/PdfPageProvider.tsx +0 -310
- package/src/features/magic-pdf/TextPageView.tsx +0 -91
- package/src/features/magic-pdf/useResizeOnDrag.ts +0 -42
|
@@ -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 b,Button as y,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 be,ConfirmModal as ye,useDebounce as xe,Panel as we,SelectList as Ne,Portal as ke,DialogDescription as Ce,Heading as _e,VTabs as je,VTabsBar as Se,VTabsPanel as Te,Breadcrumbs as Pe,Center as Ie}from"@vertesia/ui/core";import{CopyIcon as Ae,Bot as Ee,MessageSquare as $e,Info as ze,AlertCircle as Oe,User as De,CheckCircle as Ue,Clock as Le,ClipboardList as Fe,XIcon as Re,MoreVertical as Me,ExternalLink as Ve,DownloadCloudIcon as qe,TableProperties as Be,LayoutGrid as We,AlertTriangle as Ge,Copy as He,SquarePen as Je,Download as Ke,Eye as Ye,Users as Qe,RefreshCw as Xe,UploadIcon as Ze,CheckCircleIcon as et,AlertCircleIcon as tt,FileIcon as nt,XCircleIcon as rt,FolderIcon as st,X as it,ChevronsUpDown as at,FileText as lt,Maximize2 as ot,ChevronRight as ct,Settings as dt,Trash2 as ut,Search as mt,FolderClosed as ht,EllipsisVertical as pt,PaperclipIcon as ft,SendIcon as gt,Activity as vt,Circle as bt,Cpu as yt,CloudDownload as xt,ChevronsUp as wt,ImageIcon as Nt,InfoIcon as kt,AtSignIcon as Ct,ChevronsDown as _t}from"lucide-react";import{useUserSession as jt}from"@vertesia/ui/session";import{AgentMessageType as St,AgentSearchScope as Tt,mergeInCodePromptSchemas as Pt,supportsToolUse as It,ContentNature as At,POSTER_RENDITION_NAME as Et,ImageRenditionFormat as $t,PrincipalType as zt,InteractionStatus as Ot,SearchTypes as Dt,SupportedEmbeddingTypes as Ut}from"@vertesia/common";import{NavLink as Lt,useNavigate as Ft}from"@vertesia/ui/router";import Rt from"dayjs";import Mt from"react-markdown";import Vt from"remark-gfm";import qt,{Ajv as Bt}from"ajv";import{MarkdownRenderer as Wt,JSONDisplay as Gt,DropZone as Ht,UploadSummary as Jt,useSchema as Kt,CodeMirrorEditor as Yt,SchemaEditor as Qt,ManagedObject as Xt,GeneratedForm as Zt,Popover as en,XMLViewer as tn,JSONCode as nn}from"@vertesia/ui/widgets";import rn from"@monaco-editor/react";import sn from"dayjs/plugin/localizedFormat";import an from"dayjs/plugin/relativeTime";import{Md5 as ln}from"ts-md5";import{json as on}from"@codemirror/lang-json";import{basicSetup as cn}from"codemirror";import{UserInfo as dn}from"@vertesia/ui/features";import{ErrorBoundary as un}from"react-error-boundary";import{capitalize as mn}from"lodash-es";import{SidebarItem as hn}from"@vertesia/ui/layout";function pn({children:t,secondary:n=!1}){return e("span",{className:n?"bg-secondary text-primary":"text-foreground bg-muted",children:t})}function fn(e){return e?"array"===e.name?fn(e.innerType):e:void 0}function gn({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(pn,{children:"optional"}),e(pn,{children:n.type.value})]})}function vn({activities:t}){return e("div",{className:"flex flex-col gap-y-4 divide-y divide-gray-200",children:t.map((t=>e(yn,{activity:t},t.name)))})}function bn({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(pn,{children:n})})]})}function yn({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(pn,{children:n.name})}),n.doc&&e("div",{className:"text-gray-700 pb-2",children:n.doc}),t("div",{className:"pb-4",children:[e(bn,{code:n.paramsType,children:"Parameters"}),e("div",{className:"divide-y divide-gray-100",children:n.params.map((t=>e(xn,{property:t},t.name)))})]}),t("div",{className:"pb-4",children:[e(bn,{children:"Returns"}),e("div",{children:n.returnType?n.returnType.value:"void"})]})]})}function xn({property:n,className:s}){const i=l((()=>{const t=fn(n.type.innerType)??n.type;return"object"===t.name&&t.members?e(Nn,{members:t.members}):"enum"===t.name&&t.enum?e(wn,{values:t.enum}):null}),[n.type.innerType]);return t("div",{className:r("py-2",s),children:[e(gn,{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 wn({values:t}){return e("div",{className:"flex flex-wrap items-center gap-2",children:t.map(((t,n)=>e(pn,{secondary:!0,children:t},n)))})}function Nn({members:n}){return e(Cn,{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(kn,{properties:n})})}function kn({properties:t}){return e("div",{className:"border-l-2 border-l-blue-200 flex flex-col divide-y divide-gray-100 border-t border-t-gray-200",children:t.map((t=>e(xn,{property:t,className:"px-4 py-2"},t.name)))})}function Cn({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 jn({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 Sn({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 Tn({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 Pn({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 In({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 An({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 En({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 $n=["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 zn=[St.COMPLETE,St.IDLE,St.REQUEST_INPUT,St.TERMINATED];function On(e){return e.workstream_id?(e.type===St.COMPLETE&&console.log("[getWorkstreamId] COMPLETE message with workstream_id:",e.workstream_id),e.workstream_id):(e.type===St.COMPLETE&&console.log("[getWorkstreamId] COMPLETE message without workstream_id, defaulting to 'main'"),"main")}function Dn({message:r,showPulsatingCircle:s=!1}){const[i,a]=o(!1),[l,d]=o(""),[u,m]=o(!1),{client:h}=jt(),p=v(),f=(()=>{const t={containerClass:"bg-white border-l-4 border-l-muted/30 shadow-sm",iconComponent:e(Ee,{className:"size-4 text-muted"}),sender:""};switch(r.type){case St.ANSWER:return{...t,containerClass:"bg-white border-l-4 border-l-muted/30 shadow-sm",iconComponent:e(Ee,{className:"size-4 text-muted"}),sender:"Agent"};case St.COMPLETE:return{...t,containerClass:"bg-white border-l-4 border-l-success shadow-sm",iconComponent:e(Ue,{className:"size-4 text-success"}),sender:"Completed"};case St.TERMINATED:return{...t,containerClass:"bg-white border-l-4 border-l-attention shadow-sm",iconComponent:e(Ue,{className:"size-4 text-attention"}),sender:"Terminated"};case St.QUESTION:return{...t,iconComponent:e(De,{className:"size-4 text-muted"}),sender:"User"};case St.THOUGHT:return{...t,iconComponent:s?e(Tn,{size:"sm",color:"blue"}):e(Ee,{className:"size-4 text-muted"}),sender:"Agent"};case St.ERROR:return{...t,iconComponent:e(Oe,{className:"size-4 text-muted"}),sender:"System"};case St.UPDATE:return{...t,containerClass:"bg-white border-l-4 border-success shadow-sm",iconComponent:e(ze,{className:"size-4 text-success"}),sender:"Update"};case St.PLAN:return{...t,iconComponent:e($e,{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()*$n.length);e=e.replace(/%thinking_message%/g,$n[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(Mt,{remarkPlugins:[Vt],components:{a:({node:t,ref:n,...r})=>{const s=r.href||"";return s.includes("/store/objects")?e(Lt,{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:`).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===St.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=On(r),k=(()=>{switch(r.type){case St.ANSWER:return"border-l-info bg-info";case St.COMPLETE:return"border-l-success bg-success";case St.IDLE:return"border-l-muted bg-muted";case St.REQUEST_INPUT:return"border-l-attention bg-attention";case St.QUESTION:return"border-l-muted bg-muted";case St.THOUGHT:return"border-l-accent dark:border-l-purple-500 bg-purple-50/50 dark:bg-purple-900/10";case St.ERROR:return"border-l-destructive bg-destructive";case St.UPDATE:return"border-l-success bg-success";case St.PLAN:return"border-l-attention bg-attention";case St.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 St.ANSWER:return"text-info";case St.COMPLETE:return"text-success";case St.IDLE:return"text-muted";case St.REQUEST_INPUT:return"text-attention";case St.QUESTION:return"text-muted";case St.THOUGHT:return"text-purple-600 dark:text-purple-400";case St.ERROR:return"text-destructive";case St.UPDATE:return"text-success";case St.PLAN:return"text-attention";default:return"text-muted"}})(),n=t=>("number"==typeof r.timestamp?r.timestamp:new Date(r.timestamp).getTime())%2==0?e(Tn,{size:"sm",color:t}):e(Sn,{color:t});switch(r.type){case St.ANSWER:return s?n("blue"):e(Ee,{className:`size-4 ${t}`});case St.COMPLETE:case St.TERMINATED:return e(Ue,{className:`size-4 ${t}`});case St.IDLE:return e(Le,{className:`size-4 ${t}`});case St.REQUEST_INPUT:case St.QUESTION:return e(De,{className:`size-4 ${t}`});case St.THOUGHT:return s?n("purple"):e(Ee,{className:`size-4 ${t}`});case St.ERROR:return e(Oe,{className:`size-4 ${t}`});case St.UPDATE:return s?n("green"):e(ze,{className:`size-4 ${t}`});case St.PLAN:return s?n("amber"):e($e,{className:`size-4 ${t}`});default:return s?n("blue"):e(Ee,{className:`size-4 ${t}`})}})()}),e("span",{className:"text-xs font-medium text-muted ",children:f.sender}),"main"!==N&&"all"!==N&&e(b,{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:Rt(r.timestamp).format("HH:mm:ss")}),e(y,{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(Ae,{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(Sn,{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 Un({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(Ue,{className:"size-3 text-success"}):e(Le,{className:"size-3 text-attention"}))]})]},n)))}:{className:"py-1"})}function Ln(e,t){return"all"===t?[...e]:"main"===t?e.filter((e=>"main"===On(e))):e.filter((e=>On(e)===t))}function Fn({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=Ln(p,"main");return e.set("main",t.length),p.forEach((t=>{const n=On(t);"main"!==n&&e.set(n,(e.get(n)||0)+1)})),e}),[p]),v=a.useMemo((()=>"all"===m?p:Ln(p,m)),[p,m]),b=l((()=>{const e=new Map,t=new Map;p.forEach((e=>{const n=On(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,[St.COMPLETE,St.IDLE,St.REQUEST_INPUT,St.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(Un,{workstreams:f,activeWorkstream:m,onSelectWorkstream:h,count:g,completionStatus:b})}),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&&!zn.includes(t.type);return e(Dn,{message:t,showPulsatingCircle:r},`${t.timestamp}-${n}`)})):e(n,{children:(()=>{const t=v.filter((e=>e.type===St.ANSWER||e.type===St.QUESTION||e.type===St.COMPLETE||e.type===St.TERMINATED)),n=d?null:v.filter((e=>e.type===St.THOUGHT||e.type===St.UPDATE||e.type===St.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&&!zn.includes(t.type);return e(Dn,{message:t,showPulsatingCircle:s},`${t.timestamp}-${n}`)}))})()}),e("div",{ref:s,className:"h-4"})]})]})}class Rn{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 Rn(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?Tt.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?Pt(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&&It(t,e.provider)?this._model=t:this._model=e?.default_model&&It(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 qt({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 Mn=d(void 0);function Vn({children:t}){const{client:n}=jt(),[r,s]=o();return c((()=>{s(new Rn(n,s))}),[]),r&&e(Mn.Provider,{value:r,children:t})}function qn(){const e=u(Mn);if(!e)throw new Error("usePayloadBuilder must be used within a PayloadProvider");return e}function Bn({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(Vn,{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(Ee,{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(y,{variant:"stacked"===a?"outline":"ghost",size:"xs",className:"rounded-l-md",onClick:()=>l("stacked"),children:"Details"}),e(y,{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(y,{size:"sm",variant:o?"primary":"secondary",onClick:d,className:"transition-all duration-200 rounded-md",title:"Toggle plan panel",children:[e(Fe,{className:"size-4 mr-1.5"}),e("span",{className:"font-medium text-xs",children:o?"Hide Plan":"Show Plan"})]})]}),e(Wn,{run:i,isModal:s,onClose:r,onDownload:u,onCopyRunId:m,resetWorkflow:h}),r&&!s&&e(y,{size:"xs",variant:"ghost",onClick:r,children:e(Re,{className:"size-4"})})]})]})})}function Wn({run:n,isModal:r,onClose:s,onDownload:i,onCopyRunId:a,resetWorkflow:l}){const o=v(),{client:c}=jt(),d=qn();return t(x,{hover:!0,children:[e(w,{children:e(y,{size:"xs",variant:"ghost",title:"More actions",children:e(Me,{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(Ve,{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(Ae,{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(qe,{className:"size-3.5 mr-2 text-muted"})," Download Conversation"]}),s&&r&&t(j,{className:"text-xs",onSelect:s,children:[e(Re,{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(Re,{className:"size-3.5 mr-2 text-destructive"})," Cancel Workflow"]})]})})})})})})]})}const Gn="vertesia.content_store.lastDisplayedView";function Hn({onUpdate:t}){const[n,r]=o("grid"===localStorage.getItem(Gn)),s=()=>{localStorage.setItem(Gn,"grid"),r(!0),t(!0)},i=()=>{localStorage.setItem(Gn,"table"),r(!1),t(!1)};return e(y,{variant:"outline",onClick:()=>{n?i():s()},alt:n?"Table View":"Thumbnail View",children:e(n?Be:We,{})})}Hn.LAST_DISPLAYED_VIEW=Gn;class Jn 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 Kn({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 Jn;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(y,{variant:"secondary",onClick:r,disabled:i,children:"Cancel"}),e(y,{variant:"primary",onClick:async()=>{await s(g,g?h:void 0)},isLoading:i,children:"Save"})]})]})}function Yn({isOpen:r,onClose:s,object:i,refetch:a}){const{client:l,store:d}=jt(),u=v(),h=Ft(),[p,f]=o(!1),[g,b]=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&&(b(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(rn,{height:"100%",language:"json",value:g,onChange:e=>b(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(y,{variant:"secondary",onClick:s,children:"Cancel"}),e(y,{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(Kn,{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 Qn=131072;var Xn;function Zn({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(er,{object:r,refetch:i??(()=>Promise.resolve()),handleCopyContent:l})}),e(U,{withHandle:!0}),e(D,{className:"min-w-[100px]",children:e(tr,{object:r,loadText:s??!1,handleCopyContent:l})})]})})}function er({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(y,{variant:""+(a?"ghost":"primary"),size:"sm",alt:"Preview properties",onClick:()=>l(!a),children:"Properties"}),e(y,{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(y,{variant:"ghost",size:"sm",title:"Copy properties",onClick:()=>i(JSON.stringify(r.properties,null,2),"properties"),children:e(He,{className:"size-4"})}),e(y,{variant:"ghost",size:"sm",onClick:()=>{d(!0)},title:"Edit properties",className:"flex items-center gap-2",children:e(Je,{className:"size-4"})})]})]}),r.properties?e("div",{className:"h-[calc(100vh-220px)] overflow-auto px-2",children:e(Gt,{value:r.properties,viewCode:a})}):e("div",{className:"h-[calc(100vh-220px)] overflow-auto px-2",children:e("div",{children:"No properties defined"})}),e(Yn,{isOpen:c,onClose:()=>{d(!1)},object:r,refetch:s})]})}function tr({object:r,loadText:s,handleCopyContent:i}){const{store:a}=jt(),l=r?.metadata?.type===At.Image,d=r?.metadata?.type===At.Video,[u,m]=o(d?Xn.Video:l?Xn.Image:Xn.Text),[h,p]=o(r.text),[f,g]=o(!1),[v,b]=o(!1);return c((()=>{s&&!h&&(g(!0),a.objects.getObjectText(r.id).then((e=>{if(e.text.length>Qn){const t=e.text.substring(0,Qn);p(t),b(!0)}else p(e.text),b(!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(y,{variant:u===Xn.Image?"primary":"ghost",size:"sm",alt:"View Image",onClick:()=>m(Xn.Image),children:"Image"}),d&&e(y,{variant:u===Xn.Video?"primary":"ghost",size:"sm",alt:"View Video",onClick:()=>m(Xn.Video),children:"Video"}),e(y,{variant:u===Xn.Text?"primary":"ghost",size:"sm",alt:"View Text",onClick:()=>m(Xn.Text),children:"Text"})]}),u===Xn.Text&&e(nr,{object:r,text:h,handleCopyContent:i})]}),u===Xn.Image?e(sr,{object:r}):u===Xn.Video?e(ir,{object:r}):f?e("div",{className:"flex justify-center items-center h-[calc(100vh-260px)]",children:e(L,{size:"lg"})}):e(rr,{object:r,text:h,isTextCropped:v})]})}function nr({object:r,text:s,handleCopyContent:i}){const{client:a}=jt(),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(y,{variant:"ghost",size:"sm",title:"Copy text",className:"flex items-center gap-2",onClick:()=>i(s,"text"),children:e(He,{className:"size-4"})}),m&&s&&t(n,{children:[t(y,{variant:"ghost",size:"sm",onClick:()=>h("docx"),disabled:null!==c,className:"flex items-center gap-2",children:["docx"===c?e(L,{size:"sm"}):e(Ke,{className:"size-4"}),"DOCX"]}),t(y,{variant:"ghost",size:"sm",onClick:()=>h("pdf"),disabled:null!==c,className:"flex items-center gap-2",children:["pdf"===c?e(L,{size:"sm"}):e(Ke,{className:"size-4"}),"PDF"]})]})]})})}!function(e){e.Text="text",e.Image="image",e.Video="video"}(Xn||(Xn={}));const rr=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("),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(Ge,{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(Wt,{components:{a:({node:t,...n})=>{const r=n.href||"";return r.includes("/store/objects/")?e(Lt,{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 sr({object:t}){const{client:n}=jt(),[r,s]=o(),i=t.content,a=t.metadata&&t.metadata.type===At.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:$t.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 ir({object:n}){const{client:r}=jt(),[s,i]=o(),[a,l]=o(),[d,u]=o(!0),m=n.content,h=n.metadata?.type===At.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),b=f.find((e=>e.name===Et));return c((()=>{(async()=>{if(b?.content?.source)try{const e=await r.files.getDownloadUrl(b.content.source);l(e.url)}catch(e){console.error("Failed to load poster image",e)}})()}),[b,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 ar(e,t=7){return e?"~"+e.slice(-t):""}function lr(e,t){return e.length>t?e.substring(0,t)+"...":e}const or="text/csv",cr="image/",dr="application/pdf",ur="video/",mr=e=>e===or||or.includes(e),hr=e=>e.startsWith(cr)||cr.includes(e),pr=e=>e===dr||dr.includes(e),fr=e=>e.startsWith(ur)||ur.includes(e),gr=import.meta.env,vr={max_hw:gr?.VITE_RENDITION_HW||256,format:$t.jpeg,generate_if_missing:!0},br="vertesia.content_store.renditionId";async function yr(e,t,n,r,s){if(!t?.content?.type||!(hr(t.content.type)||fr(t.content.type)||pr(t.content.type)))return void s("No preview available");s("Preparing preview...");const i=(new Date).getTime()/1e3,a=localStorage.getItem(`${br}_${t.id}_${vr.max_hw}`),l=localStorage.getItem(`${br}_${t.id}_${vr.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,vr).then((i=>{if("generating"===i.status)s("Preparing preview..."),n(""),r(""),setTimeout((()=>yr(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(`${br}_${t.id}_${vr.max_hw}`,e),localStorage.setItem(`${br}_${t.id}_${vr.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 xr({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 wr({selection:n,document:r,onSelectionChange:s,onRowClick:i,previewObject:a,selectedObject:l}){const{client:d}=jt(),[u,m]=o(void 0),[h,p]=o(void 0),[f,g]=o(void 0);return c((()=>{r?.content&&yr(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(y,{variant:"ghost",size:"sm",title:"Preivew Object",onClick:e=>{e.stopPropagation(),a?.(r.id)},children:e(Ye,{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 Nr(e){return`${e._id} (${e.count})`}function kr(e){return`${e.name} (${e.count})`}function Cr({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:Nr,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(B,{className:s,value:i,onChange:a,placeholder:r})}function jr(e){return`${e.name} (${e.count})`}function Sr({search:t,buckets:n,placeholder:r="Filter by Type",className:s}){const[i,a]=o([]),{typeRegistry:l}=jt(),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:jr,options:i,value:u,onChange:e=>{t.setFilterValue("type",e?._id)},by:"_id",placeholder:r})}function Tr({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:Nr(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 Pr({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 Ir={},Ar={};function Er(e){const{client:t}=jt();return W((()=>{let n=Ir[e];return n||(n=t.users.retrieve(e).then((e=>e)),Ir[e]=n),n}),[e])}function $r(e){const{client:t}=jt();return W((()=>{let n=Ar[e];return n||(n=t.iam.groups.retrieve(e).then((e=>e)),Ar[e]=n),n}),[e])}function zr(){return e("div",{className:"size-8"})}function Or({showTitle:n=!1,size:r="md"}){return e(qr,{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 Dr({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(qr,{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 Ur({title:t="Error",error:n,showTitle:r=!1,size:s="md"}){return e(Fr,{title:t,message:"string"==typeof n?n:n.message,color:"bg-red-500",showTitle:r,size:s})}function Lr({userRef:t,showTitle:n=!1,size:r="md"}){if(!t)return e(Fr,{title:"Unknown User",message:"User information is not available.",showTitle:n,size:r});const[s,i]=t?t.split(":"):["unknown"];switch(s){case zt.User:return e(Mr,{userId:i,showTitle:n,size:r});case zt.Group:return e(Rr,{userId:i,showTitle:n,size:r});case"system":return e(Or,{showTitle:n,size:r});case zt.ServiceAccount:case zt.Agent:return e(Dr,{accountId:i,showTitle:n,size:r});case zt.ApiKey:return e(Vr,{keyId:i,size:r,showTitle:n});default:return e(Ur,{title:"Unknown User",error:`Invalid user ref type: ${s}`,showTitle:n,size:r})}}function Fr({title:n,message:r,color:s,size:i="md",showTitle:a=!1}){return e(qr,{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 Rr({userId:n,showTitle:r=!1,size:s="md"}){const{data:i,error:a}=$r(n);if(a)return e(Ur,{title:"Failed to fetch group",error:a,showTitle:r,size:s});if(!i)return e(zr,{});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(qr,{title:i.name||"Unnamed Group",description:l,children:t("div",{className:"flex flex-row items-center gap-2",children:[e(Qe,{className:"size-6 text-indigo-500",size:s}),r&&e("div",{className:"text-sm font-semibold pl-2",children:i.name||"Unnamed Group"})]})})}function Mr({userId:n,showTitle:r=!1,size:s="md"}){const{data:i,error:a}=Er(n);if(a)return e(Ur,{title:"Failed to fetch user",error:a,showTitle:r,size:s});if(!i)return e(zr,{});const l=e("div",{className:"truncate",title:i.email,children:i.email});return e(qr,{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 Vr({keyId:n,showTitle:r=!1,size:s="md"}){const{client:i}=jt(),{data:a,error:l}=W((()=>i.apikeys.retrieve(n)),[]);if(l)return e(Ur,{title:"Failed to fetch the apikey",error:l,showTitle:r,size:s});if(!a)return e(zr,{});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(qr,{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 qr({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 Br({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(Lr,{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 Wr({search:t,buckets:n,placeholder:r="All Environments",className:s}){const{client:i}=jt(),[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:kr,options:a,value:u,onChange:e=>{t.setFilterValue("environment",e?._id)},by:"_id",placeholder:r})}function Gr(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 Ot.published:a="success";break;case Ot.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(b,{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=Tr({buckets:n.models||[],name:"model"});r.push(e)}if(n.statuses){const e=Tr({buckets:n.statuses||[],name:"status"});r.push(e)}if(n.finish_reason){const e=Tr({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=Br({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 Hr(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 Jr({facets:n,search:r}){const[s,i]=o([]),a=Gr(n),l=Hr(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(y,{onClick:()=>{r.search()},variant:"outline",title:"Refresh",children:e(Xe,{className:"size-5"})})]}),t("div",{className:"flex gap-2 items-center",children:[e(Y,{}),e(Q,{})]})]})}function Kr(e){const t=[];if(t.push({placeholder:"Workflow or Run ID",name:"name",type:"text",options:[]}),e.status){const n=Tr({buckets:e.status||[],name:"status",placeholder:"Status"});t.push(n)}if(e.initiated_by){const n=Br({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 Yr(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 Qr({facets:n,search:r}){const[s,i]=o([]),a=Kr(n),l=Yr(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 Xr(e){const{typeRegistry:t}=jt(),n=[];if(n.push({placeholder:"ID",name:"id",type:"text",options:[]}),n.push({placeholder:"Name",name:"name",type:"text",options:[]}),e.type){const r=Pr({buckets:e.type||[],typeRegistry:t,type:"select",multiple:!0});n.push(r)}if(e.status){const t=Tr({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 Zr(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 es({facets:n,search:r}){const[s,i]=o([]),a=Xr(n),l=Zr(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 ts(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 ns(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 rs({facets:n,search:r}){const[s,i]=o([]),a=ts(),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 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 is(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 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{typeRegistry:t}=jt(),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 os(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 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,{})]})})}class ds{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 ds(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 us=d(void 0);function ms(){const e=u(us);if(!e)throw new Error("useObjectSelection must be used within a ObjectSelectionProvider");return e}function hs(){return u(us)}function ps({value:t,collectionId:n,children:r}){const[s,i]=o();return c((()=>{const e=new ds(t,n,{},i);i(e)}),[t]),s&&e(us.Provider,{value:s,children:r})}Rt.extend(an),Rt.extend(sn);const fs={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(y,{variant:"ghost",alt:"Preview Object",onClick:e=>{e.stopPropagation(),r?.(n.id)},children:e(Ye,{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||ar(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:Rt(t)[r](s)},n)}},gs=fs.string();function vs(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 bs(e){return e&&"."!==e?e.split("."):[]}class ys{layout;renderer=gs;path;fallbackPath;previewObject;constructor(e,t){if(this.layout=e,this.path=bs(e.field||""),this.fallbackPath=e.fallback?bs(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=fs[e](r)}else this.renderer=fs[t]()}}get name(){return this.layout.name}resolveValue(e){let t=vs(e,this.path);return void 0===t&&this.fallbackPath&&(t=vs(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 fs.objectId(s,(e=>{this.previewObject(t.id)}))(t,n)}return this.renderer(this.resolveValue(t),n)}}function xs({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 ws({objects:r,selection:s,isLoading:i,onSelectionChange:a,onRowClick:l,previewObject:o,selectedObject:c}){return t(n,{children:[e(xr,{isLoading:i}),e("div",{className:"w-full gap-2 grid lg:grid-cols-6",children:r.map((t=>e(wr,{document:t,selection:s,onSelectionChange:a,onRowClick:l,previewObject:o,selectedObject:c},t.id)))})]})}class Ns{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 ks=d(void 0);function Cs(){return u(ks)}function _s(){return ee(Cs().facets)}function js(){const e=Cs();return{...ee(e.result),search:e}}function Ss(){const e=Cs();return ee(e.facets).total}var Ts;async function Ps(e){try{const t=await e.arrayBuffer(),n=new ln;n.appendByteArray(new Uint8Array(t));const r=n.end();return r?.toString()}catch(e){return void console.error("Error calculating file hash:",e)}}function Is(){const{client:e}=jt(),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 Ps(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:void 0};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=Ts.SKIP)}},a=async()=>{const n=t.filter((e=>e.action!==Ts.SKIP)),r=n.map((e=>e.location)),i=Array.from(new Set(r)),a=[];for(const t of i){const r=n.filter((e=>e.location===t)).map((e=>e.name)),i={location:t??"","content.name":{$in:r}};if(s){const t=e.store.collections.searchMembers(s,{query:{match:i},select:void 0}).then((e=>e.results));a.push(t)}else{const t=e.store.objects.find({query:{match:i},select:void 0});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=Ts.UPDATE)}console.log(`Reconciled ${t.filter((e=>e.action===Ts.UPDATE)).length}`)};return await i(),await a(),t.forEach((e=>{e.action||(e.action=Ts.CREATE)})),console.log("Document processing check results:",{totalFiles:n.length,toCreate:t.filter((e=>e.action===Ts.CREATE)).length,toUpdate:t.filter((e=>e.action===Ts.UPDATE)).length,toSkip:t.filter((e=>e.action===Ts.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 As({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:b}=jt(),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(st,{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}=Is(),Z=l((()=>b?.types||[]),[b?.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===Ts.CREATE)).length,r=t.filter((e=>e.action===Ts.UPDATE)).length,s=t.filter((e=>e.action===Ts.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===Ts.CREATE?"create":e.action===Ts.UPDATE?"update":"skip"})));I(t),E(!0),z(!1);const n=k.filter((e=>e.action===Ts.SKIP)),r=k.filter((e=>e.action===Ts.UPDATE)),s=k.filter((e=>e.action===Ts.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(ze,{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(et,{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(ze,{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(nt,{className:"size-5 text-muted"}),"uploading"===n.status&&e(L,{size:"sm"}),"success"===n.status&&e(et,{className:"size-5 text-success"}),"error"===n.status&&e(rt,{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(Jt,{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(Ze,{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(et,{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(tt,{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(Ht,{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(y,{variant:"ghost",onClick:ee,children:"Cancel"}),e(y,{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(y,{variant:"ghost",onClick:ee,children:"Cancel"})});if(!A&&!$){const n=_;return t(ie,{children:[e(y,{variant:"ghost",onClick:ee,children:"Cancel"}),e(y,{disabled:!n,onClick:ce,children:Y.toCreate+Y.toUpdate>0?"Upload":"Continue"})]})}return A?e(ie,{children:e(y,{variant:"ghost",disabled:!0,children:"Uploading..."})}):t(ie,{children:[e(y,{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(y,{onClick:()=>{h&&q&&h(q),ee()},children:"Close"})]})})()]},U)}function Es(e){const t="function"==typeof e?e:e.onUploadDone,{client:n,project:r,store:s}=jt(),i=Cs(),a=v(),{checkDocumentProcessing:l}=Is();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===Ts.CREATE)).length,v=f.filter((e=>e.action===Ts.UPDATE)).length,b=f.filter((e=>e.action===Ts.SKIP)).length;a({title:"Files analyzed",description:`${u.length} file(s): ${g} new, ${v} to update, ${b} to skip`,status:"info",duration:4e3});for(const e of f.filter((e=>e.action===Ts.SKIP&&e.existingId)))m.push({id:e.existingId,name:e.name,type:o,status:"skipped",location:e.location});const y=f.filter((e=>(e.action===Ts.CREATE||e.action===Ts.UPDATE)&&e.file));if(y.length>0){console.log(`Processing ${y.length} files (${y.filter((e=>e.action===Ts.CREATE)).length} create, ${y.filter((e=>e.action===Ts.UPDATE)).length} update)...`);const e=50,t=[];for(let n=0;n<y.length;n+=e)t.push(y.slice(n,n+e));for(let r=0;r<t.length;r++){const i=t[r],l=r*e;console.log(`Processing batch ${r+1}/${t.length} (${i.length} files)`),y.length>e&&a({title:"Processing files",description:`Processed ${l}/${y.length} files...`,status:"info",duration:2e3});const u=await Promise.all(i.map((async e=>{try{if(e.action===Ts.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"}(Ts||(Ts={}));const $s=[{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 zs({isGridView:t=!1,onUpload:n,collectionId:r,...s}){return n?e(Os,{...s,onUpload:n,isGridView:t,collectionId:r}):e(Ds,{...s,isGridView:t})}function Os({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),[b,y]=o(!1),x=Cs(),w=v(),{checkDocumentProcessing:N}=Is(),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}),y(!0)}},C=e=>{const t=[...u];m([]),g(null),y(!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(Ds,{...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(Ht,{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(As,{isOpen:b&&u.length>0,onClose:()=>{m([]),g(null),y(!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),y(!1),e&&e.success&&e.objectIds.length>0?C(null):C(void 0)}})]})}function Ds({objects:t,layout:n=$s,isLoading:r,onRowClick:s,onSelectionChange:i,previewObject:a,selectedObject:o,isGridView:c}){const d=hs(),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:$s).map((e=>new ys(e,a)))),[n,a]);return e(c?ws:xs,{objects:t,isLoading:r,columns:h,onRowClick:s,previewObject:a,selectedObject:o,selection:d,toggleAll:m,onSelectionChange:u})}function Us({children:t,limit:n,parent:r,typeId:s,facets:i,name:a,collectionId:o}){const{store:c}=jt(),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 Ns(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(ks.Provider,{value:d,children:t})}const Ls=[{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 Fs({onChange:t}){return e(Us,{children:e(Ms,{onRowClick:e=>{t(e||void 0)}})})}const Rs="vertesia.content_store.lastDisplayedView";function Ms({onRowClick:n}){const[r,s]=o(!1),[i,a]=o("grid"===localStorage.getItem(Rs)),{search:l,isLoading:d,error:u,objects:h}=js(),p=m(null);le(p,(()=>{r&&l.loadMore(!0)}),{deps:[r]}),c((()=>{l.search().then((()=>s(!0)))}),[]);const f=_s(),g=Cs();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(es,{facets:f,search:g}),t("div",{className:"flex items-center gap-2",children:[e(y,{variant:"outline",onClick:()=>{s(!1),l.search().then((()=>s(!0)))},alt:"Refresh",children:e(Xe,{size:16})}),e(Hn,{onUpdate:a})]})]}),e(zs,{objects:h||[],isLoading:!1,layout:Ls,onRowClick:n,isGridView:i}),e("div",{ref:p,className:"mt-10"}),d&&e("div",{className:"flex justify-center",children:e(L,{size:"xl"})})]})}function Vs({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(Fs,{onChange:r})})]})}const qs=/store:([a-f0-9]+)/;function Bs({object:n}){const{client:s}=jt(),{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(qs);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(y,{onClick:p,variant:"unstyled",className:"hover:text-red-500 hover:bg-gray-100 dark:hover:bg-gray-600",children:e(it,{className:"size-5"})})}),e("div",{className:"absolute inset-y-0 right-0 flex items-center justify-center",children:e(y,{onClick:a,variant:"unstyled",className:"hover:bg-gray-100 dark:hover:bg-gray-600",children:e(at,{className:"size-5"})})}),e(Vs,{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 Ws(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 Gs({objectId:n,isOpen:r,onClose:s}){const i=Ft(),{client:a,store:l}=jt(),[d,u]=o(null),[m,h]=o(!1),[p,f]=o(!1),[g,b]=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?b(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),b(void 0),w(void 0))}),[n,r,l.objects]);const _=async e=>{f(!0);try{const t=await l.objects.getObjectText(e);b(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:$t.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(lt,{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(y,{variant:"ghost",size:"sm",onClick:S,className:"flex items-center gap-1 text-indigo-600 hover:text-indigo-800",children:[e(ot,{className:"h-4 w-4"}),e("span",{children:"Full View"})]}),e(y,{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(it,{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(We,{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(ze,{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(Wt,{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(lt,{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(y,{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(lt,{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(Gt,{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(ze,{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?Hs(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(y,{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(Ke,{className:"h-4 w-4 mr-2"}),"Download"]})}),t(y,{onClick:S,className:"bg-indigo-600 hover:bg-indigo-700 text-white",children:["Open Full Document",e(ct,{className:"h-4 w-4 ml-2"})]})]})]}):null}function Hs(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 Js=Object.values(Dt),Ks=Object.values(Ut);function Ys({onChange:n,isLoading:r,refresh:s,searchTypes:i}){const{client:a,project:l}=jt(),d=v(),[u,m]=o(void 0),[h,p]=o(void 0),f=!(!l||!h?.embeddings.text&&!h?.embeddings.image),[g,b]=o(void 0),[x,w]=o(!1),[N,k]=o(i||Js),[C,_]=o(100);c((()=>{i&&k(i)}),[i]);const j={};let I=!1,A=!1;N.forEach((e=>{e===Dt.full_text?I=!0:A=!0,Ks.includes(e)&&(j[e]=!0)})),c((()=>{m(void 0),b(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}),b("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(y,{variant:"ghost",onClick:()=>w(!0),alt:"Semantic search settings",className:"ml-1",children:e(dt,{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(Dt.full_text),onCheckedChange:O(Dt.full_text)}),e("span",{children:"Full Text"})]}),e("div",{className:"font-semibold mt-2 mb-1",children:"Embeddings"}),Ks.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(y,{variant:"outline",onClick:()=>w(!1),children:"Close"})})]}),e(y,{variant:"secondary",isLoading:r,onClick:z,isDisabled:!f,alt:"Semantic search",children:"Search"})]})}const Qs=[{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 Xs({onUploadDone:t=async()=>{},layout:n}){const r=Cs(),s=v(),i=Es((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(Zs,{layout:n,onUpload:(e,t)=>{const n=r.collectionId;return i(e,t,n)}})}function Zs({layout:n,onUpload:r,allowFilter:s=!0,allowSearch:i=!0}){const a=Cs(),[l,d]=o(!1),[u,h]=o(null),{typeRegistry:p}=jt(),{search:f,isLoading:g,error:v,objects:b,hasMore:y}=js(),[x,w]=o(p?n||function(e,t){const n=t?e.getTypeLayout(t):Qs;console.log("[DEBUG] getTableLayout called with type:",t),console.log("[DEBUG] Layout from registry:",n),console.log("[DEBUG] Using defaultLayout?",n===Qs);const r=n??Qs;return console.log("[DEBUG] Final layout:",r),console.log("[DEBUG] Has Status field?",r.some((e=>"status"===e.field))),r}(p,f.query.type):Qs);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(Hn.LAST_DISPLAYED_VIEW)),[T,P]=o([]),I=m(null);c((()=>{l||0!==b.length||(_(0),f._updateRunningState(!0),f.search().then((()=>{d(!0)})).catch((e=>{console.error("Initial search failed:",e),f._updateRunningState(!1)})))}),[]),c((()=>{b.length<C&&_(b.length)}),[b.length,C]),le(I,(()=>{l&&b.length>0&&b.length!=C&&(d(!1),f.loadMore().finally((()=>{_(b.length),d(!0)})))}),{deps:[l,b.length]});const A=_s(),E=Cs(),$=Xr(A),z=Zr(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=Ft();return t("div",{className:"flex flex-col gap-y-2",children:[e(ti,{object:u,onClose:()=>h(null)}),v&&e(oe,{title:"Error",children:v.message}),e(ei,{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(zs,{objects:b,isLoading:!b.length&&g,layout:x,onRowClick:e=>{U(`/objects/${e.id}`)},previewObject:e=>{const t=b.find((t=>t.id===e))||null;h(t)},selectedObject:u,onUpload:r,isGridView:j,collectionId:a.collectionId}),e("div",y?{ref:I,className:"w-full flex justify-center",children:e(L,{size:"xl"})}:{className:"text-muted text-center text-sm py-1",children:`All ${b.length} objects loaded.`})]})}function ei(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(Ys,{onChange:d,isLoading:r,refresh:s,className:"w-full"}),e(K,{})]}),t("div",{className:"flex gap-1 items-center",children:[e(y,{variant:"outline",onClick:u,alt:"Refresh",children:e(Xe,{size:16})}),e(Hn,{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(Ys,{onChange:d,isLoading:r,refresh:s})}),t("div",{className:"flex gap-1 items-center",children:[e(y,{variant:"outline",onClick:u,alt:"Refresh",children:e(Xe,{size:16})}),e(Hn,{onUpdate:m})]})]})]})}function ti({object:n,onClose:r}){const{store:s}=jt(),i=v(),a=Ft(),l=Ws(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(y,{variant:"ghost",size:"sm",title:"Open Object",onClick:()=>a(`/objects/${n.id}`),children:e(Ve,{className:"size-4"})}),n.content?.source&&e(y,{variant:"ghost",size:"sm",title:"Download",onClick:l,children:e(Ke,{className:"size-4"})})]}),e(pe,{className:"my-2"}),e("div",{className:"pt-2",children:e(Zn,{object:n,loadText:!0},n.id)})]}):null}var ni;function ri({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(si,{onClose:s}),n&&e(ii,{})]})}function si({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(ni),value:r,onChange:s,placeholder:"Choose a format",className:"h-full w-full text-sm",filterBy:"name",isClearable:!0}),e(y,{className:"w-full",isDisabled:!r||!i,onClick:()=>{n(r,i==l[1])},children:"Export Properties"})]})]})}function ii({}){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 ai({collection:t}){const n=v(),{client:r,typeRegistry:s}=jt();Cs().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(Zs,{layout:i}):e(Xs,{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"}(ni||(ni={}));const li=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 oi({className:t,defaultValue:n,onChange:r,isClearable:s,multiple:i}){const a=jt(),[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:li,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:li,className:t||"text-sm bg-background",filterBy:"name",isClearable:s||!1})})}function ci({onClose:n,redirect:r=!0,onAddToCollection:s}){const i=Ft(),a=v(),[l,c]=o(!1),{client:d}=jt(),[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(oi,{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(oi,{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(y,{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 di({isOpen:n,onClose:r}){return t(te,{onClose:r,isOpen:n,children:[e(ne,{children:"Create a Collection"}),e(ci,{onClose:r})]})}function ui({}){const{client:r}=jt(),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:[mi(n.dynamic),e(Lt,{href:`/collections/${n.id}`,children:n.name})]})}),e("td",{children:n.type?.name||"-"}),e("td",{children:Rt(n.created_at).fromNow()}),e("td",{className:"text-right",children:e(y,{variant:"destructive",size:"sm",onClick:()=>a(n.id),children:e(ut,{className:"size-4"})})})]},n.id)))})]}):e(be,{title:"No Collections",buttonLabel:"New Collections",onClick:()=>m(!0),children:"Get started by creating a new Collections."})),e(di,{isOpen:u,onClose:()=>m(!1)}),e(ye,{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 mi(t){const n=t?"Dynamic Collection":"Static Collection",r=e(t?mt:ht,{className:"size-5"});return e(V,{description:n,className:"mr-2",children:r})}function hi({objects:n,isLoading:r}){const s=Ft();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:Rt(n.updated_at).fromNow()})]},n.id)))})]})})}Rt.extend(an),Rt.extend(an);class pi{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 fi=d(void 0);function gi(){return u(fi)}function vi(){const e=gi();return{...ee(e.result),search:e}}function bi(){return gi().objects.length}function yi({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(y,{variant:"secondary",onClick:()=>s(),children:"Cancel"}),e(y,{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 xi;function wi({isDirty:n=!1}){const r=jt(),{store:s}=r,i=v(),[a,l]=o(!1),{search:d,isLoading:u,error:h,objects:p}=vi(),[f,g]=o(""),b=xe(f,500),y=m(null);le(y,(()=>{a&&d.loadMore()}),{deps:[a]}),c((()=>{d.search().then((()=>l(!0)))}),[]),c((()=>{d.query.name=f,d.search().then((()=>l(!0)))}),[b]);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(xi),value:x,onChange:e=>{w(e)},placeholder:"Is Chunkable"})]}),t("div",{className:"flex-1",children:[u||0!==p?.length?e(hi,{objects:p,isLoading:u}):e(be,{title:"No Type",buttonLabel:"Create Type",onClick:()=>{k(!0)},children:"Get started by creating a new Type."}),e(yi,{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"}(xi||(xi={}));const Ni=[cn,on()];function ki({objectType:n,onSchemaUpdate:r}){const{store:s}=jt(),i=v(),[a,c]=o(!1),d=Kt(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);Ci(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(y,{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(y,{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(Yt,{value:f,extensions:Ni,editorRef:u}):e(Qt,{schema:d})})]})}const Ci=e=>{try{new Bt({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}=jt(),a=l((()=>{const e=new pi(i,n);return e.query.name=r,e.query.chunkable=s,e}),[n]);return e(fi.Provider,{value:a,children:t})}function ji({isOpen:n,onClose:r,title:s="Select Content Type",children:i,initialSelectedType:a=null,confirmLabel:l="Select Type",allowNone:c=!0}){const{typeRegistry:d}=jt(),[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(et,{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(y,{variant:"ghost",onClick:p,children:"Cancel"}),e(y,{onClick:()=>{r(u?.id??null)},children:u?`${l}: ${u.name}`:c?"Let Vertesia Choose":l})]})]})}const Si=[cn,on()];function Ti({objectType:n,onLayoutUpdate:r}){const s=v(),[i,a]=o(!1),{store:c}=jt(),d=m(void 0),u=l((()=>Pi(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(y,{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(Yt,{value:u,extensions:Si,editorRef:d})})]})}function Pi(e){return e?JSON.stringify(e,null,2):"[\n\n]"}const Ii=[cn,on()];function Ai({refetch:n,collection:r}){const s=r.type?.id,i=m(void 0),a=v(),{client:c}=jt(),[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((()=>Pi(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(y,{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(dn,{userRef:r.created_by,showTitle:!0}),t("span",{children:["at ",Rt(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(dn,{userRef:r.updated_by,showTitle:!0}),t("span",{children:["at ",Rt(r.updated_at).format("YYYY-MM-DD HH:mm:ss")]})]})]})]}),e(A,{label:"Name",required:!0,children:e(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(oi,{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(Yt,{className:"border-1 rounded-md border-border",value:f,extensions:Ii,editorRef:i})}),e(A,{label:"Type",description:"Select a content type to assign custom properties and data to the collection.",children:e(oi,{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(Ei,{typeId:s,collection:r})]})}function Ei({typeId:t,collection:n}){const r=v(),{client:s}=jt(),[i,a]=o(!1),{data:c,error:d}=W((()=>s.store.types.retrieve(t)),[t]),u=c?.object_schema||{},m=l((()=>new Xt(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(y,{size:"lg",isLoading:i,type:"submit",children:"Save"}),children:e(Zt,{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 $i(e){return e.name}function zi({onChange:t,value:n,disabled:r=!1,placeholder:s="Select a collection",filterOut:i,allowDynamic:a=!0,multiple:l=!1}){const{client:o}=jt(),c=p((e=>{if(l){const n=e;if(n&&n.length>0){const e=n.map((e=>e.id));t(e,n)}else t(void 0)}else{const n=e;n?t(n.id,n):t(void 0)}}),[t,l]),{data:d,error:u}=W((async()=>{const e=await o.store.collections.search({dynamic:!!a&&void 0});return i&&i.length>0?e.filter((e=>!i.includes(e.id))):e}),[o,a,i]);if(u)return e(oe,{title:"Error",children:u.message||String(u)});const m=l?d?.filter((e=>Array.isArray(n)&&n.includes(e.id)))||[]:d?.find((e=>e.id===n))||null;return e(ae,{className:"w-full",by:"id",value:m,filterBy:"name",options:d||[],disabled:r,optionLabel:e=>$i(e),placeholder:s,onChange:c,isClearable:!0,multiple:l})}function Oi({action:n,objectIds:r,children:s}){const{store:i}=jt(),a=v(),[l,c]=o(!1),d=p((()=>(c(!0),Promise.resolve(!0))),[]);ta(n.id,d);return t("div",{children:[s,e(ji,{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 Di={id:"changeType",name:"Change Content Type",description:"Change the Content Type of the selected documents",confirm:!1,component:Oi};function Ui({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=ta(r.id,d);return t(n,{children:[i,e(ye,{onConfirm:()=>{l(!1),s({...u.params,action:r})},onCancel:()=>l(!1),title:"Are you sure?",content:c,isOpen:a})]})}function Li({action:t,objectIds:n,children:r}){const s=ea(),i=v(),{client:a}=jt(),l=Cs(),o=Ft(),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(Ui,{action:t,callback:c,children:r})}const Fi={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:Li,destructive:!0},Ri={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:Li,destructive:!0};function Mi({action:t,objectIds:n}){const{store:r}=jt(),s=v(),[i,a]=o(!1),[l,c]=o(!1),d=p((()=>(a(!0),Promise.resolve(!0))),[]),u=ta(t.id,d);return e("div",{children:e(ri,{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===ni.CSV)i=new Blob([r.data],{type:r.type});else if(e===ni.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 Vi={id:"exportProperties",name:"Export Properties",description:"Export all Object Properties",confirm:!1,component:Mi};function qi({action:t,objectIds:n,collectionId:r}){const s=ea(),i=v(),{client:a}=jt(),l=Cs(),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(Ui,{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:qi,destructive:!0};function Wi({action:t,objectIds:n,collectionId:r}){const s=v(),{client:i}=jt(),[a,l]=o(!1),c=p((()=>(l(!0),Promise.resolve(!0))),[]);return ta(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 Gi={id:"startWorkflow",name:"Start Workflow",description:"Start an workflow on the selected objects",confirm:!1,hideInList:!0,component:Wi};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(Ki,{onClose:r})]})}function Ji(n){return{label:t("div",{children:[e("div",{children:n.name}),e("div",{className:"text-sm text-muted",children:n.description})]}),reverse:!0}}function Ki({onClose:n}){const[r,s]=o(void 0),i=ea();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(Ne,{options:i.wfRules,optionLayout:Ji,onChange:e=>{s(e)},value:r})})]}),t(ie,{children:[e(y,{variant:"secondary",onClick:()=>n(),children:"Cancel"}),e(y,{onClick:()=>{r&&n(r.id)},isDisabled:!r,children:"Start"})]})]})}class Yi{params;allActions=[Vi,Di,Gi,sa,Fi,Bi,Ri];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:Wi}))).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 Qi=d(void 0);function Xi({children:n}){const r=ms(),s=v(),{client:i}=jt(),a=Cs(),{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:Wi}))).sort(((e,t)=>e.name.localeCompare(t.name)))))),[]),d=l((()=>{const e=new Yi({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(Qi.Provider,{value:d,children:[e(Zi,{}),n]})}function Zi({}){const t=ea(),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 ea(){const e=u(Qi);if(!e)throw new Error("You cannot use useActionContext outside an ActionProvider");return e}function ta(e,t){const n=ea();return c((()=>n.registerCallback(e,t)),[n,e,t]),n}function na(e){const t=ea();return c((()=>(t.startWorkflow=e,()=>{t.startWorkflow=void 0})),[e,t]),t}function ra({action:t,objectIds:n}){const[r,s]=o(!1),i=p((()=>(n.length>0&&s(!0),Promise.resolve(!0))),[n]);return ta(t.id,i),r&&e(ke,{children:e(ia,{objectIds:n,isOpen:r,onClose:()=>{s(!1)}})})}const sa={id:"addToCollection",name:"Add to Collection",description:"Add documents to a collection",confirm:!1,component:ra};function ia({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(Ce,{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(aa,{onClose:r,objectIds:s})})]})}function aa({onClose:n,objectIds:r}){const s=v(),{client:i}=jt(),[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(zi,{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(y,{isDisabled:!a,onClick:()=>a&&c({collectionId:a}),children:"Add to Collection"})})]})},{name:"create",label:"Create new",content:e("div",{className:"p-4",children:e(ci,{onClose:n,onAddToCollection:e=>c({collectionId:e}),redirect:!1})})}];return t(je,{defaultValue:"select",tabs:d,fullWidth:!0,children:[e(Se,{}),e(Te,{})]})}function la(){const n=ms(),r=n.size(),s=r>1?"s":"",i=n?.hasSelection(),a=n?.isSingleSelection();return e(Xi,{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(y,{title:"Clear selection",variant:"ghost",onClick:()=>{n?.removeAll()},children:e(it,{className:"size-4"})})]}),e(ma,{selection:n,children:e(y,{variant:"ghost",alt:"More action",size:"sm",children:e(pt,{size:16})})}),i&&e(oa,{selection:n})]})})}function oa({}){return e(da,{})}function ca({collectionId:r}){const[s,i]=o([]),a=ms(),l=a?.hasSelection();return!l&&t(n,{children:[e(y,{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(As,{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 da(){const t=ea();return t.params.selection.hasSelection()&&e(y,{onClick:()=>t.run(Gi.id),children:"Start Workflow"})}function ua(e){return{label:e.name,className:r("flex-1 px-2 py-2 hover:bg-accent nowrap",e.destructive?"text-destructive":"")}}function ma({selection:n,children:r}){const s=ea();return t(x,{hover:!0,children:[e(w,{children:r}),e(N,{className:"p-0 w-50",align:"end",sideOffset:6,children:e(ha,{executeAction:e=>{s.run(e.id)},selection:n})})]})}function ha({executeAction:t,selection:n}){const r=ea(),s=n?.hasSelection()?r.actions.filter((e=>!e.hideInList)):[Vi];return e("div",{className:"rounded-md shadow-md py-2",children:e("div",{className:"px-1 text-sm",children:e(Ne,{options:s,optionLayout:ua,onChange:e=>{t(e)},noCheck:!0})})})}function pa({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(y,{variant:"ghost",className:"rounded-full",disabled:!l,onClick:()=>f(!0),alt:"Link Object",children:e(ft,{className:"size-4"})})]}),t(y,{onClick:s,disabled:i||a||!n.trim(),className:"px-4 py-2.5",children:[a?e(L,{size:"sm",className:"mr-2"}):e(gt,{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(vt,{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(Fs,{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 fa({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(y,{variant:"ghost",onClick:a,children:[e(it,{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(y,{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(y,{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=bt,c="text-muted";return"in_progress"===l?(o=Le,c="text-info"):"completed"===l&&(o=Ue,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(b,{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(Oe,{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=bt,i="text-gray-400",a="bg-gray-100 dark:bg-gray-800",l="Pending";return"in_progress"===r?(s=Le,i="text-info",a="bg-info/20",l="In Progress"):"completed"===r&&(s=Ue,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 ga(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(ya,{...t,run:r})}return r?e(ba,{...t}):e(va,{})}function va(){return t(se,{status:"info",icon:e(Ee,{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,b]=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&&(b({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(ya,{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(yt,{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(y,{size:"xs",variant:"ghost",onClick:s,title:"Close",className:"text-slate-500 hover:text-slate-700",children:e(Re,{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(y,{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(gt,{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 ya({run:n,title:r,interactive:s=!0,onClose:i,isModal:a=!1,placeholder:d="Type your message...",resetWorkflow:u}){const{client:h}=jt(),p=m(null),[f,g]=o([]),[b,y]=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(!b){const e=setInterval((()=>{O((()=>Math.floor(Math.random()*($n.length-1))))}),4e3);return()=>clearInterval(e)}}),[b]);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((()=>{y(!function(e){if(!e.length)return!0;const t=new Map;if(e.forEach((e=>{const n=On(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}`),zn.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}`),zn.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(!zn.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===St.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===St.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===St.TERMINATED?(L(!1),R("TERMINATED")):L(!!s||e.type===St.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(Bn,{title:V,isCompleted:b,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||b?e(Fn,{messages:f,bottomRef:p,viewMode:C,isCompleted:b,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(Tn,{size:"sm",color:"blue"}),e("div",{className:"text-sm text-muted font-medium",children:$n[z]})]}),e("div",{className:"mt-4 flex justify-center",children:e(Sn,{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(pa,{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((()=>{y(!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:b,activeTaskCount:(()=>{if(!f.length)return 0;const e=new Map;f.forEach((t=>{const n=On(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];[St.COMPLETE,St.IDLE].includes(e.type)||t++}return t})(),placeholder:d}))]}),j&&e("div",{className:"h-full lg:w-1/3 border-l",children:e(fa,{plan:M.plan,workstreamStatus:M.workstreamStatus,isOpen:j,onClose:()=>S(!1),plans:T,activePlanIndex:I,onChangePlan:A})})]})}function xa({children:t,fallback:n}){return wa?e(wa,{fallback:n,children:t}):e(un,{FallbackComponent:n,children:t})}let wa=null;function Na(e){wa=e}function ka({children:t}){return e(xa,{fallback:Ca,children:t})}function Ca({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 _a({children:t}){return e(xa,{fallback:ja,children:t})}function ja({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 Sa({children:t}){return e(xa,{fallback:Ta,children:t})}function Ta({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 Pa({className:n,children:s,title:i,description:a,actions:l,breadcrumbs:o,isCompact:c=!1,useDynamicBreadcrumbs:d=!0}){const u=Ft(),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`${mn(e)} Detail`}return n.length>=2?mn(n[n.length-1]):1===n.length?mn(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(Pe,{path:h,separator:e(ct,{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(ze,{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 Ia({}){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 Aa{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(Ra(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(Ma(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 $a=d(void 0);function za({children:t,object:n}){const{client:r}=jt(),[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(Da(e,t.id,s+1));const s=await Promise.all(r),i=[];for(let r=0;r<n;r++)i.push(Ua(e,t.id,r+1));const a=await Promise.all(i),l=[];for(let r=0;r<n;r++)l.push(La(e,t.id,r+1));const o=await Promise.all(l),c=[];for(let r=0;r<n;r++)c.push(Fa(e,t.id,r+1));const d=await Promise.all(c),u=new Aa(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?qa(h):[]}})(r,n,e).then(i)}),[n.id]),s&&e($a.Provider,{value:s,children:t})}function Oa(e){return`magic-pdf/${e}`}function Da(e,t,n){return e.files.getDownloadUrl(function(e,t,n=".jpg"){return`${Oa(e)}/pages/page-${t}${n}`}(t,n))}function Ua(e,t,n){return e.files.getDownloadUrl(function(e,t,n=".jpg"){return`${Oa(e)}/pages/page-${t}-annotated${n}`}(t,n))}function La(e,t,n){return e.files.getDownloadUrl(function(e,t,n=".jpg"){return`${Oa(e)}/pages/page-${t}.instrumented${n}`}(t,n))}function Fa(e,t,n){return e.files.getDownloadUrl(function(e,t,n=".jpg"){return`${Oa(e)}/pages/page-${t}.original${n}`}(t,n))}function Ra(e,t,n){return e.files.getDownloadUrl(function(e,t){return`${Oa(e)}/pages/page-${t}.layout.json`}(t,n))}function Ma(e,t,n){return e.files.getDownloadUrl(function(e,t){return`${Oa(e)}/pages/page-${t}.md`}(t,n))}function Va(){const e=a.useContext($a);if(!e)throw new Error("usePdfPagesInfo must be used within a PdfPageProvider");return e}function qa(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 Wa({object:r}){const{client:s}=jt(),i=e=>{(function(e,t,n){return e.files.getDownloadUrl(`${Oa(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(en,{strategy:"absolute",placement:"top-end",zIndex:100,offset:20,children:[e(en.Trigger,{click:!0,children:e(xt,{className:"size-6"})}),e(en.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 Ga;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()?Ga.original:Ga.default),h=m(null),{urls:p,originalUrls:f,annotatedUrls:g,instrumentedUrls:v}=Va(),b=d===Ga.instrumented?v:d===Ga.annotated?g:d===Ga.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:Ka,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(wt,{className:"w-5 h-5"})}),e("div",{className:"absolute right-3 flex gap-x-1",children:"markdown"===c()?t(n,{children:[e("button",{className:Ya(Ga.original,d),onClick:()=>u(Ga.original),children:e(Nt,{className:"w-5 h-5 mt-1"})}),e("button",{className:Ya(Ga.instrumented,d),onClick:()=>u(Ga.instrumented),children:e(kt,{className:"w-5 h-5 mt-1"})})]}):t(n,{children:[e("button",{className:Ya(Ga.default,d),onClick:()=>u(Ga.default),children:e(Nt,{className:"w-5 h-5 mt-1"})}),e("button",{className:Ya(Ga.instrumented,d),onClick:()=>u(Ga.instrumented),children:e(kt,{className:"w-5 h-5 mt-1"})}),e("button",{className:Ya(Ga.annotated,d),onClick:()=>u(Ga.annotated),children:e(Ct,{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:b.map(((t,n)=>e(Ja,{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:Ka,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(_t,{className:"size-5"})})})]})}function Ja({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(Ie,{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"}(Ga||(Ga={}));const Ka="cursor-pointer text-gray-500 dark:text-gray-400 hover:text-blue-600 dark:hover:text-blue-500 hover:font-semibold";function Ya(e,t){return e===t?"${BTN_CLASS} text-pink-600":`${Ka}`}const Qa={attributeKeyColor:"#FFD700",attributeValueColor:"#FF4500",tagColor:"#87CEFA",textColor:"#00FF00",separatorColor:"#FFD700",commentColor:"#BEBEBE",cdataColor:"#33CC66"};function Xa({viewType:t,pageNumber:n}){switch(t){case"json":return e(el,{pageNumber:n});case"markdown":return e(tl,{pageNumber:n});default:return e(Za,{pageNumber:n})}}function Za({pageNumber:t}){const[n,r]=o(),{xmlPages:s}=Va();return f((()=>{const e=window.matchMedia("(prefers-color-scheme: dark)"),t=e=>{r(e.matches?Qa:void 0)};return e.addEventListener("change",t),e.matches&&r(Qa),()=>{e.removeEventListener("change",t)}}),[]),e("div",{className:"px-4 py-2",children:e(tn,{xml:s[t-1],collapsible:!0,theme:n})})}function el({pageNumber:t}){const[n,r]=o(),{layoutProvider:s}=Va();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(nn,{className:"w-full",data:n})}function tl({pageNumber:t}){const[n,r]=o(),{markdownProvider:s}=Va();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(Wt,{children:n}):e("div",{children:"No markdown content available"})})}function nl({objectId:t,onClose:n}){const{client:r}=jt(),{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(za,{object:s,children:e(rl,{object:s,onClose:n})})}):"Loading..."}function rl({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(Xa,{pageNumber:l,viewType:i})}),e(Wa,{object:r}),"xml"===u&&e(sl,{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(it,{className:"size-6"})})]})}function sl({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&&il,"json"===e&&ll,"markdown"===e&&al]})}const il=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"})}),al=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"})}),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:"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 ol(...e){const t=Array.from(e);return t.__AnyOf__=!0,t}function cl(...e){return Array.from(e)}function dl(e){return!0===e.__AnyOf__}class ul{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(dl(e))return e.some((e=>this.permissions.has(e)));for(const t of e)if(!this.permissions.has(t))return!1;return!0}}const ml=d(void 0);function hl(){const e=u(ml);if(!e)throw new Error("UserPermissionContext cannot be used outside UserPermissionProvider");return e}function pl({children:t}){const n=jt(),{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 ul(n,r):void 0),[n,r,i]);return s?e(oe,{title:"Failed to fetch role mappings",children:s.message}):a&&e(ml.Provider,{value:a,children:t})}function fl({permission:t,isDisabled:n,title:r,children:s,...i}){return hl().hasPermission(t)||(n=!0,r="You do not have permission to perform this action"),e(y,{isDisabled:n,title:r,...i,children:s})}function gl({permission:t,...n}){return hl().hasPermission(t)?e(hn,{...n}):null}function vl({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{vn as ActivitiesDoc,yn as ActivityDoc,sa as AddToCollectionAction,ra as AddToCollectionActionComponent,cl as AllOf,Sn as AnimatedThinkingDots,ol as AnyOf,Vr as ApiKeyAvatar,ai as BrowseCollectionView,Di as ChangeTypeAction,Oi as ChangeTypeActionComponent,cs as CollectionsFacetsNav,ui as CollectionsTable,Hn as ContentDispositionButton,wi as ContentObjectTypesSearch,hi as ContentObjectTypesTable,Zn as ContentOverview,ci as CreateCollectionForm,di as CreateCollectionModal,yi as CreateOrUpdateTypeModal,Fi as DeleteObjectsAction,Li as DeleteObjectsActionComponent,Ri as DeleteObjectsFromCollectionsAction,ws as DocumentGridView,wr as DocumentIcon,xr as DocumentIconSkeleton,Bs as DocumentInput,Gs as DocumentPreviewPanel,Ns as DocumentSearch,Us as DocumentSearchProvider,Zs as DocumentSearchResults,Xs as DocumentSearchResultsWithDropZone,ds as DocumentSelection,ps as DocumentSelectionProvider,zs as DocumentTable,ys as DocumentTableColumn,xs as DocumentTableView,As as DocumentUploadModal,es as DocumentsFacetsNav,Ai as EditCollectionView,Wr as EnvironmentFacet,Vi as ExportPropertiesAction,Mi as ExportPropertiesComponent,ri as ExportPropertiesModal,ni as ExportTypes,Ts as FileUploadAction,Pa as GenericPageNavHeader,rs as InteractionsFacetsNav,jn as JumpingDots,nl as MagicPdfView,ga as ModernAgentConversation,Ia as NotFoundView,ki as ObjectSchemaEditor,pi as ObjectTypeSearch,fi as ObjectTypeSearchContext,_i as ObjectTypeSearchProvider,Yi as ObjectsActionContext,Xi as ObjectsActionContextProvider,ka as PanelErrorBoundary,Rn as PayloadBuilder,Vn as PayloadBuilderProvider,Mn as PayloadContext,as as PromptsFacetsNav,Yn as PropertiesEditorModal,Tn as PulsatingCircle,In as PulsingMessageLoader,Bi as RemoveFromCollectionAction,qi as RemoveFromCollectionActionComponent,_a as RowErrorBoundary,Jr as RunsFacetsNav,Kn as SaveVersionConfirmModal,ks as SearchContext,fl as SecureButton,gl as SecureSidebarItem,zi as SelectCollection,oi as SelectContentType,ji as SelectContentTypeModal,Fs as SelectDocument,Vs as SelectDocumentModal,la as SelectionActions,Gi as StartWorkflowAction,Wi as StartWorkflowComponent,Cr as StringFacet,_r as StringListFacet,Ti as TableLayoutEditor,An as ThinkingBar,$n as ThinkingMessages,Sr as TypeFacet,Pn as TypedDots,ca as UploadObjectsButton,vl as UserAvatar,Lr as UserInfo,pl as UserPermissionProvider,ul as UserPermissions,ml as UserPermissionsContext,Tr as VStringFacet,Pr as VTypeFacet,Br as VUserFacet,xa as VertesiaErrorBoundary,En as WavyThinking,Sa as WidgetErrorBoundary,Qr as WorkflowExecutionsFacetsNav,mi as collectionIcon,dl as isAnyOf,mr as isCsv,hr as isImage,pr as isPdf,fr as isVideo,yr as retrieveRendition,Na as setErrorBoundaryComponent,ar as shortId,lr as shortenString,Pi as stringifyTableLayout,ls as useCollectionsFilterGroups,os as useCollectionsFilterHandler,Xr as useDocumentFilterGroups,Zr as useDocumentFilterHandler,Cs as useDocumentSearch,Ss as useDocumentSearchCount,ms as useDocumentSelection,Es as useDocumentUploadHandler,Ws as useDownloadDocument,$r as useFetchGroupInfo,Er as useFetchUserInfo,ts as useInteractionsFilterGroups,ns as useInteractionsFilterHandler,ta as useObjectsActionCallback,ea as useObjectsActionContext,hs as useOptionalDocumentSelection,qn as usePayloadBuilder,ss as usePromptsFilterGroups,is as usePromptsFilterHandler,Gr as useRunsFilterGroups,Hr as useRunsFilterHandler,gi as useSearch,bi as useSearchCount,Is as useSmartFileUploadProcessing,na as useStartWorkflowCallback,hl as useUserPermissions,_s as useWatchDocumentSearchFacets,js as useWatchDocumentSearchResult,vi as useWatchSearchResult,Kr as useWorkflowExecutionsFilterGroups,Yr as useWorkflowExecutionsFilterHandler};
|
|
1
|
+
import{jsx as e,jsxs as t,Fragment as n}from"react/jsx-runtime";import r from"clsx";import{AnimatePresence as i,motion as a}from"motion/react";import s,{useMemo as l,useState as o,useEffect as c,createContext as d,useContext as u,useRef as m,useCallback as h,Component as p,memo as f}from"react";import{cn as g,useToast as y,Badge as b,Button as v,Popover as x,PopoverTrigger as w,PopoverContent as N,Command as k,CommandList as C,CommandGroup as S,CommandItem as P,Modal as j,ModalTitle as _,ModalBody as T,RadioGroup as I,FormItem as A,Input as z,ModalFooter as E,RadioOptionAdapter as F,Center as D,VTooltip as $,useFetch as L,ErrorBox as O,ResizablePanelGroup as R,ResizablePanel as U,ResizableHandle as M,Spinner as V,Portal as K,VModal as q,VModalTitle as B,VModalBody as W,VModalFooter as G,Card as H,Separator as J,CardContent as Y,SelectBox as Z,InputList as Q,Avatar as X,Table as ee,FilterProvider as te,FilterBtn as ne,FilterBar as re,FilterClear as ie,TBody as ae,SharedState as se,useWatchSharedState as le,MessageBox as oe,VSelectBox as ce,useIntersectionObserver as de,useFlag as ue,Styles as me,Checkbox as he,NumberInput as pe,SidePanel as fe,Divider as ge,Textarea as ye,Switch as be,TR as ve,EmptyCollection as xe,ConfirmModal as we,useDebounce as Ne,Panel as ke,CommandInput as Ce,CommandEmpty as Se,TagsInput as Pe,SelectList as je,DialogDescription as _e,Heading as Te,VTabs as Ie,VTabsBar as Ae,VTabsPanel as ze,Breadcrumbs as Ee}from"@vertesia/ui/core";import{CopyIcon as Fe,Bot as De,MessageSquare as $e,Info as Le,AlertCircle as Oe,User as Re,CheckCircle as Ue,Clock as Me,ClipboardList as Ve,XIcon as Ke,MoreVertical as qe,ExternalLink as Be,DownloadCloudIcon as We,TableProperties as Ge,LayoutGrid as He,Loader2 as Je,ChevronsUp as Ye,ChevronsDown as Ze,Minus as Qe,Plus as Xe,Maximize as et,Image as tt,ScanSearch as nt,Download as rt,X as it,Maximize2 as at,AlertTriangle as st,Copy as lt,SquarePen as ot,FileSearch as ct,Eye as dt,Users as ut,RefreshCw as mt,UploadIcon as ht,CheckCircleIcon as pt,AlertCircleIcon as ft,FileIcon as gt,XCircleIcon as yt,FolderIcon as bt,ChevronsUpDown as vt,FileText as xt,ChevronRight as wt,Settings as Nt,Trash2 as kt,Search as Ct,FolderClosed as St,Check as Pt,EllipsisVertical as jt,PaperclipIcon as _t,SendIcon as Tt,Activity as It,Circle as At,Cpu as zt}from"lucide-react";import{useUserSession as Et}from"@vertesia/ui/session";import{AgentMessageType as Ft,AgentSearchScope as Dt,mergeInCodePromptSchemas as $t,supportsToolUse as Lt,ImageRenditionFormat as Ot,WorkflowExecutionStatus as Rt,PDF_RENDITION_NAME as Ut,MarkdownRenditionFormat as Mt,ContentObjectStatus as Vt,ContentNature as Kt,POSTER_RENDITION_NAME as qt,PrincipalType as Bt,InteractionStatus as Wt,SearchTypes as Gt,SupportedEmbeddingTypes as Ht}from"@vertesia/common";import{NavLink as Jt,useNavigate as Yt}from"@vertesia/ui/router";import{MarkdownRenderer as Zt,Popover as Qt,XMLViewer as Xt,JSONCode as en,JSONDisplay as tn,Progress as nn,DropZone as rn,UploadSummary as an,useSchema as sn,CodeMirrorEditor as ln,SchemaEditor as on,ManagedObject as cn,GeneratedForm as dn}from"@vertesia/ui/widgets";import un from"dayjs";import mn,{Ajv as hn}from"ajv";import pn from"@monaco-editor/react";import{pdfjs as fn,Document as gn,Page as yn}from"react-pdf";import bn from"dayjs/plugin/localizedFormat";import vn from"dayjs/plugin/relativeTime";import{Md5 as xn}from"ts-md5";import{json as wn}from"@codemirror/lang-json";import{UserInfo as Nn,SyncMemberHeadsToggle as kn,SharedPropsEditor as Cn}from"@vertesia/ui/features";import{basicSetup as Sn}from"codemirror";import{toPng as Pn}from"html-to-image";import{XAxis as jn,YAxis as _n,CartesianGrid as Tn,Tooltip as In,Legend as An,ReferenceLine as zn,ResponsiveContainer as En,ComposedChart as Fn,AreaChart as Dn,LineChart as $n,BarChart as Ln,Line as On,Area as Rn,Bar as Un,PieChart as Mn,Pie as Vn,Cell as Kn,ScatterChart as qn,Scatter as Bn,RadarChart as Wn,PolarGrid as Gn,PolarAngleAxis as Hn,PolarRadiusAxis as Jn,Radar as Yn,RadialBarChart as Zn,RadialBar as Qn,FunnelChart as Xn,Funnel as er,LabelList as tr,Treemap as nr}from"recharts";import{ErrorBoundary as rr}from"react-error-boundary";import{capitalize as ir}from"lodash-es";import{SidebarItem as ar}from"@vertesia/ui/layout";function sr({children:t,secondary:n=!1}){return e("span",{className:n?"bg-secondary text-primary":"text-foreground bg-muted",children:t})}function lr(e){return e?"array"===e.name?lr(e.innerType):e:void 0}function or({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(sr,{children:"optional"}),e(sr,{children:n.type.value})]})}function cr({activities:t}){return e("div",{className:"flex flex-col gap-y-4 divide-y divide-gray-200",children:t.map(t=>e(ur,{activity:t},t.name))})}function dr({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(sr,{children:n})})]})}function ur({activity:n,headingClass:r,headingRef:i}){return t("div",{className:r,id:n.name,ref:i,children:[e("div",{className:"text-xl font-semibold pt-8",children:n.title}),e("div",{className:"pb-4",children:e(sr,{children:n.name})}),n.doc&&e("div",{className:"text-gray-700 pb-2",children:n.doc}),t("div",{className:"pb-4",children:[e(dr,{code:n.paramsType,children:"Parameters"}),e("div",{className:"divide-y divide-gray-100",children:n.params.map(t=>e(mr,{property:t},t.name))})]}),t("div",{className:"pb-4",children:[e(dr,{children:"Returns"}),e("div",{children:n.returnType?n.returnType.value:"void"})]})]})}function mr({property:n,className:i}){const a=l(()=>{const t=lr(n.type.innerType)??n.type;return"object"===t.name&&t.members?e(pr,{members:t.members}):"enum"===t.name&&t.enum?e(hr,{values:t.enum}):null},[n.type.innerType]);return t("div",{className:r("py-2",i),children:[e(or,{property:n}),n.doc&&e("div",{className:"text-gray-700 text-sm pt-2",children:n.doc}),a&&e("div",{className:"my-2 overflow-hidden",children:a})]})}function hr({values:t}){return e("div",{className:"flex flex-wrap items-center gap-2",children:t.map((t,n)=>e(sr,{secondary:!0,children:t},n))})}function pr({members:n}){return e(gr,{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(yr,{isOpen:n}),e("div",n?{children:"Hide child properties"}:{children:"Show child properties"})]}),body:e(fr,{properties:n})})}function fr({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(mr,{property:t,className:"px-4 py-2"},t.name))})}function gr({button:n,body:s,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(i,{children:n(d)})}),e(i,{children:d&&e(a.div,{className:"overflow-hidden",initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.3,ease:"easeOut"},children:s})})]})}function yr({isOpen:t}){return e(i,{propagate:!0,mode:"wait",children:e(a.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 br({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 vr({className:n,inline:r=!1,color:i="blue"}){const a={blue:"from-blue-400 to-indigo-500 dark:from-blue-500 dark:to-indigo-400",purple:"from-purple-400 to-violet-500 dark:from-purple-500 dark:to-violet-400",teal:"from-teal-400 to-emerald-500 dark:from-teal-500 dark:to-emerald-400",green:"from-green-400 to-emerald-500 dark:from-green-500 dark:to-emerald-400",amber:"from-amber-400 to-orange-500 dark:from-amber-500 dark:to-orange-400"}[i];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 ${a} rounded-full animate-[bounce_1.2s_ease-in-out_infinite]`}),e("div",{className:`w-2 h-2 bg-gradient-to-r ${a} rounded-full animate-[bounce_1.2s_ease-in-out_0.2s_infinite]`}),e("div",{className:`w-2 h-2 bg-gradient-to-r ${a} rounded-full animate-[bounce_1.2s_ease-in-out_0.4s_infinite]`})]})}function xr({className:n,size:r="md",color:i="blue"}){const a={blue:"bg-blue-500 dark:bg-blue-400",purple:"bg-purple-500 dark:bg-purple-400",teal:"bg-teal-500 dark:bg-teal-400",green:"bg-green-500 dark:bg-green-400",amber:"bg-amber-500 dark:bg-amber-400"};return t("span",{className:g("relative flex",n),children:[e("span",{className:g("animate-ping absolute inline-flex h-full w-full rounded-full opacity-60",a[i])}),e("span",{className:g("animate-pulse absolute inline-flex h-[80%] w-[80%] rounded-full opacity-80",a[i]),style:{left:"10%",top:"10%",animationDuration:"2s"}}),e("span",{className:g("relative inline-flex rounded-full",a[i],{sm:"w-3 h-3",md:"w-5 h-5",lg:"w-7 h-7"}[r])})]})}function wr({className:t,color:n="blue"}){const[r,i]=o(".");return c(()=>{const e=setInterval(()=>{i(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 Nr({message:n,className:r,color:i="blue"}){const a={blue:{dot:"bg-blue-500 dark:bg-blue-400",text:"text-blue-700 dark:text-blue-300"},purple:{dot:"bg-purple-500 dark:bg-purple-400",text:"text-purple-700 dark:text-purple-300"},teal:{dot:"bg-teal-500 dark:bg-teal-400",text:"text-teal-700 dark:text-teal-300"},green:{dot:"bg-green-500 dark:bg-green-400",text:"text-green-700 dark:text-green-300"},amber:{dot:"bg-amber-500 dark:bg-amber-400",text:"text-amber-700 dark:text-amber-300"}};return t("div",{className: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 ${a[i].dot} rounded-full animate-bounce`}),e("div",{className:`w-1.5 h-1.5 ${a[i].dot} rounded-full animate-bounce`,style:{animationDelay:"0.2s"}}),e("div",{className:`w-1.5 h-1.5 ${a[i].dot} rounded-full animate-bounce`,style:{animationDelay:"0.4s"}})]}),e("div",{className:`${a[i].text} font-medium text-xs`,children:n})]})}function kr({className:n,color:r="blue",width:i="md",message:a}){const[s,l]=o(15),[d,u]=o("increasing"),[m,h]=o(.4);return c(()=>{let e,t=Date.now();const n=()=>{const r=Date.now(),i=r-t;t=r,l(e=>{const t=m*(i/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:[a&&e("div",{className:`text-xs font-medium ${{blue:"text-blue-700 dark:text-blue-300",purple:"text-purple-700 dark:text-purple-300",teal:"text-teal-700 dark:text-teal-300",green:"text-green-700 dark:text-green-300",amber:"text-amber-700 dark:text-amber-300"}[r]} mb-1`,children:a}),e("div",{className: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"}[i]),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:`${s}%`,transition:"width 150ms cubic-bezier(0.4, 0.0, 0.2, 1)"}})})]})}function Cr({className:t,color:n="blue",size:r="md"}){const[i,a]=o(Array(7).fill(50)),s={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 s=()=>{r+=.02;const l=i.map((e,i)=>10+40*(Math.sin(r*t[i]+n[i])+1));a(l),e=requestAnimationFrame(s)};return e=requestAnimationFrame(s),()=>{cancelAnimationFrame(e)}},[]),e("div",{className:g("flex items-end justify-center",s[r].width,s[r].height,s[r].gap,t),children:i.map((t,i)=>e("div",{className:g(s[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}},i))})}const Sr=["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 Pr=[Ft.COMPLETE,Ft.IDLE,Ft.REQUEST_INPUT,Ft.TERMINATED];function jr(e){return e.workstream_id?(e.type===Ft.COMPLETE&&console.log("[getWorkstreamId] COMPLETE message with workstream_id:",e.workstream_id),e.workstream_id):(e.type===Ft.COMPLETE&&console.log("[getWorkstreamId] COMPLETE message without workstream_id, defaulting to 'main'"),"main")}function _r({message:n,showPulsatingCircle:r=!1}){const[i,a]=o(!1),[s,l]=o(""),[d,u]=o(!1),{client:m}=Et(),h=y(),p=(()=>{const t={containerClass:"bg-white border-l-4 border-l-muted/30 shadow-sm",iconComponent:e(De,{className:"size-4 text-muted"}),sender:""};switch(n.type){case Ft.ANSWER:return{...t,containerClass:"bg-white border-l-4 border-l-muted/30 shadow-sm",iconComponent:e(De,{className:"size-4 text-muted"}),sender:"Agent"};case Ft.COMPLETE:return{...t,containerClass:"bg-white border-l-4 border-l-success shadow-sm",iconComponent:e(Ue,{className:"size-4 text-success"}),sender:"Completed"};case Ft.TERMINATED:return{...t,containerClass:"bg-white border-l-4 border-l-attention shadow-sm",iconComponent:e(Ue,{className:"size-4 text-attention"}),sender:"Terminated"};case Ft.QUESTION:return{...t,iconComponent:e(Re,{className:"size-4 text-muted"}),sender:"User"};case Ft.THOUGHT:return{...t,iconComponent:r?e(xr,{size:"sm",color:"blue"}):e(De,{className:"size-4 text-muted"}),sender:"Agent"};case Ft.ERROR:return{...t,iconComponent:e(Oe,{className:"size-4 text-muted"}),sender:"System"};case Ft.UPDATE:return{...t,containerClass:"bg-white border-l-4 border-success shadow-sm",iconComponent:e(Le,{className:"size-4 text-success"}),sender:"Update"};case Ft.PLAN:return{...t,iconComponent:e($e,{className:"size-4 text-muted"}),sender:"Agent"};default:return{...t,sender:"Agent"}}})(),f=()=>{let e="";if(n.message&&(e="object"==typeof n.message?JSON.stringify(n.message,null,2):n.message.trim?n.message.trim():String(n.message)),"string"==typeof e&&e.includes("%thinking_message%")){const t=Math.floor(Math.random()*Sr.length);e=e.replace(/%thinking_message%/g,Sr[t])}return e},g=t=>{if("object"==typeof t)return e("pre",{className:"text-xs font-mono whitespace-pre-wrap overflow-x-auto bg-gray-100 dark:bg-gray-800 p-2 rounded text-gray-700 ",children:JSON.stringify(t,null,2)});const r=n.workflow_run_id;return e("div",{className:"vprose prose-sm",children:e(Zt,{artifactRunId:r,components:{a:({node:t,ref:n,...r})=>{const i=r.href||"";return i.includes("/store/objects")?e(Jt,{href:i,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")})},children:t})})},x=f(),[w,N]=o([]);c(()=>{(async()=>{const e=n.workflow_run_id,t=n.details,r=t&&t.outputFiles;if(e&&Array.isArray(r)&&0!==r.length)try{const t=await Promise.all(r.map(async t=>{if("string"!=typeof t||!t.trim())return null;const n=t.trim(),r=n.startsWith("out/")||n.startsWith("files/")||n.startsWith("scripts/")?n:`out/${n}`,i=r.split(".").pop()?.toLowerCase()||"",a=new Set(["png","jpg","jpeg","gif","webp","bmp","svg"]).has(i);try{const t=a?"inline":"attachment",{url:i}=await m.files.getArtifactDownloadUrl(e,r,t);return{displayName:n,artifactPath:r,url:i,isImage:a}}catch(e){return console.error(`Failed to resolve artifact URL for ${r}`,e),null}}));N(t.filter(e=>!!e))}catch(e){console.error("Error loading artifact URLs from message details",e),N([])}else N([])})()},[n.details,n.timestamp,m]),c(()=>{(async()=>{if(x){u(!0);try{const e=await(async e=>e)((e=>{if("string"!=typeof e)return e;if(n.type===Ft.THOUGHT||"string"==typeof n.message&&(n.message.toLowerCase().includes("thinking about")||n.message.toLowerCase().includes("i'm thinking")||n.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})(x));l(e)}catch(e){console.error("Error processing message content:",e),l(x)}finally{u(!1)}}})()},[x,m]);const k=jr(n),C=(()=>{switch(n.type){case Ft.ANSWER:return"border-l-info bg-info";case Ft.COMPLETE:return"border-l-success bg-success";case Ft.IDLE:return"border-l-muted bg-muted";case Ft.REQUEST_INPUT:return"border-l-attention bg-attention";case Ft.QUESTION:return"border-l-muted bg-muted";case Ft.THOUGHT:return"border-l-accent dark:border-l-purple-500 bg-purple-50/50 dark:bg-purple-900/10";case Ft.ERROR:return"border-l-destructive bg-destructive";case Ft.UPDATE:return"border-l-success bg-success";case Ft.PLAN:return"border-l-attention bg-attention";case Ft.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 ${C}`,"data-workstream-id":k,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:r?"animate-fadeIn":"",children:(()=>{const t=(()=>{switch(n.type){case Ft.ANSWER:return"text-info";case Ft.COMPLETE:return"text-success";case Ft.IDLE:return"text-muted";case Ft.REQUEST_INPUT:return"text-attention";case Ft.QUESTION:return"text-muted";case Ft.THOUGHT:return"text-purple-600 dark:text-purple-400";case Ft.ERROR:return"text-destructive";case Ft.UPDATE:return"text-success";case Ft.PLAN:return"text-attention";default:return"text-muted"}})(),i=t=>("number"==typeof n.timestamp?n.timestamp:new Date(n.timestamp).getTime())%2==0?e(xr,{size:"sm",color:t}):e(vr,{color:t});switch(n.type){case Ft.ANSWER:return r?i("blue"):e(De,{className:`size-4 ${t}`});case Ft.COMPLETE:case Ft.TERMINATED:return e(Ue,{className:`size-4 ${t}`});case Ft.IDLE:return e(Me,{className:`size-4 ${t}`});case Ft.REQUEST_INPUT:case Ft.QUESTION:return e(Re,{className:`size-4 ${t}`});case Ft.THOUGHT:return r?i("purple"):e(De,{className:`size-4 ${t}`});case Ft.ERROR:return e(Oe,{className:`size-4 ${t}`});case Ft.UPDATE:return r?i("green"):e(Le,{className:`size-4 ${t}`});case Ft.PLAN:return r?i("amber"):e($e,{className:`size-4 ${t}`});default:return r?i("blue"):e(De,{className:`size-4 ${t}`})}})()}),e("span",{className:"text-xs font-medium text-muted ",children:p.sender}),"main"!==k&&"all"!==k&&e(b,{variant:"default",className:"text-xs text-muted",children:k})]}),t("div",{className:"flex items-center gap-2 print:hidden",children:[e("span",{className:"text-xs text-muted",children:un(n.timestamp).format("HH:mm:ss")}),e(v,{variant:"ghost",size:"xs",onClick:()=>{const e=f()||"",t="string"==typeof n.details?n.details:n.details?JSON.stringify(n.details,null,2):"",r=[e,t?"\n\nDetails:\n"+t:""].join("").trim();navigator.clipboard.writeText(r).then(()=>{h({status:"success",title:"Copied to clipboard",duration:2e3})})},className:"text-muted",title:"Copy message",children:e(Fe,{className:"size-3"})})]})]}),t("div",{className:"px-4 py-3 bg-white dark:bg-gray-900",children:[x&&e("div",{className:"message-content",children:d?t("div",{className:"flex items-center gap-2 text-sm text-gray-500",children:[e(vr,{color:"blue"}),e("span",{children:"Loading images..."})]}):g(s||x)}),w.length>0&&t("div",{className:"mt-3 text-xs",children:[e("div",{className:"font-medium text-muted mb-1",children:"Artifacts"}),w.some(e=>e.isImage)&&e("div",{className:"mb-2 flex flex-wrap gap-3",children:w.filter(e=>e.isImage).map(({displayName:n,artifactPath:r,url:i})=>t("div",{className:"max-w-xs cursor-pointer",onClick:()=>window.open(i,"_blank"),children:[e("img",{src:i,alt:n,className:"max-w-full h-auto rounded-lg shadow-sm hover:shadow-md transition-shadow"}),e("div",{className:"mt-1 text-[11px] text-muted truncate",children:n})]},`${r}-preview`))}),e("div",{className:"flex flex-wrap gap-2 print:hidden",children:w.map(({displayName:t,artifactPath:n,url:r})=>e(v,{variant:"outline",size:"xs",className:"px-2 py-1 text-xs",onClick:()=>window.open(r,"_blank"),title:n,children:t},n+r))})]}),n.details&&t("div",{className:"mt-2 print:hidden",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 n.details?g(n.details):e("pre",{className:"text-xs font-mono whitespace-pre-wrap overflow-x-auto bg-muted p-2 rounded text-muted ",children:JSON.stringify(n.details,null,2)})})]})]})]})}function Tr({workstreams:n,activeWorkstream:r,onSelectWorkstream:i,count:a,completionStatus:s}){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:()=>i(n),title:l.length>20?l:void 0,children:[l.length>20?l.substring(0,18)+"...":l,a&&a.has(n)&&a.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:a.get(n)}),s&&"all"!==n&&(s.get(n)?e(Ue,{className:"size-3 text-success"}):e(Me,{className:"size-3 text-attention"}))]})]},n))}:{className:"py-1"})}function Ir(e,t){return"all"===t?[...e]:"main"===t?e.filter(e=>"main"===jr(e)):e.filter(e=>jr(e)===t)}const Ar=s.memo(function({messages:r,bottomRef:i,viewMode:a="stacked",isCompleted:d=!1}){const u=s.useRef(null),[m,h]=o("all");c(()=>{i.current&&i.current.scrollIntoView({behavior:"smooth"})},[r,i]);const p=s.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=s.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=s.useMemo(()=>{const e=new Map;e.set("all",p.length);const t=Ir(p,"main");return e.set("main",t.length),p.forEach(t=>{const n=jr(t);"main"!==n&&e.set(n,(e.get(n)||0)+1)}),e},[p]),y=s.useMemo(()=>"all"===m?p:Ir(p,m),[p,m]),b=l(()=>{const e=new Map,t=new Map;p.forEach(e=>{const n=jr(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,[Ft.COMPLETE,Ft.IDLE,Ft.REQUEST_INPUT,Ft.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(Tr,{workstreams:f,activeWorkstream:m,onSelectWorkstream:h,count:g,completionStatus:b})}),0===y.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"===a?y.map((t,n)=>{const r=!d&&n===y.length-1&&!Pr.includes(t.type);return e(_r,{message:t,showPulsatingCircle:r},`${t.timestamp}-${n}`)}):e(n,{children:(()=>{const t=y.filter(e=>e.type===Ft.ANSWER||e.type===Ft.QUESTION||e.type===Ft.COMPLETE||e.type===Ft.IDLE||e.type===Ft.REQUEST_INPUT||e.type===Ft.TERMINATED),n=d?null:y.filter(e=>e.type===Ft.THOUGHT||e.type===Ft.UPDATE||e.type===Ft.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 i=!d&&n===r.length-1&&!Pr.includes(t.type);return e(_r,{message:t,showPulsatingCircle:i},`${t.timestamp}-${n}`)})})()}),e("div",{ref:i,className:"h-4"})]})]})});class zr{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 zr(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?Dt.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,i=e.config?.model,a=await(r?this.vertesia.environments.retrieve(e.config?.environment):Promise.resolve(void 0));this.interactionParamsSchema=e.interactionParamsSchema??null,this.interaction=n,this._tool_names=e.tool_names||[],this._data=e.data,this._interactive=e.interactive,this._debug_mode=e.debug_mode??!1,this.collection=e.collection_id??void 0,this.environment=a,i&&(this._model=i),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&&Lt(t,e.provider)?this._model=t:this._model=e?.default_model&&Lt(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 mn({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 Er=d(void 0);function Fr({children:t}){const{client:n}=Et(),[r,i]=o();return c(()=>{i(new zr(n,i))},[]),r&&e(Er.Provider,{value:r,children:t})}function Dr(){const e=u(Er);if(!e)throw new Error("usePayloadBuilder must be used within a PayloadProvider");return e}function $r({title:n,onClose:r,isModal:i,run:a,viewMode:s,onViewModeChange:l,showPlanPanel:o,hasPlan:c=!1,onTogglePlanPanel:d,onDownload:u,onCopyRunId:m,resetWorkflow:h,onExportPdf:p}){return e(Fr,{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(De,{className:"size-5 text-muted"}),e("span",{className:"font-medium",children:n})]}),t("span",{className:"text-xs text-muted ml-1",children:["(Run ID: ",a.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(v,{variant:"stacked"===s?"outline":"ghost",size:"xs",className:"rounded-l-md",onClick:()=>l("stacked"),children:"Details"}),e(v,{variant:"sliding"===s?"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(v,{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(Lr,{run:a,isModal:i,onClose:r,onDownload:u,onCopyRunId:m,resetWorkflow:h,onExportPdf:p}),r&&!i&&e(v,{size:"xs",variant:"ghost",onClick:r,children:e(Ke,{className:"size-4"})})]})]})})}function Lr({run:n,isModal:r,onClose:i,onDownload:a,onCopyRunId:s,resetWorkflow:l,onExportPdf:o}){const c=y(),{client:d}=Et(),u=Dr();return t(x,{hover:!0,children:[e(w,{children:e(v,{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(S,{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(P,{className:"text-xs",onSelect:()=>{return e=`/store/agent-runner?agentId=${n.runId}__${n.workflowId}`,window.open(e,"_blank"),e;var e},children:[e(Be,{className:"size-3.5 mr-2 text-muted"})," Open in new tab"]}),t(P,{className:"text-xs",onSelect:()=>{s?s():(navigator.clipboard.writeText(n.runId),c({status:"success",title:"Run ID copied",duration:2e3}))},children:[e(Fe,{className:"size-3.5 mr-2 text-muted"})," Copy Run ID"]}),t(P,{className:"text-xs",onSelect:()=>{a?a():async function(e,t){return e.files.getDownloadUrl(`agents/${t}/conversation.json`).then(e=>e.url)}(d,n.runId).then(e=>window.open(e,"_blank"))},children:[e(We,{className:"size-3.5 mr-2 text-muted"})," Download Conversation"]}),o&&t(P,{className:"text-xs",onSelect:o,children:[e(We,{className:"size-3.5 mr-2 text-muted"})," Export as PDF"]}),i&&r&&t(P,{className:"text-xs",onSelect:i,children:[e(Ke,{className:"size-3.5 mr-2 text-muted"})," Close"]}),t(P,{className:"text-xs text-destructive",onSelect:()=>{(async e=>{try{return await d.store.workflows.terminate(e.workflowId,e.runId,"cancel"),c({status:"success",title:"Workflow cancelled",duration:2e3}),u.reset(),l?.(),!0}catch(e){return c({status:"error",title:"Failed to cancel workflow",duration:2e3}),!1}})(n)},children:[e(Ke,{className:"size-3.5 mr-2 text-destructive"})," Cancel Workflow"]})]})})})})})})]})}const Or="vertesia.content_store.lastDisplayedView";function Rr({onUpdate:t}){const[n,r]=o("grid"===localStorage.getItem(Or)),i=()=>{localStorage.setItem(Or,"grid"),r(!0),t(!0)},a=()=>{localStorage.setItem(Or,"table"),r(!1),t(!1)};return e(v,{variant:"outline",onClick:()=>{n?a():i()},alt:n?"Table View":"Thumbnail View",children:e(n?Ge:He,{})})}function Ur(e,t=7){return e?"~"+e.slice(-t):""}function Mr(e,t){return e.length>t?e.substring(0,t)+"...":e}Rr.LAST_DISPLAYED_VIEW=Or;const Vr="text/csv",Kr="image/",qr="application/pdf",Br="video/",Wr=["application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/msword","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.ms-powerpoint"],Gr=e=>e===Vr||Vr.includes(e),Hr=e=>e.startsWith(Kr)||Kr.includes(e),Jr=e=>e===qr||qr.includes(e),Yr=e=>e.startsWith(Br)||Br.includes(e),Zr=e=>Wr.includes(e),Qr=import.meta.env,Xr={max_hw:Qr?.VITE_RENDITION_HW||256,format:Ot.jpeg,generate_if_missing:!0},ei="vertesia.content_store.renditionId";async function ti(e,t,n,r,i){if(!t?.content?.type||!(Hr(t.content.type)||Yr(t.content.type)||Jr(t.content.type)))return void i("No preview available");i("Preparing preview...");const a=(new Date).getTime()/1e3,s=localStorage.getItem(`${ei}_${t.id}_${Xr.max_hw}`),l=localStorage.getItem(`${ei}_${t.id}_${Xr.max_hw}_time`);if(s?.length&&l&&Math.abs(a-parseInt(l))<=900)return n(s),r(`${t.name} Rendition`),i("ready"),s;i("Preparing preview..."),e.objects.getRendition(t.id,Xr).then(a=>{if("generating"===a.status)i("Preparing preview..."),n(""),r(""),setTimeout(()=>ti(e,t,n,r,i),6e4);else{if("failed"===a.status)return i("No preview available"),n(""),void r("");{if(!a?.renditions?.length)return i("No preview available"),n(""),void r("");const e=a.renditions[0];localStorage.setItem(`${ei}_${t.id}_${Xr.max_hw}`,e),localStorage.setItem(`${ei}_${t.id}_${Xr.max_hw}_time`,((new Date).getTime()/1e3).toString()),n(e),r(`${t.name} Rendition`),i("ready"),console.log(`Rendition for document ${t.id} retrieved successfully: ${e}`)}}}).catch(e=>{i("No preview available"),console.warn("Failed to retrieve rendition:",e),n(""),r("")})}function ni(e,t){if("undefined"==typeof window||"undefined"==typeof document)return!1;const n=document.createElement("iframe");n.style.position="fixed",n.style.right="0",n.style.bottom="0",n.style.width="0",n.style.height="0",n.style.border="0",n.style.visibility="hidden",document.body.appendChild(n);const r=n.contentWindow;if(!r)return n.parentNode?.removeChild(n),!1;const i=r.document;i.open(),i.write(`<!doctype html><html><head><title>${t}</title></head><body></body></html>`),i.close(),i.title=t;document.querySelectorAll('link[rel="stylesheet"], style').forEach(e=>{i.head.appendChild(e.cloneNode(!0))});const a=i.createElement("style");return a.textContent='\n@media print {\n body {\n margin: 24px;\n font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;\n font-size: 14px;\n line-height: 1.5;\n color: #111827;\n background-color: #ffffff;\n }\n\n .vprose {\n max-width: 800px;\n margin: 0 auto;\n }\n\n .vprose h1 {\n font-size: 24px;\n font-weight: 700;\n margin: 1.5rem 0 0.75rem;\n }\n\n .vprose h2 {\n font-size: 20px;\n font-weight: 600;\n margin: 1.25rem 0 0.75rem;\n }\n\n .vprose h3 {\n font-size: 18px;\n font-weight: 600;\n margin: 1rem 0 0.5rem;\n }\n\n .vprose p {\n margin: 0 0 0.5rem;\n }\n\n .vprose ul,\n .vprose ol {\n margin: 0.5rem 0 0.5rem 1.5rem;\n padding: 0;\n }\n\n .vprose li {\n margin: 0.25rem 0;\n }\n\n .vprose table {\n width: 100%;\n border-collapse: collapse;\n margin: 1rem 0;\n }\n\n .vprose th,\n .vprose td {\n border: 1px solid #d1d5db;\n padding: 0.5rem 0.75rem;\n vertical-align: top;\n }\n\n .vprose thead th {\n background-color: #f3f4f6;\n font-weight: 600;\n }\n\n .vprose pre,\n .vprose code {\n font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;\n font-size: 12px;\n }\n\n .vprose pre {\n padding: 0.75rem;\n border-radius: 4px;\n border: 1px solid #e5e7eb;\n background-color: #f9fafb;\n white-space: pre-wrap;\n word-break: break-word;\n }\n\n /* Hide chart action buttons when printing */\n .chart-actions {\n display: none !important;\n }\n\n /* Hide interactive elements in agent conversation when printing */\n .print-hidden,\n [class*="print:hidden"],\n button[title="Copy message"],\n button[title="Copy to clipboard"],\n button[title="Export as PNG"],\n .message-actions {\n display: none !important;\n }\n\n /* Prevent page breaks inside elements */\n .vprose table,\n .vprose pre,\n .vprose blockquote,\n .vprose figure,\n .vprose img,\n .recharts-wrapper,\n [class*="chart"],\n [class*="Chart"] {\n break-inside: avoid;\n page-break-inside: avoid;\n }\n\n /* Keep headings with following content */\n .vprose h1,\n .vprose h2,\n .vprose h3,\n .vprose h4,\n .vprose h5,\n .vprose h6 {\n break-after: avoid;\n page-break-after: avoid;\n }\n\n /* Keep list items together when possible */\n .vprose li {\n break-inside: avoid;\n page-break-inside: avoid;\n }\n}\n',i.head.appendChild(a),i.body.innerHTML=e.innerHTML,r.focus(),r.print(),setTimeout(()=>{n.parentNode?.removeChild(n)},1e3),!0}function ri(e){switch(e){case Rt.RUNNING:return"text-info";case Rt.COMPLETED:return"text-success";case Rt.FAILED:return"text-destructive";case Rt.TERMINATED:case Rt.CANCELED:return"text-attention";default:return"text-muted"}}function ii(e){switch(e){case Rt.RUNNING:return"Running";case Rt.COMPLETED:return"Completed";case Rt.FAILED:return"Failed";case Rt.CONTINUED_AS_NEW:return"Continued As New";case Rt.TERMINATED:return"Terminated";case Rt.TIMED_OUT:return"Timed Out";case Rt.CANCELED:return"Canceled";default:return"Unknown"}}class ai extends F{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 si({isOpen:n,onClose:r,onConfirm:i,isLoading:a,uploadedFileName:s}){const l=[{id:"update",label:"Update current version",description:s?"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:s?"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=s?l[1]:l[0],[u,m]=o(d),[h,p]=o(""),f=new ai;c(()=>{n&&(m(d),p(""))},[n,s]);const g="new-version"===u?.id;return t(j,{isOpen:n,onClose:r,className:"sm:max-w-md",children:[e(_,{children:"Save Changes"}),e(T,{children:t("div",{className:"space-y-4",children:[s&&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:s})]})}),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(z,{value:h,onChange:p,placeholder:"e.g., v1.2, approved, post-review",className:"w-full"})})]})}),t(E,{children:[e(v,{variant:"secondary",onClick:r,disabled:a,children:"Cancel"}),e(v,{variant:"primary",onClick:async()=>{await i(g,g?h:void 0)},isLoading:a,children:"Save"})]})]})}function li({isOpen:r,onClose:i,object:a,refetch:s}){const{client:l,store:d}=Et(),u=y(),h=Yt(),[p,f]=o(!1),[g,b]=o(""),[x,w]=o(!1),[N,k]=o(null),C=m(null),S=m(null),[P,I]=o(null),[A,z]=o(null);function F(e,t){e.languages.json.jsonDefaults.setDiagnosticsOptions({validate:!0,schemas:[{uri:"http://myserver/object-schema.json",fileMatch:["*"],schema:t}]})}return c(()=>{r&&(b(JSON.stringify(a.properties||{},null,2)),a.type?.id&&async function(e){try{const t=await d.types.retrieve(e);t.object_schema&&(I(t.object_schema),S.current&&F(S.current,t.object_schema))}catch(e){console.error("Failed to fetch JSON schema:",e)}}(a.type.id))},[r,a]),t(n,{children:[t(j,{isOpen:r,onClose:i,className:"sm:max-w-[90%] md:max-w-[80%] lg:max-w-[75%] xl:max-w-[70%]",children:[e(_,{children:"Edit Properties"}),t(T,{children:[t("div",{className:"mb-2 text-sm text-gray-500",children:[a.type?.name?t("span",{children:["Editing properties for object type: ",e("strong",{children:a.type.name})]}):e("span",{children:"Editing properties for generic document"}),P&&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(pn,{height:"100%",language:"json",value:g,onChange:e=>b(e||""),onMount:function(e,t){C.current=e,S.current=t,P&&F(t,P)},options:{minimap:{enabled:!1},scrollBeyondLastLine:!1,formatOnPaste:!0,formatOnType:!0,automaticLayout:!0,wordWrap:"on"}})})]}),t(E,{children:[e(v,{variant:"secondary",onClick:i,children:"Cancel"}),e(v,{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(si,{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(a.id,{properties:n},{createRevision:!0,revisionLabel:t});e.id!==a.id&&z(e.id),u({status:"success",title:"New version created",description:"A new version with updated properties has been created.",duration:2e3}),w(!1),i(),e.id!==a.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(a.id,{properties:n}),u({status:"success",title:"Properties updated",description:"The object properties have been updated successfully.",duration:2e3}),s&&await s(),w(!1),i()}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})]})}function oi({className:t,size:n="md"}){return e("div",{className:`flex items-center justify-center ${t||""}`,children:e(Je,{className:`${{sm:"w-4 h-4",md:"w-6 h-6",lg:"w-8 h-8"}[n]} animate-spin text-muted-foreground`})})}function ci({pdfUrl:n,pageNumber:r,width:i,className:a,renderTextLayer:s=!1,renderAnnotationLayer:l=!1,onLoadSuccess:c,onError:d}){const[u,m]=o(!0),[h,p]=o(null);return h?e("div",{className:`flex items-center justify-center text-destructive text-sm ${a||""}`,children:"Failed to load PDF"}):t("div",{className:a,children:[u&&e(oi,{className:"py-4",size:"md"}),e(gn,{file:n,onLoadSuccess:({numPages:e})=>{m(!1),c?.(e)},onLoadError:e=>{m(!1),p(e),d?.(e)},loading:null,children:e(yn,{pageNumber:r,width:i,renderTextLayer:s,renderAnnotationLayer:l,loading:e(oi,{className:"py-4",size:"sm"})})})]})}fn.GlobalWorkerOptions.workerSrc=`//unpkg.com/pdfjs-dist@${fn.version}/build/pdf.worker.min.mjs`;const di=d(null);function ui({pdfUrl:t,urlLoading:n=!1,children:r,onLoadSuccess:i}){const[a,s]=o(0),[l,c]=o(!0),[d,u]=o(null),[m,h]=o(null),p={pdfUrl:t,numPages:a,loading:n||!t||l,error:d,pageDimensions:m};return d?e("div",{className:"flex items-center justify-center text-destructive text-sm py-4",children:"Failed to load PDF"}):e(di.Provider,{value:p,children:t?e(gn,{file:t,onLoadSuccess:async e=>{s(e.numPages),i?.(e.numPages);try{const t=(await e.getPage(1)).getViewport({scale:1});h({width:t.width,height:t.height,aspectRatio:t.width/t.height})}catch(e){console.error("Failed to get page dimensions:",e)}c(!1)},onLoadError:e=>{c(!1),u(e)},loading:e(oi,{className:"py-4",size:"md"}),children:r((t,n)=>e(yn,{pageNumber:t,width:n,renderTextLayer:!1,renderAnnotationLayer:!1,loading:e(oi,{className:"py-4",size:"sm"})},t))}):e(oi,{className:"py-4",size:"md"})})}function mi(){return u(di)}const hi=210/297;function pi({pageNumber:t,width:n,className:r}){const i=mi(),a=i?.pageDimensions?.aspectRatio??hi,s=n?Math.round(n/a):200;return e("div",i?.loading?{className:`flex items-center justify-center bg-muted ${r||""}`,style:{height:s,width:n||"100%"},children:e(oi,{size:"md"})}:{className:r,children:e(yn,{pageNumber:t,width:n,renderTextLayer:!1,renderAnnotationLayer:!1,loading:e(oi,{className:"py-4",size:"sm"})})})}function fi({pageNumber:t,width:n,isSelected:r,onSelect:i,renderThumbnail:a,aspectRatio:s=hi,rootMargin:l="200px 0px"}){const d=m(null),[u,h]=o(!1);c(()=>{const e=d.current;if(!e)return;const t=new IntersectionObserver(e=>{const t=e[0];t?.isIntersecting&&h(!0)},{rootMargin:l,threshold:0});return t.observe(e),()=>t.disconnect()},[l]);const p=n?Math.round(n/s):200,f=u?e(yn,{pageNumber:t,width:n,renderTextLayer:!1,renderAnnotationLayer:!1,loading:e("div",{className:"flex items-center justify-center bg-muted",style:{height:p},children:e(oi,{size:"sm"})})}):e("div",{className:"flex items-center justify-center bg-muted",style:{height:p,width:n||"100%"},children:e("span",{className:"text-muted-foreground text-xs",children:t})});return e("div",{ref:d,children:a({pageNumber:t,isSelected:r,pageElement:f,onSelect:i})})}function gi({pdfUrl:r,urlLoading:i=!1,pageCount:a,currentPage:s,thumbnailWidth:l,onPageSelect:d,renderThumbnail:u,scrollContainerRef:p,onAspectRatioChange:f,onItemHeightChange:g,calculateItemHeight:y,onPageCountChange:b}){const[v,x]=o(null),[w,N]=o({start:0,end:Math.min(15,a)}),[k,C]=o(null),S=m(null),P=h(e=>{x(e)},[]),j=h(async e=>{b?.(e.numPages);try{const t=(await e.getPage(1)).getViewport({scale:1}),n=t.width/t.height;C(n),f?.(n)}catch(e){console.error("Failed to get page dimensions:",e),C(hi),f?.(hi)}},[f,b]),_=k??hi,T=l?Math.round(l/_):200,I=y?y(T):T+16+24+8;c(()=>{I>0&&null!==k&&g?.(I)},[I,k,g]);if(c(()=>{const e=p?.current||function(e){if(!e)return null;let t=e.parentElement;for(;t;){const e=window.getComputedStyle(t).overflowY;if("auto"===e||"scroll"===e)return t;t=t.parentElement}return null}(S.current);if(!e)return;const t=()=>{const t=e.scrollTop,n=e.clientHeight,r=Math.floor(t/I),i=Math.ceil((t+n)/I),s=Math.max(0,r-5),l=Math.min(a,i+5);N(e=>e.start!==s||e.end!==l?{start:s,end:l}:e)};return t(),e.addEventListener("scroll",t,{passive:!0}),()=>e.removeEventListener("scroll",t)},[I,a,p]),v)return e("div",{className:"flex items-center justify-center text-destructive text-sm py-4",children:"Failed to load PDF"});if(i||!r)return e(oi,{className:"py-4",size:"md"});const A=w.start*I,z=(a-w.end)*I,E=null!==k;return e("div",{ref:S,children:e(gn,{file:r,onLoadSuccess:j,onLoadError:P,loading:e(oi,{className:"py-4",size:"md"}),children:E?t(n,{children:[A>0&&e("div",{style:{height:A}}),Array.from({length:w.end-w.start},(t,n)=>{const r=w.start+n+1;return e("div",{"data-page-index":r-1,style:{height:I,overflow:"hidden"},children:e(fi,{pageNumber:r,width:l,isSelected:r===s,onSelect:()=>d(r),renderThumbnail:u,aspectRatio:_})},r)}),z>0&&e("div",{style:{height:z}})]}):e(oi,{className:"py-4",size:"md"})})})}function yi({pdfUrl:n,pageNumber:r,width:i,height:a,className:s,renderTextLayer:l=!1,renderAnnotationLayer:d=!1,onPageChange:u}){const[m,h]=o(0),[p,f]=o(!0),[g,y]=o(null);c(()=>{m>0&&u?.(r,m)},[r,m,u]);return g?e("div",{className:`flex items-center justify-center text-destructive ${s||""}`,children:t("span",{children:["Failed to load PDF: ",g.message]})}):t("div",{className:s,children:[p&&e(oi,{className:"py-8",size:"lg"}),e(gn,{file:n,onLoadSuccess:({numPages:e})=>{h(e),f(!1)},onLoadError:e=>{f(!1),y(e)},loading:null,children:e(yn,{pageNumber:Math.min(r,m||1),width:i,height:a,renderTextLayer:l,renderAnnotationLayer:d,loading:e(oi,{className:"py-8",size:"md"})})})]})}const bi=210/297,vi=[50,75,100,125,150,200,300];function xi({pdfUrl:i,pdfUrlLoading:a=!1,pageCount:s,currentPage:l,onChange:d,onPageCountChange:u,className:p,compact:f=!1,headerExtra:g}){const y=m(null),b=m(null),[x,w]=o(void 0),[N,k]=o(100),[C,S]=o(bi),[P,j]=o(null),_=m(null),T=x?Math.round(x*N/100):void 0,I=h(()=>{let e=vi.findIndex(e=>e>=N);-1===e&&(e=vi.length-1);const t=Math.min(e+1,vi.length-1);k(vi[t])},[N]),A=h(()=>{let e=vi.findIndex(e=>e>=N);-1===e&&(e=vi.length-1);const t=Math.max(e-1,0);k(vi[t])},[N]),z=h(()=>{k(100)},[]),E=h(e=>e+(f?28:48),[f]),F=(e,t)=>{const n=e?Math.round(e/t):200;return E(n)};c(()=>{const e=b.current;if(!e)return;let t=null;const n=()=>e.clientWidth-16-16-4,r=()=>{const t=n();if(t<=0)return;const r=_.current;if(r&&r>0){const n=e.scrollTop,i=Math.round(n/r),a=F(t,C),s=i*a;w(t),requestAnimationFrame(()=>{e.scrollTo({top:s,behavior:"instant"})}),_.current=a}else w(t),_.current=F(t,C)},i=n();i>0&&(w(i),_.current=F(i,C));const a=new ResizeObserver(()=>{t&&clearTimeout(t),t=setTimeout(r,150)});return a.observe(e),()=>{t&&clearTimeout(t),a.disconnect()}},[C]);const $=m(!1),L=m(null),O=m(N);c(()=>{O.current!==N&&(O.current=N,L.current={targetPage:l},$.current=!0)},[N,l]),c(()=>{const e=b.current,t=L.current;if(t&&e&&P){L.current=null;const n=(t.targetPage-1)*P;requestAnimationFrame(()=>{e.scrollTo({top:n,behavior:"instant"}),requestAnimationFrame(()=>{$.current=!1})})}},[P]);const R=m(!1);c(()=>{const e=b.current;if(e&&P&&!R.current)if(l>1){R.current=!0,$.current=!0;const t=(l-1)*P;e.scrollTo({top:t,behavior:"instant"}),requestAnimationFrame(()=>{$.current=!1})}else R.current=!0},[P,l]);const U=m(l);c(()=>{const e=b.current;if(e&&P&&U.current!==l){U.current=l,$.current=!0;const t=(l-1)*P;e.scrollTo({top:t,behavior:"instant"}),requestAnimationFrame(()=>{$.current=!1})}},[l,P]),c(()=>{const e=b.current;if(!e||!P)return;let t=null;const n=()=>{$.current||(t&&clearTimeout(t),t=setTimeout(()=>{const t=e.scrollTop,n=Math.round(t/P)+1,r=Math.max(1,Math.min(n,s));r!==l&&(U.current=r,d(r))},50))};return e.addEventListener("scroll",n,{passive:!0}),()=>{t&&clearTimeout(t),e.removeEventListener("scroll",n)}},[P,s,l,d]);return t("div",{ref:y,className:r("flex flex-col items-stretch",f?"gap-y-1":"gap-y-2",p),children:[t("div",{className:r("relative flex items-center justify-center px-2",f?"h-6":"h-9"),children:[e(v,{variant:"ghost",size:"xs",onClick:()=>{l>1&&d(l-1)},alt:"Previous page",children:e(Ye,{className:"size-4"})}),t("div",{className:"absolute left-2 flex items-center gap-x-1",children:[e(Ni,{zoom:N,onZoomIn:I,onZoomOut:A,onFitToView:z,canZoomIn:N<vi[vi.length-1],canZoomOut:N>vi[0]}),g&&t(n,{children:[e("div",{className:"w-px h-4 bg-border mx-1"}),g]})]}),e("div",{className:"absolute right-2",children:e(wi,{currentPage:l,totalPages:s,onChange:d})})]}),e("div",{ref:b,className:r("flex flex-col items-center flex-1 overflow-y-auto px-2",f?"gap-1":"gap-2"),children:e(gi,{pdfUrl:i,urlLoading:a,pageCount:s,currentPage:l,thumbnailWidth:T,onPageSelect:d,onPageCountChange:u,scrollContainerRef:b,onAspectRatioChange:S,onItemHeightChange:j,calculateItemHeight:E,renderThumbnail:({pageNumber:n,isSelected:i,pageElement:a,onSelect:s})=>t("div",{className:r("hover:bg-muted rounded-md w-full",f?"p-1":"p-2"),children:[e("div",{className:r("relative border-[2px] cursor-pointer overflow-hidden",i?"border-primary":"border-border"),onClick:s,children:a}),e(D,{className:r("text-muted-foreground font-semibold",f?"text-xs pt-0.5":"text-sm pt-1"),children:n})]},n)})}),e("div",{className:r("flex items-center justify-center",f?"h-6":"h-9"),children:e(v,{variant:"ghost",size:"xs",onClick:()=>{l<s&&d(l+1)},alt:"Next page",children:e(Ze,{className:"size-4"})})})]})}function wi({currentPage:n,totalPages:r,onChange:i}){const a=m(null),[s,l]=o(String(n));c(()=>{l(String(n))},[n]);const d=()=>{const e=parseInt(s,10);!isNaN(e)&&e>=1&&e<=r?i(e):l(String(n))};return t("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e("span",{children:"Page"}),e("input",{ref:a,type:"text",value:s,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"===e.key?(d(),a.current?.blur()):"Escape"===e.key&&(l(String(n)),a.current?.blur())},onBlur:()=>{d()},className:"w-8 h-5 text-center text-xs px-1 py-0 bg-background border border-border rounded focus:outline-none focus:border-primary"}),t("span",{children:["/ ",r]})]})}function Ni({zoom:n,onZoomIn:i,onZoomOut:a,onFitToView:s,canZoomIn:l,canZoomOut:o}){return t("div",{className:"flex items-center gap-x-0.5",children:[e($,{description:"Zoom out",placement:"bottom",size:"xs",children:e("button",{className:r("p-1 rounded cursor-pointer transition-colors",o?"text-muted-foreground hover:text-foreground hover:bg-muted":"text-muted-foreground/40 cursor-not-allowed"),onClick:a,disabled:!o,children:e(Qe,{className:"size-4"})})}),t("span",{className:"text-xs text-muted-foreground min-w-[32px] text-center",children:[n,"%"]}),e($,{description:"Zoom in",placement:"bottom",size:"xs",children:e("button",{className:r("p-1 rounded cursor-pointer transition-colors",l?"text-muted-foreground hover:text-foreground hover:bg-muted":"text-muted-foreground/40 cursor-not-allowed"),onClick:i,disabled:!l,children:e(Xe,{className:"size-4"})})}),e($,{description:"Fit to width",placement:"bottom",size:"xs",children:e("button",{className:r("p-1 rounded cursor-pointer transition-colors",100!==n?"text-muted-foreground hover:text-foreground hover:bg-muted":"text-muted-foreground/40"),onClick:s,children:e(et,{className:"size-4"})})})]})}const ki="magic-pdf";var Ci;!function(e){e.original="original",e.instrumented="instrumented"}(Ci||(Ci={}));class Si{client;objectId;totalPages;cache=new Map;pending=new Map;constructor(e,t,n){this.client=e,this.objectId=t,this.totalPages=n}getCacheKey(e,t){return`${t}-${e}`}async getPageImageUrl(e,t){const n=this.getCacheKey(e,t),r=this.cache.get(n);if(r)return r;const i=this.pending.get(n);if(i)return i;const a=this.fetchImageUrl(e,t);this.pending.set(n,a);try{const e=await a;return this.cache.set(n,e),e}finally{this.pending.delete(n)}}async fetchImageUrl(e,t){const n=this.getImagePath(e,t);return(await this.client.files.getDownloadUrl(n)).url}getImagePath(e,t){const n=`${ki}/${this.objectId}/pages`;switch(t){case Ci.original:return`${n}/page-${e}.original.jpg`;case Ci.instrumented:return`${n}/page-${e}.instrumented.jpg`}}}class Pi{client;objectId;totalPages;cache=new Map;pending=new Map;constructor(e,t,n){this.client=e,this.objectId=t,this.totalPages=n}async getPageLayout(e){const t=this.cache.get(e);if(void 0!==t)return t;const n=this.pending.get(e);if(n)return n;const r=this.fetchPageLayout(e);this.pending.set(e,r);try{const t=await r;return this.cache.set(e,t),t}finally{this.pending.delete(e)}}async fetchPageLayout(e){const t=`${ki}/${this.objectId}/pages/page-${e}.layout.json`,n=await this.client.files.getDownloadUrl(t),r=await fetch(n.url,{method:"GET"});if(!r.ok)throw new Error("Failed to fetch json layout: "+r.statusText);return r.text()}}class ji{totalPages;pages=[];constructor(e){this.totalPages=e}initFromContent(e){this.pages=function(e,t){const n=new Array(t).fill(""),r=/<!--\s*\{\s*"page"\s*:\s*(\d+)\s*\}\s*-->/g,i=[];let a;for(;null!==(a=r.exec(e));)i.push({page:parseInt(a[1],10),index:a.index+a[0].length});for(let r=0;r<i.length;r++){const a=i[r],s=a.page-1;if(s<0||s>=t)continue;const l=a.index,o=e.slice(l).match(/<!--\s*\{\s*"page"\s*:\s*\d+\s*\}\s*-->/),c=o?l+o.index:e.length;let d=e.slice(l,c).trim();d=d.replace(/\n---\s*$/,"").trim(),n[s]=d}return n}(e,this.totalPages)}async loadUrls(e,t){}async getPageMarkdown(e){const t=e-1;return t<0||t>=this.pages.length?"":this.pages[t]}}const _i=d(void 0);function Ti({children:t,object:n}){const{client:r}=Et(),i=n.metadata.page_count||10,a="markdown"===n.metadata?.content_processor?.type,[s,l]=o(()=>{const e=new ji(i);a&&n.text&&e.initFromContent(n.text);const t=n.text?zi(n.text):"";return{count:i,layoutProvider:new Pi(r,n.id,i),markdownProvider:e,imageProvider:new Si(r,n.id,i),xml:t,xmlPages:n.text?Ai(t):[],pdfUrl:"",pdfUrlLoading:!0}});return c(()=>{if(a){const e=n.metadata,t=e?.renditions?.find(e=>e.name===Ut),i="application/pdf"===n.content?.type,a=t?.content?.source||(i?n.content?.source:void 0);a?r.store.objects.getDownloadUrl(a,void 0,"inline").then(e=>{l(t=>({...t,pdfUrl:e.url,pdfUrlLoading:!1}))}).catch(e=>{console.warn("Failed to get PDF URL:",e),l(e=>({...e,pdfUrlLoading:!1}))}):l(e=>({...e,pdfUrlLoading:!1}))}else l(e=>({...e,pdfUrlLoading:!1}))},[n.id,r,a,i]),e(_i.Provider,{value:s,children:t})}function Ii(){const e=s.useContext(_i);if(!e)throw new Error("useMagicPdfContext must be used within a MagicPdfProvider");return e}function Ai(e){const t=(new DOMParser).parseFromString(zi(e),"text/xml").getElementsByTagName("page"),n=new XMLSerializer;return Array.from(t).map(e=>n.serializeToString(e))}function zi(e){return e.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,"").replace(/<\?xml.*?\?>/g,"")}const Ei=[50,75,100,125,150,200,300],Fi=11/8.5;function Di({className:n,currentPage:i,onChange:a}){const[s,l]=o(Ci.instrumented),[d,u]=o(Fi),[p,f]=o(new Map),[g,y]=o(100),b=m(new Set),x=m(null),w=m(null),N=m(!1),{imageProvider:k,count:C}=Ii(),S=h(()=>{let e=Ei.findIndex(e=>e>=g);-1===e&&(e=Ei.length-1);const t=Math.min(e+1,Ei.length-1);y(Ei[t])},[g]),P=h(()=>{let e=Ei.findIndex(e=>e>=g);-1===e&&(e=Ei.length-1);const t=Math.max(e-1,0);y(Ei[t])},[g]),j=h(()=>{y(100)},[]);c(()=>{k.getPageImageUrl(1,s).then(e=>{const t=new window.Image;t.onload=()=>{t.width>0&&t.height>0&&u(t.height/t.width)},t.src=e}).catch(()=>{})},[k,s]);const _=m(s);c(()=>{let e=!1;_.current!==s&&(_.current=s,b.current=new Set,f(new Map));const t=function(e,t){const n=[e];let r=1;for(;n.length<t;){const i=e+r,a=e-r;i<=t&&n.push(i),a>=1&&n.push(a),r++}return n}(i,C);return t.forEach(t=>(async t=>{if(!e&&!b.current.has(t))try{const n=await k.getPageImageUrl(t,s);e||(b.current.add(t),f(e=>new Map(e).set(t,n)))}catch{}})(t)),()=>{e=!0}},[i,C,s,k]);const T=m(g);c(()=>{if(T.current!==g&&w.current){T.current=g,N.current=!0;const e=w.current.querySelector(`[data-page="${i}"]`);e?requestAnimationFrame(()=>{e.scrollIntoView({behavior:"instant",block:"center"}),requestAnimationFrame(()=>{N.current=!1})}):N.current=!1}},[g,i]);const I=m(i);c(()=>{if(I.current!==i&&w.current){I.current=i,N.current=!0;const e=w.current.querySelector(`[data-page="${i}"]`);e&&e.scrollIntoView({behavior:"instant",block:"nearest"}),requestAnimationFrame(()=>{N.current=!1})}},[i]),c(()=>{const e=w.current;if(!e)return;let t=null;const n=()=>{N.current||(t&&clearTimeout(t),t=setTimeout(()=>{const t=e.getBoundingClientRect(),n=t.top+t.height/2;let r=i,s=1/0;for(let t=1;t<=C;t++){const i=e.querySelector(`[data-page="${t}"]`);if(i){const e=i.getBoundingClientRect(),a=e.top+e.height/2,l=Math.abs(a-n);l<s&&(s=l,r=t)}}r!==i&&(I.current=r,a(r))},50))};return e.addEventListener("scroll",n,{passive:!0}),()=>{t&&clearTimeout(t),e.removeEventListener("scroll",n)}},[C,i,a]);return t("div",{ref:x,className:r("flex flex-col items-stretch gap-y-2",n),children:[t("div",{className:"relative flex items-center justify-center px-2 h-9",children:[e(v,{variant:"ghost",size:"xs",onClick:()=>{i>1&&a(i-1)},alt:"Previous page",children:e(Ye,{className:"size-4"})}),t("div",{className:"absolute left-2 flex items-center gap-x-1",children:[e($i,{type:Ci.original,currentType:s,onClick:()=>l(Ci.original),icon:e(tt,{className:"size-4"}),tooltip:"Original images"}),e($i,{type:Ci.instrumented,currentType:s,onClick:()=>l(Ci.instrumented),icon:e(nt,{className:"size-4"}),tooltip:"Instrumented images"}),e("div",{className:"w-px h-4 bg-border mx-1"}),e(Li,{zoom:g,onZoomIn:S,onZoomOut:P,onFitToView:j,canZoomIn:g<Ei[Ei.length-1],canZoomOut:g>Ei[0]})]}),e("div",{className:"absolute right-2",children:e(Ri,{currentPage:i,totalPages:C,onChange:a})})]}),e("div",{ref:w,className:"flex flex-col items-center gap-2 flex-1 overflow-y-auto px-2",children:Array.from({length:C},(t,n)=>e(Oi,{currentPage:i,pageNumber:n+1,aspectRatio:d,zoom:g,url:p.get(n+1),onSelect:()=>a(n+1)},n))}),e("div",{className:"flex items-center justify-center h-9",children:e(v,{variant:"ghost",size:"xs",onClick:()=>{i<C&&a(i+1)},alt:"Next page",children:e(Ze,{className:"size-4"})})})]})}function $i({type:t,currentType:n,onClick:i,icon:a,tooltip:s}){return e($,{description:s,placement:"bottom",size:"xs",children:e("button",{className:r("p-1 rounded cursor-pointer transition-colors",t===n?"text-primary bg-primary/10":"text-muted-foreground hover:text-foreground hover:bg-muted"),onClick:i,children:a})})}function Li({zoom:n,onZoomIn:i,onZoomOut:a,onFitToView:s,canZoomIn:l,canZoomOut:o}){return t("div",{className:"flex items-center gap-x-0.5",children:[e($,{description:"Zoom out",placement:"bottom",size:"xs",children:e("button",{className:r("p-1 rounded cursor-pointer transition-colors",o?"text-muted-foreground hover:text-foreground hover:bg-muted":"text-muted-foreground/40 cursor-not-allowed"),onClick:a,disabled:!o,children:e(Qe,{className:"size-4"})})}),t("span",{className:"text-xs text-muted-foreground min-w-[32px] text-center",children:[n,"%"]}),e($,{description:"Zoom in",placement:"bottom",size:"xs",children:e("button",{className:r("p-1 rounded cursor-pointer transition-colors",l?"text-muted-foreground hover:text-foreground hover:bg-muted":"text-muted-foreground/40 cursor-not-allowed"),onClick:i,disabled:!l,children:e(Xe,{className:"size-4"})})}),e($,{description:"Fit to width",placement:"bottom",size:"xs",children:e("button",{className:r("p-1 rounded cursor-pointer transition-colors",100!==n?"text-muted-foreground hover:text-foreground hover:bg-muted":"text-muted-foreground/40"),onClick:s,children:e(et,{className:"size-4"})})})]})}function Oi({pageNumber:n,currentPage:i,aspectRatio:a,zoom:s,url:l,onSelect:o}){return t("div",{className:"p-2 hover:bg-muted rounded-md flex flex-col items-center","data-page":n,style:{width:`${s}%`},children:[e("div",{className:r("relative border-[2px] cursor-pointer overflow-hidden flex items-center justify-center bg-muted/50 w-full",n===i?"border-primary":"border-border"),style:{aspectRatio:`1 / ${a}`},onClick:o,children:l?e("img",{src:l,alt:`Page ${n}`,className:"w-full"}):e(Je,{className:"w-6 h-6 animate-spin text-muted-foreground"})}),e(D,{className:"text-sm text-muted-foreground pt-1 font-semibold",children:n})]})}function Ri({currentPage:n,totalPages:r,onChange:i}){const a=m(null),[s,l]=o(String(n));c(()=>{l(String(n))},[n]);const d=()=>{const e=parseInt(s,10);!isNaN(e)&&e>=1&&e<=r?i(e):l(String(n))};return t("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e("span",{children:"Page"}),e("input",{ref:a,type:"text",value:s,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"===e.key?(d(),a.current?.blur()):"Escape"===e.key&&(l(String(n)),a.current?.blur())},onBlur:()=>{d()},className:"w-8 h-5 text-center text-xs px-1 py-0 bg-background border border-border rounded focus:outline-none focus:border-primary"}),t("span",{children:["/ ",r]})]})}function Ui({object:n}){const{client:r}=Et(),i=e=>{(function(e,t,n){return e.files.getDownloadUrl(`${ki}/${t}/${n}`).then(e=>e.url)})(r,n.id,e).then(e=>window.open(e,"_blank"))},a="p-2 cursor-pointer hover:bg-muted text-left text-sm";return"markdown"===(()=>{if("document"===n.metadata?.type){const e=n.metadata;return e.content_processor?.type||"xml"}return"xml"})()?e(v,{variant:"ghost",size:"xs",onClick:()=>i("document.md"),alt:"Download",children:e(rt,{className:"size-4"})}):t(Qt,{strategy:"absolute",placement:"bottom-start",zIndex:100,offset:8,children:[e(Qt.Trigger,{click:!0,children:e(v,{variant:"ghost",size:"xs",alt:"Download",children:e(rt,{className:"size-4"})})}),e(Qt.Content,{children:t("div",{className:"rounded-md shadow-md border border-border bg-popover min-w-[200px] flex flex-col divide-y divide-border",children:[e("button",{className:a,onClick:()=>i("annotated.pdf"),children:"annotated.pdf"}),e("button",{className:a,onClick:()=>i("document.xml"),children:"document.xml"}),e("button",{className:a,onClick:()=>i("analyzed-pages.json"),children:"analyzed-pages.json"})]})})]})}function Mi({className:t}){return e("div",{className:`flex items-center justify-center ${t||""}`,children:e(Je,{className:"w-6 h-6 animate-spin text-gray-400"})})}function Vi({viewType:t,pageNumber:n}){switch(t){case"json":return e(qi,{pageNumber:n});case"markdown":return e(Bi,{pageNumber:n});default:return e(Ki,{pageNumber:n})}}function Ki({pageNumber:t}){const{xmlPages:n}=Ii();return e("div",{className:"px-4 py-2",children:e(Xt,{xml:n[t-1],collapsible:!0})})}function qi({pageNumber:t}){const[n,r]=o(null),[i,a]=o(!0),[s,l]=o(null),{layoutProvider:d}=Ii();return c(()=>{a(!0),l(null),d.getPageLayout(t).then(e=>{r(e?JSON.parse(e):null),a(!1)}).catch(e=>{console.error(e),l(e.message||"Failed to load layout"),a(!1)})},[t,d]),i?e("div",{className:"px-4 py-8",children:e(Mi,{})}):s?e("div",{className:"px-4 py-2 text-red-500 text-sm",children:s}):n?e(en,{className:"w-full",data:n}):null}function Bi({pageNumber:n}){const[r,i]=o(null),[a,s]=o(!0),[l,d]=o(null),{markdownProvider:u}=Ii();return c(()=>{s(!0),d(null),u.getPageMarkdown(n).then(e=>{i(e),s(!1)}).catch(e=>{console.error(e),d(e.message||"Failed to load markdown"),s(!1)})},[n,u]),a?t("div",{className:"h-full flex flex-col items-center justify-center gap-2",children:[e(Mi,{}),e("span",{className:"text-sm text-muted-foreground",children:"Loading..."})]}):e("div",l?{className:"px-4 py-2 text-red-500 text-sm",children:l}:{className:"px-4 py-2 prose prose-sm max-w-none dark:prose-invert",children:r?e(Zt,{children:r}):e("div",{children:"No markdown content available"})})}class Wi extends p{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){console.error("PDF View error:",e,t)}render(){return this.state.hasError?e("div",{className:"fixed inset-0 bg-background z-50 flex items-center justify-center",children:t("div",{className:"flex flex-col items-center gap-4 p-8 max-w-md",children:[e(O,{title:"Failed to load PDF viewer",children:this.state.error?.message||"An unexpected error occurred"}),this.props.onClose&&e(v,{variant:"outline",onClick:this.props.onClose,children:"Close"})]})}):this.props.children}}function Gi({objectId:n,onClose:r}){const{client:i}=Et(),{data:a,error:s}=L(()=>i.store.objects.retrieve(n,"+text"),[n]);return s?e("div",{className:"fixed inset-0 bg-background z-50 flex items-center justify-center",children:t("div",{className:"flex flex-col items-center gap-4 p-8 max-w-md",children:[e(O,{title:"Fetching document failed",children:s.message}),r&&e(v,{variant:"outline",onClick:r,children:"Close"})]})}):a?e(Wi,{onClose:r,children:e("div",{className:"fixed inset-0 bg-background z-50 flex items-center justify-center",children:e(Ti,{object:a,children:e(Hi,{object:a,onClose:r})})})}):t("div",{className:"fixed inset-0 bg-background z-50 flex flex-col",children:[e("div",{className:"flex h-9 items-center justify-end shrink-0 bg-sidebar px-2 border-b border-sidebar-border",children:r&&e(v,{variant:"ghost",size:"xs",onClick:r,alt:"Close",children:e(it,{className:"size-4"})})}),e("div",{className:"flex-1 flex items-center justify-center",children:e("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})]})}function Hi({object:n,onClose:r}){const{count:i,pdfUrl:a,pdfUrlLoading:s}=Ii(),[l,c]=o(1),d=(()=>{if("document"===n.metadata?.type){const e=n.metadata,t=e.content_processor?.type;if("markdown"===t)return"markdown"}return"xml"})();return t(R,"xml"===d?{direction:"horizontal",className:"absolute inset-0",children:[e(U,{defaultSize:50,minSize:20,maxSize:80,className:"bg-muted",children:e(Di,{className:"h-full",currentPage:l,onChange:c})}),e(M,{className:"w-[4px] bg-border cursor-ew-resize"}),t(U,{defaultSize:50,minSize:20,className:"flex flex-col",children:[t("div",{className:"flex h-9 items-center justify-between shrink-0 bg-sidebar px-2 border-b border-sidebar-border",children:[e("div",{className:"flex items-center gap-x-2",children:e(Ui,{object:n})}),t("span",{className:"text-xs text-muted-foreground",children:["Page ",l," / ",i]}),e("div",{className:"flex items-center gap-x-2",children:!!r&&e(v,{variant:"ghost",size:"xs",onClick:r,alt:"Close",children:e(it,{className:"size-4"})})})]}),e("div",{className:"flex-1 overflow-auto px-2",children:e(Vi,{pageNumber:l,viewType:"xml"})})]})]}:{direction:"horizontal",className:"absolute inset-0",children:[e(U,{defaultSize:50,minSize:20,maxSize:80,className:"bg-muted",children:e(xi,{pdfUrl:a,pdfUrlLoading:s,pageCount:i,className:"h-full",currentPage:l,onChange:c})}),e(M,{className:"w-[4px] bg-border cursor-ew-resize"}),t(U,{defaultSize:50,minSize:20,className:"flex flex-col",children:[t("div",{className:"flex h-9 items-center justify-between shrink-0 bg-sidebar px-2 border-b border-sidebar-border",children:[e("div",{className:"flex items-center gap-x-2",children:e(Ui,{object:n})}),t("span",{className:"text-xs text-muted-foreground",children:["Page ",l," / ",i]}),e("div",{className:"flex items-center gap-x-2",children:!!r&&e(v,{variant:"ghost",size:"xs",onClick:r,alt:"Close",children:e(it,{className:"size-4"})})})]}),e("div",{className:"flex-1 overflow-auto px-2",children:e(Vi,{pageNumber:l,viewType:"markdown"})})]})]})}function Ji({object:n,url:r,source:i,className:a}){const{client:s}=Et(),[l,d]=o(1),[u,m]=o(r||""),[h,p]=o(!r),[f,g]=o(0),[y,b]=o(!1);c(()=>{if(r)return m(r),void p(!1);const e=i||n?.content?.source;e?(p(!0),s.files.getDownloadUrl(e).then(e=>{m(e.url)}).catch(e=>{console.error("Failed to get PDF URL:",e)}).finally(()=>{p(!1)})):p(!1)},[r,i,n?.content?.source,s]),c(()=>{const e=n?.metadata,t=e?.pages||e?.page_count||0;t>0&&g(t)},[n?.metadata]);const x=e=>{g(e)};return h?e("div",{className:"flex items-center justify-center h-full",children:e(V,{size:"lg"})}):u?y?t("div",{className:"fixed inset-0 bg-background z-50 flex flex-col overflow-hidden",children:[e("div",{className:"flex h-9 items-center justify-end shrink-0 bg-sidebar px-2 border-b border-sidebar-border",children:e(v,{variant:"ghost",size:"xs",onClick:()=>b(!1),alt:"Close fullscreen",children:e(it,{className:"size-4"})})}),e(xi,{pdfUrl:u,pdfUrlLoading:h,pageCount:f||100,currentPage:l,onChange:d,onPageCountChange:x,className:"flex-1 min-h-0"})]}):e("div",{className:"relative h-full flex flex-col",children:e(xi,{pdfUrl:u,pdfUrlLoading:h,pageCount:f||100,currentPage:l,onChange:d,onPageCountChange:x,className:a,compact:!0,headerExtra:e($,{description:"Fullscreen",placement:"bottom",size:"xs",children:e("button",{className:"p-1 rounded cursor-pointer transition-colors text-muted-foreground hover:text-foreground hover:bg-muted",onClick:()=>b(!0),children:e(at,{className:"size-4"})})})})}):e("div",{className:"flex items-center justify-center h-full text-muted",children:"No PDF available"})}const Yi=131072;const Zi=["image/jpeg","image/jpg","image/png","image/gif","image/webp","image/svg+xml"],Qi=["video/mp4","video/webm"],Xi="h-[calc(100vh-208px)]",ea="h-[calc(100vh-228px)]",ta="h-[calc(100vh-218px)]",na="max-h-[calc(100vh-268px)]";function ra(e){return e===Vt.created||e===Vt.processing}function ia(e){return e.metadata?.content_processor?.type}var aa;function sa({object:r,loadText:i,refetch:a}){const s=y(),l=async(e,t)=>{try{await navigator.clipboard.writeText(e),s({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),s({status:"error",title:"Copy failed",description:`Failed to copy ${t} to clipboard`,duration:5e3})}};return e(n,{children:t(R,{direction:"horizontal",className:Xi,children:[e(U,{className:"min-w-[100px]",children:e(la,{object:r,refetch:a??(()=>Promise.resolve()),handleCopyContent:l})}),e(M,{withHandle:!0}),e(U,{className:"min-w-[100px]",children:e(oa,{object:r,loadText:i??!1,handleCopyContent:l,refetch:a})})]})})}function la({object:r,refetch:i,handleCopyContent:a}){const[s,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(v,{variant:""+(s?"ghost":"primary"),size:"sm",alt:"Preview properties",onClick:()=>l(!s),children:"Properties"}),e(v,{variant:""+(s?"primary":"ghost"),size:"sm",alt:"View in JSON format",onClick:()=>l(!s),children:"JSON"})]}),t("div",{className:"flex items-center gap-2",children:[r.properties&&e(v,{variant:"ghost",size:"sm",title:"Copy properties",onClick:()=>a(JSON.stringify(r.properties,null,2),"properties"),children:e(lt,{className:"size-4"})}),e(v,{variant:"ghost",size:"sm",onClick:()=>{d(!0)},title:"Edit properties",className:"flex items-center gap-2",children:e(ot,{className:"size-4"})})]})]}),r.properties?e("div",{className:`${ea} overflow-auto px-2`,children:e(tn,{value:r.properties,viewCode:s})}):e("div",{className:`${ea} overflow-auto px-2`,children:e("div",{children:"No properties defined"})}),e(li,{isOpen:c,onClose:()=>{d(!1)},object:r,refetch:i})]})}function oa({object:n,loadText:r,handleCopyContent:i,refetch:a}){const s=n?.metadata?.type===Kt.Image,l=n?.metadata?.type===Kt.Video,d="application/pdf"===n?.content?.type,u=!!n?.content?.type&&Zr(n.content.type),p=ra(n?.status),f=n.metadata,g=f?.renditions?.find(e=>e.name===Ut),[y,b]=o(l?aa.Video:s?aa.Image:aa.Text),{fullText:x,displayText:w,isLoading:N,isCropped:k}=function(e,t,n=!1){const{store:r}=Et(),[i,a]=o(t),[s,l]=o(()=>t&&t.length>Yi?t.substring(0,Yi):t),[d,u]=o(!1),[m,p]=o(()=>!!t&&t.length>Yi),f=h(()=>{u(!0),r.objects.getObjectText(e).then(e=>{a(e.text),e.text.length>Yi?(l(e.text.substring(0,Yi)),p(!0)):(l(e.text),p(!1))}).catch(e=>{console.error("Failed to load text",e)}).finally(()=>{u(!1)})},[e,r]);return c(()=>{n&&!s&&f()},[n,s,f]),{fullText:i,displayText:s,isLoading:d,isCropped:m,loadText:f}}(n.id,n.text,r),C=(d||u)&&p,{progress:S,status:P,outputFormat:j,isComplete:_}=function(e,t){const{client:n}=Et(),[r,i]=o(),[a,s]=o(),[l,d]=o(),[u,m]=o(!1);return c(()=>{if(!t)return;let r=!1;return function t(){r||n.objects.analyze(e).getStatus().then(e=>{i(e.progress),s(e.status),d(e.output_format??e.progress?.output_format),e.status===Rt.RUNNING?r||setTimeout(t,2e3):m(!0)}).catch(()=>{r||setTimeout(t,1e4)})}(),()=>{r=!0}},[t,e,n]),{progress:r,status:a,outputFormat:l,isComplete:u}}(n.id,C),{pdfUrl:T,isConverting:I,error:A,triggerConversion:z}=function(e,t){const{client:n}=Et(),[r,i]=o(),[a,s]=o(!1),[l,c]=o(),d=h(async()=>{if(!t||a)return;s(!0),c(void 0);const r=async t=>{try{const a=await n.objects.getRendition(e,{format:Mt.pdf,generate_if_missing:t,sign_url:!0,block_on_generation:!1});"generating"===a.status?setTimeout(()=>r(!1),5e3):"found"===a.status&&a.renditions?.length?(i(a.renditions[0]),s(!1)):"failed"===a.status&&(c("PDF conversion failed"),s(!1))}catch(e){console.error("Failed to convert Office document to PDF:",e),c("Failed to convert to PDF"),s(!1)}};await r(!0)},[e,t,a,n]);return{pdfUrl:r,isConverting:a,error:l,triggerConversion:d}}(n.id,u);c(()=>{_&&P===Rt.COMPLETED&&a?.()},[_,P,a]);const E=(d||u)&&p&&!_&&P===Rt.RUNNING,F=m(null);return t("div",{className:"flex flex-col h-full",children:[t("div",{className:"flex justify-between items-center px-2 shrink-0",children:[t("div",{className:"flex items-center gap-2 mb-2",children:[t("div",{className:"flex items-center gap-1 bg-muted p-1 rounded",children:[s&&e(v,{variant:y===aa.Image?"primary":"ghost",size:"sm",alt:"View Image",onClick:()=>b(aa.Image),children:"Image"}),l&&e(v,{variant:y===aa.Video?"primary":"ghost",size:"sm",alt:"View Video",onClick:()=>b(aa.Video),children:"Video"}),e(v,{variant:y===aa.Text?"primary":"ghost",size:"sm",alt:"View Text",onClick:()=>b(aa.Text),children:"Text"}),d&&e(v,{variant:y===aa.Pdf?"primary":"ghost",size:"sm",alt:"View PDF",onClick:()=>b(aa.Pdf),children:"PDF"}),u&&e(v,{variant:y===aa.Pdf?"primary":"ghost",size:"sm",alt:"View as PDF",onClick:()=>{b(aa.Pdf),g||T||I||z()},disabled:I,children:I?e(V,{size:"sm"}):"PDF"})]}),e(ha,{object:n})]}),y===aa.Text&&!E&&e(ca,{object:n,text:w,fullText:x,handleCopyContent:i,textContainerRef:F}),y===aa.Pdf&&u&&(g||T)&&e(pa,{object:n,pdfRendition:g,officePdfUrl:T})]}),y===aa.Image&&e(ua,{object:n}),y===aa.Video&&e(ma,{object:n}),y===aa.Pdf&&d&&e(fa,{object:n}),y===aa.Pdf&&u&&e(ga,{pdfRendition:g,officePdfUrl:T,officePdfConverting:I,officePdfError:A,onConvert:z}),y===aa.Text&&E&&e(ya,{progress:S,status:P,outputFormat:j}),y===aa.Text&&!E&&N&&e("div",{className:"flex justify-center items-center flex-1",children:e(V,{size:"lg"})}),y===aa.Text&&!E&&!N&&e(da,{object:n,text:w,isTextCropped:k,textContainerRef:F})]})}function ca({object:r,text:i,fullText:a,handleCopyContent:s,textContainerRef:l}){const{client:c}=Et(),d=y(),[u,m]=o(null),[h,p]=o(!1),f=r.content,g=f&&f.type&&"text/markdown"===f.type,b=ia(r),x=async e=>{if(!u){m(e),d({status:"info",title:`Preparing ${e.toUpperCase()}`,description:"Fetching your document...",duration:2e3});try{const t=await c.objects.getRendition(r.id,{format:e,generate_if_missing:!0,sign_url:!0});if("generating"===t.status)return d({status:"info",title:"Generating document",description:`Please wait while we prepare your ${e.toUpperCase()} file...`,duration:5e3}),void setTimeout(()=>x(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);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),d({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),d({status:"error",title:"Export failed",description:`Failed to export document to ${e.toUpperCase()} format`,duration:5e3})}finally{m(null)}}};return t(n,{children:[e("div",{className:"h-[41px] text-lg font-semibold flex justify-between items-center px-2",children:t("div",{className:"flex items-center gap-2",children:[a&&t(n,{children:[e(v,{variant:"ghost",size:"sm",title:"Copy text",onClick:()=>s(a,"text"),children:e(lt,{className:"size-4"})}),e(v,{variant:"ghost",size:"sm",title:"Download text",onClick:e=>{if(e.preventDefault(),e.stopPropagation(),!a)return;let t="txt",n="text/plain";"xml"===b?(t="xml",n="text/xml"):("markdown"===b||g)&&(t="md",n="text/markdown");const i=new Blob([a],{type:n}),s=URL.createObjectURL(i),l=`${r.name||"document"}.${t}`,o=document.createElement("a");o.href=s,o.download=l,o.style.display="none",setTimeout(()=>{o.click(),URL.revokeObjectURL(s)},0)},children:e(rt,{className:"size-4"})})]}),g&&i&&t(n,{children:[t(v,{variant:"ghost",size:"sm",onClick:()=>x("docx"),disabled:null!==u,className:"flex items-center gap-2",children:["docx"===u?e(V,{size:"sm"}):e(rt,{className:"size-4"}),"DOCX"]}),t(v,{variant:"ghost",size:"sm",onClick:()=>{l.current?p(!0):d({status:"error",title:"PDF export failed",description:"No content available to export",duration:3e3})},className:"flex items-center gap-2",children:[e(rt,{className:"size-4"}),"PDF"]})]})]})}),t(q,{isOpen:h,onClose:()=>p(!1),children:[e(B,{children:"Export document as PDF"}),t(W,{children:[e("p",{className:"mb-2",children:"This will open your browser's print dialog with the current document content."}),e("p",{className:"text-sm text-muted",children:'To save a PDF, choose "Save as PDF" or a similar option in the print dialog.'})]}),t(G,{align:"right",children:[e(v,{variant:"ghost",size:"sm",onClick:()=>p(!1),children:"Cancel"}),e(v,{size:"sm",onClick:()=>{if(!l.current)return void d({status:"error",title:"PDF export failed",description:"No content available to export",duration:3e3});const e=`${r.name||r.id||"document"} - content`;ni(l.current,e)?(d({status:"success",title:"PDF export ready",description:"Use your browser's Print dialog to save as PDF",duration:4e3}),p(!1)):d({status:"error",title:"PDF export failed",description:"Unable to open print preview",duration:4e3})},children:"Open print dialog"})]})]})]})}!function(e){e.Text="text",e.Image="image",e.Video="video",e.Pdf="pdf"}(aa||(aa={}));const da=f(({object:r,text:i,isTextCropped:a,textContainerRef:s})=>{const l=r.content,o=ra(r?.status),c="xml"===ia(r),d=l&&l.type&&("text/markdown"===l.type||"text/plain"===l.type),u=!c&&(d||function(e){return!!e&&(e.includes("\n# ")||e.includes("\n## ")||e.includes("\n### ")||e.includes("\n* ")||e.includes("\n- ")||e.includes("\n+ ")||e.includes(")}(i));return i?t(n,{children:[a&&e("div",{className:"px-2 py-2 bg-attention/10 border-l-4 border-attention mx-2 mb-2 rounded",children:t("div",{className:"flex items-center gap-2 text-attention",children:[e(st,{className:"size-4"}),e("span",{className:"text-sm font-semibold",children:"Showing first 128K characters only"})]})}),e("div",{className:`max-w-7xl px-2 ${ta} overflow-auto`,ref:s,children:c?e("div",{className:"px-4 py-2",children:e(Xt,{xml:i,collapsible:!0})}):u?e("div",{className:"vprose prose-sm p-1",children:e(Zt,{components:{a:({node:t,...n})=>{const r=n.href||"";return r.includes("/store/objects/")?e(Jt,{topLevelNav:!0,href:r,className:"text-info",children:n.children}):e("a",{...n,target:"_blank",rel:"noopener noreferrer"})},p:({node:t,...n})=>e("p",{...n,className:"my-0"}),pre:({node:t,...n})=>e("pre",{...n,className:"my-2 p-2 rounded"}),code:({node:t,className:n,children:r,...i})=>{const a=/language-(\w+)/.exec(n||"");return e("code",{...i,className:a?"text-muted":"px-1.5 py-0.5 rounded",children:r})},h1:({node:t,...n})=>e("h1",{...n,className:"font-bold text-2xl my-2"}),h2:({node:t,...n})=>e("h2",{...n,className:"font-bold text-xl my-2"}),h3:({node:t,...n})=>e("h3",{...n,className:"font-bold text-lg my-2"}),li:({node:t,...n})=>e("li",{...n})},children:i})}):e("pre",{className:"text-wrap bg-muted text-muted p-2",children:i})})]}):e("div",{className:"px-2",children:e("div",{children:o?"Extracting content...":"No content"})})});function ua({object:t}){const{client:n}=Et(),[r,i]=o(),a=t.content,s=t.metadata&&t.metadata.type===Kt.Image;return c(()=>{if(s){(async()=>{const e=a?.type&&Zi.includes(a.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)i(r.renditions[0]);else if(e){const e=await n.files.getDownloadUrl(t.content.source);i(e.url)}}catch(r){if(e){const e=await n.files.getDownloadUrl(t.content.source);i(e.url)}}})()}},[]),e("div",{className:"mb-4 px-2",children:r?e("img",{src:r,alt:t.name,className:"w-full object-contain"}):e(V,{size:"md"})})}function ma({object:n}){const{client:r}=Et(),[i,a]=o(),[s,l]=o(),[d,u]=o(!0),m=n.content,h=n.metadata?.type===Kt.Video,p=n.metadata,f=p?.renditions||[],g=f.find(e=>"video/mp4"===e.content.type)||f.find(e=>"video/webm"===e.content.type),y=m?.type&&Qi.includes(m.type),b=f.find(e=>e.name===qt);return c(()=>{(async()=>{if(b?.content?.source)try{const e=await r.files.getDownloadUrl(b.content.source);l(e.url)}catch(e){console.error("Failed to load poster image",e)}})()},[b,r]),c(()=>{if(h&&(g?.content?.source||y)){(async()=>{try{let e;g?.content?.source?e=await r.files.getDownloadUrl(g.content.source):y&&m?.source&&(e=await r.files.getDownloadUrl(m.source)),e&&a(e.url)}catch(e){console.error("Failed to get video URL",e)}finally{u(!1)}})()}else u(!1)},[h,g,y,m?.source,r]),e("div",{className:"mb-4 px-2",children:g||y?d?e("div",{className:"flex justify-center items-center h-[400px]",children:e(V,{size:"md"})}):i?e("video",{src:i,poster:s,controls:!0,className:`w-full ${na} 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 ha({object:r}){const[i,a]=o(!1),s=ia(r);return"xml"===s||"markdown"===s?t(n,{children:[e(v,{variant:"ghost",size:"sm",onClick:()=>a(!0),title:"Side by side view",children:e(ct,{className:"size-4"})}),i&&e(K,{children:e(Gi,{objectId:r.id,onClose:()=>a(!1)})})]}):null}function pa({object:t,pdfRendition:n,officePdfUrl:r}){const{client:i}=Et(),a=y(),[s,l]=o(!1);return e("div",{className:"flex items-center gap-2",children:e(v,{variant:"ghost",size:"sm",onClick:async()=>{l(!0);try{let e=r;if(!e&&n?.content?.source){e=(await i.files.getDownloadUrl(n.content.source,`${t.name||"document"}.pdf`,"attachment")).url}e&&window.open(e,"_blank")}catch(e){console.error("Failed to download PDF:",e),a({status:"error",title:"Download failed",description:"Failed to download the PDF file",duration:5e3})}finally{l(!1)}},disabled:s,title:"Download PDF",children:s?e(V,{size:"sm"}):e(rt,{className:"size-4"})})})}function fa({object:t}){return e("div",{className:ta,children:e(Ji,{object:t,className:"h-full"})})}function ga({pdfRendition:n,officePdfUrl:r,officePdfConverting:i,officePdfError:a,onConvert:s}){return i?t("div",{className:"flex flex-col justify-center items-center flex-1 gap-2",children:[e(V,{size:"lg"}),e("span",{className:"text-muted",children:"Converting to PDF..."})]}):a?t("div",{className:"flex flex-col justify-center items-center flex-1 gap-2 text-destructive",children:[e(st,{className:"size-8"}),e("span",{children:a})]}):e("div",n?.content?.source?{className:ta,children:e(Ji,{source:n.content.source,className:"h-full"})}:r?{className:ta,children:e(Ji,{url:r,className:"h-full"})}:{className:"flex flex-col justify-center items-center flex-1 gap-2",children:e(v,{onClick:s,children:"Convert to PDF"})})}function ya({progress:r,status:i,outputFormat:a}){const s=ri(i),l=ii(i),o="xml"===a,c=null==r?.percent||isNaN(r.percent)?0:r.percent;return t("div",{className:"px-4 py-4",children:[r&&t("div",{className:"space-y-2",children:[t("div",{className:"flex flex-col gap-1",children:[e(ba,{name:o?"Analyze Layouts":"Analyze Page",progress:r.pages}),o&&t(n,{children:[e(ba,{name:"Extract Tables",progress:r.tables}),e(ba,{name:"Describe Images",progress:r.images}),e(ba,{name:"Process Visually",progress:r.visuals})]})]}),t("div",{className:"pt-2 text-sm text-muted",children:["Progress: ",c,"%",e("span",{className:"px-2",children:"•"}),e("span",{className:s,children:l}),r.started_at&&t(n,{children:[e("span",{className:"px-2",children:"•"}),t("span",{children:[((Date.now()-r.started_at)/1e3).toFixed(0)," sec. elapsed"]})]})]}),e(nn,{percent:c})]}),!r&&t("div",{className:"flex items-center gap-2 text-muted",children:[e(V,{size:"sm"}),e("span",{children:"Loading processing status..."})]})]})}function ba({name:e,progress:n}){return t("div",{className:"flex gap-2 text-sm",children:[t("span",{className:"text-muted min-w-36",children:[e,":"]}),t("span",{children:[n.processed," of ",n.total]})]})}function va({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(H,{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(J,{className:"bg-muted h-[2px]"}),t(Y,{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 xa({selection:n,document:r,onSelectionChange:i,onRowClick:a,previewObject:s,selectedObject:l}){const{client:d}=Et(),[u,m]=o(void 0),[h,p]=o(void 0),[f,g]=o(void 0);return c(()=>{r?.content&&ti(d,r,m,p,g)},[r]),t(H,{className:"relative flex flex-col border h-fit "+(l?.id===r.id?"border-attention border-4":""),onClick:()=>a&&a(r),children:[n&&e("div",{className:"absolute top-2 left-2 z-10 flex flex-col items-center gap-1",children:e("input",{checked:n.isSelected(r.id),type:"checkbox",onChange:e=>{e.stopPropagation(),i(r,e)},onClick:e=>e.stopPropagation()})}),e("div",{className:"absolute top-1 right-1 z-10 flex flex-col items-center",children:e(v,{variant:"ghost",size:"sm",title:"Preivew Object",onClick:e=>{e.stopPropagation(),s?.(r.id)},children:e(dt,{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(J,{className:"bg-gray-200 h-[2px]"}),t(Y,{className:"p-2 flex flex-col",children:[t("div",{className:"flex flex-col overflow-hidden",children:[e($,{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($,{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 wa(e){return`${e._id} (${e.count})`}function Na(e){return`${e.name} (${e.count})`}function ka({search:t,buckets:n,name:r,placeholder:i,className:a}){const s=t.getFilterValue(r),l=n?.find(e=>JSON.stringify(e._id)===JSON.stringify(s));return e(Z,{filterBy:"_id",className:a,isClearable:!0,optionLabel:wa,options:n,value:l,onChange:e=>{t.setFilterValue(r,e?._id)},by:"_id",placeholder:i})}function Ca({search:t,name:n,placeholder:r,className:i}){const[a,s]=o([]);return c(()=>{t.setFilterValue(n,a)},[a]),e(Q,{className:i,value:a,onChange:s,placeholder:r})}function Sa(e){return`${e.name} (${e.count})`}function Pa({search:t,buckets:n,placeholder:r="Filter by Type",className:i}){const[a,s]=o([]),{typeRegistry:l}=Et(),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)),s(e)}},[n,l]);const u=a?.find(e=>e._id===d);return e(Z,{filterBy:"name",className:i,isClearable:!0,optionLabel:Sa,options:a,value:u,onChange:e=>{t.setFilterValue("type",e?._id)},by:"_id",placeholder:r})}function ja({buckets:e,name:t,placeholder:n,type:r,multiple:i}){return function({buckets:e,name:t,placeholder:n,type:r="select",multiple:i=!1}){return{name:t,options:e.map(e=>({label:wa(e),value:e._id})),type:r,multiple:i,placeholder:`${n??`${t.charAt(0).toUpperCase()+t.slice(1)}`}`,allowCreate:!1}}({buckets:e,name:t,placeholder:n,type:r,multiple:i})}function _a({buckets:n,typeRegistry:r,type:i="select",multiple:a=!1}){const s=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)),s.set(n,{name:t,count:e.count})});return{name:"types",placeholder:"Types",type:i,multiple:a,options:n.map(e=>{const t=e._id,n=t||"Document",r=s.get(n);return{value:t,label:r?`${r.name} (${r.count})`:`Unknown (${e.count})`}}),labelRenderer:n=>{const r=s.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=s.get(e);return n?n.name.toLowerCase().includes(t.toLowerCase()):(console.warn(`Type name not found for ${e}`),!1)}}}const Ta={},Ia={};function Aa(e){const{client:t}=Et();return L(()=>{let n=Ta[e];return n||(n=t.users.retrieve(e).then(e=>e),Ta[e]=n),n},[e])}function za(e){const{client:t}=Et();return L(()=>{let n=Ia[e];return n||(n=t.iam.groups.retrieve(e).then(e=>e),Ia[e]=n),n},[e])}function Ea(){return e("div",{className:"size-8"})}function Fa({showTitle:n=!1,size:r="md"}){return e(Va,{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(X,{src:"/icon.svg",size:r}),n&&e("div",{className:"text-sm font-semibold pl-2",children:"System User"})]})})}function Da({accountId:r,showTitle:i=!1,size:a="md"}){const s=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(Va,{title:"Service Account",description:s,children:t("div",{className:"flex flex-row items-center gap-2",children:[e(X,{src:"/cloud.svg",name:"SA",color:"bg-amber-500",className:"px-[5px] text-white",size:a}),i&&t("div",{className:"text-sm font-semibold pl-2 truncate",children:["Service Account : ",r]})]})})}function $a({title:t="Error",error:n,showTitle:r=!1,size:i="md"}){return e(Oa,{title:t,message:"string"==typeof n?n:n.message,color:"bg-red-500",showTitle:r,size:i})}function La({userRef:t,showTitle:n=!1,size:r="md"}){if(!t)return e(Oa,{title:"Unknown User",message:"User information is not available.",showTitle:n,size:r});const[i,a]=t?t.split(":"):["unknown"];switch(i){case Bt.User:return e(Ua,{userId:a,showTitle:n,size:r});case Bt.Group:return e(Ra,{userId:a,showTitle:n,size:r});case"system":return e(Fa,{showTitle:n,size:r});case Bt.ServiceAccount:case Bt.Agent:return e(Da,{accountId:a,showTitle:n,size:r});case Bt.ApiKey:return e(Ma,{keyId:a,size:r,showTitle:n});default:return e($a,{title:"Unknown User",error:`Invalid user ref type: ${i}`,showTitle:n,size:r})}}function Oa({title:n,message:r,color:i,size:a="md",showTitle:s=!1}){return e(Va,{title:n,description:r,children:t("div",{className:"flex flex-row items-center gap-2",children:[e(X,{color:i,size:a}),s&&e("div",{className:"text-sm font-semibold pl-1",children:n})]})})}function Ra({userId:n,showTitle:r=!1,size:i="md"}){const{data:a,error:s}=za(n);if(s)return e($a,{title:"Failed to fetch group",error:s,showTitle:r,size:i});if(!a)return e(Ea,{});const l=t("div",{className:"space-y-1",children:[a.description&&e("div",{className:"text-sm",children:a.description}),t("div",{className:"text-xs text-muted-foreground",children:["Group ID: ",a.id]}),a.tags&&a.tags.length>0&&e("div",{className:"flex flex-wrap gap-1",children:a.tags.map(t=>e("span",{className:"px-1.5 py-0.5 bg-muted rounded text-xs",children:t},t))})]});return e(Va,{title:a.name||"Unnamed Group",description:l,children:t("div",{className:"flex flex-row items-center gap-2",children:[e(ut,{className:"size-6 text-indigo-500",size:i}),r&&e("div",{className:"text-sm font-semibold pl-2",children:a.name||"Unnamed Group"})]})})}function Ua({userId:n,showTitle:r=!1,size:i="md"}){const{data:a,error:s}=Aa(n);if(s)return e($a,{title:"Failed to fetch user",error:s,showTitle:r,size:i});if(!a)return e(Ea,{});const l=e("div",{className:"truncate",title:a.email,children:a.email});return e(Va,{title:a.name||a.email||a.username||"unknown",description:l,children:t("div",{className:"flex flex-row items-center gap-2",children:[e(X,{src:a.picture,name:a.name,color:"bg-indigo-500",size:i}),r&&e("div",{className:"text-sm font-semibold pl-2",children:a.name||a.email||a.username||"unknown"})]})})}function Ma({keyId:n,showTitle:r=!1,size:i="md"}){const{client:a}=Et(),{data:s,error:l}=L(()=>a.apikeys.retrieve(n),[]);if(l)return e($a,{title:"Failed to fetch the apikey",error:l,showTitle:r,size:i});if(!s)return e(Ea,{});const o=e(X,{name:"PK",color:"bg-pink-500",size:i}),c=t(ee,{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:s?.name})]}),t("tr",{children:[e("td",{className:"font-semibold w-20",children:"Account:"}),e("td",{className:"truncate max-w-0",children:s?.account})]}),t("tr",{children:[e("td",{className:"font-semibold w-20",children:"Project:"}),e("td",{className:"truncate max-w-0",children:s?.project.name})]})]});return e(Va,{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:s?.name||s?.account||s?.project.name||"unknown"})]})})}function Va({title:n,description:r,children:i}){return t(x,{hover:!0,children:[e(w,{className:"cursor-pointer flex items-center inline-block",children:e("div",{children:i})}),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 Ka({buckets:n,name:r,placeholder:i}){return function({buckets:n,name:r,placeholder:i}){const a=n.map(e=>({value:e._id,label:`(${e.count})`}));return{name:r,placeholder:i||`${r.charAt(0).toUpperCase()+r.slice(1)}`,options:a,labelRenderer:r=>{if("Unknown User"===r||!r){const e=n.find(e=>e._id===r);return`Unknown User (${e?.count||0})`}const i=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(La,{userRef:r,showTitle:!0,size:"sm"})}),t("span",{className:"text-muted-foreground flex-shrink-0",children:["(",i?.count||0,")"]})]})}}}({buckets:n,name:r,placeholder:i})}function qa({search:t,buckets:n,placeholder:r="All Environments",className:i}){const{client:a}=Et(),[s,l]=o([]),d=t.getFilterValue("environment");c(()=>{if(a){const e=n.map(async e=>{let t;return await a.environments.retrieve(e._id).then(e=>{t=e.name}).catch(()=>{t=`${e._id} (deleted)`}),t||(t=e._id),{...e,name:t}});Promise.all(e).then(e=>{e.sort((e,t)=>e.name.localeCompare(t.name)),l(e)})}},[n,a]);const u=s?.find(e=>e._id===d);return e(Z,{filterBy:"name",className:i,isClearable:!0,optionLabel:Na,options:s,value:u,onChange:e=>{t.setFilterValue("environment",e?._id)},by:"_id",placeholder:r})}function Ba(n){const r=[];if(r.push({name:"run_ids",placeholder:"Run ID",type:"text",multiple:!1}),n.interactions){const i=function({buckets:n,name:r,placeholder:i}){return{name:r,placeholder:i,options:n.map(e=>({label:`(${e.count})`,value:e._id})),type:"select",labelRenderer:r=>{const i=n.find(e=>e._id===r),a=i?.name||r;let s="success";if(i?.status)switch(i.status){case Wt.published:s="success";break;case Wt.archived:s="destructive";break;default:s="attention"}const l=i?.version&&i?.status?`v${i.version} ${i.status}`:i?.status||(i?.version?`v${i.version}`:"");return t("div",{className:"w-full flex items-center justify-between",children:[t("div",{className:"flex flex-row flex-wrap items-center gap-2 min-w-0 flex-1",children:[e("span",{className:"text-sm truncate",children:a}),l&&e(b,{variant:s,className:"text-xs w-fit",children:l})]}),t("span",{className:"ml-2 text-xs shrink-0",children:["(",i?.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(i)}if(n.environments){const i=function({buckets:n,name:r}){const i=n.map(e=>({label:`(${e.count})`,value:e._id}));return{name:r.charAt(0).toUpperCase()+r.slice(1),options:i,type:"select",labelRenderer:r=>{const i=n.find(e=>e._id===r);return t("div",{className:"w-full flex items-center",children:[e("span",{className:"text-sm truncate",children:i?.name||r}),t("span",{className:"ml-2 text-xs",children:["(",i?.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(i)}if(r.push({name:"tags",placeholder:"Tags",type:"stringList",multiple:!0}),n.models){const e=ja({buckets:n.models||[],name:"model"});r.push(e)}if(n.statuses){const e=ja({buckets:n.statuses||[],name:"status"});r.push(e)}if(n.finish_reason){const e=ja({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=Ka({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 Wa(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 Ga({facets:n,search:r}){const[i,a]=o([]),s=Ba(n),l=Wa(r);return t(te,{filterGroups:s,filters:i,setFilters:e=>{const t="function"==typeof e?e(i):e;a(t),l(t)},children:[t("div",{className:"flex justify-between mb-1",children:[e(ne,{}),e(v,{onClick:()=>{r.search()},variant:"outline",title:"Refresh",children:e(mt,{className:"size-5"})})]}),t("div",{className:"flex gap-2 items-center",children:[e(re,{}),e(ie,{})]})]})}function Ha(e){const t=[];if(t.push({placeholder:"Workflow or Run ID",name:"name",type:"text",options:[]}),e.status){const n=ja({buckets:e.status||[],name:"status",placeholder:"Status"});t.push(n)}if(e.initiated_by){const n=Ka({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 Ja(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 Ya({facets:n,search:r}){const[i,a]=o([]),s=Ha(n),l=Ja(r);return e(te,{filterGroups:s,filters:i,setFilters:e=>{const t="function"==typeof e?e(i):e;a(t),l(t)},children:t("div",{className:"flex gap-2 items-center",children:[e(ne,{}),e(re,{}),e(ie,{})]})})}function Za(e){const{typeRegistry:t}=Et(),n=[];if(n.push({placeholder:"ID",name:"id",type:"text",options:[]}),n.push({placeholder:"Name",name:"name",type:"text",options:[]}),e.type){const r=_a({buckets:e.type||[],typeRegistry:t,type:"select",multiple:!0});n.push(r)}if(e.status){const t=ja({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 Qa(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 Xa({facets:n,search:r}){const[i,a]=o([]),s=Za(n),l=Qa(r);return e(te,{filterGroups:s,filters:i,setFilters:e=>{const t="function"==typeof e?e(i):e;a(t),l(t)},children:t("div",{className:"flex gap-2 items-center",children:[e(ne,{}),e(re,{}),e(ie,{})]})})}function es(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 ts(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 ns({facets:n,search:r}){const[i,a]=o([]),s=es(),l=ts(r);return e(te,{filterGroups:s,filters:i,setFilters:e=>{const t="function"==typeof e?e(i):e;a(t),l(t)},children:t("div",{className:"flex gap-2 items-center",children:[e(ne,{}),e(re,{}),e(ie,{})]})})}function rs(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 is(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 as({facets:n,search:r}){const[i,a]=o([]),s=rs(n),l=is(r);return e(te,{filterGroups:s,filters:i,setFilters:e=>{const t="function"==typeof e?e(i):e;a(t),l(t)},children:t("div",{className:"flex gap-2 items-center",children:[e(ne,{}),e(re,{}),e(ie,{})]})})}function ss(e){const{typeRegistry:t}=Et(),n=[];if(n.push({name:"name",placeholder:"Name",type:"text",multiple:!1}),t){const e=t.types.map(e=>({label:e.name,value:e.id})),r={name:"types",placeholder:"Type",type:"select",multiple:!0,options:e,filterBy:(t,n)=>{const r=e.find(e=>e.value===t);return r?.label?.toLowerCase().includes(n.toLowerCase())??!1}};n.push(r)}return n}function ls(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 os({facets:n,search:r}){const[i,a]=o([]),s=ss(),l=ls(r);return e(te,{filterGroups:s,filters:i,setFilters:e=>{const t="function"==typeof e?e(i):e;a(t),l(t)},children:t("div",{className:"flex gap-2 items-center",children:[e(ne,{}),e(re,{}),e(ie,{})]})})}class cs{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 cs(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 ds=d(void 0);function us(){const e=u(ds);if(!e)throw new Error("useObjectSelection must be used within a ObjectSelectionProvider");return e}function ms(){return u(ds)}function hs({value:t,collectionId:n,children:r}){const[i,a]=o();return c(()=>{const e=new cs(t,n,{},a);a(e)},[t]),i&&e(ds.Provider,{value:i,children:r})}un.extend(vn),un.extend(bn);const ps={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 i;if(t){if(i=String(t),r.length>0)for(const e of r)i=e(i)}else i="";return e("td",{children:i},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,i;t&&(r=t.get("currency")||void 0,i=t.get("decimals")||void 0);const a=i?parseInt(i):2;return(t,n)=>{let i=new Intl.NumberFormat("en-US",{style:r?"currency":"decimal",currency:r,maximumFractionDigits:a}).format(t);return e("td",{children:i},n)}},objectId(n,r){let i=[],a=!1;if(n){const e=n.get("slice");e&&(a=!0,i.push(t=>t.slice(parseInt(e))))}return(n,s)=>{const l=i.reduce((e,t)=>t(e),n.id);return t("td",{className:"flex justify-between items-center gap-2",children:[a?"~":"",l,e(v,{variant:"ghost",alt:"Preview Object",onClick:e=>{e.stopPropagation(),r?.(n.id)},children:e(dt,{className:"size-4"})})]},s)}},objectName(t,n){let r="title";return t&&(r=t.get("title")||"title"),(t,n)=>e("td",{children:t.properties?.[r]||t.name||Ur(t.id)},n)},objectLink(n,r){const i=[];return i.push(e=>e.slice(-7)),(n,a)=>{const s=i.reduce((e,t)=>t(e),n.id);return t("td",{className:"flex justify-between items-center gap-2 max-w-48",children:["~",s,e(v,{variant:"ghost",alt:"Preview Object",onClick:e=>{e.stopPropagation(),r?.(n.id)},children:e(dt,{className:"size-4"})})]},a)}},typeLink:(t,n)=>(t,n)=>e("td",{children:t?.name||"n/a"},n),date(t,n){let r="format",i="LLL";if(t){const e=t.get("localized");if(e)i=e;else{const e=t.get("relative");e&&(r=e,i=void 0)}}return(t,n)=>e("td",{children:un(t)[r](i)},n)}},fs=ps.string();function gs(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 ys(e){return e&&"."!==e?e.split("."):[]}class bs{layout;renderer=fs;path;fallbackPath;previewObject;constructor(e,t){if(this.layout=e,this.path=ys(e.field||""),this.fallbackPath=e.fallback?ys(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=ps[e](r)}else this.renderer=ps[t]()}}get name(){return this.layout.name}resolveValue(e){let t=gs(e,this.path);return void 0===t&&this.fallbackPath&&(t=gs(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",i=r.indexOf("?")>0?r.substring(0,r.indexOf("?")):r;if(("objectId"===i||"objectLink"===i)&&this.previewObject){const e=r.indexOf("?"),a=e>0?new URLSearchParams(r.substring(e+1)):void 0;return ps[i](a,e=>{this.previewObject(t.id)})(t,n)}return this.renderer(this.resolveValue(t),n)}}function vs({objects:n,selection:r,isLoading:i,columns:a,onRowClick:s,selectedObject:l,toggleAll:o,onSelectionChange:c}){return t(ee,{className:"w-full border-t",children:[e("thead",{children:t("tr",{children:[r&&e("th",{children:e("input",{type:"checkbox",onChange:o})}),a.map(t=>e("th",{children:t.name},t.name))]})}),t(ae,{isLoading:i,columns:a.length+1,children:[n?.map(n=>t("tr",{className:"cursor-pointer hover:bg-muted group "+(l?.id===n.id?"bg-muted":""),onClick:()=>{s&&s(n)},children:[r&&e("td",{onClick:e=>e.stopPropagation(),children:e("input",{checked:r.isSelected(n.id),type:"checkbox",className:""+(r.isSelected(n.id)?"":"hidden group-hover:block"),onChange:e=>c(n,e)})}),a.map((e,t)=>e.render(n,t))]},n.id)),0===n.length&&e("tr",{children:e("td",{colSpan:a.length+(r?1:0),className:"text-center",children:"No objects. Just drag and drop documents or images here to create content objects."})})]})]})}function xs({objects:r,selection:i,isLoading:a,onSelectionChange:s,onRowClick:l,previewObject:o,selectedObject:c}){return t(n,{children:[e(va,{isLoading:a}),e("div",{className:"w-full gap-2 grid lg:grid-cols-6",children:r.map(t=>e(xa,{document:t,selection:i,onSelectionChange:s,onRowClick:l,previewObject:o,selectedObject:c},t.id))})]})}class ws{client;limit;collectionId;facets=new se({});result=new se({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:i,score_aggregation:a,dynamic_scaling:s,limit:l,all_revisions:o}=this.query;this.query={parent:t,...void 0!==n&&{full_text:n},...void 0!==r&&{vector:r},...void 0!==i&&{weights:i},...void 0!==a&&{score_aggregation:a},...void 0!==s&&{dynamic_scaling:s},...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 i={limit:t,offset:n,query:e,facets:r?this.facetSpecs:void 0};return this.collectionId?this.client.collections.searchMembers(this.collectionId,i):this.client.objects.search(i)}_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 i=r.results||[],a=r.facets||{};return this.result.value={isLoading:!1,objects:e?this.objects.concat(i):i,hasMore:i.length===n},!t&&a&&Object.keys(a).length>0&&(this.facets.value=a),!0}).catch(e=>{throw this.result.value={error:e,isLoading:!1,objects:this.objects,hasMore:this.result.value.hasMore},e})}search(e=!1){return this.isRunning&&this.objects.length>0?Promise.resolve(!1):this._search(!1,e)}loadMore(e=!1){return this.isRunning||!this.hasMore||this.query.vector?Promise.resolve(!1):(this.objects.length>0&&(e=!0),this._search(!0,e))}}const Ns=d(void 0);function ks(){return u(Ns)}function Cs(){return le(ks().facets)}function Ss(){const e=ks();return{...le(e.result),search:e}}function Ps(){const e=ks();return le(e.facets).total}var js;async function _s(e){try{const t=await e.arrayBuffer(),n=new xn;n.appendByteArray(new Uint8Array(t));const r=n.end();return r?.toString()}catch(e){return void console.error("Error calculating file hash:",e)}}function Ts(){const{client:e}=Et(),t=y();return{checkDocumentProcessing:async(n,r,i)=>{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 i=e.slice(r,r+5),a=await Promise.all(i.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 _s(e),name:e.name,size:e.size,location:n}}));n.push(...a)}return n}(n,r),a=async()=>{let n;const r={query:{match:{"content.etag":{$in:t.map(e=>e.hash)}}},select:"id content.etag"};n=i?(await e.store.collections.searchMembers(i,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=js.SKIP)}},s=async()=>{const n=t.filter(e=>e.action!==js.SKIP),r=n.map(e=>e.location),a=Array.from(new Set(r)),s=[];for(const t of a){const r={"content.name":{$in:n.filter(e=>e.location===t).map(e=>e.name)},location:t||"/"};if(i){const t=e.store.collections.searchMembers(i,{query:{match:r},select:"id content.name location"}).then(e=>e.results);s.push(t)}else{const t=e.store.objects.find({query:r,select:"id content.name location"});s.push(t)}}const l=(await Promise.all(s)).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=js.UPDATE)}console.log(`Reconciled ${t.filter(e=>e.action===js.UPDATE).length}`)};return await a(),await s(),t.forEach(e=>{e.action||(e.action=js.CREATE)}),console.log("Document processing check results:",{totalFiles:n.length,toCreate:t.filter(e=>e.action===js.CREATE).length,toUpdate:t.filter(e=>e.action===js.UPDATE).length,toSkip:t.filter(e=>e.action===js.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 Is({isOpen:r,onClose:i,files:a,collectionId:s,selectedFolder:d,title:u="Upload Files",children:m,onUploadComplete:h,hideFileSelection:p=!1,showTypeSelectionOnly:f=!1}){const{client:g,typeRegistry:b}=Et(),x=y(),[w,N]=o([]),[k,C]=o([]),[S,P]=o(!1),[j,_]=o(null),[T,I]=o([]),[A,z]=o(!1),[E,F]=o(!1),[D,L]=o(0),[O,R]=o(Date.now()),[U,M]=o(void 0),[K,H]=o(null),[J,Y]=o(u),[Z,Q]=o("");c(()=>{s&&g.store.collections.retrieve(s).then(M)},[s]),c(()=>{A?(Y("Uploading Files"),Q(`${Math.round(D)}% complete`)):E?(Y("Upload Complete"),Q("")):S?(Y("File Analysis Results"),Q(`${w.length} file${1!==w.length?"s":""}`)):w.length>0?(Y(u),Q("Checking for duplicates and updates")):(Y(u),Q(""))},[A,E,S,u,D,w.length]);const X=()=>U||d?t(oe,{className:"mb-4",status:"default",icon:e(bt,{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:[U&&t("div",{className:"flex items-center",children:[e("span",{className:"mr-1",children:"Collection:"}),e("span",{className:"font-medium",children:U.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,[ee,te]=o({toCreate:0,toUpdate:0,toSkip:0}),{checkDocumentProcessing:ne}=Ts(),re=l(()=>b?.types||[],[b?.types]);c(()=>{r&&(C([]),P(!1),_(null),I([]),z(!1),F(!1),L(0),te({toCreate:0,toUpdate:0,toSkip:0}),H(null),Y(u),Q(""),a&&a.length>0?(N(a),se(a)):N([]),R(Date.now()))},[r,a]);const ie=()=>{N([]),C([]),P(!1),_(null),I([]),z(!1),F(!1),L(0),te({toCreate:0,toUpdate:0,toSkip:0}),H(null),Y(u),Q(""),R(Date.now()),i()},ae=e=>{e&&e.length>0&&(N(e),se(e))},se=async e=>{if(e.length)try{console.log(`Processing ${e.length} files to determine required actions...`);const t=await ne(e,d,s);C(t);const n=t.filter(e=>e.action===js.CREATE).length,r=t.filter(e=>e.action===js.UPDATE).length,i=t.filter(e=>e.action===js.SKIP).length;te({toCreate:n,toUpdate:r,toSkip:i}),x({title:"Files analyzed",description:`${e.length} file(s): ${n} new, ${r} to update, ${i} to skip`,status:"info",duration:4e3}),P(!0)}catch(e){console.error("Error processing files:",e),x({title:"Error",description:"There was an error analyzing the files",status:"error",duration:5e3})}},le=async()=>{if(!k.length)return;const e=j?.id||null,t=k.map(e=>({file:e.file,status:"pending",progress:0,action:e.action===js.CREATE?"create":e.action===js.UPDATE?"update":"skip"}));I(t),z(!0),F(!1);const n=k.filter(e=>e.action===js.SKIP),r=k.filter(e=>e.action===js.UPDATE),i=k.filter(e=>e.action===js.CREATE),a={success:!0,objectIds:[],uploadedFiles:[],skippedFiles:[],failedFiles:[]};for(const t of n)t.existingId&&(a.objectIds.push(t.existingId),a.skippedFiles.push({id:t.existingId,name:t.name,type:e,status:"skipped",location:t.location}),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 i=0;i<r.length;i++){const l=r[i];if(console.log(`Processing ${n} batch ${i+1}/${r.length} (${l.length} files)`),t.length>50){x({title:`Processing files (${n})`,description:`Processed ${50*i}/${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)),a.objectIds.push(t.existingId),a.uploadedFiles.push({id:t.existingId,name:t.name,type:e,status:"updated",location:t.location});else{const n=await g.store.objects.create({type:e||void 0,content:t.file,location:t.location||t.file.webkitRelativePath||t.name},{collection_id:s});I(e=>e.map(e=>e.file===t.file?{...e,status:"success",progress:100,id:n.id}:e)),a.objectIds.push(n.id),a.uploadedFiles.push({id:n.id,name:t.name,type:e,status:"created",location:t.location})}}catch(n){console.error(`Failed to process file ${t.name}:`,n),I(e=>e.map(e=>e.file===t.file?{...e,status:"error",progress:100,message:n.message||"Unknown error"}:e)),a.failedFiles.push({name:t.name,error:n.message||"Unknown error",status:"failed",location:t.location,type:e}),a.success=!1}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 L(r),e})}))}};r.length>0&&await l(r,"update"),i.length>0&&await l(i,"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=>{a.failedFiles.push({name:e.file.name,error:"Upload process interrupted",status:"failed",type:j?.id||null})}),a.success=!1,e.map(e=>"pending"===e.status?{...e,status:"error",progress:100,message:"Upload process interrupted"}:e)):e}),z(!1),F(!0);const o=a.uploadedFiles.filter(e=>"created"===e.status).length,c=a.uploadedFiles.filter(e=>"updated"===e.status).length,d=a.skippedFiles.length,u=a.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}),H(a)},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($,{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(Le,{className:"size-3 ml-2"})})]}),e(ce,{options:re,value:j,optionLabel:e=>e?e.name:"Select a content type",placeholder:"Select a content type or leave empty for automatic detection",onChange:e=>_(void 0===e?null:e),filterBy:"name",isClearable:!0}),j?e(n,{}):e("div",{className:"p-2 rounded-md",children:t("div",{className:"flex items-center text-attention",children:[e(pt,{className:"size-4 mr-1"}),"Automatic Type Detection",e($,{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(Le,{className:"size-3 ml-2"})})]})})]});return t(q,{isOpen:r,onClose:ie,className:"mx-auto",disableCloseOnClickOutside:!0,children:[e(B,{description:Z,children:J}),f?t(W,{children:[m,X(),de()]}):0!==w.length||p?A||E?A?t(W,{children:[X(),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:`${D}%`}})})}),e("div",{className:"max-h-96 overflow-y-auto",children:T.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(gt,{className:"size-5 text-muted"}),"uploading"===n.status&&e(V,{size:"sm"}),"success"===n.status&&e(pt,{className:"size-5 text-success"}),"error"===n.status&&e(yt,{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(W,{children:t("div",{className:"mb-4",children:[X(),e(an,{files:T.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:U?.name})]})}):e(W,{children:S?t(n,{children:[X(),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(ht,{className:"size-5 text-primary"}),e("span",{className:"font-medium",children:"New"})]}),e("div",{className:"text-2xl font-semibold",children:ee.toCreate})]}),t("div",{className:"flex flex-col items-center",children:[t("div",{className:"flex items-center gap-2",children:[e(pt,{className:"size-5 text-success"}),e("span",{className:"font-medium",children:"Update"})]}),e("div",{className:"text-2xl font-semibold",children:ee.toUpdate})]}),t("div",{className:"flex flex-col items-center",children:[t("div",{className:"flex items-center gap-2",children:[e(ft,{className:"size-5 text-mixer-attention/40"}),e("span",{className:"font-medium",children:"Skip"})]}),e("div",{className:"text-2xl font-semibold",children:ee.toSkip})]})]})})}),de(),e(oe,{className:"mb-4",status:"info",children:ee.toCreate+ee.toUpdate>0?t("div",{className:"space-y-1",children:[t("p",{children:[ee.toCreate+ee.toUpdate," file",ee.toCreate+ee.toUpdate>1?"s are":" is"," ready to process"]}),e("p",{children:ee.toSkip>0&&`${ee.toSkip} file${ee.toSkip>1?"s are":" is"} already in the system and will be skipped.`})]}):ee.toSkip>0?t("span",{children:["All ",ee.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(V,{size:"lg",className:"mb-4"}),e("div",{className:"text-lg font-medium",children:"Analyzing files..."})]})}):t(W,{className:"flex flex-col items-center justify-center p-8",children:[X(),e(rn,{onDrop:ae,message:"Drag and drop files here or click to select",buttonLabel:"Select Files",className:"w-full h-64"}),m]}),(()=>{if(f)return t(G,{children:[e(v,{variant:"ghost",onClick:ie,children:"Cancel"}),e(v,{onClick:()=>{h&&h({success:!0,objectIds:[],uploadedFiles:[{name:"type-selection",type:j?.id||null,status:"created"}],skippedFiles:[],failedFiles:[]}),ie()},children:j?`Use ${j.name}`:"Use Automatic Type Detection"})]});if(0===w.length&&!p)return e(G,{children:e(v,{variant:"ghost",onClick:ie,children:"Cancel"})});if(!A&&!E){const n=S;return t(G,{children:[e(v,{variant:"ghost",onClick:ie,children:"Cancel"}),e(v,{disabled:!n,onClick:le,children:ee.toCreate+ee.toUpdate>0?"Upload":"Continue"})]})}return A?e(G,{children:e(v,{variant:"ghost",disabled:!0,children:"Uploading..."})}):t(G,{children:[e(v,{variant:"ghost",onClick:()=>{N([]),C([]),P(!1),_(null),I([]),z(!1),F(!1),L(0),te({toCreate:0,toUpdate:0,toSkip:0})},children:"Upload More"}),e(v,{onClick:()=>{h&&K&&h(K),ie()},children:"Close"})]})})()]},O)}function As(e){const t="function"==typeof e?e:e.onUploadDone,{client:n,project:r,store:i}=Et(),a=ks(),s=y(),{checkDocumentProcessing:l}=Ts();return async(e,o,c)=>{const d={success:!1,objectIds:[],uploadedFiles:[],skippedFiles:[],failedFiles:[]};if(!r)return s({status:"error",title:"No project selected",duration:3e3}),d;if(!e||0===e.length)return s({status:"warning",title:"No files selected",duration:3e3}),d;const u=Array.from(e).filter(e=>e.size>0);if(0===u.length)return s({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===js.CREATE).length,y=f.filter(e=>e.action===js.UPDATE).length,b=f.filter(e=>e.action===js.SKIP).length;s({title:"Files analyzed",description:`${u.length} file(s): ${g} new, ${y} to update, ${b} to skip`,status:"info",duration:4e3});for(const e of f.filter(e=>e.action===js.SKIP&&e.existingId))m.push({id:e.existingId,name:e.name,type:o,status:"skipped",location:e.location});const v=f.filter(e=>(e.action===js.CREATE||e.action===js.UPDATE)&&e.file);if(v.length>0){console.log(`Processing ${v.length} files (${v.filter(e=>e.action===js.CREATE).length} create, ${v.filter(e=>e.action===js.UPDATE).length} update)...`);const e=50,t=[];for(let n=0;n<v.length;n+=e)t.push(v.slice(n,n+e));for(let r=0;r<t.length;r++){const a=t[r],l=r*e;console.log(`Processing batch ${r+1}/${t.length} (${a.length} files)`),v.length>e&&s({title:"Processing files",description:`Processed ${l}/${v.length} files...`,status:"info",duration:2e3});const u=await Promise.all(a.map(async e=>{try{if(e.action===js.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 i.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}),s({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&&s({status:N>0?"warning":"success",title:C,duration:4e3}),a.search(),d}}!function(e){e.CREATE="create",e.SKIP="skip",e.UPDATE="update"}(js||(js={}));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 Es({isGridView:t=!1,onUpload:n,collectionId:r,...i}){return n?e(Fs,{...i,onUpload:n,isGridView:t,collectionId:r}):e(Ds,{...i,isGridView:t})}function Fs({isGridView:n,onUpload:i,collectionId:a,skipTypeModal:s=!1,...l}){const[c,d]=o(!1),[u,m]=o([]),[h,p]=o(!1),[f,g]=o(null),[b,v]=o(!1),x=ks(),w=y(),{checkDocumentProcessing:N}=Ts(),k=async(e,t)=>{console.log("Files dropped on ObjectTable:",e.length,t),d(!0);try{if(a){const t=await N(e,null,a);g(t);const n=t.filter(e=>"create"===e.action).length,r=t.filter(e=>"update"===e.action).length,i=t.filter(e=>"skip"===e.action).length;w({title:"Files ready to process",description:`${e.length} file(s): ${n} new, ${r} to update, ${i} 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),s){console.log("Skipping type modal and calling onUpload directly",{filesLength:e.length,processedFilesLength:f?.length});const t=i(e,null,a);t&&"object"==typeof t&&(t.processedFiles=f)}else console.log("Setting typeSelectionOpen to true",{filesLength:e.length}),v(!0)}},C=e=>{const t=[...u];m([]),g(null),v(!1),t.length>0&&void 0!==e&&(d(!0),console.log("Starting upload with",{typeId:e,filesCount:t.length,hasProcessingResults:!!f,collectionId:a}),i(t,e,a).finally(()=>{d(!1),x.search()}))},S=e=>{e.preventDefault(),e.stopPropagation(),p(!0)};return t("div",{className:"min-h-[400px] relative",onDragOver:S,onDragEnter:S,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(V,{size:"xl"})}),e(Ds,{...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(rn,{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(Is,{isOpen:b&&u.length>0,onClose:()=>{m([]),g(null),v(!1),C(void 0)},files:u,collectionId:a,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),v(!1),e&&e.success&&e.objectIds.length>0?C(null):C(void 0)}})]})}function Ds({objects:t,layout:n=zs,isLoading:r,onRowClick:i,onSelectionChange:a,previewObject:s,selectedObject:o,isGridView:c}){const d=ms(),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 i=r+1;i<n;i++)e.push(t[i]);d.addAll(e)}else{const e=function(e,t,n){const r=e.length;for(let i=t+1;i<r;i++)if(n.isSelected(e[i].id))return i;return-1}(t,n,d);if(e>-1&&e>n+1){const r=[];for(let i=n+1;i<e;i++)r.push(t[i]);d.addAll(r)}}}}else d.remove(e.id);a&&a(d)}},m=e=>{if(d){e.target.checked?d.addAll(t):d.removeAll()}},h=l(()=>(n.length>0?n:zs).map(e=>new bs(e,s)),[n,s]);return e(c?xs:vs,{objects:t,isLoading:r,columns:h,onRowClick:i,previewObject:s,selectedObject:o,selection:d,toggleAll:m,onSelectionChange:u})}function $s({children:t,limit:n,parent:r,typeId:i,facets:a,name:s,collectionId:o}){const{store:c}=Et(),d=l(()=>{let e;a?e=a:(e=[{name:"status",field:"status"},{name:"location",field:"location"}],i||e.unshift({name:"type",field:"type"}));const t=new ws(c,n).withFacets(e);return t.collectionId=o,t.query.type=i,t.query.parent=r,t.query.name=s,t},[i,n,o]);return e(Ns.Provider,{value:d,children:t})}const Ls=[{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 Os({onChange:t}){return e($s,{children:e(Us,{onRowClick:e=>{t(e||void 0)}})})}const Rs="vertesia.content_store.lastDisplayedView";function Us({onRowClick:n}){const[r,i]=o(!1),[a,s]=o("grid"===localStorage.getItem(Rs)),{search:l,isLoading:d,error:u,objects:h}=Ss(),p=m(null);de(p,()=>{r&&l.loadMore(!0)},{deps:[r]}),c(()=>{l.search().then(()=>i(!0))},[]);const f=Cs(),g=ks();return u?e(O,{title:"Search failed",children:u.message}):t("div",{children:[t("div",{className:"flex justify-between items-center mb-4",children:[e(Xa,{facets:f,search:g}),t("div",{className:"flex items-center gap-2",children:[e(v,{variant:"outline",onClick:()=>{i(!1),l.search().then(()=>i(!0))},alt:"Refresh",children:e(mt,{size:16})}),e(Rr,{onUpdate:s})]})]}),e(Es,{objects:h||[],isLoading:!1,layout:Ls,onRowClick:n,isGridView:a}),e("div",{ref:p,className:"mt-10"}),d&&e("div",{className:"flex justify-center",children:e(V,{size:"xl"})})]})}function Ms({isOpen:n,onClose:r}){return t(q,{onClose:()=>r(),isOpen:!!n,className:"min-w-[60vw]",children:[e(B,{children:"Select Content"}),e(W,{className:"pt-0 overflow-y-auto max-h-[80vh] min-h-[80vh]",children:n&&e(Os,{onChange:r})})]})}const Vs=/store:([a-f0-9]+)/;function Ks({object:n}){const{client:i}=Et(),{off:a,on:s,isOn:l}=ue(),[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(Vs);e&&i.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(me.INPUT,"pr-10 w-full")}),m&&e("div",{className:"absolute inset-y-0 right-10 flex items-center justify-center ",children:e(v,{onClick:p,variant:"unstyled",className:"hover:text-red-500 hover:bg-gray-100 dark:hover:bg-gray-600",children:e(it,{className:"size-5"})})}),e("div",{className:"absolute inset-y-0 right-0 flex items-center justify-center",children:e(v,{onClick:s,variant:"unstyled",className:"hover:bg-gray-100 dark:hover:bg-gray-600",children:e(vt,{className:"size-5"})})}),e(Ms,{value:d,isOpen:l,onClose:e=>{if(e){const t="store:"+e.id;u(t),h(e||void 0),n.value=t}a()}})]}),m&&e("div",{className:"p-1 semibold text-sm text-gray-600 dark:text-slate-300",children:m.properties?.title||m.name})]})}function 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 Bs({objectId:n,isOpen:r,onClose:i}){const a=Yt(),{client:s,store:l}=Et(),[d,u]=o(null),[m,h]=o(!1),[p,f]=o(!1),[g,b]=o(),[x,w]=o(),[N,k]=o("preview"),C=y();c(()=>{n&&r?(h(!0),l.objects.retrieve(n,"+embeddings").then(e=>{u(e),e.text?b(e.text):S(e.id);const t=e.content;t&&t.source&&t.type&&t.type.startsWith("image/")&&P(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),b(void 0),w(void 0))},[n,r,l.objects]);const S=async e=>{f(!0);try{const t=await l.objects.getObjectText(e);b(t.text)}catch(e){console.error("Error loading text:",e)}finally{f(!1)}},P=async e=>{try{"found"===(await s.objects.getRendition(e.id,{format:Ot.jpeg,generate_if_missing:!1})).status&&console.log("Found rendition");const t=await s.files.getDownloadUrl(e.content.source);w(t.url)}catch(e){console.error("Error loading image:",e)}},j=()=>{d&&(a(`/legal/objects/${d.id}`),i())},_=g&&(g.startsWith("#")||g.includes("\n#")||g.includes("\n*")),T=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(xt,{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(v,{variant:"ghost",size:"sm",onClick:j,className:"flex items-center gap-1 text-indigo-600 hover:text-indigo-800",children:[e(at,{className:"h-4 w-4"}),e("span",{children:"Full View"})]}),e(v,{variant:"ghost",size:"sm",onClick:i,className:"flex items-center text-gray-600 hover:text-gray-800 dark:text-gray-300 dark:hover:text-gray-100",children:e(it,{className:"h-5 w-5"})})]})]}),m?e("div",{className:"flex-1 flex items-center justify-center",children:t("div",{className:"text-center",children:[e(V,{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(He,{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(Le,{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(V,{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:_?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(Zt,{children:g})}):e("pre",{className:"text-wrap whitespace-pre-wrap dark:text-gray-200",children:g})}):null,T&&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(V,{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(xt,{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(v,{onClick:j,className:"bg-indigo-600 hover:bg-indigo-700 text-white",children:"Open Full Document View"})]}),!T&&!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(xt,{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(tn,{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(Le,{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?Ws(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(v,{onClick:()=>{d?.content?.source&&s.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(rt,{className:"h-4 w-4 mr-2"}),"Download"]})}),t(v,{onClick:j,className:"bg-indigo-600 hover:bg-indigo-700 text-white",children:["Open Full Document",e(wt,{className:"h-4 w-4 ml-2"})]})]})]}):null}function Ws(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 Gs=Object.values(Gt),Hs=Object.values(Ht);function Js({onChange:n,isLoading:r,refresh:i,searchTypes:a}){const{client:s,project:l}=Et(),d=y(),[u,m]=o(void 0),[h,p]=o(void 0),f=!(!l||!h?.embeddings.text&&!h?.embeddings.image),[g,b]=o(void 0),[x,w]=o(!1),[N,k]=o(a||Gs),[C,S]=o(100);c(()=>{a&&k(a)},[a]);const P={};let I=!1,A=!1;N.forEach(e=>{e===Gt.full_text?I=!0:A=!0,Hs.includes(e)&&(P[e]=!0)}),c(()=>{m(void 0),b(void 0)},[i]),c(()=>{l&&s.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 F=()=>{if(!f||!u)return;n({vector:A?{text:u,config:P}:void 0,full_text:I?u:void 0,limit:C}),b("Searching...")},D=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(z,{placeholder:"Type what you are looking for, or select a filter",value:u,onChange:m,onKeyDown:e=>{"Enter"===e.key&&F()}}),e(v,{variant:"ghost",onClick:()=>w(!0),alt:"Semantic search settings",className:"ml-1",children:e(Nt,{size:18})}),t(j,{isOpen:x,onClose:()=>w(!1),children:[e(_,{children:"Search Types"}),e(T,{children:t("div",{className:"flex flex-col gap-2",children:[t("label",{className:"flex items-center gap-2",children:[e(he,{checked:N.includes(Gt.full_text),onCheckedChange:D(Gt.full_text)}),e("span",{children:"Full Text"})]}),e("div",{className:"font-semibold mt-2 mb-1",children:"Embeddings"}),Hs.map(n=>t("label",{className:"flex items-center gap-2",children:[e(he,{checked:N.includes(n),onCheckedChange:D(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(pe,{type:"number",min:1,value:C,onChange:e=>S(Number(e)||1),style:{width:80}})]})]})}),e(E,{children:e(v,{variant:"outline",onClick:()=>w(!1),children:"Close"})})]}),e(v,{variant:"secondary",isLoading:r,onClick:F,isDisabled:!f,alt:"Semantic search",children:"Search"})]})}const Ys=[{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 Zs({onUploadDone:t=async()=>{},layout:n}){const r=ks(),i=y(),a=As(async e=>{await t(e),setTimeout(()=>{console.log("Delayed refresh after upload to ensure backend consistency"),r.search().then(()=>{i({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(Qs,{layout:n,onUpload:(e,t)=>{const n=r.collectionId;return a(e,t,n)}})}function Qs({layout:n,onUpload:r,allowFilter:i=!0,allowSearch:a=!0}){const s=ks(),[l,d]=o(!1),[u,h]=o(null),{typeRegistry:p}=Et(),{search:f,isLoading:g,error:y,objects:b,hasMore:v}=Ss(),[x,w]=o(p?n||(N=p,((k=f.query.type)?N.getTypeLayout(k):Ys)??Ys):Ys);var N,k;const[C,S]=o(0),[P,j]=o(0),[_,T]=o("grid"===localStorage.getItem(Rr.LAST_DISPLAYED_VIEW)),[I,A]=o([]),z=m(null);c(()=>{l||0!==b.length||(j(0),f._updateRunningState(!0),f.search().then(()=>{d(!0)}).catch(e=>{console.error("Initial search failed:",e),f._updateRunningState(!1)}))},[]),c(()=>{b.length<P&&j(b.length)},[b.length,P]),de(z,()=>{l&&b.length>0&&b.length!=P&&(d(!1),f.loadMore().finally(()=>{j(b.length),d(!0)}))},{deps:[l,b.length]});const E=Cs(),F=ks(),D=Za(E),$=Qa(F),L=new URL(window.location.href),R=L.searchParams.get("filters");if(R)try{const e=R.split(";"),t=e.filter(e=>{const[t]=e.split(":"),n=decodeURIComponent(t);return"start"!==n&&"end"!==n});if(t.length!==e.length){const e=t.length>0?t.join(";"):"";e?L.searchParams.set("filters",e):L.searchParams.delete("filters"),window.history.replaceState(window.history.state||{},"",L.toString())}}catch(y){console.error("Failed to clean start/end filters from URL:",y)}const U=Yt();return t("div",{className:"flex flex-col gap-y-2",children:[e(el,{object:u,onClose:()=>h(null)}),y&&e(O,{title:"Error",children:y.message}),e(Xs,{isLoading:g,refreshTrigger:C,allowFilter:i,allowSearch:a,filterGroups:D,filters:I,handleFilterChange:e=>{const t="function"==typeof e?e(I):e;A(t),$(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:T}),e(Es,{objects:b,isLoading:!b.length&&g,layout:x,onRowClick:e=>{U(`/objects/${e.id}`)},previewObject:e=>{const t=b.find(t=>t.id===e)||null;h(t)},selectedObject:u,onUpload:r,isGridView:_,collectionId:s.collectionId}),e("div",v?{ref:z,className:"w-full flex justify-center",children:e(V,{size:"xl"})}:{className:"text-muted text-center text-sm py-1",children:`All ${b.length} objects loaded.`})]})}function Xs(n){const{isLoading:r,refreshTrigger:i,allowFilter:a,allowSearch:s,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:[a&&t(te,{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:[s&&e(Js,{onChange:d,isLoading:r,refresh:i,className:"w-full"}),e(ne,{})]}),t("div",{className:"flex gap-1 items-center",children:[e(v,{variant:"outline",onClick:u,alt:"Refresh",children:e(mt,{size:16})}),e(Rr,{onUpdate:m})]})]}),t("div",{className:"flex gap-2 items-center pt-2",children:[e(re,{}),e(ie,{})]})]}),!a&&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:s&&e(Js,{onChange:d,isLoading:r,refresh:i})}),t("div",{className:"flex gap-1 items-center",children:[e(v,{variant:"outline",onClick:u,alt:"Refresh",children:e(mt,{size:16})}),e(Rr,{onUpdate:m})]})]})]})}function el({object:n,onClose:r}){const{store:i}=Et(),a=y(),s=Yt(),l=qs(i,a,n?.content?.source,n?.name||n?.content?.name);return n?t(fe,{title:n.properties?.title||n.name,isOpen:!0,onClose:r,children:[t("div",{className:"flex items-center gap-x-2",children:[e(v,{variant:"ghost",size:"sm",title:"Open Object",onClick:()=>s(`/objects/${n.id}`),children:e(Be,{className:"size-4"})}),n.content?.source&&e(v,{variant:"ghost",size:"sm",title:"Download",onClick:l,children:e(rt,{className:"size-4"})})]}),e(ge,{className:"my-2"}),e("div",{className:"pt-2",children:e(sa,{object:n,loadText:!0},n.id)})]}):null}var tl;function nl({isExporting:n,isOpen:r,onClose:i}){return t(j,{onClose:()=>i(void 0),isOpen:r,className:"relative overflow-visible",children:[e(_,{children:"Export Object Properties"}),!n&&e(rl,{onClose:i}),n&&e(il,{})]})}function rl({onClose:n}){const[r,i]=o(void 0),[a,s]=o(void 0),l=["Export selected objects","Export all objects"];return t(T,{className:"min-h-[104px] pt-0 flex flex-col gap-y-4",children:[e("div",{className:"h-1/3",children:e(Z,{options:l,value:a,onChange:s,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(Z,{options:Object.values(tl),value:r,onChange:i,placeholder:"Choose a format",className:"h-full w-full text-sm",filterBy:"name",isClearable:!0}),e(v,{className:"w-full",isDisabled:!r||!a,onClick:()=>{n(r,a==l[1])},children:"Export Properties"})]})]})}function il({}){return e(T,{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(V,{size:"lg"})]})})}function al({collection:t}){const n=y(),{client:r,typeRegistry:i}=Et();ks().query.all_revisions=!0;const a=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,i);return t.dynamic?e(Qs,{layout:a}):e(Zs,{onUploadDone:async e=>{e.length>0&&await r.store.collections.addMembers(t.id,e).catch(e=>{n({title:"Failed to add objects to collection",description:e.message,status:"error"})})},layout:a})}!function(e){e.CSV="CSV",e.JSON="JSON"}(tl||(tl={}));const sl=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 ll({className:t,defaultValue:n,onChange:r,isClearable:i,multiple:a}){const s=Et(),[l,d]=o(!1),[u,m]=o(),[h,p]=o([]);c(()=>{if(!l&&(d(!0),s.typeRegistry&&n)){if(a&&Array.isArray(n)){const e=s.typeRegistry.types.filter(e=>n.includes(e.id));p(e)}const e=s.typeRegistry.types.find(e=>e.id===n);e&&m(e)}},[s.typeRegistry,n,a]);const f=e=>{p(e),r(e)};return e("div",a?{className:"flex flex-col gap-4 content-between",children:e(ce,{options:s.typeRegistry?.types||[],value:h,onChange:f,placeholder:"Choose Content Types...",optionLabel:sl,className:t||"text-sm bg-background",filterBy:"name",isClearable:i||!1,multiple:!0})}:{className:"flex flex-col gap-4 content-between",children:e(ce,{options:s.typeRegistry?.types||[],value:u,onChange:e=>{m(e||void 0),r(e)},placeholder:"Choose a Content Type...",optionLabel:sl,className:t||"text-sm bg-background",filterBy:"name",isClearable:i||!1})})}function ol({onClose:n,redirect:r=!0,onAddToCollection:i}){const a=Yt(),s=y(),[l,c]=o(!1),{client:d}=Et(),[u,m]=o({dynamic:!1,name:"",description:""});function h(e,t){m({...u,[e]:t})}return t("form",{onSubmit:e=>e.preventDefault(),children:[t(W,{children:[e(A,{label:"Name",required:!0,children:e(z,{type:"text",value:u.name||"",onChange:e=>h("name",e)})}),e(A,{label:"Description",className:"mt-2",children:e(ye,{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(be,{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(ll,{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(ll,{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(G,{children:e(v,{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(),s({title:"Collection created",description:`Collection "${e.name}" created successfully`,status:"success",duration:3e3}),r&&a(`/collections/${e.id}`),i&&i(e.id)}).catch(e=>{s({title:"Failed to create collection",description:e.message,status:"error",duration:5e3})}).finally(()=>c(!1))):s({title:"Name is required",description:"Please provide a name for the collection",status:"error",duration:5e3})},children:"Create Collection"})})]})}function cl({isOpen:n,onClose:r}){return t(q,{onClose:r,isOpen:n,children:[e(B,{children:"Create a Collection"}),e(ol,{onClose:r})]})}function dl({}){const{client:r}=Et(),i=y(),[a,s]=o(),[l,d]=o(!0),[u,m]=o(!1),{data:h,error:p,refetch:f}=L(()=>r.store.collections.search({}),[]);if(c(()=>{(h||p)&&d(!1)},[h,p]),p)return e(O,{title:"Collections fetch failed",children:p.message});return t(n,{children:[h&&(h.length>0?t(ee,{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(ae,{columns:4,isLoading:l,children:h.map(n=>t(ve,{children:[e("td",{children:t("div",{className:"flex items-center gap-2",children:[ul(n.dynamic),e(Jt,{href:`/collections/${n.id}`,children:n.name})]})}),e("td",{children:n.type?.name||"-"}),e("td",{children:un(n.created_at).fromNow()}),e("td",{className:"text-right",children:e(v,{variant:"destructive",size:"sm",onClick:()=>s(n.id),children:e(kt,{className:"size-4"})})})]},n.id))})]}):e(xe,{title:"No Collections",buttonLabel:"New Collections",onClick:()=>m(!0),children:"Get started by creating a new Collections."})),e(cl,{isOpen:u,onClose:()=>m(!1)}),e(we,{isOpen:!!a,title:"Delete Collection",content:"Are you sure you want to delete this collection? This action cannot be undone.",onConfirm:async()=>{if(a)try{await r.store.collections.delete(a),i({title:"Collection deleted",status:"success",duration:3e3}),f()}catch(e){console.error("Failed to delete collection:",e),i({title:"Failed to delete collection",description:e.message||"An error occurred",status:"error",duration:5e3})}finally{s(void 0)}},onCancel:()=>s(void 0)})]})}function ul(t){const n=t?"Dynamic Collection":"Static Collection",r=e(t?Ct:St,{className:"size-5"});return e($,{description:n,className:"mr-2",children:r})}function ml({objects:n,isLoading:r}){const i=Yt();return e("div",{children:t(ee,{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(ae,{isLoading:r,columns:3,children:n?.map(n=>t("tr",{onClick:()=>i(`/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:un(n.updated_at).fromNow()})]},n.id))})]})})}un.extend(vn),un.extend(vn);class hl{client;limit;result=new se({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 pl=d(void 0);function fl(){return u(pl)}function gl(){const e=fl();return{...le(e.result),search:e}}function yl(){return fl().objects.length}function bl({title:n,isOpen:r,onClose:i,okLabel:a,initialPayload:s}){const l=y(),[c,d]=o(s?.name),[u,m]=o(s?.description),[h,p]=o(s?.strict_mode??!1);return t(j,{isOpen:r,onClose:()=>i(),children:[e(_,{children:n}),e(T,{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(z,{value:c,onChange:d})]}),t("div",{children:[e("label",{className:"block text-sm font-medium text-muted",children:"Description"}),e(ye,{value:u,onChange:e=>m(e.target.value)})]})]})}),e(E,{children:t("div",{className:"flex justify-end gap-4",children:[e(v,{variant:"secondary",onClick:()=>i(),children:"Cancel"}),e(v,{variant:"primary",onClick:()=>(()=>{if(!c)return void l({status:"error",title:"Name is required",duration:5e3});i({name:c,description:u,strict_mode:h}).then(()=>i()),d(void 0),m(void 0),p(!1)})(),children:a})]})})]})}var vl;function xl({isDirty:n=!1}){const r=Et(),{store:i}=r,a=y(),[s,l]=o(!1),{search:d,isLoading:u,error:h,objects:p}=gl(),[f,g]=o(""),b=Ne(f,500),v=m(null);de(v,()=>{s&&d.loadMore()},{deps:[s]}),c(()=>{d.search().then(()=>l(!0))},[]),c(()=>{d.query.name=f,d.search().then(()=>l(!0))},[b]);const[x,w]=o(void 0);c(()=>{d.query.chunkable=x?"Yes"==x:void 0,d.search().then(()=>l(!0))},[x]),c(()=>{n&&s&&d.search().then(()=>l(!0))},[n]);const[N,k]=o(!1);if(h)return e(O,{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(z,{placeholder:"Filter by Name",value:f,onChange:g}),e(Z,{className:"w-60",isClearable:!0,options:Object.values(vl),value:x,onChange:e=>{w(e)},placeholder:"Is Chunkable"})]}),t("div",{className:"flex-1",children:[u||0!==p?.length?e(ml,{objects:p,isLoading:u}):e(xe,{title:"No Type",buttonLabel:"Create Type",onClick:()=>{k(!0)},children:"Get started by creating a new Type."}),e(bl,{okLabel:"Create",title:"Create Type",isOpen:N,onClose:async e=>e?i.types.create(e).then(async()=>{a({status:"success",title:"Type created",duration:2e3}),r.reloadTypes(),d.search().then(()=>l(!0))}).catch(e=>{a({status:"error",title:"Error creating type",description:e.message,duration:5e3})}):(k(!1),Promise.resolve())})]})]})}!function(e){e.true="Yes",e.false="No"}(vl||(vl={}));const wl=[Sn,wn()];function Nl({objectType:n,onSchemaUpdate:r}){const{store:i}=Et(),a=y(),[s,c]=o(!1),d=sn(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);kl(t),d.replaceSchema(t)}catch(e){return a({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(v,{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(v,{isLoading:s,variant:"outline",size:"sm",onClick:()=>{h&&!g()||(c(!0),i.types.update(n.id,{object_schema:d.schema}).then(()=>{r(d),a({status:"success",title:"Schema updated",description:"The schema has been updated successfully",duration:2e3})}).catch(e=>{a({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(ln,{value:f,extensions:wl,editorRef:u}):e(on,{schema:d})})]})}const kl=e=>{try{new hn({strict:!1}).compile(e)}catch(e){throw new Error(`Invalid JSON Schema definition: ${e.message}`)}};function Cl({children:t,limit:n,name:r,chunkable:i}){const{store:a}=Et(),s=l(()=>{const e=new hl(a,n);return e.query.name=r,e.query.chunkable=i,e},[n]);return e(pl.Provider,{value:s,children:t})}function Sl({isOpen:n,onClose:r,title:i="Select Content Type",children:a,initialSelectedType:s=null,confirmLabel:l="Select Type",allowNone:c=!0}){const{typeRegistry:d}=Et(),[u,m]=o(s),h=d?.types||[],p=()=>{r(void 0)};return t(j,{isOpen:n,onClose:p,className:"w-full max-w-xl mx-auto",children:[e(_,{children:i}),t(T,{className:"p-6",children:[a,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(Z,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(pt,{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(v,{variant:"ghost",onClick:p,children:"Cancel"}),e(v,{onClick:()=>{r(u?.id??null)},children:u?`${l}: ${u.name}`:c?"Let Vertesia Choose":l})]})]})}const Pl=[Sn,wn()];function jl({objectType:n,onLayoutUpdate:r}){const i=y(),[a,s]=o(!1),{store:c}=Et(),d=m(void 0),u=l(()=>_l(n.table_layout),[n.table_layout]),h=(e,t)=>{i({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(v,{isLoading:a,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?}"):(s(!0),void c.types.update(n.id,{table_layout:t}).then(e=>{i({status:"success",title:"Table Layout updated",description:"The table layout has been updated successfully",duration:2e3}),r(e.table_layout)}).catch(e=>{i({status:"error",title:"Failed to update table layout",description:e.message,duration:5e3})}).finally(()=>{s(!1)})):h("Invalid JSON","The table layout must be an array")},children:"Save Changes"})})]}),e("div",{className:"px-4 py-2",children:e(ln,{value:u,extensions:Pl,editorRef:d})})]})}function _l(e){return e?JSON.stringify(e,null,2):"[\n\n]"}const Tl=[Sn,wn()];function Il({refetch:r,collection:i}){const a=i.type?.id,s=m(void 0),c=y(),{client:d}=Et(),[u,h]=o(!1),[p,f]=o({name:i.name,description:i.description||"",query:i.query?JSON.stringify(i.query,null,2):"",tags:i.tags||[],type:i.type?.id||"",allowed_types:i.allowed_types||[]}),g=l(()=>_l(i.table_layout),[i.table_layout]),b=(e,t)=>{f({...p,[e]:t})};return t("div",{className:"flex flex-col gap-4 py-2",children:[t(ke,{title:"Configuration",action:e(v,{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(s.current){const e=s.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(i.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(Nn,{userRef:i.created_by,showTitle:!0}),t("span",{children:["at ",un(i.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(Nn,{userRef:i.updated_by,showTitle:!0}),t("span",{children:["at ",un(i.updated_at).format("YYYY-MM-DD HH:mm:ss")]})]})]})]}),e(A,{label:"Name",required:!0,children:e(z,{value:p.name,onChange:e=>b("name",e)})}),e(A,{label:"Description",children:e(ye,{value:p.description,onChange:e=>b("description",e.target.value)})}),!i.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(ll,{defaultValue:p.allowed_types||null,onChange:e=>{Array.isArray(e)?b("allowed_types",e.map(e=>e.id)):b("allowed_types",e?[e.id]:[])},isClearable:!0,multiple:!0})}),i.dynamic&&e(A,{label:"Query",description:"Define the query to dynamically fetch content for the collection.",children:e(ye,{className:me.INPUT,value:p.query,onChange:e=>b("query",e.target.value)})}),e(A,{label:"Table Layout",description:"Define a custom layout for displaying the collection in tables.",children:e(ln,{className:"border-1 rounded-md border-border",value:g,extensions:Tl,editorRef:s})}),e(A,{label:"Type",description:"Select a content type to assign custom properties and data to the collection.",children:e(ll,{defaultValue:p.type||null,onChange:e=>{Array.isArray(e)?b("type",e.length>0?e[0].id:null):b("type",e?.id||null)},isClearable:!0})})]}),a&&e(Al,{typeId:a,collection:i}),!i.dynamic&&t(n,{children:[e(kn,{collection:i}),e(Cn,{collection:i})]})]})}function Al({typeId:t,collection:n}){const[r,i]=o({}),a=y(),{client:s}=Et(),[c,d]=o(!1),{data:u,error:m}=L(()=>s.store.types.retrieve(t),[t]),h=u?.object_schema||{},p=l(()=>new cn(h,n.properties||{}),[h,n.properties]);if(m)return e(O,{title:"Failed to load type",children:m.message});if(!u)return null;return e(ke,{title:"Properties",action:e(v,{size:"lg",isLoading:c,type:"submit",onClick:()=>(e=>{if(!e||!Object.keys(e).length)return;const t={properties:e||{}};d(!0),s.store.collections.update(n.id,t).then(()=>{a({title:"Collection properties updated",description:"Collection has been updated successfully",status:"success",duration:3e3})}).catch(e=>{a({title:"Failed to update collection properties",description:e.message,status:"error",duration:5e3})}).finally(()=>{d(!1)})})(r),children:"Save"}),children:e(dn,{object:p,onChange:e=>{e instanceof cn&&i(e.value)}})})}function zl({onChange:n,value:r,disabled:i=!1,placeholder:a="Select a collection",searchPlaceholder:s="Search collections",filterOut:c,allowDynamic:d=!0,multiple:u=!1}){const{client:m}=Et(),[p,f]=o(""),[y,b]=o(!1),[C,j]=o(!1),_=Ne(p,300),T=h(async e=>{b(!0);const t=e.trim(),n=await m.store.collections.search({dynamic:!!d&&void 0,name:C&&t||void 0});return b(!1),!C&&n.length>=1e3&&j(!0),c&&c.length>0?n.filter(e=>!c.includes(e.id)):n},[m,d,c,C]),{data:I,error:A}=L(()=>T(C?_:""),[C?_:"",T]),z=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=h(e=>{if(u){const t=Array.isArray(r)?r:[];if(t.includes(e.id)){const r=t.filter(t=>t!==e.id),i=I?.filter(e=>r.includes(e.id))||[];n(r,i)}else{const r=[...t,e.id],i=I?.filter(e=>r.includes(e.id))||[];n(r,i)}}else n(e.id,e)},[n,r,I,u]),F=h(()=>{n(void 0,void 0)},[n]),D=h(e=>{f(e)},[]),$=p.trim().length>0,R=l(()=>{if(!I)return[];if(C)return I;if(!$)return I;const e=p.toLowerCase();return I.filter(t=>t.name.toLowerCase().includes(e))},[I,C,$,p]),U=z&&$;if(A)return e(O,{title:"Collection fetch failed",children:A.message});return t(x,{children:[e(w,{asChild:!0,children:t(v,{variant:"outline",role:"combobox","aria-haspopup":"listbox",className:g("w-full justify-between min-w-0"),disabled:i,children:[e("span",{className:"truncate flex-1 text-left min-w-0",children:u&&Array.isArray(z)&&z.length>0?1===z.length?z[0].name:`${z.length} collections selected`:u||!z||Array.isArray(z)?a:z.name}),e(vt,{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(Ce,{placeholder:s,value:p,onValueChange:D,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"}),y&&e("div",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"})]}),e(Se,{children:y?"Searching...":$?"No collections found.":"No collections available."}),t(S,{className:"max-h-[300px] overflow-auto",children:[U&&!u&&e(P,{value:"__clear__",onSelect:F,className:"text-muted-foreground",children:"Clear selection"}),R.map(n=>{const i=u&&Array.isArray(r)?r.includes(n.id):r===n.id;return t(P,{value:n.id,onSelect:()=>E(n),className:"flex items-center justify-between",children:[e("span",{className:"truncate",children:n.name}),i&&e(Pt,{className:"ml-2 h-4 w-4 shrink-0"})]},n.id)})]})]})})]})}function El({collection:t}){const{client:n}=Et(),[r,i]=o(void 0),[a,s]=o(t.shared_properties||[]),l=y();c(()=>{t.type?.id&&n.store.types.retrieve(t.type.id).then(i)},[t.type?.id]);const d=r?Object.keys(r.object_schema?.properties||{}):[];return e(ke,{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(v,{size:"lg",isLoading:!1,onClick:()=>{n.store.collections.update(t.id,{shared_properties:a}).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(Pe,{value:a,onChange:e=>{s(e)},options:d,placeholder:"Select properties to share"})})})}function Fl({collection:t}){const{client:n}=Et(),[r,i]=o(t.skip_head_sync??!1),[a,s]=o(!1),l=y();return e(ke,{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(be,{disabled:a,value:!r,onChange:e=>{const r=!e;s(!0),n.store.collections.update(t.id,{skip_head_sync:r}).then(()=>{l({title:"Updated skip head sync setting",status:"success"}),i(r)}).catch(e=>{l({title:"Failed to update skip head sync",description:e.message,status:"error"})}).finally(()=>{s(!1)})},children:"Enable synchronizing member heads"})})}function Dl({action:n,objectIds:r,children:i}){const{store:a}=Et(),s=y(),[l,c]=o(!1),d=h(()=>(c(!0),Promise.resolve(!0)),[]);to(n.id,d);return t("div",{children:[i,e(Sl,{isOpen:l,onClose:e=>{c(!1),void 0!==e&&a.runOperation({name:"change_type",ids:r,params:{typeId:e}}).then(e=>{s({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=>{s({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 $l={id:"changeType",name:"Change Content Type",description:"Change the Content Type of the selected documents",confirm:!1,component:Dl};function Ll({action:r,callback:i,children:a}){const[s,l]=o(!1),c=r.confirmationText||`Are you sure you want to ${r.name}?`,d=h(e=>r.confirm?(l(!0),Promise.resolve(!0)):i(e),[r.confirm,i]),u=to(r.id,d);return t(n,{children:[a,e(we,{onConfirm:()=>{l(!1),i({...u.params,action:r})},onCancel:()=>l(!1),title:"Are you sure?",content:c,isOpen:s})]})}function Ol({action:t,objectIds:n,children:r}){const i=eo(),a=y(),{client:s}=Et(),l=ks(),o=Yt(),c=h(()=>{if(!n||!n.length)return a({status:"error",title:"No objects selected",description:"Please select objects to delete",duration:3e3}),Promise.resolve(!1);function e(e,t){if(e.length<=t)return e;const n=e.lastIndexOf("."),r=-1!==n?e.substring(n):"";return`${(-1!==n?e.substring(0,n):e).substring(0,t-r.length-3)}...${r}`}return Promise.all(n.map(e=>s.store.objects.delete(e))).then(t=>{const r=t.length>1?"s":"";if(a({status:"success",title:`${t.length} object${r} deleted`,description:`Objects ${e(t.map(e=>e.id).join(", "),100)} have been deleted`,duration:2e3}),l){i.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=>{a({status:"error",title:"Error deleting objects",description:e.message,duration:5e3})})},[n]);return e(Ll,{action:t,callback:c,children:r})}const Rl={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:Ol,destructive:!0},Ul={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:Ol,destructive:!0};function Ml({action:t,objectIds:n}){const{store:r}=Et(),i=y(),[a,s]=o(!1),[l,c]=o(!1),d=h(()=>(s(!0),Promise.resolve(!0)),[]),u=to(t.id,d);return e("div",{children:e(nl,{isExporting:l,isOpen:a,onClose:(e,t)=>{if(e&&(t||n.length>0)){c(!0);const a=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?a.vector?l:[]:0===n.length?[]:(await o(n[0])).concat(n):n)().then(l=>{r.objects.exportProperties({objectIds:l,type:e,query:t&&!a.vector?a:{type:a.type}}).then(r=>{let a;if(e===tl.CSV)a=new Blob([r.data],{type:r.type});else if(e===tl.JSON)a=new Blob([JSON.stringify(r.data)],{type:r.type});else{const e=r.data;a=new Blob([new Uint8Array(e.data)],{type:r.type})}const s=window.URL.createObjectURL(a),l=document.createElement("a");l.download=r.name,l.href=s,l.click(),i({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=>{i({status:"error",title:"Error Export Properties",description:e.message,duration:5e3})}).finally(()=>{c(!1),s(!1)})})}else s(!1)}})})}const Vl={id:"exportProperties",name:"Export Properties",description:"Export all Object Properties",confirm:!1,component:Ml};function Kl({action:t,objectIds:n,collectionId:r}){const i=eo(),a=y(),{client:s}=Et(),l=ks(),o=h(()=>n&&n.length?r?s.store.collections.deleteMembers(r,n).then(()=>{const e=n.length>1?"s":"";a({status:"success",title:`${n.length} object${e} removed from collection`,description:"Objects have been removed from the collection",duration:2e3}),l&&(i.params?.selection?.removeAll(),l.search())}).catch(e=>{a({status:"error",title:"Error removing objects from collection",description:e.message,duration:5e3})}):(a({status:"error",title:"No collection context",description:"Cannot remove objects: no collection specified",duration:3e3}),Promise.resolve(!1)):(a({status:"error",title:"No objects selected",description:"Please select objects to remove from collection",duration:3e3}),Promise.resolve(!1)),[n,r]);return e(Ll,{action:t,callback:o})}const ql={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:Kl,destructive:!0};function Bl({action:t,objectIds:n,collectionId:r}){const i=y(),{client:a}=Et(),[s,l]=o(!1),c=h(()=>(l(!0),Promise.resolve(!0)),[]);return to(t.id,c),e(Gl,{isOpen:s,onClose:e=>{if(l(!1),e)return a.store.workflows.rules.execute(e,n,{collection_id:r}).then(()=>{i({title:"Workflow started",status:"success",duration:3e3})}).catch(e=>{i({title:"Error starting workflow",status:"error",description:e.message,duration:9e3})})}})}const Wl={id:"startWorkflow",name:"Start Workflow",description:"Start an workflow on the selected objects",confirm:!1,hideInList:!0,component:Bl};function Gl({isOpen:n,onClose:r}){return t(q,{onClose:()=>r(void 0),isOpen:n,className:"",children:[e(B,{children:"Start a Workflow by Rule"}),e(Jl,{onClose:r})]})}function Hl(n){return{label:t("div",{children:[e("div",{children:n.name}),e("div",{className:"text-sm text-muted",children:n.description})]}),reverse:!0}}function Jl({onClose:n}){const[r,i]=o(void 0),a=eo();return t("div",{children:[t(W,{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(je,{options:a.wfRules,optionLayout:Hl,onChange:e=>{i(e)},value:r})})]}),t(G,{children:[e(v,{variant:"secondary",onClick:()=>n(),children:"Cancel"}),e(v,{onClick:()=>{r&&n(r.id)},isDisabled:!r,children:"Start"})]})]})}class Yl{params;allActions=[Vl,$l,Wl,io,Rl,ql,Ul];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:Bl})).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 Zl=d(void 0);function Ql({children:n}){const r=us(),i=y(),{client:a}=Et(),s=ks(),{data:o,error:c}=L(()=>a.workflows.rules.list().then(e=>e.map(e=>({id:e.id,name:e.name,description:e.description,confirm:!1,isWorkflow:!0,component:Bl})).sort((e,t)=>e.name.localeCompare(t.name))),[]),d=l(()=>{const e=new Yl({selection:r,toast:i,client:a,search:s});return e.wfRules=o,e},[r,o]);return c?e(O,{title:"Failed to fetch workflows",children:c.message}):d&&t(Zl.Provider,{value:d,children:[e(Xl,{}),n]})}function Xl({}){const t=eo(),n=t.params.selection,r=n.getObjectId(),i=n.isSingleSelection()&&r?[r]:n.getObjectIds();return e("div",{style:{display:"none"},children:t.allActions.map(t=>e(t.component,{action:t,objectIds:i,collectionId:n.collectionId},t.id))})}function eo(){const e=u(Zl);if(!e)throw new Error("You cannot use useActionContext outside an ActionProvider");return e}function to(e,t){const n=eo();return c(()=>n.registerCallback(e,t),[n,e,t]),n}function no(e){const t=eo();return c(()=>(t.startWorkflow=e,()=>{t.startWorkflow=void 0}),[e,t]),t}function ro({action:t,objectIds:n}){const[r,i]=o(!1),a=h(()=>(n.length>0&&i(!0),Promise.resolve(!0)),[n]);return to(t.id,a),r&&e(K,{children:e(ao,{objectIds:n,isOpen:r,onClose:()=>{i(!1)}})})}const io={id:"addToCollection",name:"Add to Collection",description:"Add documents to a collection",confirm:!1,component:ro};function ao({isOpen:n,onClose:r,objectIds:i}){return t(q,{isOpen:n,onClose:r,className:"max-w-lg w-full min-w-0 overflow-hidden",children:[e(B,{className:"flex flex-col min-w-0 overflow-hidden",children:"Add to a Collection"}),e(_e,{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(so,{onClose:r,objectIds:i})})]})}function so({onClose:n,objectIds:r}){const i=y(),{client:a}=Et(),[s,l]=o(),c=({collectionId:e})=>{e&&r?.length&&a.store.collections.addMembers(e,r).then(()=>{i({title:"Add to collection success",status:"success",description:`Added ${r.length} objects to the selected collection`,duration:3e3}),n()}).catch(()=>{i({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(W,{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(zl,{onChange:(e,t)=>{"string"==typeof e||void 0===e?l(e):Array.isArray(e)&&e.length>0?l(e[0]):l(void 0)},value:s})})}),e(G,{children:e(v,{isDisabled:!s,onClick:()=>s&&c({collectionId:s}),children:"Add to Collection"})})]})},{name:"create",label:"Create new",content:e("div",{className:"p-4",children:e(ol,{onClose:n,onAddToCollection:e=>c({collectionId:e}),redirect:!1})})}];return t(Ie,{defaultValue:"select",tabs:d,fullWidth:!0,children:[e(Ae,{}),e(ze,{})]})}function lo(){const n=us(),r=n.size(),i=r>1?"s":"",a=n?.hasSelection(),s=n?.isSingleSelection();return e(Ql,{children:t("div",{className:"flex items-center gap-x-2",children:[a&&!s&&t("div",{className:"flex items-center gap-x-1 shrink-0",children:[t("div",{className:"text-sm nowrap",children:[r," document",i," selected"]}),e(v,{title:"Clear selection",variant:"ghost",onClick:()=>{n?.removeAll()},children:e(it,{className:"size-4"})})]}),e(ho,{selection:n,children:e(v,{variant:"ghost",alt:"More action",size:"sm",children:e(jt,{size:16})})}),a&&e(oo,{selection:n})]})})}function oo({}){return e(uo,{})}function co({collectionId:r}){const[i,a]=o([]),s=us(),l=s?.hasSelection();return!l&&t(n,{children:[e(v,{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&&a(Array.from(t))}})(),children:"Upload"}),e(Is,{collectionId:r??"",isOpen:i.length>0,onClose:()=>a([]),files:i,title:"Upload Files",onUploadComplete:e=>{e&&e.success&&a([])},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 uo(){const t=eo();return t.params.selection.hasSelection()&&e(v,{onClick:()=>t.run(Wl.id),children:"Start Workflow"})}function mo(e){return{label:e.name,className:r("flex-1 px-2 py-2 hover:bg-accent nowrap",e.destructive?"text-destructive":"")}}function ho({selection:n,children:r}){const i=eo();return t(x,{hover:!0,children:[e(w,{children:r}),e(N,{className:"p-0 w-50",align:"end",sideOffset:6,children:e(po,{executeAction:e=>{i.run(e.id)},selection:n})})]})}function po({executeAction:t,selection:n}){const r=eo(),i=n?.hasSelection()?r.actions.filter(e=>!e.hideInList):[Vl];return e("div",{className:"rounded-md shadow-md py-2",children:e("div",{className:"px-1 text-sm",children:e(je,{options:i,optionLayout:mo,onChange:e=>{t(e)},noCheck:!0})})})}function fo({onSend:n,disabled:r=!1,isSending:i=!1,isCompleted:a=!1,activeTaskCount:s=0,placeholder:l="Type your message..."}){const d=m(null),[u,h]=o(""),[p,f]=o(!1);c(()=>{!r&&a&&d.current?.focus()},[r,a]);const g=()=>{const e=u.trim();!e||r||i||(n(e),h(""))};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(z,{ref:d,value:u,onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),g())},onChange:h,disabled:r||i,placeholder:l,className:"pr-12 py-2.5"}),e(v,{variant:"ghost",className:"rounded-full",disabled:!a,onClick:()=>f(!0),alt:"Link Object",children:e(_t,{className:"size-4"})})]}),t(v,{onClick:g,disabled:r||i||!u.trim(),className:"px-4 py-2.5",children:[i?e(V,{size:"sm",className:"mr-2"}):e(Tt,{className:"size-4 mr-2"})," Send"]})]}),e("div",{className:"text-xs text-muted mt-2 text-center",children:s>0?t("div",{className:"flex items-center justify-center",children:[e(It,{className:"h-3 w-3 mr-1 text-attention"}),t("span",{children:["Agent has ",s," active workstream",1!==s?"s":""," running"]})]}):r?"Agent is processing, you can continue once it completes...":"You can send a message at any time"}),t(q,{isOpen:p,onClose:()=>f(!1),className:"min-w-[60vw]",children:[e(B,{children:"Link Object"}),e(W,{className:"pb-6",children:e(Os,{onChange:e=>{const t=`[${e.properties?.title||e.name||"Object"}](store:${e.id})`,n=u||"",r=d.current?.selectionStart||n.length,i=n.substring(0,r)+t+n.substring(r);h(i),f(!1),setTimeout(()=>{if(d.current){d.current.focus();const e=r+t.length;d.current.setSelectionRange(e,e)}},100)}})})]})]})}const go=s.memo(function({plan:r,workstreamStatus:i,isOpen:a,onClose:s,plans:l=[],activePlanIndex:o=0,onChangePlan:c=()=>{}}){return a?t("div",{className:"h-full shadow-xl border border-muted/20 overflow-hidden",children:[t("div",{className:"flex items-center justify-between p-3 border-b border-muted/20",children:[e("h3",{className:"font-bold text-base",children:"Plan"}),t(v,{variant:"ghost",onClick:s,children:[e(it,{className:"size-4"}),e("span",{className:"sr-only",children:"Close"})]})]}),t("div",{className:"p-3 overflow-y-auto",style:{height:"calc(100% - 44px)",maxHeight:"calc(100vh - 150px)"},children:[t("div",{className:"mb-3 p-2 bg-info rounded-md border border-info",children:[e("div",{className:"text-xs font-medium text-info mb-1",children:"Task Progress"}),e("div",{className:"flex items-center gap-2",children:(()=>{const a=r.plan||[],s=a.length;let l=0;s>0&&a.forEach(e=>{if(e&&e.id){const t=e.id.toString();"completed"===i.get(t)&&l++}});const o=s>0?Math.round(l/s*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:s>0?`${l}/${s}`:"0/0"})]})})()})]}),l.length>1&&t("div",{className:"mb-3 flex items-center justify-between",children:[e(v,{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(v,{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 a=n.id?n.id.toString():`task-${r}`,s=n.goal||`Task ${r+1}`;let l=n.status||"pending";i.has(a)&&(l=i.get(a));let o=At,c="text-muted";return"in_progress"===l?(o=Me,c="text-info"):"completed"===l&&(o=Ue,c="text-success"),t("div",{className:"flex p-3 my-1",children:[e("div",{className:"mr-2 mt-0.5 flex-shrink-0 text-muted",children:a}),t("div",{className:"w-full",children:[e("div",{className:"text-sm font-medium mb-2 text-muted",children:s}),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(b,{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(Oe,{className:"size-4 mx-auto mb-2 text-attention"}),e("p",{className:"text-xs",children:"No plan has been detected yet"}),e("p",{className:"text-xs mt-1",children:"Plans will appear here when the agent creates one"})]})})]}),(()=>{const n=new Set((r.plan||[]).filter(e=>e&&e.id).map(e=>e.id.toString())),a=Array.from(i.entries()).filter(([e])=>"main"!==e&&!n.has(e));return a.length>0?t("div",{className:"mt-3 rounded-md border border-gray-200 dark:border-gray-800",children:[e("div",{className:"p-2 border-b border-gray-200 dark:border-gray-800 bg-gray-50 dark:bg-gray-900/50",children:e("div",{className:"font-medium text-xs",children:"Workstreams"})}),e("div",{className:"p-3",children:e("div",{className:"grid grid-cols-1 gap-2",children:a.map(([n,r])=>{let i=At,a="text-gray-400",s="bg-gray-100 dark:bg-gray-800",l="Pending";return"in_progress"===r?(i=Me,a="text-info",s="bg-info/20",l="In Progress"):"completed"===r&&(i=Ue,a="text-success",s="bg-success/20",l="Completed"),t("div",{className:`flex items-center p-1.5 rounded ${s}`,children:[e("div",{className:`mr-1.5 ${a}`,children:e(i,{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 yo(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(xo,{...t,run:r})}return r?e(vo,{...t}):e(bo,{})}function bo(){return t(oe,{status:"info",icon:e(De,{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 vo({initialMessage:n,startWorkflow:r,onClose:i,isModal:a=!1,placeholder:s="Type your message...",startButtonText:l="Start Agent",title:d="Start New Conversation"}){const[u,h]=o(""),[p,f]=o(!1),[g,b]=o(),x=y(),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&&(b({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(xo,{onClose:i,isModal:a,initialMessage:n,placeholder:s,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(zt,{className:"size-3.5 text-muted"})}),e("span",{className:"font-medium text-sm text-gray-700 dark:text-gray-300",children:d})]}),i&&!a&&e(v,{size:"xs",variant:"ghost",onClick:i,title:"Close",className:"text-slate-500 hover:text-slate-700",children:e(Ke,{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:s,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(v,{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(V,{size:"sm",className:"mr-1.5"}):e(Tt,{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 xo({run:n,title:r,interactive:i=!0,onClose:a,isModal:s=!1,placeholder:d="Type your message...",resetWorkflow:u}){const{client:h}=Et(),p=m(null),f=m(null),[g,b]=o([]),[x,w]=o(!1),[N,k]=o(!1),[C,S]=o("sliding"),[P,j]=o(!s),[_,T]=o([]),[I,A]=o(0),[z,E]=o(new Map),[F,D]=o(0),$=y(),[L,O]=o(i),[R,U]=o(null),M=l(()=>{const e=_[I]||{plan:{plan:[]},timestamp:0},t=z.get(e.timestamp)||new Map;return{plan:e.plan,workstreamStatus:t}},[_,I,z]);c(()=>{if(!x){const e=setInterval(()=>{D(()=>Math.floor(Math.random()*(Sr.length-1)))},4e3);return()=>clearInterval(e)}},[x]);c(()=>(b([]),T([]),A(0),E(new Map),j(!1),U(null),(async()=>{try{const e=await h.store.workflows.getRunDetails(n.runId,n.workflowId);U(e.status)}catch(e){console.error("Failed to check workflow status:",e)}})(),h.store.workflows.streamMessages(n.workflowId,n.runId,e=>{e.message&&b(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]))}),()=>{b([])}),[n.runId,h.store.workflows]),c(()=>{w(!function(e){if(!e.length)return!0;const t=new Map;if(e.forEach(e=>{const n=jr(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}`),Pr.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}`),Pr.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(!Pr.includes(t.type))return console.log(`[isInProgress] Workstream ${e} is still active`),!0}return console.log("[isInProgress] All workstreams are completed"),!1}(g)),0===_.length&&j(!1)},[g,_.length]),c(()=>{if(1===_.length&&!P&&!sessionStorage.getItem("plan-panel-shown")){const e=setTimeout(()=>{j(!0),sessionStorage.setItem("plan-panel-shown","true")},500);return()=>clearTimeout(e)}g.forEach(e=>{if(e.type===Ft.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===_.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),T(t=>{const n=[e,...t];return console.log("New plans array:",n),n}),A(0),console.log("Setting showSlidingPanel to true"),j(!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===Ft.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=g[g.length-1];e&&(e.type===Ft.TERMINATED?(O(!1),U("TERMINATED")):O(!!i||e.type===Ft.REQUEST_INPUT))},[g,_,I]);const V=r||n.workflowId.split(":")[2]||"Agent Conversation",[K,H]=o(!1);return t("div",{className:"flex gap-2 h-full",children:[t("div",{ref:f,className:"flex flex-col h-full min-h-0 border-0 "+(P?"lg:w-2/3 flex-1":"flex-1 mx-auto "+(s?"":"max-w-4xl")),children:[e($r,{title:V,isCompleted:x,onClose:a,isModal:s,run:n,viewMode:C,onViewModeChange:S,showPlanPanel:P,hasPlan:_.length>0,onTogglePlanPanel:()=>{j(!P),P||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),$({status:"error",title:"Failed to download conversation",duration:3e3})}},onCopyRunId:()=>{navigator.clipboard.writeText(n.runId),$({status:"success",title:"Run ID copied",duration:2e3})},resetWorkflow:u,onExportPdf:()=>{f.current?H(!0):$({status:"error",title:"PDF export failed",description:"No conversation content available to export",duration:3e3})}}),0!==g.length||x?e(Ar,{messages:g,bottomRef:p,viewMode:C,isCompleted:x,plan:M.plan,workstreamStatus:M.workstreamStatus,showPlanPanel:P,onTogglePlanPanel:()=>{console.log("Toggle plan panel called, current state:",P),j(!P)},plans:_,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(xr,{size:"sm",color:"blue"}),e("div",{className:"text-sm text-muted font-medium",children:Sr[F]})]}),e("div",{className:"mt-4 flex justify-center",children:e(vr,{color:"blue",className:"mt-1"})})]})}),R&&("RUNNING"!==R?t(oe,{status:"COMPLETED"===R?"success":"done",icon:null,className:"flex-shrink-0 m-2",children:["This Workflow is ",R]}):L&&e(fo,{onSend:e=>{const t=e.trim();t&&!N&&(k(!0),h.store.workflows.sendSignal(n.workflowId,n.runId,"UserInput",{message:t}).then(()=>{w(!1),$({status:"success",title:"Message Sent",duration:2e3})}).catch(e=>{$({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:x,activeTaskCount:(()=>{if(!g.length)return 0;const e=new Map;g.forEach(t=>{const n=jr(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];[Ft.COMPLETE,Ft.IDLE].includes(e.type)||t++}return t})(),placeholder:d}))]}),P&&e("div",{className:"h-full lg:w-1/3 border-l",children:e(go,{plan:M.plan,workstreamStatus:M.workstreamStatus,isOpen:P,onClose:()=>j(!1),plans:_,activePlanIndex:I,onChangePlan:A})}),t(q,{isOpen:K,onClose:()=>H(!1),children:[e(B,{children:"Export conversation as PDF"}),t(W,{children:[e("p",{className:"mb-2",children:"This will open your browser's print dialog with the current conversation."}),e("p",{className:"text-sm text-muted",children:'To save a PDF, choose "Save as PDF" or a similar option in the print dialog.'})]}),t(G,{align:"right",children:[e(v,{variant:"ghost",size:"sm",onClick:()=>H(!1),children:"Cancel"}),e(v,{size:"sm",onClick:()=>{if(!f.current)return void $({status:"error",title:"PDF export failed",description:"No conversation content available to export",duration:3e3});const e=`${V} - ${n.runId}`,t=function(e,t){if("undefined"==typeof window||"undefined"==typeof document)return!1;const n=document.createElement("iframe");n.style.position="fixed",n.style.right="0",n.style.bottom="0",n.style.width="0",n.style.height="0",n.style.border="0",n.style.visibility="hidden",document.body.appendChild(n);const r=n.contentWindow;if(!r)return n.parentNode?.removeChild(n),!1;const i=r.document;return i.open(),i.write(`<!doctype html><html><head><title>${t}</title></head><body></body></html>`),i.close(),i.title=t,document.querySelectorAll('link[rel="stylesheet"], style').forEach(e=>{i.head.appendChild(e.cloneNode(!0))}),i.body.innerHTML=e.innerHTML,r.focus(),r.print(),setTimeout(()=>{n.parentNode?.removeChild(n)},1e3),!0}(f.current,e);t?($({status:"success",title:"PDF export ready",description:"Use your browser's Print dialog to save as PDF",duration:4e3}),H(!1)):$({status:"error",title:"PDF export failed",description:"Unable to open print preview",duration:4e3})},children:"Open print dialog"})]})]})]})}const wo=["#4f46e5","#06b6d4","#22c55e","#f59e0b","#ef4444","#8b5cf6","#ec4899","#14b8a6"];class No extends p{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){console.error(`Chart rendering error (${this.props.chartType}):`,e,t)}render(){return this.state.hasError?e("div",{className:"flex items-center justify-center h-full bg-red-50 dark:bg-red-950 rounded-md p-4",children:t("div",{className:"text-center",children:[t("p",{className:"text-sm font-medium text-red-600 dark:text-red-400",children:["Cannot render ",this.props.chartType," chart"]}),e("p",{className:"text-xs text-red-500 dark:text-red-500 mt-1 max-w-xs truncate",children:this.state.error?.message||"Unknown error"})]})}):this.props.children}}function ko(e){if(!isFinite(e))return String(e);const t=Math.abs(e);return t>=1e9?(e/1e9).toFixed(1)+"B":t>=1e6?(e/1e6).toFixed(1)+"M":t>=1e3?(e/1e3).toFixed(1)+"K":e.toLocaleString()}const Co=f(function({spec:r}){const{chart:i,title:a,description:s,data:l,xKey:c,series:d,yAxis:u,options:p,nameKey:f,valueKey:g,yKey:y,zKey:b,axisKey:v,dataKey:x}=r,[w,N]=o(!1),[k,C]=o(!1),S=m(null),P=h(async()=>{if(S.current&&!k)try{const e=await Pn(S.current,{backgroundColor:"#ffffff",pixelRatio:2}),t=await fetch(e),n=await t.blob();await navigator.clipboard.write([new ClipboardItem({"image/png":n})]),C(!0),setTimeout(()=>C(!1),2e3)}catch(e){console.error("Failed to copy chart:",e)}},[k]),j=h(async()=>{if(S.current&&!w){N(!0);try{const e=await Pn(S.current,{backgroundColor:"#ffffff",pixelRatio:2}),t=document.createElement("a");t.download=`${a||"chart"}.png`,t.href=e,t.click()}catch(e){console.error("Failed to export chart:",e)}finally{N(!1)}}},[a,w]),_=d||[],T=l||[],I=t(n,{children:[e(jn,{dataKey:c,tick:{fontSize:12}}),e(_n,{yAxisId:"left",tickFormatter:ko,label:u?.left?.label?{value:u.left.label,angle:-90,position:"insideLeft"}:void 0}),_.some(e=>"right"===e.yAxisId)&&e(_n,{yAxisId:"right",orientation:"right",tickFormatter:ko,label:u?.right?.label?{value:u.right.label,angle:-90,position:"insideRight"}:void 0})]}),A=t(n,{children:[e(Tn,{strokeDasharray:"3 3"}),e(In,{formatter:e=>"number"==typeof e?ko(e):String(e)}),e(An,{}),p?.referenceZero&&e(zn,{y:0,stroke:"#999",strokeDasharray:"3 3"})]}),z=()=>_.map((t,n)=>{const r=t.color||wo[n%wo.length],a=t.yAxisId||"left";return"line"===i?e(On,{type:"monotone",dataKey:t.key,name:t.label||t.key,stroke:r,dot:t.dot??!1,yAxisId:a},t.key):"area"===i?e(Rn,{type:"monotone",dataKey:t.key,name:t.label||t.key,stroke:r,fill:r,fillOpacity:.3,stackId:p?.stacked?t.stackId||"stack":void 0,yAxisId:a},t.key):"bar"===i||"bar"===t.type?e(Un,{dataKey:t.key,name:t.label||t.key,fill:r,stackId:p?.stacked?t.stackId||"stack":void 0,yAxisId:a},t.key):"area"===t.type?e(Rn,{type:"monotone",dataKey:t.key,name:t.label||t.key,stroke:r,fill:r,fillOpacity:.3,stackId:p?.stacked?t.stackId||"stack":void 0,yAxisId:a},t.key):e(On,{type:"monotone",dataKey:t.key,name:t.label||t.key,stroke:r,dot:t.dot??!1,yAxisId:a},t.key)});return e("div",{className:"bg-white dark:bg-gray-900 rounded-lg border border-gray-200 dark:border-gray-800 shadow-sm",children:t("div",{className:"flex flex-col gap-2 p-3",children:[t("div",{className:"flex items-center justify-between",children:[e("span",{className:"font-medium text-sm text-gray-900 dark:text-gray-100",children:a||"Chart"}),t("div",{className:"flex items-center gap-2 print:hidden chart-actions",children:[t("button",{onClick:P,disabled:k,className:"text-xs px-2 py-1 rounded border border-gray-300 dark:border-gray-700 bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700 cursor-pointer transition-colors disabled:opacity-50 flex items-center gap-1",title:"Copy to clipboard",children:[e(k?Pt:lt,{className:"w-3 h-3"}),k?"Copied":"Copy"]}),t("button",{onClick:j,disabled:w,className:"text-xs px-2 py-1 rounded border border-gray-300 dark:border-gray-700 bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700 cursor-pointer transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1",title:"Export as PNG",children:[e(rt,{className:"w-3 h-3"}),w?"Exporting...":"Export"]})]})]}),s&&e("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:s}),e("div",{ref:S,className:"bg-white dark:bg-gray-900 rounded",style:{width:"100%",height:280,minWidth:0},children:e(No,{chartType:i,children:e(En,{width:"100%",height:"100%",children:(()=>{switch(i){case"bar":return t(Ln,{data:T,children:[I,A,z()]});case"line":return t($n,{data:T,children:[I,A,z()]});case"area":return t(Dn,{data:T,children:[I,A,z()]});case"composed":default:return t(Fn,{data:T,children:[I,A,z()]});case"pie":return t(Mn,{children:[e(Vn,{data:T,dataKey:g||"value",nameKey:f||"name",cx:"50%",cy:"50%",innerRadius:p?.innerRadius||0,outerRadius:100,label:!1!==p?.showLabels,children:T.map((t,n)=>e(Kn,{fill:wo[n%wo.length]},`cell-${n}`))}),e(In,{formatter:e=>"number"==typeof e?ko(e):String(e)}),e(An,{})]});case"scatter":return(()=>{const n=c,r=y||"y";return t(qn,{children:[e(Tn,{strokeDasharray:"3 3"}),e(jn,{dataKey:n,name:n,tick:{fontSize:12}}),e(_n,{dataKey:r,name:r,tickFormatter:ko}),e(In,{formatter:e=>"number"==typeof e?ko(e):String(e)}),e(An,{}),_.length>0?_.map((t,n)=>e(Bn,{name:t.label||t.key,data:T,fill:t.color||wo[n%wo.length]},t.key)):e(Bn,{name:"Data",data:T,fill:wo[0]})]})})();case"radar":return(()=>{const n=v||c||"axis";return t(Wn,{cx:"50%",cy:"50%",outerRadius:100,data:T,children:[e(Gn,{}),e(Hn,{dataKey:n,tick:{fontSize:11}}),e(Jn,{tickFormatter:ko}),_.map((t,n)=>e(Yn,{name:t.label||t.key,dataKey:t.key,stroke:t.color||wo[n%wo.length],fill:t.color||wo[n%wo.length],fillOpacity:.3},t.key)),e(In,{formatter:e=>"number"==typeof e?ko(e):String(e)}),e(An,{})]})})();case"radialBar":return(()=>{const n=f||"name",r=g||"value",i=p?.startAngle??180,a=p?.endAngle??0;return t(Zn,{cx:"50%",cy:"50%",innerRadius:p?.innerRadius??30,outerRadius:100,barSize:15,data:T,startAngle:i,endAngle:a,children:[e(Qn,{label:{position:"insideStart",fill:"#fff",fontSize:11},background:!0,dataKey:r,children:T.map((t,n)=>e(Kn,{fill:wo[n%wo.length]},`cell-${n}`))}),e(In,{formatter:e=>"number"==typeof e?ko(e):String(e)}),e(An,{iconSize:10,layout:"vertical",verticalAlign:"middle",align:"right",formatter:(e,t)=>{const i=T.find(i=>i[n]===e||i[r]===t.payload?.value);return i?i[n]:e}})]})})();case"funnel":return(()=>{const n=f||"name",r=g||"value";return t(Xn,{children:[e(In,{formatter:e=>"number"==typeof e?ko(e):String(e)}),t(er,{dataKey:r,data:T,isAnimationActive:!0,children:[T.map((t,n)=>e(Kn,{fill:wo[n%wo.length]},`cell-${n}`)),!1!==p?.showLabels&&e(tr,{position:"center",fill:"#fff",stroke:"none",dataKey:n})]})]})})();case"treemap":return e(nr,{data:T,dataKey:x||g||"value",aspectRatio:4/3,stroke:"#fff",fill:"#4f46e5",content:({x:r,y:i,width:a,height:s,name:l,value:o,index:c})=>t("g",{children:[e("rect",{x:r,y:i,width:a,height:s,style:{fill:wo[c%wo.length],stroke:"#fff",strokeWidth:2}}),a>50&&s>30&&t(n,{children:[e("text",{x:r+a/2,y:i+s/2-7,textAnchor:"middle",fill:"#fff",fontSize:12,children:l}),e("text",{x:r+a/2,y:i+s/2+10,textAnchor:"middle",fill:"#fff",fontSize:11,children:ko(o)})]})]})})}})()})})})]})})},(e,t)=>JSON.stringify(e.spec)===JSON.stringify(t.spec));function So(e){const{title:t,leftLabel:n,rightLabel:r,metrics:i,description:a,collapseInitially:s}=e;return{version:"1.0",library:"recharts",chart:"bar",title:t||"Scenario Comparison",description:a,data:i.map(e=>({label:e.label,left:e.left,right:e.right})),xKey:"label",series:[{key:"left",label:n,type:"bar"},{key:"right",label:r,type:"bar"}],yAxis:{left:{label:"Value"}},options:{stacked:!1,referenceZero:!1,collapseInitially:s}}}function Po(e){const{title:t,metrics:n,description:r,collapseInitially:i}=e;return{version:"1.0",library:"recharts",chart:"bar",title:t||"Change vs. Baseline (%)",description:r,data:n.map(e=>({label:e.label,deltaPct:0!==e.left?(e.right-e.left)/e.left*100:0})),xKey:"label",series:[{key:"deltaPct",label:"% Change",type:"bar"}],yAxis:{left:{label:"% Change"}},options:{stacked:!1,referenceZero:!0,collapseInitially:i}}}function jo(e){return["```chart",JSON.stringify(e,null,2),"```"].join("\n")}function _o(e){const{title:t,description:n,rows:r,collapseInitially:i}=e;return{version:"1.0",library:"recharts",chart:"composed",title:t||"Cashflow Timeline",description:n,data:r.map(e=>({period:e.period,calls:e.calls,distributions:e.distributions,netCashflow:e.netCashflow??e.distributions-e.calls})),xKey:"period",series:[{key:"calls",label:"Calls",type:"bar",color:"#ef4444"},{key:"distributions",label:"Distributions",type:"bar",color:"#22c55e"},{key:"netCashflow",label:"Net Cashflow",type:"line",color:"#0ea5e9",yAxisId:"right",dot:!1}],yAxis:{left:{label:"Amount"},right:{label:"Net"}},options:{stacked:!1,referenceZero:!0,collapseInitially:i}}}function To(e){const{title:t,description:n,rows:r,collapseInitially:i}=e;return{version:"1.0",library:"recharts",chart:"line",title:t||"Performance (J‑Curve)",description:n,data:r.map(e=>({period:e.period,tvpi:e.tvpi??null,dpi:e.dpi??null,rvpi:e.rvpi??null})),xKey:"period",series:[{key:"tvpi",label:"TVPI",type:"line",color:"#4f46e5",dot:!1},{key:"dpi",label:"DPI",type:"line",color:"#16a34a",dot:!1},{key:"rvpi",label:"RVPI",type:"line",color:"#f59e0b",dot:!1}],yAxis:{left:{label:"Multiple (x)"}},options:{stacked:!1,referenceZero:!0,collapseInitially:i}}}function Io(e){const{title:t,description:n,rows:r,leftLabel:i,rightLabel:a,collapseInitially:s}=e;return{version:"1.0",library:"recharts",chart:"line",title:t||"TVPI Over Time",description:n,data:r,xKey:"period",series:[{key:"tvpi_left",label:`TVPI – ${i}`,type:"line",color:"#4f46e5",dot:!1},{key:"tvpi_right",label:`TVPI – ${a}`,type:"line",color:"#6366f1",dot:!1}],yAxis:{left:{label:"Multiple (x)"}},options:{stacked:!1,referenceZero:!0,collapseInitially:s}}}function Ao(e){const{title:t,description:n,rows:r,collapseInitially:i}=e;return{version:"1.0",library:"recharts",chart:"line",title:t||"NAV Over Time",description:n,data:r.map(e=>({period:e.period,nav:e.nav})),xKey:"period",series:[{key:"nav",label:"NAV",type:"line",color:"#0ea5e9",dot:!1}],yAxis:{left:{label:"NAV"}},options:{stacked:!1,referenceZero:!0,collapseInitially:i}}}const zo={name:"create_chart",description:'Create an interactive chart visualization that will be rendered in the UI.\n\nIMPORTANT: You don\'t actually "call" this tool. Instead, you include a markdown code block with language "chart" in your response.\n\nCharts are created using JSON specifications in markdown code blocks:\n\n```chart\n{\n "chart": "bar|line|area|composed|pie|scatter|radar|radialBar|funnel|treemap",\n "title": "Chart Title",\n "data": [...],\n ...\n}\n```\n\n## CHART TYPES & WHEN TO USE\n\n| Type | Use Case | Data Shape |\n|------|----------|------------|\n| bar | Category comparisons | `[{x, y1, y2}]` |\n| line | Trends over time | `[{x, y1, y2}]` |\n| area | Trends with volume emphasis | `[{x, y1, y2}]` |\n| composed | Mix bars + lines | `[{x, y1, y2}]` with series.type |\n| pie | Part-to-whole (%) | `[{name, value}]` |\n| scatter | Correlation analysis | `[{x, y}]` |\n| radar | Multi-dimensional comparison | `[{axis, A, B}]` |\n| radialBar | Progress/gauges | `[{name, value}]` |\n| funnel | Conversion stages | `[{name, value}]` |\n| treemap | Hierarchical proportions | `[{name, value}]` |\n\n## EXAMPLES\n\n### Bar Chart\n```chart\n{"chart":"bar","title":"Revenue by Quarter","data":[{"quarter":"Q1","revenue":100000},{"quarter":"Q2","revenue":150000}],"xKey":"quarter","series":[{"key":"revenue","label":"Revenue"}]}\n```\n\n### Line Chart\n```chart\n{"chart":"line","title":"Performance","data":[{"period":"Q1","tvpi":1.2},{"period":"Q2","tvpi":1.5}],"xKey":"period","series":[{"key":"tvpi","label":"TVPI","color":"#4f46e5"}]}\n```\n\n### Area Chart\n```chart\n{"chart":"area","title":"Sales Volume","data":[{"month":"Jan","sales":1000},{"month":"Feb","sales":1500}],"xKey":"month","series":[{"key":"sales","label":"Sales"}],"options":{"stacked":true}}\n```\n\n### Composed Chart (Bar + Line)\n```chart\n{"chart":"composed","title":"Cashflow","data":[{"period":"Q1","calls":1000000,"net":-500000}],"xKey":"period","series":[{"key":"calls","type":"bar","color":"#ef4444"},{"key":"net","type":"line","yAxisId":"right"}],"yAxis":{"left":{"label":"Amount"},"right":{"label":"Net"}}}\n```\n\n### Pie Chart\n```chart\n{"chart":"pie","title":"Market Share","data":[{"name":"Product A","value":400},{"name":"Product B","value":300},{"name":"Product C","value":200}],"nameKey":"name","valueKey":"value"}\n```\n\n### Donut Chart (Pie with innerRadius)\n```chart\n{"chart":"pie","title":"Revenue Split","data":[{"name":"Services","value":60},{"name":"Products","value":40}],"nameKey":"name","valueKey":"value","options":{"innerRadius":50}}\n```\n\n### Scatter Chart\n```chart\n{"chart":"scatter","title":"Price vs Volume","data":[{"price":100,"volume":500},{"price":150,"volume":400}],"xKey":"price","yKey":"volume","series":[{"key":"data","label":"Products"}]}\n```\n\n### Radar Chart\n```chart\n{"chart":"radar","title":"Skills Comparison","data":[{"skill":"Speed","A":120,"B":110},{"skill":"Power","A":98,"B":130}],"axisKey":"skill","series":[{"key":"A","label":"Team A"},{"key":"B","label":"Team B"}]}\n```\n\n### RadialBar Chart (Progress)\n```chart\n{"chart":"radialBar","title":"Goal Progress","data":[{"name":"Sales","value":80},{"name":"Users","value":65}],"nameKey":"name","valueKey":"value"}\n```\n\n### Funnel Chart\n```chart\n{"chart":"funnel","title":"Conversion Funnel","data":[{"name":"Visits","value":5000},{"name":"Cart","value":2500},{"name":"Purchase","value":1000}],"nameKey":"name","valueKey":"value"}\n```\n\n### Treemap\n```chart\n{"chart":"treemap","title":"Budget Allocation","data":[{"name":"Engineering","value":500000},{"name":"Marketing","value":200000},{"name":"Sales","value":300000}],"nameKey":"name","dataKey":"value"}\n```\n\n## CONFIGURATION\n\n### Series (for bar/line/area/composed/radar)\n- key: (required) Field name in data\n- label: Display name\n- type: "bar"|"line"|"area" (composed only)\n- color: Hex color\n- yAxisId: "left"|"right"\n- dot: Show dots on lines\n\n### Keys (for pie/scatter/radar/funnel/treemap)\n- nameKey: Field for labels (default: "name")\n- valueKey: Field for values (default: "value")\n- xKey/yKey: For scatter charts\n- axisKey: For radar axis labels\n- dataKey: For treemap values\n\n### Options\n- stacked: Stack bars/areas\n- referenceZero: Show y=0 line\n- innerRadius: For donut charts (0-100)\n- showLabels: Show value labels\n- startAngle/endAngle: For radialBar\n\n## COLORS\n- Blue #4f46e5 - Primary\n- Cyan #06b6d4 - Secondary\n- Green #22c55e - Positive\n- Amber #f59e0b - Warning\n- Red #ef4444 - Negative\n- Purple #8b5cf6 - Accent\n- Pink #ec4899 - Highlight\n- Teal #14b8a6 - Alternative\n\nNumbers auto-format: 1K, 1M, 1B',input_schema:{type:"object",properties:{chart:{type:"string",enum:["bar","line","area","composed","pie","scatter","radar","radialBar","funnel","treemap"],description:"Type of chart to create"},title:{type:"string",description:"Chart title"},description:{type:"string",description:"Optional description shown below the title"},data:{type:"array",description:"Array of data objects",items:{type:"object",additionalProperties:!0}},xKey:{type:"string",description:"Field name to use for X-axis (for bar/line/area/composed/scatter)"},yKey:{type:"string",description:"Field name for Y values (for scatter charts)"},nameKey:{type:"string",description:'Field name for labels (for pie/funnel/radialBar/treemap, default: "name")'},valueKey:{type:"string",description:'Field name for values (for pie/funnel/radialBar, default: "value")'},axisKey:{type:"string",description:"Field name for radar axis labels"},dataKey:{type:"string",description:"Field name for treemap values"},series:{type:"array",description:"Array of series to plot (for bar/line/area/composed/radar)",items:{type:"object",properties:{key:{type:"string",description:"Field name in data"},label:{type:"string",description:"Display name"},type:{type:"string",enum:["bar","line","area"],description:"Series type (for composed charts)"},color:{type:"string",description:"Hex color code"},yAxisId:{type:"string",enum:["left","right"],description:"Which Y-axis to use"},dot:{type:"boolean",description:"Show dots on line (default: false)"}},required:["key"]}},yAxis:{type:"object",description:"Y-axis configuration",properties:{left:{type:"object",properties:{label:{type:"string"}}},right:{type:"object",properties:{label:{type:"string"}}}}},options:{type:"object",description:"Chart options",properties:{stacked:{type:"boolean",description:"Stack bars/areas"},referenceZero:{type:"boolean",description:"Show reference line at y=0"},collapsible:{type:"boolean",description:"Allow user to collapse chart"},collapseInitially:{type:"boolean",description:"Start collapsed"},innerRadius:{type:"number",description:"Inner radius for donut/radialBar charts (0-100)"},showLabels:{type:"boolean",description:"Show value labels on pie/funnel"},startAngle:{type:"number",description:"Start angle for radialBar (default: 180)"},endAngle:{type:"number",description:"End angle for radialBar (default: 0)"}}}},required:["chart","data"]}},Eo='\n# Chart Visualization Capability\n\nYou can create interactive charts by including markdown code blocks with the language "chart".\n\n## Chart Types\n\n| Type | Use Case | Required Fields |\n|------|----------|-----------------|\n| bar | Category comparisons | xKey, series |\n| line | Trends over time | xKey, series |\n| area | Trends with volume | xKey, series |\n| composed | Mix bars + lines | xKey, series with type |\n| pie | Part-to-whole | nameKey, valueKey |\n| scatter | Correlation | xKey, yKey |\n| radar | Multi-dimensional | axisKey, series |\n| radialBar | Progress/gauges | nameKey, valueKey |\n| funnel | Conversion stages | nameKey, valueKey |\n| treemap | Hierarchical data | nameKey, dataKey |\n\n## Quick Examples\n\nBar: `{"chart":"bar","data":[{"x":"A","y":10}],"xKey":"x","series":[{"key":"y"}]}`\nPie: `{"chart":"pie","data":[{"name":"A","value":60},{"name":"B","value":40}]}`\nScatter: `{"chart":"scatter","data":[{"x":1,"y":2}],"xKey":"x","yKey":"y"}`\n\nUse charts when:\n- User requests visualization\n- 3+ data points to display\n- Visual form clarifies comparisons/trends\n\nColors: Blue #4f46e5 (primary), Green #22c55e (positive), Red #ef4444 (negative)\n';function Fo(e){if(!(e.chart&&e.data&&e.xKey&&e.series))throw new Error("Invalid chart spec: missing required fields (chart, data, xKey, series)");if(!Array.isArray(e.data))throw new Error("Invalid chart spec: data must be an array");if(!Array.isArray(e.series)||0===e.series.length)throw new Error("Invalid chart spec: series must be a non-empty array");return`\`\`\`chart\n${JSON.stringify(e,null,2)}\n\`\`\``}function Do(e){const t=/```chart\s*\n([\s\S]*?)\n```/g,n=[];let r;for(;null!==(r=t.exec(e));)try{const e=JSON.parse(r[1]);n.push(e)}catch(e){console.warn("Failed to parse chart spec:",e)}return n}function $o({children:t,fallback:n}){return Lo?e(Lo,{fallback:n,children:t}):e(rr,{FallbackComponent:n,children:t})}let Lo=null;function Oo(e){Lo=e}function Ro({children:t}){return e($o,{fallback:Uo,children:t})}function Uo({error:n}){return t(oe,{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 Mo({children:t}){return e($o,{fallback:Vo,children:t})}function Vo({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 Ko({children:t}){return e($o,{fallback:qo,children:t})}function qo({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 Bo({className:n,children:i,title:a,description:s,actions:l,breadcrumbs:o,isCompact:c=!1,useDynamicBreadcrumbs:d=!0}){const u=Yt();function m(e){return e.replace(/[-_]/g," ").split(" ").map(e=>ir(e)).join(" ")}const h=e=>{const t=e?.href||"";if(!t)return"Page";const n=t.split("#")[0].split("?")[0].split("/").filter(e=>e.length>0);if(3===n.length){if(e.title!==document.title&&e.title)return e.title;return`${m(n[1])} Detail (...${n[2].slice(-6)})`}return n.length>=2?m(n[n.length-1]):1===n.length?m(n[0]):"Page"},p=(()=>{const e=[];if(d&&"undefined"!=typeof window&&window.history.state?.historyChain){const t=window.history.state.historyChain;t.forEach((n,r)=>{const i=t.length-r;e.push({label:h(n),href:n.href,onClick:()=>u(n.href,{stepsBack:i})})})}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:p.length>0&&e(Ee,{path:p,separator:e(wt,{className:"w-3.5 h-3.5"}),maxItems:4})}),t("div",{className:"flex gap-2 items-center",children:[e("h1",{className:"text-xl font-semibold break-all",children:a}),s&&e($,{description:s,children:e(Le,{className:"size-4 text-muted"})})]})]}),e("div",{className:"flex gap-x-2 shrink-0",children:l})]}),i&&e("div",{className:"w-full flex items-center",children:i})]})}function Wo({}){return t("div",{className:"text-center pt-32",children:[e("h1",{className:"text-3xl font-bold text-red-500",children:"404"}),e("p",{className:"text-2xl",children:"Page Not Found"})]})}function Go(...e){const t=Array.from(e);return t.__AnyOf__=!0,t}function Ho(...e){return Array.from(e)}function Jo(e){return!0===e.__AnyOf__}class Yo{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 i=new Set;for(const e of n){const t=r[e];if(t)for(const e of t)i.add(e)}this.permissions=i}hasPermission(e){if("string"==typeof e)return this.permissions.has(e);if(Jo(e))return e.some(e=>this.permissions.has(e));for(const t of e)if(!this.permissions.has(t))return!1;return!0}}const Zo=d(void 0);function Qo(){const e=u(Zo);if(!e)throw new Error("UserPermissionContext cannot be used outside UserPermissionProvider");return e}function Xo({children:t}){const n=Et(),{data:r,error:i,isLoading:a}=L(()=>n.user?n.client.iam.roles.list():Promise.resolve(void 0),[n.user]),s=l(()=>n.authToken&&r&&!a?new Yo(n,r):void 0,[n,r,a]);return i?e(O,{title:"Failed to fetch role mappings",children:i.message}):s&&e(Zo.Provider,{value:s,children:t})}function ec({permission:t,isDisabled:n,title:r,children:i,...a}){return Qo().hasPermission(t)||(n=!0,r="You do not have permission to perform this action"),e(v,{isDisabled:n,title:r,...a,children:i})}function tc({permission:t,...n}){return Qo().hasPermission(t)?e(ar,{...n}):null}function nc({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{cr as ActivitiesDoc,ur as ActivityDoc,io as AddToCollectionAction,ro as AddToCollectionActionComponent,Co as AgentChart,Ho as AllOf,vr as AnimatedThinkingDots,Go as AnyOf,Ma as ApiKeyAvatar,al as BrowseCollectionView,$l as ChangeTypeAction,Dl as ChangeTypeActionComponent,os as CollectionsFacetsNav,dl as CollectionsTable,Rr as ContentDispositionButton,xl as ContentObjectTypesSearch,ml as ContentObjectTypesTable,sa as ContentOverview,ol as CreateCollectionForm,cl as CreateCollectionModal,bl as CreateOrUpdateTypeModal,Rl as DeleteObjectsAction,Ol as DeleteObjectsActionComponent,Ul as DeleteObjectsFromCollectionsAction,xs as DocumentGridView,xa as DocumentIcon,va as DocumentIconSkeleton,Ks as DocumentInput,Bs as DocumentPreviewPanel,ws as DocumentSearch,$s as DocumentSearchProvider,Qs as DocumentSearchResults,Zs as DocumentSearchResultsWithDropZone,cs as DocumentSelection,hs as DocumentSelectionProvider,Es as DocumentTable,bs as DocumentTableColumn,vs as DocumentTableView,Is as DocumentUploadModal,Xa as DocumentsFacetsNav,Il as EditCollectionView,qa as EnvironmentFacet,Vl as ExportPropertiesAction,Ml as ExportPropertiesComponent,nl as ExportPropertiesModal,tl as ExportTypes,js as FileUploadAction,Bo as GenericPageNavHeader,ns as InteractionsFacetsNav,br as JumpingDots,Gi as MagicPdfView,yo as ModernAgentConversation,Wo as NotFoundView,Nl as ObjectSchemaEditor,hl as ObjectTypeSearch,pl as ObjectTypeSearchContext,Cl as ObjectTypeSearchProvider,Yl as ObjectsActionContext,Ql as ObjectsActionContextProvider,Ro as PanelErrorBoundary,zr as PayloadBuilder,Fr as PayloadBuilderProvider,Er as PayloadContext,yi as PdfDocumentRenderer,ci as PdfPageRenderer,xi as PdfPageSlider,gi as PdfThumbnailList,as as PromptsFacetsNav,li as PropertiesEditorModal,xr as PulsatingCircle,Nr as PulsingMessageLoader,ql as RemoveFromCollectionAction,Kl as RemoveFromCollectionActionComponent,Mo as RowErrorBoundary,Ga as RunsFacetsNav,si as SaveVersionConfirmModal,Ns as SearchContext,ec as SecureButton,tc as SecureSidebarItem,zl as SelectCollection,ll as SelectContentType,Sl as SelectContentTypeModal,Os as SelectDocument,Ms as SelectDocumentModal,lo as SelectionActions,ui as SharedPdfProvider,El as SharedPropsEditor,pi as SimplePdfPage,Ji as SimplePdfViewer,Wl as StartWorkflowAction,Bl as StartWorkflowComponent,ka as StringFacet,Ca as StringListFacet,Fl as SyncMemberHeadsToggle,jl as TableLayoutEditor,kr as ThinkingBar,Sr as ThinkingMessages,Pa as TypeFacet,wr as TypedDots,co as UploadObjectsButton,nc as UserAvatar,La as UserInfo,Xo as UserPermissionProvider,Yo as UserPermissions,Zo as UserPermissionsContext,ja as VStringFacet,_a as VTypeFacet,Ka as VUserFacet,$o as VertesiaErrorBoundary,Cr as WavyThinking,Ko as WidgetErrorBoundary,Ya as WorkflowExecutionsFacetsNav,_o as buildCashflowComposedChart,Fo as buildChartSpec,Ao as buildNavLineChart,To as buildPerformanceLineChart,So as buildScenarioComparisonBarChart,Po as buildScenarioDeltaPercentChart,Io as buildTvpiOverlayChart,Eo as chartSystemPromptAddition,ul as collectionIcon,zo as createChartToolDefinition,Do as extractChartSpecs,ri as getWorkflowStatusColor,ii as getWorkflowStatusName,Jo as isAnyOf,Gr as isCsv,Hr as isImage,Jr as isPdf,Zr as isPreviewableAsPdf,Yr as isVideo,ni as printElementToPdf,ti as retrieveRendition,Oo as setErrorBoundaryComponent,Ur as shortId,Mr as shortenString,_l as stringifyTableLayout,jo as toChartMarkdown,ss as useCollectionsFilterGroups,ls as useCollectionsFilterHandler,Za as useDocumentFilterGroups,Qa as useDocumentFilterHandler,ks as useDocumentSearch,Ps as useDocumentSearchCount,us as useDocumentSelection,As as useDocumentUploadHandler,qs as useDownloadDocument,za as useFetchGroupInfo,Aa as useFetchUserInfo,es as useInteractionsFilterGroups,ts as useInteractionsFilterHandler,to as useObjectsActionCallback,eo as useObjectsActionContext,ms as useOptionalDocumentSelection,Dr as usePayloadBuilder,rs as usePromptsFilterGroups,is as usePromptsFilterHandler,Ba as useRunsFilterGroups,Wa as useRunsFilterHandler,fl as useSearch,yl as useSearchCount,mi as useSharedPdf,Ts as useSmartFileUploadProcessing,no as useStartWorkflowCallback,Qo as useUserPermissions,Cs as useWatchDocumentSearchFacets,Ss as useWatchDocumentSearchResult,gl as useWatchSearchResult,Ha as useWorkflowExecutionsFilterGroups,Ja as useWorkflowExecutionsFilterHandler};
|
|
2
2
|
//# sourceMappingURL=vertesia-ui-features.js.map
|