@mgamadeus/ddd-agents 0.11.13 → 0.13.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 +138 -6
- package/boundary.json +5 -0
- package/dist/admin.js +13839 -0
- package/dist/admin.js.map +1 -0
- package/dist/chat.js +1627 -109
- package/dist/chat.js.map +1 -1
- package/dist/chunks/{AgentsConversationClientContext-C4T7g_Qk.js → AgentsConversationClientContext-B_UJSLXU.js} +2 -2
- package/dist/chunks/{AgentsConversationClientContext-C4T7g_Qk.js.map → AgentsConversationClientContext-B_UJSLXU.js.map} +1 -1
- package/dist/chunks/{ConversationMarkdown-D-aP3Ssl.js → ConversationMarkdown-DlvwT3Qk.js} +5 -4
- package/dist/chunks/{ConversationMarkdown-D-aP3Ssl.js.map → ConversationMarkdown-DlvwT3Qk.js.map} +1 -1
- package/dist/chunks/{ConversationMessageInputComposerWidgets-7HNAmZE1.js → ConversationMessageInputComposerWidgets-TchR1lPj.js} +6 -6
- package/dist/chunks/{ConversationMessageInputComposerWidgets-7HNAmZE1.js.map → ConversationMessageInputComposerWidgets-TchR1lPj.js.map} +1 -1
- package/dist/chunks/{VoiceBarsIcon-FhLAcgLG.js → VoiceBarsIcon-y3mgSqbn.js} +4 -4
- package/dist/chunks/{VoiceBarsIcon-FhLAcgLG.js.map → VoiceBarsIcon-y3mgSqbn.js.map} +1 -1
- package/dist/chunks/{WebSearchResultsConversationWidget-dEq19U7k.js → WebSearchResultsConversationWidget-l9Aek_lG.js} +3 -2
- package/dist/chunks/WebSearchResultsConversationWidget-l9Aek_lG.js.map +1 -0
- package/dist/chunks/agents-http-trace-mappers-LWNi-3a4.js +759 -0
- package/dist/chunks/agents-http-trace-mappers-LWNi-3a4.js.map +1 -0
- package/dist/chunks/{browser-request-interception-ydNOzeUL.js → browser-request-interception-D678IemW.js} +2 -2
- package/dist/chunks/{browser-request-interception-ydNOzeUL.js.map → browser-request-interception-D678IemW.js.map} +1 -1
- package/dist/chunks/{canvas-reducers-BInd3xNz.js → canvas-reducers-BYArW_Ji.js} +2 -2
- package/dist/chunks/{canvas-reducers-BInd3xNz.js.map → canvas-reducers-BYArW_Ji.js.map} +1 -1
- package/dist/chunks/{canvas-title-slot-context-BI1PLnPn.js → canvas-title-slot-context-BRGnFzYP.js} +3 -3
- package/dist/chunks/{canvas-title-slot-context-BI1PLnPn.js.map → canvas-title-slot-context-BRGnFzYP.js.map} +1 -1
- package/dist/chunks/{canvasBodies-CRVh8pCw.js → canvasBodies-BjXypuHf.js} +4 -4
- package/dist/chunks/{canvasBodies-CRVh8pCw.js.map → canvasBodies-BjXypuHf.js.map} +1 -1
- package/dist/chunks/{canvasStorage-Cr3omZeI.js → canvasStorage-DSspwRMg.js} +2 -2
- package/dist/chunks/{canvasStorage-Cr3omZeI.js.map → canvasStorage-DSspwRMg.js.map} +1 -1
- package/dist/chunks/content-from-unified-diff-CovnmG2Q.js +2927 -0
- package/dist/chunks/content-from-unified-diff-CovnmG2Q.js.map +1 -0
- package/dist/chunks/{contract-C18owGKs.js → contract-886XjdID.js} +2 -2
- package/dist/chunks/{contract-C18owGKs.js.map → contract-886XjdID.js.map} +1 -1
- package/dist/chunks/{conversation-CbWEHPbL.js → conversation-B7-evdj_.js} +4 -4
- package/dist/chunks/{conversation-CbWEHPbL.js.map → conversation-B7-evdj_.js.map} +1 -1
- package/dist/chunks/{icon-names-Di6c4zLo.js → icon-names-C5PeVvkJ.js} +32 -1
- package/dist/chunks/icon-names-C5PeVvkJ.js.map +1 -0
- package/dist/chunks/{link-navigation-DRHt6g7U.js → index-DZovGMpG.js} +65 -106
- package/dist/chunks/index-DZovGMpG.js.map +1 -0
- package/dist/chunks/link-navigation-a_sRfmsj.js +49 -0
- package/dist/chunks/link-navigation-a_sRfmsj.js.map +1 -0
- package/dist/chunks/{widget-name-resolver-Dq6Ejo7d.js → widget-name-resolver-DS3zH_5W.js} +5 -4
- package/dist/chunks/{widget-name-resolver-Dq6Ejo7d.js.map → widget-name-resolver-DS3zH_5W.js.map} +1 -1
- package/dist/chunks/{withPollingChangeSubscription-ClyOABgu.js → withPollingChangeSubscription-XvCpjGmd.js} +13 -2
- package/dist/chunks/{withPollingChangeSubscription-ClyOABgu.js.map → withPollingChangeSubscription-XvCpjGmd.js.map} +1 -1
- package/dist/client-testing.js +5 -5
- package/dist/client.js +50 -231
- package/dist/client.js.map +1 -1
- package/dist/contract.js +5 -5
- package/dist/files/i18n-keys.json +18277 -1298
- package/dist/files/widgets/DriveFilesConversationWidget/DriveFilesConversationWidget.md +3 -3
- package/dist/image-render.js +7 -7
- package/dist/index.js +62 -61
- package/dist/index.js.map +1 -1
- package/dist/kit.js +2 -2
- package/dist/preview.js +7 -7
- package/dist/provider.js +57 -56
- package/dist/provider.js.map +1 -1
- package/dist/renderer.js +15 -15
- package/dist/styles.css +2962 -15
- package/dist/types/admin/blocks/CodeBlock.d.ts +28 -0
- package/dist/types/admin/blocks/DetailModal.d.ts +34 -0
- package/dist/types/admin/blocks/Disclosure.d.ts +25 -0
- package/dist/types/admin/blocks/JsonTree.d.ts +18 -0
- package/dist/types/admin/blocks/LineDiffView.d.ts +18 -0
- package/dist/types/admin/blocks/ProportionBar.d.ts +43 -0
- package/dist/types/admin/blocks/TokenFigure.d.ts +14 -0
- package/dist/types/admin/blocks/json-tree.d.ts +40 -0
- package/dist/types/admin/blocks/line-diff.d.ts +46 -0
- package/dist/types/admin/blocks/proportion-bar.d.ts +34 -0
- package/dist/types/admin/blocks/series-fill-classes.d.ts +13 -0
- package/dist/types/admin/blocks/token-figure.d.ts +8 -0
- package/dist/types/admin/connections/AgentConnectionCard.d.ts +21 -0
- package/dist/types/admin/connections/AgentConnectionDriveRootSpaces.d.ts +25 -0
- package/dist/types/admin/connections/AgentConnectionDriveScopeDialog.d.ts +20 -0
- package/dist/types/admin/connections/AgentConnectionDriveSearchFilters.d.ts +34 -0
- package/dist/types/admin/connections/AgentConnectionDrivesDrawer.d.ts +39 -0
- package/dist/types/admin/connections/AgentConnectionLevelsDrawer.d.ts +27 -0
- package/dist/types/admin/connections/AgentConnectionSharingDialog.d.ts +12 -0
- package/dist/types/admin/connections/AgentConnectionsPanel.d.ts +105 -0
- package/dist/types/admin/connections/AgentConnectionsScreen.d.ts +18 -0
- package/dist/types/admin/connections/ConnectDialogs.d.ts +22 -0
- package/dist/types/admin/connections/agent-connection-drive-scope.d.ts +112 -0
- package/dist/types/admin/connections/agent-connection-drives.d.ts +107 -0
- package/dist/types/admin/connections/agent-connection-format.d.ts +82 -0
- package/dist/types/admin/connections/agent-connection-oauth.d.ts +138 -0
- package/dist/types/admin/connections/agent-connections-api.d.ts +420 -0
- package/dist/types/admin/connections/agent-connections-context.d.ts +60 -0
- package/dist/types/admin/connections/agent-connections-types.d.ts +447 -0
- package/dist/types/admin/connections/connection-logos.d.ts +53 -0
- package/dist/types/admin/connections/connection-parts.d.ts +84 -0
- package/dist/types/admin/connections/use-agent-connect.d.ts +25 -0
- package/dist/types/admin/context/CompactionThresholdBanner.d.ts +13 -0
- package/dist/types/admin/context/ContextCompositionPanel.d.ts +27 -0
- package/dist/types/admin/context/ContextSegmentList.d.ts +20 -0
- package/dist/types/admin/context/SentPayloadPanel.d.ts +37 -0
- package/dist/types/admin/context/agent-inspect-context-api.d.ts +53 -0
- package/dist/types/admin/context/agent-inspect-context-types.d.ts +98 -0
- package/dist/types/admin/context/context-composition-grouping.d.ts +78 -0
- package/dist/types/admin/context/context-segment-families.d.ts +18 -0
- package/dist/types/admin/context/context-segment-label-texts.d.ts +19 -0
- package/dist/types/admin/context/context-segment-labels.d.ts +18 -0
- package/dist/types/admin/control-panel/AgentControlPanelScreen.d.ts +71 -0
- package/dist/types/admin/control-panel/BudgetsTab.d.ts +13 -0
- package/dist/types/admin/control-panel/SettingsTab.d.ts +22 -0
- package/dist/types/admin/control-panel/SpacesTab.d.ts +24 -0
- package/dist/types/admin/control-panel/StatisticsTab.d.ts +26 -0
- package/dist/types/admin/control-panel/TimeSeriesChartCard.d.ts +37 -0
- package/dist/types/admin/control-panel/ToolResponseSamplesDrawer.d.ts +22 -0
- package/dist/types/admin/control-panel/agent-control-panel-api.d.ts +104 -0
- package/dist/types/admin/control-panel/agent-control-panel-types.d.ts +241 -0
- package/dist/types/admin/control-panel/budget-meters.d.ts +35 -0
- package/dist/types/admin/control-panel/control-panel-statistics.d.ts +49 -0
- package/dist/types/admin/control-panel/runtime-settings-form.d.ts +44 -0
- package/dist/types/admin/control-panel/time-series-chart.d.ts +54 -0
- package/dist/types/admin/conversations/AgentConversationDetailScreen.d.ts +128 -0
- package/dist/types/admin/conversations/AgentConversationsScreen.d.ts +60 -0
- package/dist/types/admin/conversations/ContextPanel.d.ts +9 -0
- package/dist/types/admin/conversations/ConversationActions.d.ts +32 -0
- package/dist/types/admin/conversations/ConversationTurns.d.ts +56 -0
- package/dist/types/admin/conversations/DebugSwitchBar.d.ts +23 -0
- package/dist/types/admin/conversations/DelegationPanel.d.ts +6 -0
- package/dist/types/admin/conversations/ModelContextDialog.d.ts +31 -0
- package/dist/types/admin/conversations/RequestCompositionRows.d.ts +14 -0
- package/dist/types/admin/conversations/RequestsPanel.d.ts +21 -0
- package/dist/types/admin/conversations/SandboxPanel.d.ts +42 -0
- package/dist/types/admin/conversations/StepDetailDialog.d.ts +19 -0
- package/dist/types/admin/conversations/agent-inspect-api.d.ts +259 -0
- package/dist/types/admin/conversations/agent-inspect-mappers.d.ts +23 -0
- package/dist/types/admin/conversations/agent-inspect-types.d.ts +517 -0
- package/dist/types/admin/conversations/conversation-list-export.d.ts +64 -0
- package/dist/types/admin/conversations/conversation-list-filters.d.ts +59 -0
- package/dist/types/admin/conversations/debug-switches.d.ts +27 -0
- package/dist/types/admin/conversations/delegation-swimlanes.d.ts +78 -0
- package/dist/types/admin/conversations/header-facts.d.ts +23 -0
- package/dist/types/admin/conversations/inspect-format.d.ts +44 -0
- package/dist/types/admin/conversations/inspect-parts.d.ts +42 -0
- package/dist/types/admin/conversations/inspect-scope.d.ts +92 -0
- package/dist/types/admin/conversations/model-call-rows.d.ts +78 -0
- package/dist/types/admin/conversations/step-descriptions.d.ts +43 -0
- package/dist/types/admin/conversations/touched-files-tree.d.ts +47 -0
- package/dist/types/admin/conversations/turn-paging.d.ts +56 -0
- package/dist/types/admin/conversations/turn-segments.d.ts +36 -0
- package/dist/types/admin/conversations/turn-timeline.d.ts +22 -0
- package/dist/types/admin/conversations/use-query-loader.d.ts +8 -0
- package/dist/types/admin/period/AdminPeriodControl.d.ts +15 -0
- package/dist/types/admin/period/admin-period.d.ts +51 -0
- package/dist/types/admin/quality/AgentQualityEvalRunScreen.d.ts +30 -0
- package/dist/types/admin/quality/AgentQualityScreen.d.ts +38 -0
- package/dist/types/admin/quality/SaveAsEvalCaseDialog.d.ts +27 -0
- package/dist/types/admin/quality/agent-quality-api.d.ts +86 -0
- package/dist/types/admin/quality/agent-quality-format.d.ts +52 -0
- package/dist/types/admin/quality/agent-quality-types.d.ts +161 -0
- package/dist/types/admin/schedules/AgentSchedulesPanel.d.ts +43 -0
- package/dist/types/admin/schedules/agent-schedules-api.d.ts +116 -0
- package/dist/types/admin/schedules/agent-schedules-format.d.ts +25 -0
- package/dist/types/admin/schedules/agent-schedules-types.d.ts +113 -0
- package/dist/types/admin/shared/AdminHrefLink.d.ts +13 -0
- package/dist/types/admin/skills/AgentSkillCatalogScreen.d.ts +51 -0
- package/dist/types/admin/skills/SharedBlocksPanel.d.ts +14 -0
- package/dist/types/admin/skills/SkillLoadSourcesPanel.d.ts +20 -0
- package/dist/types/admin/skills/SkillPurposesPanel.d.ts +16 -0
- package/dist/types/admin/skills/SkillTreeRowView.d.ts +31 -0
- package/dist/types/admin/skills/ToolSchemaDrawer.d.ts +21 -0
- package/dist/types/admin/skills/agent-skill-catalog-api.d.ts +101 -0
- package/dist/types/admin/skills/agent-skill-catalog-types.d.ts +259 -0
- package/dist/types/admin/skills/skill-catalog-colors.d.ts +10 -0
- package/dist/types/admin/skills/skill-catalog-tree.d.ts +159 -0
- package/dist/types/admin/skills/skill-purpose-texts.d.ts +11 -0
- package/dist/types/admin/wire/admin-wire.d.ts +21 -0
- package/dist/types/chat/controller/AgentChatController.d.ts +22 -0
- package/dist/types/chat/controller/turn-initiators.d.ts +21 -0
- package/dist/types/chat/trace/BackgroundTasksList.d.ts +35 -0
- package/dist/types/chat/trace/ChangeSetCard.d.ts +34 -0
- package/dist/types/chat/trace/ChangedFilesPane.d.ts +33 -0
- package/dist/types/chat/trace/ChangedRecordsList.d.ts +34 -0
- package/dist/types/chat/trace/ConsentRequestCard.d.ts +23 -0
- package/dist/types/chat/trace/ContextRing.d.ts +19 -0
- package/dist/types/chat/trace/ConversationChildTrace.d.ts +18 -0
- package/dist/types/chat/trace/ConversationTurnTrace.d.ts +48 -0
- package/dist/types/chat/trace/EntityChip.d.ts +23 -0
- package/dist/types/chat/trace/FileChangesSummary.d.ts +14 -0
- package/dist/types/chat/trace/FileEditBlock.d.ts +42 -0
- package/dist/types/chat/trace/LoadedSkillsDisclosure.d.ts +16 -0
- package/dist/types/chat/trace/QueuedMessageChip.d.ts +17 -0
- package/dist/types/chat/trace/RunStatusLine.d.ts +27 -0
- package/dist/types/chat/trace/StepKindDetails.d.ts +59 -0
- package/dist/types/chat/trace/SubAgentStepGroup.d.ts +53 -0
- package/dist/types/chat/trace/TaskPlanPane.d.ts +31 -0
- package/dist/types/chat/trace/TaskPlanRow.d.ts +28 -0
- package/dist/types/chat/trace/TerminalBlock.d.ts +16 -0
- package/dist/types/chat/trace/ThinkingBlock.d.ts +19 -0
- package/dist/types/chat/trace/ToolStepDetail.d.ts +49 -0
- package/dist/types/chat/trace/ToolStepGroup.d.ts +58 -0
- package/dist/types/chat/trace/ToolStepRow.d.ts +52 -0
- package/dist/types/chat/trace/TraceViewModeSwitch.d.ts +14 -0
- package/dist/types/chat/trace/TurnMetaLine.d.ts +27 -0
- package/dist/types/chat/trace/content-from-unified-diff.d.ts +25 -0
- package/dist/types/chat/trace/conversation-trace-loader.d.ts +133 -0
- package/dist/types/chat/trace/index.d.ts +34 -0
- package/dist/types/chat/trace/parse-unified-diff.d.ts +51 -0
- package/dist/types/chat/trace/task-plan-counts.d.ts +41 -0
- package/dist/types/chat/trace/trace-collect.d.ts +91 -0
- package/dist/types/chat/trace/trace-counts.d.ts +21 -0
- package/dist/types/chat/trace/trace-format.d.ts +73 -0
- package/dist/types/chat/trace/trace-labels.d.ts +60 -0
- package/dist/types/chat/trace/trace-parts.d.ts +63 -0
- package/dist/types/chat/trace/trace-step-focus.d.ts +12 -0
- package/dist/types/chat/trace/trace-types.d.ts +370 -0
- package/dist/types/chat/trace/use-conversation-trace.d.ts +47 -0
- package/dist/types/client/AgentsConversationClient.d.ts +20 -0
- package/dist/types/client/http/agents-http-trace-mappers.d.ts +31 -0
- package/dist/types/client/http/agents-http-trace-wire.d.ts +433 -0
- package/dist/types/contract/conversation-trace.d.ts +594 -0
- package/dist/types/entries/admin.d.ts +86 -0
- package/dist/types/entries/chat.d.ts +3 -1
- package/dist/types/entries/client.d.ts +2 -0
- package/dist/types/entries/contract.d.ts +1 -0
- package/dist/types/provider/components/icon-names.d.ts +4 -2
- package/dist/types/provider/components/types.d.ts +3 -1
- package/dist/types/widgets/DriveFilesConversationWidget/shared/drive-files.d.ts +1 -1
- package/dist/voice.js +3 -3
- package/dist/widgets.js +6 -6
- package/package.json +7 -3
- package/public-api.json +1047 -3
- package/dist/chunks/WebSearchResultsConversationWidget-dEq19U7k.js.map +0 -1
- package/dist/chunks/icon-names-Di6c4zLo.js.map +0 -1
- package/dist/chunks/link-navigation-DRHt6g7U.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"admin.js","sources":["../src/admin/blocks/CodeBlock.tsx","../src/admin/blocks/DetailModal.tsx","../src/admin/blocks/Disclosure.tsx","../src/admin/blocks/json-tree.ts","../src/admin/blocks/JsonTree.tsx","../src/admin/blocks/line-diff.ts","../src/admin/blocks/LineDiffView.tsx","../src/admin/blocks/proportion-bar.ts","../src/admin/blocks/ProportionBar.tsx","../src/admin/blocks/series-fill-classes.ts","../src/admin/blocks/token-figure.ts","../src/admin/blocks/TokenFigure.tsx","../src/admin/context/agent-inspect-context-api.ts","../src/admin/context/agent-inspect-context-types.ts","../src/admin/context/CompactionThresholdBanner.tsx","../src/admin/context/context-segment-labels.ts","../src/admin/context/context-segment-families.ts","../src/admin/context/context-composition-grouping.ts","../src/admin/context/context-segment-label-texts.ts","../src/admin/context/ContextSegmentList.tsx","../src/admin/context/ContextCompositionPanel.tsx","../src/admin/context/SentPayloadPanel.tsx","../src/admin/skills/agent-skill-catalog-api.ts","../src/admin/period/admin-period.ts","../src/admin/period/AdminPeriodControl.tsx","../src/admin/skills/skill-catalog-tree.ts","../src/admin/skills/SharedBlocksPanel.tsx","../src/admin/skills/skill-catalog-colors.ts","../src/admin/skills/SkillTreeRowView.tsx","../src/admin/skills/skill-purpose-texts.ts","../src/admin/wire/admin-wire.ts","../src/admin/skills/SkillLoadSourcesPanel.tsx","../src/admin/skills/SkillPurposesPanel.tsx","../src/admin/skills/ToolSchemaDrawer.tsx","../src/admin/skills/AgentSkillCatalogScreen.tsx","../src/admin/shared/AdminHrefLink.tsx","../src/admin/control-panel/agent-control-panel-api.ts","../src/admin/control-panel/agent-control-panel-types.ts","../src/admin/control-panel/control-panel-statistics.ts","../src/admin/schedules/agent-schedules-format.ts","../src/admin/schedules/AgentSchedulesPanel.tsx","../src/admin/control-panel/budget-meters.ts","../src/admin/control-panel/BudgetsTab.tsx","../src/admin/control-panel/runtime-settings-form.ts","../src/admin/control-panel/SettingsTab.tsx","../src/admin/control-panel/SpacesTab.tsx","../src/admin/control-panel/time-series-chart.ts","../src/admin/control-panel/TimeSeriesChartCard.tsx","../src/admin/control-panel/ToolResponseSamplesDrawer.tsx","../src/admin/control-panel/StatisticsTab.tsx","../src/admin/control-panel/AgentControlPanelScreen.tsx","../src/admin/schedules/agent-schedules-api.ts","../src/admin/quality/agent-quality-api.ts","../src/admin/quality/agent-quality-types.ts","../src/admin/quality/agent-quality-format.ts","../src/admin/quality/AgentQualityEvalRunScreen.tsx","../src/admin/quality/AgentQualityScreen.tsx","../src/admin/quality/SaveAsEvalCaseDialog.tsx","../src/admin/conversations/agent-inspect-api.ts","../src/admin/conversations/agent-inspect-mappers.ts","../src/admin/conversations/agent-inspect-types.ts","../src/admin/conversations/debug-switches.ts","../src/admin/conversations/header-facts.ts","../src/admin/conversations/inspect-format.ts","../src/admin/conversations/inspect-parts.tsx","../src/admin/conversations/inspect-scope.tsx","../src/admin/conversations/step-descriptions.ts","../src/admin/conversations/turn-paging.ts","../src/admin/conversations/turn-segments.ts","../src/admin/conversations/turn-timeline.ts","../src/admin/conversations/ConversationTurns.tsx","../src/admin/conversations/ContextPanel.tsx","../src/admin/conversations/ConversationActions.tsx","../src/admin/conversations/DebugSwitchBar.tsx","../src/admin/conversations/delegation-swimlanes.ts","../src/admin/conversations/DelegationPanel.tsx","../src/admin/conversations/RequestCompositionRows.tsx","../src/admin/conversations/ModelContextDialog.tsx","../src/admin/conversations/model-call-rows.ts","../src/admin/conversations/RequestsPanel.tsx","../src/admin/conversations/touched-files-tree.ts","../src/admin/conversations/SandboxPanel.tsx","../src/admin/conversations/StepDetailDialog.tsx","../src/admin/conversations/use-query-loader.tsx","../src/admin/conversations/AgentConversationDetailScreen.tsx","../src/admin/conversations/conversation-list-export.ts","../src/admin/conversations/conversation-list-filters.ts","../src/admin/conversations/AgentConversationsScreen.tsx","../src/admin/connections/agent-connections-api.ts","../src/admin/connections/agent-connection-format.ts","../src/admin/connections/agent-connection-oauth.ts","../src/admin/connections/agent-connection-drives.ts","../src/admin/connections/connection-logos.tsx","../src/admin/connections/agent-connections-context.tsx","../src/admin/connections/connection-parts.tsx","../src/admin/connections/agent-connection-drive-scope.ts","../src/admin/connections/AgentConnectionCard.tsx","../src/admin/connections/use-agent-connect.ts","../src/admin/connections/AgentConnectionDriveScopeDialog.tsx","../src/admin/connections/AgentConnectionDriveSearchFilters.tsx","../src/admin/connections/AgentConnectionDriveRootSpaces.tsx","../src/admin/connections/AgentConnectionDrivesDrawer.tsx","../src/admin/connections/AgentConnectionLevelsDrawer.tsx","../src/admin/connections/AgentConnectionSharingDialog.tsx","../src/admin/connections/ConnectDialogs.tsx","../src/admin/connections/AgentConnectionsPanel.tsx","../src/admin/connections/AgentConnectionsScreen.tsx"],"sourcesContent":["import type { CodeHighlighterLoader } from \"@mgamadeus/ddd-admin-ui/files\";\nimport { CodeText } from \"@mgamadeus/ddd-admin-ui/files\";\nimport { m, useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { CopyButton } from \"@mgamadeus/ddd-admin-ui/list\";\nimport { cn } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { WrapText } from \"lucide-react\";\nimport { type ReactNode, useState } from \"react\";\n\nexport interface CodeBlockProps {\n /** The text, shown as it is in a monospaced face. */\n code: string;\n /** A language the host's highlighter knows (`json`, `php`); `null` / absent: plain. */\n language?: string | null;\n /** Loads the host's highlighter on the first block shown; without it the code stays plain. */\n loadCodeHighlighter?: CodeHighlighterLoader;\n /** Long lines wrap at first (default `true`); the wrap toggle switches to sideways scrolling. */\n defaultWrap?: boolean;\n /** The wrap toggle in the block's corner (default `true`). */\n showWrapToggle?: boolean;\n /** The copy button in the block's corner (default `true`). */\n showCopyButton?: boolean;\n /** Left of the block's buttons (a caption, a badge). */\n caption?: ReactNode;\n /** Height: `auto` grows with the text up to 24 rem and scrolls inside; `fill` takes the height it is given. */\n height?: \"auto\" | \"fill\";\n /** Accessible name of the code region. */\n \"aria-label\"?: string;\n className?: string;\n}\n\n/**\n * Text in a monospaced block with a wrap toggle and a copy button. The code is drawn as text nodes (plain at once,\n * coloured once the host's highlighter answered), never as HTML. Copy writes exactly `code`.\n */\nexport const CodeBlock = ({\n code,\n language = null,\n loadCodeHighlighter,\n defaultWrap = true,\n showWrapToggle = true,\n showCopyButton = true,\n caption,\n height = \"auto\",\n \"aria-label\": ariaLabel,\n className,\n}: CodeBlockProps) => {\n const { t } = useTranslate();\n const [isWrapped, setIsWrapped] = useState(defaultWrap);\n const hasBar = showWrapToggle || showCopyButton || (caption !== undefined && caption !== null);\n return (\n <div\n data-slot=\"code-block\"\n role=\"group\"\n aria-label={ariaLabel}\n className={cn(\"flex min-w-0 flex-col overflow-hidden rounded-lg border bg-muted/40\", height === \"fill\" && \"min-h-0 flex-1\", className)}\n >\n {hasBar && (\n <div className=\"flex items-center gap-1 border-b border-border px-2 py-1\">\n <div className=\"min-w-0 flex-1 truncate text-xs text-muted-foreground\">{caption}</div>\n {showWrapToggle && (\n <button\n type=\"button\"\n aria-pressed={isWrapped}\n aria-label={t(\"Wrap long lines\")}\n title={t(\"Wrap long lines\")}\n onClick={() => setIsWrapped((current) => !current)}\n className={cn(\n \"inline-flex size-6 shrink-0 items-center justify-center rounded-md text-muted-foreground outline-none hover:bg-tint hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\",\n isWrapped && \"bg-tint-strong text-foreground\",\n )}\n >\n <WrapText aria-hidden className=\"size-3.5\" />\n </button>\n )}\n {showCopyButton && <CopyButton value={code} label={m(\"Copy\")} />}\n </div>\n )}\n <CodeText\n code={code}\n language={language}\n loadCodeHighlighter={loadCodeHighlighter}\n layout={height === \"fill\" ? \"canvas\" : \"drawer\"}\n className={cn(\"rounded-none border-0 bg-transparent\", height === \"auto\" && \"max-h-[24rem]\", isWrapped && \"break-words whitespace-pre-wrap\")}\n />\n </div>\n );\n};\n","import { m, useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { useCopyToClipboard } from \"@mgamadeus/ddd-admin-ui/logic\";\nimport { Button } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { cn } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { Dialog, DialogClose, DialogContent, DialogDescription, DialogTitle } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { SegmentedControl, type SegmentedControlOption } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { Sheet, SheetClose, SheetContent, SheetDescription, SheetTitle } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { Check, Copy, X } from \"lucide-react\";\nimport { type ReactNode, useState } from \"react\";\n\n/** The two readings of a detail: prepared for reading, or the text exactly as it is. */\nexport type DetailModalView = \"formatted\" | \"raw\";\n\nexport interface DetailModalProps {\n open: boolean;\n onOpenChange: (open: boolean) => void;\n title: ReactNode;\n /** One muted line under the title. */\n description?: ReactNode;\n /** Between the title and the view control (filters, a badge, a picker). */\n toolbar?: ReactNode;\n /** The Formatted / Raw control (default `true`); without it `children` is always asked for `formatted`. */\n showViewControl?: boolean;\n /** Uncontrolled: the view shown first (default `formatted`). */\n defaultView?: DetailModalView;\n /** Controlled view. */\n view?: DetailModalView;\n onViewChange?: (view: DetailModalView) => void;\n /** With it the Copy button is shown; it writes this text (a function is called on the click). */\n copyText?: string | (() => string);\n /** `dialog` (default): a large centred dialog. `sheet`: a wide panel from the right. */\n presentation?: \"dialog\" | \"sheet\";\n /** The content, or a function of the chosen view. It scrolls inside the modal. */\n children: ReactNode | ((view: DetailModalView) => ReactNode);\n className?: string;\n bodyClassName?: string;\n}\n\nconst VIEW_OPTIONS: readonly SegmentedControlOption<DetailModalView>[] = [\n { value: \"formatted\", label: m(\"Formatted\", { context: \"detail-view\" }), context: \"detail-view\" },\n { value: \"raw\", label: m(\"Raw\", { context: \"detail-view\" }), context: \"detail-view\" },\n];\n\n/**\n * A large modal for reading one thing in full: the title, a toolbar slot, the Formatted / Raw control, Copy and Close\n * in a fixed head, the content scrolling below. The view control only switches what `children` is asked for; what\n * \"formatted\" means (markdown, a tree) is the caller's. Copy turns into a check for a moment once the text is on the\n * clipboard. Escape, the Close button and a click outside close it.\n */\nexport const DetailModal = ({\n open,\n onOpenChange,\n title,\n description,\n toolbar,\n showViewControl = true,\n defaultView = \"formatted\",\n view,\n onViewChange,\n copyText,\n presentation = \"dialog\",\n children,\n className,\n bodyClassName,\n}: DetailModalProps) => {\n const { t } = useTranslate();\n const { copy, copied } = useCopyToClipboard();\n const [ownView, setOwnView] = useState<DetailModalView>(defaultView);\n const shownView = showViewControl ? (view ?? ownView) : \"formatted\";\n const changeView = (next: DetailModalView) => {\n setOwnView(next);\n onViewChange?.(next);\n };\n const isSheet = presentation === \"sheet\";\n const Title = isSheet ? SheetTitle : DialogTitle;\n const Description = isSheet ? SheetDescription : DialogDescription;\n const Close = isSheet ? SheetClose : DialogClose;\n\n const content = (\n <>\n <div data-slot=\"detail-modal-head\" className=\"flex flex-wrap items-center gap-x-3 gap-y-2 border-b border-border px-4 py-3\">\n <div className=\"min-w-0 flex-1\">\n <Title className=\"truncate text-base leading-tight font-semibold\">{title}</Title>\n {description !== undefined && description !== null ? (\n <Description className=\"mt-0.5 text-xs\">{description}</Description>\n ) : (\n <Description className=\"sr-only\">{t(\"Details\")}</Description>\n )}\n </div>\n {toolbar !== undefined && toolbar !== null && <div className=\"flex min-w-0 flex-wrap items-center gap-2\">{toolbar}</div>}\n <div className=\"flex shrink-0 items-center gap-2\">\n {showViewControl && <SegmentedControl<DetailModalView> aria-label={m(\"View mode\")} value={shownView} onValueChange={changeView} options={VIEW_OPTIONS} />}\n {copyText !== undefined && (\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n data-slot=\"detail-modal-copy\"\n onClick={() => void copy(typeof copyText === \"function\" ? copyText() : copyText)}\n >\n {copied ? <Check aria-hidden className=\"text-success\" /> : <Copy aria-hidden />}\n {copied ? t(\"Copied\") : t(\"Copy\")}\n </Button>\n )}\n <Close asChild>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" data-slot=\"detail-modal-close\">\n <X aria-hidden />\n {t(\"Close\", { context: \"dialog-close-button\" })}\n </Button>\n </Close>\n </div>\n </div>\n <div data-slot=\"detail-modal-body\" className={cn(\"min-h-0 flex-1 overflow-y-auto px-4 py-4\", bodyClassName)}>\n {typeof children === \"function\" ? children(shownView) : children}\n </div>\n </>\n );\n\n if (isSheet) {\n return (\n <Sheet open={open} onOpenChange={onOpenChange}>\n <SheetContent side=\"right\" showCloseButton={false} className={cn(\"flex w-full flex-col gap-0 p-0 sm:max-w-4xl\", className)}>\n {content}\n </SheetContent>\n </Sheet>\n );\n }\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent\n showCloseButton={false}\n className={cn(\"flex h-[90dvh] w-full max-w-[calc(100%-2rem)] flex-col gap-0 overflow-hidden p-0 sm:max-w-6xl\", className)}\n >\n {content}\n </DialogContent>\n </Dialog>\n );\n};\n","import { Collapsible, CollapsibleContent, CollapsibleTrigger } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { cn } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { ChevronRight } from \"lucide-react\";\nimport type { ReactNode } from \"react\";\n\nexport interface DisclosureProps {\n /** The line that opens and closes the content. */\n title: ReactNode;\n /** Right of the title, outside the click target's text (figures, a badge). */\n meta?: ReactNode;\n children: ReactNode;\n /** Uncontrolled: open at first. */\n defaultOpen?: boolean;\n /** Controlled state. */\n open?: boolean;\n onOpenChange?: (open: boolean) => void;\n /** `sm`: a line inside a list or a table cell. `md` (default): a section line. */\n size?: \"sm\" | \"md\";\n disabled?: boolean;\n className?: string;\n triggerClassName?: string;\n contentClassName?: string;\n}\n\n/**\n * A line that opens the content below it: a chevron that turns, the title, an optional right-aligned `meta`. The\n * content is mounted only while open, so a closed disclosure costs nothing. The trigger is one button\n * (`aria-expanded`, `aria-controls`); `meta` is part of it, so it holds no control of its own.\n */\nexport const Disclosure = ({\n title,\n meta,\n children,\n defaultOpen,\n open,\n onOpenChange,\n size = \"md\",\n disabled,\n className,\n triggerClassName,\n contentClassName,\n}: DisclosureProps) => (\n <Collapsible data-slot=\"disclosure\" defaultOpen={defaultOpen} open={open} onOpenChange={onOpenChange} disabled={disabled} className={cn(\"group/disclosure min-w-0\", className)}>\n <CollapsibleTrigger\n className={cn(\n \"flex w-full min-w-0 items-center gap-2 rounded-md text-left outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-default\",\n size === \"sm\" ? \"py-1 text-sm\" : \"py-1.5 text-sm font-medium\",\n triggerClassName,\n )}\n >\n <ChevronRight\n aria-hidden\n className={cn(\"shrink-0 text-muted-foreground transition-transform group-data-[state=open]/disclosure:rotate-90\", size === \"sm\" ? \"size-3.5\" : \"size-4\")}\n />\n <span className=\"min-w-0 flex-1\">{title}</span>\n {meta !== undefined && meta !== null && <span className=\"shrink-0 text-muted-foreground\">{meta}</span>}\n </CollapsibleTrigger>\n <CollapsibleContent className={contentClassName}>{children}</CollapsibleContent>\n </Collapsible>\n);\n","/** A value as JSON carries it. */\nexport type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };\n\nexport type JsonValueKind = \"object\" | \"array\" | \"string\" | \"number\" | \"boolean\" | \"null\";\n\n/** How many children of one object or array a tree shows before it asks to show more. */\nexport const JSON_TREE_WINDOW_SIZE = 100;\n\n/** The kind of a JSON value; anything JSON cannot carry (undefined, a function) reads as `null`. */\nexport const jsonValueKindOf = (value: unknown): JsonValueKind => {\n if (Array.isArray(value)) return \"array\";\n if (value === null || value === undefined) return \"null\";\n if (typeof value === \"object\") return \"object\";\n if (typeof value === \"string\") return \"string\";\n if (typeof value === \"number\") return \"number\";\n if (typeof value === \"boolean\") return \"boolean\";\n return \"null\";\n};\n\n/** True for an object or an array: a value with children. */\nexport const isJsonContainer = (value: unknown): value is JsonValue[] | { [key: string]: JsonValue } => {\n const kind = jsonValueKindOf(value);\n return kind === \"object\" || kind === \"array\";\n};\n\n/**\n * The object or array a text holds as JSON, or `undefined` when the text is anything else (prose, markdown, a JSON\n * scalar, broken JSON). Only a text that starts with `{` or `[` is parsed, so long prose costs nothing.\n */\nexport const parseJsonContainer = (text: string): JsonValue[] | { [key: string]: JsonValue } | undefined => {\n const trimmed = text.trim();\n const first = trimmed.charAt(0);\n const last = trimmed.charAt(trimmed.length - 1);\n if (!((first === \"{\" && last === \"}\") || (first === \"[\" && last === \"]\"))) return undefined;\n try {\n const parsed: unknown = JSON.parse(trimmed);\n return isJsonContainer(parsed) ? parsed : undefined;\n } catch {\n return undefined;\n }\n};\n\n/** One child of a container: its key (an array index as a number) and its value. */\nexport interface JsonChildEntry {\n key: string | number;\n value: unknown;\n}\n\n/** The children of an object (key order as given) or an array (by index); none for a scalar. */\nexport const jsonChildEntriesOf = (value: unknown): JsonChildEntry[] => {\n if (Array.isArray(value)) return value.map((item, index) => ({ key: index, value: item }));\n if (value !== null && typeof value === \"object\") return Object.entries(value as Record<string, unknown>).map(([key, item]) => ({ key, value: item }));\n return [];\n};\n\n/** How many children a container has; 0 for a scalar. */\nexport const jsonChildCountOf = (value: unknown): number => {\n if (Array.isArray(value)) return value.length;\n if (value !== null && typeof value === \"object\") return Object.keys(value as Record<string, unknown>).length;\n return 0;\n};\n\n/** The part of a list a window shows and how many entries wait behind it. */\nexport interface JsonEntryWindow<TEntry> {\n visible: TEntry[];\n hiddenCount: number;\n}\n\n/** The first `visibleCount` entries and the number left out (a count below 1 shows one entry). */\nexport const windowJsonEntries = <TEntry>(entries: readonly TEntry[], visibleCount: number): JsonEntryWindow<TEntry> => {\n const shownCount = Math.min(entries.length, Math.max(1, Math.floor(visibleCount)));\n return { visible: entries.slice(0, shownCount), hiddenCount: entries.length - shownCount };\n};\n\n/** A JSON value as indented text (two spaces), key order kept; a value JSON cannot carry gives `null`. */\nexport const formatJsonText = (value: unknown): string => JSON.stringify(value ?? null, null, 2) ?? \"null\";\n\n/** A scalar as the tree writes it: a string in quotes with its escapes, the others as JSON. */\nexport const formatJsonScalar = (value: unknown): string => {\n const kind = jsonValueKindOf(value);\n if (kind === \"null\") return \"null\";\n return JSON.stringify(value) ?? \"null\";\n};\n","import { useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { cn } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { ChevronRight } from \"lucide-react\";\nimport { useId, useState } from \"react\";\nimport { formatJsonScalar, JSON_TREE_WINDOW_SIZE, jsonChildCountOf, jsonChildEntriesOf, jsonValueKindOf, type JsonValueKind, windowJsonEntries } from \"./json-tree\";\n\nexport interface JsonTreeProps {\n /** The value to show: anything `JSON.parse` returns. */\n value: unknown;\n /** How many levels are open at first (0: only the root line; default 2). */\n defaultExpandDepth?: number;\n /** How many children of one object or array are drawn before \"Show more\" (default 100). */\n windowSize?: number;\n /** Accessible name of the tree. */\n \"aria-label\"?: string;\n className?: string;\n}\n\nconst SCALAR_CLASS_NAMES: Readonly<Record<JsonValueKind, string>> = {\n string: \"text-success\",\n number: \"text-warning\",\n boolean: \"text-primary-emphasis\",\n null: \"text-muted-foreground italic\",\n object: \"\",\n array: \"\",\n};\n\ninterface JsonTreeNodeProps {\n nodeKey: string | number | null;\n value: unknown;\n depth: number;\n defaultExpandDepth: number;\n windowSize: number;\n}\n\nconst JsonTreeNode = ({ nodeKey, value, depth, defaultExpandDepth, windowSize }: JsonTreeNodeProps) => {\n const { t } = useTranslate();\n const kind = jsonValueKindOf(value);\n const isContainer = kind === \"object\" || kind === \"array\";\n const [isOpen, setIsOpen] = useState(depth < defaultExpandDepth);\n const [visibleCount, setVisibleCount] = useState(windowSize);\n const groupId = useId();\n const keyLabel =\n nodeKey === null ? null : (\n <span className={typeof nodeKey === \"number\" ? \"text-muted-foreground\" : \"text-info\"}>\n {typeof nodeKey === \"number\" ? nodeKey : JSON.stringify(nodeKey)}\n <span className=\"text-muted-foreground\">: </span>\n </span>\n );\n\n if (!isContainer) {\n return (\n <li role=\"treeitem\" aria-selected={false} className=\"flex min-w-0 gap-1 pl-5\">\n <span className=\"min-w-0 break-words whitespace-pre-wrap\">\n {keyLabel}\n <span className={SCALAR_CLASS_NAMES[kind]}>{formatJsonScalar(value)}</span>\n </span>\n </li>\n );\n }\n\n const childCount = jsonChildCountOf(value);\n const summary =\n kind === \"array\"\n ? t(\"{count, plural, one {# item} other {# items}}\", { count: childCount })\n : t(\"{count, plural, one {# key} other {# keys}}\", { count: childCount });\n const openBracket = kind === \"array\" ? \"[\" : \"{\";\n const closeBracket = kind === \"array\" ? \"]\" : \"}\";\n const entryWindow = isOpen ? windowJsonEntries(jsonChildEntriesOf(value), visibleCount) : null;\n\n return (\n <li role=\"treeitem\" aria-selected={false} aria-expanded={childCount > 0 ? isOpen : undefined} className=\"min-w-0\">\n <button\n type=\"button\"\n disabled={childCount === 0}\n aria-expanded={childCount > 0 ? isOpen : undefined}\n aria-controls={isOpen ? groupId : undefined}\n onClick={() => setIsOpen((current) => !current)}\n className=\"flex max-w-full items-start gap-1 rounded-sm text-left outline-none hover:bg-tint focus-visible:ring-2 focus-visible:ring-ring disabled:hover:bg-transparent\"\n >\n <ChevronRight aria-hidden className={cn(\"mt-0.5 size-3.5 shrink-0 text-muted-foreground transition-transform\", isOpen && \"rotate-90\", childCount === 0 && \"invisible\")} />\n <span className=\"min-w-0 break-words\">\n {keyLabel}\n <span className=\"text-muted-foreground\">\n {openBracket}\n {(!isOpen || childCount === 0) && (\n <>\n {childCount > 0 && <span className=\"px-1\">{summary}</span>}\n {closeBracket}\n </>\n )}\n </span>\n </span>\n </button>\n {entryWindow !== null && childCount > 0 && (\n <>\n <ul id={groupId} role=\"group\" className=\"ml-[7px] border-l border-border pl-2\">\n {entryWindow.visible.map((entry) => (\n <JsonTreeNode key={entry.key} nodeKey={entry.key} value={entry.value} depth={depth + 1} defaultExpandDepth={defaultExpandDepth} windowSize={windowSize} />\n ))}\n {entryWindow.hiddenCount > 0 && (\n <li role=\"none\" className=\"pl-5\">\n <button\n type=\"button\"\n data-slot=\"json-tree-show-more\"\n onClick={() => setVisibleCount((current) => current + windowSize)}\n className=\"rounded-sm text-primary-emphasis underline-offset-2 outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring\"\n >\n {t(\"Show %count% more (%remaining% not shown)\", {\n replacements: { count: Math.min(windowSize, entryWindow.hiddenCount), remaining: entryWindow.hiddenCount },\n })}\n </button>\n </li>\n )}\n </ul>\n <span className=\"pl-5 text-muted-foreground\">{closeBracket}</span>\n </>\n )}\n </li>\n );\n};\n\n/**\n * A JSON value as a tree: objects and arrays open and close (the first `defaultExpandDepth` levels are open), a closed\n * one says how many keys or items it holds, scalars are coloured by kind. A container draws its children only while\n * open and at most `windowSize` of them at a time (\"Show more\" adds the next window), so a payload with thousands of\n * entries stays light. Strings are shown whole, wrapped. Nothing of the value is inserted as HTML.\n */\nexport const JsonTree = ({ value, defaultExpandDepth = 2, windowSize = JSON_TREE_WINDOW_SIZE, \"aria-label\": ariaLabel, className }: JsonTreeProps) => (\n <ul data-slot=\"json-tree\" role=\"tree\" aria-label={ariaLabel} className={cn(\"min-w-0 font-mono text-xs leading-relaxed\", className)}>\n <JsonTreeNode nodeKey={null} value={value} depth={0} defaultExpandDepth={defaultExpandDepth} windowSize={Math.max(1, windowSize)} />\n </ul>\n);\n","/** One line of a line diff: in both texts, only in the first (`removed`) or only in the second (`added`). */\nexport interface LineDiffRow {\n kind: \"equal\" | \"removed\" | \"added\";\n text: string;\n /** 1-based line number in the first text (absent for an added line). */\n beforeLineNumber?: number;\n /** 1-based line number in the second text (absent for a removed line). */\n afterLineNumber?: number;\n}\n\nexport interface LineDiff {\n rows: LineDiffRow[];\n addedCount: number;\n removedCount: number;\n /**\n * True when the part that differs was too large to align (`maximumCells`): its lines are then listed as all removed,\n * then all added, without matching equal lines inside it. The common start and end are still exact.\n */\n isApproximate: boolean;\n}\n\nexport interface LineDiffOptions {\n /**\n * The largest table (lines of the differing part of the first text × those of the second) the alignment builds;\n * above it the differing part is not aligned (`isApproximate`). Default 4 000 000 (two parts of 2 000 lines).\n */\n maximumCells?: number;\n}\n\nconst splitLines = (text: string): string[] => (text === \"\" ? [] : text.split(/\\r\\n|\\r|\\n/));\n\n/**\n * The line diff of two texts by their longest common subsequence of lines. The common start and the common end are\n * cut off first (two payloads of one conversation share most of their lines), so the table only covers the part in\n * between. A removed line comes before the added line that replaces it. Lines are compared exactly (no trimming).\n */\nexport const diffLines = (before: string, after: string, options: LineDiffOptions = {}): LineDiff => {\n const maximumCells = options.maximumCells ?? 4_000_000;\n const beforeLines = splitLines(before);\n const afterLines = splitLines(after);\n let prefixLength = 0;\n const shortestLength = Math.min(beforeLines.length, afterLines.length);\n while (prefixLength < shortestLength && beforeLines[prefixLength] === afterLines[prefixLength]) prefixLength += 1;\n let suffixLength = 0;\n while (\n suffixLength < shortestLength - prefixLength &&\n beforeLines[beforeLines.length - 1 - suffixLength] === afterLines[afterLines.length - 1 - suffixLength]\n ) {\n suffixLength += 1;\n }\n const beforeMiddle = beforeLines.slice(prefixLength, beforeLines.length - suffixLength);\n const afterMiddle = afterLines.slice(prefixLength, afterLines.length - suffixLength);\n\n const rows: LineDiffRow[] = [];\n for (let index = 0; index < prefixLength; index += 1) {\n rows.push({ kind: \"equal\", text: beforeLines[index] ?? \"\", beforeLineNumber: index + 1, afterLineNumber: index + 1 });\n }\n\n const rowCount = beforeMiddle.length;\n const columnCount = afterMiddle.length;\n let isApproximate = false;\n if (rowCount > 0 && columnCount > 0 && rowCount * columnCount > maximumCells) {\n isApproximate = true;\n beforeMiddle.forEach((text, index) => rows.push({ kind: \"removed\", text, beforeLineNumber: prefixLength + index + 1 }));\n afterMiddle.forEach((text, index) => rows.push({ kind: \"added\", text, afterLineNumber: prefixLength + index + 1 }));\n } else {\n // lengths[row * width + column]: the longest common subsequence of beforeMiddle[row…] and afterMiddle[column…]\n const width = columnCount + 1;\n const lengths = new Uint32Array((rowCount + 1) * width);\n for (let row = rowCount - 1; row >= 0; row -= 1) {\n for (let column = columnCount - 1; column >= 0; column -= 1) {\n lengths[row * width + column] =\n beforeMiddle[row] === afterMiddle[column]\n ? (lengths[(row + 1) * width + column + 1] ?? 0) + 1\n : Math.max(lengths[(row + 1) * width + column] ?? 0, lengths[row * width + column + 1] ?? 0);\n }\n }\n let row = 0;\n let column = 0;\n while (row < rowCount || column < columnCount) {\n if (row < rowCount && column < columnCount && beforeMiddle[row] === afterMiddle[column]) {\n rows.push({ kind: \"equal\", text: beforeMiddle[row] ?? \"\", beforeLineNumber: prefixLength + row + 1, afterLineNumber: prefixLength + column + 1 });\n row += 1;\n column += 1;\n } else if (row < rowCount && (column >= columnCount || (lengths[(row + 1) * width + column] ?? 0) >= (lengths[row * width + column + 1] ?? 0))) {\n rows.push({ kind: \"removed\", text: beforeMiddle[row] ?? \"\", beforeLineNumber: prefixLength + row + 1 });\n row += 1;\n } else {\n rows.push({ kind: \"added\", text: afterMiddle[column] ?? \"\", afterLineNumber: prefixLength + column + 1 });\n column += 1;\n }\n }\n }\n\n for (let index = 0; index < suffixLength; index += 1) {\n const beforeIndex = beforeLines.length - suffixLength + index;\n const afterIndex = afterLines.length - suffixLength + index;\n rows.push({ kind: \"equal\", text: beforeLines[beforeIndex] ?? \"\", beforeLineNumber: beforeIndex + 1, afterLineNumber: afterIndex + 1 });\n }\n return {\n rows,\n addedCount: rows.reduce((count, diffRow) => count + (diffRow.kind === \"added\" ? 1 : 0), 0),\n removedCount: rows.reduce((count, diffRow) => count + (diffRow.kind === \"removed\" ? 1 : 0), 0),\n isApproximate,\n };\n};\n\n/** A stretch of a diff as it is drawn: changed and nearby lines, or a run of equal lines folded away. */\nexport type LineDiffSection = { kind: \"lines\"; rows: LineDiffRow[] } | { kind: \"folded\"; rows: LineDiffRow[] };\n\n/**\n * The rows cut into sections: every changed line with `contextLineCount` equal lines around it stays visible, a longer\n * run of equal lines between (or before, or after) the changes is one folded section. A diff without a change is one\n * folded section; an empty diff has none.\n */\nexport const foldEqualLines = (rows: readonly LineDiffRow[], contextLineCount = 3): LineDiffSection[] => {\n const context = Math.max(0, Math.floor(contextLineCount));\n const isVisible = new Array<boolean>(rows.length).fill(false);\n rows.forEach((diffRow, index) => {\n if (diffRow.kind === \"equal\") return;\n for (let near = Math.max(0, index - context); near <= Math.min(rows.length - 1, index + context); near += 1) isVisible[near] = true;\n });\n const sections: LineDiffSection[] = [];\n rows.forEach((diffRow, index) => {\n const kind = isVisible[index] ? \"lines\" : \"folded\";\n const last = sections[sections.length - 1];\n if (last && last.kind === kind) last.rows.push(diffRow);\n else sections.push({ kind, rows: [diffRow] });\n });\n return sections;\n};\n","import { useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { cn } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { Fragment, useMemo, useState } from \"react\";\nimport { foldEqualLines, type LineDiff, type LineDiffRow } from \"./line-diff\";\n\nexport interface LineDiffViewProps {\n /** The diff to draw (`diffLines(before, after)`). */\n diff: LineDiff;\n /** Equal lines kept around every change (default 3); longer equal runs are folded and open on a click. */\n contextLineCount?: number;\n /** How many rows are drawn before \"Show more\" (default 1500). */\n maximumRows?: number;\n /** Accessible name of the diff (\"Payload of call 4 against call 5\"). */\n \"aria-label\": string;\n className?: string;\n}\n\nconst ROW_CLASS_NAMES: Readonly<Record<LineDiffRow[\"kind\"], string>> = {\n equal: \"\",\n removed: \"bg-destructive/10\",\n added: \"bg-success/10\",\n};\n\nconst MARKS: Readonly<Record<LineDiffRow[\"kind\"], string>> = { equal: \" \", removed: \"−\", added: \"+\" };\n\nconst DiffRow = ({ diffRow }: { diffRow: LineDiffRow }) => (\n <tr data-diff-kind={diffRow.kind} className={ROW_CLASS_NAMES[diffRow.kind]}>\n <td className=\"w-px px-2 text-right text-muted-foreground tabular-nums select-none\">{diffRow.beforeLineNumber ?? \"\"}</td>\n <td className=\"w-px px-2 text-right text-muted-foreground tabular-nums select-none\">{diffRow.afterLineNumber ?? \"\"}</td>\n <td\n aria-hidden\n className={cn(\"w-px px-1 text-center select-none\", diffRow.kind === \"removed\" && \"text-destructive\", diffRow.kind === \"added\" && \"text-success\")}\n >\n {MARKS[diffRow.kind]}\n </td>\n <td className=\"px-2 break-words whitespace-pre-wrap\">\n {diffRow.kind !== \"equal\" && <span className=\"sr-only\">{diffRow.kind === \"removed\" ? \"− \" : \"+ \"}</span>}\n {diffRow.text}\n </td>\n </tr>\n);\n\n/**\n * A line diff as a table: line number in the first text, line number in the second, the mark (`−` only in the first,\n * `+` only in the second) and the line. Equal lines far from a change are folded into one row that says how many they\n * are and opens on a click. Added and removed lines carry a tint and their mark, so the colour is not the only sign.\n */\nexport const LineDiffView = ({ diff, contextLineCount = 3, maximumRows = 1500, \"aria-label\": ariaLabel, className }: LineDiffViewProps) => {\n const { t } = useTranslate();\n const sections = useMemo(() => foldEqualLines(diff.rows, contextLineCount), [diff.rows, contextLineCount]);\n const [openSectionIndexes, setOpenSectionIndexes] = useState<ReadonlySet<number>>(new Set());\n const [rowLimit, setRowLimit] = useState(maximumRows);\n\n if (diff.rows.length === 0) {\n return <p className={cn(\"text-sm text-muted-foreground\", className)}>{t(\"Both texts are empty.\")}</p>;\n }\n\n let drawnRows = 0;\n let isCut = false;\n return (\n <div data-slot=\"line-diff\" className={cn(\"min-w-0 overflow-x-auto rounded-lg border bg-muted/40\", className)}>\n <table aria-label={ariaLabel} className=\"w-full border-collapse font-mono text-xs leading-relaxed\">\n <tbody>\n {sections.map((section, sectionIndex) => {\n if (isCut) return null;\n const firstRow = section.rows[0];\n const sectionKey = `${section.kind}-${firstRow?.beforeLineNumber ?? \"x\"}-${firstRow?.afterLineNumber ?? \"x\"}`;\n if (section.kind === \"folded\" && !openSectionIndexes.has(sectionIndex)) {\n return (\n <tr key={sectionKey} data-diff-kind=\"folded\">\n <td colSpan={4} className=\"border-y border-border bg-card/60 px-2 py-0.5 text-center\">\n <button\n type=\"button\"\n onClick={() => setOpenSectionIndexes((current) => new Set(current).add(sectionIndex))}\n className=\"rounded-sm text-muted-foreground underline-offset-2 outline-none hover:text-foreground hover:underline focus-visible:ring-2 focus-visible:ring-ring\"\n >\n {t(\"{count, plural, one {# unchanged line} other {# unchanged lines}}\", { count: section.rows.length })}\n </button>\n </td>\n </tr>\n );\n }\n const remaining = rowLimit - drawnRows;\n const shownRows = section.rows.length > remaining ? section.rows.slice(0, Math.max(0, remaining)) : section.rows;\n drawnRows += shownRows.length;\n if (shownRows.length < section.rows.length) isCut = true;\n return (\n <Fragment key={sectionKey}>\n {shownRows.map((diffRow) => (\n <DiffRow key={`${diffRow.kind}-${diffRow.beforeLineNumber ?? \"x\"}-${diffRow.afterLineNumber ?? \"x\"}`} diffRow={diffRow} />\n ))}\n </Fragment>\n );\n })}\n </tbody>\n </table>\n {isCut && (\n <div className=\"border-t border-border px-2 py-1 text-center text-xs\">\n <button\n type=\"button\"\n onClick={() => setRowLimit((current) => current + maximumRows)}\n className=\"rounded-sm text-primary-emphasis underline-offset-2 outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring\"\n >\n {t(\"Show more lines\")}\n </button>\n </div>\n )}\n </div>\n );\n};\n","/** One part of a whole, as the maths reads it. */\nexport interface ProportionValue {\n key: string;\n value: number;\n}\n\n/** A part with its share of the whole and its width in the bar. */\nexport interface ProportionShare {\n key: string;\n /** The value counted (a negative or non-finite value counts as 0). */\n value: number;\n /** The part's share of the sum, 0 … 1 (0 when the sum is 0). */\n share: number;\n /** The part's width in the bar in percent; the widths of all parts sum to 100 (all 0 for an empty list). */\n widthPercent: number;\n}\n\nexport interface ProportionShareOptions {\n /**\n * The smallest width in percent a part with a value takes, so a tiny part stays visible and clickable. The other\n * parts shrink in proportion. Default 0.75.\n */\n minimumWidthPercent?: number;\n}\n\nconst countedValueOf = (value: number): number => (Number.isFinite(value) && value > 0 ? value : 0);\n\n/**\n * The shares and bar widths of the parts of a whole. A part without a value has share and width 0. A part whose share\n * is below the minimum width takes the minimum, and the parts above it give that width up in proportion; when even\n * the minimum does not fit for every part, the parts with a value share the bar equally. A sum of 0 gives every part\n * the same width (there is nothing to weigh), with share 0.\n */\nexport const computeProportionShares = (values: readonly ProportionValue[], options: ProportionShareOptions = {}): ProportionShare[] => {\n const minimumWidthPercent = Math.max(0, options.minimumWidthPercent ?? 0.75);\n const counted = values.map((part) => ({ key: part.key, value: countedValueOf(part.value) }));\n const total = counted.reduce((sum, part) => sum + part.value, 0);\n if (counted.length === 0) return [];\n if (total === 0) {\n return counted.map((part) => ({ key: part.key, value: 0, share: 0, widthPercent: 100 / counted.length }));\n }\n const withValue = counted.filter((part) => part.value > 0);\n if (withValue.length * minimumWidthPercent >= 100) {\n return counted.map((part) => ({\n key: part.key,\n value: part.value,\n share: part.value / total,\n widthPercent: part.value > 0 ? 100 / withValue.length : 0,\n }));\n }\n // Parts raised to the minimum are fixed; the rest share what is left in proportion. Raising one may push another\n // below the minimum, so repeat until no part changes sides.\n const raisedKeys = new Set<number>();\n let hasChanged = true;\n while (hasChanged) {\n hasChanged = false;\n const freeTotal = counted.reduce((sum, part, index) => (raisedKeys.has(index) ? sum : sum + part.value), 0);\n const freeWidth = 100 - raisedKeys.size * minimumWidthPercent;\n counted.forEach((part, index) => {\n if (raisedKeys.has(index) || part.value === 0) return;\n if ((part.value / freeTotal) * freeWidth < minimumWidthPercent) {\n raisedKeys.add(index);\n hasChanged = true;\n }\n });\n }\n const freeTotal = counted.reduce((sum, part, index) => (raisedKeys.has(index) ? sum : sum + part.value), 0);\n const freeWidth = 100 - raisedKeys.size * minimumWidthPercent;\n return counted.map((part, index) => ({\n key: part.key,\n value: part.value,\n share: part.value / total,\n widthPercent: part.value === 0 ? 0 : raisedKeys.has(index) ? minimumWidthPercent : (part.value / freeTotal) * freeWidth,\n }));\n};\n\n/**\n * A share as a percentage in `locale` (`12.4%`, German `12,4 %`): one decimal below 10 %, none from there, and\n * `<0.1%` for a share that would round to zero but is not zero.\n */\nexport const formatProportionShare = (share: number, locale?: string): string => {\n const safeShare = Number.isFinite(share) && share > 0 ? Math.min(share, 1) : 0;\n const smallest = 0.001;\n if (safeShare > 0 && safeShare < smallest) {\n return `<${new Intl.NumberFormat(locale, { style: \"percent\", minimumFractionDigits: 1, maximumFractionDigits: 1 }).format(smallest)}`;\n }\n const fractionDigits = safeShare > 0 && safeShare < 0.1 ? 1 : 0;\n return new Intl.NumberFormat(locale, { style: \"percent\", minimumFractionDigits: fractionDigits, maximumFractionDigits: fractionDigits }).format(safeShare);\n};\n","import { getUiLocale, useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { cn } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { Tooltip, TooltipContent, TooltipTrigger } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { type ReactNode, useMemo, useState } from \"react\";\nimport { computeProportionShares, formatProportionShare } from \"./proportion-bar\";\n\n/** One part of the whole a `ProportionBar` draws. */\nexport interface ProportionBarSegment {\n /** Stable identity of the part (the argument of `onSegmentSelect`). */\n key: string;\n /** The part's size; the bar weighs the parts by it. */\n value: number;\n /** The fill as a colour token class (`bg-primary`, a class of `SERIES_FILL_CLASS_NAMES`); never a colour value. */\n colorClassName: string;\n /** The part's name, already translated. */\n label: string;\n /** After the label in the legend (a count such as `×3`), already translated. */\n badge?: ReactNode;\n /** The value as text; default `formatValue(value)`. */\n valueText?: string;\n}\n\nexport interface ProportionBarProps {\n segments: readonly ProportionBarSegment[];\n /** Accessible name of the bar: what the whole is (\"Context of this model call by segment\"). */\n \"aria-label\": string;\n /** With it every part of the bar and every legend chip is a button calling it. */\n onSegmentSelect?: (key: string) => void;\n /** The value of a part as text (bar tooltip, legend); default the grouped number in the UI language's locale. */\n formatValue?: (value: number) => string;\n /** The legend below the bar: colour mark, label, value and share per part. Default `true`. */\n showLegend?: boolean;\n /** The share after the value in the legend (`12%`). Default `true`. */\n showShare?: boolean;\n /** `sm`: a 6 px line for a table row. `md` (default): a 20 px bar. */\n size?: \"sm\" | \"md\";\n /** The smallest width in percent a part with a value takes. Default 0.75. */\n minimumWidthPercent?: number;\n className?: string;\n legendClassName?: string;\n}\n\nconst formatGroupedNumber = (value: number): string => new Intl.NumberFormat(getUiLocale(), { maximumFractionDigits: 0 }).format(value);\n\n/**\n * Parts of one whole as a single horizontal bar, each part as wide as its share, with a 2 px gap between parts, and\n * a legend that names every part with its value and share. Colour never stands alone: every part is named in the\n * legend and in its tooltip, and pointing at a legend entry marks its part in the bar. With `onSegmentSelect` the\n * parts and the legend entries are buttons (one tab stop each, the name says label, value and share); without it the\n * bar is one image with a text alternative and the legend a plain list.\n */\nexport const ProportionBar = ({\n segments,\n \"aria-label\": ariaLabel,\n onSegmentSelect,\n formatValue = formatGroupedNumber,\n showLegend = true,\n showShare = true,\n size = \"md\",\n minimumWidthPercent,\n className,\n legendClassName,\n}: ProportionBarProps) => {\n // re-renders on a language change, so numbers and shares follow the active language\n useTranslate();\n const [highlightedKey, setHighlightedKey] = useState<string | null>(null);\n const shares = useMemo(\n () => computeProportionShares(segments, { minimumWidthPercent }),\n [segments, minimumWidthPercent],\n );\n const locale = getUiLocale();\n const parts = segments.map((segment, index) => {\n const share = shares[index];\n const valueText = segment.valueText ?? formatValue(share?.value ?? 0);\n const shareText = formatProportionShare(share?.share ?? 0, locale);\n return { segment, widthPercent: share?.widthPercent ?? 0, valueText, shareText, name: `${segment.label}: ${valueText} (${shareText})` };\n });\n const isInteractive = onSegmentSelect !== undefined;\n const dimmedClassName = (key: string) => (highlightedKey !== null && highlightedKey !== key ? \"opacity-35\" : undefined);\n\n return (\n <div data-slot=\"proportion-bar\" className={cn(\"min-w-0\", className)}>\n <div\n role={isInteractive ? \"group\" : \"img\"}\n aria-label={isInteractive ? ariaLabel : `${ariaLabel}: ${parts.map((part) => part.name).join(\"; \")}`}\n className={cn(\"flex w-full gap-0.5 overflow-hidden\", size === \"sm\" ? \"h-1.5 rounded-full\" : \"h-5 rounded-md\")}\n >\n {parts.map(({ segment, widthPercent, name, valueText, shareText }) => {\n if (widthPercent <= 0) return null;\n const partClassName = cn(\n \"h-full min-w-[3px] rounded-[2px] transition-opacity\",\n segment.colorClassName,\n dimmedClassName(segment.key),\n );\n const partStyle = { flex: `${widthPercent} 1 0%` };\n const tooltip = (\n <TooltipContent>\n <span className=\"font-medium\">{segment.label}</span>\n <span className=\"tabular-nums\">\n {\" \"}\n · {valueText} · {shareText}\n </span>\n </TooltipContent>\n );\n return (\n <Tooltip key={segment.key}>\n <TooltipTrigger asChild>\n {isInteractive ? (\n <button\n type=\"button\"\n data-proportion-key={segment.key}\n aria-label={name}\n className={cn(partClassName, \"cursor-pointer outline-none hover:brightness-110 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset\")}\n style={partStyle}\n onClick={() => onSegmentSelect(segment.key)}\n onPointerEnter={() => setHighlightedKey(segment.key)}\n onPointerLeave={() => setHighlightedKey(null)}\n />\n ) : (\n <span data-proportion-key={segment.key} aria-hidden className={partClassName} style={partStyle} />\n )}\n </TooltipTrigger>\n {tooltip}\n </Tooltip>\n );\n })}\n </div>\n {showLegend && (\n <ul data-slot=\"proportion-bar-legend\" aria-label={isInteractive ? undefined : ariaLabel} className={cn(\"mt-2 flex flex-wrap gap-1.5\", legendClassName)}>\n {parts.map(({ segment, valueText, shareText, name }) => {\n const content = (\n <>\n <span aria-hidden className={cn(\"size-2.5 shrink-0 rounded-[3px]\", segment.colorClassName)} />\n <span className=\"min-w-0 truncate text-foreground\">{segment.label}</span>\n {segment.badge !== undefined && segment.badge !== null && <span className=\"font-medium text-muted-foreground\">{segment.badge}</span>}\n <span className=\"shrink-0 text-muted-foreground tabular-nums\">\n {valueText}\n {showShare && ` · ${shareText}`}\n </span>\n </>\n );\n const chipClassName = \"inline-flex max-w-full items-center gap-1.5 rounded-md border bg-card px-2 py-0.5 text-xs\";\n return (\n <li key={segment.key} className=\"min-w-0 max-w-full\">\n {isInteractive ? (\n <button\n type=\"button\"\n data-proportion-legend-key={segment.key}\n title={name}\n className={cn(chipClassName, \"cursor-pointer outline-none hover:bg-tint focus-visible:ring-2 focus-visible:ring-ring\")}\n onClick={() => onSegmentSelect(segment.key)}\n onPointerEnter={() => setHighlightedKey(segment.key)}\n onPointerLeave={() => setHighlightedKey(null)}\n onFocus={() => setHighlightedKey(segment.key)}\n onBlur={() => setHighlightedKey(null)}\n >\n {content}\n </button>\n ) : (\n <span\n data-proportion-legend-key={segment.key}\n title={name}\n className={chipClassName}\n onPointerEnter={() => setHighlightedKey(segment.key)}\n onPointerLeave={() => setHighlightedKey(null)}\n >\n {content}\n </span>\n )}\n </li>\n );\n })}\n </ul>\n )}\n </div>\n );\n};\n","/**\n * Fill classes for parts of a whole (proportion bars, legends): the slots of the host's categorical series palette\n * (`--series-1` … `--series-8`, a fixed, validated order) and two neutral slots. A host without the series properties\n * gets the colour role named as the fallback. Each slot has three steps of one hue (full, 70 %, 45 %): neighbours of the\n * same kind take different steps, so the 2 px gap between them is not the only thing that separates them. The classes\n * are literals, so the host's Tailwind build finds them in the package's JavaScript.\n */\nexport type SeriesFillSlot = \"series1\" | \"series2\" | \"series3\" | \"series4\" | \"series5\" | \"series6\" | \"series7\" | \"series8\" | \"neutral\" | \"ink\";\n\n/** The three steps of one slot, strongest first. */\nexport type SeriesFillSteps = readonly [string, string, string];\n\nexport const SERIES_FILL_CLASS_NAMES: Readonly<Record<SeriesFillSlot, SeriesFillSteps>> = {\n series1: [\n \"bg-[color:var(--series-1,var(--brand))]\",\n \"bg-[color:var(--series-1,var(--brand))]/70\",\n \"bg-[color:var(--series-1,var(--brand))]/45\",\n ],\n series2: [\n \"bg-[color:var(--series-2,var(--warning))]\",\n \"bg-[color:var(--series-2,var(--warning))]/70\",\n \"bg-[color:var(--series-2,var(--warning))]/45\",\n ],\n series3: [\n \"bg-[color:var(--series-3,var(--primary))]\",\n \"bg-[color:var(--series-3,var(--primary))]/70\",\n \"bg-[color:var(--series-3,var(--primary))]/45\",\n ],\n series4: [\n \"bg-[color:var(--series-4,var(--warning))]\",\n \"bg-[color:var(--series-4,var(--warning))]/70\",\n \"bg-[color:var(--series-4,var(--warning))]/45\",\n ],\n series5: [\n \"bg-[color:var(--series-5,var(--destructive))]\",\n \"bg-[color:var(--series-5,var(--destructive))]/70\",\n \"bg-[color:var(--series-5,var(--destructive))]/45\",\n ],\n series6: [\n \"bg-[color:var(--series-6,var(--success))]\",\n \"bg-[color:var(--series-6,var(--success))]/70\",\n \"bg-[color:var(--series-6,var(--success))]/45\",\n ],\n series7: [\n \"bg-[color:var(--series-7,var(--info))]\",\n \"bg-[color:var(--series-7,var(--info))]/70\",\n \"bg-[color:var(--series-7,var(--info))]/45\",\n ],\n series8: [\n \"bg-[color:var(--series-8,var(--destructive))]\",\n \"bg-[color:var(--series-8,var(--destructive))]/70\",\n \"bg-[color:var(--series-8,var(--destructive))]/45\",\n ],\n neutral: [\"bg-muted-foreground\", \"bg-muted-foreground/60\", \"bg-muted-foreground/30\"],\n ink: [\"bg-foreground/80\", \"bg-foreground/55\", \"bg-foreground/30\"],\n};\n\n/** The fill class of a slot for the n-th part of that slot (0-based): the steps repeat, strongest first. */\nexport const seriesFillClassNameOf = (slot: SeriesFillSlot, positionInSlot = 0): string => {\n const steps = SERIES_FILL_CLASS_NAMES[slot];\n return steps[((positionInSlot % steps.length) + steps.length) % steps.length] ?? steps[0];\n};\n","export interface TokenFigureFormatOptions {\n /** `true` (default): the figure is an estimate and carries the mark `≈`. */\n isEstimate?: boolean;\n /** The `Intl` locale of the digits' grouping; default the runtime's. */\n locale?: string;\n}\n\n/** A token count as text: grouped digits in `locale`, `≈` before an estimate (`≈7,505`), `—` without a number. */\nexport const formatTokenFigure = (value: number | null | undefined, options: TokenFigureFormatOptions = {}): string => {\n if (value === null || value === undefined || !Number.isFinite(value)) return \"—\";\n const digits = new Intl.NumberFormat(options.locale, { maximumFractionDigits: 0 }).format(Math.round(value));\n return (options.isEstimate ?? true) ? `≈${digits}` : digits;\n};\n","import { getUiLocale, useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { cn } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport type { ReactNode } from \"react\";\nimport { formatTokenFigure } from \"./token-figure\";\n\nexport interface TokenFigureProps {\n /** The token count; `null` / `undefined` shows a dash. */\n value: number | null | undefined;\n /** `true` (default): an estimate, marked `≈`. */\n isEstimate?: boolean;\n /** The `Intl` locale of the digits; default the locale of the active UI language. */\n locale?: string;\n /** Shown after the figure in the muted colour (a unit such as \"tokens\"), already translated. */\n suffix?: ReactNode;\n className?: string;\n}\n\n/** A token count in tabular digits: `≈7,505` for an estimate, `7,505` for an exact count, in the UI language's locale. */\nexport const TokenFigure = ({ value, isEstimate = true, locale, suffix, className }: TokenFigureProps) => {\n // re-renders on a language change, so the digits follow the active language\n useTranslate();\n return (\n <span data-slot=\"token-figure\" className={cn(\"whitespace-nowrap tabular-nums\", className)}>\n {formatTokenFigure(value, { isEstimate, locale: locale ?? getUiLocale() })}\n {suffix !== undefined && suffix !== null && <span className=\"text-muted-foreground\"> {suffix}</span>}\n </span>\n );\n};\n","import {\n type ApiQueryHook,\n type InjectableBaseApi,\n type InjectedEndpointDefinition,\n type InjectedRequest,\n injectEndpointsOnce,\n type StaticQueryFailure,\n staticQueryHook,\n trimApiPrefix,\n} from \"@mgamadeus/ddd-admin-ui/logic/pure\";\nimport type { AgentContextCompositionResponse, AgentInspectMessageArg, AgentSentPayloadResponse } from \"./agent-inspect-context-types\";\n\n/** The cache tag type of the context reads (ids `COMPOSITION`, `PAYLOAD`). */\nexport const AGENT_INSPECT_CONTEXT_TAG = \"AdminUiAgentInspectContext\";\n\n/** The hooks `createAgentInspectContextApi` returns; `ContextCompositionPanel` and `SentPayloadPanel` take them as `api`. */\nexport interface AgentInspectContextApi {\n /** `GET /{conversationId}/messages/{messageId}/contextComposition`: the segments of that message's model call. */\n useContextCompositionQuery: ApiQueryHook<AgentInspectMessageArg, AgentContextCompositionResponse>;\n /** `GET /{conversationId}/messages/{messageId}/sentPayload`: the request body of that message's model call. */\n useSentPayloadQuery: ApiQueryHook<AgentInspectMessageArg, AgentSentPayloadResponse>;\n}\n\nexport interface CreateAgentInspectContextApiOptions {\n /** The host's RTK Query api (`createApi` with the React hooks module). */\n baseApi: InjectableBaseApi;\n /** Where the host mounts the conversation inspection routes, without a trailing slash (`/api/admin/ai/conversations`). */\n apiPrefix: string;\n}\n\n/** The request of every operation, on `apiPrefix`. Pure: no RTK runtime. */\nexport const buildAgentInspectContextRequests = (apiPrefix: string) => {\n const prefix = trimApiPrefix(apiPrefix);\n const messagePath = ({ conversationId, messageId }: AgentInspectMessageArg): string =>\n `${prefix}/${encodeURIComponent(String(conversationId))}/messages/${encodeURIComponent(String(messageId))}`;\n return {\n contextComposition: (arg: AgentInspectMessageArg): InjectedRequest => ({ url: `${messagePath(arg)}/contextComposition` }),\n sentPayload: (arg: AgentInspectMessageArg): InjectedRequest => ({ url: `${messagePath(arg)}/sentPayload` }),\n };\n};\n\nconst COMPOSITION = { type: AGENT_INSPECT_CONTEXT_TAG, id: \"COMPOSITION\" } as const;\nconst PAYLOAD = { type: AGENT_INSPECT_CONTEXT_TAG, id: \"PAYLOAD\" } as const;\n\n/** The operations as injected. */\nexport const agentInspectContextEndpointDefinitions = (apiPrefix: string) => {\n const requests = buildAgentInspectContextRequests(apiPrefix);\n return {\n adminUiAgentContextComposition: { kind: \"query\", request: requests.contextComposition, providesTags: [COMPOSITION] },\n adminUiAgentSentPayload: { kind: \"query\", request: requests.sentPayload, providesTags: [PAYLOAD] },\n } as const satisfies Record<string, InjectedEndpointDefinition<never>>;\n};\n\n/**\n * Injects the context reads into the host's RTK Query api and returns their hooks. Call it once at module scope:\n * `export const agentInspectContextApi = createAgentInspectContextApi({ baseApi: adminApi, apiPrefix: \"/api/admin/ai/conversations\" });`\n */\nexport const createAgentInspectContextApi = ({ baseApi, apiPrefix }: CreateAgentInspectContextApiOptions): AgentInspectContextApi =>\n injectEndpointsOnce(\n baseApi,\n `agentInspectContext:${trimApiPrefix(apiPrefix)}`,\n [AGENT_INSPECT_CONTEXT_TAG],\n agentInspectContextEndpointDefinitions(apiPrefix),\n (hookOf) => ({\n useContextCompositionQuery: hookOf(\"adminUiAgentContextComposition\") as AgentInspectContextApi[\"useContextCompositionQuery\"],\n useSentPayloadQuery: hookOf(\"adminUiAgentSentPayload\") as AgentInspectContextApi[\"useSentPayloadQuery\"],\n }),\n );\n\n/** Fixed answers of a `createStaticAgentInspectContextApi`; a query without one stays loading. */\nexport interface StaticAgentInspectContextData {\n contextComposition?: (arg: AgentInspectMessageArg) => AgentContextCompositionResponse | StaticQueryFailure | undefined;\n sentPayload?: (arg: AgentInspectMessageArg) => AgentSentPayloadResponse | StaticQueryFailure | undefined;\n}\n\n/** An `AgentInspectContextApi` answering fixed payloads, without a store or a request (previews, tests, reviews). */\nexport const createStaticAgentInspectContextApi = (data: StaticAgentInspectContextData): AgentInspectContextApi => ({\n useContextCompositionQuery: staticQueryHook((arg) => data.contextComposition?.(arg)),\n useSentPayloadQuery: staticQueryHook((arg) => data.sentPayload?.(arg)),\n});\n","/**\n * Every kind of segment a model call's context is made of, as the backend names them\n * (`AgentContextSegmentType`): the parts of the composed system message in compose order, the two tool-schema blocks,\n * then the kinds of the wire message array.\n */\nexport const AGENT_CONTEXT_SEGMENT_TYPES = [\n \"BASE_PROMPT\",\n \"SUB_AGENT_DIRECTIVE\",\n \"PURPOSE_DIRECTIVE\",\n \"CONVERSATION_SUBJECT\",\n \"SCHEDULED_RUN_DIRECTIVE\",\n \"TIME_RULE\",\n \"OWNER_PRESENCE\",\n \"MEMORY_DIRECTIVES\",\n \"EPISODIC_HISTORY\",\n \"DAY_CONTEXT\",\n \"LOCAL_SITUATION\",\n \"PRODUCT_CAPABILITIES\",\n \"RESTRICTED_CAPABILITIES\",\n \"AI_BUDGET_AWARENESS\",\n \"SKILL_CATALOG\",\n \"LOADED_SKILLS\",\n \"QUERY_OPTIONS_SYNTAX\",\n \"SHARED_PARAMS\",\n \"ALREADY_FETCHED_READS\",\n \"TASK_PLAN\",\n \"ANSWER_CONTRACT\",\n \"COMPACTION_SUMMARY\",\n \"META_TOOL_SCHEMAS\",\n \"TOOL_SCHEMAS\",\n \"USER_MESSAGE\",\n \"ASSISTANT_MESSAGE\",\n \"TOOL_CALL\",\n \"TOOL_RESULT\",\n \"SIGNAL\",\n \"REPLY_LANGUAGE_CUE\",\n] as const;\n\nexport type AgentContextSegmentType = (typeof AGENT_CONTEXT_SEGMENT_TYPES)[number];\n\n/** A compaction cover node as far as a segment's label reads it; the node carries more. */\nexport interface AgentContextCompactionNode {\n level?: number | null;\n coveredFromMessageIndex?: number | null;\n coveredToMessageIndex?: number | null;\n [property: string]: unknown;\n}\n\n/**\n * One labelled piece of a model call's context (`AgentContextSegment`). `type` is one of\n * `AGENT_CONTEXT_SEGMENT_TYPES`; a newer backend may send a type this version does not know, which is shown with a\n * neutral colour and its own label.\n */\nexport interface AgentContextSegment {\n type: AgentContextSegmentType | (string & {});\n /** The backend's label of the segment (type plus provenance); older backends do not send it. */\n label?: string | null;\n /** The segment's content: a slice of the system text, or the wire JSON of a tool block or a message. */\n text?: string | null;\n tokenCount?: number | null;\n /** True: `tokenCount` is a characters / 4 estimate, shown with `≈`. */\n tokenCountIsEstimate?: boolean | null;\n /** Loaded skills: the conditional skill sections rendered (`Skill.Name[dimension=value]`). */\n skillSectionIds?: string[] | null;\n /** Loaded skills: the variants the sections were selected by (`dimension → value(provenance)`); `[]` when empty. */\n variants?: Record<string, string> | unknown[] | null;\n /** The skills (or tools) the segment carries: loaded skills, offered skills, the tools of a schema block. */\n skillNames?: string[] | null;\n /** Compaction summary: the cover nodes it was rendered from, as a set (`elements`) or a plain list. */\n compactionNodes?: { elements?: AgentContextCompactionNode[] | null } | AgentContextCompactionNode[] | null;\n /** A wire message or an already fetched read: the index of the conversation message it comes from. */\n sourceMessageIndex?: number | null;\n /** Purpose directive: the purpose name. */\n purposeName?: string | null;\n /** Purpose directive: the purpose this one inherits its plan from. */\n purposeInheritsFromName?: string | null;\n}\n\n/** The whole breakdown of one model call (`ModelCallComposition`). */\nexport interface AgentModelCallComposition {\n systemSegments?: AgentContextSegment[] | null;\n toolSchemaSegments?: AgentContextSegment[] | null;\n messageSegments?: AgentContextSegment[] | null;\n /** True: the message made no model call (no request snapshot), so there is nothing to show. */\n isUnavailable?: boolean | null;\n /**\n * True: rebuilt from the stored rows and the current prompt, skills and memory, so it may differ from what was sent.\n * False: as sent. Null when unavailable.\n */\n isReconstructed?: boolean | null;\n}\n\n/** Where a conversation's compaction threshold comes from (`CompactionThresholdBreakdown::SOURCE_*`). */\nexport type AgentCompactionThresholdSource = \"conversationOverride\" | \"purposeContextBudget\" | \"modelEffective\" | \"defaultFallback\";\n\n/** The compaction threshold in effect for a conversation and how full the context is (`CompactionThresholdBreakdown`). */\nexport interface AgentCompactionThreshold {\n thresholdTokens?: number | null;\n source?: AgentCompactionThresholdSource | (string & {}) | null;\n latestContextInputTokens?: number | null;\n isDue?: boolean | null;\n modelName?: string | null;\n modelEffectiveContextTokens?: number | null;\n conversationTriggerTokens?: number | null;\n defaultFallbackTokens?: number | null;\n purposeName?: string | null;\n purposeContextBudgetTokens?: number | null;\n compactionNodeCount?: number | null;\n}\n\n/** The arguments of both reads: one message of one conversation. */\nexport interface AgentInspectMessageArg {\n conversationId: number | string;\n messageId: number | string;\n}\n\n/**\n * `GET {prefix}/{conversationId}/messages/{messageId}/contextComposition`. The module's routes answer the breakdown as\n * `composition` with the reconstruction mark beside it; an answer that names it `contextComposition` (the mark inside)\n * is read alike. Read the breakdown with `agentContextCompositionOf`, never by field name.\n */\nexport interface AgentContextCompositionResponse {\n contextComposition?: AgentModelCallComposition | null;\n composition?: AgentModelCallComposition | null;\n /** The reconstruction mark of an answer that carries it beside `composition`. */\n isReconstructed?: boolean | null;\n compactionThreshold?: AgentCompactionThreshold | null;\n}\n\n/** `GET {prefix}/{conversationId}/messages/{messageId}/sentPayload`. */\nexport interface AgentSentPayloadResponse {\n /** The request body of the model call: an object, or its JSON text. */\n payload?: unknown;\n /** True: the payload stored when the call was made. False: rebuilt from the stored rows and the current state. */\n isStoredPayload?: boolean | null;\n}\n","import { formatUiNumber, getUiLocale, useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { Badge } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { cn } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { TokenFigure } from \"../blocks/TokenFigure\";\nimport type { AgentCompactionThreshold } from \"./agent-inspect-context-types\";\n\nexport interface CompactionThresholdBannerProps {\n threshold: AgentCompactionThreshold;\n className?: string;\n}\n\n/** The context's fill of the threshold in whole percent, or `null` when one of the two is unknown. */\nexport const compactionThresholdFillPercentOf = (threshold: AgentCompactionThreshold): number | null => {\n const limit = threshold.thresholdTokens ?? 0;\n const current = threshold.latestContextInputTokens;\n if (limit <= 0 || current === null || current === undefined) return null;\n return Math.round((current / limit) * 100);\n};\n\n/**\n * The compaction threshold in effect for the conversation: its size, whether compaction is due, where the threshold\n * comes from (an override on the conversation, the purpose's context budget, the model, the default), how full the\n * context is now and how many compaction nodes exist.\n */\nexport const CompactionThresholdBanner = ({ threshold, className }: CompactionThresholdBannerProps) => {\n const { t } = useTranslate();\n const limit = threshold.thresholdTokens ?? 0;\n const current = threshold.latestContextInputTokens ?? null;\n const fillPercent = compactionThresholdFillPercentOf(threshold);\n const fillShareText = fillPercent === null ? \"\" : new Intl.NumberFormat(getUiLocale(), { style: \"percent\", maximumFractionDigits: 0 }).format(fillPercent / 100);\n const isDue = threshold.isDue === true;\n const sourceText = (() => {\n switch (threshold.source) {\n case \"conversationOverride\":\n return t(\"Source: override on this conversation (trigger at %tokens% tokens).\", {\n replacements: { tokens: formatUiNumber(threshold.conversationTriggerTokens ?? limit) },\n });\n case \"purposeContextBudget\":\n return t(\"Source: context budget of the purpose %purpose% (%tokens% tokens, within the model's window).\", {\n replacements: { purpose: threshold.purposeName ?? \"?\", tokens: formatUiNumber(threshold.purposeContextBudgetTokens ?? limit) },\n });\n case \"modelEffective\":\n return t(\"Source: effective context of the model %model% (without a model the default would be %tokens% tokens).\", {\n replacements: { model: threshold.modelName ?? \"?\", tokens: formatUiNumber(threshold.defaultFallbackTokens ?? 0) },\n });\n default:\n return t(\"Source: default (no model override on this conversation).\");\n }\n })();\n return (\n <div data-slot=\"compaction-threshold\" className={cn(\"rounded-xl border bg-card px-3 py-2.5\", className)}>\n <div className=\"flex flex-wrap items-center gap-x-3 gap-y-1\">\n <span className=\"text-sm font-medium\">\n {t(\"Compaction threshold\")}: <TokenFigure value={limit} isEstimate={false} suffix={t(\"tokens\")} />\n </span>\n <Badge variant={isDue ? \"warning\" : \"success\"}>{isDue ? t(\"Compaction is due\") : t(\"Under the threshold\")}</Badge>\n </div>\n {fillPercent !== null && (\n <div\n role=\"meter\"\n aria-label={t(\"Context fill of the compaction threshold\")}\n aria-valuemin={0}\n aria-valuemax={100}\n aria-valuenow={Math.min(100, fillPercent)}\n aria-valuetext={fillShareText}\n className=\"mt-2 h-1.5 w-full overflow-hidden rounded-full bg-muted\"\n >\n <div className={cn(\"h-full rounded-full\", isDue ? \"bg-warning\" : \"bg-success\")} style={{ width: `${Math.min(100, Math.max(0, fillPercent))}%` }} />\n </div>\n )}\n <p className=\"mt-2 text-xs text-muted-foreground\">\n {t(\"Context now\")}: {current === null ? \"—\" : <TokenFigure value={current} suffix={t(\"tokens\")} />}\n {fillPercent !== null && ` (${t(\"%share% of the threshold\", { replacements: { share: fillShareText } })})`}\n {\" · \"}\n {t(\"Compaction nodes\")}: {formatUiNumber(threshold.compactionNodeCount ?? 0)}\n </p>\n <p className=\"mt-0.5 text-xs text-muted-foreground\">{sourceText}</p>\n </div>\n );\n};\n","import { AGENT_CONTEXT_SEGMENT_TYPES, type AgentContextCompactionNode, type AgentContextSegment, type AgentContextSegmentType } from \"./agent-inspect-context-types\";\n\n/**\n * The label of every segment type for a backend that does not send `label` yet: the fixed part of what the backend's\n * `AgentContextSegment::getLabel()` writes. The types whose label carries provenance (purpose, skills, compaction\n * nodes) get it added in `agentContextSegmentLabelOf`. Technical names, like the backend's own label (the copied text\n * carries them); the screens show the translated names of `translateAgentContextSegmentLabel`.\n */\nexport const AGENT_CONTEXT_SEGMENT_TYPE_LABELS: Readonly<Record<AgentContextSegmentType, string>> = {\n BASE_PROMPT: \"System prompt\",\n SUB_AGENT_DIRECTIVE: \"Sub-agent directive\",\n PURPOSE_DIRECTIVE: \"Conversation purpose directive\",\n CONVERSATION_SUBJECT: \"Record of this conversation (subject)\",\n SCHEDULED_RUN_DIRECTIVE: \"Scheduled run directive\",\n TIME_RULE: \"Time rule\",\n OWNER_PRESENCE: \"Owner presence (who the agent is talking to)\",\n MEMORY_DIRECTIVES: \"Standing instructions (memory)\",\n EPISODIC_HISTORY: \"Recent sessions (episodic history)\",\n DAY_CONTEXT: \"Day context (what the application noted for the day)\",\n LOCAL_SITUATION: \"Local situation (what goes on around the space)\",\n PRODUCT_CAPABILITIES: \"Product plan & capabilities\",\n RESTRICTED_CAPABILITIES: \"Restricted for this user (account rights)\",\n AI_BUDGET_AWARENESS: \"AI budget awareness\",\n SKILL_CATALOG: \"Skill catalog\",\n LOADED_SKILLS: \"Loaded skills\",\n QUERY_OPTIONS_SYNTAX: \"QueryOptions syntax\",\n SHARED_PARAMS: \"Shared request parameters\",\n ALREADY_FETCHED_READS: \"Data already fetched (reuse)\",\n TASK_PLAN: \"Task plan\",\n ANSWER_CONTRACT: \"Answer contract (completed writes)\",\n COMPACTION_SUMMARY: \"Compaction summary\",\n META_TOOL_SCHEMAS: \"Meta tool schemas\",\n TOOL_SCHEMAS: \"Skill tool schemas\",\n USER_MESSAGE: \"User message\",\n ASSISTANT_MESSAGE: \"Assistant reply\",\n TOOL_CALL: \"Tool call\",\n TOOL_RESULT: \"Tool result\",\n SIGNAL: \"Signal\",\n REPLY_LANGUAGE_CUE: \"Reply-language cue\",\n};\n\nconst KNOWN_TYPES: ReadonlySet<string> = new Set(AGENT_CONTEXT_SEGMENT_TYPES);\n\n/** True for a type of `AGENT_CONTEXT_SEGMENT_TYPES`. */\nexport const isKnownAgentContextSegmentType = (type: string): type is AgentContextSegmentType => KNOWN_TYPES.has(type);\n\n/** The cover nodes of a compaction segment, whether they arrive as a set (`elements`) or as a list. */\nexport const agentContextCompactionNodesOf = (segment: AgentContextSegment): AgentContextCompactionNode[] => {\n const nodes = segment.compactionNodes;\n if (Array.isArray(nodes)) return nodes;\n return nodes?.elements ?? [];\n};\n\n/** The variants of a segment as `dimension → value`; an empty list (how an empty map arrives) gives none. */\nexport const agentContextSegmentVariantsOf = (segment: AgentContextSegment): Record<string, string> => {\n const variants = segment.variants;\n if (variants === null || variants === undefined || Array.isArray(variants)) return {};\n return Object.fromEntries(Object.entries(variants).filter((entry): entry is [string, string] => typeof entry[1] === \"string\"));\n};\n\nconst hasEntries = (list: readonly string[] | null | undefined): list is readonly string[] => Array.isArray(list) && list.length > 0;\n\n/** The label built from the type and the provenance, as the backend builds it; an unknown type is its own label. */\nexport const buildAgentContextSegmentFallbackLabel = (segment: AgentContextSegment): string => {\n const type = segment.type;\n if (!isKnownAgentContextSegmentType(type)) return type === \"\" ? \"Segment\" : type;\n const base = AGENT_CONTEXT_SEGMENT_TYPE_LABELS[type];\n switch (type) {\n case \"PURPOSE_DIRECTIVE\":\n return `${base}${segment.purposeName ? `: ${segment.purposeName}` : \"\"}${segment.purposeInheritsFromName ? ` (inherits ${segment.purposeInheritsFromName})` : \"\"}`;\n case \"SKILL_CATALOG\":\n return `${base} (${segment.skillNames?.length ?? 0} offered)`;\n case \"META_TOOL_SCHEMAS\":\n case \"TOOL_SCHEMAS\":\n return `${base} (${segment.skillNames?.length ?? 0})`;\n case \"LOADED_SKILLS\":\n return `${hasEntries(segment.skillNames) ? `${base}: ${segment.skillNames.join(\", \")}` : base}${hasEntries(segment.skillSectionIds) ? ` · sections: ${segment.skillSectionIds.join(\", \")}` : \"\"}`;\n case \"COMPACTION_SUMMARY\": {\n const nodes = agentContextCompactionNodesOf(segment);\n if (nodes.length === 0) return base;\n return `${base} · ${nodes.map((node) => `L${node.level ?? 0} [${node.coveredFromMessageIndex ?? 0}–${node.coveredToMessageIndex ?? 0}]`).join(\" · \")}`;\n }\n default:\n return base;\n }\n};\n\n/** The label of a segment: the backend's `label` when it sends one, else the label built from type and provenance. */\nexport const agentContextSegmentLabelOf = (segment: AgentContextSegment): string => {\n const label = typeof segment.label === \"string\" ? segment.label.trim() : \"\";\n return label !== \"\" ? label : buildAgentContextSegmentFallbackLabel(segment);\n};\n","import { type SeriesFillSlot, seriesFillClassNameOf } from \"../blocks/series-fill-classes\";\nimport type { AgentContextSegmentType } from \"./agent-inspect-context-types\";\nimport { isKnownAgentContextSegmentType } from \"./context-segment-labels\";\n\n/** The colour families of a model call's context: one hue per family, shared by the bar, the legend and the modal. */\nexport type AgentContextSegmentFamily =\n | \"system\"\n | \"skills\"\n | \"toolSchemas\"\n | \"compaction\"\n | \"fetchedReads\"\n | \"user\"\n | \"assistant\"\n | \"toolCalls\"\n | \"toolResults\"\n | \"signals\";\n\n/**\n * The fill slot of every family, defined once. Eight families take the host's categorical series colours; the tool\n * schemas (a large, constant block) and the platform's own signals and cues take the two neutral slots.\n */\nexport const AGENT_CONTEXT_FAMILY_FILL_SLOTS: Readonly<Record<AgentContextSegmentFamily, SeriesFillSlot>> = {\n system: \"series4\",\n skills: \"series7\",\n toolSchemas: \"neutral\",\n compaction: \"series3\",\n fetchedReads: \"series6\",\n user: \"series1\",\n assistant: \"series5\",\n toolCalls: \"series2\",\n toolResults: \"series8\",\n signals: \"ink\",\n};\n\n/** The family of every segment type. */\nexport const AGENT_CONTEXT_SEGMENT_TYPE_FAMILIES: Readonly<Record<AgentContextSegmentType, AgentContextSegmentFamily>> = {\n BASE_PROMPT: \"system\",\n SUB_AGENT_DIRECTIVE: \"system\",\n PURPOSE_DIRECTIVE: \"system\",\n CONVERSATION_SUBJECT: \"system\",\n SCHEDULED_RUN_DIRECTIVE: \"system\",\n TIME_RULE: \"system\",\n OWNER_PRESENCE: \"system\",\n MEMORY_DIRECTIVES: \"system\",\n EPISODIC_HISTORY: \"system\",\n DAY_CONTEXT: \"system\",\n LOCAL_SITUATION: \"system\",\n PRODUCT_CAPABILITIES: \"system\",\n RESTRICTED_CAPABILITIES: \"system\",\n AI_BUDGET_AWARENESS: \"system\",\n SKILL_CATALOG: \"skills\",\n LOADED_SKILLS: \"skills\",\n QUERY_OPTIONS_SYNTAX: \"skills\",\n SHARED_PARAMS: \"skills\",\n ALREADY_FETCHED_READS: \"fetchedReads\",\n TASK_PLAN: \"signals\",\n ANSWER_CONTRACT: \"signals\",\n COMPACTION_SUMMARY: \"compaction\",\n META_TOOL_SCHEMAS: \"toolSchemas\",\n TOOL_SCHEMAS: \"toolSchemas\",\n USER_MESSAGE: \"user\",\n ASSISTANT_MESSAGE: \"assistant\",\n TOOL_CALL: \"toolCalls\",\n TOOL_RESULT: \"toolResults\",\n SIGNAL: \"signals\",\n REPLY_LANGUAGE_CUE: \"signals\",\n};\n\n/** The family of a segment type; a type this version does not know reads as a signal (neutral). */\nexport const agentContextSegmentFamilyOf = (type: string): AgentContextSegmentFamily =>\n isKnownAgentContextSegmentType(type) ? AGENT_CONTEXT_SEGMENT_TYPE_FAMILIES[type] : \"signals\";\n\n/**\n * The fill class of a family for its n-th part (0-based): parts of one family that sit side by side take the family's\n * three steps in turn.\n */\nexport const agentContextFamilyFillClassNameOf = (family: AgentContextSegmentFamily, positionInFamily = 0): string =>\n seriesFillClassNameOf(AGENT_CONTEXT_FAMILY_FILL_SLOTS[family], positionInFamily);\n","import { m } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport type { AgentContextCompositionResponse, AgentContextSegment, AgentModelCallComposition } from \"./agent-inspect-context-types\";\nimport { type AgentContextSegmentFamily, agentContextFamilyFillClassNameOf, agentContextSegmentFamilyOf } from \"./context-segment-families\";\nimport { agentContextSegmentLabelOf } from \"./context-segment-labels\";\n\n/** The translation context of the role group names. */\nexport const AGENT_CONTEXT_TEXT_CONTEXT = \"agent-context\";\n\n/**\n * The plural name of a role group of the message tail, as an English text key (the panel translates it with the\n * context `AGENT_CONTEXT_TEXT_CONTEXT`). A tail type without an entry (a cue, a task plan) keeps its segment label.\n */\nexport const AGENT_CONTEXT_TAIL_GROUP_LABELS: Readonly<Record<string, string>> = {\n USER_MESSAGE: m(\"User messages\", { context: \"agent-context\" }),\n ASSISTANT_MESSAGE: m(\"Assistant replies\", { context: \"agent-context\" }),\n TOOL_CALL: m(\"Tool calls\", { context: \"agent-context\" }),\n TOOL_RESULT: m(\"Tool results\", { context: \"agent-context\" }),\n SIGNAL: m(\"Signals\", { context: \"agent-context\" }),\n};\n\n/** The fixed order of the role groups; other tail types follow in the order they first appear. */\nexport const AGENT_CONTEXT_TAIL_GROUP_ORDER: readonly string[] = [\"USER_MESSAGE\", \"ASSISTANT_MESSAGE\", \"TOOL_CALL\", \"TOOL_RESULT\", \"SIGNAL\"];\n\n/** One part of the composition bar and its legend entry: a structural segment, or the messages of one role. */\nexport interface AgentContextCompositionEntry {\n key: string;\n /** The entry's name: a segment label (shown as it is), or the text key of a role group (`isTextKey`). */\n label: string;\n /** True: `label` is an English text key the view translates (a role group name). */\n isTextKey: boolean;\n /** The segment type the entry stands for. */\n type: string;\n family: AgentContextSegmentFamily;\n /** The fill class of the entry (family hue, stepped within the family). */\n colorClassName: string;\n /** Σ of the tokens of the entry's segments. */\n tokenCount: number;\n /** True when a segment of the entry carries an estimate. */\n isEstimate: boolean;\n /** How many segments the entry holds (above 1 only for a role group of the message tail). */\n segmentCount: number;\n /** True for a part of the message tail (grouped by type). */\n isTailGroup: boolean;\n segments: AgentContextSegment[];\n}\n\nconst tokenCountOf = (segment: AgentContextSegment): number =>\n typeof segment.tokenCount === \"number\" && Number.isFinite(segment.tokenCount) && segment.tokenCount > 0 ? segment.tokenCount : 0;\n\n/**\n * The breakdown an answer of the composition read carries, under either of its two names (`contextComposition`, or\n * `composition` with the reconstruction mark beside it); null for an answer without one. The one place that reads the\n * answer: every panel and summary goes through it.\n */\nexport const agentContextCompositionOf = (response: AgentContextCompositionResponse | null | undefined): AgentModelCallComposition | null => {\n if (response?.contextComposition) return response.contextComposition;\n const composition = response?.composition ?? null;\n if (composition === null) return null;\n if (composition.isUnavailable === true) return { ...composition, isReconstructed: null };\n return typeof response?.isReconstructed === \"boolean\" ? { ...composition, isReconstructed: response.isReconstructed } : composition;\n};\n\n/** Every segment of the composition in the order the model reads it: system parts, tool schemas, wire messages. */\nexport const orderedAgentContextSegmentsOf = (composition: AgentModelCallComposition | null | undefined): AgentContextSegment[] => [\n ...(composition?.systemSegments ?? []),\n ...(composition?.toolSchemaSegments ?? []),\n ...(composition?.messageSegments ?? []),\n];\n\n/**\n * The parts of the composition bar: one entry per structural segment (system parts, tool-schema blocks) in order, then\n * the message tail grouped by type: the five message roles in their fixed order, then every other type the tail\n * carries. A long conversation therefore stays a handful of entries; a role group names how many messages it holds.\n * Entries of one family take the family's colour steps in turn.\n */\nexport const buildAgentContextCompositionEntries = (composition: AgentModelCallComposition | null | undefined): AgentContextCompositionEntry[] => {\n const positionsByFamily = new Map<AgentContextSegmentFamily, number>();\n const nextColorClassNameOf = (family: AgentContextSegmentFamily): string => {\n const position = positionsByFamily.get(family) ?? 0;\n positionsByFamily.set(family, position + 1);\n return agentContextFamilyFillClassNameOf(family, position);\n };\n\n const structuralSegments = [...(composition?.systemSegments ?? []), ...(composition?.toolSchemaSegments ?? [])];\n const structuralEntries = structuralSegments.map((segment, index): AgentContextCompositionEntry => {\n const family = agentContextSegmentFamilyOf(segment.type);\n return {\n key: `segment-${index}`,\n label: agentContextSegmentLabelOf(segment),\n isTextKey: false,\n type: segment.type,\n family,\n colorClassName: nextColorClassNameOf(family),\n tokenCount: tokenCountOf(segment),\n isEstimate: segment.tokenCountIsEstimate === true,\n segmentCount: 1,\n isTailGroup: false,\n segments: [segment],\n };\n });\n\n const tailSegmentsByType = new Map<string, AgentContextSegment[]>();\n for (const segment of composition?.messageSegments ?? []) {\n const segmentsOfType = tailSegmentsByType.get(segment.type);\n if (segmentsOfType) segmentsOfType.push(segment);\n else tailSegmentsByType.set(segment.type, [segment]);\n }\n const tailTypes = [\n ...AGENT_CONTEXT_TAIL_GROUP_ORDER.filter((type) => tailSegmentsByType.has(type)),\n ...[...tailSegmentsByType.keys()].filter((type) => !AGENT_CONTEXT_TAIL_GROUP_ORDER.includes(type)),\n ];\n const tailEntries = tailTypes.map((type): AgentContextCompositionEntry => {\n const segments = tailSegmentsByType.get(type) ?? [];\n const family = agentContextSegmentFamilyOf(type);\n const groupLabel = AGENT_CONTEXT_TAIL_GROUP_LABELS[type];\n const firstSegment = segments[0];\n return {\n key: `tail-${type}`,\n label: groupLabel ?? (firstSegment ? agentContextSegmentLabelOf(firstSegment) : type),\n isTextKey: groupLabel !== undefined,\n type,\n family,\n colorClassName: nextColorClassNameOf(family),\n tokenCount: segments.reduce((sum, segment) => sum + tokenCountOf(segment), 0),\n isEstimate: segments.some((segment) => segment.tokenCountIsEstimate === true),\n segmentCount: segments.length,\n isTailGroup: true,\n segments,\n };\n });\n return [...structuralEntries, ...tailEntries];\n};\n\n/** The figures of the line under the bar. */\nexport interface AgentContextCompositionSummary {\n /** Every segment: structural ones plus each wire message. */\n segmentCount: number;\n /** The wire messages among them. */\n messageSegmentCount: number;\n totalTokens: number;\n /** True when any segment's count is an estimate (the total is then one too). */\n isEstimate: boolean;\n}\n\nexport const summarizeAgentContextComposition = (composition: AgentModelCallComposition | null | undefined): AgentContextCompositionSummary => {\n const segments = orderedAgentContextSegmentsOf(composition);\n return {\n segmentCount: segments.length,\n messageSegmentCount: (composition?.messageSegments ?? []).length,\n totalTokens: segments.reduce((sum, segment) => sum + tokenCountOf(segment), 0),\n isEstimate: segments.some((segment) => segment.tokenCountIsEstimate === true),\n };\n};\n\n/** A segment as the detail modal lists it: label, colour, tokens, the text. */\nexport interface AgentContextSegmentView {\n key: string;\n label: string;\n colorClassName: string;\n tokenCount: number | null;\n isEstimate: boolean;\n text: string;\n segment: AgentContextSegment;\n}\n\n/**\n * The segments of the whole composition in reading order, each with the colour of the bar entry it belongs to (a wire\n * message takes its role group's colour), for \"View whole context\".\n */\nexport const buildAgentContextSegmentViews = (\n composition: AgentModelCallComposition | null | undefined,\n entries: readonly AgentContextCompositionEntry[] = buildAgentContextCompositionEntries(composition),\n): AgentContextSegmentView[] => {\n const colorBySegment = new Map<AgentContextSegment, string>();\n for (const entry of entries) for (const segment of entry.segments) colorBySegment.set(segment, entry.colorClassName);\n return orderedAgentContextSegmentsOf(composition).map((segment, index) => ({\n key: `view-${index}`,\n label: agentContextSegmentLabelOf(segment),\n colorClassName: colorBySegment.get(segment) ?? agentContextFamilyFillClassNameOf(agentContextSegmentFamilyOf(segment.type)),\n tokenCount: typeof segment.tokenCount === \"number\" ? segment.tokenCount : null,\n isEstimate: segment.tokenCountIsEstimate === true,\n text: segment.text ?? \"\",\n segment,\n }));\n};\n\n/** The segments of one bar entry as the detail modal lists them, in order. */\nexport const buildAgentContextEntrySegmentViews = (entry: AgentContextCompositionEntry): AgentContextSegmentView[] =>\n entry.segments.map((segment, index) => ({\n key: `${entry.key}-${index}`,\n label: agentContextSegmentLabelOf(segment),\n colorClassName: entry.colorClassName,\n tokenCount: typeof segment.tokenCount === \"number\" ? segment.tokenCount : null,\n isEstimate: segment.tokenCountIsEstimate === true,\n text: segment.text ?? \"\",\n segment,\n }));\n\n/** The text Copy writes for a list of segments: one segment as it is, several under a heading line each. */\nexport const agentContextSegmentViewsToText = (views: readonly AgentContextSegmentView[]): string =>\n views.length === 1 ? (views[0]?.text ?? \"\") : views.map((view) => `===== ${view.label} =====\\n${view.text}`).join(\"\\n\\n\");\n","import { m, type TranslateFn } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport type { AgentContextSegment, AgentContextSegmentType } from \"./agent-inspect-context-types\";\nimport { AGENT_CONTEXT_TEXT_CONTEXT, type AgentContextCompositionEntry } from \"./context-composition-grouping\";\nimport { agentContextCompactionNodesOf, agentContextSegmentLabelOf, isKnownAgentContextSegmentType } from \"./context-segment-labels\";\n\n/** The translation context of the segment names. */\nexport const AGENT_CONTEXT_SEGMENT_TEXT_CONTEXT = \"agent-context-segment\";\n\n/**\n * The name of every segment type as an English text key (translated with `AGENT_CONTEXT_SEGMENT_TEXT_CONTEXT`). The\n * types that name a count (offered skills, tool schemas) are ICU plural messages filled with `count`; provenance\n * (purpose, loaded skills, compaction nodes) is added in `translateAgentContextSegmentLabel`. The wire carries the\n * type and its provenance only; the backend's own `label` stays the technical name for an unknown type.\n */\nexport const AGENT_CONTEXT_SEGMENT_TYPE_TEXTS: Readonly<Record<AgentContextSegmentType, string>> = {\n BASE_PROMPT: m(\"System prompt\", { context: \"agent-context-segment\" }),\n SUB_AGENT_DIRECTIVE: m(\"Sub-agent directive\", { context: \"agent-context-segment\" }),\n PURPOSE_DIRECTIVE: m(\"Conversation purpose directive\", { context: \"agent-context-segment\" }),\n CONVERSATION_SUBJECT: m(\"Record of this conversation (subject)\", { context: \"agent-context-segment\" }),\n SCHEDULED_RUN_DIRECTIVE: m(\"Scheduled run directive\", { context: \"agent-context-segment\" }),\n TIME_RULE: m(\"Time rule (time zone)\", { context: \"agent-context-segment\" }),\n OWNER_PRESENCE: m(\"Owner presence (who the agent is talking to)\", { context: \"agent-context-segment\" }),\n MEMORY_DIRECTIVES: m(\"Standing instructions (memory)\", { context: \"agent-context-segment\" }),\n EPISODIC_HISTORY: m(\"Recent sessions (episodic history)\", { context: \"agent-context-segment\" }),\n DAY_CONTEXT: m(\"Day context (what the application noted for the day)\", { context: \"agent-context-segment\" }),\n LOCAL_SITUATION: m(\"Local situation (what goes on around the space)\", { context: \"agent-context-segment\" }),\n PRODUCT_CAPABILITIES: m(\"Product plan & capabilities\", { context: \"agent-context-segment\" }),\n RESTRICTED_CAPABILITIES: m(\"Restricted for this user (account rights)\", { context: \"agent-context-segment\" }),\n AI_BUDGET_AWARENESS: m(\"AI budget awareness\", { context: \"agent-context-segment\" }),\n SKILL_CATALOG: m(\"{count, plural, one {Skill catalog (# skill offered)} other {Skill catalog (# skills offered)}}\", { context: \"agent-context-segment\" }),\n LOADED_SKILLS: m(\"Loaded skills\", { context: \"agent-context-segment\" }),\n QUERY_OPTIONS_SYNTAX: m(\"QueryOptions syntax\", { context: \"agent-context-segment\" }),\n SHARED_PARAMS: m(\"Shared request parameters\", { context: \"agent-context-segment\" }),\n ALREADY_FETCHED_READS: m(\"Data already fetched (reuse)\", { context: \"agent-context-segment\" }),\n TASK_PLAN: m(\"Task plan\", { context: \"agent-context-segment\" }),\n ANSWER_CONTRACT: m(\"Answer contract (completed writes)\", { context: \"agent-context-segment\" }),\n COMPACTION_SUMMARY: m(\"Compaction summary\", { context: \"agent-context-segment\" }),\n META_TOOL_SCHEMAS: m(\"{count, plural, one {Meta tool schemas (# tool)} other {Meta tool schemas (# tools)}}\", { context: \"agent-context-segment\" }),\n TOOL_SCHEMAS: m(\"{count, plural, one {Skill tool schemas (# tool)} other {Skill tool schemas (# tools)}}\", { context: \"agent-context-segment\" }),\n USER_MESSAGE: m(\"User message\", { context: \"agent-context-segment\" }),\n ASSISTANT_MESSAGE: m(\"Assistant reply\", { context: \"agent-context-segment\" }),\n TOOL_CALL: m(\"Tool call\", { context: \"agent-context-segment\" }),\n TOOL_RESULT: m(\"Tool result\", { context: \"agent-context-segment\" }),\n SIGNAL: m(\"Signal\", { context: \"agent-context-segment\" }),\n REPLY_LANGUAGE_CUE: m(\"Reply-language cue\", { context: \"agent-context-segment\" }),\n};\n\nconst PURPOSE_WITH_NAME = m(\"Conversation purpose directive: %purpose%\", { context: \"agent-context-segment\" });\nconst PURPOSE_WITH_PARENT = m(\"Conversation purpose directive: %purpose% (inherits %parent%)\", { context: \"agent-context-segment\" });\nconst LOADED_SKILLS_WITH_NAMES = m(\"Loaded skills: %skills%\", { context: \"agent-context-segment\" });\nconst SKILL_SECTIONS = m(\"sections: %sections%\", { context: \"agent-context-segment\" });\n\nconst hasEntries = (list: readonly string[] | null | undefined): list is readonly string[] => Array.isArray(list) && list.length > 0;\n\n/**\n * The name of a segment in the viewer's language: the type's text, its count and its provenance (names stay as they\n * are). A type the admin does not know keeps the backend's label.\n */\nexport const translateAgentContextSegmentLabel = (segment: AgentContextSegment, t: TranslateFn): string => {\n const type = segment.type;\n if (!isKnownAgentContextSegmentType(type)) return agentContextSegmentLabelOf(segment);\n const context = AGENT_CONTEXT_SEGMENT_TEXT_CONTEXT;\n const text = AGENT_CONTEXT_SEGMENT_TYPE_TEXTS[type];\n switch (type) {\n case \"PURPOSE_DIRECTIVE\": {\n if (!segment.purposeName) return t(text, { context });\n return segment.purposeInheritsFromName\n ? t(PURPOSE_WITH_PARENT, { context, replacements: { purpose: segment.purposeName, parent: segment.purposeInheritsFromName } })\n : t(PURPOSE_WITH_NAME, { context, replacements: { purpose: segment.purposeName } });\n }\n case \"SKILL_CATALOG\":\n case \"META_TOOL_SCHEMAS\":\n case \"TOOL_SCHEMAS\":\n return t(text, { context, count: segment.skillNames?.length ?? 0 });\n case \"LOADED_SKILLS\": {\n const base = hasEntries(segment.skillNames) ? t(LOADED_SKILLS_WITH_NAMES, { context, replacements: { skills: segment.skillNames.join(\", \") } }) : t(text, { context });\n return hasEntries(segment.skillSectionIds) ? `${base} · ${t(SKILL_SECTIONS, { context, replacements: { sections: segment.skillSectionIds.join(\", \") } })}` : base;\n }\n case \"COMPACTION_SUMMARY\": {\n const nodes = agentContextCompactionNodesOf(segment);\n const base = t(text, { context });\n if (nodes.length === 0) return base;\n return `${base} · ${nodes.map((node) => `L${node.level ?? 0} [${node.coveredFromMessageIndex ?? 0}–${node.coveredToMessageIndex ?? 0}]`).join(\" · \")}`;\n }\n default:\n return t(text, { context });\n }\n};\n\n/** The name of a bar entry in the viewer's language: a role group's text key, else the name of its first segment. */\nexport const translateAgentContextEntryLabel = (entry: AgentContextCompositionEntry, t: TranslateFn): string => {\n if (entry.isTextKey) return t(entry.label, { context: AGENT_CONTEXT_TEXT_CONTEXT });\n const firstSegment = entry.segments[0];\n return firstSegment !== undefined ? translateAgentContextSegmentLabel(firstSegment, t) : entry.label;\n};\n","import { useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { MarkdownPreview } from \"@mgamadeus/ddd-admin-ui/markdown\";\nimport { Badge } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { Button } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { cn } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { type ReactNode, useMemo, useState } from \"react\";\nimport type { DetailModalView } from \"../blocks/DetailModal\";\nimport { parseJsonContainer } from \"../blocks/json-tree\";\nimport { JsonTree } from \"../blocks/JsonTree\";\nimport { TokenFigure } from \"../blocks/TokenFigure\";\nimport type { AgentContextSegmentView } from \"./context-composition-grouping\";\nimport { translateAgentContextSegmentLabel } from \"./context-segment-label-texts\";\nimport { agentContextSegmentVariantsOf } from \"./context-segment-labels\";\n\n/** How many segments the list draws before \"Show more\" (a whole context can hold hundreds of messages). */\nexport const CONTEXT_SEGMENT_LIST_WINDOW_SIZE = 25;\n\nexport interface ContextSegmentListProps {\n segments: readonly AgentContextSegmentView[];\n /** `formatted`: markdown, or a tree for a text that is a JSON object or array. `raw`: the text as it is. */\n view: DetailModalView;\n /** Draws a markdown text; default the admin UI's markdown preview in its mode for texts of unknown origin. */\n renderMarkdown?: (source: string) => ReactNode;\n className?: string;\n}\n\ninterface ContextSegmentBodyProps {\n text: string;\n view: DetailModalView;\n renderMarkdown?: (source: string) => ReactNode;\n}\n\nconst ContextSegmentBody = ({ text, view, renderMarkdown }: ContextSegmentBodyProps) => {\n const { t } = useTranslate();\n const json = useMemo(() => (view === \"formatted\" ? parseJsonContainer(text) : undefined), [text, view]);\n if (text === \"\") return <p className=\"text-sm text-muted-foreground\">{t(\"This segment has no text.\")}</p>;\n if (view === \"raw\") {\n return (\n <pre data-slot=\"context-segment-raw\" className=\"font-mono text-xs leading-relaxed break-words whitespace-pre-wrap\">\n {text}\n </pre>\n );\n }\n if (json !== undefined) return <JsonTree value={json} defaultExpandDepth={3} />;\n return (\n <div data-slot=\"context-segment-markdown\" className=\"min-w-0 text-sm\">\n {renderMarkdown ? renderMarkdown(text) : <MarkdownPreview source={text} untrusted />}\n </div>\n );\n};\n\n/**\n * Segments of a model call's context one below the other, each under its colour mark, label and token count (and the\n * variants a loaded-skills segment was selected by). The text is prose (markdown) or JSON (a tree); `raw` shows it\n * unchanged. Texts come from prompts, tools and users: markdown is drawn by the renderer for texts of unknown origin,\n * JSON as text nodes.\n */\nexport const ContextSegmentList = ({ segments, view, renderMarkdown, className }: ContextSegmentListProps) => {\n const { t } = useTranslate();\n const [visibleCount, setVisibleCount] = useState(CONTEXT_SEGMENT_LIST_WINDOW_SIZE);\n const shownSegments = segments.slice(0, visibleCount);\n const hiddenCount = segments.length - shownSegments.length;\n return (\n <div data-slot=\"context-segment-list\" className={cn(\"space-y-4\", className)}>\n {shownSegments.map((segmentView) => {\n const variants = Object.entries(agentContextSegmentVariantsOf(segmentView.segment));\n return (\n <section key={segmentView.key} data-segment-type={segmentView.segment.type} className=\"min-w-0 rounded-xl border bg-card\">\n <header className=\"flex flex-wrap items-center gap-x-3 gap-y-1 border-b border-border px-3 py-2\">\n <span className=\"inline-flex min-w-0 items-center gap-2 text-sm font-medium\">\n <span aria-hidden className={cn(\"size-2.5 shrink-0 rounded-[3px]\", segmentView.colorClassName)} />\n <span className=\"min-w-0 break-words\">{translateAgentContextSegmentLabel(segmentView.segment, t)}</span>\n </span>\n <TokenFigure value={segmentView.tokenCount} isEstimate={segmentView.isEstimate} suffix={t(\"tokens\")} className=\"text-xs\" />\n {typeof segmentView.segment.sourceMessageIndex === \"number\" && (\n <span className=\"text-xs text-muted-foreground\">\n {t(\"message %index%\", { replacements: { index: segmentView.segment.sourceMessageIndex } })}\n </span>\n )}\n {variants.map(([dimension, value]) => (\n <Badge key={dimension} variant=\"outline\" className=\"font-mono text-[11px]\">\n {dimension}={value}\n </Badge>\n ))}\n </header>\n <div className=\"min-w-0 px-3 py-3\">\n <ContextSegmentBody text={segmentView.text} view={view} renderMarkdown={renderMarkdown} />\n </div>\n </section>\n );\n })}\n {hiddenCount > 0 && (\n <div className=\"text-center\">\n <Button type=\"button\" variant=\"outline\" size=\"sm\" data-slot=\"context-segment-list-more\" onClick={() => setVisibleCount((current) => current + CONTEXT_SEGMENT_LIST_WINDOW_SIZE)}>\n {t(\"Show more segments (%remaining% not shown)\", { replacements: { remaining: hiddenCount } })}\n </Button>\n </div>\n )}\n </div>\n );\n};\n","import { normalizeDddError } from \"@mgamadeus/ddd-web/contract\";\nimport { getUiLocale, useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { StatusCallout } from \"@mgamadeus/ddd-admin-ui/page\";\nimport { Badge } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { cn } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { Skeleton } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { Maximize2 } from \"lucide-react\";\nimport { type ReactNode, useMemo, useState } from \"react\";\nimport { DetailModal } from \"../blocks/DetailModal\";\nimport { ProportionBar, type ProportionBarSegment } from \"../blocks/ProportionBar\";\nimport { formatTokenFigure } from \"../blocks/token-figure\";\nimport { TokenFigure } from \"../blocks/TokenFigure\";\nimport type { AgentInspectContextApi } from \"./agent-inspect-context-api\";\nimport { CompactionThresholdBanner } from \"./CompactionThresholdBanner\";\nimport {\n type AgentContextCompositionEntry,\n type AgentContextSegmentView,\n agentContextCompositionOf,\n agentContextSegmentViewsToText,\n buildAgentContextCompositionEntries,\n buildAgentContextEntrySegmentViews,\n buildAgentContextSegmentViews,\n summarizeAgentContextComposition,\n} from \"./context-composition-grouping\";\nimport { translateAgentContextEntryLabel } from \"./context-segment-label-texts\";\nimport { ContextSegmentList } from \"./ContextSegmentList\";\n\nexport interface ContextCompositionPanelProps {\n /** `createAgentInspectContextApi(…)` of the host. */\n api: AgentInspectContextApi;\n conversationId: number | string;\n /** The message whose model call is broken down (an assistant message; another message has no composition). */\n messageId: number | string;\n /**\n * Shows the conversation's compaction threshold above the bar (which threshold applies, where it comes from, whether\n * compaction is due) when the answer carries one. For the panel at the top of a conversation; per-message panels\n * leave it off.\n */\n showCompactionThreshold?: boolean;\n /** Draws a markdown text of a segment; default the admin UI's markdown preview for texts of unknown origin. */\n renderMarkdown?: (source: string) => ReactNode;\n className?: string;\n}\n\n/** What the detail modal shows: the segments, and the title above them. */\ninterface OpenDetail {\n title: string;\n segments: AgentContextSegmentView[];\n}\n\n/**\n * What one model call was made of: every part of the system message, the tool schemas and the wire messages as one\n * bar weighed by tokens, a legend with the tokens of each part, and the texts on a click. Structural parts are single\n * entries; the wire messages are grouped by role (\"Tool calls ×13\"), so a long conversation stays readable. A click\n * on a part of the bar or on a legend entry opens its text in a large modal (markdown, or a tree for JSON; raw;\n * copy); \"View whole context\" opens every segment in the order the model read it. The panel says whether the\n * breakdown is what was sent or a reconstruction from the stored rows and the current prompt, skills and memory.\n */\nexport const ContextCompositionPanel = ({ api, conversationId, messageId, showCompactionThreshold = false, renderMarkdown, className }: ContextCompositionPanelProps) => {\n const { t } = useTranslate();\n const query = api.useContextCompositionQuery({ conversationId, messageId });\n const [openDetail, setOpenDetail] = useState<OpenDetail | null>(null);\n // Memoized: the reader builds a new object when the answer carries the reconstruction mark beside the breakdown.\n const composition = useMemo(() => agentContextCompositionOf(query.data), [query.data]);\n const threshold = showCompactionThreshold ? (query.data?.compactionThreshold ?? null) : null;\n const entries = useMemo(() => buildAgentContextCompositionEntries(composition), [composition]);\n const summary = useMemo(() => summarizeAgentContextComposition(composition), [composition]);\n\n const entryLabelOf = (entry: AgentContextCompositionEntry): string => translateAgentContextEntryLabel(entry, t);\n const barSegments: ProportionBarSegment[] = entries.map((entry) => ({\n key: entry.key,\n value: entry.tokenCount,\n colorClassName: entry.colorClassName,\n label: entryLabelOf(entry),\n badge: entry.segmentCount > 1 ? `×${entry.segmentCount}` : undefined,\n // an estimated part carries the estimate mark in its value\n valueText: formatTokenFigure(entry.tokenCount, { isEstimate: entry.isEstimate, locale: getUiLocale() }),\n }));\n const openEntry = (key: string) => {\n const entry = entries.find((candidate) => candidate.key === key);\n if (!entry) return;\n setOpenDetail({ title: entry.segmentCount > 1 ? `${entryLabelOf(entry)} ×${entry.segmentCount}` : entryLabelOf(entry), segments: buildAgentContextEntrySegmentViews(entry) });\n };\n\n if (query.isLoading) {\n return (\n <div data-slot=\"context-composition\" className={cn(\"space-y-2\", className)}>\n <Skeleton className=\"h-5 w-full rounded-md\" />\n <Skeleton className=\"h-4 w-2/3\" />\n </div>\n );\n }\n if (query.isError) {\n return (\n <StatusCallout\n size=\"compact\"\n tone=\"destructive\"\n className={className}\n title={t(\"The context composition could not be loaded.\")}\n description={normalizeDddError(query.error, \"\").message}\n />\n );\n }\n\n const isUnavailable = composition === null || composition.isUnavailable === true || summary.segmentCount === 0;\n return (\n <div data-slot=\"context-composition\" className={cn(\"min-w-0 space-y-3\", className)}>\n {threshold !== null && <CompactionThresholdBanner threshold={threshold} />}\n {isUnavailable ? (\n <p data-slot=\"context-composition-unavailable\" className=\"text-sm text-muted-foreground\">\n {t(\"No composition for this message: it made no model call (no request snapshot).\")}\n </p>\n ) : (\n <>\n <ProportionBar\n aria-label={t(\"Context of this model call by segment, in tokens\")}\n segments={barSegments}\n onSegmentSelect={openEntry}\n />\n <div className=\"flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground\">\n <span data-slot=\"context-composition-summary\">\n {t(\"{count, plural, one {# segment} other {# segments}}\", { count: summary.segmentCount })} (\n {t(\"{count, plural, one {# raw message} other {# raw messages}}\", { count: summary.messageSegmentCount })}) ·{\" \"}\n <TokenFigure value={summary.totalTokens} isEstimate={summary.isEstimate} suffix={t(\"tokens\")} className=\"text-foreground\" />\n </span>\n {composition?.isReconstructed === true && (\n <Badge\n variant=\"warning\"\n data-slot=\"context-composition-origin\"\n title={t(\"Rebuilt from the stored messages and the current prompt, skills and memory. It may differ from what was sent if those changed since.\")}\n >\n {t(\"Reconstructed\", { context: \"agent-context\" })}\n </Badge>\n )}\n {composition?.isReconstructed === false && (\n <Badge variant=\"success\" data-slot=\"context-composition-origin\" title={t(\"The breakdown of the request as it was sent to the model.\")}>\n {t(\"As sent\", { context: \"agent-context\" })}\n </Badge>\n )}\n <button\n type=\"button\"\n data-slot=\"context-composition-whole\"\n onClick={() => setOpenDetail({ title: t(\"Whole context of this model call\"), segments: buildAgentContextSegmentViews(composition, entries) })}\n className=\"ml-auto inline-flex items-center gap-1 rounded-sm font-medium text-primary-emphasis underline-offset-2 outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring\"\n >\n <Maximize2 aria-hidden className=\"size-3.5\" />\n {t(\"View whole context\")}\n </button>\n </div>\n </>\n )}\n <DetailModal\n open={openDetail !== null}\n onOpenChange={(isOpen) => {\n if (!isOpen) setOpenDetail(null);\n }}\n title={openDetail?.title ?? \"\"}\n description={\n openDetail && openDetail.segments.length > 1\n ? t(\"{count, plural, one {# segment} other {# segments}}\", { count: openDetail.segments.length })\n : undefined\n }\n copyText={() => agentContextSegmentViewsToText(openDetail?.segments ?? [])}\n >\n {(view) => <ContextSegmentList segments={openDetail?.segments ?? []} view={view} renderMarkdown={renderMarkdown} />}\n </DetailModal>\n </div>\n );\n};\n","import { normalizeDddError } from \"@mgamadeus/ddd-web/contract\";\nimport { m, useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { useCopyToClipboard } from \"@mgamadeus/ddd-admin-ui/logic\";\nimport { StatusCallout } from \"@mgamadeus/ddd-admin-ui/page\";\nimport { Badge } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { Button } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { cn } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { SegmentedControl, type SegmentedControlOption } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { Skeleton } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { Check, Copy } from \"lucide-react\";\nimport { useMemo, useState } from \"react\";\nimport { formatJsonText, parseJsonContainer } from \"../blocks/json-tree\";\nimport { JsonTree } from \"../blocks/JsonTree\";\nimport { diffLines } from \"../blocks/line-diff\";\nimport { LineDiffView } from \"../blocks/LineDiffView\";\nimport type { AgentInspectContextApi } from \"./agent-inspect-context-api\";\n\n/** Another model call the payload can be compared with. */\nexport interface SentPayloadComparableMessage {\n messageId: number | string;\n /** How the picker names it (\"Turn 4, call 2\"), already translated. */\n label: string;\n}\n\nexport type SentPayloadPanelMode = \"tree\" | \"raw\" | \"diff\";\n\nexport interface SentPayloadPanelProps {\n /** `createAgentInspectContextApi(…)` of the host. */\n api: AgentInspectContextApi;\n conversationId: number | string;\n messageId: number | string;\n /** The other model calls of the conversation; with at least one the panel offers the diff mode. */\n comparableMessages?: readonly SentPayloadComparableMessage[];\n /** The mode shown first (default `tree`). */\n defaultMode?: SentPayloadPanelMode;\n /** The message compared with at first, one of `comparableMessages`. */\n defaultComparedMessageId?: number | string;\n /**\n * For a host that draws the mode switch, the origin and the copy action itself (the request drawer of the\n * conversation detail): the panel shows only the content of `defaultMode` and, in the diff, the call it compares with.\n */\n isEmbedded?: boolean;\n className?: string;\n}\n\n/** The payload as a value: an object as it is, a JSON text parsed, anything else unchanged. */\nexport const readSentPayloadValue = (payload: unknown): unknown => {\n if (typeof payload !== \"string\") return payload ?? null;\n return parseJsonContainer(payload) ?? payload;\n};\n\n/** The payload as indented JSON text (a text that is not JSON stays as it is): what Raw shows, Copy writes and the diff compares. */\nexport const formatSentPayloadText = (payload: unknown): string => {\n const value = readSentPayloadValue(payload);\n return typeof value === \"string\" ? value : formatJsonText(value);\n};\n\n/**\n * The request body of one model call: as a tree, as raw JSON, or as a line diff against another model call of the\n * conversation. A badge says whether this is the payload stored when the call was made or one rebuilt from the stored\n * rows and the current state. The diff compares the two indented JSON texts line by line: `−` marks a line only this\n * call sent, `+` a line only the other call sent.\n */\nexport const SentPayloadPanel = ({\n api,\n conversationId,\n messageId,\n comparableMessages = [],\n defaultMode = \"tree\",\n defaultComparedMessageId,\n isEmbedded = false,\n className,\n}: SentPayloadPanelProps) => {\n const { t } = useTranslate();\n const { copy, copied } = useCopyToClipboard();\n const canCompare = comparableMessages.length > 0;\n const [mode, setMode] = useState<SentPayloadPanelMode>(defaultMode === \"diff\" && !canCompare ? \"tree\" : defaultMode);\n const [comparedMessageId, setComparedMessageId] = useState<string>(defaultComparedMessageId === undefined ? \"\" : String(defaultComparedMessageId));\n const query = api.useSentPayloadQuery({ conversationId, messageId });\n const comparedMessage = comparableMessages.find((message) => String(message.messageId) === comparedMessageId);\n const comparedQuery = api.useSentPayloadQuery(\n { conversationId, messageId: comparedMessage?.messageId ?? messageId },\n { skip: mode !== \"diff\" || comparedMessage === undefined },\n );\n\n const payloadValue = useMemo(() => readSentPayloadValue(query.data?.payload), [query.data]);\n const payloadText = useMemo(() => formatSentPayloadText(query.data?.payload), [query.data]);\n const comparedText = useMemo(() => (comparedQuery.data ? formatSentPayloadText(comparedQuery.data.payload) : null), [comparedQuery.data]);\n const diff = useMemo(\n () => (mode === \"diff\" && comparedMessage !== undefined && comparedText !== null ? diffLines(payloadText, comparedText) : null),\n [mode, comparedMessage, comparedText, payloadText],\n );\n\n const modeOptions: SegmentedControlOption<SentPayloadPanelMode>[] = [\n { value: \"tree\", label: m(\"Tree\", { context: \"payload-view\" }), context: \"payload-view\" },\n { value: \"raw\", label: m(\"Raw\", { context: \"payload-view\" }), context: \"payload-view\" },\n ...(canCompare ? [{ value: \"diff\" as const, label: m(\"Diff\", { context: \"payload-view\" }), context: \"payload-view\" }] : []),\n ];\n\n if (query.isLoading) {\n return (\n <div data-slot=\"sent-payload\" className={cn(\"space-y-2\", className)}>\n <Skeleton className=\"h-8 w-64\" />\n <Skeleton className=\"h-40 w-full rounded-lg\" />\n </div>\n );\n }\n if (query.isError) {\n return (\n <StatusCallout\n size=\"compact\"\n tone=\"destructive\"\n className={className}\n title={t(\"The sent payload could not be loaded.\")}\n description={normalizeDddError(query.error, \"\").message}\n />\n );\n }\n if (query.data?.payload === undefined || query.data.payload === null) {\n return (\n <p data-slot=\"sent-payload-unavailable\" className={cn(\"text-sm text-muted-foreground\", className)}>\n {t(\"No payload for this message: it made no model call.\")}\n </p>\n );\n }\n\n const isStoredPayload = query.data.isStoredPayload === true;\n return (\n <div data-slot=\"sent-payload\" className={cn(\"min-w-0 space-y-3\", className)}>\n <div className={cn(\"flex flex-wrap items-center gap-2\", isEmbedded && mode !== \"diff\" && \"hidden\")}>\n {!isEmbedded && <SegmentedControl<SentPayloadPanelMode> aria-label={m(\"Payload view\")} value={mode} onValueChange={setMode} options={modeOptions} />}\n {!isEmbedded && (\n <Badge\n variant={isStoredPayload ? \"success\" : \"warning\"}\n data-slot=\"sent-payload-origin\"\n title={\n isStoredPayload\n ? t(\"The request body stored when the model call was made.\")\n : t(\"Rebuilt from the stored messages and the current prompt, skills and memory. It may differ from what was sent.\")\n }\n >\n {isStoredPayload ? t(\"Stored payload\") : t(\"Rebuilt payload\")}\n </Badge>\n )}\n {mode === \"diff\" && (\n <Select value={comparedMessageId} onValueChange={setComparedMessageId}>\n <SelectTrigger size=\"sm\" aria-label={t(\"Compare with another model call\")} className=\"min-w-56\">\n <SelectValue placeholder={t(\"Compare with another model call\")} />\n </SelectTrigger>\n <SelectContent>\n {comparableMessages.map((message) => (\n <SelectItem key={String(message.messageId)} value={String(message.messageId)}>\n {message.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n )}\n {!isEmbedded && (\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"ml-auto\" data-slot=\"sent-payload-copy\" onClick={() => void copy(payloadText)}>\n {copied ? <Check aria-hidden className=\"text-success\" /> : <Copy aria-hidden />}\n {copied ? t(\"Copied\") : t(\"Copy JSON\")}\n </Button>\n )}\n </div>\n\n {mode === \"tree\" &&\n (typeof payloadValue === \"string\" ? (\n <pre className=\"max-h-[32rem] overflow-auto rounded-lg border bg-muted/40 p-3 font-mono text-xs leading-relaxed break-words whitespace-pre-wrap\">{payloadValue}</pre>\n ) : (\n <div className=\"max-h-[32rem] overflow-auto rounded-lg border bg-muted/40 p-3\">\n <JsonTree value={payloadValue} defaultExpandDepth={1} aria-label={t(\"Sent payload\")} />\n </div>\n ))}\n {mode === \"raw\" && (\n <pre data-slot=\"sent-payload-raw\" className=\"max-h-[32rem] overflow-auto rounded-lg border bg-muted/40 p-3 font-mono text-xs leading-relaxed break-words whitespace-pre-wrap\">\n {payloadText}\n </pre>\n )}\n {mode === \"diff\" && (\n <div data-slot=\"sent-payload-diff\" className=\"space-y-2\">\n {comparedMessage === undefined ? (\n <p className=\"text-sm text-muted-foreground\">{t(\"Choose the model call to compare this payload with.\")}</p>\n ) : comparedQuery.isError ? (\n <StatusCallout size=\"compact\" tone=\"destructive\" title={t(\"The payload to compare with could not be loaded.\")} description={normalizeDddError(comparedQuery.error, \"\").message} />\n ) : diff === null ? (\n <Skeleton className=\"h-40 w-full rounded-lg\" />\n ) : (\n <>\n <p className=\"text-xs text-muted-foreground\">\n <span className=\"font-medium text-destructive tabular-nums\">−{diff.removedCount}</span>{\" \"}\n <span className=\"font-medium text-success tabular-nums\">+{diff.addedCount}</span>\n {\" · \"}\n {t(\"− only in this call, + only in %label%\", { replacements: { label: comparedMessage.label } })}\n {comparedQuery.data?.isStoredPayload === false && ` · ${t(\"the other payload is rebuilt\")}`}\n {diff.isApproximate && ` · ${t(\"the changed part is too large to align line by line\")}`}\n </p>\n {diff.addedCount === 0 && diff.removedCount === 0 ? (\n <p className=\"text-sm text-muted-foreground\">{t(\"Both payloads are identical.\")}</p>\n ) : (\n <LineDiffView diff={diff} aria-label={t(\"Line diff of the two payloads\")} className=\"max-h-[32rem] overflow-auto\" />\n )}\n </>\n )}\n </div>\n )}\n </div>\n );\n};\n","import {\n type ApiQueryHook,\n type InjectableBaseApi,\n type InjectedEndpointDefinition,\n type InjectedRequest,\n injectEndpointsOnce,\n type StaticQueryFailure,\n staticQueryHook,\n toQueryString,\n trimApiPrefix,\n} from \"@mgamadeus/ddd-admin-ui/logic/pure\";\nimport type {\n AgentSkillCatalogResponse,\n AgentSkillLoadCountsResponse,\n AgentSkillLoadSourcesResponse,\n AgentSkillPurposesResponse,\n AgentSkillSharedBlocksResponse,\n AgentSkillToolArg,\n AgentSkillToolDocumentationResponse,\n AgentSkillUsageArg,\n} from \"./agent-skill-catalog-types\";\n\n/** The cache tag type of the skill catalog reads (ids `CATALOG`, `TOOL`, `SHARED_BLOCKS`, `PURPOSES`, `LOAD_COUNTS`, `LOAD_SOURCES`). */\nexport const AGENT_SKILL_CATALOG_TAG = \"AdminUiAgentSkillCatalog\";\n\n/** The hooks `createAgentSkillCatalogApi` returns; `AgentSkillCatalogScreen` takes them as `api`. */\nexport interface AgentSkillCatalogApi {\n /** `GET /skills`: totals, every skill with its packages and tools, the namespace and purpose groups. */\n useSkillCatalogQuery: ApiQueryHook<void, AgentSkillCatalogResponse>;\n /** `GET /tools/{toolName}`: one tool's wire schema and where its tokens sit. */\n useSkillToolDocumentationQuery: ApiQueryHook<AgentSkillToolArg, AgentSkillToolDocumentationResponse>;\n /** `GET /sharedBlocks`: the blocks the system prompt carries once per turn. */\n useSkillSharedBlocksQuery: ApiQueryHook<void, AgentSkillSharedBlocksResponse>;\n /** `GET /purposes?from&to`: the registered purposes with their run count and finish rate in a period. */\n useSkillPurposesQuery: ApiQueryHook<AgentSkillUsageArg, AgentSkillPurposesResponse>;\n /** `GET /skillLoadCounts?from&to`: how often the model asked for each skill in a period. */\n useSkillLoadCountsQuery: ApiQueryHook<AgentSkillUsageArg, AgentSkillLoadCountsResponse>;\n /** `GET /skillLoadSources?from&to`: the loads of each skill by source (preload, follow-up pass, the model) and the preload outcomes. */\n useSkillLoadSourcesQuery: ApiQueryHook<AgentSkillUsageArg, AgentSkillLoadSourcesResponse>;\n}\n\nexport interface CreateAgentSkillCatalogApiOptions {\n /** The host's RTK Query api (`createApi` with the React hooks module). */\n baseApi: InjectableBaseApi;\n /** Where the host mounts the skill catalog routes, without a trailing slash (`/api/admin/ai/skillCatalog`). */\n apiPrefix: string;\n}\n\n/** The request of every operation, on `apiPrefix`. Pure: no RTK runtime. */\nexport const buildAgentSkillCatalogRequests = (apiPrefix: string) => {\n const prefix = trimApiPrefix(apiPrefix);\n return {\n skills: (): InjectedRequest => ({ url: `${prefix}/skills` }),\n tool: ({ toolName }: AgentSkillToolArg): InjectedRequest => ({ url: `${prefix}/tools/${encodeURIComponent(toolName)}` }),\n sharedBlocks: (): InjectedRequest => ({ url: `${prefix}/sharedBlocks` }),\n purposes: (arg: AgentSkillUsageArg = {}): InjectedRequest => ({ url: `${prefix}/purposes${toQueryString({ from: arg.from, to: arg.to })}` }),\n skillLoadCounts: (arg: AgentSkillUsageArg = {}): InjectedRequest => ({ url: `${prefix}/skillLoadCounts${toQueryString({ from: arg.from, to: arg.to })}` }),\n skillLoadSources: (arg: AgentSkillUsageArg = {}): InjectedRequest => ({ url: `${prefix}/skillLoadSources${toQueryString({ from: arg.from, to: arg.to })}` }),\n };\n};\n\nconst CATALOG = { type: AGENT_SKILL_CATALOG_TAG, id: \"CATALOG\" } as const;\nconst TOOL = { type: AGENT_SKILL_CATALOG_TAG, id: \"TOOL\" } as const;\nconst SHARED_BLOCKS = { type: AGENT_SKILL_CATALOG_TAG, id: \"SHARED_BLOCKS\" } as const;\nconst PURPOSES = { type: AGENT_SKILL_CATALOG_TAG, id: \"PURPOSES\" } as const;\nconst LOAD_COUNTS = { type: AGENT_SKILL_CATALOG_TAG, id: \"LOAD_COUNTS\" } as const;\nconst LOAD_SOURCES = { type: AGENT_SKILL_CATALOG_TAG, id: \"LOAD_SOURCES\" } as const;\n\n/** The operations as injected. */\nexport const agentSkillCatalogEndpointDefinitions = (apiPrefix: string) => {\n const requests = buildAgentSkillCatalogRequests(apiPrefix);\n return {\n adminUiAgentSkillCatalog: { kind: \"query\", request: requests.skills, providesTags: [CATALOG] },\n adminUiAgentSkillToolDocumentation: { kind: \"query\", request: requests.tool, providesTags: [TOOL] },\n adminUiAgentSkillSharedBlocks: { kind: \"query\", request: requests.sharedBlocks, providesTags: [SHARED_BLOCKS] },\n adminUiAgentSkillPurposes: { kind: \"query\", request: requests.purposes, providesTags: [PURPOSES] },\n adminUiAgentSkillLoadCounts: { kind: \"query\", request: requests.skillLoadCounts, providesTags: [LOAD_COUNTS] },\n adminUiAgentSkillLoadSources: { kind: \"query\", request: requests.skillLoadSources, providesTags: [LOAD_SOURCES] },\n } as const satisfies Record<string, InjectedEndpointDefinition<never>>;\n};\n\n/**\n * Injects the skill catalog reads into the host's RTK Query api and returns their hooks. Call it once at module scope:\n * `export const agentSkillCatalogApi = createAgentSkillCatalogApi({ baseApi: adminApi, apiPrefix: \"/api/admin/ai/skillCatalog\" });`\n */\nexport const createAgentSkillCatalogApi = ({ baseApi, apiPrefix }: CreateAgentSkillCatalogApiOptions): AgentSkillCatalogApi =>\n injectEndpointsOnce(\n baseApi,\n `agentSkillCatalog:${trimApiPrefix(apiPrefix)}`,\n [AGENT_SKILL_CATALOG_TAG],\n agentSkillCatalogEndpointDefinitions(apiPrefix),\n (hookOf) => ({\n useSkillCatalogQuery: hookOf(\"adminUiAgentSkillCatalog\") as AgentSkillCatalogApi[\"useSkillCatalogQuery\"],\n useSkillToolDocumentationQuery: hookOf(\"adminUiAgentSkillToolDocumentation\") as AgentSkillCatalogApi[\"useSkillToolDocumentationQuery\"],\n useSkillSharedBlocksQuery: hookOf(\"adminUiAgentSkillSharedBlocks\") as AgentSkillCatalogApi[\"useSkillSharedBlocksQuery\"],\n useSkillPurposesQuery: hookOf(\"adminUiAgentSkillPurposes\") as AgentSkillCatalogApi[\"useSkillPurposesQuery\"],\n useSkillLoadCountsQuery: hookOf(\"adminUiAgentSkillLoadCounts\") as AgentSkillCatalogApi[\"useSkillLoadCountsQuery\"],\n useSkillLoadSourcesQuery: hookOf(\"adminUiAgentSkillLoadSources\") as AgentSkillCatalogApi[\"useSkillLoadSourcesQuery\"],\n }),\n );\n\n/** Fixed answers of a `createStaticAgentSkillCatalogApi`; a query without one stays loading. */\nexport interface StaticAgentSkillCatalogData {\n skills?: () => AgentSkillCatalogResponse | StaticQueryFailure | undefined;\n tool?: (arg: AgentSkillToolArg) => AgentSkillToolDocumentationResponse | StaticQueryFailure | undefined;\n sharedBlocks?: () => AgentSkillSharedBlocksResponse | StaticQueryFailure | undefined;\n purposes?: (arg: AgentSkillUsageArg) => AgentSkillPurposesResponse | StaticQueryFailure | undefined;\n skillLoadCounts?: (arg: AgentSkillUsageArg) => AgentSkillLoadCountsResponse | StaticQueryFailure | undefined;\n skillLoadSources?: (arg: AgentSkillUsageArg) => AgentSkillLoadSourcesResponse | StaticQueryFailure | undefined;\n}\n\n/** An `AgentSkillCatalogApi` answering fixed payloads, without a store or a request (previews, tests, reviews). */\nexport const createStaticAgentSkillCatalogApi = (data: StaticAgentSkillCatalogData): AgentSkillCatalogApi => ({\n useSkillCatalogQuery: staticQueryHook(() => data.skills?.()),\n useSkillToolDocumentationQuery: staticQueryHook((arg) => data.tool?.(arg)),\n useSkillSharedBlocksQuery: staticQueryHook(() => data.sharedBlocks?.()),\n useSkillPurposesQuery: staticQueryHook((arg) => data.purposes?.(arg ?? {})),\n useSkillLoadCountsQuery: staticQueryHook((arg) => data.skillLoadCounts?.(arg ?? {})),\n useSkillLoadSourcesQuery: staticQueryHook((arg) => data.skillLoadSources?.(arg ?? {})),\n});\n","import { addCalendarDays, localToday } from \"@mgamadeus/ddd-admin-ui/logic/pure\";\n\n/** The presets of a period control: the last n days up to today, or a range of two typed days. */\nexport type AdminPeriodPresetId = \"7d\" | \"14d\" | \"30d\" | \"90d\" | \"custom\";\n\n/** One preset with the days it covers (today included); the custom preset covers the two typed days. */\nexport interface AdminPeriodPreset {\n id: AdminPeriodPresetId;\n days: number | null;\n}\n\nexport const ADMIN_PERIOD_PRESETS: readonly AdminPeriodPreset[] = [\n { id: \"7d\", days: 7 },\n { id: \"14d\", days: 14 },\n { id: \"30d\", days: 30 },\n { id: \"90d\", days: 90 },\n { id: \"custom\", days: null },\n];\n\n/** The longest range the admin reads accept (`AgentControlPanelRange::MAX_DAYS`). */\nexport const ADMIN_PERIOD_MAX_DAYS = 366;\n\n/** What a screen keeps of its period (its URL keys `period`, `from`, `to`): each `\"\"` when unset. */\nexport interface AdminPeriodState {\n preset: string;\n from: string;\n to: string;\n}\n\n/** A period as the requests take it: two inclusive calendar days and how many days they cover. */\nexport interface AdminPeriod {\n preset: AdminPeriodPresetId;\n /** The first day, `YYYY-MM-DD`. */\n from: string;\n /** The last day, `YYYY-MM-DD`. */\n to: string;\n dayCount: number;\n}\n\nconst DAY_PATTERN = /^\\d{4}-\\d{2}-\\d{2}$/;\n\n/** Whether `value` is a calendar day that exists (`2026-02-30` does not). */\nexport const isAdminPeriodDay = (value: string | null | undefined): value is string => {\n if (typeof value !== \"string\" || !DAY_PATTERN.test(value)) return false;\n const [year, month, day] = value.split(\"-\").map(Number) as [number, number, number];\n const date = new Date(Date.UTC(year, month - 1, day));\n return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day;\n};\n\nconst utcTimeOfDay = (day: string): number => {\n const [year, month, dayOfMonth] = day.split(\"-\").map(Number) as [number, number, number];\n return Date.UTC(year, month - 1, dayOfMonth);\n};\n\n/** The days from `from` to `to`, both counted; 0 when `to` is before `from` or a day is invalid. */\nexport const countAdminPeriodDays = (from: string, to: string): number => {\n if (!isAdminPeriodDay(from) || !isAdminPeriodDay(to)) return 0;\n const days = Math.round((utcTimeOfDay(to) - utcTimeOfDay(from)) / 86_400_000) + 1;\n return days > 0 ? days : 0;\n};\n\nconst isPresetId = (value: string): value is AdminPeriodPresetId => ADMIN_PERIOD_PRESETS.some((preset) => preset.id === value);\n\n/**\n * The period of a screen's state on `today`: a preset of days ends today; the custom preset takes the two typed days\n * when both exist, are in order and cover at most `ADMIN_PERIOD_MAX_DAYS` days, else the default preset applies. An\n * unknown or empty preset is the default preset.\n */\nexport const resolveAdminPeriod = (state: Partial<AdminPeriodState>, defaultPreset: Exclude<AdminPeriodPresetId, \"custom\"> = \"30d\", today: string = localToday()): AdminPeriod => {\n const requested = state.preset !== undefined && isPresetId(state.preset) ? state.preset : defaultPreset;\n if (requested === \"custom\") {\n const dayCount = countAdminPeriodDays(state.from ?? \"\", state.to ?? \"\");\n if (dayCount > 0 && dayCount <= ADMIN_PERIOD_MAX_DAYS && isAdminPeriodDay(state.from) && isAdminPeriodDay(state.to)) {\n return { preset: \"custom\", from: state.from, to: state.to, dayCount };\n }\n }\n const preset = requested === \"custom\" ? defaultPreset : requested;\n const days = ADMIN_PERIOD_PRESETS.find((candidate) => candidate.id === preset)?.days ?? 30;\n return { preset, from: addCalendarDays(today, -(days - 1)), to: today, dayCount: days };\n};\n\n/** The period of the same length that ends the day before `period` starts. */\nexport const precedingAdminPeriod = (period: Pick<AdminPeriod, \"from\" | \"dayCount\">): { from: string; to: string } => {\n const to = addCalendarDays(period.from, -1);\n return { from: addCalendarDays(to, -(period.dayCount - 1)), to };\n};\n\n/** The bucket of a time series: one point per day, or per ISO week keyed by its Monday. */\nexport type AdminPeriodGranularity = \"DAY\" | \"WEEK\";\n\n/** The Monday of the ISO week `day` lies in. */\nexport const mondayOfAdminPeriodDay = (day: string): string => {\n if (!isAdminPeriodDay(day)) return \"\";\n const weekday = new Date(utcTimeOfDay(day)).getUTCDay();\n return addCalendarDays(day, -((weekday + 6) % 7));\n};\n\n/**\n * Every bucket key of a period in order: each day, or the Monday of each ISO week the period touches (the first\n * Monday may lie before `from`). Empty for an invalid period.\n */\nexport const adminPeriodBucketKeys = (from: string, to: string, granularity: AdminPeriodGranularity): string[] => {\n if (countAdminPeriodDays(from, to) === 0) return [];\n const step = granularity === \"WEEK\" ? 7 : 1;\n const keys: string[] = [];\n for (let key = granularity === \"WEEK\" ? mondayOfAdminPeriodDay(from) : from; key !== \"\" && key <= to; key = addCalendarDays(key, step)) {\n keys.push(key);\n if (keys.length > ADMIN_PERIOD_MAX_DAYS + 7) break;\n }\n return keys;\n};\n\n/** The bucket key of a point's day under a granularity: the day itself, or its week's Monday. */\nexport const adminPeriodBucketKeyOf = (day: string, granularity: AdminPeriodGranularity): string => {\n const dayPart = day.slice(0, 10);\n return granularity === \"WEEK\" ? mondayOfAdminPeriodDay(dayPart) : dayPart;\n};\n","import { m, useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { localToday } from \"@mgamadeus/ddd-admin-ui/logic/pure\";\nimport { cn, Input, SegmentedControl, type SegmentedControlOption } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { type AdminPeriod, type AdminPeriodPresetId, type AdminPeriodState, isAdminPeriodDay } from \"./admin-period\";\n\nexport interface AdminPeriodControlProps {\n /** The resolved period (`resolveAdminPeriod` of the screen's state). */\n period: AdminPeriod;\n /** Called with the state to keep (the URL keys `period`, `from`, `to`); a preset of days clears the two days. */\n onChange: (state: AdminPeriodState) => void;\n /** The presets offered, in order; default all five. */\n presets?: readonly AdminPeriodPresetId[];\n className?: string;\n}\n\nconst PRESET_OPTIONS: Readonly<Record<AdminPeriodPresetId, SegmentedControlOption<AdminPeriodPresetId>>> = {\n \"7d\": { value: \"7d\", label: m(\"7 days\", { context: \"admin-period\" }), context: \"admin-period\" },\n \"14d\": { value: \"14d\", label: m(\"14 days\", { context: \"admin-period\" }), context: \"admin-period\" },\n \"30d\": { value: \"30d\", label: m(\"30 days\", { context: \"admin-period\" }), context: \"admin-period\" },\n \"90d\": { value: \"90d\", label: m(\"90 days\", { context: \"admin-period\" }), context: \"admin-period\" },\n custom: { value: \"custom\", label: m(\"Custom\", { context: \"admin-period\" }), context: \"admin-period\" },\n};\n\nconst DEFAULT_PRESETS: readonly AdminPeriodPresetId[] = [\"7d\", \"14d\", \"30d\", \"90d\", \"custom\"];\n\n/**\n * The period of an admin screen: the last 7, 14, 30 or 90 days up to today, or two typed days. The custom preset\n * shows two date fields that start with the days of the period shown; each bound limits the other.\n */\nexport const AdminPeriodControl = ({ period, onChange, presets = DEFAULT_PRESETS, className }: AdminPeriodControlProps) => {\n const { t } = useTranslate();\n const today = localToday();\n return (\n <div data-slot=\"admin-period-control\" className={cn(\"flex flex-wrap items-center gap-2\", className)}>\n <SegmentedControl<AdminPeriodPresetId>\n aria-label={t(\"Period\", { context: \"admin-period\" })}\n value={period.preset}\n onValueChange={(preset) => onChange(preset === \"custom\" ? { preset, from: period.from, to: period.to } : { preset, from: \"\", to: \"\" })}\n options={presets.map((preset) => PRESET_OPTIONS[preset])}\n />\n {period.preset === \"custom\" && (\n <span className=\"flex items-center gap-1.5\">\n <Input\n type=\"date\"\n aria-label={t(\"First day of the period\")}\n value={period.from}\n max={period.to}\n onChange={(event) => {\n if (isAdminPeriodDay(event.target.value)) onChange({ preset: \"custom\", from: event.target.value, to: period.to });\n }}\n className=\"h-8 w-36\"\n />\n <span aria-hidden className=\"text-muted-foreground\">\n –\n </span>\n <Input\n type=\"date\"\n aria-label={t(\"Last day of the period\")}\n value={period.to}\n min={period.from}\n max={today}\n onChange={(event) => {\n if (isAdminPeriodDay(event.target.value)) onChange({ preset: \"custom\", from: period.from, to: event.target.value });\n }}\n className=\"h-8 w-36\"\n />\n </span>\n )}\n </div>\n );\n};\n","import type {\n AgentSkillCatalog,\n AgentSkillCatalogEntry,\n AgentSkillCatalogNamespaceGroup,\n AgentSkillCatalogPackage,\n AgentSkillCatalogPurposeGroup,\n AgentSkillCatalogSharedBlock,\n AgentSkillCatalogTool,\n AgentSkillCatalogToolComponents,\n AgentSkillLoadCounts,\n AgentSkillSharedBlocksResponse,\n AgentSkillTokenEntry,\n} from \"./agent-skill-catalog-types\";\n\nconst countOf = (value: unknown): number => (typeof value === \"number\" && Number.isFinite(value) ? value : 0);\n\n/**\n * Named token counts as a list, whatever shape they arrived in: a map keeps its key order, a list of\n * `{ name, tokens }` its own, an empty list (how an empty map arrives) or anything else gives none.\n */\nexport const normalizeSkillTokenEntries = (value: unknown): AgentSkillTokenEntry[] => {\n if (value !== null && typeof value === \"object\" && !Array.isArray(value) && Array.isArray((value as { elements?: unknown }).elements)) {\n // an object set of `{ name, tokens }` (`AISkillCatalogTokenCounts`)\n return normalizeSkillTokenEntries((value as { elements: unknown[] }).elements);\n }\n if (Array.isArray(value)) {\n return value\n .filter((entry): entry is AgentSkillTokenEntry => entry !== null && typeof entry === \"object\" && typeof (entry as AgentSkillTokenEntry).name === \"string\")\n .map((entry) => ({ name: entry.name, tokens: countOf(entry.tokens) }));\n }\n if (value !== null && typeof value === \"object\") {\n return Object.entries(value as Record<string, unknown>).map(([name, tokens]) => ({ name, tokens: countOf(tokens) }));\n }\n return [];\n};\n\n/** The parameters of a tool with their tokens: the list form (`parameterTokens`) when sent, else the map. */\nexport const skillToolParameterTokensOf = (components: AgentSkillCatalogToolComponents | null | undefined): AgentSkillTokenEntry[] => {\n const listed = normalizeSkillTokenEntries(components?.parameterTokens);\n return listed.length > 0 ? listed : normalizeSkillTokenEntries(components?.parameters);\n};\n\n/** The shared definitions of a tool with their tokens: the list form (`defTokens`) when sent, else the map. */\nexport const skillToolDefinitionTokensOf = (components: AgentSkillCatalogToolComponents | null | undefined): AgentSkillTokenEntry[] => {\n const listed = normalizeSkillTokenEntries(components?.defTokens);\n return listed.length > 0 ? listed : normalizeSkillTokenEntries(components?.defs);\n};\n\n/** The loads of a period by skill name (`AgentSkillLoadCounts`); a skill named twice adds up. */\nexport const skillLoadCountsByNameOf = (loadCounts: AgentSkillLoadCounts | null | undefined): Map<string, number> => {\n const countsByName = new Map<string, number>();\n for (const entry of loadCounts?.elements ?? []) {\n if (typeof entry?.skillName !== \"string\" || entry.skillName === \"\") continue;\n countsByName.set(entry.skillName, (countsByName.get(entry.skillName) ?? 0) + countOf(entry.loadCount));\n }\n return countsByName;\n};\n\n/** The kind of a part of a tool's wire schema. */\nexport type SkillToolTokenPartKind = \"description\" | \"parameter\" | \"envelope\" | \"definition\";\n\n/** One part of a tool's wire schema with its tokens. */\nexport interface SkillToolTokenPart {\n key: string;\n kind: SkillToolTokenPartKind;\n /** The parameter or definition name; empty for the description and the envelope. */\n name: string;\n tokens: number;\n}\n\n/**\n * The parts of a tool's tokens in the order of the bar: the description, every parameter, the envelope, every shared\n * definition. Parts without tokens are left out.\n */\nexport const buildSkillToolTokenParts = (components: AgentSkillCatalogToolComponents | null | undefined): SkillToolTokenPart[] => {\n if (!components) return [];\n const parts: SkillToolTokenPart[] = [\n { key: \"description\", kind: \"description\", name: \"\", tokens: countOf(components.description) },\n ...skillToolParameterTokensOf(components).map((entry): SkillToolTokenPart => ({ key: `parameter:${entry.name}`, kind: \"parameter\", name: entry.name, tokens: entry.tokens })),\n { key: \"envelope\", kind: \"envelope\", name: \"\", tokens: countOf(components.envelope) },\n ...skillToolDefinitionTokensOf(components).map((entry): SkillToolTokenPart => ({ key: `definition:${entry.name}`, kind: \"definition\", name: entry.name, tokens: entry.tokens })),\n ];\n return parts.filter((part) => part.tokens > 0);\n};\n\ntype JsonSchemaLike = Readonly<Record<string, unknown>>;\n\nconst isRecord = (value: unknown): value is JsonSchemaLike => value !== null && typeof value === \"object\" && !Array.isArray(value);\n\nconst referenceNameOf = (reference: string): string => reference.slice(reference.lastIndexOf(\"/\") + 1);\n\n/**\n * A JSON-Schema type in one short text: `string`, `integer`, `array<string>`, `enum(3)`, `object{name, id}`, a `$ref`\n * by its definition name, unions as `a | b`, a nullable type with ` | null`. Nested types are named, not unfolded\n * (two levels at most).\n */\nexport const summarizeJsonSchemaType = (schema: unknown, depth = 0): string => {\n if (!isRecord(schema)) return \"any\";\n if (typeof schema.$ref === \"string\") return referenceNameOf(schema.$ref);\n for (const unionKey of [\"anyOf\", \"oneOf\"] as const) {\n const variants = schema[unionKey];\n if (Array.isArray(variants) && variants.length > 0) {\n return [...new Set(variants.map((variant) => summarizeJsonSchemaType(variant, depth + 1)))].join(\" | \");\n }\n }\n if (Array.isArray(schema.allOf) && schema.allOf.length > 0) {\n return [...new Set(schema.allOf.map((variant) => summarizeJsonSchemaType(variant, depth + 1)))].join(\" & \");\n }\n const type = schema.type;\n if (Array.isArray(type)) {\n return type.map((single) => summarizeJsonSchemaType({ ...schema, type: single }, depth + 1)).join(\" | \");\n }\n if (Array.isArray(schema.enum) && (type === undefined || type === \"string\" || type === \"integer\" || type === \"number\")) {\n return `enum(${schema.enum.length})`;\n }\n if (type === \"array\") {\n return depth >= 2 ? \"array\" : `array<${summarizeJsonSchemaType(schema.items, depth + 1)}>`;\n }\n if (type === \"object\" || (type === undefined && isRecord(schema.properties))) {\n const propertyNames = isRecord(schema.properties) ? Object.keys(schema.properties) : [];\n if (propertyNames.length === 0 || depth >= 2) return \"object\";\n const shownNames = propertyNames.slice(0, 4).join(\", \");\n return `object{${shownNames}${propertyNames.length > 4 ? \", …\" : \"\"}}`;\n }\n return typeof type === \"string\" ? type : \"any\";\n};\n\n/** One row of a tool's parameter table. */\nexport interface SkillToolParameterRow {\n name: string;\n /** The type in short (`summarizeJsonSchemaType`). */\n type: string;\n isRequired: boolean;\n /** The parameter's tokens; `null` when the breakdown does not name it. */\n tokens: number | null;\n description: string;\n}\n\n/** The `function.parameters` schema of a tool's wire schema; `null` when the schema has none. */\nexport const skillToolParametersSchemaOf = (openAiToolSchema: unknown): JsonSchemaLike | null => {\n if (!isRecord(openAiToolSchema)) return null;\n const functionSchema = isRecord(openAiToolSchema.function) ? openAiToolSchema.function : openAiToolSchema;\n return isRecord(functionSchema.parameters) ? functionSchema.parameters : null;\n};\n\n/** The description of a tool's wire schema (`function.description`). */\nexport const skillToolDescriptionOf = (openAiToolSchema: unknown): string => {\n if (!isRecord(openAiToolSchema)) return \"\";\n const functionSchema = isRecord(openAiToolSchema.function) ? openAiToolSchema.function : openAiToolSchema;\n return typeof functionSchema.description === \"string\" ? functionSchema.description : \"\";\n};\n\n/**\n * A text without the line breaks of its source's line length: a single line break between two lines of prose becomes a\n * space; an empty line (a paragraph) and a break before a list line (`-`, `*`, `1.`) stay.\n */\nexport const unwrapHardLineBreaks = (text: string): string => text.replace(/[ \\t]*\\r?\\n(?!\\s*\\r?\\n|\\s*(?:[-*•]|\\d+[.)])\\s)(?<!\\n[ \\t]*\\r?\\n)[ \\t]*/g, \" \").trim();\n\n/**\n * The parameters of a tool for its table, from `function.parameters.properties` of the wire schema, with the tokens of\n * the breakdown: heaviest first where tokens are known, the rest in schema order. A parameter the breakdown names but\n * the schema lacks is listed too (type `any`). A description loses the line breaks of its source's line length.\n */\nexport const buildSkillToolParameterRows = (openAiToolSchema: unknown, components: AgentSkillCatalogToolComponents | null | undefined): SkillToolParameterRow[] => {\n const parametersSchema = skillToolParametersSchemaOf(openAiToolSchema);\n const properties = parametersSchema && isRecord(parametersSchema.properties) ? parametersSchema.properties : {};\n const requiredNames = new Set(parametersSchema && Array.isArray(parametersSchema.required) ? parametersSchema.required.filter((name): name is string => typeof name === \"string\") : []);\n const tokensByName = new Map(skillToolParameterTokensOf(components).map((entry) => [entry.name, entry.tokens]));\n const names = [...new Set([...Object.keys(properties), ...tokensByName.keys()])];\n const rows = names.map((name): SkillToolParameterRow => {\n const propertySchema = properties[name];\n return {\n name,\n type: summarizeJsonSchemaType(propertySchema),\n isRequired: requiredNames.has(name),\n tokens: tokensByName.get(name) ?? null,\n description: isRecord(propertySchema) && typeof propertySchema.description === \"string\" ? unwrapHardLineBreaks(propertySchema.description) : \"\",\n };\n });\n // a stable sort: rows without tokens keep their schema order after the weighed ones\n return rows.sort((first, second) => (second.tokens ?? -1) - (first.tokens ?? -1));\n};\n\n/** One row of a skill tree: a skill and the sub-skills listed under it. */\nexport interface SkillTreeRow {\n skill: AgentSkillCatalogEntry;\n subSkills: AgentSkillCatalogEntry[];\n}\n\nconst indexSkillsByName = (skills: readonly AgentSkillCatalogEntry[]): Map<string, AgentSkillCatalogEntry> => new Map(skills.map((skill) => [skill.name, skill]));\n\n/**\n * A tree over `candidates`: the top level is every candidate no candidate root claims as its sub-skill; each root\n * carries the sub-skills it lists (looked up in `skillsByName`, so a root always shows all of them). A sub-skill of\n * several roots appears under each; a sub-skill no candidate root lists stays at the top level instead of vanishing.\n */\nexport const buildSkillTreeRows = (candidates: readonly AgentSkillCatalogEntry[], skillsByName: ReadonlyMap<string, AgentSkillCatalogEntry>): SkillTreeRow[] => {\n const candidateNames = new Set(candidates.map((skill) => skill.name));\n const claimedSubSkillNames = new Set<string>();\n for (const skill of candidates) {\n if (skill.isSubSkill) continue;\n for (const subSkillName of skill.subSkillNames ?? []) {\n if (skillsByName.get(subSkillName)?.isSubSkill && candidateNames.has(subSkillName)) claimedSubSkillNames.add(subSkillName);\n }\n }\n return candidates\n .filter((skill) => !skill.isSubSkill || !claimedSubSkillNames.has(skill.name))\n .map((skill) => ({\n skill,\n subSkills: skill.isSubSkill\n ? []\n : (skill.subSkillNames ?? []).map((subSkillName) => skillsByName.get(subSkillName)).filter((subSkill): subSkill is AgentSkillCatalogEntry => subSkill?.isSubSkill === true),\n }));\n};\n\n/** The general skills of a catalog: those an open conversation is offered. */\nexport const generalSkillsOf = (catalog: AgentSkillCatalog | null | undefined): AgentSkillCatalogEntry[] => (catalog?.skills ?? []).filter((skill) => !skill.isPurposeBound);\n\n/** One namespace group with its skill tree. */\nexport interface SkillNamespaceSection {\n key: string;\n group: AgentSkillCatalogNamespaceGroup;\n rows: SkillTreeRow[];\n}\n\n/** One purpose with the tree of the skills bound to it. */\nexport interface SkillPurposeSection {\n key: string;\n group: AgentSkillCatalogPurposeGroup;\n rows: SkillTreeRow[];\n}\n\n/** The key of a group section; namespace and purpose groups never collide. */\nexport const skillGroupSectionKeyOf = (kind: \"namespace\" | \"purpose\", name: string): string => `${kind}:${name}`;\n\n/**\n * The general skills, one tree per namespace group in the backend's order (it decides the membership and puts\n * \"Ungrouped\" last). A backend that sends no groups gives one unnamed group over all general skills, so the screen\n * always has a section to draw.\n */\nexport const buildSkillNamespaceSections = (catalog: AgentSkillCatalog | null | undefined): SkillNamespaceSection[] => {\n const generalSkills = generalSkillsOf(catalog);\n const generalByName = indexSkillsByName(generalSkills);\n const groups = catalog?.namespaceGroups ?? [];\n if (groups.length === 0) {\n if (generalSkills.length === 0) return [];\n return [{ key: skillGroupSectionKeyOf(\"namespace\", \"\"), group: summarizeSkillGroup(\"\", generalSkills), rows: buildSkillTreeRows(generalSkills, generalByName) }];\n }\n return groups.map((group) => ({\n key: skillGroupSectionKeyOf(\"namespace\", group.name),\n group,\n rows: buildSkillTreeRows(\n (group.skillNames ?? []).map((name) => generalByName.get(name)).filter((skill): skill is AgentSkillCatalogEntry => skill !== undefined),\n generalByName,\n ),\n }));\n};\n\n/** The purpose-bound skills, one tree per purpose in the backend's order. */\nexport const buildSkillPurposeSections = (catalog: AgentSkillCatalog | null | undefined): SkillPurposeSection[] => {\n const skillsByName = indexSkillsByName(catalog?.skills ?? []);\n return (catalog?.purposeGroups ?? []).map((group) => ({\n key: skillGroupSectionKeyOf(\"purpose\", group.purposeName),\n group,\n rows: buildSkillTreeRows(\n (group.skillNames ?? []).map((name) => skillsByName.get(name)).filter((skill): skill is AgentSkillCatalogEntry => skill !== undefined),\n skillsByName,\n ),\n }));\n};\n\n/** The tools of a skill that carry a breakdown, by name with their tokens (a package's error rows are skipped). */\nconst toolTokensByNameOf = (skill: AgentSkillCatalogEntry): Map<string, number> => {\n const tokensByName = new Map<string, number>();\n for (const skillPackage of skill.packages ?? []) {\n for (const tool of skillPackage.tools ?? []) {\n if (tool.components !== null && tool.components !== undefined) tokensByName.set(tool.name, countOf(tool.tokens));\n }\n }\n return tokensByName;\n};\n\n/** The figures of a group over its skills, computed as the backend computes them (a shared tool counts once). */\nexport const summarizeSkillGroup = (name: string, skills: readonly AgentSkillCatalogEntry[]): AgentSkillCatalogNamespaceGroup => {\n const toolTokensByName = new Map<string, number>();\n for (const skill of skills) for (const [toolName, tokens] of toolTokensByNameOf(skill)) toolTokensByName.set(toolName, tokens);\n const rootSkills = skills.filter((skill) => !skill.isSubSkill);\n return {\n name,\n skillNames: skills.map((skill) => skill.name),\n rootSkillCount: rootSkills.length,\n subSkillCount: skills.length - rootSkills.length,\n toolCount: toolTokensByName.size,\n catalogTokens: rootSkills.reduce((sum, skill) => sum + countOf(skill.catalogLineTokens), 0),\n instructionTokens: skills.reduce((sum, skill) => sum + countOf(skill.instructionTokens), 0),\n uniqueToolDefTokens: [...toolTokensByName.values()].reduce((sum, tokens) => sum + tokens, 0),\n sumOfSkillTotals: skills.reduce((sum, skill) => sum + countOf(skill.total), 0),\n };\n};\n\n/** Σ of the totals of a root's sub-skills (counted beside the root's own total, never inside it). */\nexport const sumSubSkillTotals = (subSkills: readonly AgentSkillCatalogEntry[]): number => subSkills.reduce((sum, subSkill) => sum + countOf(subSkill.total), 0);\n\n/** The heaviest tool of a skill in tokens (the full width of the tool bars of that skill); 0 without tools. */\nexport const heaviestToolTokensOf = (skill: AgentSkillCatalogEntry): number =>\n (skill.packages ?? []).reduce((heaviest, skillPackage) => (skillPackage.tools ?? []).reduce((inner, tool) => Math.max(inner, countOf(tool.tokens)), heaviest), 0);\n\nconst normalizeSearchText = (text: string): string => text.trim().toLowerCase();\n\n/** A skill as the search left it: the skill, why it stayed, and the packages and tools still shown. */\nexport interface FilteredSkill {\n skill: AgentSkillCatalogEntry;\n /** True: the skill's own name matches (all its packages and tools stay). */\n isNameMatch: boolean;\n /** The packages shown: all of them on a name match or without a query, else those with a matching name or tool. */\n packages: AgentSkillCatalogPackage[];\n /** True: the skill stayed because of a package or a tool, so its content opens by itself. */\n isOpenedBySearch: boolean;\n}\n\n/**\n * One skill against a search text (case-insensitive, part of a name): it stays when its name matches (everything\n * inside stays), or when a package name or a tool name matches (then only the matching packages, and inside a package\n * that does not match by name only the matching tools). `null` when nothing matches. An empty query keeps everything.\n */\nexport const filterSkill = (skill: AgentSkillCatalogEntry, query: string): FilteredSkill | null => {\n const needle = normalizeSearchText(query);\n const packages = skill.packages ?? [];\n if (needle === \"\") return { skill, isNameMatch: false, packages, isOpenedBySearch: false };\n if (skill.name.toLowerCase().includes(needle)) return { skill, isNameMatch: true, packages, isOpenedBySearch: false };\n const matchingPackages = packages\n .map((skillPackage): AgentSkillCatalogPackage | null => {\n if (skillPackage.name.toLowerCase().includes(needle)) return skillPackage;\n const matchingTools = (skillPackage.tools ?? []).filter((tool: AgentSkillCatalogTool) => tool.name.toLowerCase().includes(needle));\n return matchingTools.length > 0 ? { ...skillPackage, tools: matchingTools } : null;\n })\n .filter((skillPackage): skillPackage is AgentSkillCatalogPackage => skillPackage !== null);\n return matchingPackages.length > 0 ? { skill, isNameMatch: false, packages: matchingPackages, isOpenedBySearch: true } : null;\n};\n\n/** One row of a filtered tree. */\nexport interface FilteredSkillTreeRow {\n skill: FilteredSkill;\n subSkills: FilteredSkill[];\n /** True: a sub-skill matched (and the root did not match by name), so the root is shown as the path to it. */\n isKeptForSubSkill: boolean;\n}\n\n/**\n * The rows of a tree against a search text: a root stays when it matches or one of its sub-skills does; under a root\n * that matches by name every sub-skill stays, else only the matching ones. An empty query keeps every row.\n */\nexport const filterSkillTreeRows = (rows: readonly SkillTreeRow[], query: string): FilteredSkillTreeRow[] => {\n const needle = normalizeSearchText(query);\n const unfiltered = (skill: AgentSkillCatalogEntry): FilteredSkill => ({ skill, isNameMatch: false, packages: skill.packages ?? [], isOpenedBySearch: false });\n if (needle === \"\") return rows.map((row) => ({ skill: unfiltered(row.skill), subSkills: row.subSkills.map(unfiltered), isKeptForSubSkill: false }));\n const filteredRows: FilteredSkillTreeRow[] = [];\n for (const row of rows) {\n const ownMatch = filterSkill(row.skill, needle);\n const matchingSubSkills = row.subSkills.map((subSkill) => filterSkill(subSkill, needle)).filter((subSkill): subSkill is FilteredSkill => subSkill !== null);\n if (ownMatch?.isNameMatch) {\n filteredRows.push({ skill: ownMatch, subSkills: row.subSkills.map((subSkill) => filterSkill(subSkill, needle) ?? unfiltered(subSkill)), isKeptForSubSkill: false });\n } else if (ownMatch !== null) {\n filteredRows.push({ skill: ownMatch, subSkills: matchingSubSkills, isKeptForSubSkill: false });\n } else if (matchingSubSkills.length > 0) {\n filteredRows.push({ skill: { skill: row.skill, isNameMatch: false, packages: [], isOpenedBySearch: false }, subSkills: matchingSubSkills, isKeptForSubSkill: true });\n }\n }\n return filteredRows;\n};\n\n/** The roots of one area of a namespace group, with the sub-skills under each. */\nexport interface SkillAreaSection {\n /** The area: the first name segment after the group's prefix (`Agent.Web.Search` in `Agent` → `Web`). */\n area: string;\n rows: FilteredSkillTreeRow[];\n}\n\n/**\n * The area of a skill inside its group: the first name segment after the group's name as a prefix; a skill outside\n * that prefix (an ungrouped skill, a group named otherwise) takes its own first segment.\n */\nexport const skillAreaOf = (skillName: string, groupName: string): string => {\n const segments = skillName.split(\".\").filter((segment) => segment !== \"\");\n const prefixSegments = groupName.split(\".\").filter((segment) => segment !== \"\");\n const hasPrefix = prefixSegments.length > 0 && prefixSegments.length < segments.length && prefixSegments.every((segment, index) => segments[index] === segment);\n return (hasPrefix ? segments[prefixSegments.length] : segments[0]) ?? skillName;\n};\n\nconst compareSkillRowsByBaseThenName = (first: FilteredSkillTreeRow, second: FilteredSkillTreeRow): number =>\n Number(second.skill.skill.isBaseSkill === true) - Number(first.skill.skill.isBaseSkill === true) || first.skill.skill.name.localeCompare(second.skill.skill.name);\n\n/**\n * The rows of a namespace group by area ({@link skillAreaOf} of each root): inside an area the base skills first, then\n * the roots by name; the sub-skills stay under their root. The areas that hold a base skill come first, then the\n * areas by name. Derived from the names and the root/sub-skill data alone: a root that becomes a sub-skill moves\n * under its new root with no change here.\n */\nexport const groupSkillTreeRowsByArea = (rows: readonly FilteredSkillTreeRow[], groupName: string): SkillAreaSection[] => {\n const rowsByArea = new Map<string, FilteredSkillTreeRow[]>();\n for (const row of rows) {\n const area = skillAreaOf(row.skill.skill.name, groupName);\n rowsByArea.set(area, [...(rowsByArea.get(area) ?? []), row]);\n }\n const areas = [...rowsByArea.entries()].map(([area, areaRows]) => ({ area, rows: [...areaRows].sort(compareSkillRowsByBaseThenName) }));\n const hasBaseSkill = (section: SkillAreaSection): boolean => section.rows.some((row) => row.skill.skill.isBaseSkill === true);\n return areas.sort((first, second) => Number(hasBaseSkill(second)) - Number(hasBaseSkill(first)) || first.area.localeCompare(second.area));\n};\n\n/** How many skills (roots and sub-skills) a filtered tree shows. */\nexport const countFilteredSkills = (rows: readonly FilteredSkillTreeRow[]): number => rows.reduce((count, row) => count + 1 + row.subSkills.length, 0);\n\n/** The shared blocks of the answer as a list, whether they arrive as a set (`blocks`) or as a list. */\nexport const sharedBlocksOf = (response: AgentSkillSharedBlocksResponse | null | undefined): AgentSkillCatalogSharedBlock[] => {\n const sharedBlocks = response?.sharedBlocks;\n if (Array.isArray(sharedBlocks)) return sharedBlocks;\n return sharedBlocks?.blocks ?? [];\n};\n\n/** Where a tool sits in the catalog: the first skill and package that list it. */\nexport interface SkillToolLocation {\n skillName: string;\n packageName: string;\n tool: AgentSkillCatalogTool;\n}\n\n/** Every place of the catalog that lists the tool (a shared tool sits in several skills), in catalog order. */\nexport const findSkillToolLocations = (catalog: AgentSkillCatalog | null | undefined, toolName: string): SkillToolLocation[] => {\n const locations: SkillToolLocation[] = [];\n for (const skill of catalog?.skills ?? []) {\n for (const skillPackage of skill.packages ?? []) {\n for (const tool of skillPackage.tools ?? []) {\n if (tool.name === toolName) locations.push({ skillName: skill.name, packageName: skillPackage.name, tool });\n }\n }\n }\n return locations;\n};\n","import { normalizeDddError } from \"@mgamadeus/ddd-web/contract\";\nimport { useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { MarkdownPreview } from \"@mgamadeus/ddd-admin-ui/markdown\";\nimport { StatusCallout } from \"@mgamadeus/ddd-admin-ui/page\";\nimport { Card, CardContent, CardDescription, CardHeader, CardTitle } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { Skeleton } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport type { ReactNode } from \"react\";\nimport { Disclosure } from \"../blocks/Disclosure\";\nimport { TokenFigure } from \"../blocks/TokenFigure\";\nimport type { AgentSkillCatalogApi } from \"./agent-skill-catalog-api\";\nimport { sharedBlocksOf } from \"./skill-catalog-tree\";\n\nexport interface SharedBlocksPanelProps {\n /** `createAgentSkillCatalogApi(…)` of the host. */\n api: AgentSkillCatalogApi;\n /** Draws a block's markdown; default the admin UI's markdown preview for texts of unknown origin. */\n renderMarkdown?: (source: string) => ReactNode;\n className?: string;\n}\n\n/**\n * The blocks the system message carries once per turn whatever is loaded (the query-options grammar, the shared\n * request parameters): title, tokens, and the markdown the agent reads on opening one.\n */\nexport const SharedBlocksPanel = ({ api, renderMarkdown, className }: SharedBlocksPanelProps) => {\n const { t } = useTranslate();\n const query = api.useSkillSharedBlocksQuery();\n const blocks = sharedBlocksOf(query.data);\n return (\n <Card data-slot=\"skill-shared-blocks\" className={className}>\n <CardHeader>\n <CardTitle>{t(\"Shared blocks\")}</CardTitle>\n <CardDescription>{t(\"Sent once per turn in the system message, not once per tool: what the tools' parameters share.\")}</CardDescription>\n </CardHeader>\n <CardContent>\n {query.isError ? (\n <StatusCallout size=\"compact\" tone=\"destructive\" title={t(\"The shared blocks could not be loaded.\")} description={normalizeDddError(query.error, \"\").message} />\n ) : query.isLoading ? (\n <div className=\"space-y-2\">\n <Skeleton className=\"h-6 w-full\" />\n <Skeleton className=\"h-6 w-full\" />\n </div>\n ) : blocks.length === 0 ? (\n <p className=\"text-sm text-muted-foreground\">{t(\"No shared blocks.\")}</p>\n ) : (\n <ul className=\"divide-y divide-border\">\n {blocks.map((block) => (\n <li key={block.key} data-shared-block={block.key}>\n <Disclosure\n title={block.title && block.title !== \"\" ? block.title : block.key}\n meta={<TokenFigure value={block.tokens} className=\"text-xs\" suffix={t(\"tokens\")} />}\n triggerClassName=\"py-2.5\"\n >\n <div className=\"min-w-0 pb-3 pl-6 text-sm\">\n {renderMarkdown ? renderMarkdown(block.markdown ?? \"\") : <MarkdownPreview source={block.markdown ?? \"\"} untrusted />}\n </div>\n </Disclosure>\n </li>\n ))}\n </ul>\n )}\n </CardContent>\n </Card>\n );\n};\n","import { seriesFillClassNameOf } from \"../blocks/series-fill-classes\";\nimport type { SkillToolTokenPartKind } from \"./skill-catalog-tree\";\n\n/** The fill of a skill's instruction tokens (the hue of the skills family of the context composition). */\nexport const SKILL_INSTRUCTIONS_FILL_CLASS_NAME = seriesFillClassNameOf(\"series7\");\n\n/** The fill of tool-definition tokens (the neutral of the tool schemas of the context composition). */\nexport const SKILL_TOOL_DEFINITIONS_FILL_CLASS_NAME = seriesFillClassNameOf(\"neutral\");\n\n/**\n * The fill of a part of a tool's wire schema: one hue per kind of part; parameters and definitions, of which a tool\n * has many, take their hue's steps in turn (`positionInKind`, 0-based).\n */\nexport const skillToolTokenPartFillClassNameOf = (kind: SkillToolTokenPartKind, positionInKind = 0): string => {\n switch (kind) {\n case \"description\":\n return seriesFillClassNameOf(\"series1\");\n case \"parameter\":\n return seriesFillClassNameOf(\"series7\", positionInKind);\n case \"definition\":\n return seriesFillClassNameOf(\"series3\", positionInKind);\n default:\n return seriesFillClassNameOf(\"neutral\");\n }\n};\n","import { formatUiNumber, getUiLocale, useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { Badge } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { cn } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { ChevronRight } from \"lucide-react\";\nimport { ProportionBar } from \"../blocks/ProportionBar\";\nimport { formatTokenFigure } from \"../blocks/token-figure\";\nimport { TokenFigure } from \"../blocks/TokenFigure\";\nimport { SKILL_INSTRUCTIONS_FILL_CLASS_NAME, SKILL_TOOL_DEFINITIONS_FILL_CLASS_NAME } from \"./skill-catalog-colors\";\nimport { type FilteredSkill, type FilteredSkillTreeRow, heaviestToolTokensOf, sumSubSkillTotals } from \"./skill-catalog-tree\";\n\n/**\n * The columns of a skill line and of the lines inside it, so figures sit below each other: name, catalog line, total,\n * the bar, tools. Below `md` the catalog line and the bar are left out.\n */\nexport const SKILL_ROW_GRID_CLASS_NAME =\n \"grid grid-cols-[minmax(0,1fr)_6rem_4.5rem] items-center gap-x-4 md:grid-cols-[minmax(0,1fr)_5.5rem_6.5rem_8rem_4.5rem]\";\n\n/** The same columns with one more at the end from `md`: how often the skill was loaded in a period. */\nexport const SKILL_ROW_WITH_LOADS_GRID_CLASS_NAME =\n \"grid grid-cols-[minmax(0,1fr)_6rem_4.5rem] items-center gap-x-4 md:grid-cols-[minmax(0,1fr)_5.5rem_6.5rem_8rem_4.5rem_4.5rem]\";\n\nexport interface SkillTreeRowViewProps {\n row: FilteredSkillTreeRow;\n /** The key prefix of the section the row sits in (a skill can sit in several sections). */\n sectionKey: string;\n /** The keys of the open skills (`<sectionKey>/<skill name>`). */\n openSkillKeys: ReadonlySet<string>;\n onToggleSkill: (skillKey: string) => void;\n onSelectTool: (toolName: string, skillName: string, packageName: string) => void;\n /** The tool whose drawer is open, marked in its line. */\n selectedToolName?: string | null;\n /**\n * How often each skill was loaded in a period, by skill name: with it every skill line ends with its loads (0 for a\n * skill the map does not name). Absent or `null`: no loads column.\n */\n loadCountBySkillName?: ReadonlyMap<string, number> | null;\n}\n\ninterface SkillLineProps extends Omit<SkillTreeRowViewProps, \"row\"> {\n filteredSkill: FilteredSkill;\n /** How many sub-skills the root lists and what they total (counted beside the root). */\n subSkillCount?: number;\n subSkillTotal?: number;\n isSubSkillLine?: boolean;\n}\n\nconst SkillLine = ({\n filteredSkill,\n sectionKey,\n openSkillKeys,\n onToggleSkill,\n onSelectTool,\n selectedToolName,\n loadCountBySkillName = null,\n subSkillCount = 0,\n subSkillTotal = 0,\n isSubSkillLine = false,\n}: SkillLineProps) => {\n const { t } = useTranslate();\n const hasLoads = loadCountBySkillName !== null;\n const gridClassName = hasLoads ? SKILL_ROW_WITH_LOADS_GRID_CLASS_NAME : SKILL_ROW_GRID_CLASS_NAME;\n const { skill, packages } = filteredSkill;\n const skillKey = `${sectionKey}/${skill.name}`;\n const hasContent = packages.length > 0;\n const isOpen = hasContent && (filteredSkill.isOpenedBySearch || openSkillKeys.has(skillKey));\n const heaviestToolTokens = heaviestToolTokensOf(skill);\n const locale = getUiLocale();\n const contentId = `skill-content-${skillKey.replace(/[^A-Za-z0-9_-]/g, \"-\")}`;\n return (\n <div data-slot=\"skill-row\" data-skill={skill.name} className=\"min-w-0\">\n <div\n className={cn(\n gridClassName,\n \"relative rounded-lg px-2 py-2 focus-within:ring-2 focus-within:ring-ring\",\n hasContent && \"hover:bg-tint\",\n )}\n >\n <span className=\"flex min-w-0 flex-wrap items-center gap-x-2 gap-y-0.5\">\n {/* the button's hit area is the whole line (`after:inset-0`); the bar sits above it for its tooltips */}\n <button\n type=\"button\"\n disabled={!hasContent}\n aria-expanded={hasContent ? isOpen : undefined}\n aria-controls={isOpen ? contentId : undefined}\n onClick={() => onToggleSkill(skillKey)}\n className=\"flex min-w-0 items-center gap-2 text-left outline-none after:absolute after:inset-0 after:rounded-lg enabled:cursor-pointer\"\n >\n <ChevronRight aria-hidden className={cn(\"size-4 shrink-0 text-muted-foreground transition-transform\", isOpen && \"rotate-90\", !hasContent && \"invisible\")} />\n <span className={cn(\"min-w-0 font-mono text-sm break-all\", isSubSkillLine ? \"font-medium\" : \"font-semibold\")}>{skill.name}</span>\n </button>\n {isSubSkillLine && (\n <Badge variant=\"outline\" className=\"text-[10px]\">\n {t(\"sub-skill\")}\n </Badge>\n )}\n {skill.isBaseSkill === true && (\n <Badge variant=\"secondary\" className=\"text-[10px]\" title={t(\"Pinned into every conversation from its start\")}>\n {t(\"base skill\")}\n </Badge>\n )}\n {skill.isPurposeBound === true && (skill.offeredUnderPurposeNames ?? []).length > 1 && (\n <span className=\"text-xs text-muted-foreground\">\n {t(\"{count, plural, one {under # purpose} other {under # purposes}}\", { count: (skill.offeredUnderPurposeNames ?? []).length })}\n </span>\n )}\n {subSkillCount > 0 && (\n <span className=\"text-xs text-muted-foreground\">\n {t(\"own share\")} · {t(\"{count, plural, one {+# sub-skill} other {+# sub-skills}}\", { count: subSkillCount })}{\" \"}\n {formatTokenFigure(subSkillTotal, { locale })} {t(\"(counted separately)\")}\n </span>\n )}\n </span>\n <span className=\"hidden text-right text-xs text-muted-foreground md:block\">\n <TokenFigure value={skill.catalogLineTokens} />\n </span>\n <span className=\"text-right text-sm font-medium\">\n <TokenFigure value={skill.total} />\n </span>\n <div className=\"relative z-[1] hidden md:block\">\n <ProportionBar\n size=\"sm\"\n showLegend={false}\n aria-label={t(\"Tokens of %skill%\", { replacements: { skill: skill.name } })}\n segments={[\n { key: \"instructions\", value: skill.instructionTokens ?? 0, colorClassName: SKILL_INSTRUCTIONS_FILL_CLASS_NAME, label: t(\"Instructions\", { context: \"skill-catalog\" }) },\n { key: \"toolDefinitions\", value: skill.toolDefTokens ?? 0, colorClassName: SKILL_TOOL_DEFINITIONS_FILL_CLASS_NAME, label: t(\"Tool definitions\") },\n ]}\n formatValue={(value) => formatTokenFigure(value, { locale })}\n />\n </div>\n <span className=\"text-right text-xs text-muted-foreground tabular-nums\">{t(\"{count, plural, one {# tool} other {# tools}}\", { count: skill.toolCount ?? 0 })}</span>\n {hasLoads && (\n <span data-slot=\"skill-load-count\" className={cn(\"hidden text-right text-sm tabular-nums md:block\", (loadCountBySkillName.get(skill.name) ?? 0) === 0 && \"text-muted-foreground\")}>\n {formatUiNumber(loadCountBySkillName.get(skill.name) ?? 0)}\n </span>\n )}\n </div>\n\n {isOpen && (\n <div id={contentId} data-slot=\"skill-packages\" className=\"mb-2 ml-4 space-y-2 border-l border-border pl-4\">\n {packages.map((skillPackage) => (\n <div key={skillPackage.name} data-package={skillPackage.name} className=\"min-w-0\">\n <div className={cn(gridClassName, \"px-2 py-1 text-xs text-muted-foreground\")}>\n <span className=\"min-w-0 font-mono break-all\">{skillPackage.name}</span>\n <span className=\"hidden md:block\" />\n <span className=\"text-right\">\n <TokenFigure value={skillPackage.total} />\n </span>\n <span className=\"hidden md:block\" />\n <span className=\"text-right tabular-nums\">{t(\"{count, plural, one {# tool} other {# tools}}\", { count: skillPackage.toolCount ?? (skillPackage.tools ?? []).length })}</span>\n </div>\n <ul>\n {(skillPackage.tools ?? []).map((tool) => {\n const hasBreakdown = tool.components !== null && tool.components !== undefined;\n const widthPercent = heaviestToolTokens > 0 ? Math.max(2, ((tool.tokens ?? 0) / heaviestToolTokens) * 100) : 0;\n return (\n <li key={tool.name}>\n <button\n type=\"button\"\n data-slot=\"skill-tool\"\n data-tool={tool.name}\n aria-current={selectedToolName === tool.name ? \"true\" : undefined}\n onClick={() => onSelectTool(tool.name, skill.name, skillPackage.name)}\n className={cn(\n gridClassName,\n \"w-full rounded-md px-2 py-1 text-left outline-none hover:bg-tint focus-visible:ring-2 focus-visible:ring-ring aria-[current=true]:bg-tint-strong\",\n )}\n >\n <span className=\"min-w-0 pl-3 font-mono text-xs break-all text-primary-emphasis\">{tool.name}</span>\n <span className=\"hidden md:block\" />\n <span className=\"text-right text-xs\">{hasBreakdown ? <TokenFigure value={tool.tokens} /> : <span className=\"text-destructive\">{t(\"not readable\")}</span>}</span>\n <span aria-hidden className=\"hidden h-1.5 overflow-hidden rounded-full bg-muted md:block\">\n <span className={cn(\"block h-full rounded-full\", SKILL_TOOL_DEFINITIONS_FILL_CLASS_NAME)} style={{ width: `${widthPercent}%` }} />\n </span>\n <span />\n </button>\n </li>\n );\n })}\n </ul>\n </div>\n ))}\n </div>\n )}\n </div>\n );\n};\n\n/**\n * One skill of the catalog as a line that opens: its name, what it adds to the catalog block, its own total, the split\n * between instructions and tool definitions as a two-colour bar, its tool count; opened, its packages with their tools\n * (each tool with a bar against the skill's heaviest tool and its tokens; a click opens the tool). The sub-skills of a\n * root sit indented below it, each a line of its own: their tokens are counted beside the root's, never inside.\n */\nexport const SkillTreeRowView = ({ row, sectionKey, openSkillKeys, onToggleSkill, onSelectTool, selectedToolName, loadCountBySkillName }: SkillTreeRowViewProps) => (\n <li data-slot=\"skill-tree-row\" className=\"min-w-0\">\n <SkillLine\n filteredSkill={row.skill}\n sectionKey={sectionKey}\n openSkillKeys={openSkillKeys}\n onToggleSkill={onToggleSkill}\n onSelectTool={onSelectTool}\n selectedToolName={selectedToolName}\n loadCountBySkillName={loadCountBySkillName}\n subSkillCount={row.subSkills.length}\n subSkillTotal={sumSubSkillTotals(row.subSkills.map((subSkill) => subSkill.skill))}\n />\n {row.subSkills.length > 0 && (\n <div data-slot=\"skill-sub-skills\" className=\"mb-1 ml-4 border-l border-border pl-2\">\n {row.subSkills.map((subSkill) => (\n <SkillLine\n key={subSkill.skill.name}\n filteredSkill={subSkill}\n sectionKey={`${sectionKey}/${row.skill.skill.name}`}\n openSkillKeys={openSkillKeys}\n onToggleSkill={onToggleSkill}\n onSelectTool={onSelectTool}\n selectedToolName={selectedToolName}\n loadCountBySkillName={loadCountBySkillName}\n isSubSkillLine\n />\n ))}\n </div>\n )}\n </li>\n);\n","import { m, type TranslateFn } from \"@mgamadeus/ddd-admin-ui/i18n\";\n\n/**\n * The owner-facing description of the package's own purposes, as English text keys: the purpose files' descriptions\n * are written for the model and in English. A host describes its own purposes through `describeSkillPurpose`.\n */\nexport const PACKAGE_PURPOSE_DESCRIPTIONS: Readonly<Record<string, string>> = {\n \"Schedule.Run\": m(\n \"One run of a scheduled task: it carries out the task's instructions without anybody watching, reports through the schedule's report channel and closes. Started only by the schedule.\",\n ),\n \"Supervisor.Checkpoint\": m(\n \"The supervisor: a background conversation that runs beside a supervised conversation and checks its work at every checkpoint. Started only by the system.\",\n ),\n \"Background.MechanicalOperation\": m(\n \"A background step the system starts for one named operation, without a call to the AI model (for example warming a cache). Never started by hand.\",\n ),\n};\n\n/**\n * The description of a purpose in the viewer's language: the host's words (`describeSkillPurpose`, already translated),\n * else the package's for its own purposes, else what the server sent.\n */\nexport const describeSkillPurposeText = (\n purposeName: string,\n serverDescription: string | null | undefined,\n t: TranslateFn,\n describeSkillPurpose?: (purposeName: string) => string | null | undefined,\n): string => {\n const hostDescription = describeSkillPurpose?.(purposeName);\n if (typeof hostDescription === \"string\" && hostDescription !== \"\") return hostDescription;\n const packageDescription = PACKAGE_PURPOSE_DESCRIPTIONS[purposeName];\n if (packageDescription !== undefined) return t(packageDescription);\n return serverDescription ?? \"\";\n};\n","/**\n * A set of the backend as it arrives: its elements under `elements` (an object set), or a plain list. Read it through\n * `wireElementsOf`.\n */\nexport type AdminWireSet<TElement> = { elements?: readonly TElement[] | null } | readonly TElement[];\n\n/** The elements of a set in either wire form; empty for anything else. */\nexport const wireElementsOf = <TElement>(value: AdminWireSet<TElement> | null | undefined): TElement[] => {\n if (Array.isArray(value)) return [...(value as readonly TElement[])];\n if (value !== null && typeof value === \"object\") {\n const elements = (value as { elements?: readonly TElement[] | null }).elements;\n return Array.isArray(elements) ? [...elements] : [];\n }\n return [];\n};\n\n/** A finite number of a wire value (a number, or digits as text); `null` for everything else. */\nexport const wireNumberOf = (value: unknown): number | null => {\n if (typeof value === \"number\") return Number.isFinite(value) ? value : null;\n if (typeof value === \"string\" && value.trim() !== \"\") {\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : null;\n }\n return null;\n};\n\n/** The change history a stored row carries. */\nexport interface AdminWireChangeHistory {\n createdTime?: string | null;\n modifiedTime?: string | null;\n}\n\n/** When a stored row was created: its change history's time, else its own `created`. */\nexport const wireCreatedTimeOf = (row: { changeHistory?: AdminWireChangeHistory | null; created?: string | null } | null | undefined): string | null =>\n row?.changeHistory?.createdTime ?? row?.created ?? null;\n","import { normalizeDddError } from \"@mgamadeus/ddd-web/contract\";\nimport { NoteList } from \"@mgamadeus/ddd-admin-ui/data\";\nimport { formatUiNumber, getUiLocale, useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { StatusCallout } from \"@mgamadeus/ddd-admin-ui/page\";\nimport { Badge, Button, Card, CardContent, cn, Skeleton, Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { useState } from \"react\";\nimport type { AdminPeriod } from \"../period/admin-period\";\nimport { wireElementsOf } from \"../wire/admin-wire\";\nimport type { AgentSkillCatalogApi } from \"./agent-skill-catalog-api\";\nimport type { AgentSkillLoadSource } from \"./agent-skill-catalog-types\";\n\nexport interface SkillLoadSourcesPanelProps {\n api: Pick<AgentSkillCatalogApi, \"useSkillLoadSourcesQuery\">;\n /** The period the loads are counted over. */\n period: Pick<AdminPeriod, \"from\" | \"to\">;\n className?: string;\n}\n\n/** The rows the card shows before \"show all\". */\nexport const SKILL_LOAD_SOURCES_COLLAPSED_ROW_COUNT = 12;\n\n/** A skill the chat model loaded itself while no preload brought it in the period: a preload candidate. */\nexport const isSkillPreloadCandidate = (loadSource: AgentSkillLoadSource): boolean =>\n (loadSource.modelLoadCount ?? 0) > 0 && (loadSource.preloadCount ?? 0) + (loadSource.subPassPreloadCount ?? 0) === 0;\n\nconst CountCell = ({ value }: { value: number }) => (\n <TableCell className={cn(\"px-3 py-2 text-right align-top tabular-nums\", value === 0 && \"text-muted-foreground\")}>{formatUiNumber(value)}</TableCell>\n);\n\n/**\n * How the skills came into conversations in a period, by source: the decision model's preloads (first pass and the\n * follow-up pass under a preloaded root) and the chat model's own calls of the skill-loading tool, with the share of\n * the preloading turns that used what was preloaded. A skill the model loads itself that no preload brought is\n * marked as a preload candidate.\n */\nexport const SkillLoadSourcesPanel = ({ api, period, className }: SkillLoadSourcesPanelProps) => {\n const { t } = useTranslate();\n const locale = getUiLocale();\n const [isShowingAll, setIsShowingAll] = useState(false);\n const query = api.useSkillLoadSourcesQuery({ from: period.from, to: period.to });\n const response = query.data ?? null;\n const loadSources = response?.loadSources ?? null;\n const rows = loadSources === null ? null : wireElementsOf(loadSources);\n if (query.isLoading || (rows === null && query.isFetching)) return <Skeleton className={cn(\"h-48 w-full rounded-2xl\", className)} />;\n if (query.isError || rows === null || loadSources === null) {\n return (\n <StatusCallout\n tone=\"destructive\"\n title={t(\"The skill load sources could not be loaded.\")}\n description={query.isError ? normalizeDddError(query.error, \"\").message : undefined}\n className={className}\n />\n );\n }\n const percent = new Intl.NumberFormat(locale, { style: \"percent\", maximumFractionDigits: 0 });\n const usedTurnCount = loadSources.preloadUsedTurnCount ?? 0;\n const unusedTurnCount = loadSources.preloadUnusedTurnCount ?? 0;\n const usedShare = typeof loadSources.preloadUsedShare === \"number\" ? Math.min(1, Math.max(0, loadSources.preloadUsedShare)) : null;\n const shownRows = isShowingAll ? rows : rows.slice(0, SKILL_LOAD_SOURCES_COLLAPSED_ROW_COUNT);\n const notes = [\n ...(response?.isLoadSourceDataAvailable === false ? [{ id: \"sourcesUnavailable\", tone: \"warning\" as const, text: t(\"The turn events cannot be read on this database: no load sources.\") }] : []),\n ...(loadSources.isModelLoadCountAvailable === false ? [{ id: \"modelLoadsUnavailable\", tone: \"warning\" as const, text: t(\"The loads of the chat model cannot be counted on this database: only the preloads are shown.\") }] : []),\n ...(loadSources.isTruncated === true ? [{ id: \"sourcesTruncated\", tone: \"warning\" as const, text: t(\"The period holds more rows than one read counts: the newest were counted.\") }] : []),\n ];\n return (\n <Card data-slot=\"skill-load-sources-panel\" className={cn(\"gap-0 py-0 transition-opacity motion-reduce:transition-none\", query.isFetching && \"opacity-80\", className)}>\n <CardContent className=\"space-y-3 px-2 py-4\">\n <div className=\"flex flex-wrap items-start justify-between gap-4 px-3\">\n <div className=\"max-w-2xl\">\n <h2 className=\"text-lg font-semibold\">{t(\"Loads by source\")}</h2>\n <p className=\"text-sm text-muted-foreground\">\n {t(\"How each skill came into the conversations: preloaded by the decision model (first pass, or the follow-up pass under a preloaded root) or loaded by the chat model itself with load_skills. A skill the model loads itself that no preload brought is a preload candidate.\")}\n </p>\n </div>\n <div data-slot=\"skill-preload-outcome\" className=\"w-60 shrink-0\">\n <span className=\"text-xs text-muted-foreground\">{t(\"Preloads used\")}</span>\n {usedShare === null ? (\n <p className=\"text-sm text-muted-foreground\">{t(\"no preloading turn\")}</p>\n ) : (\n <>\n <span className=\"flex items-baseline justify-between gap-2 text-sm\">\n <span className=\"font-semibold tabular-nums\">{percent.format(usedShare)}</span>\n <span className=\"text-xs text-muted-foreground tabular-nums\">\n {t(\"%used% used, %unused% unused\", { replacements: { used: formatUiNumber(usedTurnCount), unused: formatUiNumber(unusedTurnCount) } })}\n </span>\n </span>\n <span\n role=\"meter\"\n aria-label={t(\"Preloads used\")}\n aria-valuemin={0}\n aria-valuemax={100}\n aria-valuenow={Math.round(usedShare * 100)}\n className=\"mt-1 block h-1.5 overflow-hidden rounded-full bg-muted\"\n >\n <span className=\"block h-full rounded-full bg-[color:var(--series-1,var(--brand))]\" style={{ width: `${usedShare * 100}%` }} />\n </span>\n </>\n )}\n </div>\n </div>\n {notes.length > 0 && (\n <div className=\"px-3\">\n <NoteList notes={notes} />\n </div>\n )}\n {rows.length === 0 ? (\n <p className=\"px-3 py-6 text-center text-sm text-muted-foreground\">{t(\"No skill was loaded in this period.\")}</p>\n ) : (\n <>\n <Table>\n <TableHeader>\n <TableRow className=\"hover:bg-transparent\">\n <TableHead className=\"px-3 text-xs text-muted-foreground\">{t(\"Skill\", { context: \"skill-catalog\" })}</TableHead>\n <TableHead className=\"px-3 text-right text-xs text-muted-foreground\">{t(\"Preload\", { context: \"skill-load-source\" })}</TableHead>\n <TableHead className=\"px-3 text-right text-xs text-muted-foreground\">{t(\"Follow-up pass\", { context: \"skill-load-source\" })}</TableHead>\n <TableHead className=\"px-3 text-right text-xs text-muted-foreground\"><span className=\"font-mono\">{\"load_skills\"}</span></TableHead>\n <TableHead className=\"px-3 text-right text-xs text-muted-foreground\">{t(\"Preload used\", { context: \"skill-load-source\" })}</TableHead>\n <TableHead className=\"px-3 text-right text-xs text-muted-foreground\">{t(\"Preload unused\", { context: \"skill-load-source\" })}</TableHead>\n </TableRow>\n </TableHeader>\n <TableBody>\n {shownRows.map((loadSource) => (\n <TableRow key={loadSource.skillName} data-slot=\"skill-load-source\" data-skill={loadSource.skillName} className=\"hover:bg-transparent\">\n <TableCell className=\"px-3 py-2 align-top whitespace-normal\">\n <span className=\"flex flex-wrap items-center gap-2\">\n <span className=\"font-mono text-sm break-all\">{loadSource.skillName}</span>\n {isSkillPreloadCandidate(loadSource) && (\n <Badge variant=\"warning\" className=\"text-[10px]\">\n {t(\"preload candidate\")}\n </Badge>\n )}\n </span>\n </TableCell>\n <CountCell value={loadSource.preloadCount ?? 0} />\n <CountCell value={loadSource.subPassPreloadCount ?? 0} />\n <CountCell value={loadSource.modelLoadCount ?? 0} />\n <CountCell value={loadSource.preloadUsedCount ?? 0} />\n <CountCell value={loadSource.preloadUnusedCount ?? 0} />\n </TableRow>\n ))}\n </TableBody>\n </Table>\n {rows.length > SKILL_LOAD_SOURCES_COLLAPSED_ROW_COUNT && (\n <div className=\"px-3\">\n <Button type=\"button\" variant=\"outline\" size=\"sm\" data-slot=\"skill-load-sources-toggle\" onClick={() => setIsShowingAll((value) => !value)}>\n {isShowingAll ? t(\"Show fewer skills\") : t(\"{count, plural, one {Show all # skill} other {Show all # skills}}\", { count: rows.length })}\n </Button>\n </div>\n )}\n </>\n )}\n </CardContent>\n </Card>\n );\n};\n","import { normalizeDddError } from \"@mgamadeus/ddd-web/contract\";\nimport { formatUiNumber, getUiLocale, useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { StatusCallout } from \"@mgamadeus/ddd-admin-ui/page\";\nimport { Badge, Card, CardContent, cn, Skeleton, Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { CalendarClock } from \"lucide-react\";\nimport type { AdminPeriod } from \"../period/admin-period\";\nimport { wireElementsOf } from \"../wire/admin-wire\";\nimport type { AgentSkillCatalogApi } from \"./agent-skill-catalog-api\";\nimport { describeSkillPurposeText } from \"./skill-purpose-texts\";\n\nexport interface SkillPurposesPanelProps {\n api: Pick<AgentSkillCatalogApi, \"useSkillPurposesQuery\">;\n /** The period the runs are counted over. */\n period: Pick<AdminPeriod, \"from\" | \"to\">;\n /** The host's description of a purpose it registered (its purpose files are English), already translated; null: the server's. */\n describeSkillPurpose?: (purposeName: string) => string | null | undefined;\n className?: string;\n}\n\nconst SkillNames = ({ names }: { names: readonly string[] }) => (\n <span className=\"flex flex-wrap gap-1\">\n {names.map((name) => (\n <Badge key={name} variant=\"outline\" className=\"font-mono text-[11px]\">\n {name}\n </Badge>\n ))}\n </span>\n);\n\n/**\n * The registered conversation purposes: what each declares (its description, the skills it preloads, the skills it\n * may load, whether the runs of a schedule may start with it) and how it was used in a period (runs started, and the\n * share of them closed as completed).\n */\nexport const SkillPurposesPanel = ({ api, period, describeSkillPurpose, className }: SkillPurposesPanelProps) => {\n const { t } = useTranslate();\n const locale = getUiLocale();\n const query = api.useSkillPurposesQuery({ from: period.from, to: period.to });\n const purposes = query.data?.purposes == null ? null : wireElementsOf(query.data.purposes);\n if (query.isLoading || (purposes === null && query.isFetching)) return <Skeleton className={cn(\"h-72 w-full rounded-2xl\", className)} />;\n if (query.isError || purposes === null) {\n return <StatusCallout tone=\"destructive\" title={t(\"The purposes could not be loaded.\")} description={query.isError ? normalizeDddError(query.error, \"\").message : undefined} className={className} />;\n }\n const percent = new Intl.NumberFormat(locale, { style: \"percent\", maximumFractionDigits: 0 });\n return (\n <Card data-slot=\"skill-purposes-panel\" className={cn(\"gap-0 py-0 transition-opacity motion-reduce:transition-none\", query.isFetching && \"opacity-80\", className)}>\n <CardContent className=\"px-2 py-4\">\n <div className=\"px-3 pb-2\">\n <h2 className=\"text-lg font-semibold\">{t(\"Purposes\", { context: \"skill-catalog-section\" })}</h2>\n <p className=\"text-sm text-muted-foreground\">\n {t(\"Conversations with a fixed course. A run is a conversation started with the purpose; it counts as finished once it is closed as completed.\")}\n </p>\n </div>\n {purposes.length === 0 ? (\n <p className=\"px-3 py-8 text-center text-sm text-muted-foreground\">{t(\"No purpose is registered.\")}</p>\n ) : (\n <Table>\n <TableHeader>\n <TableRow className=\"hover:bg-transparent\">\n <TableHead className=\"px-3 text-xs text-muted-foreground\">{t(\"Purpose\", { context: \"skill-catalog\" })}</TableHead>\n <TableHead className=\"px-3 text-xs text-muted-foreground\">{t(\"Preloads\")}</TableHead>\n <TableHead className=\"px-3 text-xs text-muted-foreground\">{t(\"May load\")}</TableHead>\n <TableHead className=\"px-3 text-right text-xs text-muted-foreground\">{t(\"Runs\", { context: \"skill-catalog\" })}</TableHead>\n <TableHead className=\"px-3 text-xs text-muted-foreground\">{t(\"Finished\", { context: \"skill-catalog\" })}</TableHead>\n </TableRow>\n </TableHeader>\n <TableBody>\n {purposes.map((purpose) => {\n const preloadSkillNames = purpose.preloadSkillNames ?? [];\n const allowedLoadSkillNames = purpose.allowedLoadSkillNames ?? [];\n const runCount = purpose.runCount ?? 0;\n const finishRate = typeof purpose.finishRate === \"number\" ? Math.min(1, Math.max(0, purpose.finishRate)) : null;\n const purposeDescription = describeSkillPurposeText(purpose.purposeName, purpose.description, t, describeSkillPurpose);\n return (\n <TableRow key={purpose.purposeName} data-slot=\"skill-purpose\" data-purpose={purpose.purposeName} className=\"hover:bg-transparent\">\n <TableCell className=\"max-w-80 px-3 py-2.5 align-top whitespace-normal\">\n <span className=\"flex flex-wrap items-center gap-2\">\n <span className=\"font-mono text-sm font-semibold break-all\">{purpose.purposeName}</span>\n {purpose.isScheduleRunPurpose === true && (\n <Badge variant=\"info\" className=\"gap-1 text-[10px]\">\n <CalendarClock aria-hidden className=\"size-3\" />\n {t(\"scheduled runs\", { context: \"skill-catalog\" })}\n </Badge>\n )}\n {purpose.isDefined === false && <Badge variant=\"destructive\">{t(\"no purpose definition\")}</Badge>}\n </span>\n {purposeDescription !== \"\" && <p className=\"text-sm text-muted-foreground\">{purposeDescription}</p>}\n </TableCell>\n <TableCell className=\"max-w-56 px-3 py-2.5 align-top text-sm whitespace-normal\">\n {preloadSkillNames.length > 0 ? <SkillNames names={preloadSkillNames} /> : <span className=\"text-muted-foreground\">{t(\"nothing\")}</span>}\n </TableCell>\n <TableCell className=\"max-w-64 px-3 py-2.5 align-top text-sm whitespace-normal\">\n {allowedLoadSkillNames.length > 0 ? <SkillNames names={allowedLoadSkillNames} /> : <span className=\"text-muted-foreground\">{t(\"every skill the account is entitled to\")}</span>}\n </TableCell>\n <TableCell className={cn(\"px-3 py-2.5 text-right align-top tabular-nums\", runCount === 0 && \"text-muted-foreground\")}>{formatUiNumber(runCount)}</TableCell>\n <TableCell className=\"w-44 px-3 py-2.5 align-top\">\n {finishRate === null ? (\n <span className=\"text-sm text-muted-foreground\">{t(\"no run\")}</span>\n ) : (\n <>\n <span className=\"flex items-baseline justify-between gap-2 text-sm\">\n <span className=\"font-semibold tabular-nums\">{percent.format(finishRate)}</span>\n <span className=\"text-xs text-muted-foreground tabular-nums\">\n {t(\"%finished% of %runs%\", { replacements: { finished: formatUiNumber(purpose.finishedRunCount ?? 0), runs: formatUiNumber(runCount) } })}\n </span>\n </span>\n <span\n role=\"meter\"\n aria-label={t(\"Finished runs of %purpose%\", { replacements: { purpose: purpose.purposeName } })}\n aria-valuemin={0}\n aria-valuemax={100}\n aria-valuenow={Math.round(finishRate * 100)}\n className=\"mt-1 block h-1.5 overflow-hidden rounded-full bg-muted\"\n >\n <span className=\"block h-full rounded-full bg-[color:var(--series-1,var(--brand))]\" style={{ width: `${finishRate * 100}%` }} />\n </span>\n </>\n )}\n </TableCell>\n </TableRow>\n );\n })}\n </TableBody>\n </Table>\n )}\n </CardContent>\n </Card>\n );\n};\n","import { normalizeDddError } from \"@mgamadeus/ddd-web/contract\";\nimport { getUiLocale, m, useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { CopyButton } from \"@mgamadeus/ddd-admin-ui/list\";\nimport { StatusCallout } from \"@mgamadeus/ddd-admin-ui/page\";\nimport { Badge } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { SegmentedControl, type SegmentedControlOption } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { Skeleton } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { useMemo, useState } from \"react\";\nimport { Disclosure } from \"../blocks/Disclosure\";\nimport { formatJsonText } from \"../blocks/json-tree\";\nimport { JsonTree } from \"../blocks/JsonTree\";\nimport { ProportionBar, type ProportionBarSegment } from \"../blocks/ProportionBar\";\nimport { formatTokenFigure } from \"../blocks/token-figure\";\nimport { TokenFigure } from \"../blocks/TokenFigure\";\nimport type { AgentSkillCatalogApi } from \"./agent-skill-catalog-api\";\nimport { skillToolTokenPartFillClassNameOf } from \"./skill-catalog-colors\";\nimport { buildSkillToolParameterRows, buildSkillToolTokenParts, skillToolDescriptionOf, type SkillToolTokenPartKind } from \"./skill-catalog-tree\";\n\nexport interface ToolSchemaDrawerProps {\n /** `createAgentSkillCatalogApi(…)` of the host. */\n api: AgentSkillCatalogApi;\n /** The tool shown; `null` closes the drawer. */\n toolName: string | null;\n onClose: () => void;\n /** The skill the tool was opened from; default the skill the documentation names. */\n skillName?: string;\n /** The package the tool was opened from; default the package the documentation names. */\n packageName?: string;\n /** The other skills that expose the same tool. */\n otherSkillNames?: readonly string[];\n}\n\ntype SchemaView = \"tree\" | \"raw\";\n\nconst SCHEMA_VIEW_OPTIONS: readonly SegmentedControlOption<SchemaView>[] = [\n { value: \"tree\", label: m(\"Tree\", { context: \"payload-view\" }), context: \"payload-view\" },\n { value: \"raw\", label: m(\"Raw\", { context: \"payload-view\" }), context: \"payload-view\" },\n];\n\n/**\n * One tool of the skill catalog in a side sheet: the skill and package that expose it and what its wire schema costs\n * per turn, the tokens of the schema by part (description, every parameter, the structural envelope, shared\n * definitions) as a bar with a legend, the parameters as a table (name, type, required, tokens, description) and the\n * schema exactly as the model receives it (tree, raw, copy).\n */\nexport const ToolSchemaDrawer = ({ api, toolName, onClose, skillName, packageName, otherSkillNames = [] }: ToolSchemaDrawerProps) => {\n const { t } = useTranslate();\n const [schemaView, setSchemaView] = useState<SchemaView>(\"tree\");\n const query = api.useSkillToolDocumentationQuery({ toolName: toolName ?? \"\" }, { skip: toolName === null });\n // the data of the tool asked for now, never the previous tool's while the next one loads\n const documentation = toolName === null ? null : (query.currentData?.documentation ?? null);\n\n const tokenSegments = useMemo((): ProportionBarSegment[] => {\n const positions = new Map<SkillToolTokenPartKind, number>();\n const partLabels: Readonly<Record<SkillToolTokenPartKind, string>> = {\n description: t(\"Description\", { context: \"tool-schema-part\" }),\n parameter: \"\",\n envelope: t(\"Envelope\", { context: \"tool-schema-part\" }),\n definition: \"\",\n };\n return buildSkillToolTokenParts(documentation?.components).map((part) => {\n const position = positions.get(part.kind) ?? 0;\n positions.set(part.kind, position + 1);\n return {\n key: part.key,\n value: part.tokens,\n colorClassName: skillToolTokenPartFillClassNameOf(part.kind, position),\n label: part.kind === \"definition\" ? `$defs.${part.name}` : part.name !== \"\" ? part.name : partLabels[part.kind],\n valueText: formatTokenFigure(part.tokens, { locale: getUiLocale() }),\n };\n });\n }, [documentation, t]);\n const parameterRows = useMemo(() => buildSkillToolParameterRows(documentation?.openAiToolSchema, documentation?.components), [documentation]);\n const schemaText = useMemo(() => formatJsonText(documentation?.openAiToolSchema ?? null), [documentation]);\n const toolDescription = skillToolDescriptionOf(documentation?.openAiToolSchema);\n const shownSkillName = skillName ?? documentation?.skill ?? \"\";\n const shownPackageName = packageName ?? documentation?.package ?? \"\";\n\n return (\n <Sheet\n open={toolName !== null}\n onOpenChange={(isOpen) => {\n if (!isOpen) onClose();\n }}\n >\n <SheetContent side=\"right\" data-slot=\"tool-schema-drawer\" className=\"flex w-full flex-col gap-0 overflow-y-auto p-0 sm:max-w-3xl\">\n <SheetHeader className=\"border-b border-border px-6 py-4 pr-12\">\n <SheetTitle className=\"font-mono text-lg break-all\">{toolName ?? \"\"}</SheetTitle>\n <SheetDescription asChild>\n <div className=\"flex flex-wrap items-center gap-x-2 gap-y-1 text-sm text-muted-foreground\">\n {shownSkillName !== \"\" && (\n <span>\n {t(\"Skill\", { context: \"tool-schema\" })} <span className=\"font-mono font-medium text-foreground\">{shownSkillName}</span>\n </span>\n )}\n {shownPackageName !== \"\" && (\n <span>\n · {t(\"Package\", { context: \"tool-schema\" })} <span className=\"font-mono font-medium text-foreground\">{shownPackageName}</span>\n </span>\n )}\n {documentation && (\n <span>\n · <TokenFigure value={documentation.tokens ?? documentation.components?.total} className=\"font-medium text-foreground\" suffix={t(\"tokens per turn\")} />\n </span>\n )}\n </div>\n </SheetDescription>\n {otherSkillNames.length > 0 && (\n <p className=\"text-xs text-muted-foreground\">\n {t(\"Also exposed by\")}: <span className=\"font-mono\">{otherSkillNames.join(\", \")}</span>\n </p>\n )}\n </SheetHeader>\n\n <div className=\"min-w-0 space-y-6 px-6 py-5\">\n {query.isError ? (\n <StatusCallout size=\"compact\" tone=\"destructive\" title={t(\"The tool documentation could not be loaded.\")} description={normalizeDddError(query.error, \"\").message} />\n ) : documentation === null ? (\n <div className=\"space-y-3\">\n <Skeleton className=\"h-5 w-full rounded-md\" />\n <Skeleton className=\"h-4 w-2/3\" />\n <Skeleton className=\"h-40 w-full rounded-lg\" />\n </div>\n ) : (\n <>\n <section className=\"space-y-2\">\n <h3 className=\"text-sm font-semibold\">{t(\"Token breakdown\")}</h3>\n {tokenSegments.length > 0 ? (\n <ProportionBar aria-label={t(\"Tokens of the tool's wire schema by part\")} segments={tokenSegments} />\n ) : (\n <p className=\"text-sm text-muted-foreground\">{t(\"No token breakdown for this tool.\")}</p>\n )}\n </section>\n\n <section className=\"space-y-2\">\n <h3 className=\"text-sm font-semibold\">{t(\"Parameters\")}</h3>\n {parameterRows.length === 0 ? (\n <p className=\"text-sm text-muted-foreground\">{t(\"This tool takes no parameters.\")}</p>\n ) : (\n <div className=\"rounded-xl border bg-card\">\n <Table data-slot=\"tool-parameters\" className=\"table-fixed text-xs\">\n <TableHeader>\n <TableRow className=\"hover:bg-transparent\">\n <TableHead className=\"h-8 w-[28%] px-3 text-xs text-muted-foreground\">{t(\"Parameter\")}</TableHead>\n <TableHead className=\"h-8 w-[17%] px-3 text-xs text-muted-foreground\">{t(\"Type\", { context: \"tool-schema\" })}</TableHead>\n <TableHead className=\"h-8 w-[11%] px-3 text-right text-xs text-muted-foreground\">{t(\"≈ Tokens\")}</TableHead>\n <TableHead className=\"h-8 px-3 text-xs text-muted-foreground\">{t(\"Description\", { context: \"tool-schema-part\" })}</TableHead>\n </TableRow>\n </TableHeader>\n <TableBody>\n {parameterRows.map((parameter) => (\n <TableRow key={parameter.name} className=\"hover:bg-transparent\">\n <TableCell className=\"px-3 py-2 align-top font-mono font-medium break-all whitespace-normal\">\n {parameter.name}\n {parameter.isRequired && (\n <Badge variant=\"secondary\" className=\"ml-2 align-middle font-sans text-[10px]\">\n {t(\"required\", { context: \"tool-schema\" })}\n </Badge>\n )}\n </TableCell>\n <TableCell className=\"px-3 py-2 align-top font-mono break-words whitespace-normal text-muted-foreground\">{parameter.type}</TableCell>\n <TableCell className=\"px-3 py-2 text-right align-top tabular-nums\">\n {parameter.tokens === null ? \"—\" : formatTokenFigure(parameter.tokens, { isEstimate: false, locale: getUiLocale() })}\n </TableCell>\n <TableCell className=\"px-3 py-2 align-top break-words whitespace-pre-line text-muted-foreground\">{parameter.description}</TableCell>\n </TableRow>\n ))}\n </TableBody>\n </Table>\n </div>\n )}\n </section>\n\n {toolDescription !== \"\" && (\n <Disclosure title={t(\"Tool description\")} meta={<TokenFigure value={documentation.components?.description} className=\"text-xs\" />} className=\"rounded-xl border bg-card px-3 py-1.5\">\n <p className=\"pt-1 pb-2 text-sm break-words whitespace-pre-wrap text-muted-foreground\">{toolDescription}</p>\n </Disclosure>\n )}\n\n <Disclosure title={t(\"Show raw wire schema (what the model receives)\")} className=\"rounded-xl border bg-card px-3 py-1.5\">\n <div data-slot=\"tool-wire-schema\" className=\"space-y-2 pt-1 pb-2\">\n <div className=\"flex items-center gap-2\">\n <SegmentedControl<SchemaView> aria-label={m(\"Schema view\")} value={schemaView} onValueChange={setSchemaView} options={SCHEMA_VIEW_OPTIONS} />\n <CopyButton value={schemaText} label={m(\"Copy schema\")} className=\"ml-auto\" />\n </div>\n {schemaView === \"tree\" ? (\n <div className=\"max-h-[32rem] overflow-auto rounded-lg border bg-muted/40 p-3\">\n <JsonTree value={documentation.openAiToolSchema ?? null} defaultExpandDepth={3} aria-label={t(\"Wire schema of the tool\")} />\n </div>\n ) : (\n <pre className=\"max-h-[32rem] overflow-auto rounded-lg border bg-muted/40 p-3 font-mono text-xs leading-relaxed break-words whitespace-pre-wrap\">{schemaText}</pre>\n )}\n </div>\n </Disclosure>\n </>\n )}\n </div>\n </SheetContent>\n </Sheet>\n );\n};\n","import { normalizeDddError } from \"@mgamadeus/ddd-web/contract\";\nimport { NoteList } from \"@mgamadeus/ddd-admin-ui/data\";\nimport { formatUiNumber, m, useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { SearchField } from \"@mgamadeus/ddd-admin-ui/list\";\nimport { type UrlStateAdapter, useMemoryUrlState, useUrlListState } from \"@mgamadeus/ddd-admin-ui/logic\";\nimport { type EntityTab, EntityTabs, PageHeader, StatusCallout } from \"@mgamadeus/ddd-admin-ui/page\";\nimport { Badge } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { Button } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { Card, CardContent } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { cn } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { Skeleton } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { ChevronRight, ChevronsDownUp, ChevronsUpDown } from \"lucide-react\";\nimport { type ReactNode, useMemo, useState } from \"react\";\nimport { TokenFigure } from \"../blocks/TokenFigure\";\nimport { type AdminPeriod, resolveAdminPeriod } from \"../period/admin-period\";\nimport { AdminPeriodControl } from \"../period/AdminPeriodControl\";\nimport type { AgentSkillCatalogApi } from \"./agent-skill-catalog-api\";\nimport type { AgentSkillCatalogNamespaceGroup, AgentSkillCatalogSkillGroup, AgentSkillCatalogTotals } from \"./agent-skill-catalog-types\";\nimport { SharedBlocksPanel } from \"./SharedBlocksPanel\";\nimport { SKILL_INSTRUCTIONS_FILL_CLASS_NAME, SKILL_TOOL_DEFINITIONS_FILL_CLASS_NAME } from \"./skill-catalog-colors\";\nimport {\n buildSkillNamespaceSections,\n buildSkillPurposeSections,\n countFilteredSkills,\n type FilteredSkillTreeRow,\n filterSkillTreeRows,\n groupSkillTreeRowsByArea,\n findSkillToolLocations,\n skillLoadCountsByNameOf,\n} from \"./skill-catalog-tree\";\nimport { SKILL_ROW_GRID_CLASS_NAME, SKILL_ROW_WITH_LOADS_GRID_CLASS_NAME, SkillTreeRowView } from \"./SkillTreeRowView\";\nimport { describeSkillPurposeText } from \"./skill-purpose-texts\";\nimport { SkillLoadSourcesPanel } from \"./SkillLoadSourcesPanel\";\nimport { SkillPurposesPanel } from \"./SkillPurposesPanel\";\nimport { ToolSchemaDrawer } from \"./ToolSchemaDrawer\";\n\nexport interface AgentSkillCatalogScreenProps {\n /** `createAgentSkillCatalogApi(…)` of the host. */\n api: AgentSkillCatalogApi;\n /** The page title; default \"Agent skills\". Already translated. */\n title?: ReactNode;\n /** The line under the title; default says what the token counts are. Already translated. */\n description?: ReactNode;\n headerActions?: ReactNode;\n /** The tool whose drawer is open, when the host keeps it (the URL); with it pass `onSelectTool`. */\n selectedToolName?: string | null;\n /** Called with the tool to open, `null` to close. Without `selectedToolName` the screen keeps the tool itself. */\n onSelectTool?: (toolName: string | null) => void;\n /** Draws the markdown of a shared block; default the admin UI's markdown preview for texts of unknown origin. */\n renderMarkdown?: (source: string) => ReactNode;\n /**\n * Where the section (`section`: the skills or the purposes), the period of the usage figures (`period`, `from`,\n * `to`) and, unless `selectedToolName` is given, the open tool (`tool`) live: the host's URL adapter. Without one\n * they live in component state.\n */\n urlStateAdapter?: UrlStateAdapter;\n /**\n * The host's words for a namespace group it configured (name, short and long description: its config is English);\n * a field the host leaves out shows as the server sent it. Already translated.\n */\n describeSkillGroup?: (group: AgentSkillCatalogNamespaceGroup) => { name?: string; shortDescription?: string; description?: string } | null;\n /**\n * The host's description of a purpose it registered (its purpose files are English, written for the model), for the\n * purpose-bound skills and the purposes section; null or empty: the package's words for its own purposes, else the\n * server's. Already translated.\n */\n describeSkillPurpose?: (purposeName: string) => string | null | undefined;\n}\n\n/** The kinds of namespace group (`AISkillCatalogNamespaceGroup::kind`), as a badge. */\nconst SKILL_GROUP_KIND_LABELS: Readonly<Record<string, string>> = {\n agent: m(\"Agent\", { context: \"skill-group-kind\" }),\n common: m(\"Shared\", { context: \"skill-group-kind\" }),\n domain: m(\"Domain\", { context: \"skill-group-kind\" }),\n ungrouped: m(\"Ungrouped\", { context: \"skill-group-kind\" }),\n};\n\n/**\n * The words of a namespace group: the package's own for the group of the skills no configured prefix matches (the\n * server writes it in English), the host's for a group it configured, else what the server sent.\n */\nconst describeNamespaceGroup = (\n group: AgentSkillCatalogNamespaceGroup,\n t: ReturnType<typeof useTranslate>[\"t\"],\n describeSkillGroup: AgentSkillCatalogScreenProps[\"describeSkillGroup\"],\n): { name: string; shortDescription?: string; description?: string } => {\n if (group.isUngrouped) {\n return {\n name: t(\"Skills without a group\"),\n shortDescription: t(\"General skills whose name matches no configured namespace group.\"),\n description: t(\n \"Every general skill should belong to one of the configured namespace groups. A skill here has a namespace the configuration does not know yet: add its prefix to the right group, or rename the skill.\",\n ),\n };\n }\n const hostWords = describeSkillGroup?.(group) ?? null;\n return {\n name: hostWords?.name ?? group.name,\n shortDescription: hostWords?.shortDescription ?? group.shortDescription,\n description: hostWords?.description ?? group.description,\n };\n};\n\n/** The sections of the screen. */\nexport type AgentSkillCatalogSection = \"skills\" | \"purposes\";\n\n/** The URL keys of the screen: the section, the period of the usage figures and the open tool. */\nexport const AGENT_SKILL_CATALOG_URL_KEYS = [\"section\", \"period\", \"from\", \"to\", \"tool\"] as const;\n\nconst SECTION_TABS: readonly EntityTab[] = [\n { id: \"skills\", label: m(\"Skills\", { context: \"skill-catalog-section\" }), context: \"skill-catalog-section\" },\n { id: \"purposes\", label: m(\"Purposes\", { context: \"skill-catalog-section\" }), context: \"skill-catalog-section\" },\n];\n\n/** The tool the drawer shows and where it was opened from. */\ninterface OpenTool {\n toolName: string;\n skillName?: string;\n packageName?: string;\n}\n\ninterface TotalsRow {\n key: string;\n label: string;\n hint: string;\n rootSkillCount: number;\n subSkillCount: number;\n toolCount: number;\n catalogTokens: number;\n instructionTokens: number;\n sumOfSkillTotals: number;\n}\n\nconst SkillCatalogTotalsCard = ({ totals }: { totals: AgentSkillCatalogTotals }) => {\n const { t } = useTranslate();\n const baseRows: TotalsRow[] =\n (totals.baseSkillCount ?? 0) > 0\n ? [\n {\n key: \"base\",\n label: t(\"Base (always loaded)\", { context: \"skill-catalog\" }),\n hint: t(\"{count, plural, one {Pinned into every conversation from the start, without a catalog line: # skill.} other {Pinned into every conversation from the start, without a catalog line: # skills.}}\", { count: totals.baseSkillCount ?? 0 }),\n rootSkillCount: totals.baseSkillCount ?? 0,\n subSkillCount: 0,\n toolCount: totals.baseToolCount ?? 0,\n catalogTokens: 0,\n instructionTokens: totals.baseInstructionTokens ?? 0,\n sumOfSkillTotals: totals.baseSkillTokens ?? 0,\n },\n ]\n : [];\n const rows: TotalsRow[] = [\n ...baseRows,\n {\n key: \"general\",\n label: t(\"General\", { context: \"skill-catalog\" }),\n hint: t(\"What a new conversation can load.\"),\n rootSkillCount: totals.generalRootSkillCount ?? 0,\n subSkillCount: totals.generalSubSkillCount ?? 0,\n toolCount: totals.generalToolCount ?? 0,\n catalogTokens: totals.rootCatalogTokens ?? 0,\n instructionTokens: totals.generalInstructionTokens ?? 0,\n sumOfSkillTotals: totals.generalSumOfSkillTotals ?? 0,\n },\n {\n key: \"purposeBound\",\n label: t(\"Purpose-bound\", { context: \"skill-catalog\" }),\n hint: t(\"{count, plural, one {Only inside the runs of # purpose.} other {Only inside the runs of # purposes.}}\", { count: totals.purposeCount ?? 0 }),\n rootSkillCount: totals.purposeBoundRootSkillCount ?? 0,\n subSkillCount: totals.purposeBoundSubSkillCount ?? 0,\n toolCount: totals.purposeBoundToolCount ?? 0,\n catalogTokens: totals.purposeBoundCatalogTokens ?? 0,\n instructionTokens: totals.purposeBoundInstructionTokens ?? 0,\n sumOfSkillTotals: totals.purposeBoundSumOfSkillTotals ?? 0,\n },\n {\n key: \"all\",\n label: t(\"All\", { context: \"skill-catalog\" }),\n hint: t(\"%skills% skills, %tools% distinct tools (tool definitions counted once: %toolTokens% tokens).\", {\n replacements: {\n skills: formatUiNumber(totals.skillCount ?? 0),\n tools: formatUiNumber(totals.uniqueToolCount ?? 0),\n toolTokens: `≈${formatUiNumber(totals.uniqueToolDefTokens ?? 0)}`,\n },\n }),\n rootSkillCount: totals.rootSkillCount ?? 0,\n subSkillCount: totals.subSkillCount ?? 0,\n toolCount: totals.uniqueToolCount ?? 0,\n catalogTokens: (totals.rootCatalogTokens ?? 0) + (totals.purposeBoundCatalogTokens ?? 0),\n instructionTokens: totals.instructionTokens ?? 0,\n sumOfSkillTotals: totals.sumOfSkillTotals ?? 0,\n },\n ];\n return (\n <Card data-slot=\"skill-catalog-totals\" className=\"py-2\">\n <CardContent className=\"px-2\">\n <Table>\n <TableHeader>\n <TableRow className=\"hover:bg-transparent\">\n <TableHead className=\"px-4 text-xs text-muted-foreground\">{t(\"Scope\", { context: \"skill-catalog\" })}</TableHead>\n <TableHead className=\"px-4 text-right text-xs text-muted-foreground\">{t(\"Root skills\")}</TableHead>\n <TableHead className=\"px-4 text-right text-xs text-muted-foreground\">{t(\"Sub-skills\")}</TableHead>\n <TableHead className=\"px-4 text-right text-xs text-muted-foreground\">{t(\"Tools\", { context: \"skill-catalog\" })}</TableHead>\n <TableHead className=\"px-4 text-right text-xs text-muted-foreground\">{t(\"Catalog block\")}</TableHead>\n <TableHead className=\"px-4 text-right text-xs text-muted-foreground\">{t(\"Instructions\", { context: \"skill-catalog\" })}</TableHead>\n <TableHead className=\"px-4 text-right text-xs text-muted-foreground\">{t(\"Σ if all loaded\")}</TableHead>\n </TableRow>\n </TableHeader>\n <TableBody>\n {rows.map((row) => (\n <TableRow key={row.key} data-totals-row={row.key} className={cn(\"hover:bg-transparent\", row.key === \"all\" && \"font-medium\")}>\n <TableCell className=\"px-4 py-2.5 whitespace-normal\">\n <div className=\"font-medium\">{row.label}</div>\n <div className=\"text-xs font-normal text-muted-foreground\">{row.hint}</div>\n </TableCell>\n <TableCell className=\"px-4 text-right tabular-nums\">{formatUiNumber(row.rootSkillCount)}</TableCell>\n <TableCell className=\"px-4 text-right tabular-nums\">{formatUiNumber(row.subSkillCount)}</TableCell>\n <TableCell className=\"px-4 text-right tabular-nums\">{formatUiNumber(row.toolCount)}</TableCell>\n <TableCell className=\"px-4 text-right\">\n <TokenFigure value={row.catalogTokens} />\n </TableCell>\n <TableCell className=\"px-4 text-right\">\n <TokenFigure value={row.instructionTokens} />\n </TableCell>\n <TableCell className=\"px-4 text-right\">\n <TokenFigure value={row.sumOfSkillTotals} />\n </TableCell>\n </TableRow>\n ))}\n </TableBody>\n </Table>\n </CardContent>\n </Card>\n );\n};\n\n/** The figures line of a group: roots and sub-skills, tools, catalog lines, instructions, tool definitions, the sum. */\nconst SkillGroupFigures = ({ group }: { group: AgentSkillCatalogSkillGroup }) => {\n const { t } = useTranslate();\n return (\n <span data-slot=\"skill-group-figures\" className=\"flex flex-wrap gap-x-2 gap-y-0.5 text-xs text-muted-foreground\">\n <span>\n {t(\"{count, plural, one {# root} other {# roots}}\", { count: group.rootSkillCount ?? 0 })} +{\" \"}\n {t(\"{count, plural, one {# sub-skill} other {# sub-skills}}\", { count: group.subSkillCount ?? 0 })}\n </span>\n <span>· {t(\"{count, plural, one {# tool} other {# tools}}\", { count: group.toolCount ?? 0 })}</span>\n <span>\n · {t(\"Catalog lines\", { context: \"skill-catalog\" })} <TokenFigure value={group.catalogTokens} />\n </span>\n <span>\n · {t(\"Instructions\", { context: \"skill-catalog\" })} <TokenFigure value={group.instructionTokens} />\n </span>\n <span>\n · {t(\"Tool definitions, each counted once\", { context: \"skill-catalog\" })} <TokenFigure value={group.uniqueToolDefTokens} />\n </span>\n <span>\n · {t(\"Σ if all loaded\")} <TokenFigure value={group.sumOfSkillTotals} className=\"font-medium text-foreground\" />\n </span>\n </span>\n );\n};\n\ninterface SkillGroupCardProps {\n sectionKey: string;\n heading: ReactNode;\n /** One line beside the heading. */\n summary?: ReactNode;\n /** Shown above the skills once the group is open. */\n details?: ReactNode;\n group: AgentSkillCatalogSkillGroup;\n rows: FilteredSkillTreeRow[];\n isOpen: boolean;\n onToggle: () => void;\n openSkillKeys: ReadonlySet<string>;\n onToggleSkill: (skillKey: string) => void;\n onSelectTool: (toolName: string, skillName: string, packageName: string) => void;\n selectedToolName: string | null;\n /** The loads of the period by skill name; `null` = no loads column. */\n loadCountBySkillName: ReadonlyMap<string, number> | null;\n /** Set: the rows are listed by area under a subheading each, the areas taken after this group name as a prefix. */\n areaGroupName?: string;\n}\n\nconst SkillGroupCard = ({ sectionKey, heading, summary, details, group, rows, isOpen, onToggle, openSkillKeys, onToggleSkill, onSelectTool, selectedToolName, loadCountBySkillName, areaGroupName }: SkillGroupCardProps) => {\n const { t } = useTranslate();\n const areaSections = useMemo(() => (areaGroupName === undefined ? null : groupSkillTreeRowsByArea(rows, areaGroupName)), [rows, areaGroupName]);\n const renderRow = (row: FilteredSkillTreeRow) => (\n <SkillTreeRowView\n key={row.skill.skill.name}\n row={row}\n sectionKey={sectionKey}\n openSkillKeys={openSkillKeys}\n onToggleSkill={onToggleSkill}\n onSelectTool={onSelectTool}\n selectedToolName={selectedToolName}\n loadCountBySkillName={loadCountBySkillName}\n />\n );\n const contentId = `skill-group-${sectionKey.replace(/[^A-Za-z0-9_-]/g, \"-\")}`;\n return (\n <Card data-slot=\"skill-group\" data-group={sectionKey} className=\"gap-0 py-0\">\n <button\n type=\"button\"\n aria-expanded={isOpen}\n aria-controls={isOpen ? contentId : undefined}\n onClick={onToggle}\n className=\"flex w-full items-start gap-3 rounded-[inherit] px-4 py-3 text-left outline-none hover:bg-tint focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset\"\n >\n <ChevronRight aria-hidden className={cn(\"mt-0.5 size-4 shrink-0 text-muted-foreground transition-transform\", isOpen && \"rotate-90\")} />\n <span className=\"min-w-0 flex-1 space-y-1\">\n <span className=\"flex flex-wrap items-center gap-x-2 gap-y-1\">\n {heading}\n {summary !== undefined && summary !== null && <span className=\"min-w-0 text-sm text-muted-foreground\">{summary}</span>}\n </span>\n <SkillGroupFigures group={group} />\n </span>\n </button>\n {isOpen && (\n <div id={contentId} className=\"border-t border-border px-2 pt-3 pb-2\">\n {details !== undefined && details !== null && <div className=\"mb-3 px-2 text-sm text-muted-foreground\">{details}</div>}\n {rows.length === 0 ? (\n <p className=\"px-2 pb-2 text-sm text-muted-foreground\">{t(\"No skill in this group.\")}</p>\n ) : (\n <>\n <div\n aria-hidden\n className={cn(loadCountBySkillName !== null ? SKILL_ROW_WITH_LOADS_GRID_CLASS_NAME : SKILL_ROW_GRID_CLASS_NAME, \"px-2 pb-1 text-[11px] font-medium tracking-wide text-muted-foreground uppercase\")}\n >\n <span>{t(\"Skill\", { context: \"tool-schema\" })}</span>\n <span className=\"hidden text-right md:block\">{t(\"Catalog line\")}</span>\n <span className=\"text-right\">{t(\"Total\", { context: \"skill-catalog\" })}</span>\n <span className=\"hidden md:block\">{t(\"Split\", { context: \"skill-catalog\" })}</span>\n <span className=\"text-right\">{t(\"Tools\", { context: \"skill-catalog\" })}</span>\n {loadCountBySkillName !== null && <span className=\"hidden text-right md:block\">{t(\"Loads\", { context: \"skill-catalog\" })}</span>}\n </div>\n {areaSections === null ? (\n <ul className=\"divide-y divide-border\">{rows.map(renderRow)}</ul>\n ) : (\n areaSections.map((areaSection) => (\n <div key={areaSection.area} data-slot=\"skill-area\" data-area={areaSection.area} className=\"pt-2 first:pt-0\">\n <h3 className=\"border-b border-border px-2 pb-1 text-xs font-semibold text-muted-foreground\">{areaSection.area}</h3>\n <ul className=\"divide-y divide-border\">{areaSection.rows.map(renderRow)}</ul>\n </div>\n ))\n )}\n </>\n )}\n </div>\n )}\n </Card>\n );\n};\n\nconst SkillNameChips = ({ names }: { names: readonly string[] }) => (\n <span className=\"inline-flex flex-wrap gap-1 align-middle\">\n {names.map((name) => (\n <Badge key={name} variant=\"outline\" className=\"font-mono text-[11px]\">\n {name}\n </Badge>\n ))}\n </span>\n);\n\nconst toggleKey = (keys: ReadonlySet<string>, key: string): Set<string> => {\n const next = new Set(keys);\n if (next.has(key)) next.delete(key);\n else next.add(key);\n return next;\n};\n\n/**\n * The agent's skill catalog with what each part costs per turn: the totals (general, purpose-bound, all), the general\n * skills by namespace group, the purpose-bound skills by purpose, every skill with its packages and tools, the tool's\n * wire schema in a side sheet, and the blocks the system message carries once. Token counts are estimates of one\n * tokenizer and marked `≈`. The search narrows skills, packages and tools by name and opens what it finds.\n */\nexport const AgentSkillCatalogScreen = ({\n api,\n title,\n description,\n headerActions,\n selectedToolName,\n onSelectTool,\n renderMarkdown,\n urlStateAdapter,\n describeSkillGroup,\n describeSkillPurpose,\n}: AgentSkillCatalogScreenProps) => {\n const { t } = useTranslate();\n const memory = useMemoryUrlState();\n const urlState = useUrlListState(AGENT_SKILL_CATALOG_URL_KEYS, { adapter: urlStateAdapter ?? memory.urlStateAdapter, debounceMs: 0, pushKeys: [\"section\"] });\n const section: AgentSkillCatalogSection = urlState.values.section === \"purposes\" ? \"purposes\" : \"skills\";\n const period: AdminPeriod = useMemo(\n () => resolveAdminPeriod({ preset: urlState.values.period, from: urlState.values.from, to: urlState.values.to }, \"14d\"),\n [urlState.values.period, urlState.values.from, urlState.values.to],\n );\n const catalogQuery = api.useSkillCatalogQuery();\n const loadCountsQuery = api.useSkillLoadCountsQuery({ from: period.from, to: period.to });\n const loadCountsResponse = loadCountsQuery.data ?? null;\n // the loads column shows once the counts arrived and the database can count them\n const loadCountBySkillName = useMemo(\n () => (loadCountsResponse !== null && loadCountsResponse.isLoadCountDataAvailable !== false ? skillLoadCountsByNameOf(loadCountsResponse.loadCounts) : null),\n [loadCountsResponse],\n );\n const catalog = catalogQuery.data?.catalog ?? null;\n const [searchText, setSearchText] = useState(\"\");\n const [openSectionKeys, setOpenSectionKeys] = useState<ReadonlySet<string>>(new Set());\n const [openSkillKeys, setOpenSkillKeys] = useState<ReadonlySet<string>>(new Set());\n const [ownOpenTool, setOwnOpenTool] = useState<OpenTool | null>(null);\n\n const namespaceSections = useMemo(() => buildSkillNamespaceSections(catalog), [catalog]);\n const purposeSections = useMemo(() => buildSkillPurposeSections(catalog), [catalog]);\n const filteredNamespaceSections = useMemo(\n () => namespaceSections.map((section) => ({ ...section, filteredRows: filterSkillTreeRows(section.rows, searchText) })),\n [namespaceSections, searchText],\n );\n const filteredPurposeSections = useMemo(\n () => purposeSections.map((section) => ({ ...section, filteredRows: filterSkillTreeRows(section.rows, searchText) })),\n [purposeSections, searchText],\n );\n const isSearching = searchText.trim() !== \"\";\n const shownNamespaceSections = isSearching ? filteredNamespaceSections.filter((section) => section.filteredRows.length > 0) : filteredNamespaceSections;\n const shownPurposeSections = isSearching ? filteredPurposeSections.filter((section) => section.filteredRows.length > 0) : filteredPurposeSections;\n const matchingSkillCount = [...shownNamespaceSections, ...shownPurposeSections].reduce((count, section) => count + countFilteredSkills(section.filteredRows), 0);\n const allSectionKeys = [...namespaceSections, ...purposeSections].map((section) => section.key);\n const areAllSectionsOpen = allSectionKeys.length > 0 && allSectionKeys.every((key) => openSectionKeys.has(key));\n\n const isToolControlled = selectedToolName !== undefined;\n const openToolName = isToolControlled ? selectedToolName : urlState.values.tool !== \"\" ? urlState.values.tool : null;\n const openToolOrigin = ownOpenTool !== null && ownOpenTool.toolName === openToolName ? ownOpenTool : null;\n const openToolLocations = useMemo(() => (openToolName ? findSkillToolLocations(catalog, openToolName) : []), [catalog, openToolName]);\n const openToolSkillName = openToolOrigin?.skillName ?? openToolLocations[0]?.skillName;\n const openToolPackageName = openToolOrigin?.packageName ?? openToolLocations[0]?.packageName;\n const selectTool = (toolName: string, skillName: string, packageName: string) => {\n setOwnOpenTool({ toolName, skillName, packageName });\n if (!isToolControlled) urlState.setValue(\"tool\", toolName);\n onSelectTool?.(toolName);\n };\n const closeTool = () => {\n setOwnOpenTool(null);\n if (!isToolControlled) urlState.setValue(\"tool\", \"\");\n onSelectTool?.(null);\n };\n\n const header = (\n <PageHeader\n title={title ?? t(\"Agent skills\")}\n description={\n description ??\n t(\"What every skill adds to the context of a turn, by skill, package and tool. Token counts come from one tokenizer: exact for its model family, an estimate (≈) for the others.\")\n }\n actions={headerActions}\n />\n );\n const sectionBar = (\n <div data-slot=\"skill-catalog-sections\" className=\"flex flex-wrap items-center justify-between gap-x-4 gap-y-3\">\n <EntityTabs\n aria-label={t(\"Sections of the skill catalog\")}\n tabs={SECTION_TABS}\n activeId={section}\n onSelect={(id) => urlState.setValues({ section: id === \"purposes\" ? \"purposes\" : \"\", ...(isToolControlled ? {} : { tool: \"\" }) })}\n variant=\"segmented\"\n />\n <span className=\"flex flex-wrap items-center gap-2 text-sm text-muted-foreground\">\n {section === \"skills\" ? t(\"Loads counted over\") : t(\"Runs counted over\")}\n <AdminPeriodControl period={period} onChange={(next) => urlState.setValues({ period: next.preset, from: next.from, to: next.to })} />\n </span>\n </div>\n );\n\n if (section === \"purposes\") {\n return (\n <div data-slot=\"agent-skill-catalog-screen\" data-section=\"purposes\" className=\"space-y-4\">\n {header}\n {sectionBar}\n <SkillPurposesPanel api={api} period={period} describeSkillPurpose={describeSkillPurpose} />\n </div>\n );\n }\n\n if (catalogQuery.isLoading) {\n return (\n <div data-slot=\"agent-skill-catalog-screen\" className=\"space-y-4\">\n {header}\n {sectionBar}\n <Skeleton className=\"h-36 w-full rounded-2xl\" />\n <Skeleton className=\"h-20 w-full rounded-2xl\" />\n <Skeleton className=\"h-20 w-full rounded-2xl\" />\n </div>\n );\n }\n if (catalogQuery.isError || catalog === null) {\n return (\n <div data-slot=\"agent-skill-catalog-screen\" className=\"space-y-4\">\n {header}\n {sectionBar}\n <StatusCallout\n tone=\"destructive\"\n title={t(\"The skill catalog could not be loaded.\")}\n description={catalogQuery.isError ? normalizeDddError(catalogQuery.error, \"\").message : undefined}\n />\n </div>\n );\n }\n\n const groupCardProps = {\n openSkillKeys,\n onToggleSkill: (skillKey: string) => setOpenSkillKeys((keys) => toggleKey(keys, skillKey)),\n onSelectTool: selectTool,\n selectedToolName: openToolName,\n loadCountBySkillName,\n };\n const loadNotes = [\n ...(loadCountsResponse?.isLoadCountDataAvailable === false ? [{ id: \"loadsUnavailable\", tone: \"warning\" as const, text: t(\"Loads cannot be counted on this database: the generated tool columns of the message table are missing.\") }] : []),\n ...(loadCountBySkillName !== null\n ? [\n {\n id: \"loadsMeaning\",\n text: t(\"Loads are the calls of the skill-loading tool the model made in the period (%calls% counted). A skill a purpose or a decision preloads is not among them.\", {\n replacements: { calls: formatUiNumber(loadCountsResponse?.loadCounts?.countedCallCount ?? 0) },\n }),\n },\n ]\n : []),\n ...(loadCountsResponse?.loadCounts?.isTruncated === true ? [{ id: \"loadsTruncated\", tone: \"warning\" as const, text: t(\"The period holds more calls than one read counts: the newest calls were counted.\") }] : []),\n ];\n return (\n <div data-slot=\"agent-skill-catalog-screen\" data-section=\"skills\" className=\"space-y-6\">\n {header}\n <div className=\"space-y-2\">\n {sectionBar}\n <NoteList notes={loadNotes} />\n </div>\n {catalog.totals && <SkillCatalogTotalsCard totals={catalog.totals} />}\n <SkillLoadSourcesPanel api={api} period={period} />\n\n <div className=\"flex flex-wrap items-center gap-3\">\n <SearchField\n value={searchText}\n onChange={setSearchText}\n clearable\n placeholder={t(\"Search skills, packages and tools\")}\n aria-label={t(\"Search skills, packages and tools\")}\n className=\"w-full sm:w-80\"\n />\n {isSearching && (\n <span data-slot=\"skill-search-count\" className=\"text-sm text-muted-foreground\" aria-live=\"polite\">\n {t(\"{count, plural, one {# skill matches} other {# skills match}}\", { count: matchingSkillCount })}\n </span>\n )}\n <span className=\"ml-auto flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted-foreground\">\n <span className=\"inline-flex items-center gap-1.5\">\n <span aria-hidden className={cn(\"size-2.5 rounded-[3px]\", SKILL_INSTRUCTIONS_FILL_CLASS_NAME)} />\n {t(\"Instructions\", { context: \"skill-catalog\" })}\n </span>\n <span className=\"inline-flex items-center gap-1.5\">\n <span aria-hidden className={cn(\"size-2.5 rounded-[3px]\", SKILL_TOOL_DEFINITIONS_FILL_CLASS_NAME)} />\n {t(\"Tool definitions\")}\n </span>\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n data-slot=\"skill-groups-toggle-all\"\n onClick={() => setOpenSectionKeys(areAllSectionsOpen ? new Set() : new Set(allSectionKeys))}\n >\n {areAllSectionsOpen ? <ChevronsDownUp aria-hidden /> : <ChevronsUpDown aria-hidden />}\n {areAllSectionsOpen ? t(\"Collapse all groups\") : t(\"Expand all groups\")}\n </Button>\n </span>\n </div>\n\n <section data-slot=\"skill-general-section\" className=\"space-y-3\">\n <div>\n <h2 className=\"text-lg font-semibold\">{t(\"General skills\")}</h2>\n <p className=\"text-sm text-muted-foreground\">{t(\"Offered in an open conversation, grouped by namespace. A sub-skill is listed under its root.\")}</p>\n </div>\n {shownNamespaceSections.length === 0 ? (\n <p className=\"text-sm text-muted-foreground\">{isSearching ? t(\"No general skill matches the search.\") : t(\"No general skills.\")}</p>\n ) : (\n shownNamespaceSections.map((section) => {\n const words = describeNamespaceGroup(section.group, t, describeSkillGroup);\n const kind = section.group.kind ?? \"\";\n const kindLabel = SKILL_GROUP_KIND_LABELS[kind];\n return (\n <SkillGroupCard\n key={section.key}\n sectionKey={section.key}\n heading={\n <>\n <span className=\"text-base font-semibold\">{words.name !== \"\" ? words.name : t(\"All general skills\")}</span>\n {kind !== \"\" && (\n <Badge variant={section.group.isUngrouped ? \"warning\" : \"secondary\"} className=\"text-[10px]\">\n {kindLabel !== undefined ? t(kindLabel, { context: \"skill-group-kind\" }) : kind}\n </Badge>\n )}\n </>\n }\n summary={words.shortDescription}\n details={words.description}\n group={section.group}\n rows={section.filteredRows}\n isOpen={isSearching || openSectionKeys.has(section.key)}\n onToggle={() => setOpenSectionKeys((keys) => toggleKey(keys, section.key))}\n areaGroupName={section.group.name}\n {...groupCardProps}\n />\n );\n })\n )}\n </section>\n\n <section data-slot=\"skill-purpose-section\" className=\"space-y-3\">\n <div>\n <h2 className=\"text-lg font-semibold\">{t(\"Purpose-bound skills\")}</h2>\n <p className=\"text-sm text-muted-foreground\">\n {t(\"Offered only inside a conversation with one of these purposes, never in an open conversation, so they are not among the general skills.\")}\n </p>\n </div>\n {shownPurposeSections.length === 0 ? (\n <p className=\"text-sm text-muted-foreground\">{isSearching ? t(\"No purpose-bound skill matches the search.\") : t(\"No purpose-bound skills.\")}</p>\n ) : (\n shownPurposeSections.map((section) => {\n const preloadSkillNames = section.group.preloadSkillNames ?? [];\n const allowedLoadSkillNames = section.group.allowedLoadSkillNames ?? [];\n return (\n <SkillGroupCard\n key={section.key}\n sectionKey={section.key}\n heading={\n <>\n <span className=\"font-mono text-base font-semibold\">{section.group.purposeName}</span>\n {section.group.isDefined === false && <Badge variant=\"destructive\">{t(\"no purpose definition\")}</Badge>}\n </>\n }\n summary={describeSkillPurposeText(section.group.purposeName, section.group.description, t, describeSkillPurpose)}\n details={\n <dl className=\"grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1.5\">\n <dt>{t(\"Preloads\")}</dt>\n <dd>{preloadSkillNames.length > 0 ? <SkillNameChips names={preloadSkillNames} /> : t(\"nothing\")}</dd>\n <dt>{t(\"May load\")}</dt>\n <dd>{allowedLoadSkillNames.length > 0 ? <SkillNameChips names={allowedLoadSkillNames} /> : t(\"every skill the account is entitled to\")}</dd>\n </dl>\n }\n group={section.group}\n rows={section.filteredRows}\n isOpen={isSearching || openSectionKeys.has(section.key)}\n onToggle={() => setOpenSectionKeys((keys) => toggleKey(keys, section.key))}\n {...groupCardProps}\n />\n );\n })\n )}\n </section>\n\n <SharedBlocksPanel api={api} renderMarkdown={renderMarkdown} />\n\n <ToolSchemaDrawer\n api={api}\n toolName={openToolName ?? null}\n onClose={closeTool}\n skillName={openToolSkillName}\n packageName={openToolPackageName}\n otherSkillNames={[...new Set(openToolLocations.map((location) => location.skillName))].filter((name) => name !== openToolSkillName)}\n />\n </div>\n );\n};\n","import { cn, type PageLinkComponent, useLinkComponent } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport type { ReactNode } from \"react\";\n\nexport interface AdminHrefLinkProps {\n /** Where the link goes in the host; `null` / absent: the content is drawn as plain text. */\n href?: string | null;\n /** The host's router link; default the provider's, else a plain `<a>`. */\n linkComponent?: PageLinkComponent;\n children: ReactNode;\n className?: string;\n \"aria-label\"?: string;\n}\n\n/** A link into a host screen (a conversation, an account, a space), or its content as text when the host names no route. */\nexport const AdminHrefLink = ({ href, linkComponent, children, className, \"aria-label\": ariaLabel }: AdminHrefLinkProps) => {\n const Link = useLinkComponent(linkComponent);\n if (href === null || href === undefined || href === \"\") return <span className={className}>{children}</span>;\n return (\n <Link href={href} aria-label={ariaLabel} className={cn(\"rounded-sm text-primary-emphasis underline-offset-2 outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring\", className)}>\n {children}\n </Link>\n );\n};\n","import {\n type ApiMutationHook,\n type ApiQueryHook,\n type InjectableBaseApi,\n type InjectedEndpointDefinition,\n type InjectedRequest,\n injectEndpointsOnce,\n staticMutationHook,\n type StaticQueryFailure,\n staticQueryHook,\n toQueryString,\n trimApiPrefix,\n} from \"@mgamadeus/ddd-admin-ui/logic/pure\";\nimport type {\n AgentBudgetsResponse,\n AgentControlPanelSpacesArg,\n AgentControlPanelSpacesResponse,\n AgentControlPanelStatisticsArg,\n AgentControlPanelStatisticsResponse,\n AgentRuntimeSettingsResponse,\n AgentRuntimeSettingsValues,\n AgentToolResponseSamplesArg,\n AgentToolResponseSamplesResponse,\n} from \"./agent-control-panel-types\";\n\n/** The cache tag type of the control panel reads (ids `STATISTICS`, `TOOL_SAMPLES`, `SETTINGS`, `SPACES`, `BUDGETS`). */\nexport const AGENT_CONTROL_PANEL_TAG = \"AdminUiAgentControlPanel\";\n\n/** The hooks `createAgentControlPanelApi` returns; `AgentControlPanelScreen` takes them as `api`. */\nexport interface AgentControlPanelApi {\n /** `GET /statistics?from&to&granularity&excludeTestUsers&topConversationsOrderBy`. */\n useControlPanelStatisticsQuery: ApiQueryHook<AgentControlPanelStatisticsArg, AgentControlPanelStatisticsResponse>;\n /** `GET /statistics/toolResponseSamples?toolName&from&to&limit`: the largest responses of one tool. */\n useToolResponseSamplesQuery: ApiQueryHook<AgentToolResponseSamplesArg, AgentToolResponseSamplesResponse>;\n /** `GET /settings`: the stored runtime settings, the defaults, what may be chosen, the newest changes. */\n useRuntimeSettingsQuery: ApiQueryHook<void, AgentRuntimeSettingsResponse>;\n /** `POST /settings`: stores all six settings as sent (null = back to the default); answers like the read. */\n useUpdateRuntimeSettingsMutation: ApiMutationHook<AgentRuntimeSettingsValues, AgentRuntimeSettingsResponse>;\n /** `GET /spaces?from&to&limit`: the agent spaces conversations were started for. */\n useControlPanelSpacesQuery: ApiQueryHook<AgentControlPanelSpacesArg, AgentControlPanelSpacesResponse>;\n /** `GET /budgets`: the budget meters of the current period. */\n useBudgetsQuery: ApiQueryHook<void, AgentBudgetsResponse>;\n}\n\nexport interface CreateAgentControlPanelApiOptions {\n /** The host's RTK Query api (`createApi` with the React hooks module). */\n baseApi: InjectableBaseApi;\n /** Where the host mounts `AdminAgentControlPanelTrait`, without a trailing slash (`/api/admin/ai/agentControlPanel`). */\n apiPrefix: string;\n}\n\n/** The six settings as the store route takes them: every one named, an unset one as null. */\nexport const buildAgentRuntimeSettingsBody = (values: AgentRuntimeSettingsValues): Required<AgentRuntimeSettingsValues> => ({\n defaultModelName: values.defaultModelName ?? null,\n defaultReasoningEffort: values.defaultReasoningEffort ?? null,\n reasoningEffortCeiling: values.reasoningEffortCeiling ?? null,\n compactionTriggerTokens: values.compactionTriggerTokens ?? null,\n storeRequestSnapshot: values.storeRequestSnapshot ?? null,\n decisionModelEnabled: values.decisionModelEnabled ?? null,\n});\n\n/** The request of every operation, on `apiPrefix`. Pure: no RTK runtime. */\nexport const buildAgentControlPanelRequests = (apiPrefix: string) => {\n const prefix = trimApiPrefix(apiPrefix);\n return {\n statistics: (arg: AgentControlPanelStatisticsArg = {}): InjectedRequest => ({\n url: `${prefix}/statistics${toQueryString({\n from: arg.from,\n to: arg.to,\n granularity: arg.granularity,\n excludeTestUsers: arg.excludeTestUsers === true ? 1 : undefined,\n topConversationsOrderBy: arg.topConversationsOrderBy,\n })}`,\n }),\n toolResponseSamples: (arg: AgentToolResponseSamplesArg): InjectedRequest => ({\n url: `${prefix}/statistics/toolResponseSamples${toQueryString({ toolName: arg.toolName, from: arg.from, to: arg.to, limit: arg.limit })}`,\n }),\n settings: (): InjectedRequest => ({ url: `${prefix}/settings` }),\n updateSettings: (values: AgentRuntimeSettingsValues): InjectedRequest => ({ url: `${prefix}/settings`, method: \"POST\", body: buildAgentRuntimeSettingsBody(values) }),\n spaces: (arg: AgentControlPanelSpacesArg = {}): InjectedRequest => ({ url: `${prefix}/spaces${toQueryString({ from: arg.from, to: arg.to, limit: arg.limit })}` }),\n budgets: (): InjectedRequest => ({ url: `${prefix}/budgets` }),\n };\n};\n\nconst STATISTICS = { type: AGENT_CONTROL_PANEL_TAG, id: \"STATISTICS\" } as const;\nconst TOOL_SAMPLES = { type: AGENT_CONTROL_PANEL_TAG, id: \"TOOL_SAMPLES\" } as const;\nconst SETTINGS = { type: AGENT_CONTROL_PANEL_TAG, id: \"SETTINGS\" } as const;\nconst SPACES = { type: AGENT_CONTROL_PANEL_TAG, id: \"SPACES\" } as const;\nconst BUDGETS = { type: AGENT_CONTROL_PANEL_TAG, id: \"BUDGETS\" } as const;\n\n/** The operations as injected. */\nexport const agentControlPanelEndpointDefinitions = (apiPrefix: string) => {\n const requests = buildAgentControlPanelRequests(apiPrefix);\n return {\n adminUiAgentControlPanelStatistics: { kind: \"query\", request: requests.statistics, providesTags: [STATISTICS] },\n adminUiAgentControlPanelToolResponseSamples: { kind: \"query\", request: requests.toolResponseSamples, providesTags: [TOOL_SAMPLES] },\n adminUiAgentControlPanelSettings: { kind: \"query\", request: requests.settings, providesTags: [SETTINGS] },\n adminUiAgentControlPanelUpdateSettings: { kind: \"mutation\", request: requests.updateSettings, invalidatesTags: [SETTINGS] },\n adminUiAgentControlPanelSpaces: { kind: \"query\", request: requests.spaces, providesTags: [SPACES] },\n adminUiAgentControlPanelBudgets: { kind: \"query\", request: requests.budgets, providesTags: [BUDGETS] },\n } as const satisfies Record<string, InjectedEndpointDefinition<never>>;\n};\n\n/**\n * Injects the control panel operations into the host's RTK Query api and returns their hooks. Call it once at module\n * scope: `export const agentControlPanelApi = createAgentControlPanelApi({ baseApi, apiPrefix: \"/api/admin/ai/agentControlPanel\" });`\n */\nexport const createAgentControlPanelApi = ({ baseApi, apiPrefix }: CreateAgentControlPanelApiOptions): AgentControlPanelApi =>\n injectEndpointsOnce(\n baseApi,\n `agentControlPanel:${trimApiPrefix(apiPrefix)}`,\n [AGENT_CONTROL_PANEL_TAG],\n agentControlPanelEndpointDefinitions(apiPrefix),\n (hookOf) => ({\n useControlPanelStatisticsQuery: hookOf(\"adminUiAgentControlPanelStatistics\") as AgentControlPanelApi[\"useControlPanelStatisticsQuery\"],\n useToolResponseSamplesQuery: hookOf(\"adminUiAgentControlPanelToolResponseSamples\") as AgentControlPanelApi[\"useToolResponseSamplesQuery\"],\n useRuntimeSettingsQuery: hookOf(\"adminUiAgentControlPanelSettings\") as AgentControlPanelApi[\"useRuntimeSettingsQuery\"],\n useUpdateRuntimeSettingsMutation: hookOf(\"adminUiAgentControlPanelUpdateSettings\") as AgentControlPanelApi[\"useUpdateRuntimeSettingsMutation\"],\n useControlPanelSpacesQuery: hookOf(\"adminUiAgentControlPanelSpaces\") as AgentControlPanelApi[\"useControlPanelSpacesQuery\"],\n useBudgetsQuery: hookOf(\"adminUiAgentControlPanelBudgets\") as AgentControlPanelApi[\"useBudgetsQuery\"],\n }),\n );\n\n/** Fixed answers of a `createStaticAgentControlPanelApi`; a query without one stays loading. */\nexport interface StaticAgentControlPanelData {\n statistics?: (arg: AgentControlPanelStatisticsArg) => AgentControlPanelStatisticsResponse | StaticQueryFailure | undefined;\n toolResponseSamples?: (arg: AgentToolResponseSamplesArg) => AgentToolResponseSamplesResponse | StaticQueryFailure | undefined;\n settings?: () => AgentRuntimeSettingsResponse | StaticQueryFailure | undefined;\n /** The answer of a store; default: the read's answer with the sent values as `settings`. */\n updateSettings?: (values: AgentRuntimeSettingsValues) => AgentRuntimeSettingsResponse | Promise<AgentRuntimeSettingsResponse>;\n spaces?: (arg: AgentControlPanelSpacesArg) => AgentControlPanelSpacesResponse | StaticQueryFailure | undefined;\n budgets?: () => AgentBudgetsResponse | StaticQueryFailure | undefined;\n}\n\n/** An `AgentControlPanelApi` answering fixed payloads, without a store or a request (previews, tests, reviews). */\nexport const createStaticAgentControlPanelApi = (data: StaticAgentControlPanelData): AgentControlPanelApi => ({\n useControlPanelStatisticsQuery: staticQueryHook((arg) => data.statistics?.(arg ?? {})),\n useToolResponseSamplesQuery: staticQueryHook((arg) => data.toolResponseSamples?.(arg)),\n useRuntimeSettingsQuery: staticQueryHook(() => data.settings?.()),\n useUpdateRuntimeSettingsMutation: staticMutationHook((values) => data.updateSettings?.(values) ?? { settings: buildAgentRuntimeSettingsBody(values) }),\n useControlPanelSpacesQuery: staticQueryHook((arg) => data.spaces?.(arg ?? {})),\n useBudgetsQuery: staticQueryHook(() => data.budgets?.()),\n});\n","import type { AdminPeriodGranularity } from \"../period/admin-period\";\nimport type { AdminWireChangeHistory, AdminWireSet } from \"../wire/admin-wire\";\n\n/** One point of a time series (`DateValue`): the bucket's day and its value. */\nexport interface AgentControlPanelDateValue {\n /** `YYYY-MM-DD`; with weekly buckets the week's Monday. */\n x: string;\n y?: number | null;\n}\n\n/** A time series (`DateValueSequence`): its metric name and its points, as an object set or a plain list. */\nexport type AgentControlPanelSequence = ({ name?: string } & { elements?: readonly AgentControlPanelDateValue[] | null }) | readonly AgentControlPanelDateValue[];\n\n/** Tokens and cost per bucket (`AgentAIUsagePerBucket`), from the application's usage log. */\nexport interface AgentControlPanelAIUsagePerBucket {\n inputTokensPerBucket?: AgentControlPanelSequence | null;\n outputTokensPerBucket?: AgentControlPanelSequence | null;\n costInUSDPerBucket?: AgentControlPanelSequence | null;\n /** Of the input tokens, the ones read from the prompt cache; empty when the source holds none. */\n cachedInputTokensPerBucket?: AgentControlPanelSequence | null;\n /** The tokens written to the prompt cache; empty when the source holds none. */\n cacheWriteTokensPerBucket?: AgentControlPanelSequence | null;\n /** The first day the usage log holds a booking; before it the figures are empty because nothing was booked. */\n dataAvailableFrom?: string | null;\n /** True: the figures come from the application's usage log. */\n isFromUsageLog?: boolean;\n}\n\n/** The totals of one period behind the key figures (`AgentControlPanelPeriodTotals`); a figure that was not read is absent. */\nexport interface AgentControlPanelPeriodTotals {\n fromDay?: string;\n toDay?: string;\n conversationCount?: number | null;\n activeAccountCount?: number | null;\n weeklyActiveAccounts?: number | null;\n monthlyActiveAccounts?: number | null;\n costInUSD?: number | null;\n costPerConversationInUSD?: number | null;\n /** `USAGE_LOG` or `MESSAGE_ROWS`. */\n costSource?: string | null;\n turnCount?: number | null;\n erroredTurnCount?: number | null;\n errorRate?: number | null;\n scheduledRunCount?: number | null;\n}\n\n/** The cost per bucket by the way a conversation starts (`AgentCostPerBucketByOrigin`). */\nexport interface AgentControlPanelCostPerBucketByOrigin {\n chatCostInUSDPerBucket?: AgentControlPanelSequence | null;\n scheduledRunCostInUSDPerBucket?: AgentControlPanelSequence | null;\n voiceCostInUSDPerBucket?: AgentControlPanelSequence | null;\n /** True: the sums of the conversations' message rows (cost booked outside them is missing). */\n isFromMessageRows?: boolean;\n}\n\n/** One tool's response sizes over the range (`AgentToolResponseStat`). */\nexport interface AgentToolResponseStat {\n toolName: string;\n callCount?: number;\n sumResultChars?: number;\n avgResultChars?: number;\n maxResultChars?: number;\n /** Calls whose stored status is failed; null when it was not read. */\n failedCallCount?: number | null;\n /** The 95th percentile of the result length (nearest rank); null when it was not read. */\n p95ResultChars?: number | null;\n}\n\n/** One conversation of the top list (`AgentConversationStat`). */\nexport interface AgentConversationStat {\n conversationId: number;\n accountId?: number | null;\n agentSpaceId?: number | null;\n messageCount?: number;\n totalTokens?: number;\n totalCostInUSD?: number;\n created?: string | null;\n title?: string | null;\n}\n\n/** The statistics of one range (`AgentControlPanelStatistics`). */\nexport interface AgentControlPanelStatistics {\n rangeFrom?: string;\n rangeTo?: string;\n granularity?: AdminPeriodGranularity;\n aiUsagePerBucket?: AgentControlPanelAIUsagePerBucket | null;\n conversationsPerBucket?: AgentControlPanelSequence | null;\n activeAccountsPerBucket?: AgentControlPanelSequence | null;\n /** Distinct active accounts over the 7 days up to the last day of the range. */\n weeklyActiveAccounts?: number;\n /** Distinct active accounts over the 30 days up to the last day of the range. */\n monthlyActiveAccounts?: number;\n toolResponseStats?: AdminWireSet<AgentToolResponseStat> | null;\n topConversations?: AdminWireSet<AgentConversationStat> | null;\n /** False: the tool-size columns are missing on this database. */\n toolResponseDataAvailable?: boolean;\n satisfactionCaptureAvailable?: boolean;\n scheduledRunCount?: number | null;\n turnCount?: number | null;\n /** Failed message rows of the range (error rows, failed tool calls): a count of rows, not of turns. */\n failedMessageCount?: number | null;\n /** Turns of the range that ended in an error (failed, given up, expired), by the newest terminal record of each turn. */\n erroredTurnCount?: number | null;\n /** `erroredTurnCount` per `turnCount`, 0 to 1: the rate the quality view shows too; null without a turn. */\n errorRate?: number | null;\n costInUSDPerBucketByOrigin?: AgentControlPanelCostPerBucketByOrigin | null;\n /** The totals of the range, and of the range of equal length right before it. */\n totals?: AgentControlPanelPeriodTotals | null;\n previousTotals?: AgentControlPanelPeriodTotals | null;\n /** Where the cost figures come from: `USAGE_LOG` or `MESSAGE_ROWS`. */\n costSource?: string | null;\n /** The first day the cost source holds a cost. */\n costDataAvailableFrom?: string | null;\n /** Whose conversations every figure counts: the environment (null = every one) and whether evaluation runs count. */\n environment?: string | null;\n includesEvalRuns?: boolean;\n}\n\n/** What the top conversations are ordered by. */\nexport type AgentTopConversationsOrder = \"totalCostInUSD\" | \"totalTokens\" | \"messageCount\";\n\nexport interface AgentControlPanelStatisticsArg {\n from?: string;\n to?: string;\n granularity?: AdminPeriodGranularity;\n excludeTestUsers?: boolean;\n topConversationsOrderBy?: AgentTopConversationsOrder;\n}\n\n/** `GET {prefix}/statistics`. */\nexport interface AgentControlPanelStatisticsResponse {\n statistics?: AgentControlPanelStatistics | null;\n}\n\n/** One stored tool response (`AgentToolResponseSample`). */\nexport interface AgentToolResponseSample {\n messageId: number;\n conversationId: number;\n created?: string | null;\n resultChars?: number;\n argumentsChars?: number;\n}\n\nexport interface AgentToolResponseSamplesArg {\n toolName: string;\n from?: string;\n to?: string;\n limit?: number;\n}\n\n/** `GET {prefix}/statistics/toolResponseSamples`. */\nexport interface AgentToolResponseSamplesResponse {\n toolName?: string;\n samples?: AdminWireSet<AgentToolResponseSample> | null;\n}\n\n/** The names of the runtime settings, in display order (`AgentRuntimeSettingsValues::SETTING_PROPERTY_NAMES`). */\nexport const AGENT_RUNTIME_SETTING_NAMES = [\n \"defaultModelName\",\n \"defaultReasoningEffort\",\n \"reasoningEffortCeiling\",\n \"compactionTriggerTokens\",\n \"storeRequestSnapshot\",\n \"decisionModelEnabled\",\n] as const;\n\nexport type AgentRuntimeSettingName = (typeof AGENT_RUNTIME_SETTING_NAMES)[number];\n\n/** The values of the runtime settings (`AgentRuntimeSettingsValues`); null = the default applies. */\nexport interface AgentRuntimeSettingsValues {\n defaultModelName?: string | null;\n defaultReasoningEffort?: string | null;\n reasoningEffortCeiling?: string | null;\n compactionTriggerTokens?: number | null;\n storeRequestSnapshot?: boolean | null;\n decisionModelEnabled?: boolean | null;\n}\n\n/** One recorded change of one setting (`AgentRuntimeSettingChange`). */\nexport interface AgentRuntimeSettingChange {\n id?: number;\n environment?: string | null;\n settingName?: string | null;\n /** The value before as text; empty = the setting was not set. */\n oldValue?: string | null;\n /** The value after as text; empty = put back to the default. */\n newValue?: string | null;\n changedByAccountId?: number | null;\n changeHistory?: AdminWireChangeHistory | null;\n created?: string | null;\n}\n\n/** `GET` and `POST {prefix}/settings`. */\nexport interface AgentRuntimeSettingsResponse {\n /** The name conversations of this installation are stamped with. */\n environment?: string;\n /** The environment in the application's words (which installation and database); shown instead of the name where present. */\n environmentLabel?: string | null;\n settings?: AgentRuntimeSettingsValues | null;\n effectiveDefaults?: AgentRuntimeSettingsValues | null;\n selectableModelNames?: string[] | null;\n selectableReasoningEfforts?: string[] | null;\n minCompactionTriggerTokens?: number;\n maxCompactionTriggerTokens?: number;\n requestSnapshotRetentionDays?: number | null;\n isSettingsTableAvailable?: boolean;\n recentChanges?: AdminWireSet<AgentRuntimeSettingChange> | null;\n}\n\n/** One agent space of a period (`AgentControlPanelSpace`); without a space id: the conversations at account level. */\nexport interface AgentControlPanelSpace {\n agentSpaceId?: number | null;\n kind?: string | null;\n label?: string;\n /** True: the row of the conversations without a space. */\n isAccountLevel?: boolean;\n ownerAccountId?: number | null;\n /** How the application names the owner; absent when it names none. */\n ownerLabel?: string | null;\n timezone?: string | null;\n conversationCount?: number;\n newestConversationAt?: string | null;\n}\n\nexport interface AgentControlPanelSpacesArg {\n from?: string;\n to?: string;\n limit?: number;\n}\n\n/** `GET {prefix}/spaces`. */\nexport interface AgentControlPanelSpacesResponse {\n rangeFrom?: string;\n rangeTo?: string;\n /** The spaces (`AgentControlPanelSpaces`, an object set; read through `wireElementsOf`). */\n spaces?: AdminWireSet<AgentControlPanelSpace> | null;\n}\n\nexport type AgentBudgetMeterKind = \"TOTAL\" | \"ACCOUNT\" | \"SCHEDULED_RUNS\";\n\n/** One budget meter (`AgentBudgetMeter`). */\nexport interface AgentBudgetMeter {\n kind?: AgentBudgetMeterKind | string;\n accountId?: number | null;\n label?: string | null;\n spentInUSD?: number | null;\n capInUSD?: number | null;\n /** The period the meter sums; `periodTo` absent = up to now. */\n periodFrom?: string | null;\n periodTo?: string | null;\n}\n\n/** The budget meters of the current period (`AgentBudgetMeters`, an object set: the meters are its `elements`). */\nexport interface AgentBudgetMeters {\n periodFrom?: string | null;\n periodTo?: string | null;\n /** The meters: the total first, then the runs of schedules, then the accounts by spend. */\n elements?: readonly AgentBudgetMeter[] | null;\n hasCaps?: boolean;\n /** True: the spend is the application's (its usage log), the same source as the cost of the statistics. */\n isSpendOfTheApplication?: boolean;\n /** `APPLICATION` or `MESSAGE_ROWS`. */\n spendSource?: string;\n spendDataAvailableFrom?: string | null;\n}\n\n/** `GET {prefix}/budgets`. */\nexport interface AgentBudgetsResponse {\n budgets?: AgentBudgetMeters | null;\n}\n","import { adminPeriodBucketKeyOf, adminPeriodBucketKeys, type AdminPeriodGranularity } from \"../period/admin-period\";\nimport { wireElementsOf, wireNumberOf } from \"../wire/admin-wire\";\nimport type { AgentControlPanelDateValue, AgentControlPanelSequence, AgentControlPanelStatistics, AgentToolResponseStat } from \"./agent-control-panel-types\";\n\n/** The points of a sequence in either wire form. */\nexport const controlPanelSequencePointsOf = (sequence: AgentControlPanelSequence | null | undefined): AgentControlPanelDateValue[] =>\n wireElementsOf<AgentControlPanelDateValue>(sequence as Parameters<typeof wireElementsOf<AgentControlPanelDateValue>>[0]);\n\n/** The sum of a sequence's values. */\nexport const sumControlPanelSequence = (sequence: AgentControlPanelSequence | null | undefined): number =>\n controlPanelSequencePointsOf(sequence).reduce((sum, point) => sum + (wireNumberOf(point.y) ?? 0), 0);\n\n/** Whether a sequence holds a point at all (an application that supplies no usage log sends empty sequences). */\nexport const hasControlPanelSequencePoints = (sequence: AgentControlPanelSequence | null | undefined): boolean => controlPanelSequencePointsOf(sequence).length > 0;\n\n/**\n * The buckets of a chart: every bucket of the period in order, joined with the buckets the sequences name outside it\n * (a week's Monday before the first day).\n */\nexport const controlPanelBucketsOf = (from: string, to: string, granularity: AdminPeriodGranularity, sequences: readonly (AgentControlPanelSequence | null | undefined)[]): string[] => {\n const keys = new Set(adminPeriodBucketKeys(from, to, granularity));\n for (const sequence of sequences) {\n for (const point of controlPanelSequencePointsOf(sequence)) {\n const key = adminPeriodBucketKeyOf(String(point.x ?? \"\"), granularity);\n if (key !== \"\") keys.add(key);\n }\n }\n return [...keys].sort();\n};\n\n/** The values of a sequence along `buckets`: a bucket without a point is 0; points of one bucket add up. */\nexport const controlPanelSeriesValuesOf = (sequence: AgentControlPanelSequence | null | undefined, buckets: readonly string[], granularity: AdminPeriodGranularity): number[] => {\n const valueByBucket = new Map<string, number>();\n for (const point of controlPanelSequencePointsOf(sequence)) {\n const key = adminPeriodBucketKeyOf(String(point.x ?? \"\"), granularity);\n valueByBucket.set(key, (valueByBucket.get(key) ?? 0) + (wireNumberOf(point.y) ?? 0));\n }\n return buckets.map((bucket) => valueByBucket.get(bucket) ?? 0);\n};\n\n/** The key figures of a range, each null when the statistics do not carry it. */\nexport interface ControlPanelKeyFigures {\n conversationCount: number;\n weeklyActiveAccounts: number | null;\n monthlyActiveAccounts: number | null;\n /** The cost of the usage log; without one, the summed cost by origin; null without both. */\n costInUSD: number | null;\n costPerConversationInUSD: number | null;\n inputTokens: number | null;\n outputTokens: number | null;\n totalTokens: number | null;\n scheduledRunCount: number | null;\n errorRate: number | null;\n failedMessageCount: number | null;\n /** The turns that ended in an error: what `errorRate` counts. */\n erroredTurnCount: number | null;\n turnCount: number | null;\n}\n\n/** The key figures the tiles show, summed from the statistics of one range. */\nexport const buildControlPanelKeyFigures = (statistics: AgentControlPanelStatistics | null | undefined): ControlPanelKeyFigures => {\n const usage = statistics?.aiUsagePerBucket;\n const byOrigin = statistics?.costInUSDPerBucketByOrigin;\n const conversationCount = sumControlPanelSequence(statistics?.conversationsPerBucket);\n const hasUsageCost = hasControlPanelSequencePoints(usage?.costInUSDPerBucket);\n const originSequences = [byOrigin?.chatCostInUSDPerBucket, byOrigin?.scheduledRunCostInUSDPerBucket, byOrigin?.voiceCostInUSDPerBucket];\n const hasOriginCost = originSequences.some(hasControlPanelSequencePoints);\n const costInUSD = hasUsageCost ? sumControlPanelSequence(usage?.costInUSDPerBucket) : hasOriginCost ? originSequences.reduce((sum, sequence) => sum + sumControlPanelSequence(sequence), 0) : null;\n const hasTokens = hasControlPanelSequencePoints(usage?.inputTokensPerBucket) || hasControlPanelSequencePoints(usage?.outputTokensPerBucket);\n const inputTokens = hasTokens ? sumControlPanelSequence(usage?.inputTokensPerBucket) : null;\n const outputTokens = hasTokens ? sumControlPanelSequence(usage?.outputTokensPerBucket) : null;\n return {\n conversationCount,\n weeklyActiveAccounts: wireNumberOf(statistics?.weeklyActiveAccounts),\n monthlyActiveAccounts: wireNumberOf(statistics?.monthlyActiveAccounts),\n costInUSD,\n costPerConversationInUSD: costInUSD !== null && conversationCount > 0 ? costInUSD / conversationCount : null,\n inputTokens,\n outputTokens,\n totalTokens: inputTokens !== null && outputTokens !== null ? inputTokens + outputTokens : null,\n scheduledRunCount: wireNumberOf(statistics?.scheduledRunCount),\n errorRate: wireNumberOf(statistics?.errorRate),\n failedMessageCount: wireNumberOf(statistics?.failedMessageCount),\n erroredTurnCount: wireNumberOf(statistics?.erroredTurnCount),\n turnCount: wireNumberOf(statistics?.turnCount),\n };\n};\n\n/** What the tool table is sorted by. */\nexport type ToolResponseStatSort = \"sum\" | \"calls\" | \"avg\" | \"max\" | \"failed\";\n\nconst TOOL_SORT_VALUE: Readonly<Record<ToolResponseStatSort, (stat: AgentToolResponseStat) => number>> = {\n sum: (stat) => stat.sumResultChars ?? 0,\n calls: (stat) => stat.callCount ?? 0,\n avg: (stat) => stat.avgResultChars ?? 0,\n max: (stat) => stat.maxResultChars ?? 0,\n failed: (stat) => stat.failedCallCount ?? 0,\n};\n\n/** The tools ordered by a measure, largest first; equal values by name. */\nexport const sortToolResponseStats = (stats: readonly AgentToolResponseStat[], sort: ToolResponseStatSort): AgentToolResponseStat[] =>\n [...stats].sort((first, second) => TOOL_SORT_VALUE[sort](second) - TOOL_SORT_VALUE[sort](first) || first.toolName.localeCompare(second.toolName));\n\n/** A character count in a short form (`940`, `2.1k`, `1.4M`), in `locale`. */\nexport const formatCharacterCount = (value: number | null | undefined, locale?: string): string => {\n if (value === null || value === undefined || !Number.isFinite(value)) return \"–\";\n return new Intl.NumberFormat(locale, { notation: \"compact\", maximumFractionDigits: value >= 1000 ? 1 : 0 }).format(value);\n};\n\n/** An amount in USD (`$1.92`); below one cent with four decimals (`$0.0042`), zero as `$0.00`. */\nexport const formatUsdAmount = (value: number | null | undefined, locale?: string): string => {\n if (value === null || value === undefined || !Number.isFinite(value)) return \"–\";\n const digits = value !== 0 && Math.abs(value) < 0.01 ? 4 : 2;\n return new Intl.NumberFormat(locale, { style: \"currency\", currency: \"USD\", minimumFractionDigits: digits, maximumFractionDigits: digits }).format(value);\n};\n\n/** A share of 0 to 1 as a percentage with one decimal below 10 % (`1.4 %`, `91 %`). */\nexport const formatShare = (value: number | null | undefined, locale?: string): string => {\n if (value === null || value === undefined || !Number.isFinite(value)) return \"–\";\n return new Intl.NumberFormat(locale, { style: \"percent\", maximumFractionDigits: Math.abs(value) < 0.1 && value !== 0 ? 1 : 0 }).format(value);\n};\n\n/** A bucket key as an axis label: day and month (`15 Nov`). */\nexport const formatBucketTick = (bucket: string, locale?: string): string => {\n const [year, month, day] = bucket.split(\"-\").map(Number);\n if (year === undefined || month === undefined || day === undefined || Number.isNaN(year + month + day)) return bucket;\n return new Intl.DateTimeFormat(locale, { day: \"numeric\", month: \"short\", timeZone: \"UTC\" }).format(new Date(Date.UTC(year, month - 1, day)));\n};\n\n/** A bucket key in full (`Sat, 28 Nov 2026`). */\nexport const formatBucketTitle = (bucket: string, locale?: string): string => {\n const [year, month, day] = bucket.split(\"-\").map(Number);\n if (year === undefined || month === undefined || day === undefined || Number.isNaN(year + month + day)) return bucket;\n return new Intl.DateTimeFormat(locale, { weekday: \"short\", day: \"numeric\", month: \"short\", year: \"numeric\", timeZone: \"UTC\" }).format(new Date(Date.UTC(year, month - 1, day)));\n};\n","import { m } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { defineStatusMap } from \"@mgamadeus/ddd-admin-ui/logic\";\nimport { Archive, Ban, CircleCheck, CirclePause, CirclePlay, CircleX, Hourglass, Loader, TimerOff, Users } from \"lucide-react\";\nimport type { AgentScheduleListItem, AgentScheduleStatus, AgentScheduleUpdateArg } from \"./agent-schedules-types\";\n\n/** Where a schedule stands (`AIConversationScheduleStatus`). */\nexport const AGENT_SCHEDULE_STATUS = defineStatusMap<AgentScheduleStatus>(\n {\n ACTIVE: { label: m(\"Active\", { context: \"agent-schedule-status\" }), tone: \"success\", icon: CirclePlay, description: m(\"Fires on its occurrences\", { context: \"agent-schedule-status\" }) },\n PAUSED: { label: m(\"Paused\", { context: \"agent-schedule-status\" }), tone: \"warning\", icon: CirclePause, description: m(\"Stopped for now, keeps its state\", { context: \"agent-schedule-status\" }) },\n EXPIRED: { label: m(\"Expired\", { context: \"agent-schedule-status\" }), tone: \"neutral\", icon: TimerOff, description: m(\"Ran past its end or its run limit\", { context: \"agent-schedule-status\" }) },\n DONE: { label: m(\"Done\", { context: \"agent-schedule-status\" }), tone: \"info\", icon: CircleCheck, description: m(\"Its done criteria were fulfilled\", { context: \"agent-schedule-status\" }) },\n CANCELLED: { label: m(\"Cancelled\", { context: \"agent-schedule-status\" }), tone: \"neutral\", icon: Ban, description: m(\"Cancelled, its runs stay readable\", { context: \"agent-schedule-status\" }) },\n ARCHIVED: { label: m(\"Archived\", { context: \"agent-schedule-status\" }), tone: \"neutral\", icon: Archive, description: m(\"Deleted after it had run\", { context: \"agent-schedule-status\" }) },\n },\n { context: \"agent-schedule-status\" },\n);\n\n/** The run state of a run's conversation (`AIConversationRunState`). */\nexport const AGENT_RUN_STATE = defineStatusMap<string>(\n {\n IDLE: { label: m(\"Finished\", { context: \"agent-run-state\" }), tone: \"success\", icon: CircleCheck },\n QUEUED: { label: m(\"Queued\", { context: \"agent-run-state\" }), tone: \"info\", icon: Hourglass },\n RUNNING: { label: m(\"Running\", { context: \"agent-run-state\" }), tone: \"info\", icon: Loader },\n AWAITING_DELEGATES: { label: m(\"Waiting for sub-agents\", { context: \"agent-run-state\" }), tone: \"warning\", icon: Users },\n COMPLETED: { label: m(\"Completed\", { context: \"agent-run-state\" }), tone: \"success\", icon: CircleCheck },\n FAILED: { label: m(\"Failed\", { context: \"agent-run-state\" }), tone: \"danger\", icon: CircleX },\n CANCELLED: { label: m(\"Cancelled\", { context: \"agent-run-state\" }), tone: \"neutral\", icon: Ban },\n },\n { context: \"agent-run-state\" },\n);\n\n/** What the edit dialog holds, as its fields hold it. */\nexport interface AgentScheduleEditValues {\n title: string;\n task: string;\n /** The cron expression of a recurring schedule. */\n cronSchedule: string;\n /** The moment of a one-time task as a `datetime-local` field holds it (`YYYY-MM-DDTHH:MM`), in the schedule's time zone. */\n runAtLocalTime: string;\n}\n\n/** A UTC moment of the backend (`Y-m-d H:i:s`) as the wall time of `timeZone`, in the form of a `datetime-local` field; `\"\"` when unreadable. */\nexport const scheduleLocalDateTimeOf = (utcDateTime: string | null | undefined, timeZone: string): string => {\n if (typeof utcDateTime !== \"string\" || utcDateTime.trim() === \"\") return \"\";\n const date = new Date(`${utcDateTime.trim().replace(\" \", \"T\").slice(0, 19)}Z`);\n if (Number.isNaN(date.getTime())) return \"\";\n try {\n const parts = new Intl.DateTimeFormat(\"en-CA\", { timeZone, year: \"numeric\", month: \"2-digit\", day: \"2-digit\", hour: \"2-digit\", minute: \"2-digit\", hourCycle: \"h23\" }).formatToParts(date);\n const partOf = (type: string) => parts.find((part) => part.type === type)?.value ?? \"\";\n return `${partOf(\"year\")}-${partOf(\"month\")}-${partOf(\"day\")}T${partOf(\"hour\")}:${partOf(\"minute\")}`;\n } catch {\n // an unknown time zone name: the field starts empty and the moment is typed anew\n return \"\";\n }\n};\n\n/** The fields of the edit dialog for a schedule as listed. */\nexport const agentScheduleEditValuesOf = (item: AgentScheduleListItem): AgentScheduleEditValues => ({\n title: item.schedule.title ?? \"\",\n task: item.schedule.task ?? \"\",\n cronSchedule: item.schedule.schedule ?? \"\",\n runAtLocalTime: item.isOneTime === true ? scheduleLocalDateTimeOf(item.schedule.oneTimeAt, item.timezone ?? \"UTC\") : \"\",\n});\n\n/**\n * The update of a schedule: only the fields that differ from what the dialog started with (the route changes only what\n * is sent). The one-time moment goes as `YYYY-MM-DD HH:MM`; null when nothing changed.\n */\nexport const buildAgentScheduleUpdate = (scheduleId: number, initial: AgentScheduleEditValues, edited: AgentScheduleEditValues, isOneTime: boolean): AgentScheduleUpdateArg | null => {\n const update: AgentScheduleUpdateArg = { scheduleId };\n if (edited.title.trim() !== initial.title.trim()) update.title = edited.title.trim();\n if (edited.task.trim() !== initial.task.trim()) update.task = edited.task.trim();\n if (!isOneTime && edited.cronSchedule.trim() !== initial.cronSchedule.trim()) update.cronSchedule = edited.cronSchedule.trim();\n if (isOneTime && edited.runAtLocalTime !== initial.runAtLocalTime && edited.runAtLocalTime !== \"\") update.runAtLocalTime = edited.runAtLocalTime.replace(\"T\", \" \").slice(0, 16);\n return Object.keys(update).length > 1 ? update : null;\n};\n\n/** The longest title the update route takes. */\nexport const AGENT_SCHEDULE_TITLE_MAX_LENGTH = 60;\n","import { normalizeDddError } from \"@mgamadeus/ddd-web/contract\";\nimport { getUiLocale, useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { DateCell, StatusBadge } from \"@mgamadeus/ddd-admin-ui/list\";\nimport { notify, useConfirm } from \"@mgamadeus/ddd-admin-ui/logic\";\nimport { StatusCallout } from \"@mgamadeus/ddd-admin-ui/page\";\nimport {\n Button,\n Card,\n CardContent,\n cn,\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n Input,\n Label,\n type PageLinkComponent,\n Sheet,\n SheetContent,\n SheetDescription,\n SheetHeader,\n SheetTitle,\n Skeleton,\n Table,\n TableBody,\n TableCell,\n TableHead,\n TableHeader,\n TableRow,\n Textarea,\n} from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { CalendarClock, History, MoreHorizontal, Pause, Pencil, Play, Repeat, Trash2, Zap } from \"lucide-react\";\nimport { type ReactNode, useEffect, useId, useMemo, useState } from \"react\";\nimport { formatUsdAmount } from \"../control-panel/control-panel-statistics\";\nimport { AdminHrefLink } from \"../shared/AdminHrefLink\";\nimport { wireElementsOf } from \"../wire/admin-wire\";\nimport type { AgentSchedulesApi } from \"./agent-schedules-api\";\nimport { AGENT_RUN_STATE, AGENT_SCHEDULE_STATUS, AGENT_SCHEDULE_TITLE_MAX_LENGTH, type AgentScheduleEditValues, agentScheduleEditValuesOf, buildAgentScheduleUpdate } from \"./agent-schedules-format\";\nimport type { AgentScheduleListItem, AgentSchedulePlace, AgentSchedulesScope, AgentScheduleStatus } from \"./agent-schedules-types\";\n\nexport interface AgentSchedulesPanelProps {\n /** `createAgentSchedulesApi(…)` of the host. */\n api: AgentSchedulesApi;\n /** Only the schedules of places of this kind (a kind the application names), and with `recordId` of this record. */\n placeKind?: string;\n recordId?: number;\n /**\n * Whose schedules: `own` (the signed-in account's, the default) or `all` (every account's, with an owner column).\n * The server refuses `all` for an account that may not see every account's schedules.\n */\n scope?: AgentSchedulesScope;\n /** The link of a schedule's owner in the host (scope `all`); `null` = no link. */\n buildAccountHref?: (accountId: number) => string | null;\n /** False: the actions that change a schedule are off. Default true. */\n writesAllowed?: boolean;\n linkComponent?: PageLinkComponent;\n /** The link of a run's conversation in the host's agent screens; `null` = no link. */\n buildConversationHref?: (conversationId: number) => string | null;\n /** The host's name of a place (its kind and record); default the place's own name, else its kind. Already translated. */\n describePlace?: (place: AgentSchedulePlace) => ReactNode;\n /**\n * The host's words for the cron expression of a recurring schedule (\"Every day at 07:00\"); null or absent = the\n * expression itself. Already translated. The expression stays readable as the tooltip.\n */\n describeCronSchedule?: (expression: string) => string | null;\n /** The schedule whose runs are open, when the host keeps it (the URL); with it pass `onSelectSchedule`. */\n selectedScheduleId?: number | null;\n onSelectSchedule?: (scheduleId: number | null) => void;\n /** The card's heading; default \"Schedules\". Already translated. */\n title?: ReactNode;\n className?: string;\n}\n\ninterface CronScheduleTextProps {\n expression: string;\n describeCronSchedule?: (expression: string) => string | null;\n}\n\n/** A recurring schedule's timing: the host's words with the expression as the tooltip, else the expression. */\nconst CronScheduleText = ({ expression, describeCronSchedule }: CronScheduleTextProps) => {\n if (expression === \"\") return <span>–</span>;\n const words = describeCronSchedule?.(expression) ?? null;\n if (words === null || words === \"\") return <span className=\"font-mono text-xs\">{expression}</span>;\n return (\n <span data-slot=\"agent-schedule-timing\" title={expression}>\n {words}\n </span>\n );\n};\n\n/** How many runs the drawer lists (the route's most). */\nconst RUNS_LIMIT = 50;\n\ninterface ScheduleRunsDrawerProps extends Pick<AgentSchedulesPanelProps, \"api\" | \"linkComponent\" | \"buildConversationHref\"> {\n item: AgentScheduleListItem | null;\n onClose: () => void;\n}\n\nconst ScheduleRunsDrawer = ({ api, item, onClose, linkComponent, buildConversationHref }: ScheduleRunsDrawerProps) => {\n const { t } = useTranslate();\n const locale = getUiLocale();\n const scheduleId = item?.schedule.id ?? null;\n const query = api.useAgentScheduleRunsQuery({ scheduleId: scheduleId ?? 0, limit: RUNS_LIMIT }, { skip: scheduleId === null });\n const runs = scheduleId === null || query.currentData?.runs == null ? null : wireElementsOf(query.currentData.runs);\n return (\n <Sheet\n open={item !== null}\n onOpenChange={(isOpen) => {\n if (!isOpen) onClose();\n }}\n >\n <SheetContent side=\"right\" data-slot=\"agent-schedule-runs-drawer\" className=\"flex w-full flex-col gap-0 overflow-y-auto p-0 sm:max-w-2xl\">\n <SheetHeader className=\"border-b border-border px-6 py-4 pr-12\">\n <SheetTitle className=\"text-lg break-words\">{item?.label ?? \"\"}</SheetTitle>\n <SheetDescription>{t(\"The runs of this schedule, the newest first.\")}</SheetDescription>\n </SheetHeader>\n <div className=\"min-w-0 px-6 py-5\">\n {query.isError ? (\n <StatusCallout size=\"compact\" tone=\"destructive\" title={t(\"The runs could not be loaded.\")} description={normalizeDddError(query.error, \"\").message} />\n ) : runs === null ? (\n <div className=\"space-y-2\">\n <Skeleton className=\"h-14 w-full\" />\n <Skeleton className=\"h-14 w-full\" />\n <Skeleton className=\"h-14 w-full\" />\n </div>\n ) : runs.length === 0 ? (\n <p className=\"py-6 text-center text-sm text-muted-foreground\">{t(\"This schedule has not run yet.\")}</p>\n ) : (\n <ul className=\"divide-y divide-border\">\n {runs.map((run) => (\n <li key={run.conversationId} data-slot=\"agent-schedule-run\" data-conversation={run.conversationId} className=\"space-y-1 py-3\">\n <div className=\"flex flex-wrap items-center gap-x-3 gap-y-1\">\n <StatusBadge value={run.runState ?? null} map={AGENT_RUN_STATE} />\n <DateCell value={run.created} className=\"text-sm\" />\n <span className=\"ml-auto text-sm tabular-nums\">{formatUsdAmount(run.costInUSD ?? 0, locale)}</span>\n </div>\n <AdminHrefLink href={buildConversationHref?.(run.conversationId) ?? null} linkComponent={linkComponent} className=\"text-sm font-medium break-words\">\n {typeof run.title === \"string\" && run.title.trim() !== \"\" ? run.title : t(\"Conversation #%id%\", { replacements: { id: String(run.conversationId) } })}\n </AdminHrefLink>\n {typeof run.outcome === \"string\" && run.outcome.trim() !== \"\" && <p className=\"line-clamp-3 text-sm text-muted-foreground\">{run.outcome}</p>}\n </li>\n ))}\n </ul>\n )}\n </div>\n </SheetContent>\n </Sheet>\n );\n};\n\ninterface ScheduleEditDialogProps extends Pick<AgentSchedulesPanelProps, \"api\"> {\n item: AgentScheduleListItem | null;\n onClose: () => void;\n}\n\nconst ScheduleEditDialog = ({ api, item, onClose }: ScheduleEditDialogProps) => {\n const { t } = useTranslate();\n const idPrefix = useId();\n const [updateSchedule, updateState] = api.useUpdateAgentScheduleMutation();\n const [initial, setInitial] = useState<AgentScheduleEditValues>({ title: \"\", task: \"\", cronSchedule: \"\", runAtLocalTime: \"\" });\n const [edited, setEdited] = useState<AgentScheduleEditValues>(initial);\n const [error, setError] = useState<string | null>(null);\n const scheduleId = item?.schedule.id ?? null;\n // the fields start from the schedule each time the dialog opens for one\n useEffect(() => {\n if (item === null) return;\n const values = agentScheduleEditValuesOf(item);\n setInitial(values);\n setEdited(values);\n setError(null);\n // (only when another schedule opens: a refetch of the same one must not reset what is being typed)\n // biome-ignore lint/correctness/useExhaustiveDependencies: keyed by the schedule id on purpose\n }, [scheduleId]);\n const isOneTime = item?.isOneTime === true;\n const update = scheduleId === null ? null : buildAgentScheduleUpdate(scheduleId, initial, edited, isOneTime);\n const isTaskEmpty = edited.task.trim() === \"\";\n const isTimingEmpty = isOneTime ? edited.runAtLocalTime === \"\" : edited.cronSchedule.trim() === \"\";\n const setField = (name: keyof AgentScheduleEditValues, value: string) => setEdited((current) => ({ ...current, [name]: value }));\n const save = async () => {\n if (update === null) return;\n setError(null);\n try {\n await updateSchedule(update).unwrap();\n notify.success(t(\"The schedule was changed.\"));\n onClose();\n } catch (caught) {\n setError(normalizeDddError(caught, t(\"The schedule could not be changed.\")).message);\n }\n };\n return (\n <Dialog\n open={item !== null}\n onOpenChange={(isOpen) => {\n if (!isOpen && !updateState.isLoading) onClose();\n }}\n >\n <DialogContent data-slot=\"agent-schedule-edit-dialog\" className=\"sm:max-w-xl\">\n <DialogHeader>\n <DialogTitle>{t(\"Edit schedule\")}</DialogTitle>\n <DialogDescription>{isOneTime ? t(\"A one-time task: its title, what it does and when it runs.\") : t(\"A recurring schedule: its title, what it does and when it fires.\")}</DialogDescription>\n </DialogHeader>\n <form\n className=\"space-y-4\"\n onSubmit={(event) => {\n event.preventDefault();\n void save();\n }}\n >\n <div className=\"space-y-1.5\">\n <Label htmlFor={`${idPrefix}-title`}>{t(\"Title\", { context: \"agent-schedule\" })}</Label>\n <Input id={`${idPrefix}-title`} name=\"title\" value={edited.title} maxLength={AGENT_SCHEDULE_TITLE_MAX_LENGTH} onChange={(event) => setField(\"title\", event.target.value)} />\n </div>\n <div className=\"space-y-1.5\">\n <Label htmlFor={`${idPrefix}-task`}>{t(\"Task\", { context: \"agent-schedule\" })}</Label>\n <Textarea id={`${idPrefix}-task`} name=\"task\" rows={6} value={edited.task} aria-invalid={isTaskEmpty} onChange={(event) => setField(\"task\", event.target.value)} />\n </div>\n {isOneTime ? (\n <div className=\"space-y-1.5\">\n <Label htmlFor={`${idPrefix}-runAt`}>{t(\"Runs at\")}</Label>\n <Input id={`${idPrefix}-runAt`} name=\"runAtLocalTime\" type=\"datetime-local\" value={edited.runAtLocalTime} onChange={(event) => setField(\"runAtLocalTime\", event.target.value)} />\n <p className=\"text-xs text-muted-foreground\">{t(\"In the time zone of the schedule: %timezone%.\", { replacements: { timezone: item?.timezone ?? \"UTC\" } })}</p>\n </div>\n ) : (\n <div className=\"space-y-1.5\">\n <Label htmlFor={`${idPrefix}-cron`}>{t(\"Cron expression\")}</Label>\n <Input id={`${idPrefix}-cron`} name=\"cronSchedule\" value={edited.cronSchedule} className=\"font-mono\" spellCheck={false} onChange={(event) => setField(\"cronSchedule\", event.target.value)} />\n <p className=\"text-xs text-muted-foreground\">\n {t(\"Minute, hour, day of the month, month, weekday. In the time zone of the schedule: %timezone%.\", { replacements: { timezone: item?.timezone ?? \"UTC\" } })}\n </p>\n </div>\n )}\n {error !== null && <StatusCallout size=\"compact\" tone=\"destructive\" title={error} />}\n <DialogFooter>\n <Button type=\"button\" variant=\"outline\" disabled={updateState.isLoading} onClick={onClose}>\n {t(\"Cancel\")}\n </Button>\n <Button type=\"submit\" data-slot=\"agent-schedule-edit-save\" disabled={update === null || isTaskEmpty || isTimingEmpty || updateState.isLoading}>\n {updateState.isLoading ? t(\"Saving…\") : t(\"Save\", { context: \"agent-schedule\" })}\n </Button>\n </DialogFooter>\n </form>\n </DialogContent>\n </Dialog>\n );\n};\n\n/**\n * The agent's schedules as a table: where a schedule lives, its label and task, its timing (cron expression or\n * one-time moment, with its time zone), its state, the last and the next run and how the newest run ended. A row's\n * menu opens the runs, edits the schedule, pauses or resumes it, runs it now or deletes it; each entry shows only when\n * the schedule allows it now, and a delete or a run asks first.\n */\nexport const AgentSchedulesPanel = ({\n api,\n placeKind,\n recordId,\n scope = \"own\",\n buildAccountHref,\n writesAllowed = true,\n linkComponent,\n buildConversationHref,\n describePlace,\n describeCronSchedule,\n selectedScheduleId,\n onSelectSchedule,\n title,\n className,\n}: AgentSchedulesPanelProps) => {\n const { t } = useTranslate();\n const confirm = useConfirm();\n const listsEveryAccount = scope === \"all\";\n const query = api.useAgentSchedulesQuery(listsEveryAccount ? { placeKind, recordId, scope: \"all\" } : { placeKind, recordId });\n const [pauseSchedule] = api.usePauseAgentScheduleMutation();\n const [resumeSchedule] = api.useResumeAgentScheduleMutation();\n const [runScheduleNow] = api.useRunAgentScheduleNowMutation();\n const [deleteSchedule] = api.useDeleteAgentScheduleMutation();\n const [ownRunsScheduleId, setOwnRunsScheduleId] = useState<number | null>(null);\n const [editScheduleId, setEditScheduleId] = useState<number | null>(null);\n const [busyScheduleId, setBusyScheduleId] = useState<number | null>(null);\n const items = useMemo(() => (query.data?.items == null ? null : wireElementsOf(query.data.items)), [query.data]);\n const runsScheduleId = selectedScheduleId !== undefined ? selectedScheduleId : ownRunsScheduleId;\n const selectRuns = (scheduleId: number | null) => {\n setOwnRunsScheduleId(scheduleId);\n onSelectSchedule?.(scheduleId);\n };\n const itemOf = (scheduleId: number | null) => (scheduleId === null ? null : ((items ?? []).find((item) => item.schedule.id === scheduleId) ?? null));\n\n const runAction = async (item: AgentScheduleListItem, action: () => Promise<unknown>, successText: string, failureText: string) => {\n setBusyScheduleId(item.schedule.id);\n try {\n await action();\n notify.success(successText);\n } catch (caught) {\n notify.error(normalizeDddError(caught, failureText).message);\n } finally {\n setBusyScheduleId(null);\n }\n };\n const pause = (item: AgentScheduleListItem) => runAction(item, () => pauseSchedule({ scheduleId: item.schedule.id }).unwrap(), t(\"The schedule was paused.\"), t(\"The schedule could not be paused.\"));\n const resume = (item: AgentScheduleListItem) => runAction(item, () => resumeSchedule({ scheduleId: item.schedule.id }).unwrap(), t(\"The schedule was resumed.\"), t(\"The schedule could not be resumed.\"));\n const runNow = async (item: AgentScheduleListItem) => {\n const isConfirmed = await confirm({\n title: t(\"Run “%label%” now?\", { replacements: { label: item.label ?? \"\" } }),\n description: t(\"A run starts at once, beside the schedule's own occurrences. It costs what a run costs.\"),\n confirmLabel: t(\"Run now\"),\n });\n if (isConfirmed) await runAction(item, () => runScheduleNow({ scheduleId: item.schedule.id }).unwrap(), t(\"The run was started.\"), t(\"The run could not be started.\"));\n };\n const remove = async (item: AgentScheduleListItem) => {\n const isConfirmed = await confirm({\n title: t(\"Delete “%label%”?\", { replacements: { label: item.label ?? \"\" } }),\n description: t(\"A schedule that never ran is removed. One that ran is archived and its runs stay readable.\"),\n confirmLabel: t(\"Delete\", { context: \"agent-schedule\" }),\n confirmVariant: \"destructive\",\n });\n if (isConfirmed) await runAction(item, () => deleteSchedule({ scheduleId: item.schedule.id }).unwrap(), t(\"The schedule was deleted.\"), t(\"The schedule could not be deleted.\"));\n };\n\n const heading = (\n <div className=\"px-3 pb-2\">\n <h3 className=\"text-base font-semibold\">{title ?? t(\"Schedules\", { context: \"agent-schedule\" })}</h3>\n <p className=\"text-sm text-muted-foreground\">\n {listsEveryAccount ? t(\"What the agent runs by itself for every account: recurring schedules and one-time tasks.\") : t(\"What the agent runs by itself: recurring schedules and one-time tasks.\")}\n </p>\n </div>\n );\n if (query.isLoading) return <Skeleton className={cn(\"h-72 w-full rounded-2xl\", className)} />;\n if (query.isError || items === null) {\n return <StatusCallout tone=\"destructive\" title={t(\"The schedules could not be loaded.\")} description={query.isError ? normalizeDddError(query.error, \"\").message : undefined} className={className} />;\n }\n\n return (\n <Card data-slot=\"agent-schedules-panel\" className={cn(\"gap-0 py-0\", className)}>\n <CardContent className=\"px-2 py-4\">\n {heading}\n {items.length === 0 ? (\n <div className=\"flex flex-col items-center gap-2 px-3 py-10 text-center\">\n <CalendarClock aria-hidden className=\"size-6 text-muted-foreground\" />\n <p className=\"text-sm text-muted-foreground\">{t(\"No schedule yet.\")}</p>\n </div>\n ) : (\n <Table>\n <TableHeader>\n <TableRow className=\"hover:bg-transparent\">\n <TableHead className=\"px-3 text-xs text-muted-foreground\">{t(\"Schedule\", { context: \"agent-schedule\" })}</TableHead>\n {listsEveryAccount && <TableHead className=\"px-3 text-xs text-muted-foreground\">{t(\"Owner\", { context: \"agent-schedule\" })}</TableHead>}\n <TableHead className=\"px-3 text-xs text-muted-foreground\">{t(\"Place\", { context: \"agent-schedule\" })}</TableHead>\n <TableHead className=\"px-3 text-xs text-muted-foreground\">{t(\"Timing\", { context: \"agent-schedule\" })}</TableHead>\n <TableHead className=\"px-3 text-xs text-muted-foreground\">{t(\"State\", { context: \"agent-schedule\" })}</TableHead>\n <TableHead className=\"px-3 text-xs text-muted-foreground\">{t(\"Last run\")}</TableHead>\n <TableHead className=\"px-3 text-xs text-muted-foreground\">{t(\"Next run\")}</TableHead>\n <TableHead className=\"px-3 text-xs text-muted-foreground\">{t(\"Outcome of the newest run\")}</TableHead>\n <TableHead className=\"w-10 px-2\">\n <span className=\"sr-only\">{t(\"Actions\", { context: \"agent-schedule\" })}</span>\n </TableHead>\n </TableRow>\n </TableHeader>\n <TableBody>\n {items.map((item) => {\n const { schedule } = item;\n const place = item.place ?? {};\n const placeText = describePlace?.(place) ?? (typeof place.name === \"string\" && place.name !== \"\" ? place.name : place.kind === \"ACCOUNT\" || place.kind === undefined ? t(\"Account level\", { context: \"agent-schedule\" }) : place.kind === \"SPACE\" ? t(\"Space #%id%\", { replacements: { id: String(place.agentSpaceId ?? \"\") } }) : place.kind);\n const newestRun = item.newestRun ?? null;\n const isBusy = busyScheduleId === schedule.id;\n const hasWriteAction = item.canBeEdited === true || item.canBePaused === true || item.canBeResumed === true || item.canRunNow === true;\n return (\n <TableRow key={schedule.id} data-slot=\"agent-schedule-row\" data-schedule={schedule.id} className={cn(\"hover:bg-transparent\", isBusy && \"opacity-60\")}>\n <TableCell className=\"max-w-64 px-3 py-2.5 align-top whitespace-normal\">\n <button\n type=\"button\"\n onClick={() => selectRuns(schedule.id)}\n className=\"block max-w-full rounded-sm text-left text-sm font-semibold break-words outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring\"\n >\n {item.label !== undefined && item.label !== \"\" ? item.label : `#${schedule.id}`}\n </button>\n {typeof schedule.task === \"string\" && schedule.task !== \"\" && schedule.task !== item.label && <p className=\"line-clamp-2 text-xs text-muted-foreground\">{schedule.task}</p>}\n </TableCell>\n {listsEveryAccount && (\n <TableCell data-slot=\"agent-schedule-owner\" className=\"max-w-40 min-w-32 px-3 py-2.5 align-top text-sm whitespace-normal\">\n {typeof item.ownerAccountId === \"number\" ? (\n <AdminHrefLink href={buildAccountHref?.(item.ownerAccountId) ?? null} linkComponent={linkComponent}>\n {typeof item.ownerAccountLabel === \"string\" && item.ownerAccountLabel !== \"\" ? item.ownerAccountLabel : `#${item.ownerAccountId}`}\n </AdminHrefLink>\n ) : (\n \"–\"\n )}\n </TableCell>\n )}\n <TableCell className=\"max-w-40 px-3 py-2.5 align-top text-sm whitespace-normal\">{placeText}</TableCell>\n <TableCell className=\"max-w-56 min-w-44 px-3 py-2.5 align-top whitespace-normal\">\n <span className=\"flex items-start gap-1.5 text-sm\">\n {item.isOneTime === true ? <Zap aria-hidden className=\"mt-0.5 size-3.5 shrink-0 text-muted-foreground\" /> : <Repeat aria-hidden className=\"mt-0.5 size-3.5 shrink-0 text-muted-foreground\" />}\n {item.isOneTime === true ? (\n <span>{t(\"Once\", { context: \"agent-schedule\" })}</span>\n ) : (\n <CronScheduleText expression={schedule.schedule ?? \"\"} describeCronSchedule={describeCronSchedule} />\n )}\n </span>\n <span className=\"text-xs text-muted-foreground\">{item.timezone ?? \"UTC\"}</span>\n </TableCell>\n <TableCell className=\"px-3 py-2.5 align-top\">\n <StatusBadge value={(schedule.status ?? null) as AgentScheduleStatus | null} map={AGENT_SCHEDULE_STATUS} />\n {(schedule.failureStreak ?? 0) > 0 && (\n <p className=\"mt-1 text-xs text-destructive\">{t(\"{count, plural, one {# failed run in a row} other {# failed runs in a row}}\", { count: schedule.failureStreak ?? 0 })}</p>\n )}\n </TableCell>\n <TableCell className=\"px-3 py-2.5 align-top\">\n <DateCell value={schedule.lastFiredAt} />\n </TableCell>\n <TableCell className=\"px-3 py-2.5 align-top\">\n <DateCell value={schedule.status === \"ACTIVE\" ? (schedule.nextRunAt ?? (item.isOneTime === true ? schedule.oneTimeAt : null)) : null} />\n </TableCell>\n <TableCell className=\"max-w-56 px-3 py-2.5 align-top whitespace-normal\">\n {newestRun === null ? (\n <span className=\"text-sm text-muted-foreground\">{t(\"has not run\")}</span>\n ) : (\n <>\n <span className=\"flex flex-wrap items-center gap-2\">\n <StatusBadge value={newestRun.runState ?? null} map={AGENT_RUN_STATE} />\n <AdminHrefLink href={buildConversationHref?.(newestRun.conversationId) ?? null} linkComponent={linkComponent} className=\"font-mono text-xs\">\n #{newestRun.conversationId}\n </AdminHrefLink>\n </span>\n {typeof newestRun.outcomeExcerpt === \"string\" && newestRun.outcomeExcerpt !== \"\" && <p className=\"mt-1 line-clamp-2 text-xs text-muted-foreground\">{newestRun.outcomeExcerpt}</p>}\n </>\n )}\n </TableCell>\n <TableCell className=\"px-2 py-2.5 align-top\">\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button type=\"button\" variant=\"ghost\" size=\"icon-sm\" rounded=\"full\" disabled={isBusy} aria-label={t(\"Actions of “%label%”\", { replacements: { label: item.label ?? String(schedule.id) } })}>\n <MoreHorizontal aria-hidden />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\" data-slot=\"agent-schedule-menu\">\n <DropdownMenuItem onSelect={() => selectRuns(schedule.id)}>\n <History aria-hidden />\n {t(\"Runs\", { context: \"agent-schedule\" })}\n </DropdownMenuItem>\n {hasWriteAction && <DropdownMenuSeparator />}\n {item.canBeEdited === true && (\n <DropdownMenuItem disabled={!writesAllowed} onSelect={() => setEditScheduleId(schedule.id)}>\n <Pencil aria-hidden />\n {t(\"Edit\", { context: \"agent-schedule\" })}\n </DropdownMenuItem>\n )}\n {item.canBePaused === true && (\n <DropdownMenuItem disabled={!writesAllowed} onSelect={() => void pause(item)}>\n <Pause aria-hidden />\n {t(\"Pause\", { context: \"agent-schedule\" })}\n </DropdownMenuItem>\n )}\n {item.canBeResumed === true && (\n <DropdownMenuItem disabled={!writesAllowed} onSelect={() => void resume(item)}>\n <Play aria-hidden />\n {t(\"Resume\", { context: \"agent-schedule\" })}\n </DropdownMenuItem>\n )}\n {item.canRunNow === true && (\n <DropdownMenuItem disabled={!writesAllowed} onSelect={() => void runNow(item)}>\n <Zap aria-hidden />\n {t(\"Run now\")}\n </DropdownMenuItem>\n )}\n <DropdownMenuSeparator />\n <DropdownMenuItem variant=\"destructive\" disabled={!writesAllowed} onSelect={() => void remove(item)}>\n <Trash2 aria-hidden />\n {t(\"Delete\", { context: \"agent-schedule\" })}\n </DropdownMenuItem>\n </DropdownMenuContent>\n </DropdownMenu>\n </TableCell>\n </TableRow>\n );\n })}\n </TableBody>\n </Table>\n )}\n </CardContent>\n <ScheduleRunsDrawer api={api} item={itemOf(runsScheduleId ?? null)} onClose={() => selectRuns(null)} linkComponent={linkComponent} buildConversationHref={buildConversationHref} />\n <ScheduleEditDialog api={api} item={itemOf(editScheduleId)} onClose={() => setEditScheduleId(null)} />\n </Card>\n );\n};\n","import { wireNumberOf } from \"../wire/admin-wire\";\nimport type { AgentBudgetMeter, AgentBudgetMeters } from \"./agent-control-panel-types\";\n\n/** How full a meter is: `normal`, `warning` from 80 % of its cap, `over` from 100 %; `none` without a cap. */\nexport type BudgetMeterLevel = \"none\" | \"normal\" | \"warning\" | \"over\";\n\n/** The share of a cap from which a meter warns. */\nexport const BUDGET_METER_WARNING_SHARE = 0.8;\n\n/** One meter as the screen draws it. */\nexport interface BudgetMeterView {\n key: string;\n kind: string;\n accountId: number | null;\n /** The application's label; null = the screen names the meter by its kind. */\n label: string | null;\n /** Null: the application named a cap only. */\n spentInUSD: number | null;\n capInUSD: number | null;\n /** Spend per cap (may exceed 1); null without a cap or a spend. */\n shareOfCap: number | null;\n /** The spend per total spend, 0 to 1; null for the total meter itself, or without a total. */\n shareOfTotal: number | null;\n /** The filled part of the bar, 0 to 1: the share of the cap, else the share of the total. */\n fillFraction: number;\n level: BudgetMeterLevel;\n}\n\nconst clampFraction = (value: number): number => (Number.isFinite(value) ? Math.min(1, Math.max(0, value)) : 0);\n\n/** The level of a spend against its cap. */\nexport const budgetMeterLevelOf = (spentInUSD: number | null, capInUSD: number | null): BudgetMeterLevel => {\n if (capInUSD === null || capInUSD <= 0 || spentInUSD === null) return \"none\";\n const share = spentInUSD / capInUSD;\n return share >= 1 ? \"over\" : share >= BUDGET_METER_WARNING_SHARE ? \"warning\" : \"normal\";\n};\n\nconst positiveOrNull = (value: unknown): number | null => {\n const number = wireNumberOf(value);\n return number !== null && number >= 0 ? number : null;\n};\n\n/** The view of one meter; `totalSpentInUSD` is the spend of the total meter. */\nexport const buildBudgetMeterView = (meter: AgentBudgetMeter, totalSpentInUSD: number | null): BudgetMeterView => {\n const kind = String(meter.kind ?? \"TOTAL\");\n const spentInUSD = positiveOrNull(meter.spentInUSD);\n const cap = positiveOrNull(meter.capInUSD);\n const capInUSD = cap !== null && cap > 0 ? cap : null;\n const shareOfCap = capInUSD !== null && spentInUSD !== null ? spentInUSD / capInUSD : null;\n const shareOfTotal = kind !== \"TOTAL\" && spentInUSD !== null && totalSpentInUSD !== null && totalSpentInUSD > 0 ? clampFraction(spentInUSD / totalSpentInUSD) : null;\n return {\n key: `${kind}_${meter.accountId ?? \"\"}`,\n kind,\n accountId: meter.accountId ?? null,\n label: typeof meter.label === \"string\" && meter.label.trim() !== \"\" ? meter.label.trim() : null,\n spentInUSD,\n capInUSD,\n shareOfCap,\n shareOfTotal,\n fillFraction: shareOfCap !== null ? clampFraction(shareOfCap) : kind === \"TOTAL\" ? (spentInUSD !== null && spentInUSD > 0 ? 1 : 0) : (shareOfTotal ?? 0),\n level: budgetMeterLevelOf(spentInUSD, capInUSD),\n };\n};\n\n/** The meters split as the screen lists them: the total and the scheduled runs first, then the accounts by spend. */\nexport interface BudgetMeterViews {\n general: BudgetMeterView[];\n accounts: BudgetMeterView[];\n hasCaps: boolean;\n}\n\n/** The meter views of a budgets answer. */\nexport const buildBudgetMeterViews = (budgets: AgentBudgetMeters | null | undefined): BudgetMeterViews => {\n const meters = budgets?.elements ?? [];\n const totalSpentInUSD = positiveOrNull(meters.find((meter) => String(meter.kind ?? \"TOTAL\") === \"TOTAL\")?.spentInUSD);\n const views = meters.map((meter) => buildBudgetMeterView(meter, totalSpentInUSD));\n const kindOrder = [\"TOTAL\", \"SCHEDULED_RUNS\"];\n return {\n general: views.filter((view) => view.kind !== \"ACCOUNT\").sort((first, second) => (kindOrder.indexOf(first.kind) + 99) % 99 - ((kindOrder.indexOf(second.kind) + 99) % 99)),\n accounts: views.filter((view) => view.kind === \"ACCOUNT\").sort((first, second) => (second.spentInUSD ?? 0) - (first.spentInUSD ?? 0)),\n hasCaps: budgets?.hasCaps === true || views.some((view) => view.capInUSD !== null),\n };\n};\n","import { normalizeDddError } from \"@mgamadeus/ddd-web/contract\";\nimport { getUiLocale, useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { formatDate } from \"@mgamadeus/ddd-admin-ui/list\";\nimport { StatusCallout } from \"@mgamadeus/ddd-admin-ui/page\";\nimport { Card, CardContent, cn, type PageLinkComponent, Skeleton } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { CircleAlert, TriangleAlert, Wallet } from \"lucide-react\";\nimport { useMemo } from \"react\";\nimport { AdminHrefLink } from \"../shared/AdminHrefLink\";\nimport type { AgentControlPanelApi } from \"./agent-control-panel-api\";\nimport { type BudgetMeterView, buildBudgetMeterViews } from \"./budget-meters\";\nimport { formatShare, formatUsdAmount } from \"./control-panel-statistics\";\n\nexport interface BudgetsTabProps {\n api: Pick<AgentControlPanelApi, \"useBudgetsQuery\">;\n linkComponent?: PageLinkComponent;\n buildAccountHref?: (accountId: number) => string | null;\n}\n\nconst FILL_CLASS_NAMES = {\n none: \"bg-[color:var(--series-1,var(--brand))]\",\n normal: \"bg-[color:var(--series-1,var(--brand))]\",\n warning: \"bg-warning\",\n over: \"bg-destructive\",\n} as const;\n\ninterface BudgetMeterRowProps extends Pick<BudgetsTabProps, \"linkComponent\" | \"buildAccountHref\"> {\n meter: BudgetMeterView;\n}\n\nconst BudgetMeterRow = ({ meter, linkComponent, buildAccountHref }: BudgetMeterRowProps) => {\n const { t } = useTranslate();\n const locale = getUiLocale();\n const kindLabel =\n meter.kind === \"TOTAL\"\n ? t(\"Total\", { context: \"agent-budget\" })\n : meter.kind === \"SCHEDULED_RUNS\"\n ? t(\"Scheduled runs\", { context: \"agent-origin\" })\n : meter.kind === \"ACCOUNT\" && meter.accountId !== null\n ? t(\"Account #%id%\", { replacements: { id: String(meter.accountId) } })\n : meter.kind;\n const name = meter.label ?? kindLabel;\n const spentText = meter.spentInUSD === null ? t(\"no spend named\") : formatUsdAmount(meter.spentInUSD, locale);\n return (\n <li data-slot=\"budget-meter\" data-meter={meter.key} data-level={meter.level} className=\"space-y-1.5 py-3\">\n <div className=\"flex flex-wrap items-baseline gap-x-3 gap-y-0.5\">\n <span className=\"min-w-0 flex-1 text-sm font-semibold\">\n {meter.kind === \"ACCOUNT\" && meter.accountId !== null ? (\n <AdminHrefLink href={buildAccountHref?.(meter.accountId) ?? null} linkComponent={linkComponent} className=\"font-semibold\">\n {name}\n </AdminHrefLink>\n ) : (\n name\n )}\n {meter.label !== null && meter.kind === \"ACCOUNT\" && meter.accountId !== null && <span className=\"ml-2 font-mono text-xs font-normal text-muted-foreground\">#{meter.accountId}</span>}\n </span>\n <span className=\"text-sm tabular-nums\">\n {meter.capInUSD !== null ? t(\"%spent% of %cap%\", { replacements: { spent: spentText, cap: formatUsdAmount(meter.capInUSD, locale) } }) : spentText}\n </span>\n <span className=\"w-40 text-right text-xs text-muted-foreground tabular-nums\">\n {meter.shareOfCap !== null ? (\n <span className={cn(\"inline-flex items-center gap-1\", meter.level === \"over\" && \"font-semibold text-destructive\", meter.level === \"warning\" && \"font-semibold text-warning\")}>\n {meter.level === \"over\" && <CircleAlert aria-hidden className=\"size-3.5\" />}\n {meter.level === \"warning\" && <TriangleAlert aria-hidden className=\"size-3.5\" />}\n {t(\"%share% of the cap\", { replacements: { share: formatShare(meter.shareOfCap, locale) } })}\n </span>\n ) : meter.shareOfTotal !== null ? (\n t(\"%share% of the total\", { replacements: { share: formatShare(meter.shareOfTotal, locale) } })\n ) : (\n t(\"No cap set\", { context: \"agent-budget\" })\n )}\n </span>\n </div>\n {/* without a cap the total has nothing to fill against: a full bar would read as an exhausted budget */}\n {!(meter.kind === \"TOTAL\" && meter.capInUSD === null) && <div\n role=\"meter\"\n aria-label={name}\n aria-valuemin={0}\n aria-valuemax={meter.capInUSD ?? undefined}\n aria-valuenow={meter.spentInUSD ?? 0}\n aria-valuetext={meter.capInUSD !== null ? t(\"%spent% of %cap%\", { replacements: { spent: spentText, cap: formatUsdAmount(meter.capInUSD, locale) } }) : spentText}\n className=\"h-2 overflow-hidden rounded-full bg-muted\"\n >\n <span className={cn(\"block h-full rounded-full\", FILL_CLASS_NAMES[meter.level])} style={{ width: `${meter.fillFraction * 100}%` }} />\n </div>}\n </li>\n );\n};\n\n/**\n * The budget meters of the current period (read-only): the agent's total spend and the runs of schedules, then the\n * accounts that spent most. A meter with a cap fills against the cap and warns from 80 %; one without fills by its\n * share of the total spend.\n */\nexport const BudgetsTab = ({ api, linkComponent, buildAccountHref }: BudgetsTabProps) => {\n const { t } = useTranslate();\n const query = api.useBudgetsQuery();\n const budgets = query.data?.budgets ?? null;\n const views = useMemo(() => buildBudgetMeterViews(budgets), [budgets]);\n if (query.isLoading) return <Skeleton className=\"h-64 w-full rounded-2xl\" />;\n if (query.isError) return <StatusCallout tone=\"destructive\" title={t(\"The budgets could not be loaded.\")} description={normalizeDddError(query.error, \"\").message} />;\n if (views.general.length === 0 && views.accounts.length === 0) {\n return (\n <Card data-slot=\"agent-budgets-tab\" className=\"py-0\">\n <CardContent className=\"flex flex-col items-center gap-2 px-5 py-12 text-center\">\n <Wallet aria-hidden className=\"size-6 text-muted-foreground\" />\n <p className=\"text-sm font-semibold\">{t(\"No budget meters\")}</p>\n <p className=\"max-w-md text-sm text-muted-foreground\">{t(\"The application reports no budget and no spend for the current period.\")}</p>\n </CardContent>\n </Card>\n );\n }\n const periodText =\n budgets?.periodFrom !== null && budgets?.periodFrom !== undefined\n ? budgets.periodTo !== null && budgets.periodTo !== undefined\n ? t(\"Period: %from% to %to%\", { replacements: { from: formatDate(budgets.periodFrom), to: formatDate(budgets.periodTo) } })\n : t(\"Period: since %from%\", { replacements: { from: formatDate(budgets.periodFrom) } })\n : null;\n return (\n <div data-slot=\"agent-budgets-tab\" className=\"space-y-4\">\n {!views.hasCaps && (\n <StatusCallout tone=\"info\" size=\"compact\" title={t(\"No spending cap is set.\")} description={t(\"The figures show what was spent in the period. An account's bar is its share of the total spend.\")} />\n )}\n <div className=\"grid items-start gap-4 xl:grid-cols-2\">\n <Card className=\"gap-0 py-0\">\n <CardContent className=\"px-5 py-4\">\n <h3 className=\"text-base font-semibold\">{t(\"Budgets\", { context: \"agent-budget\" })}</h3>\n {periodText !== null && <p className=\"text-sm text-muted-foreground\">{periodText}</p>}\n <ul className=\"divide-y divide-border\">\n {views.general.map((meter) => (\n <BudgetMeterRow key={meter.key} meter={meter} linkComponent={linkComponent} buildAccountHref={buildAccountHref} />\n ))}\n </ul>\n </CardContent>\n </Card>\n <Card className=\"gap-0 py-0\">\n <CardContent className=\"px-5 py-4\">\n <h3 className=\"text-base font-semibold\">{t(\"Accounts by spend\")}</h3>\n {views.accounts.length === 0 ? (\n <p className=\"py-4 text-sm text-muted-foreground\">{t(\"No account spent anything in this period.\")}</p>\n ) : (\n <ul className=\"divide-y divide-border\">\n {views.accounts.map((meter) => (\n <BudgetMeterRow key={meter.key} meter={meter} linkComponent={linkComponent} buildAccountHref={buildAccountHref} />\n ))}\n </ul>\n )}\n </CardContent>\n </Card>\n </div>\n </div>\n );\n};\n","import { AGENT_RUNTIME_SETTING_NAMES, type AgentRuntimeSettingName, type AgentRuntimeSettingsValues } from \"./agent-control-panel-types\";\n\n/** The six settings with every value named: a string, a number, a boolean, or null for \"uses the default\". */\nexport type RuntimeSettingsFormValues = Required<{ [Name in AgentRuntimeSettingName]: NonNullable<AgentRuntimeSettingsValues[Name]> | null }>;\n\n/** One value of the form. */\nexport type RuntimeSettingValue = string | number | boolean | null;\n\nconst TEXT_SETTING_NAMES: readonly AgentRuntimeSettingName[] = [\"defaultModelName\", \"defaultReasoningEffort\", \"reasoningEffortCeiling\"];\n\n/** The form values of stored settings: an absent value and an empty text are \"uses the default\" (null). */\nexport const runtimeSettingsFormValuesOf = (values: AgentRuntimeSettingsValues | null | undefined): RuntimeSettingsFormValues => {\n const textOf = (value: string | null | undefined): string | null => (typeof value === \"string\" && value.trim() !== \"\" ? value.trim() : null);\n return {\n defaultModelName: textOf(values?.defaultModelName),\n defaultReasoningEffort: textOf(values?.defaultReasoningEffort),\n reasoningEffortCeiling: textOf(values?.reasoningEffortCeiling),\n compactionTriggerTokens: typeof values?.compactionTriggerTokens === \"number\" && Number.isFinite(values.compactionTriggerTokens) ? values.compactionTriggerTokens : null,\n storeRequestSnapshot: typeof values?.storeRequestSnapshot === \"boolean\" ? values.storeRequestSnapshot : null,\n decisionModelEnabled: typeof values?.decisionModelEnabled === \"boolean\" ? values.decisionModelEnabled : null,\n };\n};\n\n/** Whether a setting has no value of its own, so the package's or the configuration's default applies. */\nexport const usesRuntimeSettingDefault = (values: RuntimeSettingsFormValues, name: AgentRuntimeSettingName): boolean => values[name] === null;\n\n/** One setting that differs between the stored values and the form. */\nexport interface RuntimeSettingChangeEntry {\n name: AgentRuntimeSettingName;\n /** The stored value; null = the default applied. */\n from: RuntimeSettingValue;\n /** The value to store; null = back to the default. */\n to: RuntimeSettingValue;\n}\n\n/** The settings whose form value differs from the stored one, in display order. */\nexport const diffRuntimeSettings = (stored: RuntimeSettingsFormValues, edited: RuntimeSettingsFormValues): RuntimeSettingChangeEntry[] =>\n AGENT_RUNTIME_SETTING_NAMES.filter((name) => stored[name] !== edited[name]).map((name) => ({ name, from: stored[name], to: edited[name] }));\n\n/** What stops a save: a compaction trigger that is no whole number or lies outside the allowed range. */\nexport type RuntimeSettingsProblem = \"compactionTriggerNotWhole\" | \"compactionTriggerTooSmall\" | \"compactionTriggerTooLarge\" | \"effortAboveCeiling\";\n\nexport interface RuntimeSettingsLimits {\n minCompactionTriggerTokens?: number;\n maxCompactionTriggerTokens?: number;\n /** The efforts in rising order (`low`, `medium`, `high`). */\n selectableReasoningEfforts?: readonly string[] | null;\n}\n\n/** The problems of the form values, by setting; empty = the values can be stored. */\nexport const validateRuntimeSettings = (values: RuntimeSettingsFormValues, limits: RuntimeSettingsLimits): Partial<Record<AgentRuntimeSettingName, RuntimeSettingsProblem>> => {\n const problems: Partial<Record<AgentRuntimeSettingName, RuntimeSettingsProblem>> = {};\n const trigger = values.compactionTriggerTokens;\n if (trigger !== null) {\n if (!Number.isInteger(trigger)) problems.compactionTriggerTokens = \"compactionTriggerNotWhole\";\n else if (limits.minCompactionTriggerTokens !== undefined && trigger < limits.minCompactionTriggerTokens) problems.compactionTriggerTokens = \"compactionTriggerTooSmall\";\n else if (limits.maxCompactionTriggerTokens !== undefined && trigger > limits.maxCompactionTriggerTokens) problems.compactionTriggerTokens = \"compactionTriggerTooLarge\";\n }\n const efforts = limits.selectableReasoningEfforts ?? [];\n const defaultPosition = values.defaultReasoningEffort !== null ? efforts.indexOf(values.defaultReasoningEffort) : -1;\n const ceilingPosition = values.reasoningEffortCeiling !== null ? efforts.indexOf(values.reasoningEffortCeiling) : -1;\n if (defaultPosition >= 0 && ceilingPosition >= 0 && defaultPosition > ceilingPosition) problems.defaultReasoningEffort = \"effortAboveCeiling\";\n return problems;\n};\n\n/** The digits of a typed compaction trigger as a number; null for an empty field, `NaN` for anything else. */\nexport const parseCompactionTriggerText = (text: string): number | null => {\n const trimmed = text.trim();\n if (trimmed === \"\") return null;\n return /^\\d+$/.test(trimmed) ? Number(trimmed) : Number.NaN;\n};\n\n/**\n * A value as the change log stores it (`AgentRuntimeSettingsValues::getValueAsText`): `true` / `false` for a switch,\n * the text of everything else, null for \"uses the default\".\n */\nexport const runtimeSettingValueAsText = (value: RuntimeSettingValue | undefined): string | null => {\n if (value === null || value === undefined || value === \"\") return null;\n return typeof value === \"boolean\" ? (value ? \"true\" : \"false\") : String(value);\n};\n\n/** Whether a setting is a switch (its change-log text is `true` or `false`). */\nexport const isRuntimeSettingSwitch = (name: string): boolean => name === \"storeRequestSnapshot\" || name === \"decisionModelEnabled\";\n\n/** Whether a name is one of the six settings. */\nexport const isRuntimeSettingName = (name: string | null | undefined): name is AgentRuntimeSettingName => AGENT_RUNTIME_SETTING_NAMES.includes(name as AgentRuntimeSettingName);\n\n/** Whether a setting holds a text (a model name, an effort). */\nexport const isRuntimeSettingText = (name: AgentRuntimeSettingName): boolean => TEXT_SETTING_NAMES.includes(name);\n","import { normalizeDddError } from \"@mgamadeus/ddd-web/contract\";\nimport { formatUiNumber, m, useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { DateCell } from \"@mgamadeus/ddd-admin-ui/list\";\nimport { notify } from \"@mgamadeus/ddd-admin-ui/logic\";\nimport { StatusCallout } from \"@mgamadeus/ddd-admin-ui/page\";\nimport {\n Badge,\n Button,\n Card,\n CardContent,\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n Input,\n type PageLinkComponent,\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n Skeleton,\n Switch,\n} from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { ArrowRight, RotateCcw } from \"lucide-react\";\nimport { type ReactNode, useEffect, useId, useMemo, useState } from \"react\";\nimport { AdminHrefLink } from \"../shared/AdminHrefLink\";\nimport { wireCreatedTimeOf, wireElementsOf } from \"../wire/admin-wire\";\nimport type { AgentControlPanelApi } from \"./agent-control-panel-api\";\nimport type { AgentRuntimeSettingChange, AgentRuntimeSettingName, AgentRuntimeSettingsResponse } from \"./agent-control-panel-types\";\nimport {\n diffRuntimeSettings,\n isRuntimeSettingName,\n isRuntimeSettingSwitch,\n parseCompactionTriggerText,\n type RuntimeSettingChangeEntry,\n type RuntimeSettingsFormValues,\n runtimeSettingsFormValuesOf,\n type RuntimeSettingsProblem,\n runtimeSettingValueAsText,\n validateRuntimeSettings,\n} from \"./runtime-settings-form\";\n\nexport interface SettingsTabProps {\n api: Pick<AgentControlPanelApi, \"useRuntimeSettingsQuery\" | \"useUpdateRuntimeSettingsMutation\">;\n /** False: the form is shown, the save is off. Default true. */\n writesAllowed?: boolean;\n /** Why writes are off, shown beside the save button; already translated. */\n writesBlockedReason?: ReactNode;\n linkComponent?: PageLinkComponent;\n buildAccountHref?: (accountId: number) => string | null;\n /** The host's display name of a model by its catalog name; null = the catalog name. */\n describeModelName?: (modelName: string) => string | null;\n /** The host's words for the environment (its name and the server's English label); null = the label as sent. */\n describeEnvironment?: (environment: string, environmentLabel: string | null) => string | null;\n}\n\n/** The select value that stands for \"uses the default\" (a select cannot hold an empty value). */\nconst DEFAULT_OPTION = \"__default__\";\n\nconst SETTING_LABELS: Readonly<Record<AgentRuntimeSettingName, string>> = {\n defaultModelName: m(\"Default model\"),\n defaultReasoningEffort: m(\"Default effort\"),\n reasoningEffortCeiling: m(\"Effort ceiling\"),\n compactionTriggerTokens: m(\"Compaction trigger\"),\n storeRequestSnapshot: m(\"Store sent requests\"),\n decisionModelEnabled: m(\"Decision model\"),\n};\n\nconst SETTING_HINTS: Readonly<Record<AgentRuntimeSettingName, string>> = {\n defaultModelName: m(\"The model a new conversation runs on, unless one was picked for it.\"),\n defaultReasoningEffort: m(\"The effort a model call is sent with when nothing raises it.\"),\n reasoningEffortCeiling: m(\"The highest effort a model call may be sent with.\"),\n compactionTriggerTokens: m(\"The size of the working context, in tokens, at which a conversation summarises its older turns.\"),\n storeRequestSnapshot: m(\"Every model call keeps the full request as sent and the raw answer of the model, for the debug view.\"),\n decisionModelEnabled: m(\"The small decisions before a turn (language, preloading a skill, a direct widget). Off switches every decision site off.\"),\n};\n\nconst EFFORT_LABELS: Readonly<Record<string, string>> = {\n low: m(\"Low\", { context: \"agent-effort\" }),\n medium: m(\"Medium\", { context: \"agent-effort\" }),\n high: m(\"High\", { context: \"agent-effort\" }),\n};\n\nconst PROBLEM_TEXTS: Readonly<Record<RuntimeSettingsProblem, string>> = {\n compactionTriggerNotWhole: m(\"Enter a whole number of tokens.\"),\n compactionTriggerTooSmall: m(\"At least %tokens% tokens.\"),\n compactionTriggerTooLarge: m(\"At most %tokens% tokens.\"),\n effortAboveCeiling: m(\"The default effort lies above the ceiling.\"),\n};\n\n/** How one stored value shows: a switch as On / Off, an effort by its name, the rest as text. */\nconst useSettingValueText = (describeModelName?: (modelName: string) => string | null) => {\n const { t } = useTranslate();\n return (name: string, valueText: string | null): string => {\n if (valueText === null || valueText === \"\") return t(\"Default\", { context: \"agent-setting-value\" });\n if (name === \"defaultModelName\") return describeModelName?.(valueText) ?? valueText;\n if (isRuntimeSettingSwitch(name)) return valueText === \"true\" ? t(\"On\", { context: \"agent-setting-value\" }) : t(\"Off\", { context: \"agent-setting-value\" });\n if (name === \"defaultReasoningEffort\" || name === \"reasoningEffortCeiling\") return EFFORT_LABELS[valueText] !== undefined ? t(EFFORT_LABELS[valueText], { context: \"agent-effort\" }) : valueText;\n if (name === \"compactionTriggerTokens\" && /^\\d+$/.test(valueText)) return formatUiNumber(Number(valueText));\n return valueText;\n };\n};\n\ninterface SettingRowProps {\n name: AgentRuntimeSettingName;\n /** The control's id, for the label. */\n controlId: string;\n usesDefault: boolean;\n /** What applies while the setting uses its default, as text; null = not known. */\n defaultText: string | null;\n onReset: () => void;\n isResetDisabled: boolean;\n problem?: string;\n extraHint?: ReactNode;\n children: ReactNode;\n}\n\nconst SettingRow = ({ name, controlId, usesDefault, defaultText, onReset, isResetDisabled, problem, extraHint, children }: SettingRowProps) => {\n const { t } = useTranslate();\n return (\n <div data-slot=\"runtime-setting\" data-setting={name} className=\"grid gap-x-8 gap-y-2 py-4 md:grid-cols-[minmax(0,1fr)_minmax(0,22rem)]\">\n <div className=\"min-w-0\">\n <label htmlFor={controlId} className=\"text-sm font-semibold\">\n {t(SETTING_LABELS[name])}\n </label>\n <p className=\"text-sm text-muted-foreground\">{t(SETTING_HINTS[name])}</p>\n {extraHint}\n </div>\n <div className=\"min-w-0 space-y-1.5\">\n {children}\n {problem !== undefined && (\n <p role=\"alert\" className=\"text-xs text-destructive\">\n {problem}\n </p>\n )}\n <div className=\"flex min-h-6 flex-wrap items-center gap-x-2 text-xs text-muted-foreground\">\n {usesDefault ? (\n <span data-slot=\"runtime-setting-default\">{defaultText !== null ? t(\"Uses the default: %value%\", { replacements: { value: defaultText } }) : t(\"Uses the default\")}</span>\n ) : (\n <>\n {defaultText !== null && <span>{t(\"Default: %value%\", { replacements: { value: defaultText } })}</span>}\n <Button type=\"button\" variant=\"ghost\" size=\"xs\" disabled={isResetDisabled} onClick={onReset} data-slot=\"runtime-setting-reset\">\n <RotateCcw aria-hidden />\n {t(\"Use the default\")}\n </Button>\n </>\n )}\n </div>\n </div>\n </div>\n );\n};\n\ninterface RecentChangesCardProps extends Pick<SettingsTabProps, \"linkComponent\" | \"buildAccountHref\" | \"describeModelName\"> {\n changes: readonly AgentRuntimeSettingChange[];\n}\n\nconst RecentChangesCard = ({ changes, linkComponent, buildAccountHref, describeModelName }: RecentChangesCardProps) => {\n const { t } = useTranslate();\n const valueText = useSettingValueText(describeModelName);\n return (\n <Card data-slot=\"runtime-setting-changes\" className=\"gap-0 py-0\">\n <CardContent className=\"px-5 py-4\">\n <h3 className=\"text-base font-semibold\">{t(\"Recent changes\")}</h3>\n {changes.length === 0 ? (\n <p className=\"py-4 text-sm text-muted-foreground\">{t(\"No setting was changed yet.\")}</p>\n ) : (\n <ul className=\"divide-y divide-border\">\n {changes.map((change, index) => {\n const name = change.settingName ?? \"\";\n const accountId = change.changedByAccountId ?? null;\n return (\n <li key={change.id ?? index} data-slot=\"runtime-setting-change\" className=\"flex flex-wrap items-center gap-x-3 gap-y-1 py-2.5 text-sm\">\n <span className=\"min-w-40 font-medium\">{isRuntimeSettingName(name) ? t(SETTING_LABELS[name]) : name}</span>\n <span className=\"inline-flex min-w-0 flex-1 flex-wrap items-center gap-1.5\">\n <span className=\"font-mono text-xs text-muted-foreground\">{valueText(name, change.oldValue ?? null)}</span>\n <ArrowRight aria-hidden className=\"size-3.5 shrink-0 text-muted-foreground\" />\n <span className=\"font-mono text-xs font-semibold\">{valueText(name, change.newValue ?? null)}</span>\n </span>\n <span className=\"text-xs text-muted-foreground\">\n {accountId === null ? (\n t(\"without a signed-in account\")\n ) : (\n <AdminHrefLink href={buildAccountHref?.(accountId) ?? null} linkComponent={linkComponent}>\n {t(\"Account #%id%\", { replacements: { id: String(accountId) } })}\n </AdminHrefLink>\n )}\n </span>\n <DateCell value={wireCreatedTimeOf(change)} className=\"text-xs text-muted-foreground\" />\n </li>\n );\n })}\n </ul>\n )}\n </CardContent>\n </Card>\n );\n};\n\nconst defaultTextOf = (response: AgentRuntimeSettingsResponse, name: AgentRuntimeSettingName, valueText: (name: string, valueText: string | null) => string): string | null => {\n const text = runtimeSettingValueAsText(response.effectiveDefaults?.[name]);\n return text === null ? null : valueText(name, text);\n};\n\n/**\n * The runtime settings of the current environment: a form of the six settings (each shows what applies while it has\n * no value of its own, and goes back to that with \"Use the default\"), a save that names what changes and that only\n * new conversations take it, and the newest recorded changes.\n */\nexport const SettingsTab = ({ api, writesAllowed = true, writesBlockedReason, linkComponent, buildAccountHref, describeModelName, describeEnvironment }: SettingsTabProps) => {\n const { t } = useTranslate();\n const valueText = useSettingValueText(describeModelName);\n const idPrefix = useId();\n const query = api.useRuntimeSettingsQuery();\n const [updateSettings, updateState] = api.useUpdateRuntimeSettingsMutation();\n const response = query.data ?? null;\n // the host's words first, then the application's label, else the name conversations are stamped with\n const environmentLabel = typeof response?.environmentLabel === \"string\" && response.environmentLabel !== \"\" ? response.environmentLabel : null;\n const environmentText = describeEnvironment?.(response?.environment ?? \"\", environmentLabel) ?? environmentLabel ?? response?.environment ?? \"\";\n const stored = useMemo(() => runtimeSettingsFormValuesOf(response?.settings), [response]);\n const [edited, setEdited] = useState<RuntimeSettingsFormValues>(stored);\n const [triggerText, setTriggerText] = useState(stored.compactionTriggerTokens === null ? \"\" : String(stored.compactionTriggerTokens));\n const [isConfirmOpen, setIsConfirmOpen] = useState(false);\n const [saveError, setSaveError] = useState<string | null>(null);\n\n // the form follows the stored values whenever they arrive anew (first load, after a save, a refetch)\n // (keyed by the values, not the object: a host hook may answer a new object of the same values on every render)\n const storedKey = JSON.stringify(stored);\n useEffect(() => {\n const next = JSON.parse(storedKey) as RuntimeSettingsFormValues;\n setEdited(next);\n setTriggerText(next.compactionTriggerTokens === null ? \"\" : String(next.compactionTriggerTokens));\n }, [storedKey]);\n\n if (query.isLoading) {\n return (\n <div className=\"space-y-4\">\n <Skeleton className=\"h-96 w-full rounded-2xl\" />\n <Skeleton className=\"h-40 w-full rounded-2xl\" />\n </div>\n );\n }\n if (query.isError || response === null) {\n return <StatusCallout tone=\"destructive\" title={t(\"The settings could not be loaded.\")} description={query.isError ? normalizeDddError(query.error, \"\").message : undefined} />;\n }\n\n const isTableAvailable = response.isSettingsTableAvailable !== false;\n const changes = diffRuntimeSettings(stored, edited);\n const problems = validateRuntimeSettings(edited, response);\n const problemTextOf = (name: AgentRuntimeSettingName): string | undefined => {\n const problem = problems[name];\n if (problem === undefined) return undefined;\n const limit = problem === \"compactionTriggerTooSmall\" ? response.minCompactionTriggerTokens : problem === \"compactionTriggerTooLarge\" ? response.maxCompactionTriggerTokens : undefined;\n return t(PROBLEM_TEXTS[problem], { replacements: { tokens: limit !== undefined ? formatUiNumber(limit) : \"\" } });\n };\n const hasProblems = Object.keys(problems).length > 0;\n const isFormDisabled = !isTableAvailable || updateState.isLoading;\n const canSave = writesAllowed && isTableAvailable && changes.length > 0 && !hasProblems && !updateState.isLoading;\n const setValue = <TName extends AgentRuntimeSettingName>(name: TName, value: RuntimeSettingsFormValues[TName]) => setEdited((current) => ({ ...current, [name]: value }));\n const modelNames = [...new Set([...(response.selectableModelNames ?? []), ...(edited.defaultModelName !== null ? [edited.defaultModelName] : [])])];\n const efforts = response.selectableReasoningEfforts ?? [];\n const effortLabelOf = (effort: string) => (EFFORT_LABELS[effort] !== undefined ? t(EFFORT_LABELS[effort], { context: \"agent-effort\" }) : effort);\n const defaultOptionLabelOf = (name: AgentRuntimeSettingName) => {\n const text = defaultTextOf(response, name, valueText);\n return text !== null ? t(\"Default (%value%)\", { replacements: { value: text } }) : t(\"Default\", { context: \"agent-setting-value\" });\n };\n const rowPropsOf = (name: AgentRuntimeSettingName) => ({\n name,\n controlId: `${idPrefix}-${name}`,\n usesDefault: edited[name] === null,\n defaultText: defaultTextOf(response, name, valueText),\n isResetDisabled: isFormDisabled,\n problem: problemTextOf(name),\n });\n const switchValueOf = (name: \"storeRequestSnapshot\" | \"decisionModelEnabled\"): boolean => edited[name] ?? response.effectiveDefaults?.[name] ?? (name === \"decisionModelEnabled\");\n\n const save = async () => {\n setSaveError(null);\n try {\n await updateSettings(edited).unwrap();\n setIsConfirmOpen(false);\n notify.success(t(\"The settings were saved.\"));\n } catch (error) {\n setSaveError(normalizeDddError(error, t(\"The settings could not be saved.\")).message);\n }\n };\n const changeLineOf = (change: RuntimeSettingChangeEntry) => (\n <li key={change.name} data-slot=\"runtime-setting-pending-change\" className=\"flex flex-wrap items-center gap-x-2 gap-y-0.5 py-1.5 text-sm\">\n <span className=\"min-w-36 font-medium text-foreground\">{t(SETTING_LABELS[change.name])}</span>\n <span className=\"font-mono text-xs text-muted-foreground\">{valueText(change.name, runtimeSettingValueAsText(change.from))}</span>\n <ArrowRight aria-hidden className=\"size-3.5 shrink-0 text-muted-foreground\" />\n <span className=\"font-mono text-xs font-semibold text-foreground\">{valueText(change.name, runtimeSettingValueAsText(change.to))}</span>\n </li>\n );\n\n return (\n <div data-slot=\"agent-settings-tab\" className=\"space-y-4\">\n {!isTableAvailable && (\n <StatusCallout\n tone=\"warning\"\n title={t(\"This installation has no runtime settings table.\")}\n description={t(\"The defaults of the package and the configuration apply. Settings cannot be stored until the table exists.\")}\n />\n )}\n <Card className=\"gap-0 py-0\">\n <CardContent className=\"px-5 py-2\">\n <div className=\"flex flex-wrap items-center gap-2 border-b border-border py-3\">\n <h3 className=\"text-base font-semibold\">{t(\"Runtime settings\")}</h3>\n {environmentText !== \"\" && (\n <Badge variant=\"secondary\" data-slot=\"runtime-settings-environment\" title={response.environment} className={environmentText === response.environment ? \"font-mono text-[11px]\" : \"text-[11px]\"}>\n {environmentText}\n </Badge>\n )}\n <span className=\"text-sm text-muted-foreground\">{t(\"They apply to conversations created after a change. A running conversation keeps the settings it was created with.\")}</span>\n </div>\n <div className=\"divide-y divide-border\">\n <SettingRow {...rowPropsOf(\"defaultModelName\")} onReset={() => setValue(\"defaultModelName\", null)}>\n <Select value={edited.defaultModelName ?? DEFAULT_OPTION} onValueChange={(value) => setValue(\"defaultModelName\", value === DEFAULT_OPTION ? null : value)} disabled={isFormDisabled}>\n <SelectTrigger id={`${idPrefix}-defaultModelName`} className=\"w-full\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n <SelectItem value={DEFAULT_OPTION}>{defaultOptionLabelOf(\"defaultModelName\")}</SelectItem>\n {modelNames.map((modelName) => (\n <SelectItem key={modelName} value={modelName}>\n {describeModelName?.(modelName) ?? modelName}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </SettingRow>\n {([\"defaultReasoningEffort\", \"reasoningEffortCeiling\"] as const).map((name) => (\n <SettingRow key={name} {...rowPropsOf(name)} onReset={() => setValue(name, null)}>\n <Select value={edited[name] ?? DEFAULT_OPTION} onValueChange={(value) => setValue(name, value === DEFAULT_OPTION ? null : value)} disabled={isFormDisabled}>\n <SelectTrigger id={`${idPrefix}-${name}`} className=\"w-full\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n <SelectItem value={DEFAULT_OPTION}>{defaultOptionLabelOf(name)}</SelectItem>\n {[...new Set([...efforts, ...(edited[name] !== null ? [edited[name] as string] : [])])].map((effort) => (\n <SelectItem key={effort} value={effort}>\n {effortLabelOf(effort)}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </SettingRow>\n ))}\n <SettingRow\n {...rowPropsOf(\"compactionTriggerTokens\")}\n defaultText={defaultTextOf(response, \"compactionTriggerTokens\", valueText) ?? t(\"the model's effective context\")}\n onReset={() => {\n setTriggerText(\"\");\n setValue(\"compactionTriggerTokens\", null);\n }}\n >\n <Input\n id={`${idPrefix}-compactionTriggerTokens`}\n type=\"text\"\n inputMode=\"numeric\"\n value={triggerText}\n disabled={isFormDisabled}\n aria-invalid={problems.compactionTriggerTokens !== undefined}\n placeholder={defaultTextOf(response, \"compactionTriggerTokens\", valueText) ?? t(\"the model's effective context\")}\n onChange={(event) => {\n setTriggerText(event.target.value);\n setValue(\"compactionTriggerTokens\", parseCompactionTriggerText(event.target.value));\n }}\n />\n {response.minCompactionTriggerTokens !== undefined && response.maxCompactionTriggerTokens !== undefined && (\n <p className=\"text-xs text-muted-foreground\">\n {t(\"Between %min% and %max% tokens.\", { replacements: { min: formatUiNumber(response.minCompactionTriggerTokens), max: formatUiNumber(response.maxCompactionTriggerTokens) } })}\n </p>\n )}\n </SettingRow>\n {([\"storeRequestSnapshot\", \"decisionModelEnabled\"] as const).map((name) => (\n <SettingRow\n key={name}\n {...rowPropsOf(name)}\n onReset={() => setValue(name, null)}\n extraHint={\n name === \"storeRequestSnapshot\" && typeof response.requestSnapshotRetentionDays === \"number\" ? (\n <p className=\"text-sm text-muted-foreground\">\n {t(\"{count, plural, one {Stored requests are removed after # day.} other {Stored requests are removed after # days.}}\", { count: response.requestSnapshotRetentionDays })}\n </p>\n ) : undefined\n }\n >\n <span className=\"flex items-center gap-2.5\">\n <Switch id={`${idPrefix}-${name}`} checked={switchValueOf(name)} onCheckedChange={(isChecked) => setValue(name, isChecked)} disabled={isFormDisabled} />\n <span className=\"text-sm\">{switchValueOf(name) ? t(\"On\", { context: \"agent-setting-value\" }) : t(\"Off\", { context: \"agent-setting-value\" })}</span>\n </span>\n </SettingRow>\n ))}\n </div>\n <div className=\"flex flex-wrap items-center justify-end gap-3 border-t border-border py-3\">\n <span data-slot=\"runtime-settings-state\" className=\"mr-auto text-sm text-muted-foreground\">\n {!writesAllowed\n ? (writesBlockedReason ?? t(\"Changes are switched off here.\"))\n : changes.length > 0\n ? t(\"{count, plural, one {# setting changed} other {# settings changed}}\", { count: changes.length })\n : t(\"No changes\")}\n </span>\n <Button type=\"button\" variant=\"outline\" disabled={changes.length === 0 || updateState.isLoading} onClick={() => {\n setEdited(stored);\n setTriggerText(stored.compactionTriggerTokens === null ? \"\" : String(stored.compactionTriggerTokens));\n }}>\n {t(\"Discard\")}\n </Button>\n <Button type=\"button\" data-slot=\"runtime-settings-save\" disabled={!canSave} onClick={() => setIsConfirmOpen(true)}>\n {t(\"Save settings\")}\n </Button>\n </div>\n </CardContent>\n </Card>\n\n <RecentChangesCard changes={wireElementsOf<AgentRuntimeSettingChange>(response.recentChanges)} linkComponent={linkComponent} buildAccountHref={buildAccountHref} describeModelName={describeModelName} />\n\n <Dialog\n open={isConfirmOpen}\n onOpenChange={(isOpen) => {\n if (!updateState.isLoading) {\n setIsConfirmOpen(isOpen);\n if (!isOpen) setSaveError(null);\n }\n }}\n >\n <DialogContent data-slot=\"runtime-settings-confirm\" className=\"sm:max-w-lg\">\n <DialogHeader>\n <DialogTitle>{t(\"Save the runtime settings?\")}</DialogTitle>\n <DialogDescription>\n {environmentText !== \"\"\n ? t(\"New conversations in %environment% take the settings from now on. A running conversation keeps the settings it was created with.\", { replacements: { environment: environmentText } })\n : t(\"New conversations take the settings from now on. A running conversation keeps the settings it was created with.\")}\n </DialogDescription>\n </DialogHeader>\n <ul className=\"divide-y divide-border rounded-lg border border-border px-3\">{changes.map(changeLineOf)}</ul>\n {saveError !== null && <StatusCallout size=\"compact\" tone=\"destructive\" title={saveError} />}\n <DialogFooter>\n <Button type=\"button\" variant=\"outline\" disabled={updateState.isLoading} onClick={() => setIsConfirmOpen(false)}>\n {t(\"Cancel\")}\n </Button>\n <Button type=\"button\" data-slot=\"runtime-settings-confirm-save\" disabled={updateState.isLoading || !canSave} onClick={() => void save()}>\n {updateState.isLoading ? t(\"Saving…\") : t(\"Save settings\")}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n </div>\n );\n};\n","import { normalizeDddError } from \"@mgamadeus/ddd-web/contract\";\nimport { formatUiNumber, useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { DateCell } from \"@mgamadeus/ddd-admin-ui/list\";\nimport { StatusCallout } from \"@mgamadeus/ddd-admin-ui/page\";\nimport { Badge, Card, CardContent, cn, type PageLinkComponent, Skeleton, Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport type { AdminPeriod } from \"../period/admin-period\";\nimport { AdminHrefLink } from \"../shared/AdminHrefLink\";\nimport { wireElementsOf } from \"../wire/admin-wire\";\nimport type { AgentControlPanelApi } from \"./agent-control-panel-api\";\nimport type { AgentControlPanelSpace } from \"./agent-control-panel-types\";\n\nexport interface SpacesTabProps {\n api: Pick<AgentControlPanelApi, \"useControlPanelSpacesQuery\">;\n period: AdminPeriod;\n /** How many spaces are listed, the busiest first (default 100, at most 200). */\n limit?: number;\n linkComponent?: PageLinkComponent;\n /** The host's screen of a space (the record behind it); `null` = no link. */\n buildSpaceHref?: (space: AgentControlPanelSpace) => string | null;\n buildAccountHref?: (accountId: number) => string | null;\n /** The host's name of a kind of space; default the kind as sent. Already translated. */\n describeSpaceKind?: (kind: string) => string;\n /** The host's name of a space when the label the server sends is its own English words; null = the label. Already translated. */\n describeSpaceLabel?: (space: AgentControlPanelSpace) => string | null;\n}\n\n/**\n * The agent spaces conversations were started for in a period, the busiest first: the label and kind the application\n * gives a space, its owner, its time zone, the conversations of the period (with a bar against the busiest space) and\n * when the newest one started. The line without a space counts the conversations at account level.\n */\nexport const SpacesTab = ({ api, period, limit = 100, linkComponent, buildSpaceHref, buildAccountHref, describeSpaceKind, describeSpaceLabel }: SpacesTabProps) => {\n const { t } = useTranslate();\n const query = api.useControlPanelSpacesQuery({ from: period.from, to: period.to, limit });\n const spaces = query.data?.spaces == null ? null : wireElementsOf(query.data.spaces);\n if (query.isLoading || (spaces === null && query.isFetching)) return <Skeleton className=\"h-72 w-full rounded-2xl\" />;\n if (query.isError || spaces === null) {\n return <StatusCallout tone=\"destructive\" title={t(\"The agent spaces could not be loaded.\")} description={query.isError ? normalizeDddError(query.error, \"\").message : undefined} />;\n }\n const busiest = spaces.reduce((largest, space) => Math.max(largest, space.conversationCount ?? 0), 0);\n return (\n <Card data-slot=\"agent-spaces-tab\" className={cn(\"gap-0 py-0 transition-opacity motion-reduce:transition-none\", query.isFetching && \"opacity-80\")}>\n <CardContent className=\"px-2 py-4\">\n <div className=\"px-3 pb-2\">\n <h3 className=\"text-base font-semibold\">{t(\"Agent spaces\")}</h3>\n <p className=\"text-sm text-muted-foreground\">{t(\"Where conversations were started in the period, the busiest first.\")}</p>\n </div>\n {spaces.length === 0 ? (\n <p className=\"px-3 py-8 text-center text-sm text-muted-foreground\">{t(\"No conversation was started in this period.\")}</p>\n ) : (\n <Table>\n <TableHeader>\n <TableRow className=\"hover:bg-transparent\">\n <TableHead className=\"px-3 text-xs text-muted-foreground\">{t(\"Space\", { context: \"agent-space\" })}</TableHead>\n <TableHead className=\"px-3 text-xs text-muted-foreground\">{t(\"Kind\", { context: \"agent-space\" })}</TableHead>\n <TableHead className=\"px-3 text-xs text-muted-foreground\">{t(\"Owner\", { context: \"agent-space\" })}</TableHead>\n <TableHead className=\"px-3 text-xs text-muted-foreground\">{t(\"Time zone\")}</TableHead>\n <TableHead className=\"px-3 text-right text-xs text-muted-foreground\">{t(\"Conversations\", { context: \"agent-statistics\" })}</TableHead>\n <TableHead className=\"px-3 text-xs text-muted-foreground\">{t(\"Newest conversation\")}</TableHead>\n </TableRow>\n </TableHeader>\n <TableBody>\n {spaces.map((space) => {\n const spaceId = space.agentSpaceId ?? null;\n const ownerAccountId = space.ownerAccountId ?? null;\n const label =\n spaceId === null\n ? t(\"Account level (no space)\")\n : (describeSpaceLabel?.(space) ?? (space.label !== undefined && space.label !== \"\" ? space.label : `#${spaceId}`));\n const count = space.conversationCount ?? 0;\n return (\n <TableRow key={spaceId ?? \"account\"} data-space={spaceId ?? \"account\"} className=\"hover:bg-transparent\">\n <TableCell className=\"max-w-80 px-3 py-2.5 whitespace-normal\">\n <AdminHrefLink href={spaceId === null ? null : (buildSpaceHref?.(space) ?? null)} linkComponent={linkComponent} className=\"text-sm font-medium break-words\">\n {label}\n </AdminHrefLink>\n {spaceId !== null && <div className=\"font-mono text-xs text-muted-foreground\">#{spaceId}</div>}\n </TableCell>\n <TableCell className=\"px-3 py-2.5\">\n {typeof space.kind === \"string\" && space.kind !== \"\" ? (\n <Badge variant=\"secondary\" className=\"text-[11px]\">\n {describeSpaceKind?.(space.kind) ?? space.kind}\n </Badge>\n ) : (\n <span className=\"text-muted-foreground\">–</span>\n )}\n </TableCell>\n <TableCell className=\"px-3 py-2.5 text-sm\">\n {ownerAccountId === null ? (\n <span className=\"text-muted-foreground\">–</span>\n ) : (\n <AdminHrefLink href={buildAccountHref?.(ownerAccountId) ?? null} linkComponent={linkComponent}>\n {typeof space.ownerLabel === \"string\" && space.ownerLabel !== \"\" ? space.ownerLabel : t(\"Account #%id%\", { replacements: { id: String(ownerAccountId) } })}\n </AdminHrefLink>\n )}\n </TableCell>\n <TableCell className=\"px-3 py-2.5 text-sm text-muted-foreground\">{space.timezone ?? \"–\"}</TableCell>\n <TableCell className=\"w-40 px-3 py-2.5 text-right\">\n <span className=\"font-semibold tabular-nums\">{formatUiNumber(count)}</span>\n <span aria-hidden className=\"mt-1 ml-auto block h-1 rounded-full bg-[color:var(--series-1,var(--brand))]\" style={{ width: `${busiest > 0 ? Math.max(3, (count / busiest) * 100) : 0}%` }} />\n </TableCell>\n <TableCell className=\"px-3 py-2.5\">\n <DateCell value={space.newestConversationAt} />\n </TableCell>\n </TableRow>\n );\n })}\n </TableBody>\n </Table>\n )}\n </CardContent>\n </Card>\n );\n};\n","import type { ReactNode } from \"react\";\nimport type { SeriesFillSlot } from \"../blocks/series-fill-classes\";\nimport type { AdminPeriodGranularity } from \"../period/admin-period\";\n\n/**\n * The colour of a series slot as a CSS value, for a chart library that takes colours as values: the host's categorical\n * series property, with the colour role the fill classes fall back to.\n */\nexport const AGENT_SERIES_COLOR_VALUES: Readonly<Record<SeriesFillSlot, string>> = {\n series1: \"var(--series-1, var(--brand))\",\n series2: \"var(--series-2, var(--warning))\",\n series3: \"var(--series-3, var(--primary))\",\n series4: \"var(--series-4, var(--warning))\",\n series5: \"var(--series-5, var(--destructive))\",\n series6: \"var(--series-6, var(--success))\",\n series7: \"var(--series-7, var(--info))\",\n series8: \"var(--series-8, var(--destructive))\",\n neutral: \"var(--muted-foreground)\",\n ink: \"var(--foreground)\",\n};\n\n/** One series of a time-series chart: its values along the chart's buckets. */\nexport interface AgentTimeSeriesChartSeries {\n key: string;\n /** Already translated. */\n label: string;\n /** The slot of the categorical palette the series keeps on every chart. */\n colorSlot: SeriesFillSlot;\n /** The slot's colour as a CSS value (`AGENT_SERIES_COLOR_VALUES`). */\n color: string;\n /** One value per bucket, in the order of `buckets`. */\n values: readonly number[];\n total: number;\n}\n\n/** What a chart implementation of the host gets (`renderTimeSeriesChart`). */\nexport interface AgentTimeSeriesChartProps {\n /** Which chart of the screen this is: `cost`, `tokens`, `conversations` or `activeAccounts`. */\n chartId: string;\n /** Accessible name of the chart, already translated. */\n ariaLabel: string;\n /** The bucket keys in order (`YYYY-MM-DD`; with weekly buckets each week's Monday). */\n buckets: readonly string[];\n granularity: AdminPeriodGranularity;\n series: readonly AgentTimeSeriesChartSeries[];\n /** `bar`: the series of a bucket stacked into one bar (parts of a sum). `line`: one line per series on one axis. */\n kind: \"bar\" | \"line\";\n /** A value in full, for a tooltip (`$1.92`, `12,400`). */\n formatValue: (value: number) => string;\n /** A value on the axis, short (`$2`, `12k`). */\n formatAxisValue: (value: number) => string;\n /** A bucket on the axis (`15 Nov`). */\n formatBucket: (bucket: string) => string;\n /** A bucket in a tooltip (`Sat, 15 Nov 2026`, or the week it starts). */\n formatBucketTitle: (bucket: string) => string;\n /** The label of the sum of a stacked bucket, already translated. */\n totalLabel: string;\n /** The height of the plot in px. */\n height: number;\n /** True: the values are counts, so an axis shows no fractions. */\n isWholeNumbers?: boolean;\n}\n\n/** Draws a time-series chart with the host's chart library; the package's own bars are the fallback. */\nexport type AgentTimeSeriesChartRenderer = (props: AgentTimeSeriesChartProps) => ReactNode;\n\n/** The largest stacked sum (bars) or single value (lines) of a chart; 0 for an empty chart. */\nexport const timeSeriesChartMaximumOf = (series: readonly Pick<AgentTimeSeriesChartSeries, \"values\">[], bucketCount: number, kind: \"bar\" | \"line\"): number => {\n let maximum = 0;\n for (let index = 0; index < bucketCount; index += 1) {\n const values = series.map((item) => Math.max(0, item.values[index] ?? 0));\n const value = kind === \"bar\" ? values.reduce((sum, item) => sum + item, 0) : Math.max(0, ...values);\n if (value > maximum) maximum = value;\n }\n return maximum;\n};\n\n/** The positions of the buckets an axis labels when there is room for about `maximumLabels`: the first, the last, and even steps between. */\nexport const timeSeriesAxisLabelPositions = (bucketCount: number, maximumLabels = 7): number[] => {\n if (bucketCount <= 0) return [];\n if (bucketCount <= maximumLabels) return Array.from({ length: bucketCount }, (_, index) => index);\n const step = (bucketCount - 1) / (maximumLabels - 1);\n return [...new Set(Array.from({ length: maximumLabels }, (_, index) => Math.round(index * step)))];\n};\n","import { useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { Card, CardContent, cn, Skeleton, Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { ChartNoAxesColumn } from \"lucide-react\";\nimport type { ReactNode } from \"react\";\nimport { Disclosure } from \"../blocks/Disclosure\";\nimport { seriesFillClassNameOf } from \"../blocks/series-fill-classes\";\nimport { type AgentTimeSeriesChartProps, type AgentTimeSeriesChartRenderer, timeSeriesAxisLabelPositions, timeSeriesChartMaximumOf } from \"./time-series-chart\";\n\n/**\n * The package's own drawing of a time-series chart, without a chart library: one column per bucket, the series of a\n * bucket stacked (`bar`) or side by side (`line`), scaled to the largest value; every column names its values in its\n * hover text. A host passes its chart library through `renderTimeSeriesChart` instead.\n */\nexport const TimeSeriesFallbackChart = ({ ariaLabel, buckets, series, kind, formatValue, formatBucket, formatBucketTitle, height }: AgentTimeSeriesChartProps) => {\n const maximum = timeSeriesChartMaximumOf(series, buckets.length, kind);\n const labelPositions = new Set(timeSeriesAxisLabelPositions(buckets.length));\n return (\n <div data-slot=\"time-series-fallback-chart\" role=\"img\" aria-label={ariaLabel}>\n <div className=\"flex items-end gap-1 border-b border-border\" style={{ height }}>\n {buckets.map((bucket, bucketIndex) => {\n const title = [formatBucketTitle(bucket), ...series.map((item) => `${item.label}: ${formatValue(item.values[bucketIndex] ?? 0)}`)].join(\"\\n\");\n return (\n <div\n key={bucket}\n title={title}\n className={cn(\"flex h-full min-w-0 flex-1 justify-center\", kind === \"bar\" ? \"flex-col-reverse items-center justify-start gap-0.5\" : \"items-end gap-px\")}\n >\n {series.map((item, seriesIndex) => {\n const value = Math.max(0, item.values[bucketIndex] ?? 0);\n if (value <= 0) return null;\n const isTopOfStack = kind === \"bar\" && series.slice(seriesIndex + 1).every((later) => (later.values[bucketIndex] ?? 0) <= 0);\n return (\n <span\n key={item.key}\n className={cn(\n \"block min-h-px\",\n seriesFillClassNameOf(item.colorSlot),\n kind === \"bar\" ? cn(\"w-full max-w-7\", isTopOfStack && \"rounded-t-[4px]\") : \"max-w-3 flex-1 rounded-t-[4px]\",\n )}\n style={{ height: `${maximum > 0 ? (value / maximum) * 100 : 0}%` }}\n />\n );\n })}\n </div>\n );\n })}\n </div>\n <div aria-hidden className=\"mt-1.5 flex gap-1 text-xs text-muted-foreground\">\n {buckets.map((bucket, bucketIndex) => (\n <span key={bucket} className=\"min-w-0 flex-1 overflow-visible text-center whitespace-nowrap\">\n {labelPositions.has(bucketIndex) ? formatBucket(bucket) : \"\"}\n </span>\n ))}\n </div>\n </div>\n );\n};\n\nexport interface TimeSeriesChartCardProps {\n title: ReactNode;\n /** One muted line under the title (what is counted, where the figures come from). */\n description?: ReactNode;\n chart: AgentTimeSeriesChartProps;\n /** The host's chart implementation; default the package's own bars. */\n renderChart?: AgentTimeSeriesChartRenderer;\n isLoading?: boolean;\n /** The text of the empty state, already translated. */\n emptyText: string;\n /** Under the chart (a footnote on the source of the figures). */\n footer?: ReactNode;\n /**\n * `false`: the legend names no total per series (a sum over the buckets that means nothing, like the accounts active\n * per day). A single series then shows no legend at all: the title names it. Default `true`.\n */\n showTotals?: boolean;\n /**\n * Where the legend stands: `beside` the title (a wide chart), or `below` it on a row of its own that keeps its\n * height when it is empty, so the plots of small charts beside each other start on one line. Default `beside`.\n */\n legendPlacement?: \"beside\" | \"below\";\n className?: string;\n}\n\n/**\n * One chart of the statistics in a card: the title, the legend with every series' total in the period (so a series is\n * never told by colour alone), the plot, and the same figures as a table that opens below.\n */\nexport const TimeSeriesChartCard = ({ title, description, chart, renderChart, isLoading = false, emptyText, footer, showTotals = true, legendPlacement = \"beside\", className }: TimeSeriesChartCardProps) => {\n const { t } = useTranslate();\n const isEmpty = !isLoading && (chart.buckets.length === 0 || chart.series.every((series) => series.total === 0));\n const showsLegend = chart.series.length > 1;\n // one series is named by the title: its entry is the sum alone, under the chart's word for a sum\n const legend =\n !isLoading && chart.series.length > 0 && (showsLegend || showTotals) ? (\n <ul data-slot=\"time-series-legend\" className=\"flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted-foreground\">\n {chart.series.map((series) => (\n <li key={series.key} className=\"flex items-center gap-1.5\">\n {showsLegend && <span aria-hidden className={cn(\"size-2.5 shrink-0 rounded-[3px]\", seriesFillClassNameOf(series.colorSlot))} />}\n <span className=\"text-foreground\">{showsLegend ? series.label : chart.totalLabel}</span>\n {showTotals && <span className=\"tabular-nums\">{chart.formatValue(series.total)}</span>}\n </li>\n ))}\n </ul>\n ) : null;\n return (\n <Card data-slot=\"time-series-chart-card\" data-chart={chart.chartId} className={cn(\"gap-0 py-0\", className)}>\n <CardContent className=\"space-y-3 px-5 py-4\">\n <div className=\"flex flex-wrap items-start justify-between gap-x-6 gap-y-2\">\n <div className=\"min-w-0\">\n <h3 className=\"text-base font-semibold\">{title}</h3>\n {description !== undefined && description !== null && <p className=\"text-sm text-muted-foreground\">{description}</p>}\n </div>\n {legendPlacement === \"beside\" && legend}\n </div>\n {legendPlacement === \"below\" && <div className=\"min-h-4\">{legend}</div>}\n <div style={{ minHeight: chart.height }}>\n {isLoading ? (\n <Skeleton className=\"w-full rounded-xl\" style={{ height: chart.height }} />\n ) : isEmpty ? (\n <div className=\"flex flex-col items-center justify-center gap-2 rounded-xl bg-tint text-center\" style={{ height: chart.height }}>\n <ChartNoAxesColumn aria-hidden className=\"size-5 text-muted-foreground\" />\n <p className=\"text-sm text-muted-foreground\">{emptyText}</p>\n </div>\n ) : (\n (renderChart ?? ((props) => <TimeSeriesFallbackChart {...props} />))(chart)\n )}\n </div>\n {footer}\n {!isLoading && !isEmpty && (\n <Disclosure size=\"sm\" title={t(\"Show as table\")}>\n <div className=\"max-h-72 overflow-auto\">\n <Table>\n <TableHeader>\n <TableRow className=\"hover:bg-transparent\">\n <TableHead className=\"text-xs text-muted-foreground\">{chart.granularity === \"WEEK\" ? t(\"Week from\") : t(\"Day\", { context: \"admin-period\" })}</TableHead>\n {chart.series.map((series) => (\n <TableHead key={series.key} className=\"text-right text-xs text-muted-foreground\">\n {series.label}\n </TableHead>\n ))}\n </TableRow>\n </TableHeader>\n <TableBody>\n {chart.buckets.map((bucket, bucketIndex) => (\n <TableRow key={bucket} className=\"hover:bg-transparent\">\n <TableCell className=\"py-1.5 text-sm\">{chart.formatBucketTitle(bucket)}</TableCell>\n {chart.series.map((series) => (\n <TableCell key={series.key} className=\"py-1.5 text-right text-sm tabular-nums\">\n {chart.formatValue(series.values[bucketIndex] ?? 0)}\n </TableCell>\n ))}\n </TableRow>\n ))}\n </TableBody>\n </Table>\n </div>\n </Disclosure>\n )}\n </CardContent>\n </Card>\n );\n};\n","import { normalizeDddError } from \"@mgamadeus/ddd-web/contract\";\nimport { formatUiNumber, useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { DateCell } from \"@mgamadeus/ddd-admin-ui/list\";\nimport { DefinitionList, StatusCallout } from \"@mgamadeus/ddd-admin-ui/page\";\nimport { type PageLinkComponent, Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle, Skeleton, Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport type { AdminPeriod } from \"../period/admin-period\";\nimport { AdminHrefLink } from \"../shared/AdminHrefLink\";\nimport { wireElementsOf } from \"../wire/admin-wire\";\nimport type { AgentControlPanelApi } from \"./agent-control-panel-api\";\nimport type { AgentToolResponseSample, AgentToolResponseStat } from \"./agent-control-panel-types\";\n\nexport interface ToolResponseSamplesDrawerProps {\n api: Pick<AgentControlPanelApi, \"useToolResponseSamplesQuery\">;\n /** The tool shown; `null` closes the drawer. */\n toolName: string | null;\n onClose: () => void;\n period: Pick<AdminPeriod, \"from\" | \"to\">;\n /** The tool's row of the statistics, for the figures above the list. */\n stat?: AgentToolResponseStat | null;\n /** How many responses are listed (default 20, at most 100). */\n limit?: number;\n linkComponent?: PageLinkComponent;\n buildConversationHref?: (conversationId: number) => string | null;\n}\n\n/**\n * The largest responses of one tool in a period, in a side sheet: the tool's figures of the range and one line per\n * stored response (when, the size of the result and of the arguments in characters, the conversation it happened in).\n */\nexport const ToolResponseSamplesDrawer = ({ api, toolName, onClose, period, stat, limit = 20, linkComponent, buildConversationHref }: ToolResponseSamplesDrawerProps) => {\n const { t } = useTranslate();\n const query = api.useToolResponseSamplesQuery({ toolName: toolName ?? \"\", from: period.from, to: period.to, limit }, { skip: toolName === null });\n const samples = toolName === null ? [] : wireElementsOf<AgentToolResponseSample>(query.currentData?.samples);\n const isLoading = toolName !== null && query.currentData === undefined && !query.isError;\n return (\n <Sheet\n open={toolName !== null}\n onOpenChange={(isOpen) => {\n if (!isOpen) onClose();\n }}\n >\n <SheetContent side=\"right\" data-slot=\"tool-response-samples-drawer\" className=\"flex w-full flex-col gap-0 overflow-y-auto p-0 sm:max-w-2xl\">\n <SheetHeader className=\"border-b border-border px-6 py-4 pr-12\">\n <SheetTitle className=\"font-mono text-lg break-all\">{toolName ?? \"\"}</SheetTitle>\n <SheetDescription>{t(\"The largest responses of this tool in the period, in characters.\")}</SheetDescription>\n </SheetHeader>\n <div className=\"min-w-0 space-y-5 px-6 py-5\">\n {stat && (\n <DefinitionList\n columns={2}\n items={[\n { label: t(\"Calls\", { context: \"agent-statistics\" }), value: formatUiNumber(stat.callCount ?? 0) },\n { label: t(\"Failed\", { context: \"agent-statistics\" }), value: stat.failedCallCount === null || stat.failedCallCount === undefined ? \"–\" : formatUiNumber(stat.failedCallCount) },\n { label: t(\"Ø size\"), value: formatUiNumber(stat.avgResultChars ?? 0) },\n { label: t(\"Largest\", { context: \"agent-statistics\" }), value: formatUiNumber(stat.maxResultChars ?? 0) },\n { label: t(\"Total size\"), value: formatUiNumber(stat.sumResultChars ?? 0) },\n ]}\n />\n )}\n {query.isError ? (\n <StatusCallout size=\"compact\" tone=\"destructive\" title={t(\"The responses could not be loaded.\")} description={normalizeDddError(query.error, \"\").message} />\n ) : isLoading ? (\n <div className=\"space-y-2\">\n <Skeleton className=\"h-9 w-full\" />\n <Skeleton className=\"h-9 w-full\" />\n <Skeleton className=\"h-9 w-full\" />\n </div>\n ) : samples.length === 0 ? (\n <p className=\"py-6 text-center text-sm text-muted-foreground\">{t(\"No stored response of this tool in the period.\")}</p>\n ) : (\n <Table>\n <TableHeader>\n <TableRow className=\"hover:bg-transparent\">\n <TableHead className=\"text-xs text-muted-foreground\">{t(\"When\", { context: \"agent-statistics\" })}</TableHead>\n <TableHead className=\"text-right text-xs text-muted-foreground\">{t(\"Result\", { context: \"agent-statistics\" })}</TableHead>\n <TableHead className=\"text-right text-xs text-muted-foreground\">{t(\"Arguments\", { context: \"agent-statistics\" })}</TableHead>\n <TableHead className=\"text-xs text-muted-foreground\">{t(\"Conversation\", { context: \"agent-statistics\" })}</TableHead>\n <TableHead className=\"text-right text-xs text-muted-foreground\">{t(\"Message\", { context: \"agent-statistics\" })}</TableHead>\n </TableRow>\n </TableHeader>\n <TableBody>\n {samples.map((sample) => (\n <TableRow key={sample.messageId} data-message={sample.messageId} className=\"hover:bg-transparent\">\n <TableCell className=\"py-2\">\n <DateCell value={sample.created} />\n </TableCell>\n <TableCell className=\"py-2 text-right font-medium tabular-nums\">{formatUiNumber(sample.resultChars ?? 0)}</TableCell>\n <TableCell className=\"py-2 text-right text-muted-foreground tabular-nums\">{formatUiNumber(sample.argumentsChars ?? 0)}</TableCell>\n <TableCell className=\"py-2\">\n <AdminHrefLink href={buildConversationHref?.(sample.conversationId) ?? null} linkComponent={linkComponent} className=\"font-mono text-xs\">\n #{sample.conversationId}\n </AdminHrefLink>\n </TableCell>\n <TableCell className=\"py-2 text-right font-mono text-xs text-muted-foreground\">#{sample.messageId}</TableCell>\n </TableRow>\n ))}\n </TableBody>\n </Table>\n )}\n </div>\n </SheetContent>\n </Sheet>\n );\n};\n","import { normalizeDddError } from \"@mgamadeus/ddd-web/contract\";\nimport { MetricGrid, MetricTile, NoteList } from \"@mgamadeus/ddd-admin-ui/data\";\nimport { formatUiNumber, getUiLocale, m, useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { DateCell } from \"@mgamadeus/ddd-admin-ui/list\";\nimport { StatusCallout } from \"@mgamadeus/ddd-admin-ui/page\";\nimport {\n Button,\n Card,\n CardContent,\n cn,\n type PageLinkComponent,\n SegmentedControl,\n type SegmentedControlOption,\n Skeleton,\n Table,\n TableBody,\n TableCell,\n TableHead,\n TableHeader,\n TableRow,\n} from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { ArrowDown } from \"lucide-react\";\nimport { type ReactNode, useMemo, useState } from \"react\";\nimport type { AdminPeriod, AdminPeriodGranularity } from \"../period/admin-period\";\nimport { AdminHrefLink } from \"../shared/AdminHrefLink\";\nimport { wireElementsOf } from \"../wire/admin-wire\";\nimport type { AgentControlPanelApi } from \"./agent-control-panel-api\";\nimport type { AgentControlPanelStatistics, AgentConversationStat, AgentToolResponseStat, AgentTopConversationsOrder } from \"./agent-control-panel-types\";\nimport {\n buildControlPanelKeyFigures,\n controlPanelBucketsOf,\n controlPanelSeriesValuesOf,\n formatBucketTick,\n formatBucketTitle,\n formatCharacterCount,\n formatShare,\n formatUsdAmount,\n hasControlPanelSequencePoints,\n sortToolResponseStats,\n type ToolResponseStatSort,\n} from \"./control-panel-statistics\";\nimport { AGENT_SERIES_COLOR_VALUES, type AgentTimeSeriesChartProps, type AgentTimeSeriesChartRenderer, type AgentTimeSeriesChartSeries } from \"./time-series-chart\";\nimport { TimeSeriesChartCard } from \"./TimeSeriesChartCard\";\nimport { ToolResponseSamplesDrawer } from \"./ToolResponseSamplesDrawer\";\nimport type { SeriesFillSlot } from \"../blocks/series-fill-classes\";\n\nexport interface StatisticsTabProps {\n api: AgentControlPanelApi;\n period: AdminPeriod;\n granularity: AdminPeriodGranularity;\n excludeTestUsers: boolean;\n topConversationsOrder: AgentTopConversationsOrder;\n onTopConversationsOrderChange: (order: AgentTopConversationsOrder) => void;\n /** The tool whose responses are open in the drawer; `null` = closed. */\n selectedToolName: string | null;\n onSelectTool: (toolName: string | null) => void;\n linkComponent?: PageLinkComponent;\n buildConversationHref?: (conversationId: number) => string | null;\n buildAccountHref?: (accountId: number) => string | null;\n renderTimeSeriesChart?: AgentTimeSeriesChartRenderer;\n}\n\nconst CHART_HEIGHT = 220;\n/** The height of the three small charts beside each other. */\nconst SMALL_CHART_HEIGHT = 180;\n/** How many of the top conversations show before \"Show all\". */\nconst TOP_CONVERSATIONS_SHOWN = 10;\n\nconst TOP_ORDER_OPTIONS: readonly SegmentedControlOption<AgentTopConversationsOrder>[] = [\n { value: \"totalCostInUSD\", label: m(\"Cost\", { context: \"agent-statistics\" }), context: \"agent-statistics\" },\n { value: \"totalTokens\", label: m(\"Tokens\", { context: \"agent-statistics\" }), context: \"agent-statistics\" },\n { value: \"messageCount\", label: m(\"Messages\", { context: \"agent-statistics\" }), context: \"agent-statistics\" },\n];\n\nconst seriesOf = (key: string, label: string, colorSlot: SeriesFillSlot, values: number[]): AgentTimeSeriesChartSeries => ({\n key,\n label,\n colorSlot,\n color: AGENT_SERIES_COLOR_VALUES[colorSlot],\n values,\n total: values.reduce((sum, value) => sum + value, 0),\n});\n\ninterface SortableHeadProps {\n sort: ToolResponseStatSort;\n activeSort: ToolResponseStatSort;\n onSort: (sort: ToolResponseStatSort) => void;\n children: ReactNode;\n}\n\n/** A numeric column header that orders the tool table by its measure, largest first. */\nconst SortableHead = ({ sort, activeSort, onSort, children }: SortableHeadProps) => (\n <TableHead aria-sort={activeSort === sort ? \"descending\" : undefined} className=\"px-2 text-right text-xs whitespace-nowrap text-muted-foreground\">\n <button\n type=\"button\"\n onClick={() => onSort(sort)}\n className={cn(\"inline-flex items-center gap-1 rounded-sm outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\", activeSort === sort && \"font-semibold text-foreground\")}\n >\n {children}\n <ArrowDown aria-hidden className={cn(\"size-3\", activeSort !== sort && \"invisible\")} />\n </button>\n </TableHead>\n);\n\ninterface ToolResponseStatsCardProps {\n statistics: AgentControlPanelStatistics;\n selectedToolName: string | null;\n onSelectTool: (toolName: string) => void;\n}\n\nconst ToolResponseStatsCard = ({ statistics, selectedToolName, onSelectTool }: ToolResponseStatsCardProps) => {\n const { t } = useTranslate();\n const locale = getUiLocale();\n const [sort, setSort] = useState<ToolResponseStatSort>(\"sum\");\n const stats = useMemo(() => sortToolResponseStats(wireElementsOf<AgentToolResponseStat>(statistics.toolResponseStats), sort), [statistics, sort]);\n const headProps = { activeSort: sort, onSort: setSort };\n return (\n <Card data-slot=\"tool-response-stats\" className=\"gap-0 py-0\">\n <CardContent className=\"px-2 py-4\">\n <div className=\"px-3 pb-2\">\n <h3 className=\"text-base font-semibold\">{t(\"Tools by response size\")}</h3>\n <p className=\"text-sm text-muted-foreground\">{t(\"What each tool put into the context, in characters. A row opens its largest responses.\")}</p>\n </div>\n {statistics.toolResponseDataAvailable === false ? (\n <StatusCallout size=\"compact\" tone=\"warning\" className=\"mx-3\" title={t(\"The tool sizes are not available on this database.\")} description={t(\"The generated tool columns of the message table are missing.\")} />\n ) : stats.length === 0 ? (\n <p className=\"px-3 py-6 text-center text-sm text-muted-foreground\">{t(\"No tool was called in this period.\")}</p>\n ) : (\n <div className=\"max-h-[26rem] overflow-auto\">\n <Table>\n <TableHeader>\n <TableRow className=\"hover:bg-transparent\">\n <TableHead className=\"w-full max-w-0 px-3 text-xs text-muted-foreground\">{t(\"Tool\", { context: \"agent-statistics\" })}</TableHead>\n <SortableHead sort=\"calls\" {...headProps}>\n {t(\"Calls\", { context: \"agent-statistics\" })}\n </SortableHead>\n <SortableHead sort=\"avg\" {...headProps}>\n {t(\"Ø size\")}\n </SortableHead>\n <SortableHead sort=\"max\" {...headProps}>\n {t(\"Largest\", { context: \"agent-statistics\" })}\n </SortableHead>\n <SortableHead sort=\"sum\" {...headProps}>\n {t(\"Total size\")}\n </SortableHead>\n <SortableHead sort=\"failed\" {...headProps}>\n {t(\"Failed\", { context: \"agent-statistics\" })}\n </SortableHead>\n </TableRow>\n </TableHeader>\n <TableBody>\n {stats.map((stat) => (\n <TableRow key={stat.toolName} data-tool={stat.toolName} aria-current={selectedToolName === stat.toolName ? \"true\" : undefined} onClick={() => onSelectTool(stat.toolName)} className=\"cursor-pointer aria-[current=true]:bg-tint-strong\">\n <TableCell className=\"w-full max-w-0 px-3 py-2\">\n <button\n type=\"button\"\n onClick={(event) => {\n event.stopPropagation();\n onSelectTool(stat.toolName);\n }}\n className=\"block max-w-full truncate rounded-sm text-left font-mono text-xs text-primary-emphasis outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n title={stat.toolName}\n >\n {stat.toolName}\n </button>\n </TableCell>\n <TableCell className=\"px-2 py-2 text-right whitespace-nowrap tabular-nums\">{formatUiNumber(stat.callCount ?? 0)}</TableCell>\n <TableCell className=\"px-2 py-2 text-right whitespace-nowrap tabular-nums\">{formatCharacterCount(stat.avgResultChars, locale)}</TableCell>\n <TableCell className=\"px-2 py-2 text-right whitespace-nowrap tabular-nums\">{formatCharacterCount(stat.maxResultChars, locale)}</TableCell>\n <TableCell className=\"px-2 py-2 text-right whitespace-nowrap tabular-nums\">{formatCharacterCount(stat.sumResultChars, locale)}</TableCell>\n <TableCell className=\"px-2 py-2 text-right whitespace-nowrap tabular-nums\">\n {stat.failedCallCount === null || stat.failedCallCount === undefined ? (\n <span className=\"text-muted-foreground\">–</span>\n ) : stat.failedCallCount > 0 ? (\n formatUiNumber(stat.failedCallCount)\n ) : (\n <span className=\"text-muted-foreground\">0</span>\n )}\n </TableCell>\n </TableRow>\n ))}\n </TableBody>\n </Table>\n </div>\n )}\n </CardContent>\n </Card>\n );\n};\n\ninterface TopConversationsCardProps extends Pick<StatisticsTabProps, \"linkComponent\" | \"buildConversationHref\" | \"buildAccountHref\" | \"topConversationsOrder\" | \"onTopConversationsOrderChange\"> {\n statistics: AgentControlPanelStatistics;\n isRefreshing: boolean;\n}\n\nconst TopConversationsCard = ({ statistics, isRefreshing, linkComponent, buildConversationHref, buildAccountHref, topConversationsOrder, onTopConversationsOrderChange }: TopConversationsCardProps) => {\n const { t } = useTranslate();\n const locale = getUiLocale();\n const [showsAll, setShowsAll] = useState(false);\n const conversations = wireElementsOf<AgentConversationStat>(statistics.topConversations);\n const shown = showsAll ? conversations : conversations.slice(0, TOP_CONVERSATIONS_SHOWN);\n const largestCost = conversations.reduce((largest, conversation) => Math.max(largest, conversation.totalCostInUSD ?? 0), 0);\n return (\n <Card data-slot=\"top-conversations\" className=\"gap-0 py-0\">\n <CardContent className=\"px-2 py-4\">\n <div className=\"flex flex-wrap items-start justify-between gap-2 px-3 pb-2\">\n <div>\n <h3 className=\"text-base font-semibold\">{t(\"Top conversations\")}</h3>\n <p className=\"text-sm text-muted-foreground\">{t(\"With their sub-agents, by what they cost or how long they are.\")}</p>\n </div>\n <SegmentedControl<AgentTopConversationsOrder> aria-label={t(\"Order the top conversations by\")} value={topConversationsOrder} onValueChange={onTopConversationsOrderChange} options={TOP_ORDER_OPTIONS} />\n </div>\n {conversations.length === 0 ? (\n <p className=\"px-3 py-6 text-center text-sm text-muted-foreground\">{t(\"No conversation in this period.\")}</p>\n ) : (\n <div className={cn(\"transition-opacity motion-reduce:transition-none\", isRefreshing && \"opacity-60\")}>\n <Table>\n <TableHeader>\n <TableRow className=\"hover:bg-transparent\">\n <TableHead className=\"px-3 text-xs text-muted-foreground\">{t(\"Conversation\", { context: \"agent-statistics\" })}</TableHead>\n <TableHead className=\"px-3 text-right text-xs text-muted-foreground\">{t(\"Messages\", { context: \"agent-statistics\" })}</TableHead>\n <TableHead className=\"px-3 text-right text-xs text-muted-foreground\">{t(\"Tokens\", { context: \"agent-statistics\" })}</TableHead>\n <TableHead className=\"px-3 text-right text-xs text-muted-foreground\">{t(\"Cost\", { context: \"agent-statistics\" })}</TableHead>\n </TableRow>\n </TableHeader>\n <TableBody>\n {shown.map((conversation) => {\n const title = typeof conversation.title === \"string\" && conversation.title.trim() !== \"\" ? conversation.title : t(\"Conversation #%id%\", { replacements: { id: String(conversation.conversationId) } });\n const accountId = conversation.accountId ?? null;\n return (\n <TableRow key={conversation.conversationId} className=\"hover:bg-transparent\">\n <TableCell className=\"max-w-72 px-3 py-2 whitespace-normal\">\n <AdminHrefLink href={buildConversationHref?.(conversation.conversationId) ?? null} linkComponent={linkComponent} className=\"line-clamp-2 text-sm font-medium break-words\">\n {title}\n </AdminHrefLink>\n <div className=\"flex flex-wrap items-center gap-x-2 text-xs text-muted-foreground\">\n <span className=\"font-mono\">#{conversation.conversationId}</span>\n {accountId !== null && (\n <AdminHrefLink href={buildAccountHref?.(accountId) ?? null} linkComponent={linkComponent}>\n {t(\"Account #%id%\", { replacements: { id: String(accountId) } })}\n </AdminHrefLink>\n )}\n <DateCell value={conversation.created} className=\"text-xs\" />\n </div>\n </TableCell>\n <TableCell className=\"px-3 py-2 text-right align-top tabular-nums\">{formatUiNumber(conversation.messageCount ?? 0)}</TableCell>\n <TableCell className=\"px-3 py-2 text-right align-top tabular-nums\">{formatCharacterCount(conversation.totalTokens ?? 0, locale)}</TableCell>\n <TableCell className=\"w-24 px-3 py-2 text-right align-top\">\n <span className=\"font-semibold tabular-nums\">{formatUsdAmount(conversation.totalCostInUSD ?? 0, locale)}</span>\n <span aria-hidden className=\"mt-1 ml-auto block h-1 rounded-full bg-[color:var(--series-1,var(--brand))]\" style={{ width: `${largestCost > 0 ? Math.max(4, ((conversation.totalCostInUSD ?? 0) / largestCost) * 100) : 0}%` }} />\n </TableCell>\n </TableRow>\n );\n })}\n </TableBody>\n </Table>\n {conversations.length > TOP_CONVERSATIONS_SHOWN && (\n <div className=\"px-3 pt-2\">\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" onClick={() => setShowsAll((current) => !current)}>\n {showsAll ? t(\"Show fewer\") : t(\"Show all %count%\", { replacements: { count: formatUiNumber(conversations.length) } })}\n </Button>\n </div>\n )}\n </div>\n )}\n </CardContent>\n </Card>\n );\n};\n\n/**\n * The statistics of a range: the key figures, the cost per bucket (by origin when the statistics carry it), three small\n * charts (tokens, conversations, active accounts per bucket: one axis each), the tools by response size (a row opens\n * its largest responses) and the top conversations.\n */\nexport const StatisticsTab = ({\n api,\n period,\n granularity,\n excludeTestUsers,\n topConversationsOrder,\n onTopConversationsOrderChange,\n selectedToolName,\n onSelectTool,\n linkComponent,\n buildConversationHref,\n buildAccountHref,\n renderTimeSeriesChart,\n}: StatisticsTabProps) => {\n const { t } = useTranslate();\n const locale = getUiLocale();\n const query = api.useControlPanelStatisticsQuery({ from: period.from, to: period.to, granularity, excludeTestUsers, topConversationsOrderBy: topConversationsOrder });\n const statistics = query.data?.statistics ?? null;\n const isLoading = query.isLoading || (statistics === null && query.isFetching);\n const figures = useMemo(() => buildControlPanelKeyFigures(statistics), [statistics]);\n\n const charts = useMemo(() => {\n const usage = statistics?.aiUsagePerBucket;\n const byOrigin = statistics?.costInUSDPerBucketByOrigin;\n const sequences = [\n statistics?.conversationsPerBucket,\n statistics?.activeAccountsPerBucket,\n usage?.inputTokensPerBucket,\n usage?.outputTokensPerBucket,\n usage?.costInUSDPerBucket,\n byOrigin?.chatCostInUSDPerBucket,\n byOrigin?.scheduledRunCostInUSDPerBucket,\n byOrigin?.voiceCostInUSDPerBucket,\n ];\n const buckets = controlPanelBucketsOf(period.from, period.to, granularity, sequences);\n const valuesOf = (sequence: Parameters<typeof controlPanelSeriesValuesOf>[0]) => controlPanelSeriesValuesOf(sequence, buckets, granularity);\n const hasOrigins = [byOrigin?.chatCostInUSDPerBucket, byOrigin?.scheduledRunCostInUSDPerBucket, byOrigin?.voiceCostInUSDPerBucket].some(hasControlPanelSequencePoints);\n const countFormat = (value: number) => formatUiNumber(value);\n const compactFormat = (value: number) => new Intl.NumberFormat(locale, { notation: \"compact\", maximumFractionDigits: 1 }).format(value);\n const shared = {\n buckets,\n granularity,\n formatBucket: (bucket: string) => formatBucketTick(bucket, locale),\n formatBucketTitle: (bucket: string) => (granularity === \"WEEK\" ? t(\"Week from %date%\", { replacements: { date: formatBucketTitle(bucket, locale) } }) : formatBucketTitle(bucket, locale)),\n totalLabel: t(\"Total\", { context: \"agent-statistics\" }),\n height: CHART_HEIGHT,\n };\n const cost: AgentTimeSeriesChartProps = {\n ...shared,\n chartId: \"cost\",\n ariaLabel: granularity === \"WEEK\" ? t(\"Cost per week\") : t(\"Cost per day\"),\n kind: \"bar\",\n series: hasOrigins\n ? [\n seriesOf(\"chat\", t(\"Chat\", { context: \"agent-origin\" }), \"series1\", valuesOf(byOrigin?.chatCostInUSDPerBucket)),\n seriesOf(\"scheduledRuns\", t(\"Scheduled runs\", { context: \"agent-origin\" }), \"series3\", valuesOf(byOrigin?.scheduledRunCostInUSDPerBucket)),\n seriesOf(\"voice\", t(\"Voice\", { context: \"agent-origin\" }), \"series4\", valuesOf(byOrigin?.voiceCostInUSDPerBucket)),\n ]\n : [seriesOf(\"cost\", t(\"Cost\", { context: \"agent-statistics\" }), \"series1\", valuesOf(usage?.costInUSDPerBucket))],\n formatValue: (value) => formatUsdAmount(value, locale),\n formatAxisValue: (value) => new Intl.NumberFormat(locale, { style: \"currency\", currency: \"USD\", notation: \"compact\", maximumFractionDigits: 2 }).format(value),\n };\n // conversations and active accounts differ by orders of magnitude: one chart each, never two scales on one axis\n const conversations: AgentTimeSeriesChartProps = {\n ...shared,\n height: SMALL_CHART_HEIGHT,\n chartId: \"conversations\",\n ariaLabel: granularity === \"WEEK\" ? t(\"Conversations per week\") : t(\"Conversations per day\"),\n kind: \"bar\",\n series: [seriesOf(\"conversations\", t(\"Conversations\", { context: \"agent-statistics\" }), \"series1\", valuesOf(statistics?.conversationsPerBucket))],\n formatValue: countFormat,\n formatAxisValue: compactFormat,\n isWholeNumbers: true,\n };\n const activeAccounts: AgentTimeSeriesChartProps = {\n ...shared,\n height: SMALL_CHART_HEIGHT,\n chartId: \"activeAccounts\",\n ariaLabel: granularity === \"WEEK\" ? t(\"Active accounts per week\") : t(\"Active accounts per day\"),\n kind: \"line\",\n series: [seriesOf(\"activeAccounts\", t(\"Active accounts\"), \"series3\", valuesOf(statistics?.activeAccountsPerBucket))],\n formatValue: countFormat,\n formatAxisValue: compactFormat,\n isWholeNumbers: true,\n };\n const tokens: AgentTimeSeriesChartProps = {\n ...shared,\n height: SMALL_CHART_HEIGHT,\n chartId: \"tokens\",\n ariaLabel: granularity === \"WEEK\" ? t(\"Tokens per week\") : t(\"Tokens per day\"),\n kind: \"bar\",\n series: [\n seriesOf(\"inputTokens\", t(\"Input\", { context: \"agent-tokens\" }), \"series7\", valuesOf(usage?.inputTokensPerBucket)),\n seriesOf(\"outputTokens\", t(\"Output\", { context: \"agent-tokens\" }), \"series2\", valuesOf(usage?.outputTokensPerBucket)),\n ],\n formatValue: countFormat,\n formatAxisValue: compactFormat,\n isWholeNumbers: true,\n };\n return { cost, conversations, activeAccounts, tokens, hasOrigins };\n }, [statistics, period.from, period.to, granularity, locale, t]);\n\n if (query.isError && statistics === null) {\n return <StatusCallout tone=\"destructive\" title={t(\"The statistics could not be loaded.\")} description={normalizeDddError(query.error, \"\").message} />;\n }\n\n const isFromMessageRows = statistics?.costInUSDPerBucketByOrigin?.isFromMessageRows === true;\n const periodHint = t(\"{count, plural, one {# day} other {# days}}\", { count: period.dayCount });\n return (\n <div data-slot=\"agent-statistics-tab\" className={cn(\"space-y-4 transition-opacity motion-reduce:transition-none\", query.isFetching && !isLoading && \"opacity-80\")}>\n <MetricGrid columns={4} isLoading={isLoading} skeletonCount={8}>\n <MetricTile label={t(\"Cost\", { context: \"agent-statistics\" })} value={formatUsdAmount(figures.costInUSD, locale)} hint={periodHint} />\n <MetricTile label={t(\"Cost per conversation\")} value={formatUsdAmount(figures.costPerConversationInUSD, locale)} hint={figures.costPerConversationInUSD === null ? t(\"No cost or no conversation\") : undefined} />\n <MetricTile\n label={t(\"Tokens\", { context: \"agent-statistics\" })}\n value={formatCharacterCount(figures.totalTokens, locale)}\n hint={\n figures.totalTokens === null\n ? t(\"No usage log\")\n : t(\"%input% in · %output% out\", { replacements: { input: formatCharacterCount(figures.inputTokens, locale), output: formatCharacterCount(figures.outputTokens, locale) } })\n }\n />\n <MetricTile label={t(\"Conversations\", { context: \"agent-statistics\" })} value={formatUiNumber(figures.conversationCount)} hint={excludeTestUsers ? t(\"Without test users\") : periodHint} />\n <MetricTile label={t(\"Active accounts · 7 days\")} value={figures.weeklyActiveAccounts === null ? \"–\" : formatUiNumber(figures.weeklyActiveAccounts)} hint={t(\"Sent a message, up to the last day\")} />\n <MetricTile label={t(\"Active accounts · 30 days\")} value={figures.monthlyActiveAccounts === null ? \"–\" : formatUiNumber(figures.monthlyActiveAccounts)} hint={t(\"Sent a message, up to the last day\")} />\n <MetricTile label={t(\"Scheduled runs\", { context: \"agent-origin\" })} value={figures.scheduledRunCount === null ? \"–\" : formatUiNumber(figures.scheduledRunCount)} hint={periodHint} />\n <MetricTile\n label={t(\"Error rate\")}\n value={formatShare(figures.errorRate, locale)}\n hint={\n figures.errorRate === null\n ? t(\"No turn events in this period\")\n : t(\"%errored% of %turns% turns ended in an error\", { replacements: { errored: formatUiNumber(figures.erroredTurnCount ?? 0), turns: formatUiNumber(figures.turnCount ?? 0) } })\n }\n />\n </MetricGrid>\n\n <TimeSeriesChartCard\n title={granularity === \"WEEK\" ? t(\"Cost per week\") : t(\"Cost per day\")}\n description={charts.hasOrigins ? t(\"By the way a conversation starts.\") : undefined}\n chart={charts.cost}\n renderChart={renderTimeSeriesChart}\n isLoading={isLoading}\n emptyText={t(\"No cost in this period.\")}\n footer={\n isFromMessageRows ? (\n <NoteList notes={[{ id: \"messageRows\", text: t(\"Sums of the conversations' message rows. Cost booked outside them (the audio of a call, decision calls, summaries) is not included.\") }]} />\n ) : undefined\n }\n />\n\n <div className=\"grid gap-4 md:grid-cols-2 xl:grid-cols-3\">\n <TimeSeriesChartCard\n title={t(\"Tokens\", { context: \"agent-statistics\" })}\n description={t(\"Sent to the models and written by them.\")}\n chart={charts.tokens}\n renderChart={renderTimeSeriesChart}\n isLoading={isLoading}\n emptyText={t(\"No token usage in this period.\")}\n legendPlacement=\"below\"\n />\n <TimeSeriesChartCard\n title={t(\"Conversations\", { context: \"agent-statistics\" })}\n description={t(\"Conversations started.\")}\n chart={charts.conversations}\n renderChart={renderTimeSeriesChart}\n isLoading={isLoading}\n emptyText={t(\"No conversation in this period.\")}\n legendPlacement=\"below\"\n />\n <TimeSeriesChartCard\n title={t(\"Active accounts\")}\n description={granularity === \"WEEK\" ? t(\"Accounts that sent a message in the week.\") : t(\"Accounts that sent a message on the day.\")}\n chart={charts.activeAccounts}\n renderChart={renderTimeSeriesChart}\n isLoading={isLoading}\n emptyText={t(\"No account sent a message in this period.\")}\n showTotals={false}\n legendPlacement=\"below\"\n />\n </div>\n\n {isLoading || statistics === null ? (\n <Skeleton className=\"h-64 w-full rounded-2xl\" />\n ) : (\n <div className=\"grid items-start gap-4 xl:grid-cols-[minmax(0,1.25fr)_minmax(0,1fr)]\">\n <ToolResponseStatsCard statistics={statistics} selectedToolName={selectedToolName} onSelectTool={onSelectTool} />\n <TopConversationsCard\n statistics={statistics}\n isRefreshing={query.isFetching}\n linkComponent={linkComponent}\n buildConversationHref={buildConversationHref}\n buildAccountHref={buildAccountHref}\n topConversationsOrder={topConversationsOrder}\n onTopConversationsOrderChange={onTopConversationsOrderChange}\n />\n </div>\n )}\n\n <ToolResponseSamplesDrawer\n api={api}\n toolName={selectedToolName}\n onClose={() => onSelectTool(null)}\n period={period}\n stat={wireElementsOf<AgentToolResponseStat>(statistics?.toolResponseStats).find((stat) => stat.toolName === selectedToolName) ?? null}\n linkComponent={linkComponent}\n buildConversationHref={buildConversationHref}\n />\n </div>\n );\n};\n","import { m, useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { type UrlStateAdapter, useMemoryUrlState, useUrlListState } from \"@mgamadeus/ddd-admin-ui/logic\";\nimport { type EntityTab, EntityTabs, PageHeader } from \"@mgamadeus/ddd-admin-ui/page\";\nimport { Label, type PageLinkComponent, SegmentedControl, type SegmentedControlOption, Switch } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { type ReactNode, useId, useMemo } from \"react\";\nimport { type AdminPeriodGranularity, resolveAdminPeriod } from \"../period/admin-period\";\nimport { AdminPeriodControl } from \"../period/AdminPeriodControl\";\nimport type { AgentSchedulesApi } from \"../schedules/agent-schedules-api\";\nimport type { AgentSchedulePlace, AgentSchedulesScope } from \"../schedules/agent-schedules-types\";\nimport { AgentSchedulesPanel } from \"../schedules/AgentSchedulesPanel\";\nimport type { AgentControlPanelApi } from \"./agent-control-panel-api\";\nimport type { AgentControlPanelSpace, AgentTopConversationsOrder } from \"./agent-control-panel-types\";\nimport { BudgetsTab } from \"./BudgetsTab\";\nimport { SettingsTab } from \"./SettingsTab\";\nimport { SpacesTab } from \"./SpacesTab\";\nimport { StatisticsTab } from \"./StatisticsTab\";\nimport type { AgentTimeSeriesChartRenderer } from \"./time-series-chart\";\n\n/** The tabs of the control panel, in order. */\nexport const AGENT_CONTROL_PANEL_TABS = [\"statistics\", \"settings\", \"spaces\", \"schedules\", \"budgets\"] as const;\nexport type AgentControlPanelTab = (typeof AGENT_CONTROL_PANEL_TABS)[number];\n\n/**\n * The URL keys of the screen: the tab, the period (`period`, `from`, `to`), the bucket of the charts, the switch that\n * leaves test users out, the order of the top conversations, the tool whose responses are open and the schedule whose\n * runs are open.\n */\nexport const AGENT_CONTROL_PANEL_URL_KEYS = [\"tab\", \"period\", \"from\", \"to\", \"bucket\", \"noTest\", \"topBy\", \"tool\", \"schedule\"] as const;\n\nexport interface AgentControlPanelScreenProps {\n /** `createAgentControlPanelApi(…)` of the host. */\n api: AgentControlPanelApi;\n /** `createAgentSchedulesApi(…)` of the host; without it the Schedules tab is left out. */\n schedulesApi?: AgentSchedulesApi;\n /** Whose schedules the Schedules tab lists: `own` (default) or `all` (every account's, with the owner; the server decides who may). */\n schedulesScope?: AgentSchedulesScope;\n /** Where the tab, the period and the other choices live: the host's URL adapter. Without one they live in component state. */\n urlStateAdapter?: UrlStateAdapter;\n /** The page title; default \"Control centre\". Already translated. */\n title?: ReactNode;\n description?: ReactNode;\n headerActions?: ReactNode;\n /** False: the settings cannot be saved and the schedule actions are off. Default true. */\n writesAllowed?: boolean;\n /** Why writes are off; already translated. */\n writesBlockedReason?: ReactNode;\n /** The host's router link; default the provider's, else a plain `<a>`. */\n linkComponent?: PageLinkComponent;\n /** The link of a conversation in the host's agent screens; `null` = no link. */\n buildConversationHref?: (conversationId: number) => string | null;\n /** The link of an account in the host; `null` = no link. */\n buildAccountHref?: (accountId: number) => string | null;\n /** The link of an agent space (the record behind it) in the host; `null` = no link. */\n buildSpaceHref?: (space: AgentControlPanelSpace) => string | null;\n /** The host's name of a kind of space. Already translated. */\n describeSpaceKind?: (kind: string) => string;\n /** The host's name of a space when the server's label is its own English words; null = the label. Already translated. */\n describeSpaceLabel?: (space: AgentControlPanelSpace) => string | null;\n /** The host's name of the place a schedule lives in. Already translated. */\n describeSchedulePlace?: (place: AgentSchedulePlace) => ReactNode;\n /** The host's words for the cron expression of a recurring schedule; null = the expression. Already translated. */\n describeCronSchedule?: (expression: string) => string | null;\n /** The host's display name of a model by its catalog name (\"GPT-6 Luna\"); null = the catalog name. */\n describeModelName?: (modelName: string) => string | null;\n /**\n * The host's words for the environment the settings apply to, from the server's name and its English label; null =\n * the label as sent. Already translated.\n */\n describeEnvironment?: (environment: string, environmentLabel: string | null) => string | null;\n /** Draws the charts of the statistics with the host's chart library; default the package's own bars. */\n renderTimeSeriesChart?: AgentTimeSeriesChartRenderer;\n /** Tabs of the host after the package's (route tabs with an `href`: its skills page, its connections). */\n extraTabs?: readonly EntityTab[];\n /** Tabs of the package the host leaves out. */\n hiddenTabs?: readonly AgentControlPanelTab[];\n}\n\nconst TAB_LABELS: Readonly<Record<AgentControlPanelTab, string>> = {\n statistics: m(\"Statistics\", { context: \"agent-control-tab\" }),\n settings: m(\"Settings\", { context: \"agent-control-tab\" }),\n spaces: m(\"Spaces\", { context: \"agent-control-tab\" }),\n schedules: m(\"Schedules\", { context: \"agent-control-tab\" }),\n budgets: m(\"Budgets\", { context: \"agent-control-tab\" }),\n};\n\nconst GRANULARITY_OPTIONS: readonly SegmentedControlOption<AdminPeriodGranularity>[] = [\n { value: \"DAY\", label: m(\"Daily\", { context: \"agent-statistics\" }), context: \"agent-statistics\" },\n { value: \"WEEK\", label: m(\"Weekly\", { context: \"agent-statistics\" }), context: \"agent-statistics\" },\n];\n\nconst TOP_ORDERS: readonly AgentTopConversationsOrder[] = [\"totalCostInUSD\", \"totalTokens\", \"messageCount\"];\n\n/**\n * The control centre of the agent: the statistics of a period (key figures, cost, conversations, tokens, tools, top\n * conversations), the runtime settings with their change log, the agent spaces of the period, the schedules and the\n * budget meters. The tab and every choice are kept in the URL through the host's adapter.\n */\nexport const AgentControlPanelScreen = ({\n api,\n schedulesApi,\n schedulesScope,\n urlStateAdapter,\n title,\n description,\n headerActions,\n writesAllowed = true,\n writesBlockedReason,\n linkComponent,\n buildConversationHref,\n buildAccountHref,\n buildSpaceHref,\n describeSpaceKind,\n describeSpaceLabel,\n describeSchedulePlace,\n describeCronSchedule,\n describeModelName,\n describeEnvironment,\n renderTimeSeriesChart,\n extraTabs = [],\n hiddenTabs = [],\n}: AgentControlPanelScreenProps) => {\n const { t } = useTranslate();\n const switchId = useId();\n const memory = useMemoryUrlState();\n const state = useUrlListState(AGENT_CONTROL_PANEL_URL_KEYS, { adapter: urlStateAdapter ?? memory.urlStateAdapter, debounceMs: 0, pushKeys: [\"tab\"] });\n const values = state.values;\n\n const shownTabs = AGENT_CONTROL_PANEL_TABS.filter((tab) => !hiddenTabs.includes(tab) && (tab !== \"schedules\" || schedulesApi !== undefined));\n const activeTab: AgentControlPanelTab = shownTabs.find((tab) => tab === values.tab) ?? shownTabs[0] ?? \"statistics\";\n const period = useMemo(() => resolveAdminPeriod({ preset: values.period, from: values.from, to: values.to }, \"30d\"), [values.period, values.from, values.to]);\n const granularity: AdminPeriodGranularity = values.bucket === \"week\" ? \"WEEK\" : \"DAY\";\n const excludeTestUsers = values.noTest === \"1\";\n const topConversationsOrder = TOP_ORDERS.find((order) => order === values.topBy) ?? \"totalCostInUSD\";\n const selectedScheduleId = /^\\d+$/.test(values.schedule) ? Number(values.schedule) : null;\n\n const tabs: EntityTab[] = [...shownTabs.map((tab): EntityTab => ({ id: tab, label: TAB_LABELS[tab], context: \"agent-control-tab\" })), ...extraTabs];\n const periodControl = <AdminPeriodControl period={period} onChange={(next) => state.setValues({ period: next.preset, from: next.from, to: next.to })} />;\n const tabControls =\n activeTab === \"statistics\" ? (\n <>\n {periodControl}\n <SegmentedControl<AdminPeriodGranularity> aria-label={t(\"Bucket of the charts\")} value={granularity} onValueChange={(next) => state.setValue(\"bucket\", next === \"WEEK\" ? \"week\" : \"\")} options={GRANULARITY_OPTIONS} />\n <span className=\"flex items-center gap-2\">\n <Switch id={switchId} checked={excludeTestUsers} onCheckedChange={(isChecked) => state.setValue(\"noTest\", isChecked ? \"1\" : \"\")} />\n <Label htmlFor={switchId} className=\"text-sm font-normal\">\n {t(\"Exclude test users\")}\n </Label>\n </span>\n </>\n ) : activeTab === \"spaces\" ? (\n periodControl\n ) : null;\n\n return (\n <div data-slot=\"agent-control-panel-screen\" data-tab={activeTab} className=\"space-y-4\">\n <PageHeader\n title={title ?? t(\"Control centre\")}\n description={description ?? t(\"How the agent works and what it costs: usage, tools, schedules and the settings of the agent.\")}\n actions={headerActions}\n />\n <div className=\"flex flex-wrap items-center justify-between gap-x-4 gap-y-3\">\n <EntityTabs\n aria-label={t(\"Sections of the control centre\")}\n tabs={tabs}\n activeId={activeTab}\n onSelect={(id) => state.setValues({ tab: id === shownTabs[0] ? \"\" : id, tool: \"\", schedule: \"\" })}\n linkComponent={linkComponent}\n variant=\"segmented\"\n />\n {tabControls !== null && <div className=\"flex flex-wrap items-center gap-x-4 gap-y-2\">{tabControls}</div>}\n </div>\n\n {activeTab === \"statistics\" && (\n <StatisticsTab\n api={api}\n period={period}\n granularity={granularity}\n excludeTestUsers={excludeTestUsers}\n topConversationsOrder={topConversationsOrder}\n onTopConversationsOrderChange={(order) => state.setValue(\"topBy\", order === \"totalCostInUSD\" ? \"\" : order)}\n selectedToolName={values.tool !== \"\" ? values.tool : null}\n onSelectTool={(toolName) => state.setValue(\"tool\", toolName ?? \"\")}\n linkComponent={linkComponent}\n buildConversationHref={buildConversationHref}\n buildAccountHref={buildAccountHref}\n renderTimeSeriesChart={renderTimeSeriesChart}\n />\n )}\n {activeTab === \"settings\" && (\n <SettingsTab\n api={api}\n writesAllowed={writesAllowed}\n writesBlockedReason={writesBlockedReason}\n linkComponent={linkComponent}\n buildAccountHref={buildAccountHref}\n describeModelName={describeModelName}\n describeEnvironment={describeEnvironment}\n />\n )}\n {activeTab === \"spaces\" && (\n <SpacesTab api={api} period={period} linkComponent={linkComponent} buildSpaceHref={buildSpaceHref} buildAccountHref={buildAccountHref} describeSpaceKind={describeSpaceKind} describeSpaceLabel={describeSpaceLabel} />\n )}\n {activeTab === \"schedules\" && schedulesApi !== undefined && (\n <AgentSchedulesPanel\n api={schedulesApi}\n scope={schedulesScope}\n buildAccountHref={buildAccountHref}\n writesAllowed={writesAllowed}\n linkComponent={linkComponent}\n buildConversationHref={buildConversationHref}\n describePlace={describeSchedulePlace}\n describeCronSchedule={describeCronSchedule}\n selectedScheduleId={selectedScheduleId}\n onSelectSchedule={(scheduleId) => state.setValue(\"schedule\", scheduleId === null ? \"\" : String(scheduleId))}\n />\n )}\n {activeTab === \"budgets\" && <BudgetsTab api={api} linkComponent={linkComponent} buildAccountHref={buildAccountHref} />}\n </div>\n );\n};\n","import {\n type ApiMutationHook,\n type ApiQueryHook,\n type InjectableBaseApi,\n type InjectedEndpointDefinition,\n type InjectedRequest,\n injectEndpointsOnce,\n staticMutationHook,\n type StaticQueryFailure,\n staticQueryHook,\n toQueryString,\n trimApiPrefix,\n} from \"@mgamadeus/ddd-admin-ui/logic/pure\";\nimport type {\n AgentScheduleActionResponse,\n AgentScheduleIdArg,\n AgentScheduleRunsArg,\n AgentScheduleRunsResponse,\n AgentSchedulesArg,\n AgentSchedulesResponse,\n AgentScheduleUpdateArg,\n} from \"./agent-schedules-types\";\n\n/** The cache tag type of the schedule operations (ids `LIST`, `RUNS`). */\nexport const AGENT_SCHEDULES_TAG = \"AdminUiAgentSchedules\";\n\n/** The hooks `createAgentSchedulesApi` returns; `AgentSchedulesPanel` takes them as `api`. */\nexport interface AgentSchedulesApi {\n /** `GET /list?placeKind&recordId&scope`: the schedules with their place, newest run and allowed actions; `scope=all` lists every account's. */\n useAgentSchedulesQuery: ApiQueryHook<AgentSchedulesArg, AgentSchedulesResponse>;\n /** `GET /{scheduleId}/runs?limit&beforeConversationId`: the runs of one schedule, newest first. */\n useAgentScheduleRunsQuery: ApiQueryHook<AgentScheduleRunsArg, AgentScheduleRunsResponse>;\n /** `POST /{scheduleId}/pause`. */\n usePauseAgentScheduleMutation: ApiMutationHook<AgentScheduleIdArg, AgentScheduleActionResponse>;\n /** `POST /{scheduleId}/resume`. */\n useResumeAgentScheduleMutation: ApiMutationHook<AgentScheduleIdArg, AgentScheduleActionResponse>;\n /** `POST /{scheduleId}/runNow`: starts a run now; answers its conversation. */\n useRunAgentScheduleNowMutation: ApiMutationHook<AgentScheduleIdArg, AgentScheduleActionResponse>;\n /** `POST /{scheduleId}/update`: title, task, cron expression or one-time moment. */\n useUpdateAgentScheduleMutation: ApiMutationHook<AgentScheduleUpdateArg, AgentScheduleActionResponse>;\n /** `DELETE /{scheduleId}`: removes, archives or keeps the schedule as history (`actionTaken`). */\n useDeleteAgentScheduleMutation: ApiMutationHook<AgentScheduleIdArg, AgentScheduleActionResponse>;\n}\n\nexport interface CreateAgentSchedulesApiOptions {\n /** The host's RTK Query api (`createApi` with the React hooks module). */\n baseApi: InjectableBaseApi;\n /** Where the host mounts `AdminAgentSchedulesTrait`, without a trailing slash (`/api/admin/ai/agentSchedules`). */\n apiPrefix: string;\n}\n\n/** The request of every operation, on `apiPrefix`. Pure: no RTK runtime. */\nexport const buildAgentSchedulesRequests = (apiPrefix: string) => {\n const prefix = trimApiPrefix(apiPrefix);\n const scheduleUrl = (scheduleId: number, action?: string) => `${prefix}/${encodeURIComponent(String(scheduleId))}${action !== undefined ? `/${action}` : \"\"}`;\n return {\n list: (arg: AgentSchedulesArg = {}): InjectedRequest => ({ url: `${prefix}/list${toQueryString({ placeKind: arg.placeKind, recordId: arg.recordId, scope: arg.scope === \"all\" ? \"all\" : undefined })}` }),\n runs: ({ scheduleId, limit, beforeConversationId }: AgentScheduleRunsArg): InjectedRequest => ({ url: `${scheduleUrl(scheduleId, \"runs\")}${toQueryString({ limit, beforeConversationId })}` }),\n pause: ({ scheduleId }: AgentScheduleIdArg): InjectedRequest => ({ url: scheduleUrl(scheduleId, \"pause\"), method: \"POST\" }),\n resume: ({ scheduleId }: AgentScheduleIdArg): InjectedRequest => ({ url: scheduleUrl(scheduleId, \"resume\"), method: \"POST\" }),\n runNow: ({ scheduleId }: AgentScheduleIdArg): InjectedRequest => ({ url: scheduleUrl(scheduleId, \"runNow\"), method: \"POST\" }),\n update: ({ scheduleId, ...changes }: AgentScheduleUpdateArg): InjectedRequest => ({ url: scheduleUrl(scheduleId, \"update\"), method: \"POST\", body: changes }),\n remove: ({ scheduleId }: AgentScheduleIdArg): InjectedRequest => ({ url: scheduleUrl(scheduleId), method: \"DELETE\" }),\n };\n};\n\nconst LIST = { type: AGENT_SCHEDULES_TAG, id: \"LIST\" } as const;\nconst RUNS = { type: AGENT_SCHEDULES_TAG, id: \"RUNS\" } as const;\n\n/** The operations as injected. */\nexport const agentSchedulesEndpointDefinitions = (apiPrefix: string) => {\n const requests = buildAgentSchedulesRequests(apiPrefix);\n return {\n adminUiAgentSchedules: { kind: \"query\", request: requests.list, providesTags: [LIST] },\n adminUiAgentScheduleRuns: { kind: \"query\", request: requests.runs, providesTags: [RUNS] },\n adminUiAgentSchedulePause: { kind: \"mutation\", request: requests.pause, invalidatesTags: [LIST] },\n adminUiAgentScheduleResume: { kind: \"mutation\", request: requests.resume, invalidatesTags: [LIST] },\n adminUiAgentScheduleRunNow: { kind: \"mutation\", request: requests.runNow, invalidatesTags: [LIST, RUNS] },\n adminUiAgentScheduleUpdate: { kind: \"mutation\", request: requests.update, invalidatesTags: [LIST] },\n adminUiAgentScheduleDelete: { kind: \"mutation\", request: requests.remove, invalidatesTags: [LIST] },\n } as const satisfies Record<string, InjectedEndpointDefinition<never>>;\n};\n\n/**\n * Injects the schedule operations into the host's RTK Query api and returns their hooks. Call it once at module scope:\n * `export const agentSchedulesApi = createAgentSchedulesApi({ baseApi, apiPrefix: \"/api/admin/ai/agentSchedules\" });`\n */\nexport const createAgentSchedulesApi = ({ baseApi, apiPrefix }: CreateAgentSchedulesApiOptions): AgentSchedulesApi =>\n injectEndpointsOnce(\n baseApi,\n `agentSchedules:${trimApiPrefix(apiPrefix)}`,\n [AGENT_SCHEDULES_TAG],\n agentSchedulesEndpointDefinitions(apiPrefix),\n (hookOf) => ({\n useAgentSchedulesQuery: hookOf(\"adminUiAgentSchedules\") as AgentSchedulesApi[\"useAgentSchedulesQuery\"],\n useAgentScheduleRunsQuery: hookOf(\"adminUiAgentScheduleRuns\") as AgentSchedulesApi[\"useAgentScheduleRunsQuery\"],\n usePauseAgentScheduleMutation: hookOf(\"adminUiAgentSchedulePause\") as AgentSchedulesApi[\"usePauseAgentScheduleMutation\"],\n useResumeAgentScheduleMutation: hookOf(\"adminUiAgentScheduleResume\") as AgentSchedulesApi[\"useResumeAgentScheduleMutation\"],\n useRunAgentScheduleNowMutation: hookOf(\"adminUiAgentScheduleRunNow\") as AgentSchedulesApi[\"useRunAgentScheduleNowMutation\"],\n useUpdateAgentScheduleMutation: hookOf(\"adminUiAgentScheduleUpdate\") as AgentSchedulesApi[\"useUpdateAgentScheduleMutation\"],\n useDeleteAgentScheduleMutation: hookOf(\"adminUiAgentScheduleDelete\") as AgentSchedulesApi[\"useDeleteAgentScheduleMutation\"],\n }),\n );\n\n/** Fixed answers of a `createStaticAgentSchedulesApi`; a query without one stays loading, an action without one answers empty. */\nexport interface StaticAgentSchedulesData {\n list?: (arg: AgentSchedulesArg) => AgentSchedulesResponse | StaticQueryFailure | undefined;\n runs?: (arg: AgentScheduleRunsArg) => AgentScheduleRunsResponse | StaticQueryFailure | undefined;\n pause?: (arg: AgentScheduleIdArg) => AgentScheduleActionResponse | Promise<AgentScheduleActionResponse>;\n resume?: (arg: AgentScheduleIdArg) => AgentScheduleActionResponse | Promise<AgentScheduleActionResponse>;\n runNow?: (arg: AgentScheduleIdArg) => AgentScheduleActionResponse | Promise<AgentScheduleActionResponse>;\n update?: (arg: AgentScheduleUpdateArg) => AgentScheduleActionResponse | Promise<AgentScheduleActionResponse>;\n remove?: (arg: AgentScheduleIdArg) => AgentScheduleActionResponse | Promise<AgentScheduleActionResponse>;\n}\n\n/** An `AgentSchedulesApi` answering fixed payloads, without a store or a request (previews, tests, reviews). */\nexport const createStaticAgentSchedulesApi = (data: StaticAgentSchedulesData): AgentSchedulesApi => ({\n useAgentSchedulesQuery: staticQueryHook((arg) => data.list?.(arg ?? {})),\n useAgentScheduleRunsQuery: staticQueryHook((arg) => data.runs?.(arg)),\n usePauseAgentScheduleMutation: staticMutationHook((arg) => data.pause?.(arg) ?? {}),\n useResumeAgentScheduleMutation: staticMutationHook((arg) => data.resume?.(arg) ?? {}),\n useRunAgentScheduleNowMutation: staticMutationHook((arg) => data.runNow?.(arg) ?? {}),\n useUpdateAgentScheduleMutation: staticMutationHook((arg) => data.update?.(arg) ?? {}),\n useDeleteAgentScheduleMutation: staticMutationHook((arg) => data.remove?.(arg) ?? {}),\n});\n","import {\n type ApiMutationHook,\n type ApiQueryHook,\n type InjectableBaseApi,\n type InjectedEndpointDefinition,\n type InjectedRequest,\n injectEndpointsOnce,\n staticMutationHook,\n type StaticQueryFailure,\n staticQueryHook,\n toQueryString,\n trimApiPrefix,\n} from \"@mgamadeus/ddd-admin-ui/logic/pure\";\nimport type {\n AgentQualityEvalCaseDraftArg,\n AgentQualityEvalCaseDraftResponse,\n AgentQualityEvalRunArg,\n AgentQualityEvalRunResponse,\n AgentQualityEvalRunsArg,\n AgentQualityEvalRunsResponse,\n AgentQualityFailuresResponse,\n AgentQualityRangeArg,\n AgentQualitySummaryResponse,\n} from \"./agent-quality-types\";\n\n/** The cache tag type of the quality reads (ids `SUMMARY`, `FAILURES`, `EVAL_RUNS`, `EVAL_RUN`). */\nexport const AGENT_QUALITY_TAG = \"AdminUiAgentQuality\";\n\n/** The hooks `createAgentQualityApi` returns; the quality screens and `SaveAsEvalCaseDialog` take them as `api`. */\nexport interface AgentQualityApi {\n /** `GET /summary?from&to`: the figures of the period and of the period before, the newest evaluation run. */\n useQualitySummaryQuery: ApiQueryHook<AgentQualityRangeArg, AgentQualitySummaryResponse>;\n /** `GET /failures?from&to`: the failures of the period, grouped by kind and tool or model. */\n useQualityFailuresQuery: ApiQueryHook<AgentQualityRangeArg, AgentQualityFailuresResponse>;\n /** `GET /evalRuns?limit&offset`: the recorded evaluation runs, the newest first. */\n useQualityEvalRunsQuery: ApiQueryHook<AgentQualityEvalRunsArg, AgentQualityEvalRunsResponse>;\n /** `GET /evalRuns/{evalRunId}?verdicts&top&skip`: one run with a page of its cases. */\n useQualityEvalRunQuery: ApiQueryHook<AgentQualityEvalRunArg, AgentQualityEvalRunResponse>;\n /** `POST /evalCases`: drafts an evaluation case from a stored turn. Answers a document; nothing is written. */\n useDraftEvalCaseMutation: ApiMutationHook<AgentQualityEvalCaseDraftArg, AgentQualityEvalCaseDraftResponse>;\n}\n\nexport interface CreateAgentQualityApiOptions {\n /** The host's RTK Query api (`createApi` with the React hooks module). */\n baseApi: InjectableBaseApi;\n /** Where the host mounts `AdminAgentQualityTrait`, without a trailing slash (`/api/admin/ai/agentQuality`). */\n apiPrefix: string;\n}\n\n/** The request of every operation, on `apiPrefix`. Pure: no RTK runtime. */\nexport const buildAgentQualityRequests = (apiPrefix: string) => {\n const prefix = trimApiPrefix(apiPrefix);\n return {\n summary: (arg: AgentQualityRangeArg = {}): InjectedRequest => ({ url: `${prefix}/summary${toQueryString({ from: arg.from, to: arg.to })}` }),\n failures: (arg: AgentQualityRangeArg = {}): InjectedRequest => ({ url: `${prefix}/failures${toQueryString({ from: arg.from, to: arg.to })}` }),\n evalRuns: (arg: AgentQualityEvalRunsArg = {}): InjectedRequest => ({ url: `${prefix}/evalRuns${toQueryString({ limit: arg.limit, offset: arg.offset })}` }),\n evalRun: ({ evalRunId, verdicts, top, skip }: AgentQualityEvalRunArg): InjectedRequest => ({\n url: `${prefix}/evalRuns/${encodeURIComponent(String(evalRunId))}${toQueryString({ verdicts: verdicts !== undefined && verdicts.length > 0 ? verdicts.join(\",\") : undefined, top, skip })}`,\n }),\n draftEvalCase: ({ conversationId, messageId, messageIndex }: AgentQualityEvalCaseDraftArg): InjectedRequest => ({\n url: `${prefix}/evalCases`,\n method: \"POST\",\n body: { conversationId, ...(messageId !== undefined ? { messageId } : {}), ...(messageId === undefined && messageIndex !== undefined ? { messageIndex } : {}) },\n }),\n };\n};\n\nconst SUMMARY = { type: AGENT_QUALITY_TAG, id: \"SUMMARY\" } as const;\nconst FAILURES = { type: AGENT_QUALITY_TAG, id: \"FAILURES\" } as const;\nconst EVAL_RUNS = { type: AGENT_QUALITY_TAG, id: \"EVAL_RUNS\" } as const;\nconst EVAL_RUN = { type: AGENT_QUALITY_TAG, id: \"EVAL_RUN\" } as const;\n\n/** The operations as injected. The draft is a mutation without tags: it writes nothing. */\nexport const agentQualityEndpointDefinitions = (apiPrefix: string) => {\n const requests = buildAgentQualityRequests(apiPrefix);\n return {\n adminUiAgentQualitySummary: { kind: \"query\", request: requests.summary, providesTags: [SUMMARY] },\n adminUiAgentQualityFailures: { kind: \"query\", request: requests.failures, providesTags: [FAILURES] },\n adminUiAgentQualityEvalRuns: { kind: \"query\", request: requests.evalRuns, providesTags: [EVAL_RUNS] },\n adminUiAgentQualityEvalRun: { kind: \"query\", request: requests.evalRun, providesTags: [EVAL_RUN] },\n adminUiAgentQualityDraftEvalCase: { kind: \"mutation\", request: requests.draftEvalCase },\n } as const satisfies Record<string, InjectedEndpointDefinition<never>>;\n};\n\n/**\n * Injects the quality operations into the host's RTK Query api and returns their hooks. Call it once at module scope:\n * `export const agentQualityApi = createAgentQualityApi({ baseApi, apiPrefix: \"/api/admin/ai/agentQuality\" });`\n */\nexport const createAgentQualityApi = ({ baseApi, apiPrefix }: CreateAgentQualityApiOptions): AgentQualityApi =>\n injectEndpointsOnce(\n baseApi,\n `agentQuality:${trimApiPrefix(apiPrefix)}`,\n [AGENT_QUALITY_TAG],\n agentQualityEndpointDefinitions(apiPrefix),\n (hookOf) => ({\n useQualitySummaryQuery: hookOf(\"adminUiAgentQualitySummary\") as AgentQualityApi[\"useQualitySummaryQuery\"],\n useQualityFailuresQuery: hookOf(\"adminUiAgentQualityFailures\") as AgentQualityApi[\"useQualityFailuresQuery\"],\n useQualityEvalRunsQuery: hookOf(\"adminUiAgentQualityEvalRuns\") as AgentQualityApi[\"useQualityEvalRunsQuery\"],\n useQualityEvalRunQuery: hookOf(\"adminUiAgentQualityEvalRun\") as AgentQualityApi[\"useQualityEvalRunQuery\"],\n useDraftEvalCaseMutation: hookOf(\"adminUiAgentQualityDraftEvalCase\") as AgentQualityApi[\"useDraftEvalCaseMutation\"],\n }),\n );\n\n/** Fixed answers of a `createStaticAgentQualityApi`; a query without one stays loading. */\nexport interface StaticAgentQualityData {\n summary?: (arg: AgentQualityRangeArg) => AgentQualitySummaryResponse | StaticQueryFailure | undefined;\n failures?: (arg: AgentQualityRangeArg) => AgentQualityFailuresResponse | StaticQueryFailure | undefined;\n evalRuns?: (arg: AgentQualityEvalRunsArg) => AgentQualityEvalRunsResponse | StaticQueryFailure | undefined;\n evalRun?: (arg: AgentQualityEvalRunArg) => AgentQualityEvalRunResponse | StaticQueryFailure | undefined;\n /** The answer of a draft; default an empty draft. A thrown error is the failed request. */\n draftEvalCase?: (arg: AgentQualityEvalCaseDraftArg) => AgentQualityEvalCaseDraftResponse | Promise<AgentQualityEvalCaseDraftResponse>;\n}\n\n/** An `AgentQualityApi` answering fixed payloads, without a store or a request (previews, tests, reviews). */\nexport const createStaticAgentQualityApi = (data: StaticAgentQualityData): AgentQualityApi => ({\n useQualitySummaryQuery: staticQueryHook((arg) => data.summary?.(arg ?? {})),\n useQualityFailuresQuery: staticQueryHook((arg) => data.failures?.(arg ?? {})),\n useQualityEvalRunsQuery: staticQueryHook((arg) => data.evalRuns?.(arg ?? {})),\n useQualityEvalRunQuery: staticQueryHook((arg) => data.evalRun?.(arg)),\n useDraftEvalCaseMutation: staticMutationHook((arg) => data.draftEvalCase?.(arg) ?? { evalCase: null }),\n});\n","import type { AdminWireSet } from \"../wire/admin-wire\";\n\n/** The kinds a quality view groups failures by (`AgentQualityFailureKind::KINDS`), in the order equal counts are listed. */\nexport const AGENT_QUALITY_FAILURE_KINDS = [\n \"TOOL_TIMEOUT\",\n \"INVALID_ARGUMENTS\",\n \"REFUSED_BY_GATE\",\n \"MODEL_ERROR\",\n \"RUN_STUCK\",\n \"TURN_GAVE_UP\",\n \"TURN_FAILED\",\n \"TURN_EXPIRED\",\n \"RUN_ERROR\",\n \"REPEATED_CALL\",\n \"TOOL_ERROR\",\n] as const;\n\nexport type AgentQualityFailureKind = (typeof AGENT_QUALITY_FAILURE_KINDS)[number];\n\n/** The counted figures of one period (`AgentQualityPeriodFigures`); a figure that could not be read is null. */\nexport interface AgentQualityPeriodFigures {\n fromDay?: string;\n toDay?: string;\n conversationsWithFailureCount?: number | null;\n toolTimeoutCount?: number | null;\n turnCount?: number | null;\n answeredTurnCount?: number | null;\n /** Turns that ended without an answer and not by expiry: failed, given up or cancelled. */\n abortedTurnCount?: number | null;\n failedTurnCount?: number | null;\n gaveUpTurnCount?: number | null;\n cancelledTurnCount?: number | null;\n expiredTurnCount?: number | null;\n}\n\n/** One recorded evaluation run (`AgentQualityEvalRunSummary`). */\nexport interface AgentQualityEvalRunSummary {\n evalRunId?: number | null;\n suiteLabel?: string | null;\n command?: string | null;\n host?: string | null;\n startedAt?: string | null;\n finishedAt?: string | null;\n durationSeconds?: number | null;\n casesTotal?: number;\n /** Cases that could pass or fail. */\n casesJudged?: number;\n casesPassed?: number;\n casesFailed?: number;\n casesErrored?: number;\n casesNotApplicable?: number;\n casesFailedAsExpected?: number;\n /** The share of the judged cases that passed, 0 to 1; null without a judged case. */\n passRate?: number | null;\n isGreen?: boolean;\n /** The run's options as a small JSON object (models, flavors, suites). */\n runOptionsJson?: string | null;\n logDirectoryName?: string | null;\n}\n\n/** The quality figures of a period (`AgentQualitySummary`). */\nexport interface AgentQualitySummary {\n figures?: AgentQualityPeriodFigures | null;\n previousFigures?: AgentQualityPeriodFigures | null;\n /** Conversations marked as running although their last heartbeat is older than the limit, now. */\n stuckRunCount?: number | null;\n stuckAfterSeconds?: number;\n purposeRunCount?: number | null;\n finishedPurposeRunCount?: number | null;\n purposeFinishRate?: number | null;\n latestEvalRun?: AgentQualityEvalRunSummary | null;\n /** False: no rating of an answer is stored, so there is no count of negative ratings. */\n isSatisfactionCaptured?: boolean;\n thumbsDownCount?: number | null;\n unavailableParts?: string[] | null;\n}\n\nexport interface AgentQualityRangeArg {\n from?: string;\n to?: string;\n}\n\n/** `GET {prefix}/summary`. */\nexport interface AgentQualitySummaryResponse {\n summary?: AgentQualitySummary | null;\n}\n\n/** One line of the failures of a period (`AgentQualityFailureGroup`). */\nexport interface AgentQualityFailureGroup {\n kind: AgentQualityFailureKind | string;\n toolName?: string | null;\n modelName?: string | null;\n errorCode?: string | null;\n count?: number;\n latestConversationId?: number | null;\n latestConversationTitle?: string | null;\n latestAt?: string | null;\n}\n\n/** `GET {prefix}/failures`. */\nexport interface AgentQualityFailuresResponse {\n rangeFrom?: string;\n rangeTo?: string;\n /** The groups (`AgentQualityFailureGroups`, an object set; read through `wireElementsOf`). */\n failures?: AdminWireSet<AgentQualityFailureGroup> | null;\n /** True: a read reached its row limit, the counts are a lower bound. */\n isTruncated?: boolean;\n /** The parts that could not be read (`toolCalls`, `errorRows`, `turnEnds`, `stuckRuns`). */\n unavailableParts?: string[] | null;\n}\n\nexport interface AgentQualityEvalRunsArg {\n limit?: number;\n offset?: number;\n}\n\n/** `GET {prefix}/evalRuns`. */\nexport interface AgentQualityEvalRunsResponse {\n /** The runs (`AgentQualityEvalRunSummaries`, an object set; read through `wireElementsOf`). */\n evalRuns?: AdminWireSet<AgentQualityEvalRunSummary> | null;\n}\n\nexport type AgentQualityEvalVerdict = \"PASS\" | \"FAIL\" | \"ERROR\" | \"NOT_APPLICABLE\" | \"EXPECTED_FAIL\";\n\n/** One case of a recorded run (`AgentEvalSuiteCase`). */\nexport interface AgentQualityEvalCase {\n id?: number;\n agentEvalSuiteRunId?: number | null;\n caseId?: string | null;\n suiteName?: string | null;\n fixtureName?: string | null;\n modelName?: string | null;\n /** `call` (deterministic, single-shot) or `judge` (simulated owner and judge). */\n flavor?: string | null;\n aiConversationId?: number | null;\n verdict?: AgentQualityEvalVerdict | string | null;\n /** What went wrong, one finding per line. */\n findings?: string | null;\n wallSeconds?: number | null;\n agentSeconds?: number | null;\n ownerTurns?: number | null;\n modelCalls?: number | null;\n toolCalls?: number | null;\n costUsd?: number | null;\n}\n\nexport interface AgentQualityEvalRunArg {\n evalRunId: number;\n /** Only cases with one of these verdicts; empty or absent = every case. */\n verdicts?: readonly string[];\n top?: number;\n skip?: number;\n}\n\n/** `GET {prefix}/evalRuns/{evalRunId}`. */\nexport interface AgentQualityEvalRunResponse {\n evalRun?: AgentQualityEvalRunSummary | null;\n cases?: AdminWireSet<AgentQualityEvalCase> | null;\n /** How many cases of the run match the verdict filter, over every page. */\n caseCount?: number;\n}\n\n/** `POST {prefix}/evalCases`: the turn a case is drafted from. */\nexport interface AgentQualityEvalCaseDraftArg {\n conversationId: number;\n /** The id of a message of the turn. */\n messageId?: number;\n /** Without `messageId`: the position of a message of the turn in the conversation. */\n messageIndex?: number;\n}\n\n/** The draft of an evaluation case (`AgentQualityEvalCaseDraft`). Nothing is written by the route. */\nexport interface AgentQualityEvalCaseDraft {\n caseId?: string;\n conversationId?: number | null;\n initiatorMessageIndex?: number | null;\n prompt?: string;\n agentSpaceId?: number | null;\n purposeName?: string | null;\n skillNames?: string[] | null;\n toolNames?: string[] | null;\n /** The case alone as JSON. */\n caseJson?: string;\n /** A fixture file with this one case as JSON. */\n fixtureJson?: string;\n}\n\n/** The answer of `POST {prefix}/evalCases`. */\nexport interface AgentQualityEvalCaseDraftResponse {\n evalCase?: AgentQualityEvalCaseDraft | null;\n}\n","import { m } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { defineStatusMap } from \"@mgamadeus/ddd-admin-ui/logic\";\nimport { Ban, CircleCheck, CircleDashed, CircleMinus, CircleX, Clock, Flag, Hand, Hourglass, type LucideIcon, Repeat, ServerCrash, ShieldX, TextCursorInput, TriangleAlert, Wrench } from \"lucide-react\";\nimport { type AdminWireSet, wireElementsOf, wireNumberOf } from \"../wire/admin-wire\";\nimport { AGENT_QUALITY_FAILURE_KINDS, type AgentQualityEvalRunSummary, type AgentQualityEvalVerdict, type AgentQualityFailureGroup, type AgentQualityFailureKind, type AgentQualityPeriodFigures } from \"./agent-quality-types\";\n\n/** How a failure kind shows: its name, what it means, its icon. */\nexport interface AgentQualityFailureKindDefinition {\n label: string;\n description: string;\n icon: LucideIcon;\n}\n\nexport const AGENT_QUALITY_FAILURE_KIND_DEFINITIONS: Readonly<Record<AgentQualityFailureKind, AgentQualityFailureKindDefinition>> = {\n TOOL_TIMEOUT: { label: m(\"Tool timeout\", { context: \"agent-failure-kind\" }), description: m(\"A tool ran into its execution time limit.\", { context: \"agent-failure-kind\" }), icon: Clock },\n INVALID_ARGUMENTS: { label: m(\"Invalid arguments\", { context: \"agent-failure-kind\" }), description: m(\"A tool refused the arguments the model sent.\", { context: \"agent-failure-kind\" }), icon: TextCursorInput },\n REFUSED_BY_GATE: { label: m(\"Refused by a gate\", { context: \"agent-failure-kind\" }), description: m(\"A right, a mandate or a confirmation refused the call before the tool ran.\", { context: \"agent-failure-kind\" }), icon: ShieldX },\n MODEL_ERROR: { label: m(\"Model error\", { context: \"agent-failure-kind\" }), description: m(\"The model call failed at the provider.\", { context: \"agent-failure-kind\" }), icon: ServerCrash },\n RUN_STUCK: { label: m(\"Run stuck\", { context: \"agent-failure-kind\" }), description: m(\"A conversation is still marked as running long after its last heartbeat.\", { context: \"agent-failure-kind\" }), icon: Hourglass },\n TURN_GAVE_UP: { label: m(\"Turn given up\", { context: \"agent-failure-kind\" }), description: m(\"A turn ended because the agent gave up.\", { context: \"agent-failure-kind\" }), icon: Hand },\n TURN_FAILED: { label: m(\"Turn failed\", { context: \"agent-failure-kind\" }), description: m(\"A turn ended as failed.\", { context: \"agent-failure-kind\" }), icon: CircleX },\n TURN_EXPIRED: { label: m(\"Turn expired\", { context: \"agent-failure-kind\" }), description: m(\"A turn was never answered and expired.\", { context: \"agent-failure-kind\" }), icon: CircleDashed },\n RUN_ERROR: { label: m(\"Run error\", { context: \"agent-failure-kind\" }), description: m(\"The run stopped on a stored error: a budget, a scope, a step limit.\", { context: \"agent-failure-kind\" }), icon: TriangleAlert },\n REPEATED_CALL: { label: m(\"Repeated call\", { context: \"agent-failure-kind\" }), description: m(\"The loop refused or aborted a call the model repeated.\", { context: \"agent-failure-kind\" }), icon: Repeat },\n TOOL_ERROR: { label: m(\"Tool error\", { context: \"agent-failure-kind\" }), description: m(\"A tool failed for another reason: an exception, an external service, a write without effect.\", { context: \"agent-failure-kind\" }), icon: Wrench },\n};\n\n/** Whether a kind is one the package names. */\nexport const isKnownAgentQualityFailureKind = (kind: string): kind is AgentQualityFailureKind => AGENT_QUALITY_FAILURE_KINDS.includes(kind as AgentQualityFailureKind);\n\n/** The failures of one kind, as the table lists them under one heading. */\nexport interface AgentQualityFailureKindSection {\n kind: string;\n /** The occurrences of the kind over all of its lines. */\n count: number;\n groups: AgentQualityFailureGroup[];\n}\n\n/**\n * The failure lines by kind: the kind with the most occurrences first (equal counts in the order of\n * `AGENT_QUALITY_FAILURE_KINDS`, unknown kinds last by name); inside a kind the lines keep the order they came in\n * (the most frequent first).\n */\nexport const groupAgentQualityFailuresByKind = (failures: AdminWireSet<AgentQualityFailureGroup> | null | undefined): AgentQualityFailureKindSection[] => {\n const sections = new Map<string, AgentQualityFailureKindSection>();\n for (const group of wireElementsOf(failures)) {\n const kind = String(group.kind ?? \"\");\n const section = sections.get(kind) ?? { kind, count: 0, groups: [] };\n section.count += Math.max(0, wireNumberOf(group.count) ?? 0);\n section.groups.push(group);\n sections.set(kind, section);\n }\n const positionOf = (kind: string): number => {\n const position = AGENT_QUALITY_FAILURE_KINDS.indexOf(kind as AgentQualityFailureKind);\n return position < 0 ? AGENT_QUALITY_FAILURE_KINDS.length : position;\n };\n return [...sections.values()].sort((first, second) => second.count - first.count || positionOf(first.kind) - positionOf(second.kind) || first.kind.localeCompare(second.kind));\n};\n\n/** What a failure line happened with: its tool, else its model, with the error code beside it; null when it names none. */\nexport const agentQualityFailureSubjectOf = (group: Pick<AgentQualityFailureGroup, \"toolName\" | \"modelName\" | \"errorCode\">): { name: string | null; errorCode: string | null } => {\n const textOf = (value: string | null | undefined): string | null => (typeof value === \"string\" && value.trim() !== \"\" ? value.trim() : null);\n return { name: textOf(group.toolName) ?? textOf(group.modelName), errorCode: textOf(group.errorCode) };\n};\n\n/** The turns of a period that ended without an answer: aborted (failed, given up, cancelled) and expired; null when neither was read. */\nexport const abortedAndExpiredTurnCountOf = (figures: AgentQualityPeriodFigures | null | undefined): number | null => {\n const aborted = wireNumberOf(figures?.abortedTurnCount);\n const expired = wireNumberOf(figures?.expiredTurnCount);\n return aborted === null && expired === null ? null : (aborted ?? 0) + (expired ?? 0);\n};\n\n/** `current - previous`; null when one of them is missing. */\nexport const qualityFigureChangeOf = (current: number | null | undefined, previous: number | null | undefined): number | null =>\n typeof current === \"number\" && typeof previous === \"number\" ? current - previous : null;\n\n/** The verdict of an evaluation case. */\nexport const AGENT_QUALITY_EVAL_VERDICT = defineStatusMap<AgentQualityEvalVerdict>(\n {\n PASS: { label: m(\"Passed\", { context: \"agent-eval-verdict\" }), tone: \"success\", icon: CircleCheck },\n FAIL: { label: m(\"Failed\", { context: \"agent-eval-verdict\" }), tone: \"danger\", icon: CircleX },\n ERROR: { label: m(\"Error\", { context: \"agent-eval-verdict\" }), tone: \"danger\", icon: TriangleAlert, description: m(\"The case did not finish: an exception, a timeout, no result\", { context: \"agent-eval-verdict\" }) },\n NOT_APPLICABLE: { label: m(\"Not applicable\", { context: \"agent-eval-verdict\" }), tone: \"neutral\", icon: CircleMinus, description: m(\"The case did not apply to its space\", { context: \"agent-eval-verdict\" }) },\n EXPECTED_FAIL: { label: m(\"Fails by design\", { context: \"agent-eval-verdict\" }), tone: \"neutral\", icon: Flag, description: m(\"The case is marked as failing by design\", { context: \"agent-eval-verdict\" }) },\n },\n { context: \"agent-eval-verdict\" },\n);\n\n/** The verdict filter of a run's cases: which verdicts each choice asks for (none = every case). */\nexport const AGENT_QUALITY_EVAL_VERDICT_FILTERS = {\n all: [],\n failed: [\"FAIL\", \"ERROR\"],\n passed: [\"PASS\"],\n notJudged: [\"NOT_APPLICABLE\", \"EXPECTED_FAIL\"],\n} as const satisfies Record<string, readonly AgentQualityEvalVerdict[]>;\n\nexport type AgentQualityEvalVerdictFilter = keyof typeof AGENT_QUALITY_EVAL_VERDICT_FILTERS;\n\n/** The models a run names in its options (`models`, `model`, `aiModelName`), in order and without repeats; empty when it names none. */\nexport const evalRunModelNamesOf = (run: Pick<AgentQualityEvalRunSummary, \"runOptionsJson\"> | null | undefined): string[] => {\n if (typeof run?.runOptionsJson !== \"string\" || run.runOptionsJson.trim() === \"\") return [];\n let options: unknown;\n try {\n options = JSON.parse(run.runOptionsJson);\n } catch {\n // options that are no JSON name no model\n return [];\n }\n if (options === null || typeof options !== \"object\") return [];\n const names: string[] = [];\n for (const key of [\"models\", \"model\", \"aiModelName\", \"modelName\"]) {\n const value = (options as Record<string, unknown>)[key];\n const candidates = Array.isArray(value) ? value : typeof value === \"string\" ? value.split(\",\") : [];\n for (const candidate of candidates) {\n if (typeof candidate === \"string\" && candidate.trim() !== \"\" && !names.includes(candidate.trim())) names.push(candidate.trim());\n }\n }\n return names;\n};\n\n/** Seconds as a short duration (`48 s`, `3 min 20 s`, `1 h 4 min`). */\nexport const formatQualityDuration = (seconds: number | null | undefined): string => {\n if (seconds === null || seconds === undefined || !Number.isFinite(seconds) || seconds < 0) return \"–\";\n const whole = Math.round(seconds);\n if (whole < 60) return `${whole} s`;\n // a zero remainder is left out (\"5 min\", not \"5 min 0 s\")\n if (whole < 3600) return whole % 60 === 0 ? `${whole / 60} min` : `${Math.floor(whole / 60)} min ${whole % 60} s`;\n const minutes = Math.floor((whole % 3600) / 60);\n return minutes === 0 ? `${Math.floor(whole / 3600)} h` : `${Math.floor(whole / 3600)} h ${minutes} min`;\n};\n\n/** The name of the file a drafted case is saved as (`eval-case-<case id>.json`), safe for a file system. */\nexport const evalCaseFileNameOf = (caseId: string | null | undefined, kind: \"case\" | \"fixture\"): string => {\n const safeId = (caseId ?? \"\").replace(/[^A-Za-z0-9._-]+/g, \"-\").replace(/^-+|-+$/g, \"\");\n return `${kind === \"fixture\" ? \"eval-fixture\" : \"eval-case\"}${safeId !== \"\" ? `-${safeId}` : \"\"}.json`;\n};\n\n/** The icon of a kind the package does not name. */\nexport const UNKNOWN_FAILURE_KIND_ICON: LucideIcon = Ban;\n","import { normalizeDddError } from \"@mgamadeus/ddd-web/contract\";\nimport { MetricGrid, MetricTile } from \"@mgamadeus/ddd-admin-ui/data\";\nimport { formatUiNumber, getUiLocale, m, useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { formatDateTime, StatusBadge } from \"@mgamadeus/ddd-admin-ui/list\";\nimport { type UrlStateAdapter, useMemoryUrlState, useUrlListState } from \"@mgamadeus/ddd-admin-ui/logic\";\nimport { PageHeader, StatusCallout } from \"@mgamadeus/ddd-admin-ui/page\";\nimport { Button, Card, CardContent, cn, type PageLinkComponent, SegmentedControl, type SegmentedControlOption, Skeleton, Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { ChevronLeft, ChevronRight } from \"lucide-react\";\nimport type { ReactNode } from \"react\";\nimport { formatShare, formatUsdAmount } from \"../control-panel/control-panel-statistics\";\nimport { AdminHrefLink } from \"../shared/AdminHrefLink\";\nimport { wireElementsOf } from \"../wire/admin-wire\";\nimport type { AgentQualityApi } from \"./agent-quality-api\";\nimport { AGENT_QUALITY_EVAL_VERDICT, AGENT_QUALITY_EVAL_VERDICT_FILTERS, type AgentQualityEvalVerdictFilter, evalRunModelNamesOf, formatQualityDuration } from \"./agent-quality-format\";\nimport type { AgentQualityEvalCase, AgentQualityEvalVerdict } from \"./agent-quality-types\";\n\n/** The URL keys of the screen: the verdict filter and the page of the cases (1-based). */\nexport const AGENT_QUALITY_EVAL_RUN_URL_KEYS = [\"verdict\", \"page\"] as const;\n\nexport interface AgentQualityEvalRunScreenProps {\n /** `createAgentQualityApi(…)` of the host. */\n api: Pick<AgentQualityApi, \"useQualityEvalRunQuery\">;\n /** The id of the recorded run (the host's route parameter). */\n evalRunId: number;\n /** Where the verdict filter and the page live: the host's URL adapter. Without one they live in component state. */\n urlStateAdapter?: UrlStateAdapter;\n /** Before the title: the host's link back to the quality screen. */\n backLink?: ReactNode;\n headerActions?: ReactNode;\n linkComponent?: PageLinkComponent;\n /** The link of the conversation a case drove; `null` = no link. */\n buildConversationHref?: (conversationId: number) => string | null;\n /** Cases per page (default 50, at most 500). */\n pageSize?: number;\n /** The host's display name of a model by its catalog name (\"GPT-6 Luna\"); null = the catalog name. */\n describeModelName?: (modelName: string) => string | null;\n}\n\nconst VERDICT_FILTER_OPTIONS: readonly SegmentedControlOption<AgentQualityEvalVerdictFilter>[] = [\n { value: \"all\", label: m(\"All\", { context: \"agent-eval-filter\" }), context: \"agent-eval-filter\" },\n { value: \"failed\", label: m(\"Failed or broken\", { context: \"agent-eval-filter\" }), context: \"agent-eval-filter\" },\n { value: \"passed\", label: m(\"Passed\", { context: \"agent-eval-filter\" }), context: \"agent-eval-filter\" },\n { value: \"notJudged\", label: m(\"Not judged\", { context: \"agent-eval-filter\" }), context: \"agent-eval-filter\" },\n];\n\nconst isVerdictFilter = (value: string): value is AgentQualityEvalVerdictFilter => value in AGENT_QUALITY_EVAL_VERDICT_FILTERS;\n\n/**\n * One recorded evaluation run: what ran and how its cases ended, and its cases with a verdict filter and pages. A\n * case names its fixture and model, its verdict, what went wrong (one finding per line), how long it took, its model\n * and tool calls, what it cost and the conversation it drove.\n */\nexport const AgentQualityEvalRunScreen = ({ api, evalRunId, urlStateAdapter, backLink, headerActions, linkComponent, buildConversationHref, pageSize = 50, describeModelName }: AgentQualityEvalRunScreenProps) => {\n const { t } = useTranslate();\n const locale = getUiLocale();\n const memory = useMemoryUrlState();\n const state = useUrlListState(AGENT_QUALITY_EVAL_RUN_URL_KEYS, { adapter: urlStateAdapter ?? memory.urlStateAdapter, debounceMs: 0 });\n const verdictFilter: AgentQualityEvalVerdictFilter = isVerdictFilter(state.values.verdict) ? state.values.verdict : \"all\";\n const top = Math.min(500, Math.max(1, pageSize));\n const page = /^\\d+$/.test(state.values.page) && Number(state.values.page) > 0 ? Number(state.values.page) : 1;\n const query = api.useQualityEvalRunQuery({ evalRunId, verdicts: AGENT_QUALITY_EVAL_VERDICT_FILTERS[verdictFilter], top, skip: (page - 1) * top }, { skip: evalRunId <= 0 });\n const run = query.data?.evalRun ?? null;\n const cases = wireElementsOf<AgentQualityEvalCase>(query.data?.cases);\n const caseCount = query.data?.caseCount ?? 0;\n const pageCount = Math.max(1, Math.ceil(caseCount / top));\n const modelNames = evalRunModelNamesOf(run).map((modelName) => describeModelName?.(modelName) ?? modelName);\n const title = run !== null && typeof run.suiteLabel === \"string\" && run.suiteLabel.trim() !== \"\" ? run.suiteLabel : t(\"Run #%id%\", { replacements: { id: String(evalRunId) } });\n\n const header = (\n <PageHeader\n leading={backLink}\n title={title}\n description={\n run !== null\n ? [t(\"Run #%id%\", { replacements: { id: String(evalRunId) } }), formatDateTime(run.startedAt ?? null, \"\"), formatQualityDuration(run.durationSeconds), modelNames.join(\", \"), run.host ?? \"\"]\n .filter((part) => part !== \"\" && part !== \"–\")\n .join(\" · \")\n : undefined\n }\n actions={headerActions}\n />\n );\n if (evalRunId <= 0 || (query.isError && run === null)) {\n return (\n <div data-slot=\"agent-quality-eval-run-screen\" className=\"space-y-4\">\n {header}\n <StatusCallout tone=\"destructive\" title={t(\"The evaluation run could not be loaded.\")} description={query.isError ? normalizeDddError(query.error, \"\").message : undefined} />\n </div>\n );\n }\n const isLoading = run === null;\n return (\n <div data-slot=\"agent-quality-eval-run-screen\" className=\"space-y-4\">\n {header}\n <MetricGrid columns={6} isLoading={isLoading} skeletonCount={6}>\n <MetricTile label={t(\"Pass rate\")} value={formatShare(run?.passRate, locale)} hint={t(\"%passed% of %judged% judged cases\", { replacements: { passed: formatUiNumber(run?.casesPassed ?? 0), judged: formatUiNumber(run?.casesJudged ?? 0) } })} />\n <MetricTile label={t(\"Passed\", { context: \"agent-eval-verdict\" })} value={formatUiNumber(run?.casesPassed ?? 0)} />\n <MetricTile label={t(\"Failed\", { context: \"agent-eval-verdict\" })} value={formatUiNumber(run?.casesFailed ?? 0)} />\n <MetricTile label={t(\"Error\", { context: \"agent-eval-verdict\" })} value={formatUiNumber(run?.casesErrored ?? 0)} hint={t(\"Did not finish\")} />\n <MetricTile label={t(\"Not judged\", { context: \"agent-eval-filter\" })} value={formatUiNumber((run?.casesNotApplicable ?? 0) + (run?.casesFailedAsExpected ?? 0))} hint={t(\"Not applicable, or failing by design\")} />\n <MetricTile label={t(\"Cases\", { context: \"agent-eval\" })} value={formatUiNumber(run?.casesTotal ?? 0)} hint={typeof run?.command === \"string\" ? <span className=\"font-mono break-all\">{run.command}</span> : undefined} />\n </MetricGrid>\n\n <Card data-slot=\"agent-quality-eval-cases\" className=\"gap-0 py-0\">\n <CardContent className=\"px-2 py-4\">\n <div className=\"flex flex-wrap items-center justify-between gap-3 px-3 pb-3\">\n <h2 className=\"text-base font-semibold\">{t(\"Cases\", { context: \"agent-eval\" })}</h2>\n <SegmentedControl<AgentQualityEvalVerdictFilter>\n aria-label={t(\"Verdict of the cases\")}\n value={verdictFilter}\n onValueChange={(next) => state.setValues({ verdict: next === \"all\" ? \"\" : next, page: \"\" })}\n options={VERDICT_FILTER_OPTIONS}\n />\n </div>\n {isLoading ? (\n <div className=\"space-y-2 px-3\">\n <Skeleton className=\"h-10 w-full\" />\n <Skeleton className=\"h-10 w-full\" />\n <Skeleton className=\"h-10 w-full\" />\n </div>\n ) : cases.length === 0 ? (\n <p className=\"px-3 py-10 text-center text-sm text-muted-foreground\">{verdictFilter === \"all\" ? t(\"This run recorded no case.\") : t(\"No case with this verdict.\")}</p>\n ) : (\n <div className={cn(\"overflow-x-auto transition-opacity motion-reduce:transition-none\", query.isFetching && \"opacity-60\")}>\n <Table>\n <TableHeader>\n <TableRow className=\"hover:bg-transparent\">\n <TableHead className=\"px-3 text-xs text-muted-foreground\">{t(\"Case\", { context: \"agent-eval\" })}</TableHead>\n <TableHead className=\"px-3 text-xs text-muted-foreground\">{t(\"Verdict\", { context: \"agent-eval\" })}</TableHead>\n <TableHead className=\"px-3 text-xs text-muted-foreground\">{t(\"Model\", { context: \"agent-eval\" })}</TableHead>\n <TableHead className=\"px-3 text-right text-xs text-muted-foreground\">{t(\"Duration\", { context: \"agent-eval\" })}</TableHead>\n <TableHead className=\"px-3 text-right text-xs text-muted-foreground\">{t(\"Model calls\")}</TableHead>\n <TableHead className=\"px-3 text-right text-xs text-muted-foreground\">{t(\"Tool calls\", { context: \"agent-eval\" })}</TableHead>\n <TableHead className=\"px-3 text-right text-xs text-muted-foreground\">{t(\"Cost\", { context: \"agent-statistics\" })}</TableHead>\n <TableHead className=\"px-3 text-xs text-muted-foreground\">{t(\"Conversation\", { context: \"agent-statistics\" })}</TableHead>\n </TableRow>\n </TableHeader>\n <TableBody>\n {cases.map((evalCase, index) => {\n const conversationId = evalCase.aiConversationId ?? null;\n const findings = typeof evalCase.findings === \"string\" ? evalCase.findings.trim() : \"\";\n return (\n <TableRow key={evalCase.id ?? `${evalCase.caseId}-${index}`} data-slot=\"agent-quality-eval-case\" data-verdict={evalCase.verdict ?? \"\"} className=\"hover:bg-transparent\">\n <TableCell className=\"max-w-md px-3 py-2.5 align-top whitespace-normal\">\n <span className=\"font-mono text-xs font-semibold break-all\">{evalCase.caseId ?? \"–\"}</span>\n <span className=\"block text-xs text-muted-foreground\">{[evalCase.suiteName, evalCase.fixtureName, evalCase.flavor].filter((part) => typeof part === \"string\" && part !== \"\").join(\" · \")}</span>\n {findings !== \"\" && (\n <p data-slot=\"agent-quality-eval-case-findings\" className={cn(\"mt-1 text-xs whitespace-pre-line\", evalCase.verdict === \"FAIL\" || evalCase.verdict === \"ERROR\" ? \"text-foreground\" : \"text-muted-foreground\")}>\n {findings}\n </p>\n )}\n </TableCell>\n <TableCell className=\"px-3 py-2.5 align-top\">\n <StatusBadge value={(evalCase.verdict ?? null) as AgentQualityEvalVerdict | null} map={AGENT_QUALITY_EVAL_VERDICT} />\n </TableCell>\n <TableCell className={describeModelName === undefined ? \"px-3 py-2.5 align-top font-mono text-xs\" : \"px-3 py-2.5 align-top text-sm\"} title={evalCase.modelName ?? undefined}>\n {typeof evalCase.modelName === \"string\" && evalCase.modelName !== \"\" ? (describeModelName?.(evalCase.modelName) ?? evalCase.modelName) : \"–\"}\n </TableCell>\n <TableCell className=\"px-3 py-2.5 text-right align-top text-sm tabular-nums\">{formatQualityDuration(evalCase.wallSeconds)}</TableCell>\n <TableCell className=\"px-3 py-2.5 text-right align-top text-sm tabular-nums\">{typeof evalCase.modelCalls === \"number\" ? formatUiNumber(evalCase.modelCalls) : \"–\"}</TableCell>\n <TableCell className=\"px-3 py-2.5 text-right align-top text-sm tabular-nums\">{typeof evalCase.toolCalls === \"number\" ? formatUiNumber(evalCase.toolCalls) : \"–\"}</TableCell>\n <TableCell className=\"px-3 py-2.5 text-right align-top text-sm tabular-nums\">{formatUsdAmount(evalCase.costUsd, locale)}</TableCell>\n <TableCell className=\"px-3 py-2.5 align-top\">\n {conversationId === null ? (\n <span className=\"text-muted-foreground\">–</span>\n ) : (\n <AdminHrefLink href={buildConversationHref?.(conversationId) ?? null} linkComponent={linkComponent} className=\"font-mono text-xs\">\n #{conversationId}\n </AdminHrefLink>\n )}\n </TableCell>\n </TableRow>\n );\n })}\n </TableBody>\n </Table>\n </div>\n )}\n {!isLoading && caseCount > top && (\n <div className=\"flex items-center justify-between gap-3 px-3 pt-3\">\n <span className=\"text-sm text-muted-foreground\">\n {t(\"Page %page% of %pages% · %count% cases\", { replacements: { page: formatUiNumber(page), pages: formatUiNumber(pageCount), count: formatUiNumber(caseCount) } })}\n </span>\n <span className=\"flex gap-2\">\n <Button type=\"button\" variant=\"outline\" size=\"sm\" disabled={page <= 1} onClick={() => state.setValue(\"page\", page - 1 > 1 ? String(page - 1) : \"\")}>\n <ChevronLeft aria-hidden />\n {t(\"Previous\", { context: \"agent-eval\" })}\n </Button>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" disabled={page >= pageCount} onClick={() => state.setValue(\"page\", String(page + 1))}>\n {t(\"Next\", { context: \"agent-eval\" })}\n <ChevronRight aria-hidden />\n </Button>\n </span>\n </div>\n )}\n </CardContent>\n </Card>\n </div>\n );\n};\n","import { normalizeDddError } from \"@mgamadeus/ddd-web/contract\";\nimport { DeltaText, MetricGrid, MetricTile, NoteList, type NoteItem } from \"@mgamadeus/ddd-admin-ui/data\";\nimport { formatUiNumber, getUiLocale, m, useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { DateCell, formatDateTime } from \"@mgamadeus/ddd-admin-ui/list\";\nimport { type UrlStateAdapter, useMemoryUrlState, useUrlListState } from \"@mgamadeus/ddd-admin-ui/logic\";\nimport { PageHeader, StatusCallout } from \"@mgamadeus/ddd-admin-ui/page\";\nimport { Badge, Button, Card, CardContent, cn, type PageLinkComponent, Skeleton, Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { ChevronLeft, ChevronRight, CircleCheck, CircleX, FlaskConical, PartyPopper, TriangleAlert } from \"lucide-react\";\nimport { Fragment, type ReactNode, useMemo } from \"react\";\nimport { formatShare } from \"../control-panel/control-panel-statistics\";\nimport { resolveAdminPeriod } from \"../period/admin-period\";\nimport { AdminPeriodControl } from \"../period/AdminPeriodControl\";\nimport { AdminHrefLink } from \"../shared/AdminHrefLink\";\nimport { wireElementsOf } from \"../wire/admin-wire\";\nimport type { AgentQualityApi } from \"./agent-quality-api\";\nimport {\n abortedAndExpiredTurnCountOf,\n AGENT_QUALITY_FAILURE_KIND_DEFINITIONS,\n agentQualityFailureSubjectOf,\n evalRunModelNamesOf,\n formatQualityDuration,\n groupAgentQualityFailuresByKind,\n isKnownAgentQualityFailureKind,\n qualityFigureChangeOf,\n UNKNOWN_FAILURE_KIND_ICON,\n} from \"./agent-quality-format\";\nimport type { AgentQualityEvalRunSummary, AgentQualityFailuresResponse, AgentQualitySummary } from \"./agent-quality-types\";\n\n/** The URL keys of the screen: the period (`period`, `from`, `to`) and how many of the newest evaluation runs are skipped. */\nexport const AGENT_QUALITY_URL_KEYS = [\"period\", \"from\", \"to\", \"runsOffset\"] as const;\n\nexport interface AgentQualityScreenProps {\n /** `createAgentQualityApi(…)` of the host. */\n api: AgentQualityApi;\n /** Where the period and the page of the runs live: the host's URL adapter. Without one they live in component state. */\n urlStateAdapter?: UrlStateAdapter;\n /** The page title; default \"Quality\". Already translated. */\n title?: ReactNode;\n description?: ReactNode;\n headerActions?: ReactNode;\n linkComponent?: PageLinkComponent;\n /** The link of a conversation in the host's agent screens; `null` = no link. */\n buildConversationHref?: (conversationId: number) => string | null;\n /** The host's route of one evaluation run (`AgentQualityEvalRunScreen`); `null` / absent = the runs are not links. */\n buildEvalRunHref?: (evalRunId: number) => string | null;\n /** Evaluation runs per page (default 8, at most 200). */\n evalRunsPageSize?: number;\n /** The host's display name of a model by its catalog name (\"GPT-6 Luna\"); null = the catalog name. */\n describeModelName?: (modelName: string) => string | null;\n}\n\n/** The parts a quality read may name as not readable, as the screen words them. */\nconst UNAVAILABLE_PART_LABELS: Readonly<Record<string, string>> = {\n toolCalls: m(\"tool calls\", { context: \"agent-quality-part\" }),\n errorRows: m(\"error rows\", { context: \"agent-quality-part\" }),\n turnEnds: m(\"turn ends\", { context: \"agent-quality-part\" }),\n stuckRuns: m(\"stuck runs\", { context: \"agent-quality-part\" }),\n purposeRuns: m(\"purposed runs\", { context: \"agent-quality-part\" }),\n evalRuns: m(\"evaluation runs\", { context: \"agent-quality-part\" }),\n};\n\nconst countText = (value: number | null | undefined): string => (typeof value === \"number\" ? formatUiNumber(value) : \"–\");\n\ninterface QualityTilesProps {\n summary: AgentQualitySummary | null;\n isLoading: boolean;\n}\n\nconst QualityTiles = ({ summary, isLoading }: QualityTilesProps) => {\n const { t } = useTranslate();\n const locale = getUiLocale();\n const figures = summary?.figures ?? null;\n const previous = summary?.previousFigures ?? null;\n const comparedText = t(\"against the period before\");\n const abortedAndExpired = abortedAndExpiredTurnCountOf(figures);\n const latestRun = summary?.latestEvalRun ?? null;\n const deltaOf = (current: number | null | undefined, before: number | null | undefined) => {\n const change = qualityFigureChangeOf(current, before);\n return change === null ? undefined : <DeltaText value={change} preference=\"lower\" title={comparedText} />;\n };\n return (\n <MetricGrid columns={3} isLoading={isLoading} skeletonCount={6}>\n <MetricTile\n label={t(\"Conversations with a failure\")}\n value={countText(figures?.conversationsWithFailureCount)}\n delta={deltaOf(figures?.conversationsWithFailureCount, previous?.conversationsWithFailureCount)}\n hint={t(\"An error row or a failed tool call\")}\n />\n <MetricTile label={t(\"Tool timeouts\")} value={countText(figures?.toolTimeoutCount)} delta={deltaOf(figures?.toolTimeoutCount, previous?.toolTimeoutCount)} hint={t(\"Calls that ran into their time limit\")} />\n <MetricTile\n label={t(\"Aborted or expired turns\")}\n value={countText(abortedAndExpired)}\n delta={deltaOf(abortedAndExpired, abortedAndExpiredTurnCountOf(previous))}\n hint={\n abortedAndExpired === null\n ? t(\"No turn events in this period\")\n : t(\"%aborted% aborted · %expired% expired\", { replacements: { aborted: countText(figures?.abortedTurnCount ?? 0), expired: countText(figures?.expiredTurnCount ?? 0) } })\n }\n />\n <MetricTile\n label={t(\"Purposes finished\")}\n value={formatShare(summary?.purposeFinishRate, locale)}\n hint={\n typeof summary?.purposeRunCount === \"number\"\n ? t(\"%finished% of %runs% purposed runs\", { replacements: { finished: countText(summary.finishedPurposeRunCount ?? 0), runs: countText(summary.purposeRunCount) } })\n : t(\"Not readable\")\n }\n />\n <MetricTile\n label={t(\"Eval cases green\")}\n value={latestRun !== null ? `${countText(latestRun.casesPassed ?? 0)} / ${countText(latestRun.casesJudged ?? 0)}` : \"–\"}\n hint={latestRun !== null ? [latestRun.suiteLabel, formatDateTime(latestRun.startedAt ?? null, \"\")].filter((part) => typeof part === \"string\" && part !== \"\").join(\" · \") : t(\"No evaluation run recorded\")}\n />\n <MetricTile\n label={t(\"Negative ratings\")}\n value={summary?.isSatisfactionCaptured === true ? countText(summary.thumbsDownCount) : <span className=\"text-base font-medium text-muted-foreground\">{t(\"Not captured\")}</span>}\n hint={summary?.isSatisfactionCaptured === true ? t(\"Answers rated negatively\") : t(\"No rating of an answer is stored\")}\n />\n </MetricGrid>\n );\n};\n\ninterface FailuresCardProps extends Pick<AgentQualityScreenProps, \"linkComponent\" | \"buildConversationHref\" | \"describeModelName\"> {\n response: AgentQualityFailuresResponse | null;\n isLoading: boolean;\n error: unknown;\n}\n\nconst FailuresCard = ({ response, isLoading, error, linkComponent, buildConversationHref, describeModelName }: FailuresCardProps) => {\n const { t } = useTranslate();\n const sections = useMemo(() => groupAgentQualityFailuresByKind(response?.failures), [response]);\n const notes: NoteItem[] = [];\n if (response?.isTruncated === true) notes.push({ id: \"truncated\", tone: \"warning\", text: t(\"A read reached its row limit: the counts are a lower bound.\") });\n const unavailableParts = response?.unavailableParts ?? [];\n if (unavailableParts.length > 0) {\n notes.push({\n id: \"unavailable\",\n tone: \"warning\",\n text: t(\"Not readable in this period: %parts%.\", { replacements: { parts: unavailableParts.map((part) => (UNAVAILABLE_PART_LABELS[part] !== undefined ? t(UNAVAILABLE_PART_LABELS[part], { context: \"agent-quality-part\" }) : part)).join(\", \") } }),\n });\n }\n return (\n <Card data-slot=\"agent-quality-failures\" className=\"gap-0 py-0\">\n <CardContent className=\"px-2 py-4\">\n <div className=\"px-3 pb-2\">\n <h2 className=\"text-base font-semibold\">{t(\"Failures by kind\")}</h2>\n <p className=\"text-sm text-muted-foreground\">{t(\"Grouped by kind and by the tool or model they happened with, each with its newest conversation.\")}</p>\n </div>\n <NoteList notes={notes} className=\"px-3 pb-2\" />\n {error !== undefined && response === null ? (\n <StatusCallout size=\"compact\" tone=\"destructive\" className=\"mx-3\" title={t(\"The failures could not be loaded.\")} description={normalizeDddError(error, \"\").message} />\n ) : isLoading ? (\n <div className=\"space-y-2 px-3\">\n <Skeleton className=\"h-9 w-full\" />\n <Skeleton className=\"h-9 w-full\" />\n <Skeleton className=\"h-9 w-full\" />\n </div>\n ) : sections.length === 0 ? (\n <div className=\"flex flex-col items-center gap-2 px-3 py-10 text-center\">\n <PartyPopper aria-hidden className=\"size-6 text-muted-foreground\" />\n <p className=\"text-sm text-muted-foreground\">{t(\"No failure in this period.\")}</p>\n </div>\n ) : (\n <Table>\n <TableHeader>\n <TableRow className=\"hover:bg-transparent\">\n <TableHead className=\"px-3 text-xs text-muted-foreground\">{t(\"Tool or model\")}</TableHead>\n <TableHead className=\"px-3 text-right text-xs text-muted-foreground\">{t(\"Count\", { context: \"agent-quality\" })}</TableHead>\n <TableHead className=\"px-3 text-xs text-muted-foreground\">{t(\"Newest conversation\")}</TableHead>\n <TableHead className=\"px-3 text-xs text-muted-foreground\">{t(\"Latest\", { context: \"agent-quality\" })}</TableHead>\n </TableRow>\n </TableHeader>\n <TableBody>\n {sections.map((section) => {\n const definition = isKnownAgentQualityFailureKind(section.kind) ? AGENT_QUALITY_FAILURE_KIND_DEFINITIONS[section.kind] : null;\n const KindIcon = definition?.icon ?? UNKNOWN_FAILURE_KIND_ICON;\n return (\n <Fragment key={section.kind}>\n <TableRow data-slot=\"agent-quality-failure-kind\" data-kind={section.kind} className=\"bg-tint hover:bg-tint\">\n <TableCell className=\"px-3 py-2 whitespace-normal\">\n <span className=\"flex items-center gap-2 text-sm font-semibold\">\n <KindIcon aria-hidden className=\"size-4 shrink-0 text-destructive\" />\n {definition !== null ? t(definition.label, { context: \"agent-failure-kind\" }) : section.kind}\n </span>\n {definition !== null && <span className=\"block pl-6 text-xs font-normal text-muted-foreground\">{t(definition.description, { context: \"agent-failure-kind\" })}</span>}\n </TableCell>\n <TableCell className=\"px-3 py-2 text-right align-top text-sm font-semibold tabular-nums\">{formatUiNumber(section.count)}</TableCell>\n <TableCell colSpan={2} />\n </TableRow>\n {section.groups.map((group, index) => {\n const subject = agentQualityFailureSubjectOf(group);\n // a model is named by the host's display name; a tool keeps its machine name\n const modelDisplayName = subject.name !== null && subject.name === group.modelName ? (describeModelName?.(subject.name) ?? null) : null;\n const conversationId = group.latestConversationId ?? null;\n return (\n <TableRow key={`${section.kind}-${index}`} data-slot=\"agent-quality-failure\" className=\"hover:bg-transparent\">\n <TableCell className=\"max-w-56 px-3 py-2 pl-9 whitespace-normal\">\n {modelDisplayName !== null ? (\n <span className=\"text-sm\" title={subject.name ?? undefined}>\n {modelDisplayName}\n </span>\n ) : (\n <span className={cn(\"font-mono text-xs break-all\", subject.name === null && \"text-muted-foreground\")}>{subject.name ?? \"–\"}</span>\n )}\n {subject.errorCode !== null && (\n <Badge variant=\"outline\" className=\"ml-2 font-mono text-[10px]\">\n {subject.errorCode}\n </Badge>\n )}\n </TableCell>\n <TableCell className=\"px-3 py-2 text-right tabular-nums\">{formatUiNumber(group.count ?? 0)}</TableCell>\n <TableCell className=\"max-w-64 px-3 py-2 whitespace-normal\">\n {conversationId === null ? (\n <span className=\"text-muted-foreground\">–</span>\n ) : (\n <AdminHrefLink href={buildConversationHref?.(conversationId) ?? null} linkComponent={linkComponent} className=\"line-clamp-2 text-sm break-words\">\n {typeof group.latestConversationTitle === \"string\" && group.latestConversationTitle.trim() !== \"\"\n ? group.latestConversationTitle\n : t(\"Conversation #%id%\", { replacements: { id: String(conversationId) } })}\n </AdminHrefLink>\n )}\n </TableCell>\n <TableCell className=\"px-3 py-2\">\n <DateCell value={group.latestAt} />\n </TableCell>\n </TableRow>\n );\n })}\n </Fragment>\n );\n })}\n </TableBody>\n </Table>\n )}\n </CardContent>\n </Card>\n );\n};\n\ninterface EvalRunLineProps extends Pick<AgentQualityScreenProps, \"linkComponent\" | \"buildEvalRunHref\" | \"describeModelName\"> {\n run: AgentQualityEvalRunSummary;\n}\n\n/** The counts of a run as three marks with their numbers: passed, failed, broken. */\nexport const EvalRunCounts = ({ run, className }: { run: AgentQualityEvalRunSummary; className?: string }) => {\n const { t } = useTranslate();\n return (\n <span data-slot=\"eval-run-counts\" className={cn(\"inline-flex items-center gap-3 text-xs tabular-nums\", className)}>\n <span className=\"inline-flex items-center gap-1\" title={t(\"Passed\", { context: \"agent-eval-verdict\" })}>\n <CircleCheck aria-hidden className=\"size-3.5 text-success\" />\n <span className=\"sr-only\">{t(\"Passed\", { context: \"agent-eval-verdict\" })}</span>\n {formatUiNumber(run.casesPassed ?? 0)}\n </span>\n <span className={cn(\"inline-flex items-center gap-1\", (run.casesFailed ?? 0) === 0 && \"text-muted-foreground\")} title={t(\"Failed\", { context: \"agent-eval-verdict\" })}>\n <CircleX aria-hidden className={cn(\"size-3.5\", (run.casesFailed ?? 0) > 0 ? \"text-destructive\" : \"text-muted-foreground\")} />\n <span className=\"sr-only\">{t(\"Failed\", { context: \"agent-eval-verdict\" })}</span>\n {formatUiNumber(run.casesFailed ?? 0)}\n </span>\n <span className={cn(\"inline-flex items-center gap-1\", (run.casesErrored ?? 0) === 0 && \"text-muted-foreground\")} title={t(\"Error\", { context: \"agent-eval-verdict\" })}>\n <TriangleAlert aria-hidden className={cn(\"size-3.5\", (run.casesErrored ?? 0) > 0 ? \"text-destructive\" : \"text-muted-foreground\")} />\n <span className=\"sr-only\">{t(\"Error\", { context: \"agent-eval-verdict\" })}</span>\n {formatUiNumber(run.casesErrored ?? 0)}\n </span>\n </span>\n );\n};\n\nconst EvalRunLine = ({ run, linkComponent, buildEvalRunHref, describeModelName }: EvalRunLineProps) => {\n const { t } = useTranslate();\n const evalRunId = run.evalRunId ?? null;\n const modelNames = evalRunModelNamesOf(run).map((modelName) => describeModelName?.(modelName) ?? modelName);\n const label = typeof run.suiteLabel === \"string\" && run.suiteLabel.trim() !== \"\" ? run.suiteLabel : evalRunId !== null ? t(\"Run #%id%\", { replacements: { id: String(evalRunId) } }) : t(\"Evaluation run\");\n return (\n <li data-slot=\"agent-quality-eval-run\" data-eval-run={evalRunId ?? \"\"} className=\"space-y-1 py-3\">\n <div className=\"flex items-start gap-x-3\">\n <AdminHrefLink href={evalRunId === null ? null : (buildEvalRunHref?.(evalRunId) ?? null)} linkComponent={linkComponent} className=\"min-w-0 flex-1 text-sm font-semibold break-all\">\n {label}\n </AdminHrefLink>\n <Badge variant={run.isGreen === true ? \"success\" : (run.casesJudged ?? 0) > 0 ? \"destructive\" : \"secondary\"} className=\"shrink-0 text-[11px]\">\n {(run.casesJudged ?? 0) > 0\n ? t(\"%passed% of %judged% passed\", { replacements: { passed: formatUiNumber(run.casesPassed ?? 0), judged: formatUiNumber(run.casesJudged ?? 0) } })\n : t(\"no judged case\")}\n </Badge>\n </div>\n <div className=\"flex items-start justify-between gap-x-3 text-xs text-muted-foreground\">\n <span className=\"flex min-w-0 flex-wrap items-center gap-x-3 gap-y-0.5\">\n <DateCell value={run.startedAt} className=\"text-xs\" />\n <span>{formatQualityDuration(run.durationSeconds)}</span>\n {modelNames.length > 0 && <span className={cn(\"break-all\", describeModelName === undefined && \"font-mono\")}>{modelNames.join(\", \")}</span>}\n </span>\n <EvalRunCounts run={run} className=\"shrink-0\" />\n </div>\n </li>\n );\n};\n\n/**\n * Where the agent fails and whether it still passes its evaluation: the figures of a period beside the period before\n * (conversations with a failure, tool timeouts, aborted or expired turns, purposes finished, the newest evaluation\n * run, ratings), the failures grouped by kind and by tool or model with their newest conversation, and the recorded\n * evaluation runs.\n */\nexport const AgentQualityScreen = ({ api, urlStateAdapter, title, description, headerActions, linkComponent, buildConversationHref, buildEvalRunHref, evalRunsPageSize = 8, describeModelName }: AgentQualityScreenProps) => {\n const { t } = useTranslate();\n const memory = useMemoryUrlState();\n const state = useUrlListState(AGENT_QUALITY_URL_KEYS, { adapter: urlStateAdapter ?? memory.urlStateAdapter, debounceMs: 0 });\n const values = state.values;\n const period = useMemo(() => resolveAdminPeriod({ preset: values.period, from: values.from, to: values.to }, \"7d\"), [values.period, values.from, values.to]);\n const pageSize = Math.min(200, Math.max(1, evalRunsPageSize));\n const runsOffset = /^\\d+$/.test(values.runsOffset) ? Number(values.runsOffset) : 0;\n\n const summaryQuery = api.useQualitySummaryQuery({ from: period.from, to: period.to });\n const failuresQuery = api.useQualityFailuresQuery({ from: period.from, to: period.to });\n // one run more than a page shows: whether there is a next page\n const runsQuery = api.useQualityEvalRunsQuery({ limit: pageSize + 1, offset: runsOffset });\n const summary = summaryQuery.data?.summary ?? null;\n const runs = runsQuery.data?.evalRuns == null ? null : wireElementsOf(runsQuery.data.evalRuns);\n const shownRuns = (runs ?? []).slice(0, pageSize);\n const hasMoreRuns = (runs ?? []).length > pageSize;\n const stuckRunCount = summary?.stuckRunCount ?? 0;\n const summaryUnavailableParts = summary?.unavailableParts ?? [];\n\n return (\n <div data-slot=\"agent-quality-screen\" className=\"space-y-4\">\n <PageHeader\n title={title ?? t(\"Quality\", { context: \"agent-quality\" })}\n description={description ?? t(\"Where the agent fails, and whether it still passes its evaluation after a change.\")}\n actions={\n <>\n {headerActions}\n <AdminPeriodControl period={period} onChange={(next) => state.setValues({ period: next.preset, from: next.from, to: next.to })} />\n </>\n }\n />\n\n {summaryQuery.isError && summary === null ? (\n <StatusCallout tone=\"destructive\" title={t(\"The quality figures could not be loaded.\")} description={normalizeDddError(summaryQuery.error, \"\").message} />\n ) : (\n <QualityTiles summary={summary} isLoading={summaryQuery.isLoading || (summary === null && summaryQuery.isFetching)} />\n )}\n {stuckRunCount > 0 && (\n <StatusCallout\n tone=\"warning\"\n size=\"compact\"\n title={t(\"{count, plural, one {# conversation is marked as running without a heartbeat.} other {# conversations are marked as running without a heartbeat.}}\", { count: stuckRunCount })}\n description={t(\"No heartbeat for more than %duration%.\", { replacements: { duration: formatQualityDuration(summary?.stuckAfterSeconds ?? 0) } })}\n />\n )}\n {summaryUnavailableParts.length > 0 && (\n <NoteList\n notes={[\n {\n id: \"summaryUnavailable\",\n tone: \"warning\",\n text: t(\"Not readable in this period: %parts%.\", {\n replacements: { parts: summaryUnavailableParts.map((part) => (UNAVAILABLE_PART_LABELS[part] !== undefined ? t(UNAVAILABLE_PART_LABELS[part], { context: \"agent-quality-part\" }) : part)).join(\", \") },\n }),\n },\n ]}\n />\n )}\n\n <div className=\"grid items-start gap-4 xl:grid-cols-[minmax(0,1.5fr)_minmax(0,1fr)]\">\n <FailuresCard\n response={failuresQuery.data ?? null}\n isLoading={failuresQuery.isLoading || (failuresQuery.data === undefined && failuresQuery.isFetching)}\n error={failuresQuery.isError ? failuresQuery.error : undefined}\n linkComponent={linkComponent}\n buildConversationHref={buildConversationHref}\n describeModelName={describeModelName}\n />\n\n <Card data-slot=\"agent-quality-eval-runs\" className=\"gap-0 py-0\">\n <CardContent className=\"px-5 py-4\">\n <h2 className=\"text-base font-semibold\">{t(\"Evaluation runs\")}</h2>\n <p className=\"text-sm text-muted-foreground\">{t(\"The recorded runs of the evaluation suites, the newest first.\")}</p>\n {runsQuery.isError && runs === null ? (\n <StatusCallout size=\"compact\" tone=\"destructive\" className=\"mt-3\" title={t(\"The evaluation runs could not be loaded.\")} description={normalizeDddError(runsQuery.error, \"\").message} />\n ) : runs === null ? (\n <div className=\"space-y-2 pt-3\">\n <Skeleton className=\"h-12 w-full\" />\n <Skeleton className=\"h-12 w-full\" />\n <Skeleton className=\"h-12 w-full\" />\n </div>\n ) : shownRuns.length === 0 ? (\n <div className=\"flex flex-col items-center gap-2 py-10 text-center\">\n <FlaskConical aria-hidden className=\"size-6 text-muted-foreground\" />\n <p className=\"text-sm text-muted-foreground\">{runsOffset > 0 ? t(\"No older evaluation run.\") : t(\"No evaluation run recorded yet.\")}</p>\n </div>\n ) : (\n <ul className={cn(\"divide-y divide-border transition-opacity motion-reduce:transition-none\", runsQuery.isFetching && \"opacity-60\")}>\n {shownRuns.map((run, index) => (\n <EvalRunLine key={run.evalRunId ?? index} run={run} linkComponent={linkComponent} buildEvalRunHref={buildEvalRunHref} describeModelName={describeModelName} />\n ))}\n </ul>\n )}\n {(runsOffset > 0 || hasMoreRuns) && (\n <div className=\"flex items-center justify-end gap-2 border-t border-border pt-3\">\n <Button type=\"button\" variant=\"outline\" size=\"sm\" disabled={runsOffset === 0} onClick={() => state.setValue(\"runsOffset\", runsOffset - pageSize > 0 ? String(runsOffset - pageSize) : \"\")}>\n <ChevronLeft aria-hidden />\n {t(\"Newer\", { context: \"agent-quality\" })}\n </Button>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" disabled={!hasMoreRuns} onClick={() => state.setValue(\"runsOffset\", String(runsOffset + pageSize))}>\n {t(\"Older\", { context: \"agent-quality\" })}\n <ChevronRight aria-hidden />\n </Button>\n </div>\n )}\n <p className=\"border-t border-border pt-3 text-xs text-muted-foreground\">{t(\"A case is made from a stored turn: in the debug view of a conversation, “Save as eval case”.\")}</p>\n </CardContent>\n </Card>\n </div>\n </div>\n );\n};\n","import { normalizeDddError } from \"@mgamadeus/ddd-web/contract\";\nimport type { CodeHighlighterLoader } from \"@mgamadeus/ddd-admin-ui/files\";\nimport { m, useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { StatusCallout } from \"@mgamadeus/ddd-admin-ui/page\";\nimport { Badge, Button, Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, SegmentedControl, type SegmentedControlOption, Skeleton } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { Download } from \"lucide-react\";\nimport { useEffect, useState } from \"react\";\nimport { CodeBlock } from \"../blocks/CodeBlock\";\nimport type { AgentQualityApi } from \"./agent-quality-api\";\nimport { evalCaseFileNameOf } from \"./agent-quality-format\";\nimport type { AgentQualityEvalCaseDraft } from \"./agent-quality-types\";\n\nexport interface SaveAsEvalCaseDialogProps {\n /** `createAgentQualityApi(…)` of the host (the dialog uses its `useDraftEvalCaseMutation`). */\n api: Pick<AgentQualityApi, \"useDraftEvalCaseMutation\">;\n /** The conversation the case is made from. */\n conversationId: number;\n /**\n * A message of the turn (the owner's message or any row after it). The route needs this or `messageIndex`: without\n * both it refuses the draft and the dialog shows its message.\n */\n messageId?: number;\n /** Without `messageId`: the position of a message of the turn in the conversation. */\n messageIndex?: number;\n open: boolean;\n onOpenChange: (open: boolean) => void;\n /** Colours the JSON with the host's highlighter; without it the JSON stays plain. */\n loadCodeHighlighter?: CodeHighlighterLoader;\n}\n\ntype DraftView = \"case\" | \"fixture\";\n\nconst VIEW_OPTIONS: readonly SegmentedControlOption<DraftView>[] = [\n { value: \"case\", label: m(\"Case\", { context: \"agent-eval-draft\" }), context: \"agent-eval-draft\" },\n { value: \"fixture\", label: m(\"Fixture file\", { context: \"agent-eval-draft\" }), context: \"agent-eval-draft\" },\n];\n\n/** Hands a text to the browser as a file to save. */\nconst downloadTextFile = (fileName: string, text: string) => {\n const url = URL.createObjectURL(new Blob([text], { type: \"application/json\" }));\n const anchor = document.createElement(\"a\");\n anchor.href = url;\n anchor.download = fileName;\n document.body.append(anchor);\n anchor.click();\n anchor.remove();\n URL.revokeObjectURL(url);\n};\n\n/**\n * Drafts an evaluation case from one stored turn and shows it for a person to keep: the prompt, the skills the agent\n * loaded and the tools it called in the turn, and the case as JSON (alone, or as a fixture file with this one case)\n * with copy and \"Download\". The draft is asked for when the dialog opens; nothing is written on the server, and what\n * the agent did is not necessarily what it should have done, so the JSON is reviewed before it goes into a fixture\n * folder.\n */\nexport const SaveAsEvalCaseDialog = ({ api, conversationId, messageId, messageIndex, open, onOpenChange, loadCodeHighlighter }: SaveAsEvalCaseDialogProps) => {\n const { t } = useTranslate();\n const [draftEvalCase] = api.useDraftEvalCaseMutation();\n const [draft, setDraft] = useState<AgentQualityEvalCaseDraft | null>(null);\n const [error, setError] = useState<string | null>(null);\n const [view, setView] = useState<DraftView>(\"case\");\n\n useEffect(() => {\n if (!open) return;\n let isCurrent = true;\n setDraft(null);\n setError(null);\n const call = draftEvalCase({ conversationId, messageId, messageIndex });\n call\n .unwrap()\n .then((response) => {\n if (!isCurrent) return;\n if (response.evalCase) setDraft(response.evalCase);\n else setError(t(\"No case could be made from this turn.\"));\n })\n .catch((caught: unknown) => {\n if (isCurrent) setError(normalizeDddError(caught, t(\"The case could not be drafted.\")).message);\n });\n return () => {\n isCurrent = false;\n };\n // biome-ignore lint/correctness/useExhaustiveDependencies: one draft per opening and turn; the trigger and `t` change identity between renders\n }, [open, conversationId, messageId, messageIndex]);\n\n const json = draft === null ? \"\" : view === \"fixture\" ? (draft.fixtureJson ?? \"\") : (draft.caseJson ?? \"\");\n const skillNames = draft?.skillNames ?? [];\n const toolNames = draft?.toolNames ?? [];\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent data-slot=\"save-as-eval-case-dialog\" className=\"flex max-h-[90vh] flex-col sm:max-w-3xl\">\n <DialogHeader>\n <DialogTitle>{t(\"Save as eval case\")}</DialogTitle>\n <DialogDescription>\n {t(\"A draft made from this turn: its prompt, and what the agent did as the expectation. Nothing was saved. Review it and keep the JSON in the fixture folder of the application.\")}\n </DialogDescription>\n </DialogHeader>\n <div className=\"min-h-0 flex-1 space-y-4 overflow-y-auto\">\n {error !== null ? (\n <StatusCallout size=\"compact\" tone=\"destructive\" title={error} />\n ) : draft === null ? (\n <div className=\"space-y-2\">\n <Skeleton className=\"h-5 w-64\" />\n <Skeleton className=\"h-48 w-full\" />\n </div>\n ) : (\n <>\n <dl className=\"grid grid-cols-[auto_minmax(0,1fr)] gap-x-4 gap-y-1.5 text-sm\">\n <dt className=\"text-muted-foreground\">{t(\"Case id\")}</dt>\n <dd className=\"font-mono text-xs break-all\">{draft.caseId ?? \"–\"}</dd>\n <dt className=\"text-muted-foreground\">{t(\"Prompt\", { context: \"agent-eval-draft\" })}</dt>\n <dd className=\"line-clamp-4 whitespace-pre-line\">{draft.prompt ?? \"\"}</dd>\n {typeof draft.purposeName === \"string\" && draft.purposeName !== \"\" && (\n <>\n <dt className=\"text-muted-foreground\">{t(\"Purpose\", { context: \"agent-eval-draft\" })}</dt>\n <dd className=\"font-mono text-xs\">{draft.purposeName}</dd>\n </>\n )}\n <dt className=\"text-muted-foreground\">{t(\"Skills loaded\")}</dt>\n <dd className=\"flex flex-wrap gap-1\">\n {skillNames.length === 0 ? (\n <span className=\"text-muted-foreground\">{t(\"none\", { context: \"agent-eval-draft\" })}</span>\n ) : (\n skillNames.map((name) => (\n <Badge key={name} variant=\"outline\" className=\"font-mono text-[11px]\">\n {name}\n </Badge>\n ))\n )}\n </dd>\n <dt className=\"text-muted-foreground\">{t(\"Tools called\")}</dt>\n <dd className=\"flex flex-wrap gap-1\">\n {toolNames.length === 0 ? (\n <span className=\"text-muted-foreground\">{t(\"none\", { context: \"agent-eval-draft\" })}</span>\n ) : (\n toolNames.map((name) => (\n <Badge key={name} variant=\"outline\" className=\"font-mono text-[11px]\">\n {name}\n </Badge>\n ))\n )}\n </dd>\n </dl>\n <CodeBlock\n code={json}\n language=\"json\"\n loadCodeHighlighter={loadCodeHighlighter}\n defaultWrap={false}\n aria-label={view === \"fixture\" ? t(\"The fixture file as JSON\") : t(\"The case as JSON\")}\n caption={<SegmentedControl<DraftView> aria-label={t(\"What the JSON holds\")} value={view} onValueChange={setView} options={VIEW_OPTIONS} />}\n />\n </>\n )}\n </div>\n <DialogFooter>\n <Button type=\"button\" variant=\"outline\" onClick={() => onOpenChange(false)}>\n {t(\"Close\", { context: \"agent-eval-draft\" })}\n </Button>\n <Button type=\"button\" data-slot=\"save-as-eval-case-download\" disabled={draft === null || json === \"\"} onClick={() => downloadTextFile(evalCaseFileNameOf(draft?.caseId, view), json)}>\n <Download aria-hidden />\n {t(\"Download as file\")}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n );\n};\n","import {\n type ApiMutationHook,\n type ApiQueryHook,\n type InjectableBaseApi,\n type InjectedEndpointDefinition,\n type InjectedRequest,\n injectEndpointsOnce,\n staticMutationHook,\n type StaticQueryFailure,\n staticQueryHook,\n toQueryString,\n trimApiPrefix,\n} from \"@mgamadeus/ddd-admin-ui/logic/pure\";\nimport { type AgentInspectContextApi, createAgentInspectContextApi, createStaticAgentInspectContextApi, type StaticAgentInspectContextData } from \"../context/agent-inspect-context-api\";\nimport type {\n AgentInspectCompactionNodesResponse,\n AgentInspectConversationArg,\n AgentInspectConversationResponse,\n AgentInspectConversationsResponse,\n AgentInspectDelegationsResponse,\n AgentInspectDriveArg,\n AgentInspectDriveResponse,\n AgentInspectFileChangeArg,\n AgentInspectFileChangeDiffResponse,\n AgentInspectFileChangesResponse,\n AgentInspectListArg,\n AgentInspectMessageRouteArg,\n AgentInspectMessageTextResponse,\n AgentInspectMetricsResponse,\n AgentInspectRunControlResponse,\n AgentInspectRunSettingsArg,\n AgentInspectRunSettingsResponse,\n AgentInspectSandboxResponse,\n AgentInspectToolCallReplayResponse,\n AgentInspectToolCallResultResponse,\n AgentInspectTraceArg,\n AgentInspectTraceResponse,\n AgentInspectTruncateArg,\n AgentInspectTruncateResponse,\n} from \"./agent-inspect-types\";\n\n/** The cache tag type of the inspection reads (ids `LIST`, `METRICS`, `CONVERSATION`). */\nexport const AGENT_INSPECT_TAG = \"AdminUiAgentInspect\";\n\n/**\n * The hooks `createAgentInspectApi` returns; the conversation screens take them as `api`. Every read of one\n * conversation carries the tag `CONVERSATION`, so an admin action (drive, truncate, run settings, cancel, stop)\n * refreshes the open detail, the list and the metrics.\n */\nexport interface AgentInspectApi {\n /** `GET /list`: a page of conversations with the labels of their accounts and spaces. */\n useConversationsQuery: ApiQueryHook<AgentInspectListArg, AgentInspectConversationsResponse>;\n /** `GET /metrics`: the figures of the period and of the period before. */\n useMetricsQuery: ApiQueryHook<AgentInspectListArg, AgentInspectMetricsResponse>;\n /** `GET /{id}`: the header of one conversation. */\n useConversationQuery: ApiQueryHook<AgentInspectConversationArg, AgentInspectConversationResponse>;\n /** `GET /{id}/trace`: a window of turns with their steps (`mapAgentInspectTrace` reads the answer). */\n useTraceQuery: ApiQueryHook<AgentInspectTraceArg, AgentInspectTraceResponse>;\n /** `GET /{id}/delegations` (`mapAgentInspectDelegationTree`). */\n useDelegationsQuery: ApiQueryHook<AgentInspectConversationArg, AgentInspectDelegationsResponse>;\n /** `GET /{id}/fileChanges` (`mapAgentInspectFileChanges`). */\n useFileChangesQuery: ApiQueryHook<AgentInspectConversationArg, AgentInspectFileChangesResponse>;\n /** `GET /{id}/fileChanges/{fileChangeId}/diff`: the whole diff of one change. */\n useFileChangeDiffQuery: ApiQueryHook<AgentInspectFileChangeArg, AgentInspectFileChangeDiffResponse>;\n /** `GET /{id}/sandbox` (`mapAgentInspectSandboxChronicle`). */\n useSandboxQuery: ApiQueryHook<AgentInspectConversationArg, AgentInspectSandboxResponse>;\n /** `GET /{id}/compactionNodes`. */\n useCompactionNodesQuery: ApiQueryHook<AgentInspectConversationArg, AgentInspectCompactionNodesResponse>;\n /** `GET /{id}/toolCalls/{messageId}/result`: the whole stored result of a tool call. */\n useToolCallResultQuery: ApiQueryHook<AgentInspectMessageRouteArg, AgentInspectToolCallResultResponse>;\n /** `GET /{id}/messages/{messageId}/text`: the whole text of a message the trace cut (`mapAgentInspectMessageText`). */\n useMessageTextQuery: ApiQueryHook<AgentInspectMessageRouteArg, AgentInspectMessageTextResponse>;\n /** `POST /{id}/drive`: writes a message as admin and runs a turn. */\n useDriveMutation: ApiMutationHook<AgentInspectDriveArg, AgentInspectDriveResponse>;\n /** `POST /{id}/truncate`: truncates from a position. */\n useTruncateMutation: ApiMutationHook<AgentInspectTruncateArg, AgentInspectTruncateResponse>;\n /** `POST /{id}/runSettings`: sets run settings on the conversation. */\n useRunSettingsMutation: ApiMutationHook<AgentInspectRunSettingsArg, AgentInspectRunSettingsResponse>;\n /** `POST /{id}/toolCalls/{messageId}/replay`: runs a reading tool again with the stored arguments. */\n useReplayToolCallMutation: ApiMutationHook<AgentInspectMessageRouteArg, AgentInspectToolCallReplayResponse>;\n /** `POST /{id}/cancel`: asks the running turn to end at its next step. */\n useCancelRunMutation: ApiMutationHook<AgentInspectConversationArg, AgentInspectRunControlResponse>;\n /** `POST /{id}/stop`: ends the run at once. */\n useStopRunMutation: ApiMutationHook<AgentInspectConversationArg, AgentInspectRunControlResponse>;\n /** The context composition and the sent payload of a message's model call, for the context panels. */\n context: AgentInspectContextApi;\n}\n\nexport interface CreateAgentInspectApiOptions {\n /** The host's RTK Query api (`createApi` with the React hooks module). */\n baseApi: InjectableBaseApi;\n /** Where the host mounts the inspection and drive traits, without a trailing slash (`/api/admin/ai/agentInspect`). */\n apiPrefix: string;\n}\n\nconst joined = (values: readonly (string | number)[] | undefined): string | undefined =>\n values !== undefined && values.length > 0 ? values.join(\",\") : undefined;\n\n/** The query string of the list and the metrics: the filters as the request DTO names them, lists comma-separated. */\nexport const buildAgentInspectListQuery = (arg: AgentInspectListArg = {}, withPaging = true): string =>\n toQueryString({\n from: arg.from,\n to: arg.to,\n accountIds: joined(arg.accountIds),\n agentSpaceIds: joined(arg.agentSpaceIds),\n runStates: joined(arg.runStates),\n purposeName: arg.purposeName,\n origin: arg.origin,\n modelName: arg.modelName,\n toolName: arg.toolName,\n loadedSkillName: arg.loadedSkillName,\n minimumCostInUSD: arg.minimumCostInUSD,\n search: arg.search,\n segment: arg.segment,\n sortBy: withPaging ? arg.sortBy : undefined,\n includeEvalRuns: arg.includeEvalRuns === true ? 1 : undefined,\n limit: withPaging ? arg.limit : undefined,\n offset: withPaging ? arg.offset : undefined,\n });\n\n/** The request of every operation, on `apiPrefix`. Pure: no RTK runtime. */\nexport const buildAgentInspectRequests = (apiPrefix: string) => {\n const prefix = trimApiPrefix(apiPrefix);\n const conversationPath = ({ conversationId }: AgentInspectConversationArg): string => `${prefix}/${encodeURIComponent(String(conversationId))}`;\n const post = (url: string, body?: unknown): InjectedRequest => ({ url, method: \"POST\", body: body ?? {} });\n return {\n conversations: (arg: AgentInspectListArg = {}): InjectedRequest => ({ url: `${prefix}/list${buildAgentInspectListQuery(arg)}` }),\n metrics: (arg: AgentInspectListArg = {}): InjectedRequest => ({ url: `${prefix}/metrics${buildAgentInspectListQuery(arg, false)}` }),\n conversation: (arg: AgentInspectConversationArg): InjectedRequest => ({ url: conversationPath(arg) }),\n trace: (arg: AgentInspectTraceArg): InjectedRequest => ({\n url: `${conversationPath(arg)}/trace${toQueryString({\n detailLevel: arg.detailLevel,\n fromTurnNumber: arg.fromTurnNumber,\n limit: arg.limit,\n afterMessageIndex: arg.afterMessageIndex,\n includeTruncated: arg.includeTruncated === true ? 1 : undefined,\n })}`,\n }),\n delegations: (arg: AgentInspectConversationArg): InjectedRequest => ({ url: `${conversationPath(arg)}/delegations` }),\n fileChanges: (arg: AgentInspectConversationArg): InjectedRequest => ({ url: `${conversationPath(arg)}/fileChanges` }),\n fileChangeDiff: (arg: AgentInspectFileChangeArg): InjectedRequest => ({\n url: `${conversationPath(arg)}/fileChanges/${encodeURIComponent(String(arg.fileChangeId))}/diff`,\n }),\n sandbox: (arg: AgentInspectConversationArg): InjectedRequest => ({ url: `${conversationPath(arg)}/sandbox` }),\n compactionNodes: (arg: AgentInspectConversationArg): InjectedRequest => ({ url: `${conversationPath(arg)}/compactionNodes` }),\n toolCallResult: (arg: AgentInspectMessageRouteArg): InjectedRequest => ({\n url: `${conversationPath(arg)}/toolCalls/${encodeURIComponent(String(arg.messageId))}/result`,\n }),\n messageText: (arg: AgentInspectMessageRouteArg): InjectedRequest => ({\n url: `${conversationPath(arg)}/messages/${encodeURIComponent(String(arg.messageId))}/text`,\n }),\n drive: ({ conversationId, ...body }: AgentInspectDriveArg): InjectedRequest => post(`${conversationPath({ conversationId })}/drive`, body),\n truncate: ({ conversationId, fromIndex }: AgentInspectTruncateArg): InjectedRequest =>\n post(`${conversationPath({ conversationId })}/truncate`, { fromIndex }),\n runSettings: ({ conversationId, runSettingsOverride }: AgentInspectRunSettingsArg): InjectedRequest =>\n post(`${conversationPath({ conversationId })}/runSettings`, { runSettingsOverride }),\n replayToolCall: (arg: AgentInspectMessageRouteArg): InjectedRequest =>\n post(`${conversationPath(arg)}/toolCalls/${encodeURIComponent(String(arg.messageId))}/replay`),\n cancelRun: (arg: AgentInspectConversationArg): InjectedRequest => post(`${conversationPath(arg)}/cancel`),\n stopRun: (arg: AgentInspectConversationArg): InjectedRequest => post(`${conversationPath(arg)}/stop`),\n };\n};\n\nconst LIST = { type: AGENT_INSPECT_TAG, id: \"LIST\" } as const;\nconst METRICS = { type: AGENT_INSPECT_TAG, id: \"METRICS\" } as const;\nconst CONVERSATION = { type: AGENT_INSPECT_TAG, id: \"CONVERSATION\" } as const;\n/** What an admin action changes: the open conversation, its row in the list and the figures. */\nconst CHANGED_BY_AN_ACTION = [CONVERSATION, LIST, METRICS] as const;\n\n/** The operations as injected. */\nexport const agentInspectEndpointDefinitions = (apiPrefix: string) => {\n const requests = buildAgentInspectRequests(apiPrefix);\n return {\n adminUiAgentInspectConversations: { kind: \"query\", request: requests.conversations, providesTags: [LIST] },\n adminUiAgentInspectMetrics: { kind: \"query\", request: requests.metrics, providesTags: [METRICS] },\n adminUiAgentInspectConversation: { kind: \"query\", request: requests.conversation, providesTags: [CONVERSATION] },\n adminUiAgentInspectTrace: { kind: \"query\", request: requests.trace, providesTags: [CONVERSATION] },\n adminUiAgentInspectDelegations: { kind: \"query\", request: requests.delegations, providesTags: [CONVERSATION] },\n adminUiAgentInspectFileChanges: { kind: \"query\", request: requests.fileChanges, providesTags: [CONVERSATION] },\n adminUiAgentInspectFileChangeDiff: { kind: \"query\", request: requests.fileChangeDiff },\n adminUiAgentInspectSandbox: { kind: \"query\", request: requests.sandbox, providesTags: [CONVERSATION] },\n adminUiAgentInspectCompactionNodes: { kind: \"query\", request: requests.compactionNodes, providesTags: [CONVERSATION] },\n adminUiAgentInspectToolCallResult: { kind: \"query\", request: requests.toolCallResult },\n adminUiAgentInspectMessageText: { kind: \"query\", request: requests.messageText },\n adminUiAgentInspectDrive: { kind: \"mutation\", request: requests.drive, invalidatesTags: CHANGED_BY_AN_ACTION },\n adminUiAgentInspectTruncate: { kind: \"mutation\", request: requests.truncate, invalidatesTags: CHANGED_BY_AN_ACTION },\n adminUiAgentInspectRunSettings: { kind: \"mutation\", request: requests.runSettings, invalidatesTags: CHANGED_BY_AN_ACTION },\n adminUiAgentInspectReplayToolCall: { kind: \"mutation\", request: requests.replayToolCall },\n adminUiAgentInspectCancelRun: { kind: \"mutation\", request: requests.cancelRun, invalidatesTags: CHANGED_BY_AN_ACTION },\n adminUiAgentInspectStopRun: { kind: \"mutation\", request: requests.stopRun, invalidatesTags: CHANGED_BY_AN_ACTION },\n } as const satisfies Record<string, InjectedEndpointDefinition<never>>;\n};\n\n/**\n * Injects the inspection and drive operations into the host's RTK Query api and returns their hooks. Call it once at\n * module scope:\n * `export const agentInspectApi = createAgentInspectApi({ baseApi: adminApi, apiPrefix: \"/api/admin/ai/agentInspect\" });`\n */\nexport const createAgentInspectApi = ({ baseApi, apiPrefix }: CreateAgentInspectApiOptions): AgentInspectApi => {\n const hooks = injectEndpointsOnce(\n baseApi,\n `agentInspect:${trimApiPrefix(apiPrefix)}`,\n [AGENT_INSPECT_TAG],\n agentInspectEndpointDefinitions(apiPrefix),\n (hookOf): Omit<AgentInspectApi, \"context\"> => ({\n useConversationsQuery: hookOf(\"adminUiAgentInspectConversations\") as AgentInspectApi[\"useConversationsQuery\"],\n useMetricsQuery: hookOf(\"adminUiAgentInspectMetrics\") as AgentInspectApi[\"useMetricsQuery\"],\n useConversationQuery: hookOf(\"adminUiAgentInspectConversation\") as AgentInspectApi[\"useConversationQuery\"],\n useTraceQuery: hookOf(\"adminUiAgentInspectTrace\") as AgentInspectApi[\"useTraceQuery\"],\n useDelegationsQuery: hookOf(\"adminUiAgentInspectDelegations\") as AgentInspectApi[\"useDelegationsQuery\"],\n useFileChangesQuery: hookOf(\"adminUiAgentInspectFileChanges\") as AgentInspectApi[\"useFileChangesQuery\"],\n useFileChangeDiffQuery: hookOf(\"adminUiAgentInspectFileChangeDiff\") as AgentInspectApi[\"useFileChangeDiffQuery\"],\n useSandboxQuery: hookOf(\"adminUiAgentInspectSandbox\") as AgentInspectApi[\"useSandboxQuery\"],\n useCompactionNodesQuery: hookOf(\"adminUiAgentInspectCompactionNodes\") as AgentInspectApi[\"useCompactionNodesQuery\"],\n useToolCallResultQuery: hookOf(\"adminUiAgentInspectToolCallResult\") as AgentInspectApi[\"useToolCallResultQuery\"],\n useMessageTextQuery: hookOf(\"adminUiAgentInspectMessageText\") as AgentInspectApi[\"useMessageTextQuery\"],\n useDriveMutation: hookOf(\"adminUiAgentInspectDrive\") as AgentInspectApi[\"useDriveMutation\"],\n useTruncateMutation: hookOf(\"adminUiAgentInspectTruncate\") as AgentInspectApi[\"useTruncateMutation\"],\n useRunSettingsMutation: hookOf(\"adminUiAgentInspectRunSettings\") as AgentInspectApi[\"useRunSettingsMutation\"],\n useReplayToolCallMutation: hookOf(\"adminUiAgentInspectReplayToolCall\") as AgentInspectApi[\"useReplayToolCallMutation\"],\n useCancelRunMutation: hookOf(\"adminUiAgentInspectCancelRun\") as AgentInspectApi[\"useCancelRunMutation\"],\n useStopRunMutation: hookOf(\"adminUiAgentInspectStopRun\") as AgentInspectApi[\"useStopRunMutation\"],\n }),\n );\n return { ...hooks, context: createAgentInspectContextApi({ baseApi, apiPrefix }) };\n};\n\ntype StaticAnswer<TArg, TData> = (arg: TArg) => TData | StaticQueryFailure | undefined;\n\n/** Fixed answers of a `createStaticAgentInspectApi`; a query without one stays loading, a mutation without one answers `{}`. */\nexport interface StaticAgentInspectData extends StaticAgentInspectContextData {\n conversations?: StaticAnswer<AgentInspectListArg, AgentInspectConversationsResponse>;\n metrics?: StaticAnswer<AgentInspectListArg, AgentInspectMetricsResponse>;\n conversation?: StaticAnswer<AgentInspectConversationArg, AgentInspectConversationResponse>;\n trace?: StaticAnswer<AgentInspectTraceArg, AgentInspectTraceResponse>;\n delegations?: StaticAnswer<AgentInspectConversationArg, AgentInspectDelegationsResponse>;\n fileChanges?: StaticAnswer<AgentInspectConversationArg, AgentInspectFileChangesResponse>;\n fileChangeDiff?: StaticAnswer<AgentInspectFileChangeArg, AgentInspectFileChangeDiffResponse>;\n sandbox?: StaticAnswer<AgentInspectConversationArg, AgentInspectSandboxResponse>;\n compactionNodes?: StaticAnswer<AgentInspectConversationArg, AgentInspectCompactionNodesResponse>;\n toolCallResult?: StaticAnswer<AgentInspectMessageRouteArg, AgentInspectToolCallResultResponse>;\n messageText?: StaticAnswer<AgentInspectMessageRouteArg, AgentInspectMessageTextResponse>;\n drive?: (arg: AgentInspectDriveArg) => AgentInspectDriveResponse;\n truncate?: (arg: AgentInspectTruncateArg) => AgentInspectTruncateResponse;\n runSettings?: (arg: AgentInspectRunSettingsArg) => AgentInspectRunSettingsResponse;\n replayToolCall?: (arg: AgentInspectMessageRouteArg) => AgentInspectToolCallReplayResponse;\n cancelRun?: (arg: AgentInspectConversationArg) => AgentInspectRunControlResponse;\n stopRun?: (arg: AgentInspectConversationArg) => AgentInspectRunControlResponse;\n}\n\n/** An `AgentInspectApi` answering fixed payloads, without a store or a request (previews, tests, reviews). */\nexport const createStaticAgentInspectApi = (data: StaticAgentInspectData): AgentInspectApi => ({\n useConversationsQuery: staticQueryHook((arg) => data.conversations?.(arg ?? {})),\n useMetricsQuery: staticQueryHook((arg) => data.metrics?.(arg ?? {})),\n useConversationQuery: staticQueryHook((arg) => data.conversation?.(arg)),\n useTraceQuery: staticQueryHook((arg) => data.trace?.(arg)),\n useDelegationsQuery: staticQueryHook((arg) => data.delegations?.(arg)),\n useFileChangesQuery: staticQueryHook((arg) => data.fileChanges?.(arg)),\n useFileChangeDiffQuery: staticQueryHook((arg) => data.fileChangeDiff?.(arg)),\n useSandboxQuery: staticQueryHook((arg) => data.sandbox?.(arg)),\n useCompactionNodesQuery: staticQueryHook((arg) => data.compactionNodes?.(arg)),\n useToolCallResultQuery: staticQueryHook((arg) => data.toolCallResult?.(arg)),\n useMessageTextQuery: staticQueryHook((arg) => data.messageText?.(arg)),\n useDriveMutation: staticMutationHook((arg) => data.drive?.(arg) ?? {}),\n useTruncateMutation: staticMutationHook((arg) => data.truncate?.(arg) ?? {}),\n useRunSettingsMutation: staticMutationHook((arg) => data.runSettings?.(arg) ?? {}),\n useReplayToolCallMutation: staticMutationHook((arg) => data.replayToolCall?.(arg) ?? {}),\n useCancelRunMutation: staticMutationHook((arg) => data.cancelRun?.(arg) ?? {}),\n useStopRunMutation: staticMutationHook((arg) => data.stopRun?.(arg) ?? {}),\n context: createStaticAgentInspectContextApi(data),\n});\n","import { mapWireTraceFileChange, mapWireTraceMessage, mapWireTraceStep, mapWireTurnTrace } from \"../../client/http/agents-http-trace-mappers\";\nimport type { WireTraceFileChange, WireTraceMessage, WireTraceStep, WireTurnTrace } from \"../../client/http/agents-http-trace-wire\";\nimport type { ConversationTraceLevel, ConversationTraceSubAgent, ConversationTraceWindowMode } from \"../../contract/conversation-trace\";\nimport type {\n AgentInspectCompactionNode,\n AgentInspectDelegationsResponse,\n AgentInspectDelegationTree,\n AgentInspectFileChange,\n AgentInspectFileChangesResponse,\n AgentInspectMessage,\n AgentInspectMessageTextResponse,\n AgentInspectSandboxChronicle,\n AgentInspectSandboxEntry,\n AgentInspectSandboxResponse,\n AgentInspectStep,\n AgentInspectSubAgent,\n AgentInspectTouchedFile,\n AgentInspectTouchedMount,\n AgentInspectTrace,\n AgentInspectTraceResponse,\n AgentInspectTurn,\n} from \"./agent-inspect-types\";\n\n// The mappers of the inspection reads. Tolerant like the client's trace mappers they stand on: a field the server\n// does not send reads as null, false or an empty list, and a list arrives as an array or as a set (`{ elements }`).\n\ntype WireObject = Record<string, unknown>;\n\nconst isWireObject = (value: unknown): value is WireObject => typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst numberOrNull = (value: unknown): number | null => (typeof value === \"number\" && Number.isFinite(value) ? value : null);\n\nconst stringOrNull = (value: unknown): string | null => (typeof value === \"string\" ? value : null);\n\n/** The elements of a list that arrives as an array or as a set. */\nexport const readInspectList = (value: unknown): unknown[] => {\n if (Array.isArray(value)) return value;\n if (isWireObject(value) && Array.isArray(value.elements)) return value.elements;\n return [];\n};\n\nconst objectsOf = (value: unknown): WireObject[] => readInspectList(value).filter(isWireObject);\n\n/** An `AgentTraceFileChange` with the facts the files table reads. */\nexport const mapAgentInspectFileChange = (wireFileChange: unknown): AgentInspectFileChange | null => {\n if (!isWireObject(wireFileChange)) return null;\n return {\n ...mapWireTraceFileChange(wireFileChange as WireTraceFileChange),\n conversationId: numberOrNull(wireFileChange.aiConversationId),\n messageId: numberOrNull(wireFileChange.aiConversationMessageId),\n toolName: stringOrNull(wireFileChange.toolName),\n changedAt: stringOrNull(wireFileChange.changedAt),\n hasStoredDiff: wireFileChange.hasStoredDiff === true,\n };\n};\n\nconst fileChangesOf = (value: unknown): AgentInspectFileChange[] =>\n readInspectList(value)\n .map(mapAgentInspectFileChange)\n .filter((fileChange): fileChange is AgentInspectFileChange => fileChange !== null);\n\n/** `GET /{id}/fileChanges`: the file changes, oldest first. */\nexport const mapAgentInspectFileChanges = (response: AgentInspectFileChangesResponse | null | undefined): AgentInspectFileChange[] =>\n fileChangesOf(response?.fileChanges);\n\nconst mapSubAgent = (wireSubAgent: unknown, mapped: ConversationTraceSubAgent | null): AgentInspectSubAgent | null => {\n if (!isWireObject(wireSubAgent) || mapped === null) return null;\n const queuedAtByRunNumber: Record<number, string> = {};\n for (const wireRun of objectsOf(wireSubAgent.runs)) {\n const runNumber = numberOrNull(wireRun.runNumber);\n const queuedAt = stringOrNull(wireRun.queuedAt);\n if (runNumber !== null && queuedAt !== null) queuedAtByRunNumber[runNumber] = queuedAt;\n }\n return {\n ...mapped,\n delegateCallMessageId: numberOrNull(wireSubAgent.delegateCallMessageId),\n requestedByToolName: stringOrNull(wireSubAgent.requestedByToolName),\n notifiesParentWithoutResuming: wireSubAgent.notifiesParentWithoutResuming === true,\n childRunState: stringOrNull(wireSubAgent.childRunState),\n tokensAreChildConversationTotal: wireSubAgent.tokensAreChildConversationTotal === true,\n queuedAtByRunNumber,\n };\n};\n\n/** An `AgentTraceSubAgent` outside a step (the delegation tree). */\nexport const mapAgentInspectSubAgent = (wireSubAgent: unknown): AgentInspectSubAgent | null => {\n if (!isWireObject(wireSubAgent)) return null;\n const step = mapWireTraceStep({ kind: \"SUB_AGENT\", subAgent: wireSubAgent } as WireTraceStep, 0);\n return mapSubAgent(wireSubAgent, step?.subAgent ?? null);\n};\n\n/** A compaction node as sent; null for anything else. */\nexport const mapAgentInspectCompactionNode = (wireNode: unknown): AgentInspectCompactionNode | null =>\n isWireObject(wireNode) ? (wireNode as AgentInspectCompactionNode) : null;\n\n/** An `AgentTraceStep`: the contract's step and the admin facts; null for a step of an unknown kind. */\nexport const mapAgentInspectStep = (wireStep: unknown, position: number, turnNumber: number | null = null): AgentInspectStep | null => {\n if (!isWireObject(wireStep)) return null;\n const step = mapWireTraceStep(wireStep as WireTraceStep, position);\n if (step === null) return null;\n const wireModelCall = isWireObject(wireStep.modelCall) ? wireStep.modelCall : null;\n return {\n ...step,\n stepId: step.stepId ?? (turnNumber === null ? step.key : `t${turnNumber}.${step.key}`),\n contextMessageId: step.modelCall?.contextMessageId ?? (step.kind === \"MODEL_CALL\" ? step.messageId : null),\n messageIndex: numberOrNull(wireStep.messageIndex),\n detailKind: stringOrNull(wireStep.detailKind),\n isSilent: wireStep.isSilent === true,\n isTruncated: wireStep.isTruncated === true,\n isCallToolWithoutToolName: wireStep.isCallToolWithoutToolName === true,\n wasRefusedByGate: wireStep.wasRefusedByGate === true,\n wasRefusedAsDuplicate: wireStep.wasRefusedAsDuplicate === true,\n wasRefusedAsFinal: wireStep.wasRefusedAsFinal === true,\n wasRemovedForSecurity: wireStep.wasRemovedForSecurity === true,\n errorCode: stringOrNull(wireStep.errorCode),\n executionCostInUsd: numberOrNull(wireStep.executionCostInUSD ?? wireStep.executionCostInUsd),\n modelCallFacts: wireModelCall\n ? {\n wireApi: stringOrNull(wireModelCall.wireApi),\n cacheWriteTokens: numberOrNull(wireModelCall.cacheWriteTokens),\n forceToolChoice: stringOrNull(wireModelCall.forceToolChoice),\n providerCallMs: numberOrNull(wireModelCall.providerCallMs),\n loopOverheadMs: numberOrNull(wireModelCall.loopOverheadMs),\n hasStoredPayload: wireModelCall.hasStoredPayload === true,\n }\n : null,\n loadedSkillsSameAsPreviousModelCall: wireStep.loadedSkillsSameAsPreviousModelCall === true,\n compactionNode: mapAgentInspectCompactionNode(wireStep.compaction),\n signalSource: stringOrNull(wireStep.signalSource),\n signalText: stringOrNull(wireStep.signalText),\n eventKind: stringOrNull(wireStep.eventKind),\n eventSite: stringOrNull(wireStep.eventSite),\n eventSubject: stringOrNull(wireStep.eventSubject),\n eventPayloadExcerpt: stringOrNull(wireStep.eventPayloadExcerpt),\n subAgent: mapSubAgent(wireStep.subAgent, step.subAgent),\n fileChanges: fileChangesOf(wireStep.fileChanges),\n };\n};\n\n/** An `AgentTurnTrace`. */\nexport const mapAgentInspectTurn = (wireTurn: unknown): AgentInspectTurn | null => {\n if (!isWireObject(wireTurn)) return null;\n const turn = mapWireTurnTrace(wireTurn as WireTurnTrace);\n const steps = readInspectList(wireTurn.steps)\n .map((wireStep, position) => mapAgentInspectStep(wireStep, position, turn.turnNumber))\n .filter((step): step is AgentInspectStep => step !== null);\n return {\n ...turn,\n steps,\n initiatorMessageIndex: numberOrNull(wireTurn.initiatorMessageIndex),\n initiatorTextExcerpt: stringOrNull(wireTurn.initiatorTextExcerpt),\n initiatorAuthor: stringOrNull(wireTurn.initiatorAuthor),\n initiatorSignalSource: stringOrNull(wireTurn.initiatorSignalSource),\n endedAt: stringOrNull(wireTurn.endedAt),\n isTruncated: wireTurn.isTruncated === true,\n modelCallCount: numberOrNull(wireTurn.modelCallCount) ?? 0,\n toolCallCount: numberOrNull(wireTurn.toolCallCount) ?? 0,\n subAgentCount: numberOrNull(wireTurn.subAgentCount) ?? 0,\n answerMessageIds: readInspectList(wireTurn.answerMessageIds).filter((id): id is number => typeof id === \"number\"),\n };\n};\n\nconst TRACE_LEVELS: readonly ConversationTraceLevel[] = [\"STEPS\", \"DEBUG\"];\nconst TRACE_WINDOW_MODES: readonly ConversationTraceWindowMode[] = [\"NEWEST\", \"FROM_TURN\", \"FOLLOW_UP\"];\n\n/** `GET /{id}/messages/{messageId}/text`: the message with its whole text; null for an answer without one. */\nexport const mapAgentInspectMessageText = (response: AgentInspectMessageTextResponse | null | undefined): AgentInspectMessage | null =>\n mapWireTraceMessage(isWireObject(response?.message) ? (response.message as WireTraceMessage) : null);\n\n/** `GET /{id}/trace`; an answer without turns reads as an empty trace. */\nexport const mapAgentInspectTrace = (response: AgentInspectTraceResponse | null | undefined): AgentInspectTrace => {\n const wireTrace: WireObject = isWireObject(response?.trace)\n ? response.trace\n : isWireObject(response) && (\"elements\" in response || \"turns\" in response || \"totalTurnCount\" in response)\n ? (response as WireObject)\n : {};\n const level = TRACE_LEVELS.find((candidate) => candidate === wireTrace.detailLevel) ?? \"STEPS\";\n // `AgentTurnTraces` is an object set: its turns are its elements (`turns` is the form of an older server)\n const turns = readInspectList(Array.isArray(wireTrace.elements) ? wireTrace.elements : wireTrace.turns)\n .map(mapAgentInspectTurn)\n .filter((turn): turn is AgentInspectTurn => turn !== null);\n return {\n conversationId: numberOrNull(wireTrace.aiConversationId),\n level,\n turns,\n windowMode: TRACE_WINDOW_MODES.find((candidate) => candidate === wireTrace.windowMode) ?? null,\n totalTurnCount: numberOrNull(wireTrace.totalTurnCount) ?? turns.length,\n firstTurnNumber: numberOrNull(wireTrace.firstTurnNumber) ?? turns[0]?.turnNumber ?? null,\n lastTurnNumber: numberOrNull(wireTrace.lastTurnNumber) ?? turns[turns.length - 1]?.turnNumber ?? null,\n hasOlderTurns: wireTrace.hasOlderTurns === true,\n hasNewerTurns: wireTrace.hasNewerTurns === true,\n newestMessageIndex: numberOrNull(wireTrace.newestMessageIndex),\n isRunLive: wireTrace.isRunLive === true,\n runState: stringOrNull(wireTrace.runState),\n };\n};\n\n/** `GET /{id}/delegations`. */\nexport const mapAgentInspectDelegationTree = (response: AgentInspectDelegationsResponse | null | undefined): AgentInspectDelegationTree => {\n const wireTree = response?.delegationTree ?? null;\n return {\n conversationId: numberOrNull(wireTree?.aiConversationId),\n runState: stringOrNull(wireTree?.runState),\n subAgents: readInspectList(wireTree?.subAgents)\n .map(mapAgentInspectSubAgent)\n .filter((subAgent): subAgent is AgentInspectSubAgent => subAgent !== null),\n batches: objectsOf(wireTree?.batches),\n waitingWindows: objectsOf(wireTree?.waitingWindows),\n waitingWindowSource: stringOrNull(wireTree?.waitingWindowSource),\n };\n};\n\nconst mapTouchedFile = (wireFile: WireObject): AgentInspectTouchedFile => ({\n path: stringOrNull(wireFile.path) ?? \"\",\n changeCount: numberOrNull(wireFile.changeCount) ?? 0,\n lastChangeType: stringOrNull(wireFile.lastChangeType),\n linesAdded: numberOrNull(wireFile.linesAdded) ?? 0,\n linesRemoved: numberOrNull(wireFile.linesRemoved) ?? 0,\n history: fileChangesOf(wireFile.history),\n});\n\nconst mapTouchedMount = (wireMount: WireObject): AgentInspectTouchedMount => ({\n mountKind: stringOrNull(wireMount.mountKind),\n mountName: stringOrNull(wireMount.mountName),\n driveSpaceId: numberOrNull(wireMount.driveSpaceId),\n files: objectsOf(wireMount.files).map(mapTouchedFile),\n});\n\nconst mapSandboxEntry = (wireEntry: WireObject, position: number): AgentInspectSandboxEntry => {\n const kind = wireEntry.kind === \"FILE_CHANGE\" ? \"FILE_CHANGE\" : \"COMMAND\";\n // The terminal goes through the step mapper, so a command reads here as it does in a turn.\n const terminalStep = isWireObject(wireEntry.terminal) ? mapWireTraceStep({ kind: \"TOOL_CALL\", terminal: wireEntry.terminal } as WireTraceStep, position) : null;\n const messageId = numberOrNull(wireEntry.messageId);\n return {\n key: `${kind}:${messageId ?? \"none\"}:${position}`,\n kind,\n at: stringOrNull(wireEntry.at),\n messageId,\n messageIndex: numberOrNull(wireEntry.messageIndex),\n toolName: stringOrNull(wireEntry.toolName),\n status: stringOrNull(wireEntry.status),\n terminal: terminalStep?.terminal ?? null,\n fileChange: mapAgentInspectFileChange(wireEntry.fileChange),\n };\n};\n\n/** `GET /{id}/sandbox`. */\nexport const mapAgentInspectSandboxChronicle = (response: AgentInspectSandboxResponse | null | undefined): AgentInspectSandboxChronicle => {\n const wireChronicle = response?.sandboxChronicle ?? null;\n const entries = objectsOf(wireChronicle?.entries).map(mapSandboxEntry);\n return {\n conversationId: numberOrNull(wireChronicle?.aiConversationId),\n entries,\n mounts: objectsOf(wireChronicle?.mounts).map(mapTouchedMount),\n commandCount: numberOrNull(wireChronicle?.commandCount) ?? entries.filter((entry) => entry.kind === \"COMMAND\").length,\n fileChangeCount: numberOrNull(wireChronicle?.fileChangeCount) ?? entries.filter((entry) => entry.kind === \"FILE_CHANGE\").length,\n linesAdded: numberOrNull(wireChronicle?.linesAdded) ?? 0,\n linesRemoved: numberOrNull(wireChronicle?.linesRemoved) ?? 0,\n };\n};\n","import type {\n ConversationFileChange,\n ConversationTraceDecision,\n ConversationTraceLevel,\n ConversationTraceMessage,\n ConversationTraceStep,\n ConversationTraceSubAgent,\n ConversationTraceWindowMode,\n ConversationTurnTrace,\n} from \"../../contract/conversation-trace\";\nimport type { WireTraceTaskPlanItem } from \"../../client/http/agents-http-trace-wire\";\nimport type { WireSet } from \"../../client/http/agents-http-wire\";\nimport type { AdminWireSet } from \"../wire/admin-wire\";\n\n/**\n * The shapes of the conversation inspection routes (`AdminAgentConversationsInspectTrait`,\n * `AdminAgentConversationsDriveTrait`). The answers of the list, the metrics, the header and the delegation and sandbox\n * reads keep the server's field names, every field optional; the trace is mapped onto the conversation contract's\n * trace with the admin facts beside it (`mapAgentInspectTrace`).\n */\n\n// ── Vocabulary ───────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** The segments of the list (`AgentInspectFilters::SEGMENT_*`). */\nexport const AGENT_INSPECT_SEGMENTS = [\"ALL\", \"RUNNING\", \"AWAITING_OWNER\", \"WITH_PROBLEMS\", \"SCHEDULED\", \"SUB_AGENTS\"] as const;\nexport type AgentInspectSegment = (typeof AGENT_INSPECT_SEGMENTS)[number];\n\n/** The orders of the list (`AgentInspectFilters::SORT_*`); `LAST_ACTIVITY` is the server's default. */\nexport const AGENT_INSPECT_SORT_ORDERS = [\"LAST_ACTIVITY\", \"CREATED\", \"COST\"] as const;\nexport type AgentInspectSortOrder = (typeof AGENT_INSPECT_SORT_ORDERS)[number];\n\n/** The run states a conversation is listed by. */\nexport const AGENT_INSPECT_RUN_STATES = [\"IDLE\", \"QUEUED\", \"RUNNING\", \"AWAITING_DELEGATES\", \"COMPLETED\", \"FAILED\", \"CANCELLED\"] as const;\nexport type AgentInspectRunState = (typeof AGENT_INSPECT_RUN_STATES)[number];\n\n/** The origins the package itself knows; an application adds its own initiator types. */\nexport const AGENT_INSPECT_ORIGINS = [\"OWNER\", \"DELEGATION\", \"SCHEDULE\", \"ADMIN_TASK\", \"PHONE_CALL\", \"EXTERNAL_AGENT\"] as const;\n\n// ── List and metrics ─────────────────────────────────────────────────────────────────────────────────────────────\n\n/** `AgentInspectLabel`: the application's label of an account or an agent space. */\nexport interface AgentInspectLabel {\n id?: number | null;\n label?: string | null;\n /** A second line (the kind of the space, the role of the account). */\n description?: string | null;\n}\n\n/** `AgentInspectedConversation`: one row of the list; cost and tokens are those of the conversation's tree. */\nexport interface AgentInspectedConversation {\n aiConversationId?: number | null;\n rootConversationId?: number | null;\n accountId?: number | null;\n agentSpaceId?: number | null;\n title?: string | null;\n purposeName?: string | null;\n /** The start of the first message of the owner, and of the newest answer of the assistant. */\n firstOwnerTextExcerpt?: string | null;\n lastAnswerTextExcerpt?: string | null;\n runState?: string | null;\n initiatorType?: string | null;\n isSubAgentConversation?: boolean | null;\n scheduleId?: number | null;\n created?: string | null;\n lastActivityAt?: string | null;\n lastMessageAt?: string | null;\n runHeartbeatAt?: string | null;\n costInUSD?: number | null;\n overheadCostsInUSD?: number | null;\n inputTokens?: number | null;\n outputTokens?: number | null;\n cachedInputTokens?: number | null;\n turnCount?: number | null;\n messageCount?: number | null;\n failedRowCount?: number | null;\n modelNames?: string[] | null;\n /** Those models as the model catalog names them (\"GPT-6 Luna\"), in the order of the names. */\n modelLabels?: string[] | null;\n subAgentCount?: number | null;\n}\n\n/** The filters of `GET /list` and `GET /metrics`, as the request carries them. */\nexport interface AgentInspectListArg {\n /** The first day of the period of last activity (`YYYY-MM-DD`, UTC, inclusive). */\n from?: string;\n /** The last day of the period (`YYYY-MM-DD`, UTC, inclusive). */\n to?: string;\n accountIds?: readonly number[];\n agentSpaceIds?: readonly number[];\n runStates?: readonly string[];\n purposeName?: string;\n origin?: string;\n modelName?: string;\n toolName?: string;\n loadedSkillName?: string;\n minimumCostInUSD?: number;\n search?: string;\n segment?: AgentInspectSegment;\n /** The order of the list; left out = last activity first. The metrics ignore it. */\n sortBy?: AgentInspectSortOrder;\n /** Lists the runs of evaluation suites too (they are left out by default). */\n includeEvalRuns?: boolean;\n limit?: number;\n offset?: number;\n}\n\n/** `GET /list`: the page (`AgentInspectedConversations`, an object set: its conversations under `elements`) and the labels. */\nexport interface AgentInspectConversationsResponse {\n conversations?: AdminWireSet<AgentInspectedConversation> | null;\n hasMore?: boolean | null;\n limit?: number | null;\n offset?: number | null;\n accountLabels?: AdminWireSet<AgentInspectLabel> | null;\n agentSpaceLabels?: AdminWireSet<AgentInspectLabel> | null;\n}\n\n/** `AgentInspectMetric`: a figure of the period and of the period of equal length before. */\nexport interface AgentInspectMetric {\n value?: number | null;\n previousValue?: number | null;\n}\n\n/** `AgentInspectMetrics`. */\nexport interface AgentInspectMetrics {\n activeFrom?: string | null;\n activeUntil?: string | null;\n previousActiveFrom?: string | null;\n previousActiveUntil?: string | null;\n conversationCount?: AgentInspectMetric | null;\n costInUSD?: AgentInspectMetric | null;\n /** `USAGE_LOG` / `MESSAGE_ROWS` (the period cost, same figure as the control-panel statistics) or `CONVERSATION_TREES` (a narrowed list). */\n costSource?: string | null;\n /** First day the cost source holds data for (`Y-m-d`); null when unknown. */\n costDataAvailableFrom?: string | null;\n averageCostInUSD?: AgentInspectMetric | null;\n conversationWithErrorsCount?: AgentInspectMetric | null;\n cacheHitPercent?: AgentInspectMetric | null;\n medianAnswerSeconds?: AgentInspectMetric | null;\n}\n\n/** `AgentInspectSegmentCount`: the conversations one segment lists under the list's other filters. */\nexport interface AgentInspectSegmentCount {\n segment?: string | null;\n conversationCount?: number | null;\n}\n\n/** `GET /metrics`. */\nexport interface AgentInspectMetricsResponse {\n metrics?: AgentInspectMetrics | null;\n /** Per segment, under the list's filters (its period as the list reads it); a server before the counts sends none. */\n segmentCounts?: AdminWireSet<AgentInspectSegmentCount> | null;\n}\n\n// ── One conversation ─────────────────────────────────────────────────────────────────────────────────────────────\n\n/** `AgentInspectConversationHeader`. */\nexport interface AgentInspectConversationHeader {\n aiConversationId?: number | null;\n rootConversationId?: number | null;\n delegatedFromMessageId?: number | null;\n accountId?: number | null;\n agentSpaceId?: number | null;\n title?: string | null;\n purposeName?: string | null;\n initiatorType?: string | null;\n scheduleId?: number | null;\n created?: string | null;\n lastInboundMessageAt?: string | null;\n modelName?: string | null;\n /** The configured model (`modelName`) as the model catalog names it (\"GPT-6 Luna\"). */\n modelLabel?: string | null;\n modelNameOverride?: string | null;\n reasoningEffort?: string | null;\n runSettingsOverrideCount?: number | null;\n budgetBypass?: boolean | null;\n storesFullRequestSnapshots?: boolean | null;\n /** The sum of the four parts below. */\n treeCostInUSD?: number | null;\n /** What the model calls of the conversation itself cost. */\n modelCallsCostInUSD?: number | null;\n /** What the tool executions of the conversation itself booked. */\n toolExecutionCostInUSD?: number | null;\n /** The overhead booked on the conversation itself (overhead exists per conversation, never per step). */\n overheadCostInUSD?: number | null;\n /** What the other conversations of the tree cost (sub-agents, supervisor), their overhead included; 0 on a sub-agent's header. */\n subAgentsCostInUSD?: number | null;\n treeOverheadCostsInUSD?: number | null;\n treeInputTokens?: number | null;\n treeOutputTokens?: number | null;\n treeCachedInputTokens?: number | null;\n treeConversationCount?: number | null;\n turnCount?: number | null;\n modelCallCount?: number | null;\n toolCallCount?: number | null;\n failedRowCount?: number | null;\n messageCount?: number | null;\n runState?: string | null;\n isRunLive?: boolean | null;\n runHeartbeatAt?: string | null;\n resumeAttempts?: number | null;\n taskPlanTitle?: string | null;\n taskPlanItemCount?: number | null;\n taskPlanOpenItemCount?: number | null;\n taskPlanDoneItemCount?: number | null;\n taskPlanBlockedItemCount?: number | null;\n /** The plan's items with their state: the open plan, or the newest snapshot once the plan is closed (a set on the wire). */\n taskPlanItems?: WireSet<WireTraceTaskPlanItem> | null;\n /** True when the plan figures come from the newest snapshot of a closed plan. */\n isTaskPlanClosed?: boolean | null;\n contextTokens?: number | null;\n contextThresholdTokens?: number | null;\n contextFillPercent?: number | null;\n compactionNodeCount?: number | null;\n loadedSkillCount?: number | null;\n loadedToolCount?: number | null;\n}\n\n/** `GET /{id}`. */\nexport interface AgentInspectConversationResponse {\n header?: AgentInspectConversationHeader | null;\n accountLabel?: AgentInspectLabel | null;\n agentSpaceLabel?: AgentInspectLabel | null;\n}\n\nexport interface AgentInspectConversationArg {\n conversationId: number | string;\n}\n\n/** Which turns `GET /{id}/trace` returns. */\nexport interface AgentInspectTraceArg extends AgentInspectConversationArg {\n detailLevel?: ConversationTraceLevel;\n fromTurnNumber?: number;\n limit?: number;\n afterMessageIndex?: number;\n includeTruncated?: boolean;\n}\n\n/** `GET /{id}/trace` as sent: `AgentTurnTraces` under `trace`. */\nexport interface AgentInspectTraceResponse {\n trace?: unknown;\n}\n\n// ── The trace as the admin reads it ──────────────────────────────────────────────────────────────────────────────\n\n/** `AgentTraceCompaction`: one compaction node. */\nexport interface AgentInspectCompactionNode {\n compactionNodeId?: number | null;\n /** 0 = over stored rows, higher = over nodes. */\n level?: number | null;\n coveredFromMessageIndex?: number | null;\n coveredToMessageIndex?: number | null;\n coveredMessageCount?: number | null;\n coveredTokens?: number | null;\n summaryTokens?: number | null;\n modelName?: string | null;\n fromRawMessages?: boolean | null;\n createdAt?: string | null;\n /** Debug level: the summary. */\n summaryText?: string | null;\n isSummaryCut?: boolean | null;\n}\n\n/** The facts of a model call the conversation contract leaves out. */\nexport interface AgentInspectModelCallFacts {\n wireApi: string | null;\n cacheWriteTokens: number | null;\n /** The forced tool choice of the call (`none` = a step without tools). */\n forceToolChoice: string | null;\n providerCallMs: number | null;\n loopOverheadMs: number | null;\n hasStoredPayload: boolean;\n}\n\n/** A side decision of a turn, as the conversation contract carries it. */\nexport type AgentInspectDecision = ConversationTraceDecision;\n\n/** A sub-agent with the facts of its delegation. */\nexport interface AgentInspectSubAgent extends ConversationTraceSubAgent {\n delegateCallMessageId: number | null;\n requestedByToolName: string | null;\n notifiesParentWithoutResuming: boolean;\n /** The run state of the sub-agent's conversation. */\n childRunState: string | null;\n /** The tokens are the total of the sub-agent's conversation, because its runs carry no stamp of their own. */\n tokensAreChildConversationTotal: boolean;\n /** When each run was queued, by run number (the swimlanes start a queued run there). */\n queuedAtByRunNumber: Record<number, string>;\n}\n\n/** A file change with what the files table reads beside the contract's fields. */\nexport interface AgentInspectFileChange extends ConversationFileChange {\n conversationId: number | null;\n messageId: number | null;\n toolName: string | null;\n changedAt: string | null;\n hasStoredDiff: boolean;\n}\n\n/** One step of a turn: the contract's step and the admin facts of its row. */\nexport interface AgentInspectStep extends ConversationTraceStep {\n /** The id a link names the step by (`?step=`): the server's, else the step's key in its turn. */\n stepId: string;\n /** The message whose context composition is this model call's (the call's own message unless the server names another). */\n contextMessageId: number | null;\n /** The position of the step's message (`indexInConversation`): where a truncation starts. */\n messageIndex: number | null;\n detailKind: string | null;\n isSilent: boolean;\n /** The row belongs to a branch an admin truncated. */\n isTruncated: boolean;\n isCallToolWithoutToolName: boolean;\n wasRefusedByGate: boolean;\n wasRefusedAsDuplicate: boolean;\n wasRefusedAsFinal: boolean;\n wasRemovedForSecurity: boolean;\n errorCode: string | null;\n executionCostInUsd: number | null;\n modelCallFacts: AgentInspectModelCallFacts | null;\n /** The loaded skills are those of the model call before (the server sends them only when they changed). */\n loadedSkillsSameAsPreviousModelCall: boolean;\n /** The compaction node a `COMPACTION` step wrote, with the messages it covers. */\n compactionNode: AgentInspectCompactionNode | null;\n signalSource: string | null;\n signalText: string | null;\n eventKind: string | null;\n eventSite: string | null;\n eventSubject: string | null;\n eventPayloadExcerpt: string | null;\n subAgent: AgentInspectSubAgent | null;\n fileChanges: AgentInspectFileChange[];\n}\n\n/** One turn: the contract's turn and what the admin reads of its start and its end. */\nexport interface AgentInspectTurn extends ConversationTurnTrace {\n /** The position of the message that started the turn (`indexInConversation`). */\n initiatorMessageIndex: number | null;\n /** The start of the initiator's text (the trace carries no more). */\n initiatorTextExcerpt: string | null;\n /** `OWNER`, `SIGNAL`, `ORCHESTRATOR` or `PLATFORM`. */\n initiatorAuthor: string | null;\n initiatorSignalSource: string | null;\n endedAt: string | null;\n isTruncated: boolean;\n modelCallCount: number;\n toolCallCount: number;\n subAgentCount: number;\n /** The assistant's text messages of the turn, in order. */\n answerMessageIds: number[];\n steps: AgentInspectStep[];\n}\n\n/** `AgentTurnTraces` as the admin reads it. */\nexport interface AgentInspectTrace {\n conversationId: number | null;\n level: ConversationTraceLevel;\n /** Oldest first. */\n turns: AgentInspectTurn[];\n /** How the window was asked for; null when the server does not say. */\n windowMode: ConversationTraceWindowMode | null;\n totalTurnCount: number;\n /** The numbers of the first and the last turn of `turns`; null without turns. */\n firstTurnNumber: number | null;\n lastTurnNumber: number | null;\n /** Facts of a page read (`NEWEST`, `FROM_TURN`); both false on a follow-up read. */\n hasOlderTurns: boolean;\n hasNewerTurns: boolean;\n newestMessageIndex: number | null;\n isRunLive: boolean;\n runState: string | null;\n}\n\n// ── Delegation, sandbox, files ───────────────────────────────────────────────────────────────────────────────────\n\n/** `AgentInspectDelegationBatch`. */\nexport interface AgentInspectDelegationBatch {\n delegationBatchId?: number | null;\n spawnedByMessageId?: number | null;\n expectedDelegationCount?: number | null;\n /** When the parent resumes (`ALL`, `ANY`, `QUORUM`, `BACKGROUND`, …). */\n delegateWakeCondition?: string | null;\n quorumSuccessThreshold?: number | null;\n timeoutSeconds?: number | null;\n createdAt?: string | null;\n deadlineAt?: string | null;\n settledAt?: string | null;\n foldedAt?: string | null;\n}\n\n/** `AgentInspectWaitingWindow`: a window in which the conversation waited for sub-agents. */\nexport interface AgentInspectWaitingWindow {\n startedAt?: string | null;\n /** Null while the waiting lasts. */\n endedAt?: string | null;\n delegationBatchIds?: number[] | null;\n /** The `delegate` call messages whose runs without a batch row lie in the window. */\n delegateCallMessageIds?: number[] | null;\n /** What the window was derived from: `DELEGATION_BATCHES`, `SUB_AGENT_RUNS` (the times of runs without a batch row) or `BOTH`. */\n source?: string | null;\n}\n\n/** `GET /{id}/delegations` as sent (`AgentInspectDelegationTree` under `delegationTree`). */\nexport interface AgentInspectDelegationsResponse {\n delegationTree?: {\n aiConversationId?: number | null;\n runState?: string | null;\n subAgents?: unknown;\n batches?: AgentInspectDelegationBatch[] | null;\n waitingWindows?: AgentInspectWaitingWindow[] | null;\n waitingWindowSource?: string | null;\n } | null;\n}\n\n/** The delegation tree with its sub-agents mapped. */\nexport interface AgentInspectDelegationTree {\n conversationId: number | null;\n runState: string | null;\n subAgents: AgentInspectSubAgent[];\n batches: AgentInspectDelegationBatch[];\n waitingWindows: AgentInspectWaitingWindow[];\n /** What the waiting windows were derived from (`DELEGATION_BATCHES`, `SUB_AGENT_RUNS`, `BOTH`); null without windows. */\n waitingWindowSource: string | null;\n}\n\n/** `GET /{id}/fileChanges` as sent. */\nexport interface AgentInspectFileChangesResponse {\n fileChanges?: unknown;\n}\n\nexport interface AgentInspectFileChangeArg extends AgentInspectConversationArg {\n fileChangeId: number | string;\n}\n\n/** `GET /{id}/fileChanges/{fileChangeId}/diff`. */\nexport interface AgentInspectFileChangeDiffResponse {\n fileChange?: unknown;\n /** The whole diff; null for a change without one. */\n diff?: string | null;\n}\n\n/** `GET /{id}/sandbox` as sent (`AgentInspectSandboxChronicle` under `sandboxChronicle`). */\nexport interface AgentInspectSandboxResponse {\n sandboxChronicle?: {\n aiConversationId?: number | null;\n entries?: unknown;\n mounts?: unknown;\n commandCount?: number | null;\n fileChangeCount?: number | null;\n linesAdded?: number | null;\n linesRemoved?: number | null;\n } | null;\n}\n\n/** One entry of the sandbox chronicle: a shell command or a file change. */\nexport interface AgentInspectSandboxEntry {\n key: string;\n kind: \"COMMAND\" | \"FILE_CHANGE\";\n at: string | null;\n messageId: number | null;\n messageIndex: number | null;\n toolName: string | null;\n status: string | null;\n terminal: ConversationTraceStep[\"terminal\"];\n fileChange: AgentInspectFileChange | null;\n}\n\n/** `AgentInspectTouchedFile`. */\nexport interface AgentInspectTouchedFile {\n path: string;\n changeCount: number;\n lastChangeType: string | null;\n linesAdded: number;\n linesRemoved: number;\n /** The changes of the file, oldest first. */\n history: AgentInspectFileChange[];\n}\n\n/** `AgentInspectTouchedMount`. */\nexport interface AgentInspectTouchedMount {\n mountKind: string | null;\n mountName: string | null;\n driveSpaceId: number | null;\n files: AgentInspectTouchedFile[];\n}\n\n/** The sandbox chronicle with its entries and mounts mapped. */\nexport interface AgentInspectSandboxChronicle {\n conversationId: number | null;\n entries: AgentInspectSandboxEntry[];\n mounts: AgentInspectTouchedMount[];\n commandCount: number;\n fileChangeCount: number;\n linesAdded: number;\n linesRemoved: number;\n}\n\n/** `GET /{id}/compactionNodes`. */\nexport interface AgentInspectCompactionNodesResponse {\n compactionNodes?: AdminWireSet<AgentInspectCompactionNode> | null;\n}\n\nexport interface AgentInspectMessageRouteArg extends AgentInspectConversationArg {\n messageId: number | string;\n}\n\n/** `GET /{id}/messages/{messageId}/text` as sent: an `AgentTraceMessage` with the whole text under `message`. */\nexport interface AgentInspectMessageTextResponse {\n message?: unknown;\n}\n\n/** A message of a turn with its text (`AgentTraceMessage`). */\nexport type AgentInspectMessage = ConversationTraceMessage;\n\n/** `GET /{id}/toolCalls/{messageId}/result`. */\nexport interface AgentInspectToolCallResultResponse {\n messageId?: number | null;\n result?: string | null;\n resultChars?: number | null;\n}\n\n// ── Admin actions ────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** `RunSettingsOverride`, the switches the action dialog offers; a field left out stays as it is. */\nexport interface AgentInspectRunSettingsOverride {\n /** The kill switch of every decision site. */\n decisionModelOff?: boolean;\n /** `inherit`, `off`, `low`, `medium`, `high`. */\n decisionModelReasoningEffort?: string;\n /** `inherit`, `chatCompletions`, `responses`, `messages`. */\n agentWireApi?: string;\n [setting: string]: unknown;\n}\n\n/** `POST /{id}/drive`. */\nexport interface AgentInspectDriveArg extends AgentInspectConversationArg {\n message: string;\n aiModelName?: string;\n budgetBypass?: boolean;\n /** Truncates from this position (`indexInConversation`) before the message is written. */\n truncateFromIndex?: number;\n runSettingsOverride?: AgentInspectRunSettingsOverride;\n /** The turn runs on a worker (default) or inside the request. */\n async?: boolean;\n}\n\nexport interface AgentInspectDriveResponse {\n aiConversationId?: number | null;\n runState?: string | null;\n isAsync?: boolean | null;\n}\n\n/** `POST /{id}/truncate`. */\nexport interface AgentInspectTruncateArg extends AgentInspectConversationArg {\n fromIndex: number;\n}\n\nexport interface AgentInspectTruncateResponse {\n truncatedMessageCount?: number | null;\n}\n\n/** `POST /{id}/runSettings`. */\nexport interface AgentInspectRunSettingsArg extends AgentInspectConversationArg {\n runSettingsOverride: AgentInspectRunSettingsOverride;\n}\n\nexport interface AgentInspectRunSettingsResponse {\n runSettings?: Record<string, unknown> | null;\n}\n\n/** `AgentToolCallReplay`: the answer of a tool run again with the stored arguments. */\nexport interface AgentInspectToolCallReplay {\n messageId?: number | null;\n toolName?: string | null;\n argumentsJson?: string | null;\n result?: string | null;\n resultChars?: number | null;\n isResultCut?: boolean | null;\n isError?: boolean | null;\n durationMs?: number | null;\n isSameAsStoredResult?: boolean | null;\n}\n\n/** `POST /{id}/toolCalls/{messageId}/replay`. */\nexport interface AgentInspectToolCallReplayResponse {\n replay?: AgentInspectToolCallReplay | null;\n}\n\n/** `POST /{id}/cancel` and `POST /{id}/stop`. */\nexport interface AgentInspectRunControlResponse {\n runState?: string | null;\n [field: string]: unknown;\n}\n","import { m } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport type { TraceTurnTotals } from \"../../chat/trace/trace-types\";\nimport type { AgentInspectStep } from \"./agent-inspect-types\";\n\n// The switches of the debug bar of a conversation: what the debug view shows of every turn. Pure (no React), so what a\n// switch leaves out is covered by tests. The view filters and strips the steps before it hands them to the chat's\n// step blocks; nothing is read again from the server.\n\n/** The switches, in the order of the bar. */\nexport const AGENT_INSPECT_DEBUG_SWITCH_NAMES = [\n \"skills\",\n \"toolCalls\",\n \"argumentsAndResults\",\n \"modelAndEffort\",\n \"tokensAndCosts\",\n \"times\",\n \"compaction\",\n \"subAgents\",\n \"widgets\",\n \"signalsAndDecisions\",\n] as const;\n\nexport type AgentInspectDebugSwitchName = (typeof AGENT_INSPECT_DEBUG_SWITCH_NAMES)[number];\n\n/** Which switch is on. */\nexport type AgentInspectDebugSwitches = Readonly<Record<AgentInspectDebugSwitchName, boolean>>;\n\n/** Every switch on except the signals and decisions (they are many and quiet: the reader turns them on when needed). */\nexport const AGENT_INSPECT_DEBUG_SWITCH_DEFAULTS: AgentInspectDebugSwitches = {\n skills: true,\n toolCalls: true,\n argumentsAndResults: true,\n modelAndEffort: true,\n tokensAndCosts: true,\n times: true,\n compaction: true,\n subAgents: true,\n widgets: true,\n signalsAndDecisions: false,\n};\n\nexport const AGENT_INSPECT_DEBUG_SWITCH_CONTEXT = \"agent-debug-switch\";\n\n/** The words of the switches. */\nexport const AGENT_INSPECT_DEBUG_SWITCH_LABELS: Readonly<Record<AgentInspectDebugSwitchName, string>> = {\n skills: m(\"Skills\", { context: \"agent-debug-switch\" }),\n toolCalls: m(\"Tool calls\", { context: \"agent-debug-switch\" }),\n argumentsAndResults: m(\"Arguments + results\", { context: \"agent-debug-switch\" }),\n modelAndEffort: m(\"Model + effort\", { context: \"agent-debug-switch\" }),\n tokensAndCosts: m(\"Tokens + costs\", { context: \"agent-debug-switch\" }),\n times: m(\"Times\", { context: \"agent-debug-switch\" }),\n compaction: m(\"Compaction\", { context: \"agent-debug-switch\" }),\n subAgents: m(\"Sub-agents\", { context: \"agent-debug-switch\" }),\n widgets: m(\"Widgets\", { context: \"agent-debug-switch\" }),\n signalsAndDecisions: m(\"Signals + decisions\", { context: \"agent-debug-switch\" }),\n};\n\n/**\n * The switches as a stored text keeps them: the names of the switches that differ from the defaults, each with `+`\n * (on) or `-` (off), comma-separated (`-times,+signalsAndDecisions`); `\"\"` = the defaults.\n */\nexport const writeAgentInspectDebugSwitches = (switches: AgentInspectDebugSwitches): string =>\n AGENT_INSPECT_DEBUG_SWITCH_NAMES.filter((name) => switches[name] !== AGENT_INSPECT_DEBUG_SWITCH_DEFAULTS[name])\n .map((name) => `${switches[name] ? \"+\" : \"-\"}${name}`)\n .join(\",\");\n\n/** The switches a stored text names (`writeAgentInspectDebugSwitches`); an unknown or broken part is ignored. */\nexport const readAgentInspectDebugSwitches = (text: string | null | undefined): AgentInspectDebugSwitches => {\n const switches: Record<AgentInspectDebugSwitchName, boolean> = { ...AGENT_INSPECT_DEBUG_SWITCH_DEFAULTS };\n for (const part of (text ?? \"\").split(\",\")) {\n const trimmedPart = part.trim();\n const name = trimmedPart.slice(1) as AgentInspectDebugSwitchName;\n if ((trimmedPart.startsWith(\"+\") || trimmedPart.startsWith(\"-\")) && AGENT_INSPECT_DEBUG_SWITCH_NAMES.includes(name)) {\n switches[name] = trimmedPart.startsWith(\"+\");\n }\n }\n return switches;\n};\n\n/** The step kinds each switch leaves out when it is off. */\nconst STEP_KINDS_OF_SWITCH: Readonly<Partial<Record<AgentInspectDebugSwitchName, readonly string[]>>> = {\n skills: [\"SKILL_LOAD\"],\n toolCalls: [\"TOOL_CALL\"],\n modelAndEffort: [\"MODEL_CALL\", \"THINKING\"],\n compaction: [\"COMPACTION\"],\n subAgents: [\"SUB_AGENT\"],\n widgets: [\"WIDGET\"],\n signalsAndDecisions: [\"SIGNAL\", \"DECISION\"],\n};\n\n/**\n * The steps of a turn as the switches show them: the kinds of a switch that is off are left out, and the facts of a\n * switch that is off are taken off the steps that stay (arguments and results, tokens and costs, durations, the\n * loaded skills). A step the reader opened by a link stays, whatever the switches say (`keptStepId`).\n */\nexport const applyAgentInspectDebugSwitches = <TStep extends AgentInspectStep>(\n steps: readonly TStep[],\n switches: AgentInspectDebugSwitches,\n keptStepId: string | null = null,\n): TStep[] => {\n const hiddenKinds = new Set<string>();\n for (const name of AGENT_INSPECT_DEBUG_SWITCH_NAMES) {\n if (!switches[name]) for (const kind of STEP_KINDS_OF_SWITCH[name] ?? []) hiddenKinds.add(kind);\n }\n return steps\n .filter((step) => !hiddenKinds.has(step.kind) || (keptStepId !== null && step.stepId === keptStepId))\n .map((step) => {\n let shownStep: TStep = step;\n if (!switches.argumentsAndResults && (step.argumentsJson !== null || step.result !== null)) {\n shownStep = { ...shownStep, argumentsJson: null, isArgumentsCut: false, result: null, isResultCut: false };\n }\n if (!switches.tokensAndCosts && step.modelCall !== null) {\n shownStep = {\n ...shownStep,\n modelCall: { ...step.modelCall, inputTokens: null, outputTokens: null, cachedInputTokens: null, cachePercent: null, costInUsd: null, reasoningTokens: null },\n executionCostInUsd: null,\n };\n } else if (!switches.tokensAndCosts && step.executionCostInUsd !== null) {\n shownStep = { ...shownStep, executionCostInUsd: null };\n }\n if (!switches.times && step.durationMs !== null) shownStep = { ...shownStep, durationMs: null };\n if (!switches.skills && (step.loadedSkills !== null || step.loadedSkillNames.length > 0)) {\n shownStep = { ...shownStep, loadedSkills: null, loadedSkillNames: [] };\n }\n return shownStep;\n });\n};\n\n/** The totals of a turn as the switches show them: tokens and costs, and the duration, only while their switch is on. */\nexport const applyAgentInspectDebugSwitchesToTotals = <TTotals extends TraceTurnTotals>(totals: TTotals, switches: AgentInspectDebugSwitches): TTotals => {\n let shownTotals: TTotals = totals;\n if (!switches.tokensAndCosts) {\n shownTotals = { ...shownTotals, inputTokens: null, outputTokens: null, cachedInputTokens: null, cachePercent: null, costInUsd: null };\n }\n if (!switches.times) shownTotals = { ...shownTotals, durationMs: null };\n if (!switches.modelAndEffort) shownTotals = { ...shownTotals, modelName: null, effort: null };\n return shownTotals;\n};\n","import { readTaskPlanCounts, readTaskPlanCountsOfStep } from \"../../chat/trace/task-plan-counts\";\nimport { describeTraceModelName } from \"../../chat/trace/trace-format\";\nimport { mapWireTraceTaskPlanItems } from \"../../client/http/agents-http-trace-mappers\";\nimport type { AgentInspectConversationHeader, AgentInspectTurn } from \"./agent-inspect-types\";\n\n/** The task plan of a conversation as the progress card shows it. */\nexport interface AgentInspectPlanProgress {\n title: string | null;\n itemCount: number;\n /** Top-level items done or not applying; a blocked item is never counted done. */\n doneCount: number;\n blockedCount: number;\n /** The first item that is neither done nor blocked, from the newest plan the loaded turns show; null when none is known. */\n nextItemTitle: string | null;\n}\n\n/** The statuses of a plan item that is not worked on next: done, not applying, or blocked. */\nconst NOT_NEXT_ITEM_STATUSES: readonly string[] = [\"done\", \"not_applicable\", \"blocked\", \"completed\", \"skipped\", \"cancelled\"];\n\n/**\n * The progress of the conversation's task plan: the counts of the header (done and blocked apart), the next step from\n * the newest `TASK_PLAN` step of the loaded turns (its first item that is neither done nor blocked). The plan step's own counts stand in when the header\n * names none. Null without a plan.\n */\nexport const readAgentInspectPlanProgress = (header: AgentInspectConversationHeader, turns: readonly AgentInspectTurn[]): AgentInspectPlanProgress | null => {\n let newestPlanStep: AgentInspectTurn[\"steps\"][number] | null = null;\n for (const turn of turns) {\n for (const step of turn.steps) if (step.kind === \"TASK_PLAN\" && (step.taskPlanItems.length > 0 || step.taskPlanItemCount !== null)) newestPlanStep = step;\n }\n const stepCounts = newestPlanStep !== null ? readTaskPlanCountsOfStep(newestPlanStep) : null;\n const itemCount = header.taskPlanItemCount ?? stepCounts?.total ?? 0;\n if (itemCount <= 0) return null;\n // The header's counts are the plan as it stands; a header without its done count (an older server) leaves the\n // counts to the newest plan step, which can tell blocked items apart.\n const counts =\n header.taskPlanDoneItemCount != null || stepCounts === null\n ? readTaskPlanCounts({\n itemCount,\n openItemCount: header.taskPlanOpenItemCount,\n doneItemCount: header.taskPlanDoneItemCount,\n blockedItemCount: header.taskPlanBlockedItemCount,\n })\n : readTaskPlanCounts({ itemCount, doneItemCount: stepCounts.done, blockedItemCount: stepCounts.blocked });\n // the header names the plan's items itself (also of a closed plan); the newest plan step stands in for an older server\n const headerItems = header.taskPlanItems ? mapWireTraceTaskPlanItems(header.taskPlanItems) : [];\n const planItems = headerItems.length > 0 ? headerItems : (newestPlanStep?.taskPlanItems ?? []);\n const nextItem = planItems.find((item) => !NOT_NEXT_ITEM_STATUSES.includes((item.status ?? \"\").toLowerCase())) ?? null;\n return {\n title: header.taskPlanTitle ?? newestPlanStep?.taskPlanTitle ?? null,\n itemCount,\n doneCount: counts.done,\n blockedCount: counts.blocked,\n nextItemTitle: nextItem?.title ?? null,\n };\n};\n\n/** A model name reduced to its letters and digits, lower case: \"OPENAI.GPT6_LUNA\" and \"GPT-6 Luna\" both read \"gpt6luna\". */\nconst modelNameKey = (name: string): string => name.toLowerCase().replace(/[^a-z0-9]/g, \"\");\n\n/**\n * A stored model name as the model catalog names it (\"GPT-6 Luna\"): the label an answer of the loaded turns carries\n * for that model (the server writes the catalog's display name there), else the name in words\n * (`describeTraceModelName`). Null without a name.\n */\nexport const readAgentInspectModelLabel = (modelName: string | null | undefined, turns: readonly AgentInspectTurn[]): string | null => {\n const words = describeTraceModelName(modelName);\n if (!modelName || words === null) return words;\n const wantedKey = modelNameKey(words);\n for (let turnPosition = turns.length - 1; turnPosition >= 0; turnPosition--) {\n for (const message of turns[turnPosition].answerMessages) {\n const label = message.modelLabel;\n if (label && (message.modelName === modelName || modelNameKey(label) === wantedKey)) return label;\n }\n // A running turn has no answer yet: its model calls carry the same catalog name.\n for (const step of turns[turnPosition].steps) {\n const label = step.modelLabel;\n if (label && step.kind === \"MODEL_CALL\" && (step.modelCall?.modelName === modelName || modelNameKey(label) === wantedKey)) return label;\n }\n }\n return words;\n};\n","import { m } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { defineStatusMap } from \"@mgamadeus/ddd-admin-ui/list\";\nimport { readTraceMoment } from \"../../chat/trace/trace-format\";\nimport { type AdminWireSet, wireElementsOf } from \"../wire/admin-wire\";\nimport type { AgentInspectLabel, AgentInspectMetric } from \"./agent-inspect-types\";\n\n/** The translation context of the run states. */\nexport const AGENT_CONVERSATION_RUN_STATE_CONTEXT = \"agent-run-state\";\n\n/** The run states of a conversation as status badges. */\nexport const AGENT_CONVERSATION_RUN_STATE = defineStatusMap(\n {\n IDLE: { label: m(\"Done\", { context: \"agent-run-state\" }), tone: \"neutral\" },\n QUEUED: { label: m(\"Queued\", { context: \"agent-run-state\" }), tone: \"info\" },\n RUNNING: { label: m(\"Running\", { context: \"agent-run-state\" }), tone: \"info\" },\n AWAITING_DELEGATES: { label: m(\"Waits for sub-agents\", { context: \"agent-run-state\" }), tone: \"warning\" },\n COMPLETED: { label: m(\"Completed\", { context: \"agent-run-state\" }), tone: \"success\" },\n FAILED: { label: m(\"Failed\", { context: \"agent-run-state\" }), tone: \"danger\" },\n CANCELLED: { label: m(\"Cancelled\", { context: \"agent-run-state\" }), tone: \"neutral\" },\n },\n { context: AGENT_CONVERSATION_RUN_STATE_CONTEXT },\n);\n\nexport type AgentRunStateValue = keyof typeof AGENT_CONVERSATION_RUN_STATE;\n\n/** The run states in which a turn is live. */\nexport const AGENT_LIVE_RUN_STATES: readonly string[] = [\"QUEUED\", \"RUNNING\", \"AWAITING_DELEGATES\"];\n\n/** Whether a run state is one the badge map knows. */\nexport const isKnownAgentRunState = (runState: string | null | undefined): runState is AgentRunStateValue =>\n typeof runState === \"string\" && Object.hasOwn(AGENT_CONVERSATION_RUN_STATE, runState);\n\n/** A heartbeat older than this is no sign of life (the worker writes one every few seconds while a turn runs). */\nexport const AGENT_RUN_HEARTBEAT_FRESH_MS = 90_000;\n\n/** Whether a conversation shows the live mark: a live run state whose heartbeat is fresh, or no heartbeat to judge by. */\nexport const isAgentRunLive = (runState: string | null | undefined, runHeartbeatAt: string | null | undefined, now: number): boolean => {\n if (!AGENT_LIVE_RUN_STATES.includes(runState ?? \"\")) return false;\n const heartbeatAt = readTraceMoment(runHeartbeatAt);\n return heartbeatAt === null || now - heartbeatAt <= AGENT_RUN_HEARTBEAT_FRESH_MS;\n};\n\n/** The translation context of the origins. */\nexport const AGENT_ORIGIN_CONTEXT = \"agent-conversation-origin\";\n\n/** The origins the package knows, in words; an application's own initiator type is shown as it is stored. */\nexport const AGENT_ORIGIN_LABELS: Readonly<Record<string, string>> = {\n OWNER: m(\"Chat\", { context: \"agent-conversation-origin\" }),\n DELEGATION: m(\"Sub-agent\", { context: \"agent-conversation-origin\" }),\n SCHEDULE: m(\"Schedule\", { context: \"agent-conversation-origin\" }),\n ADMIN_TASK: m(\"Admin task\", { context: \"agent-conversation-origin\" }),\n PHONE_CALL: m(\"Voice\", { context: \"agent-conversation-origin\" }),\n EXTERNAL_AGENT: m(\"External agent\", { context: \"agent-conversation-origin\" }),\n};\n\n/** The origin of a conversation: a sub-agent's, its initiator type, else the owner's chat. */\nexport const agentOriginOf = (conversation: { isSubAgentConversation?: boolean | null; initiatorType?: string | null; delegatedFromMessageId?: number | null }): string => {\n if (conversation.isSubAgentConversation === true || (conversation.delegatedFromMessageId ?? null) !== null) return \"DELEGATION\";\n return conversation.initiatorType ? conversation.initiatorType : \"OWNER\";\n};\n\n/** The labels of a response by id. */\nexport const agentInspectLabelsById = (labels: AdminWireSet<AgentInspectLabel> | null | undefined): Map<number, AgentInspectLabel> => {\n const labelById = new Map<number, AgentInspectLabel>();\n for (const label of wireElementsOf(labels)) {\n if (typeof label.id === \"number\") labelById.set(label.id, label);\n }\n return labelById;\n};\n\n/** The change of a metric against the period before; null when either figure is missing. */\nexport const agentInspectMetricChange = (metric: AgentInspectMetric | null | undefined): number | null => {\n const value = metric?.value ?? null;\n const previousValue = metric?.previousValue ?? null;\n return value === null || previousValue === null ? null : value - previousValue;\n};\n\n/** The change of a metric as a fraction of the figure before (`0.18` = +18 %); null without a figure before or a zero one. */\nexport const agentInspectMetricRelativeChange = (metric: AgentInspectMetric | null | undefined): number | null => {\n const change = agentInspectMetricChange(metric);\n const previousValue = metric?.previousValue ?? null;\n return change === null || previousValue === null || previousValue === 0 ? null : change / previousValue;\n};\n\n/** The default cost format: US dollars with three decimals below one dollar. */\nexport const formatAgentInspectCost = (costInUsd: number, locale?: string): string =>\n new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency: \"USD\",\n minimumFractionDigits: Math.abs(costInUsd) < 1 ? 3 : 2,\n maximumFractionDigits: Math.abs(costInUsd) < 1 ? 3 : 2,\n }).format(costInUsd);\n\n/** A count in short form (`812`, `1.2K`, `2.1M`). */\nexport const formatAgentInspectCount = (value: number, locale?: string): string =>\n Math.abs(value) < 1000\n ? new Intl.NumberFormat(locale, { maximumFractionDigits: 0 }).format(value)\n : new Intl.NumberFormat(locale, { notation: \"compact\", maximumFractionDigits: 1 }).format(value);\n\n/** The local calendar day of a moment as a number that grows by one per day (for \"today\" and \"yesterday\"). */\nconst localDayNumberOf = (moment: number): number => {\n const date = new Date(moment);\n return Math.floor(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) / 86_400_000);\n};\n\n/**\n * A past moment relative to `now`, as a list shows it: `justNow` under a minute, \"4 min. ago\" under an hour, \"1 hr.\n * ago\" up to six hours on the same day, the clock time for an earlier hour of the same day, \"yesterday\", the weekday and\n * the time within a week, else the date (with the year only when it is another year). `justNow` is the caller's\n * translated text; every other word comes from `Intl` in the locale.\n */\nexport const describeAgentInspectMomentRelative = (moment: number, now: number, locale: string | undefined, justNow: string): string => {\n const elapsedMs = Math.max(0, now - moment);\n if (elapsedMs < 60_000) return justNow;\n const relative = new Intl.RelativeTimeFormat(locale, { numeric: \"auto\", style: \"short\" });\n if (elapsedMs < 3_600_000) return relative.format(-Math.floor(elapsedMs / 60_000), \"minute\");\n const dayDistance = localDayNumberOf(now) - localDayNumberOf(moment);\n const clockTime = new Intl.DateTimeFormat(locale, { hour: \"2-digit\", minute: \"2-digit\" }).format(moment);\n if (dayDistance <= 0) return elapsedMs < 6 * 3_600_000 ? relative.format(-Math.floor(elapsedMs / 3_600_000), \"hour\") : clockTime;\n if (dayDistance === 1) return relative.format(-1, \"day\");\n if (dayDistance < 7) return `${new Intl.DateTimeFormat(locale, { weekday: \"short\" }).format(moment)} ${clockTime}`;\n const isSameYear = new Date(moment).getFullYear() === new Date(now).getFullYear();\n return new Intl.DateTimeFormat(locale, isSameYear ? { day: \"2-digit\", month: \"2-digit\" } : { day: \"2-digit\", month: \"2-digit\", year: \"2-digit\" }).format(moment);\n};\n\n/** A duration in seconds in short form (`11 s`, `2:05 min`). */\nexport const formatAgentInspectSeconds = (seconds: number, locale?: string): string => {\n if (seconds < 60) return `${new Intl.NumberFormat(locale, { maximumFractionDigits: seconds < 10 ? 1 : 0 }).format(seconds)} s`;\n const wholeSeconds = Math.round(seconds);\n return `${Math.floor(wholeSeconds / 60)}:${String(wholeSeconds % 60).padStart(2, \"0\")} min`;\n};\n","import { cn } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport type { HTMLAttributes, ReactNode } from \"react\";\n\n/** A small pulsing dot: a turn runs right now. `label` names it for screen readers and on hover. */\nexport const LiveDot = ({ label, className }: { label: string; className?: string }) => (\n <span className={cn(\"relative inline-flex size-2 shrink-0\", className)} role=\"img\" aria-label={label} title={label} data-slot=\"agent-live-dot\">\n <span className=\"absolute inline-flex size-full animate-ping rounded-full bg-info opacity-60 motion-reduce:animate-none\" />\n <span className=\"relative inline-flex size-2 rounded-full bg-info\" />\n </span>\n);\n\n/** The attributes a host puts on the element around the chat's trace blocks (the scope of its theme mapping). */\nexport type AgentTraceFrameAttributes = Readonly<Record<`data-${string}`, string>>;\n\nexport interface AgentTraceFrameProps extends HTMLAttributes<HTMLDivElement> {\n frameAttributes?: AgentTraceFrameAttributes;\n children: ReactNode;\n}\n\n/**\n * The element around trace blocks of the chat side that are drawn outside the chat window. The blocks read the\n * package's `--agents-*` properties; a host that maps them to its theme below a selector of its own passes that\n * selector's attributes as `frameAttributes`.\n */\nexport const AgentTraceFrame = ({ frameAttributes, className, children, ...rest }: AgentTraceFrameProps) => (\n <div {...frameAttributes} {...rest} className={cn(\"min-w-0\", className)} data-slot=\"agent-trace-frame\">\n {children}\n </div>\n);\n\n/** A fact of a card: a small caption over its value and a muted line. */\nexport const InspectFactCard = ({\n caption,\n value,\n detail,\n tone,\n children,\n className,\n}: {\n caption: ReactNode;\n value: ReactNode;\n detail?: ReactNode;\n tone?: \"warning\" | \"danger\";\n children?: ReactNode;\n className?: string;\n}) => (\n <div\n data-slot=\"agent-inspect-fact\"\n className={cn(\n \"flex min-w-0 flex-col gap-0.5 rounded-2xl bg-card px-4 py-3 shadow-sm\",\n tone === \"warning\" && \"shadow-[inset_3px_0_0_var(--warning)]\",\n tone === \"danger\" && \"shadow-[inset_3px_0_0_var(--destructive)]\",\n className,\n )}\n >\n <span className=\"text-[11px] font-semibold tracking-wide text-muted-foreground uppercase\">{caption}</span>\n <span className=\"truncate text-base font-bold\">{value}</span>\n {detail ? (\n <span className=\"line-clamp-2 text-xs leading-5 text-muted-foreground\" title={typeof detail === \"string\" ? detail : undefined}>\n {detail}\n </span>\n ) : null}\n {children}\n </div>\n);\n\n/** A thin meter: how much of a whole is used (0–100 and above; above 100 is full). */\nexport const InspectMeter = ({ percent, tone, label }: { percent: number; tone?: \"warning\" | \"danger\"; label: string }) => (\n <div className=\"h-1.5 overflow-hidden rounded-full bg-muted\" role=\"img\" aria-label={label} title={label}>\n <div\n className={cn(\"h-full rounded-full bg-brand-emphasis\", tone === \"warning\" && \"bg-warning\", tone === \"danger\" && \"bg-destructive\")}\n style={{ width: `${Math.min(100, Math.max(0, percent))}%` }}\n />\n </div>\n);\n\n/** A quiet text button inside a row of actions. */\nexport const InspectActionButton = ({\n icon,\n children,\n onClick,\n disabled,\n title,\n testId,\n}: {\n icon?: ReactNode;\n children: ReactNode;\n onClick: () => void;\n disabled?: boolean;\n title?: string;\n testId?: string;\n}) => (\n <button\n type=\"button\"\n onClick={onClick}\n disabled={disabled}\n title={title}\n data-testid={testId}\n className=\"inline-flex h-7 items-center gap-1.5 rounded-full bg-card px-2.5 text-xs font-semibold text-foreground shadow-[inset_0_0_0_1px_var(--input)] hover:bg-muted disabled:cursor-not-allowed disabled:opacity-50 [&_svg]:size-3.5\"\n >\n {icon}\n {children}\n </button>\n);\n","import type { CodeHighlighterLoader } from \"@mgamadeus/ddd-admin-ui/files\";\nimport type { PageLinkComponent } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { createContext, type ReactNode, useContext } from \"react\";\nimport type { TraceDescribeMount, TraceFileChange, TraceHostBindings } from \"../../chat/trace/trace-types\";\nimport type { ConversationTraceLevel } from \"../../contract/conversation-trace\";\nimport type { AgentInspectApi } from \"./agent-inspect-api\";\nimport type { AgentInspectFileChange, AgentInspectStep } from \"./agent-inspect-types\";\nimport type { AgentTraceFrameAttributes } from \"./inspect-parts\";\n\n/** What the admin may do to the open conversation; each function asks before it acts. */\nexport interface AgentInspectActions {\n /** False: the controls show, disabled (the environment locks writes). */\n writesAllowed: boolean;\n /**\n * Opens the dialog that writes a message as admin; `truncateFromIndex` branches from that position first and\n * `initialMessage` fills the message (running a turn again with the message that started it).\n */\n openDrive: (options?: { truncateFromIndex?: number; truncateLabel?: string; initialMessage?: string }) => void;\n /** Truncates from a position (`indexInConversation`) after a confirmation. */\n truncateFrom: (fromIndex: number, label: string) => void;\n /** Runs a reading tool call again after a confirmation and shows its answer. */\n replayToolCall: (step: AgentInspectStep) => void;\n}\n\n/** The file and the change of the sandbox and files tabs a link names (`?file=…&change=…`). */\nexport interface AgentInspectFileSelection {\n /** The path of the picked file in its mount; null for none. */\n filePath: string | null;\n /** The picked change of that file; null for its newest. */\n fileChangeId: number | null;\n select: (filePath: string | null, fileChangeId?: number | null) => void;\n}\n\n/** What the detail hands the host's file preview beside the change. */\nexport interface AgentInspectFilePreviewOptions {\n /**\n * The file's content as the recorded change wrote it (rebuilt from the change's diff, drawn by type, with a note\n * that says so), for the host to show in place of its own \"cannot show this file\" state: the stored file is gone,\n * the reader may not open it, its malware check has not released it. Null when the change's diff does not hold the\n * whole file (then the host shows its own state).\n */\n fallback: ReactNode | null;\n}\n\n/**\n * The host's preview of a changed file as it is stored (the rendered document, the picture, the highlighted code);\n * null for a change without a stored version (a temporary file, a deleted file): the detail then shows\n * `options.fallback` itself when there is one, else the diff alone.\n */\nexport type AgentInspectRenderFilePreview = (fileChange: AgentInspectFileChange, options?: AgentInspectFilePreviewOptions) => ReactNode;\n\n/** What the parts of the conversation detail share. */\nexport interface AgentInspectScope {\n api: AgentInspectApi;\n conversationId: number;\n /** The level the trace is read at: `DEBUG` while the debug switch is on. */\n level: ConversationTraceLevel;\n isDebug: boolean;\n locale: string | undefined;\n formatCost: (costInUsd: number) => string;\n linkComponent: PageLinkComponent;\n /** The host's bindings of the trace blocks: links, records, mounts, money, the whole diff of a change. */\n host: TraceHostBindings;\n describeMount?: TraceDescribeMount;\n loadFullDiff: (fileChange: TraceFileChange) => Promise<string>;\n renderMarkdown?: (source: string) => ReactNode;\n frameAttributes?: AgentTraceFrameAttributes;\n /** How the agent is named beside its answers. */\n agentDisplayName: string;\n buildConversationHref?: (conversationId: number) => string | null;\n /** Null: the reader may not drive conversations. */\n actions: AgentInspectActions | null;\n /** The reader may read what a model call was sent (the composition and the payload); false hides those actions. */\n canReadModelContext: boolean;\n /** Opens what the model was sent at the call of a message. */\n openModelContext: (messageId: number, view?: \"composition\" | \"payload\") => void;\n /** Opens the detail of one step beside the conversation. */\n openStepDetail: (stepId: string) => void;\n /** Opens \"Save as evaluation case\" for the turn of a message; undefined when the host offers none. */\n openEvalCase?: (messageId: number) => void;\n fileSelection: AgentInspectFileSelection;\n /** The host's preview of a changed file as it is stored; see `AgentInspectRenderFilePreview`. */\n renderFilePreview?: AgentInspectRenderFilePreview;\n /** The host's highlighter, for the source of a file rebuilt from a recorded change; without it the source stays plain. */\n loadCodeHighlighter?: CodeHighlighterLoader;\n /** The host's facts of the conversation's live workspace (state, usage, a link to its screen), above the sandbox tab. */\n renderSandboxFacts?: () => ReactNode;\n /** The host's display name of a model by its catalog name (\"GPT-6 Luna\"); null or absent: the name in words. */\n describeModelName?: (modelName: string) => string | null;\n}\n\nconst AgentInspectScopeContext = createContext<AgentInspectScope | null>(null);\n\nexport const AgentInspectScopeProvider = AgentInspectScopeContext.Provider;\n\n/** The scope of the conversation detail the part is drawn in. */\nexport const useAgentInspectScope = (): AgentInspectScope => {\n const scope = useContext(AgentInspectScopeContext);\n if (scope === null) throw new Error(\"This block is a part of AgentConversationDetailScreen and needs its scope.\");\n return scope;\n};\n","import { m } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { describeTraceDecisionSite, describeTraceSignal, type TraceLabelTranslate } from \"../../chat/trace/trace-labels\";\nimport type { AgentInspectDecision, AgentInspectStep } from \"./agent-inspect-types\";\n\n// The words of the steps the trace carries without a line of their own: side decisions and signals. Pure (the\n// translation comes in as a function), so the lines are covered by tests.\n\nexport const AGENT_DECISION_STATUS_CONTEXT = \"agent-decision-status\";\n\n/** How a side decision ended, in words (the keys are the server's statuses in lowercase). */\nexport const AGENT_DECISION_STATUS_LABELS: Readonly<Record<string, string>> = {\n decided: m(\"decided\", { context: \"agent-decision-status\" }),\n applied: m(\"applied\", { context: \"agent-decision-status\" }),\n shadow: m(\"recorded only\", { context: \"agent-decision-status\" }),\n fallback: m(\"fallback\", { context: \"agent-decision-status\" }),\n skipped: m(\"skipped\", { context: \"agent-decision-status\" }),\n};\n\nexport const AGENT_DECISION_ENGINE_CONTEXT = \"agent-decision-engine\";\n\n/** What decided, in words; another engine shows the server's label, else its name. */\nexport const AGENT_DECISION_ENGINE_LABELS: Readonly<Record<string, string>> = {\n decisionModel: m(\"decision model\", { context: \"agent-decision-engine\" }),\n rule: m(\"rule\", { context: \"agent-decision-engine\" }),\n default: m(\"default, no answer\", { context: \"agent-decision-engine\" }),\n};\n\n/** Translates a text key in a context (`useTranslate().t` bound to the context). */\nexport type TranslateInContext = (text: string, context: string) => string;\n\nexport type AgentDecisionStatusTone = \"neutral\" | \"success\" | \"warning\" | \"info\";\n\nexport interface AgentDecisionWords {\n /** The site in words (\"Skill preload\"): the server's label, else the site's id in words. */\n site: string | null;\n /** What decided (\"decision model\", \"Jev\", \"rule · precondition\"); null when the step does not say. */\n engine: string | null;\n /** The end in words (\"applied\"). */\n status: string | null;\n /** The tone of the end: a fallback is a warning, an applied decision a success. */\n statusTone: AgentDecisionStatusTone;\n summary: string | null;\n}\n\n/** An id in camel case as words (`skillPreload` → `Skill preload`); anything else stays as it is. */\nexport const wordsOfIdentifier = (identifier: string): string => {\n if (!/^[a-z][A-Za-z0-9]*$/.test(identifier)) return identifier;\n const words = identifier.replace(/([a-z0-9])([A-Z])/g, \"$1 $2\").toLowerCase();\n return `${words[0].toUpperCase()}${words.slice(1)}`;\n};\n\nconst STATUS_TONES: Readonly<Record<string, AgentDecisionStatusTone>> = { applied: \"success\", fallback: \"warning\", shadow: \"info\" };\n\n/** A label translation that leaves the key as it is (tests, a caller without a text store). */\nconst keepLabel: TraceLabelTranslate = (text) => text;\n\n/**\n * The words of a side decision: where it was taken (the stable words of a known site, `translateLabel`; else the\n * server's label, else the id in words), what decided, how it ended and what came out.\n */\nexport const describeAgentDecision = (decision: AgentInspectDecision, translate: TranslateInContext, translateLabel: TraceLabelTranslate = keepLabel): AgentDecisionWords => {\n const statusKey = decision.status?.toLowerCase() ?? null;\n const status =\n statusKey !== null && Object.hasOwn(AGENT_DECISION_STATUS_LABELS, statusKey)\n ? translate(AGENT_DECISION_STATUS_LABELS[statusKey], AGENT_DECISION_STATUS_CONTEXT)\n : decision.status;\n const engine =\n decision.engineLabel ??\n (decision.engine !== null && Object.hasOwn(AGENT_DECISION_ENGINE_LABELS, decision.engine)\n ? translate(AGENT_DECISION_ENGINE_LABELS[decision.engine], AGENT_DECISION_ENGINE_CONTEXT)\n : decision.engine === null\n ? null\n : wordsOfIdentifier(decision.engine));\n return {\n site: describeTraceDecisionSite(decision.site, decision.siteLabel, translateLabel),\n engine,\n status,\n statusTone: statusKey !== null && Object.hasOwn(STATUS_TONES, statusKey) ? STATUS_TONES[statusKey] : \"neutral\",\n summary: decision.resultSummary ?? decision.skipReason ?? decision.fallbackReason,\n };\n};\n\n/** One line for the row of a side decision: `Skill preload · decision model · applied: preloaded Agent.Sandbox.Shell`. */\nexport const agentDecisionLine = (words: AgentDecisionWords): string | null => {\n const head = [words.site, words.engine, words.status].filter((part): part is string => part !== null && part !== \"\").join(\" · \");\n if (head === \"\") return words.summary;\n return words.summary ? `${head}: ${words.summary}` : head;\n};\n\n/**\n * A JSON text set out over lines for reading. A text that is no whole JSON (a cut excerpt, a plain text) comes back\n * as it is: showing it unformatted is the right answer for it, so the parser's refusal is the signal, not a failure.\n */\nexport const formatJsonForReading = (text: string): string => {\n const trimmedText = text.trim();\n if (!trimmedText.startsWith(\"{\") && !trimmedText.startsWith(\"[\")) return text;\n try {\n return JSON.stringify(JSON.parse(trimmedText), null, 2);\n } catch {\n return text;\n }\n};\n\n/** The longest signal text a row shows. */\nconst SIGNAL_LINE_MAX_CHARS = 120;\n\n/**\n * The step with the line of its row: a side decision by its words (site, what decided, end, result — more than the\n * server's own short line), a signal without a line by its name in words (`describeTraceSignal`: its tag, else its\n * source) and the start of its text. Every other step comes back as it is. `translateLabel` translates the stable\n * words of the trace values (`chat/trace/trace-labels.ts`).\n */\nexport const withInspectStepLine = (step: AgentInspectStep, translate: TranslateInContext, translateLabel: TraceLabelTranslate = keepLabel): AgentInspectStep => {\n if (step.kind === \"DECISION\" && step.decision !== null) {\n const line = agentDecisionLine(describeAgentDecision(step.decision, translate, translateLabel));\n return line === null || line === step.line ? step : { ...step, line };\n }\n if (step.line) return step;\n if (step.kind === \"SIGNAL\" && (step.signalSource || step.signalText)) {\n const text = (step.signalText ?? \"\").replace(/\\s+/g, \" \").trim();\n const shownText = text.length > SIGNAL_LINE_MAX_CHARS ? `${text.slice(0, SIGNAL_LINE_MAX_CHARS)}…` : text;\n const signalName = describeTraceSignal(step.signal?.tag ?? step.signal?.kind ?? null, step.signalSource, null, translateLabel);\n return { ...step, line: [signalName, shownText].filter((part) => part !== null && part !== \"\").join(\": \") };\n }\n return step;\n};\n","import { describeTraceModelName } from \"../../chat/trace/trace-format\";\nimport type { AgentInspectStep, AgentInspectTrace, AgentInspectTurn } from \"./agent-inspect-types\";\n\n// How the turns of a long conversation are held: the newest window first, older windows on demand, and the turns a\n// follow-up read of a running conversation returns laid over them. Pure, so the merge is covered by tests.\n\n/** Turns loaded per window (the newest ones first, then each \"load earlier turns\"). */\nexport const AGENT_INSPECT_TURN_PAGE_SIZE = 10;\n\n/** A window of turns of the trace read. */\nexport interface AgentInspectTurnWindow {\n fromTurnNumber: number;\n limit: number;\n}\n\n/**\n * The turns of two reads as one list, oldest first: a turn of `incoming` replaces the loaded turn of the same number\n * (a polled running turn carries more steps than the one loaded before), every other turn stays.\n */\nexport const mergeAgentInspectTurns = (loaded: readonly AgentInspectTurn[], incoming: readonly AgentInspectTurn[]): AgentInspectTurn[] => {\n if (incoming.length === 0) return [...loaded];\n const turnByNumber = new Map<number, AgentInspectTurn>();\n for (const turn of loaded) turnByNumber.set(turn.turnNumber, turn);\n for (const turn of incoming) turnByNumber.set(turn.turnNumber, turn);\n return [...turnByNumber.values()].sort((first, second) => first.turnNumber - second.turnNumber);\n};\n\n/** What a page read of older turns answered: its turns and the paging facts of that page. */\nexport type AgentInspectTurnPage = Pick<AgentInspectTrace, \"turns\" | \"firstTurnNumber\" | \"hasOlderTurns\">;\n\n/**\n * The trace a screen shows: the page of the newest turns with the pages of older turns before it and the follow-up\n * read of a running conversation over it.\n *\n * - `hasOlderTurns` is the fact of the page that reaches furthest back (the server says whether turns exist before\n * the first turn of a page); a follow-up read is no page and never changes it.\n * - `hasNewerTurns` stays the newest page's (false: it ends at the newest turn, and the follow-up read reads through\n * the newest turn).\n * - The run facts (`isRunLive`, `runState`, `newestMessageIndex`) and the turn count are those of the follow-up read\n * when there is one, since it is the newer look at the conversation.\n */\nexport const mergeAgentInspectTraces = (\n newest: AgentInspectTrace,\n olderPages: readonly AgentInspectTurnPage[],\n followUp: AgentInspectTrace | null,\n): AgentInspectTrace => {\n const olderTurns = olderPages.reduce<AgentInspectTurn[]>((turns, page) => mergeAgentInspectTurns(turns, page.turns), []);\n const turns = mergeAgentInspectTurns(mergeAgentInspectTurns(olderTurns, newest.turns), followUp?.turns ?? []);\n // The page that starts at the lowest turn number knows whether anything is older.\n let oldestPage: AgentInspectTurnPage = newest;\n for (const page of olderPages) {\n if (page.firstTurnNumber !== null && (oldestPage.firstTurnNumber === null || page.firstTurnNumber < oldestPage.firstTurnNumber)) oldestPage = page;\n }\n return {\n ...newest,\n turns,\n totalTurnCount: Math.max(followUp?.totalTurnCount ?? newest.totalTurnCount, turns[turns.length - 1]?.turnNumber ?? 0),\n firstTurnNumber: turns[0]?.turnNumber ?? null,\n lastTurnNumber: turns[turns.length - 1]?.turnNumber ?? null,\n hasOlderTurns: oldestPage.hasOlderTurns,\n hasNewerTurns: newest.hasNewerTurns,\n newestMessageIndex: followUp?.newestMessageIndex ?? newest.newestMessageIndex,\n isRunLive: followUp ? followUp.isRunLive : newest.isRunLive,\n runState: followUp?.runState ?? newest.runState,\n };\n};\n\n/**\n * The page before the first loaded turn: null when the trace says nothing is older (`hasOlderTurns`), else the\n * `pageSize` turns that end right before `firstTurnNumber` (turn numbers are positions among all turns, from 1).\n */\nexport const previousAgentInspectTurnWindow = (\n trace: Pick<AgentInspectTrace, \"hasOlderTurns\" | \"firstTurnNumber\">,\n pageSize: number = AGENT_INSPECT_TURN_PAGE_SIZE,\n): AgentInspectTurnWindow | null => {\n if (!trace.hasOlderTurns || trace.firstTurnNumber === null || trace.firstTurnNumber <= 1) return null;\n const fromTurnNumber = Math.max(1, trace.firstTurnNumber - pageSize);\n return { fromTurnNumber, limit: trace.firstTurnNumber - fromTurnNumber };\n};\n\n/**\n * The position (`indexInConversation`) the follow-up read of a live conversation asks after: the newest row the page\n * of the newest turns saw, moved back before the first row of every turn that runs — a running turn comes back whole\n * with every poll, because a step changes its status without a new row. Null when the page saw no row.\n */\nexport const followUpPositionOfAgentInspectTrace = (trace: Pick<AgentInspectTrace, \"newestMessageIndex\" | \"turns\">): number | null => {\n if (trace.newestMessageIndex === null) return null;\n let position = trace.newestMessageIndex;\n for (const turn of trace.turns) {\n if (turn.isRunning && turn.turnMessageIndex !== null) position = Math.min(position, turn.turnMessageIndex - 1);\n }\n return Math.max(-1, position);\n};\n\n/** The step a link names (`?step=<id>`) among the loaded turns; null when none of them holds it. */\nexport const findAgentInspectStep = (turns: readonly AgentInspectTurn[], stepId: string | null): AgentInspectStep | null => {\n if (stepId === null) return null;\n for (const turn of turns) {\n const step = turn.steps.find((candidate) => candidate.stepId === stepId);\n if (step) return step;\n }\n return null;\n};\n\n/** A model call of the conversation, as a picker names it. */\nexport interface AgentInspectModelCallReference {\n messageId: number;\n turnNumber: number;\n /** The number of the call within its turn, from 1. */\n callNumber: number;\n /** The model of the call in words (\"GPT6 LUNA\"). */\n modelName: string | null;\n}\n\n/**\n * The model calls of the loaded turns, oldest first. At debug level they are the `MODEL_CALL` steps; at the level of\n * steps (no such steps) the assistant's text messages stand for them, since each of them came out of a model call.\n */\nexport const collectAgentInspectModelCalls = (turns: readonly AgentInspectTurn[]): AgentInspectModelCallReference[] => {\n const modelCalls: AgentInspectModelCallReference[] = [];\n for (const turn of turns) {\n const callSteps = turn.steps.filter((step) => step.kind === \"MODEL_CALL\" && step.messageId !== null);\n if (callSteps.length > 0) {\n callSteps.forEach((step, position) => {\n modelCalls.push({\n messageId: step.messageId as number,\n turnNumber: turn.turnNumber,\n callNumber: position + 1,\n modelName: step.modelLabel ?? describeTraceModelName(step.modelCall?.modelName),\n });\n });\n continue;\n }\n turn.answerMessageIds.forEach((messageId, position) => {\n const answerMessage = turn.answerMessages.find((message) => message.messageId === messageId);\n modelCalls.push({ messageId, turnNumber: turn.turnNumber, callNumber: position + 1, modelName: answerMessage?.modelLabel ?? describeTraceModelName(turn.totals.modelName) });\n });\n }\n // A message that carries a call and an answer is one call.\n const seenMessageIds = new Set<number>();\n return modelCalls.filter((modelCall) => (seenMessageIds.has(modelCall.messageId) ? false : (seenMessageIds.add(modelCall.messageId), true)));\n};\n\n/** The message whose model call is the newest of the loaded turns; null without one. */\nexport const newestAgentInspectModelCallMessageId = (turns: readonly AgentInspectTurn[]): number | null => {\n const modelCalls = collectAgentInspectModelCalls(turns);\n return modelCalls[modelCalls.length - 1]?.messageId ?? null;\n};\n","import type { AgentInspectMessage, AgentInspectStep, AgentInspectTurn } from \"./agent-inspect-types\";\n\n// How a turn reads as a conversation: the steps in order, cut where the assistant wrote a text between two steps (an\n// interim text: the model call that wrote it also called tools), and the answers after them. Pure, covered by tests.\n\n/** A stretch of a turn's steps; one that starts at a model call with an interim text carries that step. */\nexport interface AgentInspectTurnSegment {\n key: string;\n /** The step whose model call wrote a text before its tools ran; null for the stretch before the first such text. */\n interimStep: AgentInspectStep | null;\n /** The steps of the stretch in order, the interim step first. */\n steps: AgentInspectStep[];\n}\n\n/**\n * The steps of a turn as stretches: a new stretch starts at every step that carries an interim text\n * (`assistantText`), so the text stands where it was written — after the steps before it and before the steps its\n * model call issued. A turn without such a text is one stretch; a turn without steps is one empty stretch.\n */\nexport const splitAgentInspectTurnAtInterimTexts = (steps: readonly AgentInspectStep[]): AgentInspectTurnSegment[] => {\n const segments: AgentInspectTurnSegment[] = [{ key: \"start\", interimStep: null, steps: [] }];\n for (const step of steps) {\n if (step.assistantText) segments.push({ key: `interim:${step.key}`, interimStep: step, steps: [step] });\n else segments[segments.length - 1].steps.push(step);\n }\n // A turn that starts with an interim text has no stretch before it.\n return segments.length > 1 && segments[0].steps.length === 0 ? segments.slice(1) : segments;\n};\n\n/** A widget block an answer's text carries, read from its fence. */\nexport interface AgentInspectWidgetFence {\n type: string | null;\n title: string | null;\n /** The JSON of the block as the text holds it. */\n json: string;\n}\n\n/** A ```widget fence: its info string (a space before the language is allowed) and the JSON up to the closing fence. */\nconst WIDGET_FENCE_PATTERN = /```[ \\t]*widget[ \\t]*\\r?\\n([\\s\\S]*?)\\r?\\n?[ \\t]*```/g;\n\nconst readFenceText = (record: Record<string, unknown>, key: string): string | null => {\n const value = record[key];\n return typeof value === \"string\" && value.trim() !== \"\" ? value.trim() : null;\n};\n\n/**\n * An answer's text without its widget blocks, and the blocks it held. The admin view shows a widget by its title (and\n * its fields behind a fold at the debug level), never as the raw JSON the model wrote. A block whose JSON does not\n * parse still leaves the text; its type and title are then unknown.\n */\nexport const splitAgentInspectWidgetFences = (text: string): { text: string; fences: AgentInspectWidgetFence[] } => {\n const fences: AgentInspectWidgetFence[] = [];\n const shownText = text.replace(WIDGET_FENCE_PATTERN, (_whole, json: string) => {\n let parsed: unknown = null;\n try {\n parsed = JSON.parse(json);\n } catch {\n // a block the model wrote broken is still a widget block: it leaves the text, its fields stay unknown\n parsed = null;\n }\n const record = parsed !== null && typeof parsed === \"object\" && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : {};\n fences.push({ type: readFenceText(record, \"type\"), title: readFenceText(record, \"title\"), json: json.trim() });\n return \"\";\n });\n return { text: fences.length > 0 ? shownText.replace(/\\n{3,}/g, \"\\n\\n\").trim() : text, fences };\n};\n\n/**\n * The texts of the assistant that stand below the steps of a turn: every answer, and an interim text only when none\n * of the turn's steps carries it (the steps of a truncated branch were left out, an older read).\n */\nexport const readAgentInspectTurnAnswers = (turn: Pick<AgentInspectTurn, \"answerMessages\" | \"steps\">): AgentInspectMessage[] => {\n const interimMessageIds = new Set<number>();\n for (const step of turn.steps) if (step.assistantText && step.messageId !== null) interimMessageIds.add(step.messageId);\n return turn.answerMessages.filter((message) => !(message.isInterim && message.messageId !== null && interimMessageIds.has(message.messageId)));\n};\n","import { describeTraceModelName, readTraceMoment, readTraceStepState } from \"../../chat/trace/trace-format\";\nimport type { AgentInspectTurn } from \"./agent-inspect-types\";\n\n// Where the time of a turn went: its model calls, tool calls and sub-agents as segments on the turn's own time axis.\n\nexport type TurnTimelineSegmentKind = \"modelCall\" | \"toolCall\" | \"subAgent\" | \"failed\";\n\nexport interface TurnTimelineSegment {\n key: string;\n /** The step behind the segment (the id its detail opens by). */\n stepId: string;\n kind: TurnTimelineSegmentKind;\n /** The step's name: its model or its tool. */\n label: string;\n durationMs: number;\n leftPercent: number;\n widthPercent: number;\n}\n\nexport interface TurnTimeline {\n durationMs: number;\n segments: TurnTimelineSegment[];\n}\n\n/** The smallest width of a segment, so a step of a few milliseconds stays visible. */\nconst MINIMUM_SEGMENT_PERCENT = 0.6;\n\n/**\n * The timeline of a turn: one segment per step that has a start and a duration, placed between the turn's start and\n * its end (the later of its recorded duration and the end of its last step). Null without a readable start.\n */\nexport const buildTurnTimeline = (turn: AgentInspectTurn): TurnTimeline | null => {\n const turnStartedAt = readTraceMoment(turn.startedAt);\n if (turnStartedAt === null) return null;\n const timedSteps = turn.steps.flatMap((step) => {\n const startedAt = readTraceMoment(step.startedAt);\n if (startedAt === null || step.durationMs === null || step.durationMs <= 0) return [];\n if (step.kind !== \"MODEL_CALL\" && step.kind !== \"TOOL_CALL\" && step.kind !== \"SUB_AGENT\" && step.kind !== \"SKILL_LOAD\") return [];\n return [{ step, startedAt: Math.max(startedAt, turnStartedAt), durationMs: step.durationMs }];\n });\n const lastStepEndedAt = timedSteps.reduce((latest, timedStep) => Math.max(latest, timedStep.startedAt + timedStep.durationMs), turnStartedAt);\n const durationMs = Math.max(turn.totals.durationMs ?? 0, lastStepEndedAt - turnStartedAt);\n if (durationMs <= 0) return { durationMs: 0, segments: [] };\n return {\n durationMs,\n segments: timedSteps.map(({ step, startedAt, durationMs: stepDurationMs }) => {\n const widthPercent = Math.max(MINIMUM_SEGMENT_PERCENT, (stepDurationMs / durationMs) * 100);\n const kind: TurnTimelineSegmentKind =\n readTraceStepState(step) === \"failed\" ? \"failed\" : step.kind === \"MODEL_CALL\" ? \"modelCall\" : step.kind === \"SUB_AGENT\" ? \"subAgent\" : \"toolCall\";\n return {\n key: step.key,\n stepId: step.stepId,\n kind,\n label: step.kind === \"MODEL_CALL\" ? (step.modelLabel ?? describeTraceModelName(step.modelCall?.modelName) ?? \"model\") : step.kind === \"SUB_AGENT\" ? (step.subAgent?.label ?? \"sub-agent\") : (step.toolName ?? \"tool\"),\n durationMs: stepDurationMs,\n leftPercent: Math.max(0, Math.min(((startedAt - turnStartedAt) / durationMs) * 100, 100 - widthPercent)),\n widthPercent,\n };\n }),\n };\n};\n","import { normalizeDddError } from \"@mgamadeus/ddd-web/contract\";\nimport { formatUiNumber, m, useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { StatusBadge, Tag } from \"@mgamadeus/ddd-admin-ui/list\";\nimport { StatusCallout } from \"@mgamadeus/ddd-admin-ui/page\";\nimport { Button, Card, CardContent, cn, Skeleton } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { Archive, ChevronsUp, CircleStop, ClipboardCheck, Clock, Eye, FileJson, GitBranch, LayoutPanelTop, PanelRightOpen, Play, RotateCcw, ScrollText } from \"lucide-react\";\nimport { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { FileChangesSummary } from \"../../chat/trace/FileChangesSummary\";\nimport { LoadedSkillsDisclosure } from \"../../chat/trace/LoadedSkillsDisclosure\";\nimport { ToolStepGroup } from \"../../chat/trace/ToolStepGroup\";\nimport { createTraceFormat, describeTraceEffort, describeTraceModelName, readTraceMoment } from \"../../chat/trace/trace-format\";\nimport type { TraceHostBindings, TraceLoadedSkill, TraceStep, TraceViewMode } from \"../../chat/trace/trace-types\";\nimport { TurnMetaLine } from \"../../chat/trace/TurnMetaLine\";\nimport { CodeBlock } from \"../blocks/CodeBlock\";\nimport type { ConversationTraceMessage } from \"../../contract/conversation-trace\";\nimport { Disclosure } from \"../blocks/Disclosure\";\nimport { mapAgentInspectMessageText, mapAgentInspectTrace } from \"./agent-inspect-mappers\";\nimport type { AgentInspectCompactionNode, AgentInspectStep, AgentInspectTrace, AgentInspectTurn } from \"./agent-inspect-types\";\nimport {\n type AgentInspectDebugSwitches,\n applyAgentInspectDebugSwitches,\n applyAgentInspectDebugSwitchesToTotals,\n} from \"./debug-switches\";\nimport { readAgentInspectModelLabel } from \"./header-facts\";\nimport { formatAgentInspectCount } from \"./inspect-format\";\nimport { AgentTraceFrame, InspectActionButton, LiveDot } from \"./inspect-parts\";\nimport { useAgentInspectScope } from \"./inspect-scope\";\nimport { formatJsonForReading, withInspectStepLine } from \"./step-descriptions\";\nimport {\n AGENT_INSPECT_TURN_PAGE_SIZE,\n type AgentInspectTurnPage,\n type AgentInspectTurnWindow,\n findAgentInspectStep,\n followUpPositionOfAgentInspectTrace,\n mergeAgentInspectTraces,\n previousAgentInspectTurnWindow,\n} from \"./turn-paging\";\nimport { readAgentInspectTurnAnswers, splitAgentInspectTurnAtInterimTexts, splitAgentInspectWidgetFences } from \"./turn-segments\";\nimport { buildTurnTimeline, type TurnTimelineSegmentKind } from \"./turn-timeline\";\n\nconst OUTCOME_CONTEXT = \"agent-turn-outcome\";\n\n/** How a turn ended, in words; `answered` is the usual end and gets no mark, a stop by the owner a quiet one of its own. */\nconst OUTCOME_LABELS: Readonly<Record<string, { label: string; tone: \"neutral\" | \"warning\" | \"danger\" }>> = {\n gaveUp: { label: m(\"gave up\", { context: \"agent-turn-outcome\" }), tone: \"warning\" },\n failed: { label: m(\"failed\", { context: \"agent-turn-outcome\" }), tone: \"danger\" },\n cancelled: { label: m(\"cancelled\", { context: \"agent-turn-outcome\" }), tone: \"neutral\" },\n expired: { label: m(\"expired\", { context: \"agent-turn-outcome\" }), tone: \"warning\" },\n waitingForSubAgents: { label: m(\"waits for sub-agents\", { context: \"agent-turn-outcome\" }), tone: \"warning\" },\n};\n\nconst TIMELINE_SEGMENT_CLASS_NAMES: Readonly<Record<TurnTimelineSegmentKind, string>> = {\n modelCall: \"bg-info/45\",\n toolCall: \"bg-brand\",\n subAgent: \"bg-success/50\",\n failed: \"bg-destructive/70\",\n};\n\n/** Whether the admin view adds facts or actions of its own to the open row of a step, beside the link to its detail. */\nconst hasStepExtras = (step: AgentInspectStep, isDebug: boolean, canDrive: boolean): boolean => {\n if (step.kind === \"MODEL_CALL\") return step.messageId !== null;\n if (step.kind === \"SIGNAL\") return Boolean(step.signalText) || Boolean(step.signalSource);\n if (step.kind === \"DECISION\") return Boolean(step.eventKind) || Boolean(step.eventPayloadExcerpt);\n if (step.kind === \"COMPACTION\") return step.compactionNode !== null;\n if (step.kind === \"WIDGET\") return isDebug && step.widget !== null;\n if (step.kind !== \"TOOL_CALL\" && step.kind !== \"SKILL_LOAD\" && step.kind !== \"TASK_PLAN\") return false;\n if (!isDebug) return false;\n return (\n step.isResultCut ||\n step.executionCostInUsd !== null ||\n step.isRefused ||\n step.wasRemovedForSecurity ||\n step.isCallToolWithoutToolName ||\n (canDrive && step.messageIndex !== null) ||\n (canDrive && step.effect === \"READ\" && step.messageId !== null)\n );\n};\n\n/** The whole stored result of a tool call, read when the admin asks for it. */\nconst FullToolCallResult = ({ messageId }: { messageId: number }) => {\n const { t } = useTranslate();\n const { api, conversationId } = useAgentInspectScope();\n const query = api.useToolCallResultQuery({ conversationId, messageId });\n if (query.isError) {\n return <p className=\"text-xs text-destructive\">{normalizeDddError(query.error, t(\"The result could not be loaded.\")).message}</p>;\n }\n if (query.data === undefined) return <Skeleton className=\"h-24 w-full\" />;\n return (\n <CodeBlock\n code={query.data.result ?? \"\"}\n caption={t(\"Whole result, %count% characters\", { replacements: { count: formatUiNumber(query.data.resultChars ?? 0) } })}\n aria-label={t(\"Whole result of the tool call\")}\n />\n );\n};\n\n/** A compaction node in one line, its summary behind a fold. */\nexport const CompactionNodeLine = ({ node, className }: { node: AgentInspectCompactionNode; className?: string }) => {\n const { t } = useTranslate();\n const { locale, describeModelName } = useAgentInspectScope();\n const facts = [\n node.coveredFromMessageIndex != null && node.coveredToMessageIndex != null\n ? t(\"messages %from%–%to%\", { replacements: { from: node.coveredFromMessageIndex, to: node.coveredToMessageIndex } })\n : null,\n node.coveredTokens != null && node.summaryTokens != null\n ? t(\"%before% → %after% tokens\", {\n replacements: { before: formatAgentInspectCount(node.coveredTokens, locale), after: formatAgentInspectCount(node.summaryTokens, locale) },\n })\n : null,\n node.level != null && node.level > 0 ? t(\"level %level%, over older summaries\", { replacements: { level: node.level } }) : null,\n (node.modelName ? describeModelName?.(node.modelName) : null) || describeTraceModelName(node.modelName),\n ].filter((fact): fact is string => fact !== null);\n return (\n <div className={cn(\"rounded-xl bg-muted px-3 py-2 text-xs text-foreground\", className)} data-slot=\"agent-compaction-node\">\n <div className=\"flex flex-wrap items-center gap-x-2 gap-y-1\">\n <Archive className=\"size-3.5 shrink-0 text-muted-foreground\" aria-hidden />\n <span className=\"font-semibold\">{t(\"Compaction\", { context: \"agent-step-kind\" })}</span>\n <span className=\"text-muted-foreground\">{facts.join(\" · \")}</span>\n </div>\n {node.summaryText ? (\n <Disclosure size=\"sm\" title={t(\"Summary\")} meta={node.isSummaryCut ? <Tag size=\"sm\">{t(\"shortened\", { context: \"agent-inspect\" })}</Tag> : undefined} className=\"mt-1\">\n <p className=\"max-h-80 overflow-auto whitespace-pre-wrap break-words pt-1 text-xs leading-5\">{node.summaryText}</p>\n </Disclosure>\n ) : null}\n </div>\n );\n};\n\n/** Why the loop refused a control call, in words (a `REFUSED` step: quiet, no failure). */\nconst REFUSAL_REASON_LABELS: Readonly<Record<string, string>> = {\n turnAnswersOwner: m(\"not run: this turn owes the owner an answer first\", { context: \"agent-step-refusal\" }),\n ownerWroteDuringTurn: m(\"not run: the owner wrote during the turn\", { context: \"agent-step-refusal\" }),\n noSubAgentRunning: m(\"not run: no sub-agent was running\", { context: \"agent-step-refusal\" }),\n other: m(\"not run: the loop refused the call by design\", { context: \"agent-step-refusal\" }),\n};\n\n/** What the admin view adds to the open detail of a step: its facts and the actions on it. */\nexport const InspectStepExtras = ({\n step,\n showsDetailLink = true,\n showsModelCallFacts = true,\n}: {\n step: AgentInspectStep;\n /** The button that opens the step's detail (off inside that detail and for the steps of a sub-agent). */\n showsDetailLink?: boolean;\n /** The line of a model call's technical facts (off where they stand as a grid already). */\n showsModelCallFacts?: boolean;\n}) => {\n const { t } = useTranslate();\n const { isDebug, actions, openModelContext, openStepDetail, canReadModelContext, formatCost, locale } = useAgentInspectScope();\n const [showsFullResult, setShowsFullResult] = useState(false);\n const facts: string[] = [];\n if (step.modelCallFacts && showsModelCallFacts) {\n const { wireApi, forceToolChoice, providerCallMs, loopOverheadMs, cacheWriteTokens, hasStoredPayload } = step.modelCallFacts;\n const format = createTraceFormat(locale);\n if (wireApi) facts.push(t(\"wire API %name%\", { replacements: { name: wireApi } }));\n if (forceToolChoice) facts.push(t(\"tool choice %choice%\", { replacements: { choice: forceToolChoice } }));\n if (providerCallMs !== null) facts.push(t(\"provider %duration%\", { replacements: { duration: format.duration(providerCallMs) } }));\n if (loopOverheadMs !== null) facts.push(t(\"loop %duration%\", { replacements: { duration: format.duration(loopOverheadMs) } }));\n if (cacheWriteTokens !== null && cacheWriteTokens > 0) {\n facts.push(t(\"%count% tokens written to the cache\", { replacements: { count: formatAgentInspectCount(cacheWriteTokens, locale) } }));\n }\n facts.push(hasStoredPayload ? t(\"payload stored as sent\") : t(\"payload can only be rebuilt\"));\n }\n if (step.executionCostInUsd !== null) facts.push(t(\"execution booked %cost%\", { replacements: { cost: formatCost(step.executionCostInUsd) } }));\n if ((step.status ?? \"\").toUpperCase() === \"REFUSED\") {\n const reason = step.refusalReason ?? \"other\";\n facts.push(t(REFUSAL_REASON_LABELS[Object.hasOwn(REFUSAL_REASON_LABELS, reason) ? reason : \"other\"], { context: \"agent-step-refusal\" }));\n if (isDebug && step.storedStatus) facts.push(t(\"stored as %status%\", { replacements: { status: step.storedStatus } }));\n }\n if (step.wasRefusedByGate) facts.push(t(\"refused by a gate before it ran\"));\n if (step.wasRefusedAsDuplicate) facts.push(t(\"refused as an identical repeat\"));\n if (step.wasRefusedAsFinal) facts.push(t(\"refused for good: the same arguments are refused again\"));\n if (step.isCallToolWithoutToolName) facts.push(t(\"call_tool named no tool\"));\n if (step.wasRemovedForSecurity) facts.push(t(\"result removed: it carried instructions aimed at the assistant\"));\n if (step.signalSource) facts.push(t(\"source %source%\", { replacements: { source: step.signalSource } }));\n if (step.kind === \"DECISION\" && step.decision === null) {\n for (const fact of [step.eventKind, step.eventSite, step.eventSubject]) if (fact) facts.push(fact);\n }\n if (step.widget?.emittedBy) facts.push(t(\"written by %author%\", { replacements: { author: step.widget.emittedBy } }));\n if (step.widget && !step.widget.isValid) facts.push(t(\"not a readable widget\"));\n\n const messageId = step.messageId;\n const messageIndex = step.messageIndex;\n const isReplayable = isDebug && actions !== null && step.effect === \"READ\" && messageId !== null && step.kind === \"TOOL_CALL\";\n return (\n <div className=\"flex flex-col gap-2 pt-1 font-sans\" data-slot=\"agent-inspect-step-extras\">\n {facts.length > 0 ? <p className=\"text-xs text-muted-foreground\">{facts.join(\" · \")}</p> : null}\n {step.signalText ? <p className=\"whitespace-pre-wrap break-words rounded-lg bg-muted px-3 py-2 text-xs leading-5\">{step.signalText}</p> : null}\n {step.eventPayloadExcerpt && step.decision === null ? <CodeBlock code={step.eventPayloadExcerpt} language=\"json\" aria-label={t(\"Payload of the decision\")} /> : null}\n {step.compactionNode ? <CompactionNodeLine node={step.compactionNode} /> : null}\n {isDebug && step.widget?.payloadJson ? <CodeBlock code={step.widget.payloadJson} language=\"json\" aria-label={t(\"Fields of the widget\")} /> : null}\n {showsFullResult && messageId !== null ? <FullToolCallResult messageId={messageId} /> : null}\n <div className=\"flex flex-wrap items-center gap-1.5\">\n {showsDetailLink ? (\n <InspectActionButton icon={<PanelRightOpen aria-hidden />} onClick={() => openStepDetail(step.stepId)} testId=\"agent-inspect-open-step\">\n {t(\"Step details\")}\n </InspectActionButton>\n ) : null}\n {step.kind === \"MODEL_CALL\" && messageId !== null && canReadModelContext ? (\n <>\n <InspectActionButton icon={<Eye aria-hidden />} onClick={() => openModelContext(messageId, \"composition\")} testId=\"agent-inspect-open-context\">\n {t(\"What the model saw\")}\n </InspectActionButton>\n {isDebug ? (\n <InspectActionButton icon={<FileJson aria-hidden />} onClick={() => openModelContext(messageId, \"payload\")} testId=\"agent-inspect-open-payload\">\n {t(\"Sent payload\")}\n </InspectActionButton>\n ) : null}\n </>\n ) : null}\n {isDebug && step.isResultCut && messageId !== null && !showsFullResult ? (\n <InspectActionButton icon={<ScrollText aria-hidden />} onClick={() => setShowsFullResult(true)} testId=\"agent-inspect-load-result\">\n {t(\"Load the whole result (%count% characters)\", { replacements: { count: formatUiNumber(step.resultChars ?? 0) } })}\n </InspectActionButton>\n ) : null}\n {isReplayable ? (\n <InspectActionButton\n icon={<Play aria-hidden />}\n onClick={() => actions.replayToolCall(step)}\n disabled={!actions.writesAllowed}\n title={actions.writesAllowed ? undefined : t(\"Writes are locked in this environment.\")}\n testId=\"agent-inspect-replay\"\n >\n {t(\"Run the tool again\")}\n </InspectActionButton>\n ) : null}\n {isDebug && actions !== null && messageIndex !== null && !step.isTruncated ? (\n <InspectActionButton\n icon={<GitBranch aria-hidden />}\n onClick={() =>\n actions.openDrive({\n truncateFromIndex: messageIndex,\n truncateLabel: step.toolName ?? step.modelLabel ?? describeTraceModelName(step.modelCall?.modelName) ?? t(\"message %index%\", { replacements: { index: messageIndex } }),\n })\n }\n disabled={!actions.writesAllowed}\n title={actions.writesAllowed ? undefined : t(\"Writes are locked in this environment.\")}\n testId=\"agent-inspect-branch\"\n >\n {t(\"Branch from here\")}\n </InspectActionButton>\n ) : null}\n </div>\n </div>\n );\n};\n\n/**\n * The host bindings of a turn's steps: the scope's, the lazy trace of a sub-agent and the admin extras of a step. With\n * `opensStepDetails` every step opens, at least to the link to its detail (the steps of the conversation itself); a\n * sub-agent's steps, whose details live on its own page, open only where the admin view has something to add.\n */\nconst useStepHostBindings = (opensStepDetails: boolean): TraceHostBindings => {\n const { host, isDebug, actions } = useAgentInspectScope();\n return useMemo(\n (): TraceHostBindings => ({\n ...host,\n renderChildTrace: (childConversationId) => <ChildConversationTrace conversationId={childConversationId} />,\n renderStepExtras: (step: TraceStep) => {\n const inspectStep = step as AgentInspectStep;\n if (opensStepDetails) return <InspectStepExtras step={inspectStep} />;\n return hasStepExtras(inspectStep, isDebug, actions !== null) ? <InspectStepExtras step={inspectStep} showsDetailLink={false} /> : null;\n },\n }),\n [host, isDebug, actions, opensStepDetails],\n );\n};\n\n/** The steps of a turn with the lines the admin view words itself (a side decision, a signal). */\nconst useStepsWithLines = (steps: AgentInspectStep[]): AgentInspectStep[] => {\n const { t } = useTranslate();\n return useMemo(\n () =>\n steps.map((step) =>\n withInspectStepLine(\n step,\n (text, context) => t(text, { context }),\n (text, replacements) => t(text, { replacements }),\n ),\n ),\n [steps, t],\n );\n};\n\n/**\n * The trace of a sub-agent's conversation, inside the open row of its delegate call: its turns as nested step groups\n * with their figures. It is mounted (and so read) only while the row is open.\n */\nexport const ChildConversationTrace = ({ conversationId, className }: { conversationId: number; className?: string }) => {\n const { t } = useTranslate();\n const { api, level, isDebug, formatCost, locale } = useAgentInspectScope();\n const stepHost = useStepHostBindings(false);\n const query = api.useTraceQuery({ conversationId, detailLevel: level, limit: 20 });\n const trace = useMemo(() => (query.data ? mapAgentInspectTrace(query.data) : null), [query.data]);\n const format = useMemo(() => createTraceFormat(locale), [locale]);\n if (query.isError) {\n return (\n <p className=\"font-sans text-xs text-destructive\" data-testid=\"agent-child-trace-error\">\n {normalizeDddError(query.error, t(\"The trace of the sub-agent could not be loaded.\")).message}\n </p>\n );\n }\n if (trace === null) return <Skeleton className=\"h-16 w-full\" />;\n if (trace.turns.length === 0) return <p className=\"font-sans text-xs text-muted-foreground\">{t(\"The sub-agent has not taken a step yet.\")}</p>;\n return (\n <div className={cn(\"flex flex-col gap-2 font-sans\", className)} data-testid=\"agent-child-trace\" data-conversation-id={conversationId}>\n {trace.hasOlderTurns ? (\n <p className=\"text-xs text-muted-foreground\">{t(\"The newest %count% turns of the sub-agent; its conversation holds the earlier ones.\", { replacements: { count: trace.turns.length } })}</p>\n ) : null}\n {trace.turns.map((turn) => (\n <div key={turn.turnNumber} className=\"flex flex-col gap-1\">\n <div className=\"flex flex-wrap items-center gap-x-2 text-xs text-muted-foreground\">\n <span className=\"font-semibold text-foreground\">{t(\"Turn %number%\", { replacements: { number: turn.turnNumber } })}</span>\n {turn.isRunning ? <LiveDot label={t(\"A turn runs right now\")} /> : null}\n {turn.totals.durationMs !== null && !turn.isRunning ? <span>{format.duration(turn.totals.durationMs)}</span> : null}\n {isDebug && turn.totals.costInUsd !== null ? <span>{formatCost(turn.totals.costInUsd)}</span> : null}\n {isDebug && turn.totals.inputTokens !== null ? (\n <span>\n {t(\"%count% tokens\", {\n replacements: { count: formatAgentInspectCount((turn.totals.inputTokens ?? 0) + (turn.totals.outputTokens ?? 0), locale) },\n })}\n </span>\n ) : null}\n </div>\n <ToolStepGroup\n steps={turn.steps}\n viewMode={isDebug ? \"verbose\" : \"normal\"}\n durationMs={turn.totals.durationMs}\n isRunning={turn.isRunning}\n defaultOpen\n host={stepHost}\n isCompact\n />\n </div>\n ))}\n </div>\n );\n};\n\ninterface MessageRowProps {\n /** Who wrote the message. */\n author: string;\n isAgent?: boolean;\n /** Right of the author: a mark, an action. */\n aside?: ReactNode;\n children: ReactNode;\n}\n\n/** One message of a turn: the author in a narrow column, the text beside it. */\nconst MessageRow = ({ author, isAgent = false, aside, children }: MessageRowProps) => (\n <div className=\"grid grid-cols-1 gap-x-3 gap-y-1 sm:grid-cols-[132px_minmax(0,1fr)]\" data-slot=\"agent-inspect-message\" data-author={isAgent ? \"agent\" : \"other\"}>\n <div className=\"flex min-w-0 flex-wrap items-start gap-x-2 gap-y-1 pt-0.5 sm:flex-col sm:flex-nowrap sm:gap-1\">\n <span className={cn(\"max-w-full min-w-0 truncate text-xs font-bold\", isAgent ? \"text-brand-emphasis\" : \"text-muted-foreground\")} title={author}>\n {author}\n </span>\n {aside}\n </div>\n <div className=\"min-w-0 text-sm leading-6\">{children}</div>\n </div>\n);\n\ninterface MessageTextProps {\n /** The stored message the text belongs to; without it a cut text cannot be read whole. */\n messageId: number | null;\n /** The text as the trace carries it: whole, or its start when `isCut`. */\n text: string;\n /** Characters of the whole text. */\n textChars: number | null;\n isCut: boolean;\n /** Draws the text as markdown (a text of the assistant); a message of the owner stays plain. */\n asMarkdown: boolean;\n}\n\n/**\n * The text of one message of a turn. A text the trace cut shows its start with \"Show the whole text\", which reads the\n * whole text through the per-message read; a failed read keeps the start and says so.\n */\nconst MessageText = ({ messageId, text, textChars, isCut, asMarkdown }: MessageTextProps) => {\n const { t } = useTranslate();\n const { api, conversationId, renderMarkdown } = useAgentInspectScope();\n const [showsWholeText, setShowsWholeText] = useState(false);\n const wholeTextQuery = api.useMessageTextQuery({ conversationId, messageId: messageId ?? 0 }, { skip: !showsWholeText || messageId === null });\n const wholeMessage = useMemo(() => (wholeTextQuery.data ? mapAgentInspectMessageText(wholeTextQuery.data) : null), [wholeTextQuery.data]);\n // An answer shows its widgets by their titles below it, never as the JSON of their blocks.\n const shownText = asMarkdown ? splitAgentInspectWidgetFences(wholeMessage?.text || text).text : wholeMessage?.text || text;\n const isStillCut = isCut && (wholeMessage === null || wholeMessage.isTextCut);\n return (\n <div className=\"min-w-0\" data-slot=\"agent-inspect-message-text\" data-cut={isStillCut ? \"true\" : undefined}>\n {asMarkdown && renderMarkdown ? (\n <div className=\"min-w-0 [&_p]:my-0 [&_p+p]:mt-2\">{renderMarkdown(shownText)}</div>\n ) : (\n <p className=\"whitespace-pre-wrap break-words\">{shownText}</p>\n )}\n {isStillCut ? (\n <div className=\"mt-1.5 flex flex-wrap items-center gap-2 text-xs text-muted-foreground\">\n <Tag size=\"sm\">{t(\"shortened\", { context: \"agent-inspect\" })}</Tag>\n {messageId !== null && !showsWholeText ? (\n <InspectActionButton icon={<ScrollText aria-hidden />} onClick={() => setShowsWholeText(true)} testId=\"agent-inspect-load-message-text\">\n {textChars !== null && textChars > 0\n ? t(\"Show the whole text (%count% characters)\", { replacements: { count: formatUiNumber(textChars) } })\n : t(\"Show the whole text\")}\n </InspectActionButton>\n ) : null}\n {showsWholeText && wholeTextQuery.isError ? (\n <span className=\"text-destructive\">{normalizeDddError(wholeTextQuery.error, t(\"The whole text could not be loaded.\")).message}</span>\n ) : showsWholeText && wholeMessage === null ? (\n <Skeleton className=\"h-4 w-32\" />\n ) : null}\n </div>\n ) : null}\n </div>\n );\n};\n\ninterface TurnCardProps {\n turn: AgentInspectTurn;\n viewMode: TraceViewMode;\n /** The switches of the debug bar; null while Debug is off (nothing is left out). */\n debugSwitches: AgentInspectDebugSwitches | null;\n /** The skills loaded at the turn's newest model call (carried from an earlier call when the set did not change). */\n loadedSkills: TraceLoadedSkill[] | null;\n ownerLabel: string;\n /** The turn a link named: it is marked and scrolled into view once. */\n isFocused: boolean;\n /** The step a link named: it stays whatever the switches say. */\n focusStepId: string | null;\n}\n\n/** The step lines of a queued message: who wrote it and where it was taken up. */\nconst QueuedMessageRow = ({ message, ownerLabel, turnNumber }: { message: ConversationTraceMessage; ownerLabel: string; turnNumber: number }) => {\n const { t } = useTranslate();\n const { agentDisplayName } = useAgentInspectScope();\n const handledInTurnNumber = message.handledInTurnNumber ?? null;\n return (\n <MessageRow\n author={ownerLabel}\n aside={\n <span className=\"inline-flex items-center gap-1 text-[11px] text-muted-foreground\" data-testid=\"agent-inspect-queued-message\">\n <Clock className=\"size-3\" aria-hidden />\n {t(\"sent while %agentName% was working\", { replacements: { agentName: agentDisplayName } })}\n </span>\n }\n >\n <MessageText messageId={message.messageId} text={message.text} textChars={message.textChars} isCut={message.isTextCut} asMarkdown={false} />\n <p className=\"mt-1 text-xs text-muted-foreground\">\n {handledInTurnNumber === null\n ? t(\"Not taken up yet.\")\n : handledInTurnNumber === turnNumber\n ? t(\"Taken up in this turn.\")\n : t(\"Taken up in turn %number%.\", { replacements: { number: handledInTurnNumber } })}\n </p>\n </MessageRow>\n );\n};\n\n/** A widget under an answer as the admin view lists it. */\ninterface AnswerWidget {\n key: string;\n type: string | null;\n title: string | null;\n summary: string | null;\n isValid: boolean;\n /** The fields as JSON: at the debug level only. */\n payloadJson: string | null;\n isPayloadCut: boolean;\n}\n\n/**\n * The widgets of an answer: the trace's widgets of the message (title, type, the fields at the debug level), else the\n * blocks its text carries (their fields at the debug level too), else the types the trace names.\n */\nconst readAnswerWidgets = (answer: AgentInspectTurn[\"answerMessages\"][number], isDebug: boolean): AnswerWidget[] => {\n const traceWidgets = answer.widgets ?? [];\n if (traceWidgets.length > 0) {\n return traceWidgets.map((widget, position) => ({\n key: widget.stepId ?? `${widget.type ?? \"widget\"}-${position}`,\n type: widget.type,\n title: widget.title,\n summary: widget.summary,\n isValid: widget.isValid,\n payloadJson: isDebug && widget.payloadJson ? formatJsonForReading(widget.payloadJson) : null,\n isPayloadCut: widget.isPayloadCut,\n }));\n }\n const fences = splitAgentInspectWidgetFences(answer.text).fences;\n if (fences.length > 0) {\n return fences.map((fence, position) => ({\n key: `fence-${position}`,\n type: fence.type,\n title: fence.title,\n summary: null,\n isValid: fence.type !== null,\n payloadJson: isDebug ? formatJsonForReading(fence.json) : null,\n isPayloadCut: answer.isTextCut,\n }));\n }\n return answer.widgetTypes.map((widgetType, position) => ({\n key: `type-${position}`,\n type: widgetType,\n title: null,\n summary: null,\n isValid: true,\n payloadJson: null,\n isPayloadCut: false,\n }));\n};\n\n/** The widgets under an answer: each with its title and type, the fields behind a fold at the debug level. */\nconst AnswerWidgets = ({ widgets }: { widgets: readonly AnswerWidget[] }) => {\n const { t } = useTranslate();\n if (widgets.length === 0) return null;\n return (\n <div className=\"mt-2 flex flex-col gap-1.5\" data-testid=\"agent-inspect-answer-widgets\">\n {widgets.map((widget) => (\n <div key={widget.key} className=\"rounded-xl bg-muted/60 px-3 py-2 text-xs\">\n <div className=\"flex flex-wrap items-center gap-x-2 gap-y-1\">\n <LayoutPanelTop className=\"size-3.5 shrink-0 text-muted-foreground\" aria-hidden />\n <span className=\"font-semibold text-foreground\">{widget.title || widget.type || t(\"Widget\", { context: \"agent-turn-answer\" })}</span>\n {widget.title && widget.type ? <Tag size=\"sm\">{widget.type}</Tag> : null}\n {!widget.isValid ? <StatusBadge tone=\"warning\" label={t(\"not a readable widget\")} /> : null}\n {widget.summary ? <span className=\"min-w-0 truncate text-muted-foreground\">{widget.summary}</span> : null}\n </div>\n {widget.payloadJson ? (\n <Disclosure\n size=\"sm\"\n title={t(\"Fields of the widget\")}\n meta={widget.isPayloadCut ? <Tag size=\"sm\">{t(\"shortened\", { context: \"agent-inspect\" })}</Tag> : undefined}\n className=\"mt-1\"\n >\n <CodeBlock code={widget.payloadJson} language=\"json\" aria-label={t(\"Fields of the widget\")} />\n </Disclosure>\n ) : null}\n </div>\n ))}\n </div>\n );\n};\n\nconst TurnCard = ({ turn, viewMode, debugSwitches, loadedSkills, ownerLabel, isFocused, focusStepId }: TurnCardProps) => {\n const { t } = useTranslate();\n const { isDebug, locale, formatCost, frameAttributes, agentDisplayName, actions, openModelContext, openStepDetail, openEvalCase, canReadModelContext, linkComponent } =\n useAgentInspectScope();\n const stepHost = useStepHostBindings(true);\n const steps = useStepsWithLines(turn.steps);\n const format = useMemo(() => createTraceFormat(locale), [locale]);\n // With Debug on, the switches of the debug bar choose what the turn shows; without it nothing is left out.\n const shows = (name: keyof AgentInspectDebugSwitches): boolean => debugSwitches === null || debugSwitches[name];\n const totals = useMemo(() => (debugSwitches === null ? turn.totals : applyAgentInspectDebugSwitchesToTotals(turn.totals, debugSwitches)), [debugSwitches, turn.totals]);\n const cardRef = useRef<HTMLDivElement>(null);\n useEffect(() => {\n if (isFocused) cardRef.current?.scrollIntoView({ block: \"start\", behavior: \"smooth\" });\n }, [isFocused]);\n const startedAt = readTraceMoment(turn.startedAt);\n // The owner's stop has its own quiet mark; a turn of an older server names it only as its outcome.\n const isStoppedByOwner = turn.isStoppedByOwner || turn.totals.outcome === \"stoppedByOwner\";\n const outcome = !isStoppedByOwner && turn.totals.outcome !== null && Object.hasOwn(OUTCOME_LABELS, turn.totals.outcome) ? OUTCOME_LABELS[turn.totals.outcome] : null;\n const showsTimes = debugSwitches === null || debugSwitches.times;\n const timeline = useMemo(() => (isDebug && showsTimes ? buildTurnTimeline(turn) : null), [isDebug, showsTimes, turn]);\n const compactionSteps = shows(\"compaction\") ? turn.steps.filter((step) => step.kind === \"COMPACTION\" && step.compactionNode !== null) : [];\n const contextMessageId = [...turn.steps].reverse().find((step) => step.kind === \"MODEL_CALL\" && step.messageId !== null)?.messageId ?? turn.answerMessageIds[turn.answerMessageIds.length - 1] ?? null;\n // The turn is cut at its interim texts first, so a text stays where it was written when its model call is hidden.\n const segments = useMemo(\n () =>\n splitAgentInspectTurnAtInterimTexts(steps).map((segment) =>\n debugSwitches === null ? segment : { ...segment, steps: applyAgentInspectDebugSwitches(segment.steps, debugSwitches, focusStepId) },\n ),\n [steps, debugSwitches, focusStepId],\n );\n const answers = useMemo(() => readAgentInspectTurnAnswers(turn), [turn]);\n // An answer the trace names by id only (a read of a server that sends no texts) keeps its place as a note.\n const answerIdsWithoutText = turn.answerMessageIds.filter((messageId) => !turn.answerMessages.some((message) => message.messageId === messageId));\n\n const author =\n turn.initiatorAuthor === \"SIGNAL\"\n ? t(\"Signal\", { context: \"agent-turn-author\" })\n : turn.initiatorAuthor === \"ORCHESTRATOR\"\n ? t(\"Parent agent\", { context: \"agent-turn-author\" })\n : turn.initiatorAuthor === \"PLATFORM\"\n ? t(\"Platform\", { context: \"agent-turn-author\" })\n : ownerLabel;\n const initiatorMessage = turn.initiatorMessage;\n const initiatorSignalSource = turn.initiatorSignalSource ?? initiatorMessage?.signalSource ?? null;\n const counts = [\n turn.modelCallCount > 0 ? t(\"{count, plural, one {# model call} other {# model calls}}\", { count: turn.modelCallCount }) : null,\n turn.toolCallCount > 0 ? t(\"{count, plural, one {# tool call} other {# tool calls}}\", { count: turn.toolCallCount }) : null,\n turn.subAgentCount > 0 ? t(\"{count, plural, one {# sub-agent} other {# sub-agents}}\", { count: turn.subAgentCount }) : null,\n ].filter((count): count is string => count !== null);\n const tokens = (totals.inputTokens ?? 0) + (totals.outputTokens ?? 0);\n const modelLabel = useMemo(() => readAgentInspectModelLabel(totals.modelName, [turn]), [totals.modelName, turn]);\n const queuedMessages = turn.queuedMessages ?? [];\n // Running the turn again: the same message, from the position where the turn started (a branch).\n const initiatorText = turn.initiatorMessage?.text ?? null;\n const canRunAgain =\n actions !== null && turn.initiatorMessageIndex !== null && !turn.isTruncated && turn.initiatorAuthor !== \"SIGNAL\" && initiatorText !== null && !turn.initiatorMessage?.isTextCut;\n\n const contextButtonOf = (messageId: number | null) =>\n canReadModelContext && messageId !== null ? (\n <button\n type=\"button\"\n className=\"inline-flex items-center gap-1 text-[11px] font-semibold text-muted-foreground hover:text-foreground\"\n onClick={() => openModelContext(messageId, \"composition\")}\n data-testid=\"agent-inspect-answer-context\"\n title={t(\"What the model was sent when it wrote this message\")}\n >\n <Eye className=\"size-3\" aria-hidden />\n {t(\"Context\", { context: \"agent-inspect-action\" })}\n </button>\n ) : null;\n\n return (\n <Card\n ref={cardRef}\n className={cn(\"scroll-mt-24 gap-0 py-0\", turn.isTruncated && \"opacity-60\", isFocused && \"shadow-[inset_0_0_0_2px_var(--brand-emphasis)]\")}\n data-testid=\"agent-inspect-turn\"\n data-turn-number={turn.turnNumber}\n data-focused={isFocused ? \"true\" : undefined}\n >\n <CardContent className=\"flex flex-col gap-3 px-5 py-4\">\n <div className=\"flex flex-wrap items-center gap-x-2.5 gap-y-1 text-xs text-muted-foreground\">\n <span className=\"text-sm font-bold text-foreground\">{t(\"Turn %number%\", { replacements: { number: turn.turnNumber } })}</span>\n {turn.isRunning ? <LiveDot label={t(\"A turn runs right now\")} /> : null}\n {startedAt !== null ? <span className=\"tabular-nums\">{new Intl.DateTimeFormat(locale, { dateStyle: \"medium\", timeStyle: \"medium\" }).format(startedAt)}</span> : null}\n {isDebug && modelLabel ? (\n <span title={totals.modelName ?? undefined}>\n {modelLabel}\n {totals.effort ? ` · ${describeTraceEffort(totals.effort) ?? totals.effort}` : \"\"}\n </span>\n ) : null}\n {counts.length > 0 ? <span>{counts.join(\" · \")}</span> : null}\n {isStoppedByOwner ? (\n <span className=\"inline-flex items-center gap-1\" data-testid=\"agent-inspect-turn-stopped\">\n <CircleStop className=\"size-3.5\" aria-hidden />\n {t(\"stopped by the owner\")}\n </span>\n ) : null}\n {outcome ? <StatusBadge tone={outcome.tone} label={t(outcome.label, { context: OUTCOME_CONTEXT })} /> : null}\n {turn.isTruncated ? <Tag size=\"sm\">{t(\"truncated branch\")}</Tag> : null}\n <span className=\"ml-auto flex items-center gap-2 font-semibold text-foreground tabular-nums\">\n {totals.durationMs !== null && !turn.isRunning ? <span>{format.duration(totals.durationMs)}</span> : null}\n {isDebug && totals.costInUsd !== null ? <span>{formatCost(totals.costInUsd)}</span> : null}\n {isDebug && tokens > 0 ? <span>{t(\"%count% tokens\", { replacements: { count: formatAgentInspectCount(tokens, locale) } })}</span> : null}\n </span>\n </div>\n\n {timeline !== null && timeline.segments.length > 0 ? (\n <div className=\"relative h-3 overflow-hidden rounded-md bg-muted\" role=\"group\" aria-label={t(\"Where the time of the turn went\")} data-slot=\"agent-turn-timeline\">\n {timeline.segments.map((segment) => (\n <button\n key={segment.key}\n type=\"button\"\n className={cn(\"absolute inset-y-0.5 rounded-sm hover:brightness-90 focus-visible:outline-2 focus-visible:outline-ring\", TIMELINE_SEGMENT_CLASS_NAMES[segment.kind])}\n style={{ left: `${segment.leftPercent}%`, width: `${segment.widthPercent}%` }}\n title={`${segment.label} · ${format.duration(segment.durationMs)}`}\n aria-label={`${segment.label} · ${format.duration(segment.durationMs)}`}\n onClick={() => openStepDetail(segment.stepId)}\n />\n ))}\n </div>\n ) : null}\n\n {turn.turnMessageId !== null || initiatorMessage !== null || turn.initiatorTextExcerpt ? (\n <MessageRow author={author} aside={turn.initiatorAuthor === \"SIGNAL\" && initiatorSignalSource ? <Tag size=\"sm\">{initiatorSignalSource}</Tag> : undefined}>\n {initiatorMessage !== null ? (\n <MessageText\n messageId={initiatorMessage.messageId ?? turn.turnMessageId}\n text={initiatorMessage.text}\n textChars={initiatorMessage.textChars}\n isCut={initiatorMessage.isTextCut}\n asMarkdown={false}\n />\n ) : (\n // A server that sends no texts: the start of the message, as the trace always carried it.\n <p className=\"whitespace-pre-wrap break-words\">\n {turn.initiatorTextExcerpt ?? \"\"}\n {(turn.initiatorTextExcerpt ?? \"\").length >= 280 ? <span className=\"text-muted-foreground\"> …</span> : null}\n </p>\n )}\n {isDebug && ((actions !== null && turn.initiatorMessageIndex !== null && !turn.isTruncated) || (openEvalCase && turn.turnMessageId !== null)) ? (\n <div className=\"mt-1.5 flex flex-wrap items-center gap-1.5\">\n {actions !== null && turn.initiatorMessageIndex !== null && !turn.isTruncated ? (\n <InspectActionButton\n icon={<GitBranch aria-hidden />}\n onClick={() => actions.truncateFrom(turn.initiatorMessageIndex as number, t(\"turn %number%\", { replacements: { number: turn.turnNumber } }))}\n disabled={!actions.writesAllowed}\n title={actions.writesAllowed ? undefined : t(\"Writes are locked in this environment.\")}\n testId=\"agent-inspect-truncate-turn\"\n >\n {t(\"Truncate from this turn\")}\n </InspectActionButton>\n ) : null}\n {canRunAgain ? (\n <InspectActionButton\n icon={<RotateCcw aria-hidden />}\n onClick={() =>\n actions.openDrive({\n truncateFromIndex: turn.initiatorMessageIndex as number,\n truncateLabel: t(\"turn %number%\", { replacements: { number: turn.turnNumber } }),\n initialMessage: initiatorText ?? \"\",\n })\n }\n disabled={!actions.writesAllowed}\n title={\n actions.writesAllowed\n ? t(\"Truncates from this turn and sends its message again; the model and the run settings can be changed first.\")\n : t(\"Writes are locked in this environment.\")\n }\n testId=\"agent-inspect-retry-turn\"\n >\n {t(\"Run this turn again\")}\n </InspectActionButton>\n ) : null}\n {openEvalCase && turn.turnMessageId !== null ? (\n <InspectActionButton icon={<ClipboardCheck aria-hidden />} onClick={() => openEvalCase(turn.turnMessageId as number)} testId=\"agent-inspect-save-eval-case\">\n {t(\"Save as evaluation case\")}\n </InspectActionButton>\n ) : null}\n </div>\n ) : null}\n </MessageRow>\n ) : null}\n\n {segments.map((segment, position) => {\n const isLastSegment = position === segments.length - 1;\n const interimStep = segment.interimStep;\n return (\n <div key={segment.key} className=\"flex flex-col gap-3\" data-slot=\"agent-inspect-turn-segment\">\n {interimStep !== null ? (\n <MessageRow\n author={agentDisplayName}\n isAgent\n aside={\n <>\n <span className=\"text-[11px] text-muted-foreground\" title={t(\"The assistant wrote this text and went on with the steps below.\")}>\n {t(\"before the next steps\", { context: \"agent-turn-interim\" })}\n </span>\n {contextButtonOf(interimStep.messageId)}\n </>\n }\n >\n <MessageText\n messageId={interimStep.messageId}\n text={interimStep.assistantText ?? \"\"}\n textChars={interimStep.assistantTextChars}\n isCut={interimStep.isAssistantTextCut}\n asMarkdown\n />\n </MessageRow>\n ) : null}\n <div className=\"sm:pl-[144px]\">\n {isLastSegment && compactionSteps.length > 0 && viewMode !== \"verbose\" ? (\n <div className=\"mb-2 flex flex-col gap-1.5\">\n {compactionSteps.map((step) => (\n <CompactionNodeLine key={step.key} node={step.compactionNode as AgentInspectCompactionNode} />\n ))}\n </div>\n ) : null}\n <AgentTraceFrame frameAttributes={frameAttributes} data-testid=\"agent-inspect-turn-steps\">\n <ToolStepGroup\n steps={segment.steps}\n viewMode={viewMode}\n durationMs={isLastSegment ? totals.durationMs : null}\n isRunning={isLastSegment && turn.isRunning}\n host={stepHost}\n summary={\n isLastSegment && (turn.totals.commandCount > 0 || turn.totals.fileCount > 0) ? (\n <FileChangesSummary\n commandCount={turn.totals.commandCount}\n fileCount={turn.totals.fileCount}\n linesAdded={turn.totals.linesAdded}\n linesRemoved={turn.totals.linesRemoved}\n />\n ) : undefined\n }\n metaLine={\n isLastSegment ? (\n <TurnMetaLine\n {...totals}\n modelLabel={modelLabel}\n onOpenContext={contextMessageId !== null && canReadModelContext ? () => openModelContext(contextMessageId, \"composition\") : undefined}\n formatCost={formatCost}\n linkComponent={linkComponent}\n />\n ) : undefined\n }\n />\n {isLastSegment && debugSwitches !== null && debugSwitches.skills && loadedSkills !== null && loadedSkills.length > 0 ? (\n <LoadedSkillsDisclosure skills={loadedSkills} className=\"mt-2\" />\n ) : null}\n </AgentTraceFrame>\n </div>\n </div>\n );\n })}\n\n {queuedMessages.map((message, position) => (\n <QueuedMessageRow key={message.messageId ?? `queued-${position}`} message={message} ownerLabel={ownerLabel} turnNumber={turn.turnNumber} />\n ))}\n {answers.map((answer, position) => (\n <MessageRow\n key={answer.messageId ?? `answer-${position}`}\n author={agentDisplayName}\n isAgent\n aside={\n <>\n {answer.signalSource ? (\n <span className=\"text-[11px] text-muted-foreground\" title={answer.signalSource}>\n {t(\"written by the platform\", { context: \"agent-turn-answer\" })}\n </span>\n ) : null}\n {answer.isInterim ? <span className=\"text-[11px] text-muted-foreground\">{t(\"before the next steps\", { context: \"agent-turn-interim\" })}</span> : null}\n {contextButtonOf(answer.messageId)}\n </>\n }\n >\n <MessageText messageId={answer.messageId} text={answer.text} textChars={answer.textChars} isCut={answer.isTextCut} asMarkdown />\n {shows(\"widgets\") ? <AnswerWidgets widgets={readAnswerWidgets(answer, isDebug)} /> : null}\n </MessageRow>\n ))}\n {answerIdsWithoutText.map((messageId) => (\n <MessageRow key={messageId} author={agentDisplayName} isAgent aside={contextButtonOf(messageId)}>\n <p className=\"text-xs text-muted-foreground\">{t(\"Message #%id%: its text is not part of the trace read.\", { replacements: { id: messageId } })}</p>\n </MessageRow>\n ))}\n </CardContent>\n </Card>\n );\n};\n\ninterface OlderTurnsLoaderProps {\n window: AgentInspectTurnWindow;\n includeTruncated: boolean;\n onLoaded: (window: AgentInspectTurnWindow, page: AgentInspectTurnPage) => void;\n}\n\n/** Reads one page of older turns and hands it up with its paging facts; draws a placeholder while it loads. */\nconst OlderTurnsLoader = ({ window, includeTruncated, onLoaded }: OlderTurnsLoaderProps) => {\n const { t } = useTranslate();\n const { api, conversationId, level } = useAgentInspectScope();\n const query = api.useTraceQuery({ conversationId, detailLevel: level, fromTurnNumber: window.fromTurnNumber, limit: window.limit, includeTruncated });\n const { currentData } = query;\n // Handed up once per answer: an api that answers an equal object on every render (a static one) must not loop.\n const answerKey = useMemo(() => (currentData === undefined ? null : JSON.stringify(currentData)), [currentData]);\n const answer = useRef(currentData);\n answer.current = currentData;\n const { fromTurnNumber, limit } = window;\n useEffect(() => {\n if (answerKey === null || answer.current === undefined) return;\n const page = mapAgentInspectTrace(answer.current);\n onLoaded({ fromTurnNumber, limit }, { turns: page.turns, firstTurnNumber: page.firstTurnNumber, hasOlderTurns: page.hasOlderTurns });\n }, [answerKey, onLoaded, fromTurnNumber, limit]);\n if (query.isError) return <p className=\"text-xs text-destructive\">{normalizeDddError(query.error, t(\"The earlier turns could not be loaded.\")).message}</p>;\n return currentData === undefined ? <Skeleton className=\"h-24 w-full rounded-2xl\" /> : null;\n};\n\nexport interface ConversationTurnsProps {\n viewMode: TraceViewMode;\n /** The switches of the debug bar; null while Debug is off. */\n debugSwitches: AgentInspectDebugSwitches | null;\n /** Grows on every \"Refresh\" of the screen: the turns are read again. */\n refreshCount?: number;\n includeTruncated: boolean;\n /** How the owner of the conversation is named beside its messages. */\n ownerLabel: string;\n /** Refetches a running conversation's newest turn every n ms (0 = off). */\n livePollingIntervalMs: number;\n turnPageSize?: number;\n /** Told the merged trace whenever it changes (the model calls of the loaded turns, the run state). */\n onTraceChange?: (trace: AgentInspectTrace | null) => void;\n /**\n * The message a link named (the message that started a turn, or one of its answers): its turn is marked and\n * scrolled into view. While it is in none of the loaded turns, earlier pages are read (a few, then it stops).\n */\n focusMessageId?: number | null;\n /** The step a link named (`?step=`): while none of the loaded turns holds it, earlier pages are read like for a message. */\n focusStepId?: string | null;\n /** Told whether earlier pages are still being read to reach the linked message or step. */\n onFocusSearchChange?: (isSearching: boolean) => void;\n}\n\n/** How many earlier pages are read on their own to reach a linked message or step. */\nconst MAX_WINDOWS_TO_FOCUS = 5;\n\nconst isTurnOfMessage = (turn: AgentInspectTurn, messageId: number): boolean =>\n turn.turnMessageId === messageId ||\n turn.answerMessageIds.includes(messageId) ||\n turn.answerMessages.some((message) => message.messageId === messageId) ||\n turn.steps.some((step) => step.messageId === messageId);\n\n/**\n * The conversation turn by turn: the message that started a turn, its steps in the chosen view mode with the texts\n * the assistant wrote between them, and the answers — all from the trace read itself. It reads the page of the newest\n * turns first and earlier pages on \"Load earlier turns\" (the trace says whether older turns exist); while a turn runs\n * it follows the conversation with the read of the turns after the newest row it has seen and lays them over the\n * loaded ones (the live tail).\n */\nexport const ConversationTurns = ({\n viewMode,\n debugSwitches,\n refreshCount = 0,\n includeTruncated,\n ownerLabel,\n livePollingIntervalMs,\n turnPageSize = AGENT_INSPECT_TURN_PAGE_SIZE,\n onTraceChange,\n focusMessageId = null,\n focusStepId = null,\n onFocusSearchChange,\n}: ConversationTurnsProps) => {\n const { t } = useTranslate();\n const { api, conversationId, level, isDebug } = useAgentInspectScope();\n const [olderWindows, setOlderWindows] = useState<AgentInspectTurnWindow[]>([]);\n // The pages of older turns by what was read (level, truncated rows, window): a page of another level never mixes in.\n const [olderPageByKey, setOlderPageByKey] = useState<Readonly<Record<string, AgentInspectTurnPage>>>({});\n const pageKeyOf = useCallback((window: AgentInspectTurnWindow) => `${level}:${includeTruncated}:${window.fromTurnNumber}:${window.limit}`, [level, includeTruncated]);\n\n const newestQuery = api.useTraceQuery({ conversationId, detailLevel: level, limit: turnPageSize, includeTruncated });\n const newestTrace = useMemo(() => (newestQuery.data ? mapAgentInspectTrace(newestQuery.data) : null), [newestQuery.data]);\n // \"Refresh\" of the screen: the newest turns are read again (the older pages stay as read).\n const { refetch: refetchNewest } = newestQuery;\n useEffect(() => {\n if (refreshCount > 0) void refetchNewest();\n }, [refreshCount, refetchNewest]);\n const afterMessageIndex = newestTrace ? followUpPositionOfAgentInspectTrace(newestTrace) : null;\n // The follow-up read is asked for while a turn runs; its last answer says when the run has ended.\n const [isFollowing, setIsFollowing] = useState(false);\n const followUpQuery = api.useTraceQuery(\n { conversationId, detailLevel: level, afterMessageIndex: afterMessageIndex ?? 0, includeTruncated },\n { skip: afterMessageIndex === null || !(newestTrace?.isRunLive === true || isFollowing), pollingInterval: isFollowing ? livePollingIntervalMs : 0 },\n );\n const followUpTrace = useMemo(() => (followUpQuery.currentData ? mapAgentInspectTrace(followUpQuery.currentData) : null), [followUpQuery.currentData]);\n const isRunLive = followUpTrace ? followUpTrace.isRunLive : newestTrace?.isRunLive === true;\n useEffect(() => setIsFollowing(isRunLive && livePollingIntervalMs > 0), [isRunLive, livePollingIntervalMs]);\n\n const olderPages = useMemo(\n () => olderWindows.map((window) => olderPageByKey[pageKeyOf(window)]).filter((page): page is AgentInspectTurnPage => page !== undefined),\n [olderWindows, olderPageByKey, pageKeyOf],\n );\n const trace = useMemo(() => (newestTrace ? mergeAgentInspectTraces(newestTrace, olderPages, followUpTrace) : null), [newestTrace, olderPages, followUpTrace]);\n useEffect(() => onTraceChange?.(trace), [trace, onTraceChange]);\n\n const addOlderPage = useCallback(\n (window: AgentInspectTurnWindow, page: AgentInspectTurnPage) => setOlderPageByKey((pages) => ({ ...pages, [pageKeyOf(window)]: page })),\n [pageKeyOf],\n );\n const previousWindow = trace ? previousAgentInspectTurnWindow(trace, turnPageSize) : null;\n const isLoadingOlder = olderWindows.some((window) => olderPageByKey[pageKeyOf(window)] === undefined);\n\n const focusedTurnNumber = focusMessageId === null ? null : (trace?.turns.find((turn) => isTurnOfMessage(turn, focusMessageId))?.turnNumber ?? null);\n const isFocusMissing =\n trace !== null && ((focusMessageId !== null && focusedTurnNumber === null) || (focusStepId !== null && findAgentInspectStep(trace.turns, focusStepId) === null));\n const windowToFocus = isFocusMissing && !isLoadingOlder && olderWindows.length < MAX_WINDOWS_TO_FOCUS ? previousWindow : null;\n const windowToFocusFrom = windowToFocus?.fromTurnNumber ?? null;\n const windowToFocusLimit = windowToFocus?.limit ?? null;\n useEffect(() => {\n if (windowToFocusFrom === null || windowToFocusLimit === null) return;\n setOlderWindows((windows) =>\n windows.some((window) => window.fromTurnNumber === windowToFocusFrom) ? windows : [...windows, { fromTurnNumber: windowToFocusFrom, limit: windowToFocusLimit }],\n );\n }, [windowToFocusFrom, windowToFocusLimit]);\n const isSearchingFocus = isFocusMissing && (isLoadingOlder || windowToFocus !== null);\n useEffect(() => onFocusSearchChange?.(isSearchingFocus), [isSearchingFocus, onFocusSearchChange]);\n\n /** The skills loaded at each turn: those of its newest model call that names a set, else the set carried from before. */\n const loadedSkillsByTurnNumber = useMemo(() => {\n const skillsByTurnNumber = new Map<number, TraceLoadedSkill[] | null>();\n let carriedSkills: TraceLoadedSkill[] | null = null;\n for (const turn of trace?.turns ?? []) {\n for (const step of turn.steps) if (step.loadedSkills !== null && step.loadedSkills.length > 0) carriedSkills = step.loadedSkills;\n skillsByTurnNumber.set(turn.turnNumber, carriedSkills);\n }\n return skillsByTurnNumber;\n }, [trace]);\n\n if (newestQuery.isError) {\n return <StatusCallout tone=\"destructive\" title={t(\"The trace could not be loaded\")} description={normalizeDddError(newestQuery.error, t(\"The trace could not be loaded.\")).message} />;\n }\n if (trace === null) {\n return (\n <div className=\"space-y-3\" data-testid=\"agent-inspect-turns-loading\">\n <Skeleton className=\"h-32 w-full rounded-2xl\" />\n <Skeleton className=\"h-32 w-full rounded-2xl\" />\n </div>\n );\n }\n if (trace.turns.length === 0) return <StatusCallout tone=\"info\" title={t(\"No turn yet\")} description={t(\"The conversation holds no message that started a turn.\")} />;\n\n return (\n <div className=\"flex flex-col gap-3\" data-testid=\"agent-inspect-turns\" data-level={level} data-has-older-turns={trace.hasOlderTurns ? \"true\" : \"false\"}>\n {olderWindows.map((window) => (\n <OlderTurnsLoader key={pageKeyOf(window)} window={window} includeTruncated={includeTruncated} onLoaded={addOlderPage} />\n ))}\n {previousWindow !== null ? (\n <div className=\"flex items-center justify-center gap-3\">\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n data-testid=\"agent-inspect-load-earlier\"\n disabled={isLoadingOlder}\n onClick={() => setOlderWindows((windows) => [...windows, previousWindow])}\n >\n <ChevronsUp />\n {t(\"Load earlier turns\")}\n </Button>\n <span className=\"text-xs text-muted-foreground tabular-nums\">\n {t(\"Turns %from%–%to% of %total%\", {\n replacements: { from: trace.firstTurnNumber ?? trace.turns[0].turnNumber, to: trace.lastTurnNumber ?? trace.turns[trace.turns.length - 1].turnNumber, total: trace.totalTurnCount },\n })}\n </span>\n </div>\n ) : null}\n {trace.turns.map((turn) => (\n <TurnCard\n key={turn.turnNumber}\n turn={turn}\n viewMode={viewMode}\n debugSwitches={isDebug ? debugSwitches : null}\n loadedSkills={loadedSkillsByTurnNumber.get(turn.turnNumber) ?? null}\n ownerLabel={ownerLabel}\n isFocused={turn.turnNumber === focusedTurnNumber}\n focusStepId={focusStepId}\n />\n ))}\n {trace.isRunLive ? (\n <p className=\"flex items-center justify-center gap-2 py-1 text-xs text-muted-foreground\" data-testid=\"agent-inspect-live-tail\" aria-live=\"polite\">\n <LiveDot label={t(\"A turn runs right now\")} />\n {t(\"Live: new steps and answers appear here while the turn runs.\")}\n </p>\n ) : null}\n </div>\n );\n};\n","import { normalizeDddError } from \"@mgamadeus/ddd-web/contract\";\nimport { useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { StatusCallout } from \"@mgamadeus/ddd-admin-ui/page\";\nimport { Card, CardContent, Skeleton } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { useMemo } from \"react\";\nimport { readTraceMoment } from \"../../chat/trace/trace-format\";\nimport { wireElementsOf } from \"../wire/admin-wire\";\nimport { ContextCompositionPanel } from \"../context/ContextCompositionPanel\";\nimport { mapAgentInspectTrace } from \"./agent-inspect-mappers\";\nimport { CompactionNodeLine } from \"./ConversationTurns\";\nimport { useAgentInspectScope } from \"./inspect-scope\";\nimport { AGENT_INSPECT_TURN_PAGE_SIZE, newestAgentInspectModelCallMessageId } from \"./turn-paging\";\n\nexport interface ContextPanelProps {\n /** The page of turns the conversation tab reads first; the same number shares its answer. */\n turnPageSize?: number;\n}\n\n/**\n * The context of a conversation as it stands: what the newest model call was sent (the composition with the\n * compaction threshold) and the compaction nodes written so far, newest first.\n */\nexport const ContextPanel = ({ turnPageSize = AGENT_INSPECT_TURN_PAGE_SIZE }: ContextPanelProps) => {\n const { t } = useTranslate();\n const { api, conversationId, level, locale, renderMarkdown } = useAgentInspectScope();\n const traceQuery = api.useTraceQuery({ conversationId, detailLevel: level, limit: turnPageSize, includeTruncated: false });\n const nodesQuery = api.useCompactionNodesQuery({ conversationId });\n const newestMessageId = useMemo(() => (traceQuery.data ? newestAgentInspectModelCallMessageId(mapAgentInspectTrace(traceQuery.data).turns) : null), [traceQuery.data]);\n const nodes = useMemo(\n () =>\n wireElementsOf(nodesQuery.data?.compactionNodes).sort(\n (first, second) => (readTraceMoment(second.createdAt) ?? 0) - (readTraceMoment(first.createdAt) ?? 0) || (second.compactionNodeId ?? 0) - (first.compactionNodeId ?? 0),\n ),\n [nodesQuery.data],\n );\n\n return (\n <div className=\"grid grid-cols-1 gap-4 xl:grid-cols-[minmax(0,1.6fr)_minmax(0,1fr)]\" data-testid=\"agent-context-panel\">\n <Card className=\"gap-0 self-start py-0\">\n <CardContent className=\"flex flex-col gap-3 px-5 py-4\">\n <div>\n <h3 className=\"text-sm font-bold\">{t(\"Context of the newest model call\")}</h3>\n <p className=\"text-xs text-muted-foreground\">{t(\"What the model was sent the last time it was asked, part by part.\")}</p>\n </div>\n {traceQuery.isError ? (\n <StatusCallout size=\"compact\" tone=\"destructive\" title={normalizeDddError(traceQuery.error, t(\"The trace could not be loaded.\")).message} />\n ) : traceQuery.data === undefined ? (\n <Skeleton className=\"h-40 w-full\" />\n ) : newestMessageId === null ? (\n <p className=\"text-sm text-muted-foreground\">{t(\"The conversation holds no model call yet.\")}</p>\n ) : (\n <ContextCompositionPanel key={newestMessageId} api={api.context} conversationId={conversationId} messageId={newestMessageId} showCompactionThreshold renderMarkdown={renderMarkdown} />\n )}\n </CardContent>\n </Card>\n\n <Card className=\"gap-0 self-start py-0\">\n <CardContent className=\"flex flex-col gap-3 px-5 py-4\">\n <div>\n <h3 className=\"text-sm font-bold\">{t(\"Compaction nodes\")}</h3>\n <p className=\"text-xs text-muted-foreground\">{t(\"Summaries that stand for older messages in the context, newest first.\")}</p>\n </div>\n {nodesQuery.isError ? (\n <StatusCallout size=\"compact\" tone=\"destructive\" title={normalizeDddError(nodesQuery.error, t(\"The compaction nodes could not be loaded.\")).message} />\n ) : nodesQuery.data === undefined ? (\n <Skeleton className=\"h-24 w-full\" />\n ) : nodes.length === 0 ? (\n <p className=\"text-sm text-muted-foreground\">{t(\"Nothing was compacted: the model still reads every message.\")}</p>\n ) : (\n <ol className=\"flex flex-col gap-2\" data-testid=\"agent-context-compaction-nodes\">\n {nodes.map((node, position) => {\n const createdAt = readTraceMoment(node.createdAt);\n return (\n <li key={node.compactionNodeId ?? position} className=\"flex flex-col gap-1\">\n {createdAt !== null ? (\n <span className=\"text-xs text-muted-foreground tabular-nums\">{new Intl.DateTimeFormat(locale, { dateStyle: \"medium\", timeStyle: \"short\" }).format(createdAt)}</span>\n ) : null}\n <CompactionNodeLine node={node} />\n </li>\n );\n })}\n </ol>\n )}\n </CardContent>\n </Card>\n </div>\n );\n};\n","import { normalizeDddError } from \"@mgamadeus/ddd-web/contract\";\nimport { FormDialog } from \"@mgamadeus/ddd-admin-ui/form\";\nimport { formatUiNumber, m, useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { StatusBadge, Tag } from \"@mgamadeus/ddd-admin-ui/list\";\nimport { notify, useConfirm } from \"@mgamadeus/ddd-admin-ui/logic\";\nimport { type MoreActionItem, StatusCallout } from \"@mgamadeus/ddd-admin-ui/page\";\nimport { Button, Label, Select, SelectContent, SelectItem, SelectTrigger, SelectValue, Switch, Textarea } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { Ban, MessageSquarePlus, SlidersHorizontal, Square } from \"lucide-react\";\nimport { type ReactNode, useCallback, useEffect, useId, useMemo, useState } from \"react\";\nimport { createTraceFormat } from \"../../chat/trace/trace-format\";\nimport { CodeBlock } from \"../blocks/CodeBlock\";\nimport { DetailModal } from \"../blocks/DetailModal\";\nimport { Disclosure } from \"../blocks/Disclosure\";\nimport type { AgentInspectApi } from \"./agent-inspect-api\";\nimport type { AgentInspectRunSettingsOverride, AgentInspectStep, AgentInspectToolCallReplay } from \"./agent-inspect-types\";\nimport type { AgentInspectActions } from \"./inspect-scope\";\n\n/** The model the conversation is configured with (no override sent). */\nconst CONFIGURED_MODEL = \"\";\n/** A run setting the dialog leaves as it is. */\nconst UNCHANGED = \"unchanged\";\n\nconst SETTING_CONTEXT = \"agent-run-setting\";\n\n/** The choices of the decision model's reasoning effort. */\nconst DECISION_EFFORT_LABELS: Readonly<Record<string, string>> = {\n inherit: m(\"as the agent's own\", { context: \"agent-run-setting\" }),\n off: m(\"off\", { context: \"agent-run-setting\" }),\n low: m(\"low\", { context: \"agent-run-setting\" }),\n medium: m(\"medium\", { context: \"agent-run-setting\" }),\n high: m(\"high\", { context: \"agent-run-setting\" }),\n};\n\n/** The kill switch of the decision model, as a choice of the run settings dialog. */\nconst DECISION_MODEL_SWITCH_LABELS: Readonly<Record<string, string>> = {\n switchedOff: m(\"off: the rules decide alone\", { context: \"agent-run-setting\" }),\n asConfigured: m(\"on, as configured\", { context: \"agent-run-setting\" }),\n};\n\n/** The choices of the wire API the agent's model calls go over. */\nconst WIRE_API_LABELS: Readonly<Record<string, string>> = {\n inherit: m(\"as the model's own\", { context: \"agent-run-setting\" }),\n chatCompletions: m(\"chat completions\", { context: \"agent-run-setting\" }),\n responses: m(\"responses\", { context: \"agent-run-setting\" }),\n messages: m(\"messages\", { context: \"agent-run-setting\" }),\n};\n\ninterface DriveRequest {\n truncateFromIndex?: number;\n truncateLabel?: string;\n /** The message the dialog opens with (running a turn again starts from the message that started it). */\n initialMessage?: string;\n}\n\ninterface DriveDialogProps {\n api: AgentInspectApi;\n conversationId: number;\n request: DriveRequest | null;\n onClose: () => void;\n writesAllowed: boolean;\n selectableModelNames: readonly string[];\n configuredModelName: string | null;\n}\n\n/** The dialog that writes a message into the conversation as an admin and runs the turn. */\nconst DriveDialog = ({ api, conversationId, request, onClose, writesAllowed, selectableModelNames, configuredModelName }: DriveDialogProps) => {\n const { t } = useTranslate();\n const confirm = useConfirm();\n const [drive, driveState] = api.useDriveMutation();\n const [message, setMessage] = useState(\"\");\n const [modelName, setModelName] = useState(CONFIGURED_MODEL);\n const [budgetBypass, setBudgetBypass] = useState(false);\n const [decisionModelOff, setDecisionModelOff] = useState(false);\n const [decisionEffort, setDecisionEffort] = useState(UNCHANGED);\n const [wireApi, setWireApi] = useState(UNCHANGED);\n const messageId = useId();\n const modelId = useId();\n const budgetId = useId();\n const decisionOffId = useId();\n const decisionEffortId = useId();\n const wireApiId = useId();\n const isBranch = request?.truncateFromIndex !== undefined;\n const initialMessage = request?.initialMessage;\n useEffect(() => {\n if (initialMessage !== undefined) setMessage(initialMessage);\n }, [initialMessage]);\n\n const reset = () => {\n setMessage(\"\");\n setModelName(CONFIGURED_MODEL);\n setBudgetBypass(false);\n setDecisionModelOff(false);\n setDecisionEffort(UNCHANGED);\n setWireApi(UNCHANGED);\n };\n const close = () => {\n reset();\n onClose();\n };\n\n const submit = async () => {\n const text = message.trim();\n if (text === \"\" || request === null) return;\n const runSettingsOverride: AgentInspectRunSettingsOverride = {};\n if (decisionModelOff) runSettingsOverride.decisionModelOff = true;\n if (decisionEffort !== UNCHANGED) runSettingsOverride.decisionModelReasoningEffort = decisionEffort;\n if (wireApi !== UNCHANGED) runSettingsOverride.agentWireApi = wireApi;\n const effects = [\n isBranch\n ? t(\"Every message from position %index% on leaves the context first (they stay stored, marked as truncated).\", { replacements: { index: request.truncateFromIndex ?? 0 } })\n : null,\n t(\"Your message is written into conversation #%id% as the platform, and the agent answers it as the account of the conversation.\", { replacements: { id: conversationId } }),\n modelName !== CONFIGURED_MODEL ? t(\"The turn runs on %model%.\", { replacements: { model: modelName } }) : null,\n budgetBypass ? t(\"The budget of the account is not checked for this turn.\") : null,\n Object.keys(runSettingsOverride).length > 0 ? t(\"The run settings you changed stay on the conversation.\") : null,\n ].filter((effect): effect is string => effect !== null);\n const isConfirmed = await confirm({\n title: isBranch ? t(\"Branch the conversation and continue as admin?\") : t(\"Continue the conversation as admin?\"),\n description: (\n <ul className=\"list-disc space-y-1 pl-4 text-left\">\n {effects.map((effect) => (\n <li key={effect}>{effect}</li>\n ))}\n </ul>\n ),\n confirmLabel: t(\"Write and run\"),\n confirmVariant: isBranch ? \"destructive\" : \"default\",\n });\n if (!isConfirmed) return;\n try {\n await drive({\n conversationId,\n message: text,\n ...(modelName !== CONFIGURED_MODEL ? { aiModelName: modelName } : {}),\n ...(budgetBypass ? { budgetBypass: true } : {}),\n ...(request.truncateFromIndex !== undefined ? { truncateFromIndex: request.truncateFromIndex } : {}),\n ...(Object.keys(runSettingsOverride).length > 0 ? { runSettingsOverride } : {}),\n }).unwrap();\n notify.success(t(\"The message was written; the turn runs.\"));\n close();\n } catch (error) {\n notify.error(normalizeDddError(error, t(\"The message could not be written.\")).message);\n }\n };\n\n const settingSelect = (id: string, label: string, value: string, onChange: (value: string) => void, labels: Readonly<Record<string, string>>) => (\n <div className=\"grid gap-1.5\">\n <Label htmlFor={id}>{label}</Label>\n <Select value={value} onValueChange={onChange}>\n <SelectTrigger id={id} className=\"w-full\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n <SelectItem value={UNCHANGED}>{t(\"leave as it is\", { context: SETTING_CONTEXT })}</SelectItem>\n {Object.entries(labels).map(([choice, choiceLabel]) => (\n <SelectItem key={choice} value={choice}>\n {t(choiceLabel, { context: SETTING_CONTEXT })}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n );\n\n return (\n <FormDialog\n open={request !== null}\n onOpenChange={(open) => !open && close()}\n title={isBranch ? t(\"Branch from here and continue as admin\") : t(\"Continue as admin\")}\n description={\n isBranch\n ? t(\"Truncates conversation #%id% from %label% (position %index%) and writes your message in its place.\", {\n replacements: { id: conversationId, label: request?.truncateLabel ?? \"\", index: request?.truncateFromIndex ?? 0 },\n })\n : t(\"Writes a message into conversation #%id% and runs the agent's turn.\", { replacements: { id: conversationId } })\n }\n submitLabel={t(\"Write and run\")}\n pendingLabel={t(\"Writing…\")}\n isPending={driveState.isLoading}\n isDirty={message.trim() !== \"\"}\n submitDisabled={!writesAllowed || message.trim() === \"\"}\n submitVariant={isBranch ? \"destructive\" : \"default\"}\n submitOnEnter={false}\n className=\"sm:max-w-xl\"\n data-testid=\"agent-inspect-drive-dialog\"\n onSubmit={() => submit()}\n >\n <div className=\"grid gap-4\">\n {!writesAllowed ? <StatusCallout size=\"compact\" tone=\"info\" title={t(\"Writes are locked in this environment.\")} /> : null}\n <div className=\"grid gap-1.5\">\n <Label htmlFor={messageId}>{t(\"Message\", { context: \"agent-drive\" })}</Label>\n <Textarea id={messageId} value={message} onChange={(event) => setMessage(event.target.value)} rows={5} required placeholder={t(\"What the agent should do next\")} />\n </div>\n <div className=\"grid gap-1.5\">\n <Label htmlFor={modelId}>{t(\"Model\", { context: \"agent-drive\" })}</Label>\n <Select value={modelName === CONFIGURED_MODEL ? UNCHANGED : modelName} onValueChange={(value) => setModelName(value === UNCHANGED ? CONFIGURED_MODEL : value)}>\n <SelectTrigger id={modelId} className=\"w-full\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n <SelectItem value={UNCHANGED}>\n {configuredModelName ? t(\"as configured (%model%)\", { replacements: { model: configuredModelName } }) : t(\"as configured\", { context: \"agent-drive\" })}\n </SelectItem>\n {selectableModelNames.map((selectableModelName) => (\n <SelectItem key={selectableModelName} value={selectableModelName}>\n {selectableModelName}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n <div className=\"flex items-start gap-3\">\n <Switch id={budgetId} checked={budgetBypass} onCheckedChange={setBudgetBypass} />\n <div className=\"grid gap-0.5\">\n <Label htmlFor={budgetId}>{t(\"Lift the budget for this turn\")}</Label>\n <span className=\"text-xs text-muted-foreground\">{t(\"The turn runs even when the account's budget is used up.\")}</span>\n </div>\n </div>\n <Disclosure title={t(\"Run settings\")} meta={<Tag size=\"sm\">{t(\"stay on the conversation\")}</Tag>}>\n <div className=\"grid gap-3 pt-2\">\n <div className=\"flex items-start gap-3\">\n <Switch id={decisionOffId} checked={decisionModelOff} onCheckedChange={setDecisionModelOff} />\n <div className=\"grid gap-0.5\">\n <Label htmlFor={decisionOffId}>{t(\"Decision model off\")}</Label>\n <span className=\"text-xs text-muted-foreground\">{t(\"No side decision is asked of a second model; the rules decide alone.\")}</span>\n </div>\n </div>\n {settingSelect(decisionEffortId, t(\"Reasoning effort of the decision model\"), decisionEffort, setDecisionEffort, DECISION_EFFORT_LABELS)}\n {settingSelect(wireApiId, t(\"Wire API of the agent's model calls\"), wireApi, setWireApi, WIRE_API_LABELS)}\n </div>\n </Disclosure>\n </div>\n </FormDialog>\n );\n};\n\ninterface RunSettingsDialogProps {\n api: AgentInspectApi;\n conversationId: number;\n open: boolean;\n onClose: () => void;\n writesAllowed: boolean;\n}\n\n/** The dialog that sets run settings on the conversation alone, without writing a message (they count from its next turn). */\nconst RunSettingsDialog = ({ api, conversationId, open, onClose, writesAllowed }: RunSettingsDialogProps) => {\n const { t } = useTranslate();\n const [saveRunSettings, saveState] = api.useRunSettingsMutation();\n const [decisionModelOff, setDecisionModelOff] = useState(UNCHANGED);\n const [decisionEffort, setDecisionEffort] = useState(UNCHANGED);\n const [wireApi, setWireApi] = useState(UNCHANGED);\n const decisionOffId = useId();\n const decisionEffortId = useId();\n const wireApiId = useId();\n const runSettingsOverride: AgentInspectRunSettingsOverride = {};\n if (decisionModelOff !== UNCHANGED) runSettingsOverride.decisionModelOff = decisionModelOff === \"switchedOff\";\n if (decisionEffort !== UNCHANGED) runSettingsOverride.decisionModelReasoningEffort = decisionEffort;\n if (wireApi !== UNCHANGED) runSettingsOverride.agentWireApi = wireApi;\n const hasChange = Object.keys(runSettingsOverride).length > 0;\n const close = () => {\n setDecisionModelOff(UNCHANGED);\n setDecisionEffort(UNCHANGED);\n setWireApi(UNCHANGED);\n onClose();\n };\n const submit = async () => {\n if (!hasChange) return;\n try {\n await saveRunSettings({ conversationId, runSettingsOverride }).unwrap();\n notify.success(t(\"The run settings were saved; they count from the next turn.\"));\n close();\n } catch (error) {\n notify.error(normalizeDddError(error, t(\"The run settings could not be saved.\")).message);\n }\n };\n const select = (id: string, label: string, value: string, onChange: (value: string) => void, labels: Readonly<Record<string, string>>) => (\n <div className=\"grid gap-1.5\">\n <Label htmlFor={id}>{label}</Label>\n <Select value={value} onValueChange={onChange}>\n <SelectTrigger id={id} className=\"w-full\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n <SelectItem value={UNCHANGED}>{t(\"leave as it is\", { context: SETTING_CONTEXT })}</SelectItem>\n {Object.entries(labels).map(([choice, choiceLabel]) => (\n <SelectItem key={choice} value={choice}>\n {t(choiceLabel, { context: SETTING_CONTEXT })}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n );\n return (\n <FormDialog\n open={open}\n onOpenChange={(isOpen) => !isOpen && close()}\n title={t(\"Run settings of the conversation\")}\n description={t(\"Sets run settings on conversation #%id% without writing a message. They count from its next turn and stay on the conversation.\", {\n replacements: { id: conversationId },\n })}\n submitLabel={t(\"Save the run settings\")}\n pendingLabel={t(\"Saving…\")}\n isPending={saveState.isLoading}\n isDirty={hasChange}\n submitDisabled={!writesAllowed || !hasChange}\n className=\"sm:max-w-lg\"\n data-testid=\"agent-inspect-run-settings-dialog\"\n onSubmit={() => submit()}\n >\n <div className=\"grid gap-3\">\n {!writesAllowed ? <StatusCallout size=\"compact\" tone=\"info\" title={t(\"Writes are locked in this environment.\")} /> : null}\n {select(decisionOffId, t(\"Decision model off\"), decisionModelOff, setDecisionModelOff, DECISION_MODEL_SWITCH_LABELS)}\n {select(decisionEffortId, t(\"Reasoning effort of the decision model\"), decisionEffort, setDecisionEffort, DECISION_EFFORT_LABELS)}\n {select(wireApiId, t(\"Wire API of the agent's model calls\"), wireApi, setWireApi, WIRE_API_LABELS)}\n </div>\n </FormDialog>\n );\n};\n\n/** The answer of a tool call run again, beside what was stored. */\nconst ReplayResultModal = ({ replay, onClose }: { replay: AgentInspectToolCallReplay | null; onClose: () => void }) => {\n const { t } = useTranslate();\n const format = useMemo(() => createTraceFormat(), []);\n return (\n <DetailModal\n open={replay !== null}\n onOpenChange={(open) => !open && onClose()}\n title={t(\"Answer of %tool% now\", { replacements: { tool: replay?.toolName ?? t(\"the tool\") } })}\n description={t(\"The tool ran again with the stored arguments. Nothing of this run is stored.\")}\n copyText={replay?.result ?? \"\"}\n showViewControl={false}\n >\n {replay !== null ? (\n <div className=\"flex flex-col gap-3\" data-testid=\"agent-inspect-replay-result\">\n <div className=\"flex flex-wrap items-center gap-1.5\">\n {replay.isError ? <StatusBadge tone=\"danger\" label={t(\"the tool answered an error\")} /> : null}\n {replay.isSameAsStoredResult === true ? <StatusBadge tone=\"success\" label={t(\"same as the stored result\")} /> : null}\n {replay.isSameAsStoredResult === false ? <StatusBadge tone=\"warning\" label={t(\"differs from the stored result\")} /> : null}\n {replay.durationMs != null ? <Tag>{format.duration(replay.durationMs)}</Tag> : null}\n {replay.resultChars != null ? <Tag>{t(\"%count% characters\", { replacements: { count: formatUiNumber(replay.resultChars) } })}</Tag> : null}\n {replay.isResultCut ? <Tag>{t(\"shortened\", { context: \"agent-inspect\" })}</Tag> : null}\n </div>\n {replay.argumentsJson ? <CodeBlock code={replay.argumentsJson} language=\"json\" caption={t(\"Arguments\", { context: \"agent-inspect\" })} /> : null}\n <CodeBlock code={replay.result ?? \"\"} caption={t(\"Result\", { context: \"agent-inspect\" })} />\n </div>\n ) : null}\n </DetailModal>\n );\n};\n\nexport interface UseConversationActionsOptions {\n api: AgentInspectApi;\n conversationId: number;\n /** False: no action is offered at all (the reader may not drive conversations). */\n isDriveAllowed: boolean;\n /** False: the controls show, disabled. */\n writesAllowed: boolean;\n selectableModelNames: readonly string[];\n configuredModelName: string | null;\n /** A turn runs (or is queued, or waits for sub-agents): stop and cancel are offered. */\n isRunActive: boolean;\n}\n\nexport interface ConversationActionsResult {\n /** Null when the reader may not drive conversations. */\n actions: AgentInspectActions | null;\n /** The buttons of the page header while a turn runs: stop, cancel. */\n headerActions: ReactNode;\n /** The entries of the header's \"…\" menu: continue as admin, run settings. Empty when the reader may not drive. */\n menuItems: MoreActionItem[];\n /** The dialogs of the actions; render once. */\n dialogs: ReactNode;\n}\n\n/**\n * The admin actions on one conversation: continue as admin (optionally from an earlier position), truncate, run a\n * reading tool call again, stop the running turn, cancel the run. Every action names its effect in a confirmation\n * before it runs; the drive mutations refresh the conversation's reads through their cache tags.\n */\nexport const useConversationActions = ({\n api,\n conversationId,\n isDriveAllowed,\n writesAllowed,\n selectableModelNames,\n configuredModelName,\n isRunActive,\n}: UseConversationActionsOptions): ConversationActionsResult => {\n const { t } = useTranslate();\n const confirm = useConfirm();\n const [truncate] = api.useTruncateMutation();\n const [replayToolCall] = api.useReplayToolCallMutation();\n const [cancelRun, cancelState] = api.useCancelRunMutation();\n const [stopRun, stopState] = api.useStopRunMutation();\n const [driveRequest, setDriveRequest] = useState<DriveRequest | null>(null);\n const [replay, setReplay] = useState<AgentInspectToolCallReplay | null>(null);\n const [isRunSettingsOpen, setIsRunSettingsOpen] = useState(false);\n\n const truncateFrom = useCallback(\n async (fromIndex: number, label: string) => {\n const isConfirmed = await confirm({\n title: t(\"Truncate from %label%?\", { replacements: { label } }),\n description: t(\n \"Every message of conversation #%id% from position %index% on, and the sub-agents they started, leaves the context. The rows stay stored and show with \\\"Truncated rows\\\"; the model no longer reads them.\",\n { replacements: { id: conversationId, index: fromIndex } },\n ),\n confirmLabel: t(\"Truncate\"),\n confirmVariant: \"destructive\",\n });\n if (!isConfirmed) return;\n try {\n const answer = await truncate({ conversationId, fromIndex }).unwrap();\n notify.success(t(\"{count, plural, one {# message truncated} other {# messages truncated}}\", { count: answer.truncatedMessageCount ?? 0 }));\n } catch (error) {\n notify.error(normalizeDddError(error, t(\"The conversation could not be truncated.\")).message);\n }\n },\n [confirm, conversationId, t, truncate],\n );\n\n const replayStep = useCallback(\n async (step: AgentInspectStep) => {\n if (step.messageId === null) return;\n const isConfirmed = await confirm({\n title: t(\"Run %tool% again?\", { replacements: { tool: step.toolName ?? t(\"the tool\") } }),\n description: t(\"The tool runs now with the stored arguments, as the account of the conversation. It only reads; its answer is shown and not stored.\"),\n confirmLabel: t(\"Run again\"),\n });\n if (!isConfirmed) return;\n const pendingToast = notify.loading(t(\"The tool runs…\"));\n try {\n const answer = await replayToolCall({ conversationId, messageId: step.messageId }).unwrap();\n setReplay(answer.replay ?? {});\n } catch (error) {\n notify.error(normalizeDddError(error, t(\"The tool call could not be run again.\")).message);\n } finally {\n notify.dismiss(pendingToast);\n }\n },\n [confirm, conversationId, replayToolCall, t],\n );\n\n const stop = async () => {\n const isConfirmed = await confirm({\n title: t(\"Stop the running turn?\"),\n description: t(\"The turn of conversation #%id% ends at its next step. The conversation stays open and can be continued.\", { replacements: { id: conversationId } }),\n confirmLabel: t(\"Stop the turn\"),\n confirmVariant: \"destructive\",\n });\n if (!isConfirmed) return;\n try {\n await stopRun({ conversationId }).unwrap();\n notify.success(t(\"The turn is asked to stop.\"));\n } catch (error) {\n notify.error(normalizeDddError(error, t(\"The turn could not be stopped.\")).message);\n }\n };\n\n const cancel = async () => {\n const isConfirmed = await confirm({\n title: t(\"Cancel the run?\"),\n description: t(\"The live run of conversation #%id% and the runs of its sub-agents are cancelled, and the conversation is closed.\", { replacements: { id: conversationId } }),\n confirmLabel: t(\"Cancel the run\"),\n cancelLabel: t(\"Keep it running\"),\n confirmVariant: \"destructive\",\n });\n if (!isConfirmed) return;\n try {\n await cancelRun({ conversationId }).unwrap();\n notify.success(t(\"The run was cancelled.\"));\n } catch (error) {\n notify.error(normalizeDddError(error, t(\"The run could not be cancelled.\")).message);\n }\n };\n\n const actions = useMemo(\n (): AgentInspectActions | null =>\n isDriveAllowed\n ? {\n writesAllowed,\n openDrive: (options) =>\n setDriveRequest({ truncateFromIndex: options?.truncateFromIndex, truncateLabel: options?.truncateLabel, initialMessage: options?.initialMessage }),\n truncateFrom: (fromIndex, label) => void truncateFrom(fromIndex, label),\n replayToolCall: (step) => void replayStep(step),\n }\n : null,\n [isDriveAllowed, writesAllowed, truncateFrom, replayStep],\n );\n\n if (!isDriveAllowed) return { actions: null, headerActions: null, menuItems: [], dialogs: null };\n const lockedTitle = writesAllowed ? undefined : t(\"Writes are locked in this environment.\");\n return {\n actions,\n headerActions: isRunActive ? (\n <>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" disabled={!writesAllowed || stopState.isLoading} title={lockedTitle} onClick={() => void stop()} data-testid=\"agent-inspect-stop\">\n <Square />\n {t(\"Stop turn\")}\n </Button>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" disabled={!writesAllowed || cancelState.isLoading} title={lockedTitle} onClick={() => void cancel()} data-testid=\"agent-inspect-cancel\">\n <Ban />\n {t(\"Cancel run\")}\n </Button>\n </>\n ) : null,\n menuItems: [\n { id: \"drive\", label: t(\"Continue as admin\"), icon: <MessageSquarePlus />, onSelect: () => setDriveRequest({}), disabled: !writesAllowed },\n { id: \"runSettings\", label: t(\"Run settings…\"), icon: <SlidersHorizontal />, onSelect: () => setIsRunSettingsOpen(true), disabled: !writesAllowed },\n ],\n dialogs: (\n <>\n <DriveDialog\n api={api}\n conversationId={conversationId}\n request={driveRequest}\n onClose={() => setDriveRequest(null)}\n writesAllowed={writesAllowed}\n selectableModelNames={selectableModelNames}\n configuredModelName={configuredModelName}\n />\n <RunSettingsDialog api={api} conversationId={conversationId} open={isRunSettingsOpen} onClose={() => setIsRunSettingsOpen(false)} writesAllowed={writesAllowed} />\n <ReplayResultModal replay={replay} onClose={() => setReplay(null)} />\n </>\n ),\n };\n};\n","import { useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { Switch } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { Bug, Code } from \"lucide-react\";\nimport type { ReactNode } from \"react\";\nimport {\n AGENT_INSPECT_DEBUG_SWITCH_CONTEXT,\n AGENT_INSPECT_DEBUG_SWITCH_LABELS,\n AGENT_INSPECT_DEBUG_SWITCH_NAMES,\n type AgentInspectDebugSwitchName,\n type AgentInspectDebugSwitches,\n} from \"./debug-switches\";\n\nexport interface DebugSwitchBarProps {\n switches: AgentInspectDebugSwitches;\n onSwitchChange: (name: AgentInspectDebugSwitchName, isOn: boolean) => void;\n /** Opens what the newest model call was sent; null hides the action (no model call loaded yet). */\n onViewRequest: (() => void) | null;\n /** More switches after the ten (the truncated rows). */\n extraSwitches?: ReactNode;\n}\n\nconst SWITCH_CLASS_NAME = \"data-[state=checked]:bg-brand data-[state=unchecked]:bg-background/25 dark:data-[state=unchecked]:bg-foreground/20\";\n\n/** One labelled switch of the debug bar. */\nexport const DebugBarSwitch = ({ label, checked, onCheckedChange, testId }: { label: string; checked: boolean; onCheckedChange: (checked: boolean) => void; testId?: string }) => (\n <label className=\"inline-flex cursor-pointer items-center gap-2 text-[13px] whitespace-nowrap text-background/85 dark:text-foreground/85\">\n <Switch size=\"sm\" checked={checked} onCheckedChange={onCheckedChange} className={SWITCH_CLASS_NAME} data-testid={testId} />\n {label}\n </label>\n);\n\n/**\n * The dark bar of the debug view: the ten switches of what every turn shows (skills, tool calls, arguments and results,\n * model and effort, tokens and costs, times, compaction, sub-agents, widgets, signals and decisions) and \"View request\"\n * (what the newest model call was sent). The state is the caller's.\n */\nexport const DebugSwitchBar = ({ switches, onSwitchChange, onViewRequest, extraSwitches }: DebugSwitchBarProps) => {\n const { t } = useTranslate();\n return (\n <div\n className=\"flex flex-wrap items-center gap-x-[18px] gap-y-2.5 rounded-[14px] bg-foreground px-4 py-2.5 text-background dark:bg-muted dark:text-foreground\"\n role=\"group\"\n aria-label={t(\"What the debug view shows\")}\n data-testid=\"agent-inspect-debug-bar\"\n >\n <span className=\"inline-flex items-center gap-1.5 text-[13px] font-bold text-brand\">\n <Bug className=\"size-3.5\" aria-hidden />\n {t(\"Debug\", { context: \"agent-conversation-switch\" })}\n </span>\n {AGENT_INSPECT_DEBUG_SWITCH_NAMES.map((name) => (\n <DebugBarSwitch\n key={name}\n label={t(AGENT_INSPECT_DEBUG_SWITCH_LABELS[name], { context: AGENT_INSPECT_DEBUG_SWITCH_CONTEXT })}\n checked={switches[name]}\n onCheckedChange={(checked) => onSwitchChange(name, checked)}\n testId={`agent-inspect-debug-switch-${name}`}\n />\n ))}\n {extraSwitches}\n <span className=\"grow\" />\n {onViewRequest !== null ? (\n <button\n type=\"button\"\n onClick={onViewRequest}\n className=\"inline-flex items-center gap-2 text-[13px] whitespace-nowrap text-background/85 hover:text-background dark:text-foreground/85 dark:hover:text-foreground\"\n data-testid=\"agent-inspect-view-request\"\n >\n <Code className=\"size-3.5\" aria-hidden />\n {t(\"View request\", { context: \"agent-debug-switch\" })}\n </button>\n ) : null}\n </div>\n );\n};\n","import { readTraceMoment } from \"../../chat/trace/trace-format\";\nimport type { AgentInspectSubAgent, AgentInspectWaitingWindow } from \"./agent-inspect-types\";\n\n// The geometry of the delegation timeline: one lane per sub-agent with its runs as bars on a shared time axis, and\n// the windows in which the parent waited. Positions are shares of the axis (0–100). Pure, so it is covered by tests.\n\n/** The source of a waiting window that no delegation batch recorded: it is derived from the times of the sub-agents' runs. */\nexport const SWIMLANE_WINDOW_SOURCE_SUB_AGENT_RUNS = \"SUB_AGENT_RUNS\";\n\n/** The smallest width of a bar, so a run of a few milliseconds stays visible and clickable. */\nexport const SWIMLANE_MINIMUM_BAR_PERCENT = 0.8;\n\nexport interface DelegationSwimlaneBar {\n key: string;\n runNumber: number | null;\n /** The stored status of the run (`QUEUED`, `RUNNING`, `COMPLETED`, `FAILED`, `CANCELLED`, …). */\n status: string | null;\n /** Epoch milliseconds. */\n startedAt: number;\n /** Null while the run lasts (the bar then ends at `now`). */\n endedAt: number | null;\n durationMs: number;\n leftPercent: number;\n widthPercent: number;\n}\n\nexport interface DelegationSwimlane {\n key: string;\n subAgent: AgentInspectSubAgent;\n bars: DelegationSwimlaneBar[];\n}\n\nexport interface DelegationSwimlaneWindow {\n key: string;\n startedAt: number;\n /** Null while the parent still waits. */\n endedAt: number | null;\n durationMs: number;\n leftPercent: number;\n widthPercent: number;\n /** What the window was derived from, as the server names it (`DELEGATION_BATCHES`, `SUB_AGENT_RUNS`, `BOTH`). */\n source: string | null;\n /** No delegation batch recorded the wait: the window comes from the times of the sub-agents' runs alone. */\n isDerivedFromRuns: boolean;\n}\n\nexport interface DelegationSwimlaneTick {\n /** Milliseconds from the start of the axis. */\n offsetMs: number;\n leftPercent: number;\n}\n\nexport interface DelegationSwimlanes {\n /** The start of the axis (epoch milliseconds): the earliest run or waiting window. */\n startedAt: number;\n endedAt: number;\n durationMs: number;\n ticks: DelegationSwimlaneTick[];\n waitingWindows: DelegationSwimlaneWindow[];\n lanes: DelegationSwimlane[];\n}\n\nconst TICK_STEPS_MS = [\n 100, 250, 500, 1000, 2000, 5000, 10_000, 15_000, 30_000, 60_000, 120_000, 300_000, 600_000, 900_000, 1_800_000, 3_600_000, 7_200_000, 21_600_000,\n 43_200_000, 86_400_000,\n];\n\n/** The marks of an axis of `durationMs`: at round distances, at most `maximumTicks` of them, the start included. */\nexport const buildSwimlaneTicks = (durationMs: number, maximumTicks = 6): DelegationSwimlaneTick[] => {\n if (!(durationMs > 0)) return [{ offsetMs: 0, leftPercent: 0 }];\n const stepMs = TICK_STEPS_MS.find((step) => durationMs / step <= maximumTicks - 1) ?? Math.ceil(durationMs / (maximumTicks - 1));\n const ticks: DelegationSwimlaneTick[] = [];\n for (let offsetMs = 0; offsetMs <= durationMs; offsetMs += stepMs) {\n ticks.push({ offsetMs, leftPercent: (offsetMs / durationMs) * 100 });\n }\n return ticks;\n};\n\ninterface Span {\n startedAt: number;\n endedAt: number | null;\n}\n\nconst placeSpan = (span: Span, axisStartedAt: number, axisDurationMs: number, now: number): { leftPercent: number; widthPercent: number; durationMs: number } => {\n const endedAt = span.endedAt ?? Math.max(now, span.startedAt);\n const durationMs = Math.max(0, endedAt - span.startedAt);\n if (!(axisDurationMs > 0)) return { leftPercent: 0, widthPercent: 100, durationMs };\n const widthPercent = Math.max(SWIMLANE_MINIMUM_BAR_PERCENT, (durationMs / axisDurationMs) * 100);\n // A bar widened to the minimum stays inside the axis.\n const leftPercent = Math.min(((span.startedAt - axisStartedAt) / axisDurationMs) * 100, 100 - widthPercent);\n return { leftPercent: Math.max(0, leftPercent), widthPercent, durationMs };\n};\n\nexport interface BuildDelegationSwimlanesInput {\n subAgents: readonly AgentInspectSubAgent[];\n waitingWindows?: readonly AgentInspectWaitingWindow[];\n /** The moment a running run or an open window ends at (epoch milliseconds). */\n now: number;\n}\n\n/**\n * The swimlanes of a conversation's sub-agents; null when no run and no window has a readable start. A run without a\n * start (still queued) starts where it was queued; a run without an end lasts until `now`.\n */\nexport const buildDelegationSwimlanes = ({ subAgents, waitingWindows = [], now }: BuildDelegationSwimlanesInput): DelegationSwimlanes | null => {\n const laneSpans = subAgents.map((subAgent, position) => ({\n key: `${subAgent.childConversationId ?? \"none\"}:${subAgent.number ?? position}`,\n subAgent,\n spans: subAgent.runs.flatMap((run, runPosition) => {\n const queuedAt = run.runNumber !== null ? readTraceMoment(subAgent.queuedAtByRunNumber[run.runNumber]) : null;\n const startedAt = readTraceMoment(run.startedAt) ?? queuedAt;\n if (startedAt === null) return [];\n return [{ key: `run-${run.runNumber ?? runPosition}`, runNumber: run.runNumber, status: run.status, startedAt, endedAt: readTraceMoment(run.finishedAt) }];\n }),\n }));\n const windowSpans = waitingWindows.flatMap((window, position) => {\n const startedAt = readTraceMoment(window.startedAt);\n const source = window.source ?? null;\n return startedAt === null\n ? []\n : [{ key: `window-${position}`, startedAt, endedAt: readTraceMoment(window.endedAt), source, isDerivedFromRuns: source === SWIMLANE_WINDOW_SOURCE_SUB_AGENT_RUNS }];\n });\n const allSpans: Span[] = [...laneSpans.flatMap((lane) => lane.spans), ...windowSpans];\n if (allSpans.length === 0) return null;\n\n const axisStartedAt = Math.min(...allSpans.map((span) => span.startedAt));\n const axisEndedAt = Math.max(...allSpans.map((span) => span.endedAt ?? Math.max(now, span.startedAt)));\n const axisDurationMs = Math.max(0, axisEndedAt - axisStartedAt);\n return {\n startedAt: axisStartedAt,\n endedAt: axisEndedAt,\n durationMs: axisDurationMs,\n ticks: buildSwimlaneTicks(axisDurationMs),\n waitingWindows: windowSpans.map((span) => ({ ...span, ...placeSpan(span, axisStartedAt, axisDurationMs, now) })),\n lanes: laneSpans.map((lane) => ({\n key: lane.key,\n subAgent: lane.subAgent,\n bars: lane.spans.map((span) => ({ ...span, ...placeSpan(span, axisStartedAt, axisDurationMs, now) })),\n })),\n };\n};\n\n/** The totals of a conversation's sub-agents. */\nexport interface DelegationTotals {\n subAgentCount: number;\n runCount: number;\n runningCount: number;\n failedCount: number;\n costInUsd: number | null;\n inputTokens: number | null;\n outputTokens: number | null;\n}\n\nconst RUNNING_STATUSES: readonly string[] = [\"QUEUED\", \"RUNNING\", \"PENDING\"];\nconst FAILED_STATUSES: readonly string[] = [\"FAILED\", \"ERROR\", \"TIMED_OUT\"];\n\nconst sumOrNull = (values: readonly (number | null)[]): number | null => {\n const numbers = values.filter((value): value is number => value !== null);\n return numbers.length === 0 ? null : numbers.reduce((sum, value) => sum + value, 0);\n};\n\n/**\n * What the sub-agents cost together. A sub-agent counts with the total of its conversation where the server sends it\n * (debug level), else with the sum of what its runs carry.\n */\nexport const summarizeDelegation = (subAgents: readonly AgentInspectSubAgent[]): DelegationTotals => ({\n subAgentCount: subAgents.length,\n runCount: subAgents.reduce((sum, subAgent) => sum + subAgent.runs.length, 0),\n runningCount: subAgents.filter((subAgent) => RUNNING_STATUSES.includes(subAgent.status ?? \"\")).length,\n failedCount: subAgents.filter((subAgent) => FAILED_STATUSES.includes(subAgent.status ?? \"\")).length,\n costInUsd: sumOrNull(subAgents.map((subAgent) => subAgent.costInUsd ?? sumOrNull(subAgent.runs.map((run) => run.costInUsd)))),\n inputTokens: sumOrNull(subAgents.map((subAgent) => subAgent.inputTokens ?? sumOrNull(subAgent.runs.map((run) => run.inputTokens)))),\n outputTokens: sumOrNull(subAgents.map((subAgent) => subAgent.outputTokens ?? sumOrNull(subAgent.runs.map((run) => run.outputTokens)))),\n});\n","import { normalizeDddError } from \"@mgamadeus/ddd-web/contract\";\nimport { formatUiNumber, m, useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { EmptyValue, StatusBadge, type StatusTone, Tag } from \"@mgamadeus/ddd-admin-ui/list\";\nimport { StatusCallout } from \"@mgamadeus/ddd-admin-ui/page\";\nimport { Card, CardContent, cn, Skeleton } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { ExternalLink, ListTree } from \"lucide-react\";\nimport { type ReactNode, useEffect, useMemo, useState } from \"react\";\nimport { createTraceFormat, describeTraceModelName, formatTraceClock, readTraceMoment, readTraceRunResultText, readTraceStateOfStatus } from \"../../chat/trace/trace-format\";\nimport type { TraceStepState } from \"../../chat/trace/trace-types\";\nimport { mapAgentInspectDelegationTree } from \"./agent-inspect-mappers\";\nimport type { AgentInspectDelegationBatch, AgentInspectSubAgent } from \"./agent-inspect-types\";\nimport { ChildConversationTrace } from \"./ConversationTurns\";\nimport { buildDelegationSwimlanes, summarizeDelegation } from \"./delegation-swimlanes\";\nimport { formatAgentInspectCount } from \"./inspect-format\";\nimport { AgentTraceFrame, InspectActionButton, InspectFactCard } from \"./inspect-parts\";\nimport { useAgentInspectScope } from \"./inspect-scope\";\n\nconst STATE_CONTEXT = \"agent-sub-agent-state\";\n\nconst STATE_BADGES: Readonly<Record<TraceStepState, { label: string; tone: StatusTone }>> = {\n running: { label: m(\"running\", { context: \"agent-sub-agent-state\" }), tone: \"info\" },\n done: { label: m(\"done\", { context: \"agent-sub-agent-state\" }), tone: \"success\" },\n failed: { label: m(\"failed\", { context: \"agent-sub-agent-state\" }), tone: \"danger\" },\n waiting: { label: m(\"queued\", { context: \"agent-sub-agent-state\" }), tone: \"warning\" },\n cancelled: { label: m(\"cancelled\", { context: \"agent-sub-agent-state\" }), tone: \"neutral\" },\n};\n\nconst BAR_CLASS_NAMES: Readonly<Record<TraceStepState, string>> = {\n running: \"bg-info/25 shadow-[inset_0_0_0_1px_var(--info)]\",\n done: \"bg-success/25 shadow-[inset_0_0_0_1px_var(--success)]\",\n failed: \"bg-destructive/25 shadow-[inset_0_0_0_1px_var(--destructive)]\",\n waiting: \"bg-warning/20 shadow-[inset_0_0_0_1px_var(--warning)]\",\n cancelled: \"bg-muted shadow-[inset_0_0_0_1px_var(--border)]\",\n};\n\n/** `#3 label`, or the label alone for a sub-agent without a number. */\nconst nameOf = (subAgent: AgentInspectSubAgent): string => (subAgent.number !== null ? `#${subAgent.number} ${subAgent.label}` : subAgent.label);\n\nconst keyOf = (subAgent: AgentInspectSubAgent, position: number): string => `${subAgent.childConversationId ?? \"none\"}:${subAgent.number ?? position}`;\n\ninterface LaneRowProps {\n label: ReactNode;\n detail?: ReactNode;\n isSelected?: boolean;\n onSelect?: () => void;\n children: ReactNode;\n}\n\n/** One lane: its name in a fixed column, its bars on the shared axis. */\nconst LaneRow = ({ label, detail, isSelected = false, onSelect, children }: LaneRowProps) => (\n <div className=\"grid grid-cols-[minmax(120px,220px)_minmax(0,1fr)] items-center gap-3\" data-slot=\"agent-delegation-lane\">\n <button\n type=\"button\"\n onClick={onSelect}\n disabled={onSelect === undefined}\n className={cn(\"min-w-0 rounded-lg px-2 py-1 text-left\", onSelect && \"hover:bg-muted\", isSelected && \"bg-muted\")}\n >\n <span className=\"block truncate text-[13px] font-semibold\">{label}</span>\n {detail ? <span className=\"block truncate text-xs text-muted-foreground\">{detail}</span> : null}\n </button>\n <div className=\"relative h-7 rounded-md bg-muted/60\">{children}</div>\n </div>\n);\n\ninterface BatchChipsProps {\n batches: readonly AgentInspectDelegationBatch[];\n timeOf: (value: string | null | undefined) => string | null;\n}\n\n/** The delegation batches of the conversation, one line of chips each. */\nconst BatchChips = ({ batches, timeOf }: BatchChipsProps) => {\n const { t } = useTranslate();\n if (batches.length === 0) return null;\n return (\n <div className=\"flex flex-col gap-1.5\" data-slot=\"agent-delegation-batches\">\n {batches.map((batch, position) => (\n <div key={batch.delegationBatchId ?? position} className=\"flex flex-wrap items-center gap-1.5\">\n <Tag size=\"sm\" tone=\"brand\">\n {t(\"Batch #%id%\", { replacements: { id: batch.delegationBatchId ?? position + 1 } })}\n </Tag>\n <Tag size=\"sm\">{t(\"expects %count%\", { replacements: { count: batch.expectedDelegationCount ?? 0 } })}</Tag>\n {batch.delegateWakeCondition ? <Tag size=\"sm\">{t(\"wakes on %condition%\", { replacements: { condition: batch.delegateWakeCondition } })}</Tag> : null}\n {batch.quorumSuccessThreshold != null ? <Tag size=\"sm\">{t(\"quorum %count%\", { replacements: { count: batch.quorumSuccessThreshold } })}</Tag> : null}\n {timeOf(batch.deadlineAt) ? (\n <Tag size=\"sm\">\n {t(\"deadline %time% (%seconds% s)\", { replacements: { time: timeOf(batch.deadlineAt) ?? \"\", seconds: formatUiNumber(batch.timeoutSeconds ?? 0) } })}\n </Tag>\n ) : null}\n {timeOf(batch.settledAt) ? <Tag size=\"sm\">{t(\"settled %time%\", { replacements: { time: timeOf(batch.settledAt) ?? \"\" } })}</Tag> : <Tag size=\"sm\">{t(\"open\", { context: \"agent-delegation-batch\" })}</Tag>}\n </div>\n ))}\n </div>\n );\n};\n\n/**\n * The delegation of a conversation: what its sub-agents cost together, the batches, a timeline with one lane per\n * sub-agent (its runs as bars on a shared axis, the parent's waiting windows above) and a card per sub-agent with its\n * task, result and figures. A lane, a bar or \"Show trace\" opens the sub-agent's own trace below the cards.\n */\nexport const DelegationPanel = () => {\n const { t } = useTranslate();\n const { api, conversationId, locale, formatCost, isDebug, buildConversationHref, linkComponent: Link, frameAttributes, describeModelName } = useAgentInspectScope();\n const modelLabelOf = (subAgent: { modelLabel?: string | null; modelName: string | null }): string | null =>\n subAgent.modelLabel || (subAgent.modelName ? describeModelName?.(subAgent.modelName) : null) || describeTraceModelName(subAgent.modelName);\n const query = api.useDelegationsQuery({ conversationId });\n const tree = useMemo(() => (query.data ? mapAgentInspectDelegationTree(query.data) : null), [query.data]);\n const [selectedKey, setSelectedKey] = useState<string | null>(null);\n const format = useMemo(() => createTraceFormat(locale), [locale]);\n\n const hasRunningRun = (tree?.subAgents ?? []).some((subAgent) => readTraceStateOfStatus(subAgent.status) === \"running\") || (tree?.waitingWindows ?? []).some((window) => !window.endedAt);\n const [now, setNow] = useState(() => Date.now());\n useEffect(() => {\n setNow(Date.now());\n if (!hasRunningRun) return undefined;\n const timer = setInterval(() => setNow(Date.now()), 1000);\n return () => clearInterval(timer);\n }, [hasRunningRun, tree]);\n\n const swimlanes = useMemo(() => (tree ? buildDelegationSwimlanes({ subAgents: tree.subAgents, waitingWindows: tree.waitingWindows, now }) : null), [tree, now]);\n const totals = useMemo(() => summarizeDelegation(tree?.subAgents ?? []), [tree]);\n // The windows come from delegation batches, or — for runs without a batch row — from the times of the runs.\n const isWaitingDerivedFromRuns = (swimlanes?.waitingWindows ?? []).length > 0 && (swimlanes?.waitingWindows ?? []).every((window) => window.isDerivedFromRuns);\n\n if (query.isError) {\n return <StatusCallout tone=\"destructive\" title={t(\"The delegation could not be loaded\")} description={normalizeDddError(query.error, t(\"The delegation could not be loaded.\")).message} />;\n }\n if (tree === null) return <Skeleton className=\"h-48 w-full rounded-2xl\" />;\n if (tree.subAgents.length === 0) {\n return <StatusCallout tone=\"info\" title={t(\"No sub-agents\")} description={t(\"This conversation delegated nothing to a sub-agent.\")} />;\n }\n\n const timeOf = (value: string | null | undefined): string | null => {\n const moment = readTraceMoment(value);\n return moment === null ? null : format.time(moment);\n };\n const selectedSubAgent = tree.subAgents.find((subAgent, position) => keyOf(subAgent, position) === selectedKey) ?? null;\n const tokensOf = (subAgent: AgentInspectSubAgent): number | null =>\n subAgent.inputTokens === null && subAgent.outputTokens === null ? null : (subAgent.inputTokens ?? 0) + (subAgent.outputTokens ?? 0);\n\n return (\n <div className=\"flex flex-col gap-4\" data-testid=\"agent-delegation-panel\">\n <div className=\"grid grid-cols-2 gap-3 lg:grid-cols-4\">\n <InspectFactCard\n caption={t(\"Sub-agents\", { context: \"agent-delegation-total\" })}\n value={formatUiNumber(totals.subAgentCount)}\n detail={[\n totals.runningCount > 0 ? t(\"%count% running\", { replacements: { count: totals.runningCount } }) : null,\n totals.failedCount > 0 ? t(\"%count% failed\", { replacements: { count: totals.failedCount } }) : null,\n ]\n .filter(Boolean)\n .join(\" · \")}\n tone={totals.failedCount > 0 ? \"danger\" : undefined}\n />\n <InspectFactCard caption={t(\"Runs\", { context: \"agent-delegation\" })} value={formatUiNumber(totals.runCount)} detail={t(\"continued sub-agents run more than once\")} />\n <InspectFactCard\n caption={t(\"Cost of the sub-agents\", { context: \"agent-delegation\" })}\n value={totals.costInUsd !== null ? formatCost(totals.costInUsd) : <EmptyValue />}\n detail={isDebug ? undefined : t(\"shown with Debug\")}\n />\n <InspectFactCard\n caption={t(\"Tokens of the sub-agents\", { context: \"agent-delegation\" })}\n value={totals.inputTokens !== null || totals.outputTokens !== null ? formatAgentInspectCount((totals.inputTokens ?? 0) + (totals.outputTokens ?? 0), locale) : <EmptyValue />}\n detail={\n totals.inputTokens !== null\n ? t(\"%input% in, %output% out\", {\n replacements: { input: formatAgentInspectCount(totals.inputTokens ?? 0, locale), output: formatAgentInspectCount(totals.outputTokens ?? 0, locale) },\n })\n : isDebug\n ? undefined\n : t(\"shown with Debug\")\n }\n />\n </div>\n\n <Card className=\"gap-0 py-0\">\n <CardContent className=\"flex flex-col gap-3 px-5 py-4\">\n <BatchChips batches={tree.batches} timeOf={timeOf} />\n {swimlanes === null ? (\n <p className=\"text-sm text-muted-foreground\">{t(\"No run of a sub-agent has started yet.\")}</p>\n ) : (\n <div className=\"flex flex-col gap-1.5\" data-testid=\"agent-delegation-swimlanes\">\n <div className=\"grid grid-cols-[minmax(120px,220px)_minmax(0,1fr)] gap-3\">\n <span className=\"px-2 text-xs text-muted-foreground\">{t(\"from %time%\", { replacements: { time: format.time(swimlanes.startedAt) } })}</span>\n <div className=\"relative h-4 text-[11px] text-muted-foreground tabular-nums\">\n {swimlanes.ticks.map((tick) => (\n <span key={tick.offsetMs} className=\"absolute top-0 -translate-x-1/2 first:translate-x-0\" style={{ left: `${tick.leftPercent}%` }}>\n {formatTraceClock(tick.offsetMs)}\n </span>\n ))}\n </div>\n </div>\n <LaneRow\n label={t(\"This conversation\", { context: \"agent-delegation-lane\" })}\n detail={t(\"waits for its sub-agents\")}\n >\n {swimlanes.waitingWindows.map((window) => {\n const title = [\n window.endedAt === null ? t(\"waits for sub-agents\") : t(\"waited for sub-agents\"),\n format.duration(window.durationMs),\n window.isDerivedFromRuns ? t(\"derived from the run times\") : null,\n ]\n .filter(Boolean)\n .join(\" · \");\n return (\n <span\n key={window.key}\n role=\"img\"\n aria-label={title}\n className={cn(\n \"absolute inset-y-1 overflow-hidden rounded-sm px-1.5 text-[11px] leading-5 font-semibold whitespace-nowrap text-foreground\",\n BAR_CLASS_NAMES.waiting,\n window.endedAt === null && \"animate-pulse motion-reduce:animate-none\",\n )}\n style={{ left: `${window.leftPercent}%`, width: `${window.widthPercent}%` }}\n title={title}\n data-testid=\"agent-delegation-waiting-window\"\n data-source={window.source ?? undefined}\n >\n {window.widthPercent > 12 ? format.duration(window.durationMs) : null}\n </span>\n );\n })}\n </LaneRow>\n {swimlanes.lanes.map((lane, position) => {\n const laneKey = keyOf(lane.subAgent, position);\n return (\n <LaneRow\n key={lane.key}\n label={nameOf(lane.subAgent)}\n detail={[\n lane.subAgent.childConversationId !== null ? `#${lane.subAgent.childConversationId}` : null,\n modelLabelOf(lane.subAgent),\n lane.subAgent.costInUsd !== null ? formatCost(lane.subAgent.costInUsd) : null,\n ]\n .filter(Boolean)\n .join(\" · \")}\n isSelected={laneKey === selectedKey}\n onSelect={() => setSelectedKey(laneKey === selectedKey ? null : laneKey)}\n >\n {lane.bars.map((bar) => {\n const state = readTraceStateOfStatus(bar.status);\n const title = `${t(\"Run %number%\", { replacements: { number: bar.runNumber ?? 1 } })} · ${t(STATE_BADGES[state].label, { context: STATE_CONTEXT })} · ${format.duration(bar.durationMs)}`;\n return (\n <button\n type=\"button\"\n key={bar.key}\n onClick={() => setSelectedKey(laneKey)}\n className={cn(\n \"absolute inset-y-1 overflow-hidden rounded-sm px-1.5 text-left text-[11px] leading-5 font-semibold whitespace-nowrap text-foreground\",\n BAR_CLASS_NAMES[state],\n bar.endedAt === null && \"animate-pulse motion-reduce:animate-none\",\n )}\n style={{ left: `${bar.leftPercent}%`, width: `${bar.widthPercent}%` }}\n title={title}\n aria-label={`${nameOf(lane.subAgent)}: ${title}`}\n data-testid=\"agent-delegation-bar\"\n >\n {bar.widthPercent > 12 ? format.duration(bar.durationMs) : null}\n </button>\n );\n })}\n </LaneRow>\n );\n })}\n </div>\n )}\n {isWaitingDerivedFromRuns ? (\n <p className=\"mt-2 text-[11px] text-muted-foreground\" data-testid=\"agent-delegation-waiting-source\">\n {t(\"No delegation batch recorded these waits: the windows are derived from when the sub-agents' runs started and ended.\", { context: \"agent-delegation-note\" })}\n </p>\n ) : null}\n </CardContent>\n </Card>\n\n <div className=\"grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-3\">\n {tree.subAgents.map((subAgent, position) => {\n const subAgentKey = keyOf(subAgent, position);\n const state = readTraceStateOfStatus(subAgent.status);\n const newestRun = subAgent.runs[subAgent.runs.length - 1];\n const startedAt = readTraceMoment(newestRun?.startedAt);\n const finishedAt = readTraceMoment(newestRun?.finishedAt);\n const tokens = tokensOf(subAgent);\n const childHref = subAgent.childConversationId !== null ? (buildConversationHref?.(subAgent.childConversationId) ?? null) : null;\n return (\n <Card key={subAgentKey} className={cn(\"gap-0 py-0\", subAgentKey === selectedKey && \"shadow-[inset_0_0_0_2px_var(--brand-emphasis)]\")} data-testid=\"agent-delegation-card\">\n <CardContent className=\"flex h-full flex-col gap-2.5 px-4 py-3.5\">\n <div className=\"flex items-start justify-between gap-2\">\n <span className=\"min-w-0 text-sm font-bold break-words\">{nameOf(subAgent)}</span>\n <StatusBadge tone={STATE_BADGES[state].tone} label={t(STATE_BADGES[state].label, { context: STATE_CONTEXT })} />\n </div>\n <dl className=\"grid grid-cols-[72px_minmax(0,1fr)] gap-x-3 gap-y-1 text-[13px]\">\n <dt className=\"text-muted-foreground\">{t(\"Task\", { context: \"agent-delegation\" })}</dt>\n <dd className=\"line-clamp-4 break-words\" title={subAgent.taskText ?? undefined}>\n {subAgent.taskText || <EmptyValue />}\n </dd>\n {subAgent.modelName ? (\n <>\n <dt className=\"text-muted-foreground\">{t(\"Model\", { context: \"agent-delegation\" })}</dt>\n <dd className=\"truncate font-semibold\" title={subAgent.modelName}>\n {modelLabelOf(subAgent)}\n </dd>\n </>\n ) : null}\n <dt className=\"text-muted-foreground\">{t(\"Duration\", { context: \"agent-delegation\" })}</dt>\n <dd className=\"font-semibold tabular-nums\">\n {startedAt === null ? <EmptyValue /> : format.duration((finishedAt ?? now) - startedAt)}\n {subAgent.runs.length > 1 ? <span className=\"font-normal text-muted-foreground\"> · {t(\"%count% runs\", { replacements: { count: subAgent.runs.length } })}</span> : null}\n </dd>\n {subAgent.costInUsd !== null ? (\n <>\n <dt className=\"text-muted-foreground\">{t(\"Cost\", { context: \"agent-delegation\" })}</dt>\n <dd className=\"font-semibold tabular-nums\">{formatCost(subAgent.costInUsd)}</dd>\n </>\n ) : null}\n {tokens !== null ? (\n <>\n <dt className=\"text-muted-foreground\">{t(\"Tokens\", { context: \"agent-delegation\" })}</dt>\n <dd className=\"tabular-nums\">\n <span className=\"font-semibold\">{formatAgentInspectCount(tokens, locale)}</span>\n {subAgent.tokensAreChildConversationTotal ? <span className=\"text-muted-foreground\"> · {t(\"whole conversation of the sub-agent\")}</span> : null}\n </dd>\n </>\n ) : null}\n <dt className=\"text-muted-foreground\">{t(\"Result\", { context: \"agent-delegation\" })}</dt>\n <dd className=\"line-clamp-5 break-words\" title={newestRun?.verdict ?? undefined}>\n {readTraceRunResultText(newestRun?.verdict) || newestRun?.failureReason || <span className=\"text-muted-foreground\">{t(\"no result yet\")}</span>}\n </dd>\n </dl>\n <div className=\"mt-auto flex flex-wrap items-center gap-1.5 pt-1\">\n {subAgent.childConversationId !== null ? (\n <InspectActionButton icon={<ListTree aria-hidden />} onClick={() => setSelectedKey(subAgentKey === selectedKey ? null : subAgentKey)} testId=\"agent-delegation-show-trace\">\n {subAgentKey === selectedKey ? t(\"Hide trace\") : t(\"Show trace\")}\n </InspectActionButton>\n ) : null}\n {childHref !== null ? (\n <Link href={childHref} className=\"inline-flex h-7 items-center gap-1.5 rounded-full px-2.5 text-xs font-semibold text-brand-emphasis hover:underline\">\n <ExternalLink className=\"size-3.5\" aria-hidden />\n {t(\"Conversation #%id%\", { replacements: { id: subAgent.childConversationId ?? 0 } })}\n </Link>\n ) : null}\n </div>\n </CardContent>\n </Card>\n );\n })}\n </div>\n\n {selectedSubAgent !== null && selectedSubAgent.childConversationId !== null ? (\n <Card className=\"gap-0 py-0\" data-testid=\"agent-delegation-trace\">\n <CardContent className=\"flex flex-col gap-3 px-5 py-4\">\n <h3 className=\"text-sm font-bold\">{t(\"Trace of %name%\", { replacements: { name: nameOf(selectedSubAgent) } })}</h3>\n <AgentTraceFrame frameAttributes={frameAttributes}>\n <ChildConversationTrace key={selectedSubAgent.childConversationId} conversationId={selectedSubAgent.childConversationId} />\n </AgentTraceFrame>\n </CardContent>\n </Card>\n ) : null}\n </div>\n );\n};\n","import { normalizeDddError } from \"@mgamadeus/ddd-web/contract\";\nimport { formatUiNumber, getUiLocale, useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { StatusCallout } from \"@mgamadeus/ddd-admin-ui/page\";\nimport { Badge, cn, Skeleton } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { Maximize2 } from \"lucide-react\";\nimport { type ReactNode, useMemo, useState } from \"react\";\nimport { DetailModal } from \"../blocks/DetailModal\";\nimport { formatTokenFigure } from \"../blocks/token-figure\";\nimport { TokenFigure } from \"../blocks/TokenFigure\";\nimport type { AgentInspectContextApi } from \"../context/agent-inspect-context-api\";\nimport {\n type AgentContextCompositionEntry,\n type AgentContextSegmentView,\n agentContextCompositionOf,\n agentContextSegmentViewsToText,\n buildAgentContextCompositionEntries,\n buildAgentContextEntrySegmentViews,\n buildAgentContextSegmentViews,\n summarizeAgentContextComposition,\n} from \"../context/context-composition-grouping\";\nimport { translateAgentContextEntryLabel } from \"../context/context-segment-label-texts\";\nimport { ContextSegmentList } from \"../context/ContextSegmentList\";\n\nexport interface RequestCompositionRowsProps {\n api: AgentInspectContextApi;\n conversationId: number | string;\n messageId: number | string;\n renderMarkdown?: (source: string) => ReactNode;\n}\n\n/** What the detail modal shows: the segments, and the title above them. */\ninterface OpenDetail {\n title: string;\n segments: AgentContextSegmentView[];\n}\n\n/**\n * The composition of one sent request as rows, in the order of the request: the segment (role groups of the message tail\n * with their count), a meter of its share and its tokens. A row opens the texts of its segments; the line below sums\n * the segments, says whether the breakdown was rebuilt and opens the whole context.\n */\nexport const RequestCompositionRows = ({ api, conversationId, messageId, renderMarkdown }: RequestCompositionRowsProps) => {\n const { t } = useTranslate();\n const query = api.useContextCompositionQuery({ conversationId, messageId });\n const [openDetail, setOpenDetail] = useState<OpenDetail | null>(null);\n const composition = useMemo(() => agentContextCompositionOf(query.data), [query.data]);\n const entries = useMemo(() => buildAgentContextCompositionEntries(composition), [composition]);\n const summary = useMemo(() => summarizeAgentContextComposition(composition), [composition]);\n const locale = getUiLocale();\n\n const labelOf = (entry: AgentContextCompositionEntry): string => translateAgentContextEntryLabel(entry, t);\n\n if (query.isLoading) {\n return (\n <div className=\"space-y-2\">\n {[0, 1, 2, 3].map((row) => (\n <Skeleton key={row} className=\"h-6 w-full\" />\n ))}\n </div>\n );\n }\n if (query.isError) {\n return (\n <StatusCallout\n size=\"compact\"\n tone=\"destructive\"\n title={t(\"The context composition could not be loaded.\")}\n description={normalizeDddError(query.error, \"\").message}\n />\n );\n }\n if (composition === null || composition.isUnavailable === true || summary.segmentCount === 0) {\n return <p className=\"text-sm text-muted-foreground\">{t(\"No composition for this message: it made no model call (no request snapshot).\")}</p>;\n }\n\n const total = Math.max(summary.totalTokens, 1);\n return (\n <div className=\"min-w-0\" data-testid=\"agent-request-composition-rows\">\n <ul className=\"divide-y divide-border border-y border-border\">\n {entries.map((entry) => {\n const share = (entry.tokenCount / total) * 100;\n const label = labelOf(entry);\n return (\n <li key={entry.key}>\n <button\n type=\"button\"\n onClick={() =>\n setOpenDetail({ title: entry.segmentCount > 1 ? `${label} ×${entry.segmentCount}` : label, segments: buildAgentContextEntrySegmentViews(entry) })\n }\n className=\"flex w-full items-center gap-3 py-2 text-left text-sm outline-none hover:bg-tint focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset\"\n >\n <span className=\"min-w-0 flex-1 truncate\" title={label}>\n {label}\n {entry.segmentCount > 1 ? <span className=\"ml-1 text-muted-foreground\">×{entry.segmentCount}</span> : null}\n </span>\n <span aria-hidden className=\"h-1.5 w-40 shrink-0 overflow-hidden rounded-full bg-muted\">\n <span className={cn(\"block h-full rounded-full\", entry.colorClassName)} style={{ width: `${Math.max(share, 1)}%` }} />\n </span>\n <span className=\"w-24 shrink-0 text-right font-mono text-xs tabular-nums\">\n {formatTokenFigure(entry.tokenCount, { isEstimate: entry.isEstimate, locale })}\n <span className=\"ml-1 text-muted-foreground\">{share < 1 ? \"<1\" : formatUiNumber(Math.round(share))} %</span>\n </span>\n </button>\n </li>\n );\n })}\n </ul>\n <div className=\"mt-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground\">\n <span>\n {t(\"{count, plural, one {# segment} other {# segments}}\", { count: summary.segmentCount })} ·{\" \"}\n <TokenFigure value={summary.totalTokens} isEstimate={summary.isEstimate} suffix={t(\"tokens\")} className=\"text-foreground\" />\n </span>\n {composition.isReconstructed === true ? (\n <Badge\n variant=\"warning\"\n title={t(\"Rebuilt from the stored messages and the current prompt, skills and memory. It may differ from what was sent if those changed since.\")}\n >\n {t(\"Reconstructed\", { context: \"agent-context\" })}\n </Badge>\n ) : null}\n <button\n type=\"button\"\n onClick={() => setOpenDetail({ title: t(\"Whole context of this model call\"), segments: buildAgentContextSegmentViews(composition, entries) })}\n className=\"ml-auto inline-flex items-center gap-1 rounded-sm font-medium text-primary-emphasis underline-offset-2 outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring\"\n >\n <Maximize2 aria-hidden className=\"size-3.5\" />\n {t(\"View whole context\")}\n </button>\n </div>\n <DetailModal\n open={openDetail !== null}\n onOpenChange={(isOpen) => {\n if (!isOpen) setOpenDetail(null);\n }}\n title={openDetail?.title ?? \"\"}\n description={\n openDetail && openDetail.segments.length > 1 ? t(\"{count, plural, one {# segment} other {# segments}}\", { count: openDetail.segments.length }) : undefined\n }\n copyText={() => agentContextSegmentViewsToText(openDetail?.segments ?? [])}\n >\n {(view) => <ContextSegmentList segments={openDetail?.segments ?? []} view={view} renderMarkdown={renderMarkdown} />}\n </DetailModal>\n </div>\n );\n};\n","import { useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { Combobox } from \"@mgamadeus/ddd-admin-ui/list\";\nimport { useCopyToClipboard } from \"@mgamadeus/ddd-admin-ui/logic\";\nimport { StatusCallout } from \"@mgamadeus/ddd-admin-ui/page\";\nimport { Button, SegmentedControl, Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { ClipboardCheck, Code, Copy } from \"lucide-react\";\nimport { useMemo } from \"react\";\nimport { describeTraceEffort } from \"../../chat/trace/trace-format\";\nimport { formatSentPayloadText, readSentPayloadValue, type SentPayloadComparableMessage, SentPayloadPanel } from \"../context/SentPayloadPanel\";\nimport { useAgentInspectScope } from \"./inspect-scope\";\nimport { RequestCompositionRows } from \"./RequestCompositionRows\";\nimport type { AgentInspectModelCallReference } from \"./turn-paging\";\n\n/**\n * The outline of a request body in one short JSON line: the model, the reasoning effort and how many tools and input\n * items it sent (`{ \"model\": \"gpt-6-luna\", \"reasoning\": { \"effort\": \"medium\" }, \"tools\": [ … 22 ], \"input\": [ … 31 ] }`);\n * null for a body that is no JSON object. Pure.\n */\nexport const describeRequestOutline = (payload: unknown): string | null => {\n const value = readSentPayloadValue(payload);\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return null;\n const envelope = value as Record<string, unknown>;\n // A rebuilt request comes as `{ reconstructed, body }`.\n const body = envelope.body !== null && typeof envelope.body === \"object\" && !Array.isArray(envelope.body) ? (envelope.body as Record<string, unknown>) : envelope;\n const parts: string[] = [];\n if (typeof body.model === \"string\") parts.push(`\"model\": ${JSON.stringify(body.model)}`);\n const reasoning = body.reasoning;\n if (reasoning !== null && typeof reasoning === \"object\" && typeof (reasoning as Record<string, unknown>).effort === \"string\") {\n parts.push(`\"reasoning\": { \"effort\": ${JSON.stringify((reasoning as Record<string, unknown>).effort)} }`);\n } else if (typeof body.reasoning_effort === \"string\") {\n parts.push(`\"reasoning_effort\": ${JSON.stringify(body.reasoning_effort)}`);\n }\n for (const key of [\"tools\", \"input\", \"messages\"]) {\n const list = body[key];\n if (Array.isArray(list)) parts.push(`\"${key}\": [ … ${list.length} ]`);\n }\n return parts.length > 0 ? `{ ${parts.join(\", \")} }` : null;\n};\n\n/** The tabs of the drawer: the composition of the request, its raw JSON, its difference to the call before. */\nexport type ModelContextView = \"composition\" | \"payload\" | \"diff\";\n\nexport interface ModelContextDialogProps {\n /** The message whose model call is shown; null closes the drawer. */\n messageId: number | null;\n view: ModelContextView;\n /** The model calls of the loaded turns: the picker's choices and what a payload is compared with. */\n modelCalls: readonly AgentInspectModelCallReference[];\n onMessageIdChange: (messageId: number | null) => void;\n onViewChange: (view: ModelContextView) => void;\n /** The model and the reasoning effort of the call in words, for the line under the title; null when unknown. */\n describeCall?: (modelCall: AgentInspectModelCallReference) => { modelLabel: string | null; effort: string | null } | null;\n}\n\n/**\n * The request one model call sent, in a drawer at the right: its composition (the segments with their tokens, each\n * opening to its text), at the debug level its raw JSON and its difference to the call before. The line under the\n * title says whether the request is the snapshot stored when the call was made or rebuilt, and which model and effort\n * it ran with. A picker steps to the other model calls of the loaded turns; the footer copies the JSON and saves the\n * turn as an evaluation case.\n */\nexport const ModelContextDialog = ({ messageId, view, modelCalls, onMessageIdChange, onViewChange, describeCall }: ModelContextDialogProps) => {\n const { t } = useTranslate();\n const { api, conversationId, isDebug, renderMarkdown, openEvalCase } = useAgentInspectScope();\n const { copy, copied } = useCopyToClipboard();\n const labelOf = (modelCall: AgentInspectModelCallReference): string =>\n t(\"Turn %turn%, call %call%\", { replacements: { turn: modelCall.turnNumber, call: modelCall.callNumber } });\n const options = useMemo(\n () =>\n modelCalls.map((modelCall) => ({\n value: String(modelCall.messageId),\n label: labelOf(modelCall),\n description: modelCall.modelName ?? undefined,\n translate: false,\n })),\n // The labels follow the UI language through `t`.\n // biome-ignore lint/correctness/useExhaustiveDependencies: `labelOf` only wraps `t`\n [modelCalls, t],\n );\n const position = modelCalls.findIndex((modelCall) => modelCall.messageId === messageId);\n const shownCall = position >= 0 ? modelCalls[position] : null;\n const previousCall = position > 0 ? modelCalls[position - 1] : null;\n const comparableMessages: SentPayloadComparableMessage[] = modelCalls\n .filter((modelCall) => modelCall.messageId !== messageId)\n .map((modelCall) => ({ messageId: modelCall.messageId, label: labelOf(modelCall) }));\n const shownView: ModelContextView = !isDebug ? \"composition\" : view === \"diff\" && previousCall === null ? \"payload\" : view;\n\n // The payload is read once here for the line under the title and \"Copy JSON\"; the panels read it from the same cache.\n const payloadQuery = api.context.useSentPayloadQuery({ conversationId, messageId: messageId ?? 0 }, { skip: messageId === null || !isDebug });\n const payload = payloadQuery.data?.payload;\n const hasPayload = payload !== undefined && payload !== null;\n const isStoredPayload = payloadQuery.data?.isStoredPayload === true;\n const outline = useMemo(() => (hasPayload ? describeRequestOutline(payload) : null), [hasPayload, payload]);\n const callWords = shownCall !== null ? (describeCall?.(shownCall) ?? null) : null;\n const descriptionParts = [\n isDebug && hasPayload ? (isStoredPayload ? t(\"Stored snapshot (complete)\") : t(\"Rebuilt, not the stored snapshot\")) : null,\n callWords?.modelLabel ?? shownCall?.modelName ?? null,\n callWords?.effort ? t(\"Effort %effort%\", { replacements: { effort: describeTraceEffort(callWords.effort) ?? callWords.effort } }) : null,\n ].filter((part): part is string => part !== null && part !== \"\");\n\n const viewOptions = [\n { value: \"composition\" as const, label: t(\"Composition\", { context: \"agent-request-view\" }), translate: false },\n { value: \"payload\" as const, label: t(\"Raw JSON\", { context: \"agent-request-view\" }), translate: false },\n ...(previousCall !== null\n ? [{ value: \"diff\" as const, label: t(\"Difference to call %call%\", { context: \"agent-request-view\", replacements: { call: previousCall.callNumber } }), translate: false }]\n : []),\n ];\n\n return (\n <Sheet open={messageId !== null} onOpenChange={(open) => !open && onMessageIdChange(null)}>\n <SheetContent side=\"right\" className=\"flex w-full flex-col gap-0 p-0 sm:max-w-[640px]\" data-testid=\"agent-model-context-drawer\">\n <SheetHeader className=\"flex-row items-start gap-3 border-b border-border px-6 py-4 pr-12\">\n <Code className=\"mt-1 size-4 shrink-0 text-muted-foreground\" aria-hidden />\n <div className=\"flex min-w-0 flex-col gap-0.5\">\n <SheetTitle className=\"text-base\">\n {shownCall !== null\n ? t(\"Sent request · %call%\", { replacements: { call: labelOf(shownCall) } })\n : t(\"Sent request of message #%id%\", { replacements: { id: messageId ?? 0 } })}\n </SheetTitle>\n <SheetDescription className=\"text-[12.5px]\">{descriptionParts.join(\" · \") || t(\"What the model was sent at this call.\")}</SheetDescription>\n </div>\n </SheetHeader>\n <div className=\"flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-6 py-4\">\n <div className=\"flex flex-wrap items-center gap-2\" data-testid=\"agent-model-context-toolbar\">\n {isDebug ? (\n <SegmentedControl aria-label={t(\"What of the request is shown\")} height={32} value={shownView} onValueChange={onViewChange} options={viewOptions} />\n ) : null}\n {options.length > 1 ? (\n <Combobox\n aria-label={t(\"Model call\", { context: \"agent-step-kind\" })}\n size=\"sm\"\n className=\"ml-auto w-48\"\n options={options}\n value={messageId !== null ? String(messageId) : \"\"}\n onChange={(value) => value !== \"\" && onMessageIdChange(Number(value))}\n translate={false}\n />\n ) : null}\n </div>\n {messageId === null ? null : shownView === \"composition\" ? (\n <>\n <RequestCompositionRows key={messageId} api={api.context} conversationId={conversationId} messageId={messageId} renderMarkdown={renderMarkdown} />\n {outline !== null ? (\n <pre className=\"rounded-lg bg-muted px-3 py-2 font-mono text-xs break-words whitespace-pre-wrap text-foreground\" data-testid=\"agent-request-outline\">\n {outline}\n </pre>\n ) : null}\n </>\n ) : (\n <SentPayloadPanel\n key={`${messageId}:${shownView}`}\n api={api.context}\n conversationId={conversationId}\n messageId={messageId}\n comparableMessages={comparableMessages}\n defaultMode={shownView === \"diff\" ? \"diff\" : \"raw\"}\n defaultComparedMessageId={previousCall?.messageId}\n isEmbedded\n />\n )}\n {isDebug ? (\n <StatusCallout\n size=\"compact\"\n tone=\"info\"\n title={t(\"Only admins with the debug right see the request. Without a stored snapshot it is rebuilt and marked as such.\")}\n />\n ) : null}\n </div>\n {isDebug ? (\n <SheetFooter className=\"flex-row justify-end gap-2 border-t border-border px-6 py-3\">\n <Button type=\"button\" variant=\"outline\" size=\"sm\" disabled={!hasPayload} onClick={() => copy(formatSentPayloadText(payload))} data-testid=\"agent-model-context-copy\">\n <Copy />\n {copied ? t(\"Copied\", { context: \"agent-request-view\" }) : t(\"Copy JSON\", { context: \"agent-request-view\" })}\n </Button>\n {openEvalCase && messageId !== null ? (\n <Button type=\"button\" variant=\"outline\" size=\"sm\" onClick={() => openEvalCase(messageId)} data-testid=\"agent-model-context-eval-case\">\n <ClipboardCheck />\n {t(\"Save as evaluation case\")}\n </Button>\n ) : null}\n </SheetFooter>\n ) : null}\n </SheetContent>\n </Sheet>\n );\n};\n\n","import { describeTraceModelName } from \"../../chat/trace/trace-format\";\nimport type { AgentInspectTrace, AgentInspectTurn } from \"./agent-inspect-types\";\nimport type { AgentInspectTurnWindow } from \"./turn-paging\";\n\n// The model calls of a conversation as the rows of a table, with their totals, and which page of turns to read next.\n// Pure, so the rows, the sums and the paging are covered by tests.\n\n/** Turns read per page of the requests table (the trace route answers at most 100). */\nexport const AGENT_INSPECT_REQUESTS_PAGE_SIZE = 50;\n\n/** One model call of the conversation. */\nexport interface AgentInspectModelCallRow {\n /** Unique among the rows: the step's id. */\n key: string;\n stepId: string;\n turnNumber: number;\n /** The number of the call within its turn, from 1: the server's, else its position among the turn's calls. */\n callNumber: number;\n /** The message of the call; null for a call without a stored message. */\n messageId: number | null;\n /** The message whose context composition and payload are this call's; null when neither can be read. */\n contextMessageId: number | null;\n /** The model in words (\"GPT6 LUNA\"), and its stored name. */\n modelLabel: string | null;\n modelName: string | null;\n effort: string | null;\n startedAt: string | null;\n inputTokens: number | null;\n outputTokens: number | null;\n cachedInputTokens: number | null;\n /** The share of the input tokens read from the cache, 0–100. */\n cachePercent: number | null;\n costInUsd: number | null;\n /** How long the call took: the step's duration, else the provider's time. */\n durationMs: number | null;\n providerCallMs: number | null;\n loopOverheadMs: number | null;\n /** How the call ended (`toolCalls`, `answer`, `empty`), as the server derives it. */\n stopReason: string | null;\n /** The tools the model called in this call, in order. */\n toolNames: string[];\n retryCount: number;\n /** The request of the call is stored as sent; false: it can only be rebuilt. */\n hasStoredPayload: boolean;\n /** The call belongs to a branch an admin truncated. */\n isTruncated: boolean;\n}\n\n/** The cached share of input tokens, 0–100 with one decimal; null without both counts. */\nconst cachePercentOf = (inputTokens: number | null, cachedInputTokens: number | null): number | null =>\n inputTokens === null || cachedInputTokens === null || inputTokens <= 0 ? null : Math.round((cachedInputTokens / inputTokens) * 1000) / 10;\n\n/**\n * The model calls of the turns, oldest first: the `MODEL_CALL` steps, and a `THINKING` step that carries the facts of\n * a call no `MODEL_CALL` step of its turn stands for. A read below the debug level has no such steps and no rows.\n */\nexport const buildAgentInspectModelCallRows = (turns: readonly AgentInspectTurn[]): AgentInspectModelCallRow[] => {\n const rows: AgentInspectModelCallRow[] = [];\n for (const turn of [...turns].sort((first, second) => first.turnNumber - second.turnNumber)) {\n const modelCallMessageIds = new Set(turn.steps.filter((step) => step.kind === \"MODEL_CALL\" && step.messageId !== null).map((step) => step.messageId));\n let positionInTurn = 0;\n for (const step of turn.steps) {\n const isModelCall = step.kind === \"MODEL_CALL\";\n const isThinkingWithFacts = step.kind === \"THINKING\" && step.modelCall !== null && !modelCallMessageIds.has(step.messageId);\n if (!isModelCall && !isThinkingWithFacts) continue;\n positionInTurn += 1;\n const modelCall = step.modelCall;\n const modelName = modelCall?.modelName ?? null;\n rows.push({\n key: step.stepId,\n stepId: step.stepId,\n turnNumber: turn.turnNumber,\n callNumber: modelCall?.callNumberInTurn ?? positionInTurn,\n messageId: step.messageId,\n contextMessageId: step.contextMessageId ?? step.messageId,\n modelLabel: step.modelLabel ?? describeTraceModelName(modelName),\n modelName,\n effort: modelCall?.effort ?? null,\n startedAt: step.startedAt,\n inputTokens: modelCall?.inputTokens ?? null,\n outputTokens: modelCall?.outputTokens ?? null,\n cachedInputTokens: modelCall?.cachedInputTokens ?? null,\n cachePercent: modelCall?.cachePercent ?? cachePercentOf(modelCall?.inputTokens ?? null, modelCall?.cachedInputTokens ?? null),\n costInUsd: modelCall?.costInUsd ?? null,\n durationMs: step.durationMs ?? modelCall?.providerCallMs ?? null,\n providerCallMs: modelCall?.providerCallMs ?? null,\n loopOverheadMs: modelCall?.loopOverheadMs ?? null,\n stopReason: modelCall?.stopReason ?? null,\n toolNames: modelCall?.toolNames ?? [],\n retryCount: modelCall?.retryCount ?? 0,\n hasStoredPayload: step.modelCallFacts?.hasStoredPayload ?? modelCall?.hasStoredPayload ?? false,\n isTruncated: step.isTruncated,\n });\n }\n }\n return rows;\n};\n\n/** The sums of the listed model calls. A figure no call carries is null, never 0. */\nexport interface AgentInspectModelCallTotals {\n callCount: number;\n /** Turns that hold at least one of the calls. */\n turnCount: number;\n inputTokens: number | null;\n outputTokens: number | null;\n cachedInputTokens: number | null;\n /** The cached share of the input tokens over the calls that carry both counts, 0–100. */\n cachePercent: number | null;\n costInUsd: number | null;\n durationMs: number | null;\n retryCount: number;\n}\n\nconst sumOrNull = (values: readonly (number | null)[]): number | null => {\n const numbers = values.filter((value): value is number => value !== null);\n return numbers.length === 0 ? null : numbers.reduce((sum, value) => sum + value, 0);\n};\n\n/** The totals of the rows. */\nexport const summarizeAgentInspectModelCalls = (rows: readonly AgentInspectModelCallRow[]): AgentInspectModelCallTotals => {\n const rowsWithBothCounts = rows.filter((row) => row.inputTokens !== null && row.cachedInputTokens !== null);\n return {\n callCount: rows.length,\n turnCount: new Set(rows.map((row) => row.turnNumber)).size,\n inputTokens: sumOrNull(rows.map((row) => row.inputTokens)),\n outputTokens: sumOrNull(rows.map((row) => row.outputTokens)),\n cachedInputTokens: sumOrNull(rows.map((row) => row.cachedInputTokens)),\n cachePercent: cachePercentOf(sumOrNull(rowsWithBothCounts.map((row) => row.inputTokens)), sumOrNull(rowsWithBothCounts.map((row) => row.cachedInputTokens))),\n costInUsd: sumOrNull(rows.map((row) => row.costInUsd)),\n durationMs: sumOrNull(rows.map((row) => row.durationMs)),\n retryCount: rows.reduce((sum, row) => sum + row.retryCount, 0),\n };\n};\n\n/** The paging facts of one page read of the trace. */\nexport type AgentInspectTracePage = Pick<AgentInspectTrace, \"firstTurnNumber\" | \"lastTurnNumber\" | \"hasOlderTurns\">;\n\n/** Which turns the pages read so far cover, and whether older turns exist before them. */\nexport interface AgentInspectTraceCoverage {\n firstTurnNumber: number | null;\n lastTurnNumber: number | null;\n /** Turns exist before `firstTurnNumber`, as the oldest page read says. */\n hasOlderTurns: boolean;\n}\n\n/**\n * What the page reads cover together. Whether older turns exist is the fact of the page that starts first; a page\n * without turns (asked beyond what the conversation holds) covers nothing and ends the paging before it.\n */\nexport const readAgentInspectTraceCoverage = (pages: readonly AgentInspectTracePage[]): AgentInspectTraceCoverage => {\n const pagesWithTurns = pages.filter((page): page is AgentInspectTracePage & { firstTurnNumber: number } => page.firstTurnNumber !== null);\n if (pagesWithTurns.length === 0) return { firstTurnNumber: null, lastTurnNumber: null, hasOlderTurns: false };\n const oldestPage = pagesWithTurns.reduce((oldest, page) => (page.firstTurnNumber < oldest.firstTurnNumber ? page : oldest));\n const hasEmptyPage = pages.some((page) => page.firstTurnNumber === null);\n return {\n firstTurnNumber: oldestPage.firstTurnNumber,\n lastTurnNumber: pagesWithTurns.reduce((last, page) => Math.max(last, page.lastTurnNumber ?? page.firstTurnNumber), 0),\n hasOlderTurns: oldestPage.hasOlderTurns && oldestPage.firstTurnNumber > 1 && !hasEmptyPage,\n };\n};\n\n/** The page before the covered turns; null when the first turn is covered. */\nexport const previousAgentInspectTracePage = (\n coverage: AgentInspectTraceCoverage,\n pageSize: number = AGENT_INSPECT_REQUESTS_PAGE_SIZE,\n): AgentInspectTurnWindow | null => {\n if (!coverage.hasOlderTurns || coverage.firstTurnNumber === null || coverage.firstTurnNumber <= 1) return null;\n const fromTurnNumber = Math.max(1, coverage.firstTurnNumber - Math.max(1, pageSize));\n return { fromTurnNumber, limit: coverage.firstTurnNumber - fromTurnNumber };\n};\n","import { normalizeDddError } from \"@mgamadeus/ddd-web/contract\";\nimport { formatUiNumber, m, useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { EmptyValue, StatusBadge } from \"@mgamadeus/ddd-admin-ui/list\";\nimport { StatusCallout } from \"@mgamadeus/ddd-admin-ui/page\";\nimport { Button, Card, CardContent, cn, Skeleton, Table, TableBody, TableCell, TableFooter, TableHead, TableHeader, TableRow } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { ChevronsUp, FileJson } from \"lucide-react\";\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { createTraceFormat, readTraceMoment } from \"../../chat/trace/trace-format\";\nimport { mapAgentInspectTrace } from \"./agent-inspect-mappers\";\nimport type { AgentInspectConversationHeader, AgentInspectTrace } from \"./agent-inspect-types\";\nimport { formatAgentInspectCount } from \"./inspect-format\";\nimport { LiveDot } from \"./inspect-parts\";\nimport { useAgentInspectScope } from \"./inspect-scope\";\nimport {\n AGENT_INSPECT_REQUESTS_PAGE_SIZE,\n type AgentInspectModelCallRow,\n buildAgentInspectModelCallRows,\n previousAgentInspectTracePage,\n readAgentInspectTraceCoverage,\n summarizeAgentInspectModelCalls,\n} from \"./model-call-rows\";\nimport { wordsOfIdentifier } from \"./step-descriptions\";\nimport { type AgentInspectTurnWindow, mergeAgentInspectTurns } from \"./turn-paging\";\n\nconst COLUMN_CONTEXT = \"agent-request-column\";\n\nconst END_CONTEXT = \"model-call-end\";\n\n/** How a model call ended, in words; another reason shows as its id in words. */\nconst END_LABELS: Readonly<Record<string, string>> = {\n toolCalls: m(\"called tools\", { context: \"model-call-end\" }),\n answer: m(\"answered\", { context: \"model-call-end\" }),\n empty: m(\"empty answer\", { context: \"model-call-end\" }),\n};\n\n/** Earlier pages read on their own, one after the other; beyond them the reader asks for each. */\nconst MAX_PAGES_READ_UNASKED = 4;\n\ninterface EarlierPageLoaderProps {\n window: AgentInspectTurnWindow;\n onLoaded: (fromTurnNumber: number, trace: AgentInspectTrace) => void;\n}\n\n/** Reads one earlier page of turns at the debug level and hands its trace up; draws only a failure. */\nconst EarlierPageLoader = ({ window, onLoaded }: EarlierPageLoaderProps) => {\n const { t } = useTranslate();\n const { api, conversationId } = useAgentInspectScope();\n const query = api.useTraceQuery({ conversationId, detailLevel: \"DEBUG\", fromTurnNumber: window.fromTurnNumber, limit: window.limit });\n const { currentData } = query;\n useEffect(() => {\n if (currentData !== undefined) onLoaded(window.fromTurnNumber, mapAgentInspectTrace(currentData));\n }, [currentData, onLoaded, window.fromTurnNumber]);\n if (!query.isError) return null;\n return <p className=\"text-xs text-destructive\">{normalizeDddError(query.error, t(\"The earlier turns could not be loaded.\")).message}</p>;\n};\n\n/** The costs of the whole conversation by where they came from, as its header names them. */\nexport type AgentInspectConversationCosts = Pick<\n AgentInspectConversationHeader,\n \"modelCallsCostInUSD\" | \"toolExecutionCostInUSD\" | \"overheadCostInUSD\" | \"subAgentsCostInUSD\" | \"treeCostInUSD\"\n>;\n\n/** The parts of the cost split, in order. */\nconst COST_PARTS: readonly { key: keyof AgentInspectConversationCosts; label: string }[] = [\n { key: \"modelCallsCostInUSD\", label: m(\"Model calls %cost%\", { context: \"agent-conversation-cost\" }) },\n { key: \"toolExecutionCostInUSD\", label: m(\"Tools %cost%\", { context: \"agent-conversation-cost\" }) },\n { key: \"overheadCostInUSD\", label: m(\"Overhead %cost%\", { context: \"agent-conversation-cost\" }) },\n { key: \"subAgentsCostInUSD\", label: m(\"Sub-agents %cost%\", { context: \"agent-conversation-cost\" }) },\n];\n\nexport interface RequestsPanelProps {\n /** The cost split of the whole conversation (all turns, not only the loaded ones), below the table. */\n conversationCosts?: AgentInspectConversationCosts | null;\n /** Conversations of sub-agents below this one: their model calls are listed on their own pages. */\n subAgentConversationCount?: number;\n /** Reads the newest turns again while a turn runs, every n ms (0 = off). */\n livePollingIntervalMs?: number;\n /** Turns read per page, at most 100. */\n pageSize?: number;\n}\n\n/**\n * The requests of a conversation: every model call as one row — turn, call number, model, effort, tokens in, out and\n * from the cache, cost, duration, how it ended and the tools it called — with the totals below. It reads the trace at\n * the debug level itself, whatever the Debug switch says (the tab is offered to a reader with the debug right), the\n * newest turns first and the earlier pages after them. A row opens what the model was sent at that call; the button\n * at its end opens the sent payload.\n */\nexport const RequestsPanel = ({\n conversationCosts = null,\n subAgentConversationCount = 0,\n livePollingIntervalMs = 0,\n pageSize = AGENT_INSPECT_REQUESTS_PAGE_SIZE,\n}: RequestsPanelProps) => {\n const { t } = useTranslate();\n const { api, conversationId, locale, formatCost, openModelContext } = useAgentInspectScope();\n const turnsPerPage = Math.min(100, Math.max(1, Math.floor(pageSize)));\n const format = useMemo(() => createTraceFormat(locale), [locale]);\n // Every part, also one of 0, so the parts add up to the whole.\n const costSplit =\n conversationCosts !== null && COST_PARTS.some((part) => typeof conversationCosts[part.key] === \"number\")\n ? COST_PARTS.map((part) => t(part.label, { context: \"agent-conversation-cost\", replacements: { cost: formatCost(conversationCosts[part.key] ?? 0) } }))\n : [];\n\n const [isRunLive, setIsRunLive] = useState(false);\n const newestQuery = api.useTraceQuery(\n { conversationId, detailLevel: \"DEBUG\", limit: turnsPerPage },\n { pollingInterval: isRunLive && livePollingIntervalMs > 0 ? livePollingIntervalMs : 0 },\n );\n const newestTrace = useMemo(() => (newestQuery.data ? mapAgentInspectTrace(newestQuery.data) : null), [newestQuery.data]);\n useEffect(() => setIsRunLive(newestTrace?.isRunLive === true), [newestTrace]);\n\n const [windows, setWindows] = useState<AgentInspectTurnWindow[]>([]);\n const [earlierPages, setEarlierPages] = useState<ReadonlyMap<number, AgentInspectTrace>>(new Map());\n // A page that answers again with what it held (a refetch) keeps its object, so nothing below it renders again.\n const addEarlierPage = useCallback(\n (fromTurnNumber: number, trace: AgentInspectTrace) =>\n setEarlierPages((pages) => {\n const heldPage = pages.get(fromTurnNumber);\n return heldPage !== undefined && JSON.stringify(heldPage) === JSON.stringify(trace) ? pages : new Map(pages).set(fromTurnNumber, trace);\n }),\n [],\n );\n\n // The newest page moves on while the conversation runs: the turns it held before stay, so no turn drops out between\n // it and the earlier pages.\n const newestTurnsSeenRef = useRef<AgentInspectTrace[\"turns\"]>([]);\n const newestTurnsSeen = useMemo(() => {\n if (newestTrace !== null) newestTurnsSeenRef.current = mergeAgentInspectTurns(newestTurnsSeenRef.current, newestTrace.turns);\n return newestTurnsSeenRef.current;\n }, [newestTrace]);\n\n const pages = useMemo(() => (newestTrace === null ? [] : [newestTrace, ...earlierPages.values()]), [newestTrace, earlierPages]);\n const coverage = useMemo(() => readAgentInspectTraceCoverage(pages), [pages]);\n const turns = useMemo(\n () => pages.reduce<AgentInspectTrace[\"turns\"]>((merged, page) => mergeAgentInspectTurns(merged, page.turns), newestTurnsSeen),\n [pages, newestTurnsSeen],\n );\n const rows = useMemo(() => buildAgentInspectModelCallRows(turns), [turns]);\n const totals = useMemo(() => summarizeAgentInspectModelCalls(rows), [rows]);\n\n const isReadingEarlier = windows.some((window) => !earlierPages.has(window.fromTurnNumber));\n const earlierWindow = isReadingEarlier ? null : previousAgentInspectTracePage(coverage, turnsPerPage);\n const earlierFrom = earlierWindow?.fromTurnNumber ?? null;\n const earlierLimit = earlierWindow?.limit ?? null;\n const readsEarlierUnasked = earlierFrom !== null && windows.length < MAX_PAGES_READ_UNASKED;\n const addWindow = useCallback(\n (fromTurnNumber: number, limit: number) =>\n setWindows((current) => (current.some((window) => window.fromTurnNumber === fromTurnNumber) ? current : [...current, { fromTurnNumber, limit }])),\n [],\n );\n useEffect(() => {\n if (readsEarlierUnasked && earlierFrom !== null && earlierLimit !== null) addWindow(earlierFrom, earlierLimit);\n }, [readsEarlierUnasked, earlierFrom, earlierLimit, addWindow]);\n\n if (newestQuery.isError) {\n return <StatusCallout tone=\"destructive\" title={t(\"The trace could not be loaded\")} description={normalizeDddError(newestQuery.error, t(\"The trace could not be loaded.\")).message} />;\n }\n if (newestTrace === null) return <Skeleton className=\"h-48 w-full rounded-2xl\" data-testid=\"agent-requests-loading\" />;\n if (newestTrace.turns.length === 0 && rows.length === 0) {\n return <StatusCallout tone=\"info\" title={t(\"No turn yet\")} description={t(\"The conversation holds no message that started a turn.\")} />;\n }\n\n const count = (value: number | null) => (value === null ? <EmptyValue /> : formatAgentInspectCount(value, locale));\n const percent = (value: number | null) => (value === null ? <EmptyValue /> : `${formatUiNumber(Math.round(value))} %`);\n const totalTurnCount = Math.max(newestTrace.totalTurnCount, coverage.lastTurnNumber ?? 0);\n const coveredTurns =\n coverage.firstTurnNumber !== null && coverage.lastTurnNumber !== null\n ? t(\"Turns %from%–%to% of %total%\", { replacements: { from: coverage.firstTurnNumber, to: coverage.lastTurnNumber, total: totalTurnCount } })\n : null;\n const timingsOf = (row: AgentInspectModelCallRow): string | undefined =>\n row.providerCallMs === null\n ? undefined\n : row.loopOverheadMs === null\n ? t(\"provider %duration%\", { replacements: { duration: format.duration(row.providerCallMs) } })\n : `${t(\"provider %duration%\", { replacements: { duration: format.duration(row.providerCallMs) } })} · ${t(\"loop %duration%\", { replacements: { duration: format.duration(row.loopOverheadMs) } })}`;\n const startedAtOf = (row: AgentInspectModelCallRow): string | undefined => {\n const startedAt = readTraceMoment(row.startedAt);\n return startedAt === null ? undefined : new Intl.DateTimeFormat(locale, { dateStyle: \"medium\", timeStyle: \"medium\" }).format(startedAt);\n };\n\n return (\n <div className=\"flex flex-col gap-3\" data-testid=\"agent-requests-panel\">\n {windows.map((window) => (\n <EarlierPageLoader key={`${window.fromTurnNumber}:${window.limit}`} window={window} onLoaded={addEarlierPage} />\n ))}\n <Card className=\"gap-0 py-0\">\n <CardContent className=\"flex flex-col gap-3 px-2 py-3.5\">\n <div className=\"flex flex-wrap items-center gap-x-3 gap-y-2 px-3\">\n <div className=\"min-w-0\">\n <h3 className=\"flex items-center gap-2 text-sm font-bold\">\n {t(\"Model calls of this conversation\")}\n {isRunLive ? <LiveDot label={t(\"A turn runs right now\")} /> : null}\n </h3>\n <p className=\"text-xs text-muted-foreground\">\n {t(\"A row opens what the model was sent at that call.\")}\n {subAgentConversationCount > 0\n ? ` ${t(\n \"{count, plural, one {The calls of the sub-agent's conversation are listed in that conversation (tab Delegation).} other {The calls of the # sub-agent conversations are listed in those conversations (tab Delegation).}}\",\n { count: subAgentConversationCount },\n )}`\n : null}\n </p>\n </div>\n <div className=\"ml-auto flex flex-wrap items-center gap-3\">\n {coveredTurns !== null ? (\n <span className=\"text-xs text-muted-foreground tabular-nums\" data-testid=\"agent-requests-coverage\">\n {coveredTurns}\n </span>\n ) : null}\n {isReadingEarlier ? <span className=\"text-xs text-muted-foreground\">{t(\"Reading earlier turns…\")}</span> : null}\n {earlierFrom !== null && earlierLimit !== null && !readsEarlierUnasked ? (\n <Button type=\"button\" variant=\"outline\" size=\"sm\" data-testid=\"agent-requests-load-earlier\" onClick={() => addWindow(earlierFrom, earlierLimit)}>\n <ChevronsUp />\n {t(\"Load earlier turns\")}\n </Button>\n ) : null}\n </div>\n </div>\n\n {rows.length === 0 ? (\n <p className=\"px-3 text-sm text-muted-foreground\" data-testid=\"agent-requests-empty\">\n {t(\"The loaded turns hold no model call.\")}\n </p>\n ) : (\n <Table className=\"min-w-[1080px]\" data-testid=\"agent-requests-table\">\n <TableHeader>\n <TableRow>\n <TableHead className=\"text-right\">{t(\"Turn\", { context: \"agent-request-column\" })}</TableHead>\n <TableHead className=\"text-right\">{t(\"Call\", { context: \"agent-request-column\" })}</TableHead>\n <TableHead>{t(\"Model\", { context: \"agent-request-column\" })}</TableHead>\n <TableHead>{t(\"Effort\", { context: \"agent-request-column\" })}</TableHead>\n <TableHead className=\"text-right\">{t(\"Tokens in\", { context: \"agent-request-column\" })}</TableHead>\n <TableHead className=\"text-right\">{t(\"Tokens out\", { context: \"agent-request-column\" })}</TableHead>\n <TableHead className=\"text-right\">{t(\"From the cache\", { context: \"agent-request-column\" })}</TableHead>\n <TableHead className=\"text-right\">{t(\"Cache\", { context: \"agent-request-column\" })}</TableHead>\n <TableHead className=\"text-right\">{t(\"Cost\", { context: \"agent-request-column\" })}</TableHead>\n <TableHead className=\"text-right\">{t(\"Duration\", { context: \"agent-request-column\" })}</TableHead>\n <TableHead>{t(\"Ended with\", { context: \"agent-request-column\" })}</TableHead>\n <TableHead>{t(\"Tools called\", { context: \"agent-request-column\" })}</TableHead>\n <TableHead className=\"w-10\">\n <span className=\"sr-only\">{t(\"Sent payload\")}</span>\n </TableHead>\n </TableRow>\n </TableHeader>\n <TableBody>\n {rows.map((row, position) => {\n const contextMessageId = row.contextMessageId;\n const isFirstOfTurn = position === 0 || rows[position - 1].turnNumber !== row.turnNumber;\n const endLabel = row.stopReason === null ? null : Object.hasOwn(END_LABELS, row.stopReason) ? t(END_LABELS[row.stopReason], { context: END_CONTEXT }) : wordsOfIdentifier(row.stopReason);\n const toolNames = row.toolNames.join(\", \");\n const callName = t(\"Turn %turn%, call %call%\", { replacements: { turn: row.turnNumber, call: row.callNumber } });\n const payloadTitle = row.hasStoredPayload ? t(\"Sent payload\") : `${t(\"Sent payload\")} · ${t(\"payload can only be rebuilt\")}`;\n return (\n <TableRow\n key={row.key}\n className={cn(contextMessageId !== null && \"cursor-pointer\", row.isTruncated && \"opacity-60\", isFirstOfTurn && position > 0 && \"border-t-2\")}\n onClick={contextMessageId !== null ? () => openModelContext(contextMessageId, \"composition\") : undefined}\n data-testid=\"agent-requests-row\"\n data-step-id={row.stepId}\n >\n <TableCell className=\"text-right text-[13px] font-semibold tabular-nums\" title={startedAtOf(row)}>\n {isFirstOfTurn ? row.turnNumber : <span className=\"sr-only\">{row.turnNumber}</span>}\n </TableCell>\n <TableCell className=\"text-right text-[13px] text-muted-foreground tabular-nums\">{row.callNumber}</TableCell>\n <TableCell className=\"max-w-48\">\n {contextMessageId !== null ? (\n <button\n type=\"button\"\n className=\"block max-w-full truncate text-left text-[13px] font-semibold hover:underline\"\n title={row.modelName ?? undefined}\n aria-label={`${callName}: ${t(\"What the model saw\")}`}\n >\n {row.modelLabel ?? row.modelName ?? \"—\"}\n </button>\n ) : (\n <span className=\"block truncate text-[13px] font-semibold\" title={row.modelName ?? undefined}>\n {row.modelLabel ?? row.modelName ?? <EmptyValue />}\n </span>\n )}\n </TableCell>\n <TableCell className=\"text-[13px] text-muted-foreground\">{row.effort ?? <EmptyValue />}</TableCell>\n <TableCell className=\"text-right text-[13px] tabular-nums\">{count(row.inputTokens)}</TableCell>\n <TableCell className=\"text-right text-[13px] tabular-nums\">{count(row.outputTokens)}</TableCell>\n <TableCell className=\"text-right text-[13px] tabular-nums\">{count(row.cachedInputTokens)}</TableCell>\n <TableCell className=\"text-right text-[13px] tabular-nums\">{percent(row.cachePercent)}</TableCell>\n <TableCell className=\"text-right text-[13px] whitespace-nowrap tabular-nums\">{row.costInUsd === null ? <EmptyValue /> : formatCost(row.costInUsd)}</TableCell>\n <TableCell className=\"text-right text-[13px] whitespace-nowrap tabular-nums\" title={timingsOf(row)}>\n {row.durationMs === null ? <EmptyValue /> : format.duration(row.durationMs)}\n </TableCell>\n <TableCell className=\"text-[13px] whitespace-nowrap\">\n <span className=\"inline-flex items-center gap-1.5\">\n {endLabel ?? <EmptyValue />}\n {row.retryCount > 0 ? (\n <StatusBadge tone=\"warning\" label={t(\"{count, plural, one {# retry} other {# retries}}\", { count: row.retryCount })} />\n ) : null}\n </span>\n </TableCell>\n <TableCell className=\"max-w-0 w-[22%]\">\n {toolNames === \"\" ? (\n <EmptyValue />\n ) : (\n <span className=\"block truncate font-mono text-xs text-muted-foreground\" title={toolNames}>\n {toolNames}\n </span>\n )}\n </TableCell>\n <TableCell className=\"w-10 text-right\">\n {contextMessageId !== null ? (\n <button\n type=\"button\"\n className=\"inline-flex size-7 items-center justify-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground\"\n title={payloadTitle}\n aria-label={`${callName}: ${payloadTitle}`}\n data-testid=\"agent-requests-open-payload\"\n onClick={(event) => {\n event.stopPropagation();\n openModelContext(contextMessageId, \"payload\");\n }}\n >\n <FileJson className=\"size-3.5\" aria-hidden />\n </button>\n ) : null}\n </TableCell>\n </TableRow>\n );\n })}\n </TableBody>\n <TableFooter>\n <TableRow data-testid=\"agent-requests-totals\">\n <TableCell colSpan={4} className=\"text-[13px]\">\n <span className=\"font-bold\">{t(\"Total\", { context: \"agent-request-column\" })}</span>\n <span className=\"font-normal text-muted-foreground\">\n {\" · \"}\n {t(\"{count, plural, one {# model call} other {# model calls}}\", { count: totals.callCount })}\n {coveredTurns !== null ? ` · ${coveredTurns}` : null}\n </span>\n </TableCell>\n <TableCell className=\"text-right text-[13px] tabular-nums\">{count(totals.inputTokens)}</TableCell>\n <TableCell className=\"text-right text-[13px] tabular-nums\">{count(totals.outputTokens)}</TableCell>\n <TableCell className=\"text-right text-[13px] tabular-nums\">{count(totals.cachedInputTokens)}</TableCell>\n <TableCell className=\"text-right text-[13px] tabular-nums\">{percent(totals.cachePercent)}</TableCell>\n <TableCell className=\"text-right text-[13px] whitespace-nowrap tabular-nums\">{totals.costInUsd === null ? <EmptyValue /> : formatCost(totals.costInUsd)}</TableCell>\n <TableCell className=\"text-right text-[13px] whitespace-nowrap tabular-nums\">{totals.durationMs === null ? <EmptyValue /> : format.duration(totals.durationMs)}</TableCell>\n <TableCell className=\"text-[13px] whitespace-nowrap\">\n {totals.retryCount > 0 ? t(\"{count, plural, one {# retry} other {# retries}}\", { count: totals.retryCount }) : null}\n </TableCell>\n <TableCell colSpan={2} />\n </TableRow>\n </TableFooter>\n </Table>\n )}\n {costSplit.length > 0 ? (\n <p className=\"mt-3 px-3 text-xs text-muted-foreground tabular-nums\" data-testid=\"agent-requests-cost-split\">\n <span className=\"font-semibold text-foreground\">\n {t(\"Whole conversation %cost%\", { replacements: { cost: formatCost(conversationCosts?.treeCostInUSD ?? 0) } })}\n </span>\n {\" = \"}\n {costSplit.join(\" + \")}\n </p>\n ) : null}\n </CardContent>\n </Card>\n </div>\n );\n};\n","import type { AgentInspectTouchedFile, AgentInspectTouchedMount } from \"./agent-inspect-types\";\n\n// The touched files of a sandbox as a tree: one group per mount, folders before files, each file with its history.\n// Pure, so the tree is covered by tests.\n\nexport interface TouchedFilesDirectoryNode {\n type: \"directory\";\n /** The folder's name; a chain of folders with nothing else in them is one node (`src/reports`). */\n name: string;\n /** The folder's path in its mount. */\n path: string;\n children: TouchedFilesNode[];\n}\n\nexport interface TouchedFilesFileNode {\n type: \"file\";\n name: string;\n path: string;\n file: AgentInspectTouchedFile;\n}\n\nexport type TouchedFilesNode = TouchedFilesDirectoryNode | TouchedFilesFileNode;\n\nexport interface TouchedFilesMountGroup {\n key: string;\n mountKind: string | null;\n mountName: string | null;\n driveSpaceId: number | null;\n fileCount: number;\n linesAdded: number;\n linesRemoved: number;\n nodes: TouchedFilesNode[];\n}\n\n/** The key of a file in the whole tree: its mount and its path. */\nexport const touchedFileKeyOf = (mountKey: string, path: string): string => `${mountKey}::${path}`;\n\n/** The key of a mount: its kind, its name and its drive space. */\nexport const touchedMountKeyOf = (mount: Pick<AgentInspectTouchedMount, \"mountKind\" | \"mountName\" | \"driveSpaceId\">): string =>\n `${mount.mountKind ?? \"\"}|${mount.mountName ?? \"\"}|${mount.driveSpaceId ?? \"\"}`;\n\nconst segmentsOf = (path: string): string[] => path.split(\"/\").filter((segment) => segment !== \"\");\n\nconst compareNodes = (first: TouchedFilesNode, second: TouchedFilesNode): number => {\n if (first.type !== second.type) return first.type === \"directory\" ? -1 : 1;\n return first.name.localeCompare(second.name, undefined, { numeric: true, sensitivity: \"base\" });\n};\n\n/** Folders before files, each by name; a folder whose only child is a folder is joined with it. */\nconst finishNodes = (nodes: TouchedFilesNode[]): TouchedFilesNode[] =>\n nodes\n .map((node): TouchedFilesNode => {\n if (node.type === \"file\") return node;\n let directory: TouchedFilesDirectoryNode = { ...node, children: finishNodes(node.children) };\n while (directory.children.length === 1 && directory.children[0].type === \"directory\") {\n const onlyChild = directory.children[0];\n directory = { type: \"directory\", name: `${directory.name}/${onlyChild.name}`, path: onlyChild.path, children: onlyChild.children };\n }\n return directory;\n })\n .sort(compareNodes);\n\n/** The files of one mount as a tree of folders. */\nexport const buildTouchedFilesNodes = (files: readonly AgentInspectTouchedFile[]): TouchedFilesNode[] => {\n const rootNodes: TouchedFilesNode[] = [];\n const directoryByPath = new Map<string, TouchedFilesDirectoryNode>();\n for (const file of files) {\n const segments = segmentsOf(file.path);\n if (segments.length === 0) continue;\n let siblings = rootNodes;\n let directoryPath = \"\";\n for (const segment of segments.slice(0, -1)) {\n directoryPath = directoryPath === \"\" ? segment : `${directoryPath}/${segment}`;\n let directory = directoryByPath.get(directoryPath);\n if (directory === undefined) {\n directory = { type: \"directory\", name: segment, path: directoryPath, children: [] };\n directoryByPath.set(directoryPath, directory);\n siblings.push(directory);\n }\n siblings = directory.children;\n }\n siblings.push({ type: \"file\", name: segments[segments.length - 1], path: file.path, file });\n }\n return finishNodes(rootNodes);\n};\n\n/** The touched files by mount, as trees; a mount without files is left out. */\nexport const buildTouchedFilesTree = (mounts: readonly AgentInspectTouchedMount[]): TouchedFilesMountGroup[] =>\n mounts\n .filter((mount) => mount.files.length > 0)\n .map((mount) => ({\n key: touchedMountKeyOf(mount),\n mountKind: mount.mountKind,\n mountName: mount.mountName,\n driveSpaceId: mount.driveSpaceId,\n fileCount: mount.files.length,\n linesAdded: mount.files.reduce((sum, file) => sum + file.linesAdded, 0),\n linesRemoved: mount.files.reduce((sum, file) => sum + file.linesRemoved, 0),\n nodes: buildTouchedFilesNodes(mount.files),\n }));\n\nexport interface TouchedFilesRow {\n key: string;\n /** 0 for a node directly below its mount. */\n depth: number;\n node: TouchedFilesNode;\n}\n\n/** The nodes of a mount as rows in display order, each with its depth; the folders named in `closedPaths` stay shut. */\nexport const flattenTouchedFilesNodes = (nodes: readonly TouchedFilesNode[], closedPaths: ReadonlySet<string> = new Set(), depth = 0): TouchedFilesRow[] =>\n nodes.flatMap((node): TouchedFilesRow[] => {\n const row: TouchedFilesRow = { key: `${node.type}:${node.path}`, depth, node };\n if (node.type === \"file\" || closedPaths.has(node.path)) return [row];\n return [row, ...flattenTouchedFilesNodes(node.children, closedPaths, depth + 1)];\n });\n\n/** The file of a key (`touchedFileKeyOf`) with its mount; null when the tree holds none. */\nexport const findTouchedFile = (\n mounts: readonly AgentInspectTouchedMount[],\n fileKey: string | null,\n): { mount: AgentInspectTouchedMount; file: AgentInspectTouchedFile } | null => {\n if (fileKey === null) return null;\n for (const mount of mounts) {\n const mountKey = touchedMountKeyOf(mount);\n const file = mount.files.find((candidate) => touchedFileKeyOf(mountKey, candidate.path) === fileKey);\n if (file) return { mount, file };\n }\n return null;\n};\n","import { normalizeDddError } from \"@mgamadeus/ddd-web/contract\";\nimport { codeLanguageOfExtension, CodeText, extensionOf } from \"@mgamadeus/ddd-admin-ui/files\";\nimport { formatUiNumber, m, useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { EmptyValue, Tag } from \"@mgamadeus/ddd-admin-ui/list\";\nimport { StatusCallout } from \"@mgamadeus/ddd-admin-ui/page\";\nimport { Card, CardContent, cn, SegmentedControl, Skeleton, Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { ChevronDown, ChevronRight, File, Folder, HardDrive, History } from \"lucide-react\";\nimport { type ReactNode, useCallback, useEffect, useMemo, useState } from \"react\";\nimport { readContentFromUnifiedDiff } from \"../../chat/trace/content-from-unified-diff\";\nimport { FileEditBlock } from \"../../chat/trace/FileEditBlock\";\nimport { TerminalBlock } from \"../../chat/trace/TerminalBlock\";\nimport {\n createTraceFormat,\n describeTraceMount,\n formatShortSha256,\n readTraceFileChangeLetter,\n readTraceFileName,\n readTraceMoment,\n readTraceStateOfStatus,\n} from \"../../chat/trace/trace-format\";\nimport type { TraceMountDescription } from \"../../chat/trace/trace-types\";\nimport { mapAgentInspectFileChanges, mapAgentInspectSandboxChronicle } from \"./agent-inspect-mappers\";\nimport type { AgentInspectFileChange, AgentInspectSandboxEntry } from \"./agent-inspect-types\";\nimport { AgentTraceFrame } from \"./inspect-parts\";\nimport { useAgentInspectScope } from \"./inspect-scope\";\nimport { buildTouchedFilesTree, findTouchedFile, flattenTouchedFilesNodes, touchedFileKeyOf, touchedMountKeyOf } from \"./touched-files-tree\";\n\nconst CHANGE_CONTEXT = \"agent-file-change\";\n\n/** The operations of a file change in words. */\nconst CHANGE_LABELS: Readonly<Record<string, string>> = {\n ADDED: m(\"added\", { context: \"agent-file-change\" }),\n MODIFIED: m(\"edited\", { context: \"agent-file-change\" }),\n DELETED: m(\"deleted\", { context: \"agent-file-change\" }),\n RENAMED: m(\"renamed\", { context: \"agent-file-change\" }),\n DIRECTORY_CREATED: m(\"new folder\", { context: \"agent-file-change\" }),\n};\n\nconst CHANGE_LETTER_CLASS_NAMES: Readonly<Record<string, string>> = {\n A: \"bg-success/15 text-success\",\n M: \"bg-info/15 text-info\",\n D: \"bg-destructive/15 text-destructive\",\n R: \"bg-warning/15 text-warning\",\n \"+\": \"bg-muted text-muted-foreground\",\n};\n\nconst MOUNT_TONE_CLASS_NAMES: Readonly<Record<NonNullable<TraceMountDescription[\"tone\"]>, string>> = {\n own: \"bg-brand-light text-brand-ink\",\n shared: \"bg-info/15 text-info\",\n external: \"bg-warning/15 text-warning\",\n neutral: \"bg-muted text-muted-foreground\",\n};\n\n/** The one-letter mark of a file operation (A, M, D, R, +). */\nexport const FileChangeLetter = ({ changeType }: { changeType: string | null | undefined }) => {\n const { t } = useTranslate();\n const letter = readTraceFileChangeLetter(changeType);\n const word = changeType && Object.hasOwn(CHANGE_LABELS, changeType) ? t(CHANGE_LABELS[changeType], { context: CHANGE_CONTEXT }) : undefined;\n return (\n <span\n className={cn(\"inline-flex size-5 shrink-0 items-center justify-center rounded-md text-[11px] font-bold\", CHANGE_LETTER_CLASS_NAMES[letter] ?? CHANGE_LETTER_CLASS_NAMES.M)}\n title={word}\n aria-label={word}\n >\n {letter}\n </span>\n );\n};\n\n/** The chip of a mount: the host's label and tint, else the mount's name. Nothing without a label. */\nexport const MountTag = ({ mountKind, mountName, driveSpaceId }: { mountKind: string | null; mountName: string | null; driveSpaceId: number | null }) => {\n const { describeMount } = useAgentInspectScope();\n const mount = describeTraceMount(describeMount, mountKind, mountName, driveSpaceId);\n if (mount === null) return null;\n return (\n <span className={cn(\"inline-flex h-5 max-w-44 items-center rounded-md px-1.5 text-[11px] font-semibold\", MOUNT_TONE_CLASS_NAMES[mount.tone ?? \"neutral\"])} title={mount.label}>\n <span className=\"truncate\">{mount.label}</span>\n </span>\n );\n};\n\n/** `+12 −3` of a change; nothing for a change without line counts. */\nexport const LineCounts = ({ linesAdded, linesRemoved }: { linesAdded: number | null; linesRemoved: number | null }) =>\n linesAdded === null && linesRemoved === null ? null : (\n <span className=\"whitespace-nowrap tabular-nums\">\n <span className=\"text-success\">+{formatUiNumber(linesAdded ?? 0)}</span> <span className=\"text-destructive\">−{formatUiNumber(linesRemoved ?? 0)}</span>\n </span>\n );\n\ntype FileChangeView = \"preview\" | \"diff\";\n\n/** The extensions of a Markdown file, lower case. */\nconst MARKDOWN_EXTENSIONS: readonly string[] = [\"md\", \"markdown\", \"mdx\"];\n\n/** The operations whose change holds no file content to rebuild. */\nconst CHANGE_TYPES_WITHOUT_CONTENT: readonly string[] = [\"DELETED\", \"DIRECTORY_CREATED\"];\n\n/** The diff a change carries in full (`INLINE` with its text); null when only its start, or nothing of it, is here. */\nconst readInlineDiffOf = (fileChange: AgentInspectFileChange): string | null =>\n fileChange.diffPreview && (fileChange.diffState ?? \"INLINE\") === \"INLINE\" ? fileChange.diffPreview : null;\n\n/** The whole diff of the change can be read: only its start is here (`STORED`), or a read at the level of steps left it out. */\nconst hasLoadableDiff = (fileChange: AgentInspectFileChange): boolean =>\n fileChange.id !== null && (fileChange.diffState === \"STORED\" || fileChange.hasStoredDiff || (fileChange.diffState === \"INLINE\" && !fileChange.diffPreview));\n\n/** The content of the file after the change, rebuilt from the change's diff; null when the diff does not hold the whole file. */\nconst rebuildContentOf = (fileChange: AgentInspectFileChange, diffText: string | null | undefined): string | null =>\n readContentFromUnifiedDiff(diffText, { changeType: fileChange.changeType, sizeAfter: fileChange.sizeAfter });\n\ninterface RecordedChangeContentProps {\n fileChange: AgentInspectFileChange;\n /** The content rebuilt from the diff the change carries in full; null: the whole diff is read first. */\n inlineContent: string | null;\n /** Told once the whole diff is read and does not hold the whole file (or could not be read). */\n onUnavailable: () => void;\n}\n\n/**\n * The file as the recorded change wrote it, rebuilt from the change's diff and drawn by its type: Markdown as markup\n * (the host's renderer), a source file with the host's highlighter, everything else as plain text — under a quiet\n * note that says where the content comes from. It is the stand-in for a stored version the drive cannot show. The\n * whole diff of a change that carries only its start is read when this block is first drawn.\n */\nconst RecordedChangeContent = ({ fileChange, inlineContent, onUnavailable }: RecordedChangeContentProps) => {\n const { t } = useTranslate();\n const { loadFullDiff, renderMarkdown, loadCodeHighlighter } = useAgentInspectScope();\n // undefined = being read, null = could not be read.\n const [loadedDiff, setLoadedDiff] = useState<string | null | undefined>(undefined);\n const needsLoad = inlineContent === null;\n useEffect(() => {\n if (!needsLoad) return undefined;\n let isCurrent = true;\n loadFullDiff(fileChange).then(\n (diff) => isCurrent && setLoadedDiff(diff),\n () => isCurrent && setLoadedDiff(null),\n );\n return () => {\n isCurrent = false;\n };\n }, [needsLoad, fileChange, loadFullDiff]);\n const loadedContent = useMemo(() => (needsLoad && loadedDiff ? rebuildContentOf(fileChange, loadedDiff) : null), [needsLoad, loadedDiff, fileChange]);\n const content = inlineContent ?? loadedContent;\n const isUnavailable = needsLoad && loadedDiff !== undefined && loadedContent === null;\n useEffect(() => {\n if (isUnavailable) onUnavailable();\n }, [isUnavailable, onUnavailable]);\n\n if (content === null) return isUnavailable ? null : <Skeleton className=\"m-4 h-40\" />;\n const extension = extensionOf(readTraceFileName(fileChange.path));\n const isMarkdown = renderMarkdown !== undefined && (MARKDOWN_EXTENSIONS.includes(extension) || fileChange.contentType === \"text/markdown\");\n const language = isMarkdown ? null : codeLanguageOfExtension(extension);\n return (\n <div className=\"flex h-full min-h-0 flex-col\" data-testid=\"agent-file-change-recorded-content\" data-content-kind={isMarkdown ? \"markdown\" : language !== null ? \"code\" : \"text\"}>\n <p\n className=\"flex shrink-0 items-center gap-1.5 border-b border-border px-3 py-1.5 text-xs text-muted-foreground\"\n title={t(\"The stored file cannot be shown here: this is its content as the recorded change wrote it.\")}\n >\n <History className=\"size-3.5 shrink-0\" aria-hidden />\n {t(\"From the recorded change\")}\n </p>\n {isMarkdown ? (\n <div className=\"min-h-0 flex-1 overflow-auto px-4 py-3 text-sm leading-6\">{renderMarkdown(content)}</div>\n ) : (\n <CodeText code={content} language={language} loadCodeHighlighter={loadCodeHighlighter} layout=\"canvas\" className=\"min-h-0 flex-1 rounded-none border-0 bg-transparent\" />\n )}\n </div>\n );\n};\n\nexport interface FileChangeViewerProps {\n /** The change whose file is shown. */\n fileChange: AgentInspectFileChange;\n /** The diff of the change against the version before (a file edit block, or the file's changes with their diffs). */\n children: ReactNode;\n}\n\n/**\n * One changed file with a switch between its preview and its diff to the version before. The preview is the host's\n * (`renderFilePreview`: the stored version of the file under the reader's own rights). Where the host has none to\n * show — a change without a stored version (a temporary file, a change that never reached the drive), or a stored\n * file it cannot show (gone, no read right, not released by the malware check) — and the change is text whose diff\n * holds the whole file (an added file, or hunks that span the file), the preview is that content rebuilt from the\n * diff, marked \"from the recorded change\". Otherwise the change shows its diff alone and says so.\n */\nexport const FileChangeViewer = ({ fileChange, children }: FileChangeViewerProps) => {\n const { t } = useTranslate();\n const { renderFilePreview } = useAgentInspectScope();\n const [pickedView, setPickedView] = useState<FileChangeView | null>(null);\n const [isRebuildUnavailable, setIsRebuildUnavailable] = useState(false);\n const markRebuildUnavailable = useCallback(() => setIsRebuildUnavailable(true), []);\n const holdsContent = !fileChange.isBinary && !CHANGE_TYPES_WITHOUT_CONTENT.includes(fileChange.changeType ?? \"\");\n const inlineDiff = holdsContent ? readInlineDiffOf(fileChange) : null;\n const inlineContent = useMemo(() => (inlineDiff !== null ? rebuildContentOf(fileChange, inlineDiff) : null), [fileChange, inlineDiff]);\n // A diff carried in full says at once whether it holds the whole file; one that is read first says so afterwards.\n const canRebuild = renderFilePreview !== undefined && holdsContent && (inlineDiff !== null ? inlineContent !== null : hasLoadableDiff(fileChange) && !isRebuildUnavailable);\n const recordedContent = canRebuild ? <RecordedChangeContent fileChange={fileChange} inlineContent={inlineContent} onUnavailable={markRebuildUnavailable} /> : null;\n const hostPreview = renderFilePreview?.(fileChange, { fallback: recordedContent }) ?? null;\n const preview = hostPreview !== null && hostPreview !== false ? hostPreview : recordedContent;\n const hasPreview = preview !== null;\n const view: FileChangeView = hasPreview ? (pickedView ?? \"preview\") : \"diff\";\n return (\n <div className=\"flex min-w-0 flex-col gap-2\" data-testid=\"agent-file-change-viewer\" data-view={view}>\n {renderFilePreview ? (\n <div className=\"flex flex-wrap items-center gap-x-3 gap-y-1\">\n <SegmentedControl\n aria-label={t(\"What of the file is shown\")}\n height={32}\n value={view}\n onValueChange={setPickedView}\n options={[\n { value: \"preview\", label: t(\"Preview\", { context: \"agent-file-view\" }), translate: false, disabled: !hasPreview },\n { value: \"diff\", label: t(\"Diff\", { context: \"agent-file-view\" }), translate: false },\n ]}\n />\n {hasPreview ? null : (\n <span className=\"text-xs text-muted-foreground\">\n {t(\"No stored version to preview (a temporary file, a change not in the drive, or a deleted file): the diff shows what changed.\")}\n </span>\n )}\n </div>\n ) : null}\n {view === \"preview\" ? (\n <div className=\"flex h-[min(60vh,36rem)] min-h-72 flex-col overflow-hidden rounded-xl bg-muted/40 shadow-[inset_0_0_0_1px_var(--border)]\" data-testid=\"agent-file-change-preview\">\n {preview}\n </div>\n ) : (\n children\n )}\n </div>\n );\n};\n\ntype ChronicleFilter = \"all\" | \"commands\" | \"files\";\n\n/**\n * The sandbox of a conversation: the chronicle (shell commands as terminal blocks and file changes, in time order),\n * the touched files as a tree by mount, and for the picked file its history with the diff of each change.\n */\nexport const SandboxPanel = () => {\n const { t } = useTranslate();\n const { api, conversationId, locale, describeMount, loadFullDiff, frameAttributes, host, fileSelection, renderSandboxFacts } = useAgentInspectScope();\n const query = api.useSandboxQuery({ conversationId });\n const chronicle = useMemo(() => (query.data ? mapAgentInspectSandboxChronicle(query.data) : null), [query.data]);\n const [filter, setFilter] = useState<ChronicleFilter>(\"all\");\n // The URL names the file by its path; the mount is remembered here, for a path that lies in two mounts.\n const [selectedMountKey, setSelectedMountKey] = useState<string | null>(null);\n const [closedPaths, setClosedPaths] = useState<ReadonlySet<string>>(new Set());\n const format = useMemo(() => createTraceFormat(locale), [locale]);\n const tree = useMemo(() => buildTouchedFilesTree(chronicle?.mounts ?? []), [chronicle]);\n\n if (query.isError) {\n return <StatusCallout tone=\"destructive\" title={t(\"The sandbox could not be loaded\")} description={normalizeDddError(query.error, t(\"The sandbox could not be loaded.\")).message} />;\n }\n if (chronicle === null) return <Skeleton className=\"h-48 w-full rounded-2xl\" />;\n if (chronicle.entries.length === 0 && tree.length === 0) {\n return <StatusCallout tone=\"info\" title={t(\"No sandbox use\")} description={t(\"This conversation ran no command and changed no file.\")} />;\n }\n\n const firstFile = chronicle.mounts.find((mount) => mount.files.length > 0);\n const mountsOfPath = fileSelection.filePath === null ? [] : chronicle.mounts.filter((mount) => mount.files.some((file) => file.path === fileSelection.filePath));\n const mountOfPath = mountsOfPath.find((mount) => touchedMountKeyOf(mount) === selectedMountKey) ?? mountsOfPath[0];\n const shownFileKey =\n mountOfPath && fileSelection.filePath !== null\n ? touchedFileKeyOf(touchedMountKeyOf(mountOfPath), fileSelection.filePath)\n : firstFile\n ? touchedFileKeyOf(touchedMountKeyOf(firstFile), firstFile.files[0].path)\n : null;\n const selected = findTouchedFile(chronicle.mounts, shownFileKey);\n const selectFile = (mountKey: string, path: string, fileChangeId: number | null = null) => {\n setSelectedMountKey(mountKey);\n fileSelection.select(path, fileChangeId);\n };\n const history = selected?.file.history ?? [];\n const pickedChangeIndex = fileSelection.fileChangeId === null ? -1 : history.findIndex((fileChange) => fileChange.id === fileSelection.fileChangeId);\n // The newest change of the file unless the link names another.\n const shownChangeIndex = pickedChangeIndex >= 0 ? pickedChangeIndex : history.length - 1;\n const shownChange = history[shownChangeIndex];\n const entries = chronicle.entries.filter((entry) => filter === \"all\" || (filter === \"commands\" ? entry.kind === \"COMMAND\" : entry.kind === \"FILE_CHANGE\"));\n const timeOf = (entry: AgentInspectSandboxEntry): string => {\n const moment = readTraceMoment(entry.at);\n return moment === null ? \"\" : new Intl.DateTimeFormat(locale, { timeStyle: \"medium\" }).format(moment);\n };\n const selectFileOf = (fileChange: AgentInspectFileChange) =>\n selectFile(touchedMountKeyOf({ mountKind: fileChange.mountKind, mountName: fileChange.mountName, driveSpaceId: fileChange.driveSpaceId }), fileChange.path, fileChange.id);\n const toggleDirectory = (path: string) =>\n setClosedPaths((current) => {\n const next = new Set(current);\n if (!next.delete(path)) next.add(path);\n return next;\n });\n\n return (\n <div className=\"grid grid-cols-1 gap-4 xl:grid-cols-[minmax(0,1.25fr)_minmax(0,1fr)]\" data-testid=\"agent-sandbox-panel\">\n <Card className=\"gap-0 self-start py-0\">\n <CardContent className=\"flex flex-col gap-3 px-5 py-4\">\n <div className=\"flex flex-wrap items-center justify-between gap-2\">\n <div>\n <h3 className=\"text-sm font-bold\">{t(\"Chronicle\")}</h3>\n <p className=\"text-xs text-muted-foreground\">\n {t(\"{count, plural, one {# command} other {# commands}}\", { count: chronicle.commandCount })} ·{\" \"}\n {t(\"{count, plural, one {# file change} other {# file changes}}\", { count: chronicle.fileChangeCount })} ·{\" \"}\n <LineCounts linesAdded={chronicle.linesAdded} linesRemoved={chronicle.linesRemoved} />\n </p>\n </div>\n <SegmentedControl\n aria-label={t(\"Entries of the chronicle\")}\n height={32}\n value={filter}\n onValueChange={setFilter}\n options={[\n { value: \"all\", label: t(\"All\", { context: \"agent-sandbox-filter\" }), translate: false },\n { value: \"commands\", label: t(\"Commands\", { context: \"agent-sandbox-filter\" }), translate: false },\n { value: \"files\", label: t(\"Files\", { context: \"agent-sandbox-filter\" }), translate: false },\n ]}\n />\n </div>\n <ol className=\"flex flex-col gap-2\" data-testid=\"agent-sandbox-chronicle\">\n {entries.map((entry) => (\n <li key={entry.key} className=\"grid grid-cols-[64px_minmax(0,1fr)] items-start gap-3\" data-entry-kind={entry.kind}>\n <span className=\"pt-1.5 text-xs text-muted-foreground tabular-nums\">{timeOf(entry)}</span>\n {entry.kind === \"COMMAND\" && entry.terminal ? (\n <AgentTraceFrame frameAttributes={frameAttributes}>\n <TerminalBlock {...entry.terminal} isRunning={readTraceStateOfStatus(entry.status) === \"running\"} maxLines={8} />\n </AgentTraceFrame>\n ) : entry.fileChange ? (\n <button\n type=\"button\"\n onClick={() => selectFileOf(entry.fileChange as AgentInspectFileChange)}\n className=\"flex min-w-0 items-center gap-2 rounded-lg px-2 py-1.5 text-left text-[13px] hover:bg-muted\"\n >\n <FileChangeLetter changeType={entry.fileChange.changeType} />\n <span className=\"min-w-0 truncate font-mono text-xs\" title={entry.fileChange.path}>\n {entry.fileChange.previousPath ? `${entry.fileChange.previousPath} → ` : \"\"}\n {entry.fileChange.path}\n </span>\n <MountTag mountKind={entry.fileChange.mountKind} mountName={entry.fileChange.mountName} driveSpaceId={entry.fileChange.driveSpaceId} />\n <span className=\"ml-auto flex shrink-0 items-center gap-2 text-xs text-muted-foreground\">\n <LineCounts linesAdded={entry.fileChange.linesAdded} linesRemoved={entry.fileChange.linesRemoved} />\n {entry.fileChange.sizeAfter !== null ? <span className=\"tabular-nums\">{format.bytes(entry.fileChange.sizeAfter)}</span> : null}\n </span>\n </button>\n ) : (\n <span className=\"pt-1.5 text-xs text-muted-foreground\">{entry.toolName ?? \"—\"}</span>\n )}\n </li>\n ))}\n </ol>\n </CardContent>\n </Card>\n\n <div className=\"flex min-w-0 flex-col gap-4\">\n {renderSandboxFacts?.() ?? null}\n <Card className=\"gap-0 py-0\">\n <CardContent className=\"flex flex-col gap-2 px-4 py-3.5\">\n <h3 className=\"text-sm font-bold\">{t(\"Touched files\")}</h3>\n {tree.length === 0 ? <p className=\"text-sm text-muted-foreground\">{t(\"No file was changed.\")}</p> : null}\n <div className=\"flex flex-col gap-2\" role=\"tree\" aria-label={t(\"Touched files\")} data-testid=\"agent-sandbox-tree\">\n {tree.map((mountGroup) => (\n <div key={mountGroup.key} role=\"group\" className=\"flex flex-col\">\n <div className=\"flex items-center gap-2 py-1 text-[13px]\">\n <HardDrive className=\"size-3.5 shrink-0 text-muted-foreground\" aria-hidden />\n <MountTag mountKind={mountGroup.mountKind} mountName={mountGroup.mountName} driveSpaceId={mountGroup.driveSpaceId} />\n <span className=\"ml-auto text-xs text-muted-foreground\">\n {t(\"{count, plural, one {# file} other {# files}}\", { count: mountGroup.fileCount })}\n </span>\n </div>\n {flattenTouchedFilesNodes(mountGroup.nodes, closedPaths).map((row) => {\n const indent = { paddingLeft: `${8 + row.depth * 16}px` };\n if (row.node.type === \"directory\") {\n const isClosed = closedPaths.has(row.node.path);\n const directoryPath = row.node.path;\n return (\n <button\n type=\"button\"\n key={row.key}\n role=\"treeitem\"\n aria-expanded={!isClosed}\n onClick={() => toggleDirectory(directoryPath)}\n className=\"flex h-7 items-center gap-1.5 rounded-md pr-2 text-left text-[13px] hover:bg-muted\"\n style={indent}\n >\n {isClosed ? <ChevronRight className=\"size-3.5 text-muted-foreground\" aria-hidden /> : <ChevronDown className=\"size-3.5 text-muted-foreground\" aria-hidden />}\n <Folder className=\"size-3.5 text-muted-foreground\" aria-hidden />\n <span className=\"truncate font-semibold\">{row.node.name}</span>\n </button>\n );\n }\n const fileKey = touchedFileKeyOf(mountGroup.key, row.node.path);\n const isDeleted = row.node.file.lastChangeType === \"DELETED\";\n return (\n <button\n type=\"button\"\n key={row.key}\n role=\"treeitem\"\n aria-selected={fileKey === shownFileKey}\n onClick={() => selectFile(mountGroup.key, row.node.path)}\n className={cn(\"flex h-7 items-center gap-1.5 rounded-md pr-2 text-left text-[13px] hover:bg-muted\", fileKey === shownFileKey && \"bg-muted font-semibold\")}\n style={{ paddingLeft: `${8 + row.depth * 16 + 20}px` }}\n data-testid=\"agent-sandbox-tree-file\"\n >\n <File className=\"size-3.5 shrink-0 text-muted-foreground\" aria-hidden />\n <span className={cn(\"truncate\", isDeleted && \"text-muted-foreground line-through\")}>{row.node.name}</span>\n <span className=\"ml-auto flex shrink-0 items-center gap-2 text-xs font-normal text-muted-foreground\">\n {row.node.file.changeCount > 1 ? <span>×{row.node.file.changeCount}</span> : null}\n <FileChangeLetter changeType={row.node.file.lastChangeType} />\n </span>\n </button>\n );\n })}\n </div>\n ))}\n </div>\n </CardContent>\n </Card>\n\n {selected !== null ? (\n <Card className=\"gap-0 py-0\" data-testid=\"agent-sandbox-file-history\">\n <CardContent className=\"flex flex-col gap-3 px-4 py-3.5\">\n <div>\n <h3 className=\"truncate font-mono text-[13px] font-bold\" title={selected.file.path}>\n {selected.file.path}\n </h3>\n <p className=\"text-xs text-muted-foreground\">\n {t(\"{count, plural, one {# change} other {# changes}}\", { count: selected.file.changeCount })} ·{\" \"}\n <LineCounts linesAdded={selected.file.linesAdded} linesRemoved={selected.file.linesRemoved} />\n </p>\n </div>\n <ol className=\"flex flex-col gap-0.5 text-xs\" data-testid=\"agent-sandbox-file-changes\">\n {history.map((fileChange, position) => {\n const changedAt = readTraceMoment(fileChange.changedAt);\n const isShown = position === shownChangeIndex;\n return (\n <li key={fileChange.id ?? position}>\n <button\n type=\"button\"\n aria-pressed={isShown}\n data-selected={isShown ? \"true\" : undefined}\n onClick={() => fileSelection.select(selected.file.path, fileChange.id)}\n className={cn(\"flex w-full flex-wrap items-center gap-x-2 gap-y-0.5 rounded-md px-1.5 py-1 text-left hover:bg-muted\", isShown && \"bg-muted font-semibold\")}\n >\n <FileChangeLetter changeType={fileChange.changeType} />\n {changedAt !== null ? <span className=\"tabular-nums\">{new Intl.DateTimeFormat(locale, { timeStyle: \"medium\" }).format(changedAt)}</span> : null}\n {fileChange.toolName ? <span className=\"font-mono font-normal text-muted-foreground\">{fileChange.toolName}</span> : null}\n <LineCounts linesAdded={fileChange.linesAdded} linesRemoved={fileChange.linesRemoved} />\n {fileChange.sizeAfter !== null ? <span className=\"font-normal text-muted-foreground tabular-nums\">{format.bytes(fileChange.sizeAfter)}</span> : null}\n {formatShortSha256(fileChange.sha256After) ? (\n <span className=\"font-mono font-normal text-muted-foreground\">sha256 {formatShortSha256(fileChange.sha256After)}</span>\n ) : null}\n </button>\n </li>\n );\n })}\n </ol>\n {shownChange ? (\n <FileChangeViewer key={`${shownFileKey}:${shownChange.id ?? shownChangeIndex}`} fileChange={shownChange}>\n <AgentTraceFrame frameAttributes={frameAttributes}>\n <FileEditBlock fileChange={shownChange} describeMount={describeMount} onLoadFullDiff={loadFullDiff} onOpenInViewer={host.openFileInViewer} isNarrow />\n </AgentTraceFrame>\n </FileChangeViewer>\n ) : null}\n </CardContent>\n </Card>\n ) : null}\n </div>\n </div>\n );\n};\n\n/**\n * Every file change of the conversation as a table (path, mount, operation, lines, size, tool, time); a row opens the\n * change's diff below the table.\n */\nexport const FilesPanel = () => {\n const { t } = useTranslate();\n const { api, conversationId, locale, describeMount, loadFullDiff, frameAttributes, host, fileSelection } = useAgentInspectScope();\n const query = api.useFileChangesQuery({ conversationId });\n const fileChanges = useMemo(() => (query.data ? mapAgentInspectFileChanges(query.data) : null), [query.data]);\n const format = useMemo(() => createTraceFormat(locale), [locale]);\n\n if (query.isError) {\n return <StatusCallout tone=\"destructive\" title={t(\"The file changes could not be loaded\")} description={normalizeDddError(query.error, t(\"The file changes could not be loaded.\")).message} />;\n }\n if (fileChanges === null) return <Skeleton className=\"h-48 w-full rounded-2xl\" />;\n if (fileChanges.length === 0) return <StatusCallout tone=\"info\" title={t(\"No file changes\")} description={t(\"This conversation changed no file.\")} />;\n\n // The change the link names; else the newest change of the file it names; else the first row.\n const changeOfLink = fileSelection.fileChangeId === null ? -1 : fileChanges.findIndex((fileChange) => fileChange.id === fileSelection.fileChangeId);\n const fileOfLink = fileSelection.filePath === null ? -1 : fileChanges.map((fileChange) => fileChange.path).lastIndexOf(fileSelection.filePath);\n const selectedIndex = changeOfLink >= 0 ? changeOfLink : fileOfLink >= 0 ? fileOfLink : 0;\n const selectedFileChange = fileChanges[selectedIndex];\n return (\n <div className=\"flex flex-col gap-4\" data-testid=\"agent-files-panel\">\n <Card className=\"gap-0 py-1\">\n <CardContent className=\"px-2\">\n <Table>\n <TableHeader>\n <TableRow>\n <TableHead>{t(\"Path\", { context: \"agent-file-change-column\" })}</TableHead>\n <TableHead>{t(\"Mount\", { context: \"agent-file-change-column\" })}</TableHead>\n <TableHead>{t(\"Operation\", { context: \"agent-file-change-column\" })}</TableHead>\n <TableHead className=\"text-right\">{t(\"Lines\", { context: \"agent-file-change-column\" })}</TableHead>\n <TableHead className=\"text-right\">{t(\"Size\", { context: \"agent-file-change-column\" })}</TableHead>\n <TableHead>{t(\"Tool\", { context: \"agent-file-change-column\" })}</TableHead>\n <TableHead className=\"text-right\">{t(\"Time\", { context: \"agent-file-change-column\" })}</TableHead>\n </TableRow>\n </TableHeader>\n <TableBody>\n {fileChanges.map((fileChange, index) => {\n const changedAt = readTraceMoment(fileChange.changedAt);\n const isSelected = fileChange === selectedFileChange;\n return (\n <TableRow\n key={fileChange.id ?? index}\n data-state={isSelected ? \"selected\" : undefined}\n className=\"cursor-pointer\"\n onClick={() => fileSelection.select(fileChange.path, fileChange.id)}\n data-testid=\"agent-files-row\"\n >\n <TableCell className=\"max-w-0 w-[40%]\">\n <button type=\"button\" className=\"block w-full truncate text-left font-mono text-xs\" title={fileChange.path} aria-pressed={isSelected}>\n {fileChange.previousPath ? <span className=\"text-muted-foreground\">{fileChange.previousPath} → </span> : null}\n {fileChange.path}\n </button>\n </TableCell>\n <TableCell>\n <MountTag mountKind={fileChange.mountKind} mountName={fileChange.mountName} driveSpaceId={fileChange.driveSpaceId} />\n </TableCell>\n <TableCell>\n <span className=\"inline-flex items-center gap-1.5 text-[13px]\">\n <FileChangeLetter changeType={fileChange.changeType} />\n {fileChange.changeType && Object.hasOwn(CHANGE_LABELS, fileChange.changeType) ? t(CHANGE_LABELS[fileChange.changeType], { context: CHANGE_CONTEXT }) : null}\n </span>\n </TableCell>\n <TableCell className=\"text-right text-[13px]\">\n {fileChange.linesAdded === null && fileChange.linesRemoved === null ? <EmptyValue /> : <LineCounts linesAdded={fileChange.linesAdded} linesRemoved={fileChange.linesRemoved} />}\n </TableCell>\n <TableCell className=\"text-right text-[13px] whitespace-nowrap tabular-nums\">\n {fileChange.sizeAfter !== null ? (\n <span title={fileChange.sizeBefore !== null ? `${format.bytes(fileChange.sizeBefore)} → ${format.bytes(fileChange.sizeAfter)}` : undefined}>{format.bytes(fileChange.sizeAfter)}</span>\n ) : (\n <EmptyValue />\n )}\n </TableCell>\n <TableCell className=\"font-mono text-xs text-muted-foreground\">{fileChange.toolName ?? \"—\"}</TableCell>\n <TableCell className=\"text-right text-[13px] whitespace-nowrap tabular-nums\">\n {changedAt !== null ? new Intl.DateTimeFormat(locale, { dateStyle: \"short\", timeStyle: \"medium\" }).format(changedAt) : <EmptyValue />}\n </TableCell>\n </TableRow>\n );\n })}\n </TableBody>\n </Table>\n </CardContent>\n </Card>\n {selectedFileChange ? (\n <Card className=\"gap-0 py-0\" data-testid=\"agent-files-diff\">\n <CardContent className=\"flex flex-col gap-2 px-4 py-3.5\">\n <div className=\"flex flex-wrap items-center gap-2\">\n <h3 className=\"text-sm font-bold\">{t(\"Change\")}</h3>\n {selectedFileChange.isBinary ? <Tag size=\"sm\">{t(\"binary file\")}</Tag> : null}\n </div>\n <FileChangeViewer key={selectedFileChange.id ?? selectedIndex} fileChange={selectedFileChange}>\n <AgentTraceFrame frameAttributes={frameAttributes}>\n <FileEditBlock fileChange={selectedFileChange} describeMount={describeMount} onLoadFullDiff={loadFullDiff} onOpenInViewer={host.openFileInViewer} />\n </AgentTraceFrame>\n </FileChangeViewer>\n </CardContent>\n </Card>\n ) : null}\n </div>\n );\n};\n","import { formatUiNumber, m, useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { StatusBadge, Tag } from \"@mgamadeus/ddd-admin-ui/list\";\nimport { StatusCallout } from \"@mgamadeus/ddd-admin-ui/page\";\nimport { Skeleton } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { type ReactNode, useMemo } from \"react\";\nimport { FileEditBlock } from \"../../chat/trace/FileEditBlock\";\nimport { LoadedSkillsDisclosure } from \"../../chat/trace/LoadedSkillsDisclosure\";\nimport { TerminalBlock } from \"../../chat/trace/TerminalBlock\";\nimport { readTaskPlanCountsOfStep } from \"../../chat/trace/task-plan-counts\";\nimport { ToolStepDetail } from \"../../chat/trace/ToolStepDetail\";\nimport { createTraceFormat, describeTraceModelName, readTraceMoment, readTraceStepState } from \"../../chat/trace/trace-format\";\nimport { CodeBlock } from \"../blocks/CodeBlock\";\nimport { DetailModal } from \"../blocks/DetailModal\";\nimport { ContextCompositionPanel } from \"../context/ContextCompositionPanel\";\nimport type { AgentInspectStep } from \"./agent-inspect-types\";\nimport { ChildConversationTrace, CompactionNodeLine, InspectStepExtras } from \"./ConversationTurns\";\nimport { formatAgentInspectCount } from \"./inspect-format\";\nimport { AgentTraceFrame } from \"./inspect-parts\";\nimport { useAgentInspectScope } from \"./inspect-scope\";\nimport { describeAgentDecision, formatJsonForReading, wordsOfIdentifier } from \"./step-descriptions\";\n\nconst KIND_CONTEXT = \"agent-step-kind\";\n\n/** The kinds of a step, in words. */\nconst KIND_LABELS: Readonly<Record<string, string>> = {\n THINKING: m(\"Model call\", { context: \"agent-step-kind\" }),\n MODEL_CALL: m(\"Model call\", { context: \"agent-step-kind\" }),\n TOOL_CALL: m(\"Tool call\", { context: \"agent-step-kind\" }),\n SKILL_LOAD: m(\"Skill load\", { context: \"agent-step-kind\" }),\n SUB_AGENT: m(\"Sub-agent\", { context: \"agent-step-kind\" }),\n WIDGET: m(\"Widget\", { context: \"agent-step-kind\" }),\n COMPACTION: m(\"Compaction\", { context: \"agent-step-kind\" }),\n SIGNAL: m(\"Signal\", { context: \"agent-step-kind\" }),\n DECISION: m(\"Decision\", { context: \"agent-step-kind\" }),\n TASK_PLAN: m(\"Task plan\", { context: \"agent-step-kind\" }),\n ERROR: m(\"Error\", { context: \"agent-step-kind\" }),\n};\n\nconst STATE_CONTEXT = \"agent-step-state\";\n\n/** Where a step stands, in words and tone. */\nconst STATE_LABELS: Readonly<Record<string, { label: string; tone: \"neutral\" | \"success\" | \"danger\" | \"warning\" | \"info\" }>> = {\n done: { label: m(\"done\", { context: \"agent-step-state\" }), tone: \"success\" },\n running: { label: m(\"running\", { context: \"agent-step-state\" }), tone: \"info\" },\n failed: { label: m(\"failed\", { context: \"agent-step-state\" }), tone: \"danger\" },\n waiting: { label: m(\"waiting\", { context: \"agent-step-state\" }), tone: \"warning\" },\n refused: { label: m(\"not run\", { context: \"agent-step-state\" }), tone: \"neutral\" },\n};\n\ninterface FactListProps {\n /** Caption and value of each fact; a fact without a value is left out. */\n facts: readonly (readonly [caption: string, value: ReactNode])[];\n}\n\n/** The facts of a step as a grid of captions and values. */\nconst FactList = ({ facts }: FactListProps) => {\n const shownFacts = facts.filter(([, value]) => value !== null && value !== undefined && value !== \"\" && value !== false);\n if (shownFacts.length === 0) return null;\n return (\n <dl className=\"grid grid-cols-2 gap-x-4 gap-y-2.5 sm:grid-cols-3 lg:grid-cols-4\" data-slot=\"agent-step-facts\">\n {shownFacts.map(([caption, value]) => (\n <div key={caption} className=\"min-w-0\">\n <dt className=\"text-[11px] font-semibold tracking-wide text-muted-foreground uppercase\">{caption}</dt>\n <dd className=\"break-words text-sm font-semibold text-foreground\">{value}</dd>\n </div>\n ))}\n </dl>\n );\n};\n\n/** A part of the detail under its heading. */\nconst DetailSection = ({ title, aside, children }: { title: string; aside?: ReactNode; children: ReactNode }) => (\n <section className=\"flex min-w-0 flex-col gap-2\">\n <div className=\"flex flex-wrap items-center gap-2\">\n <h3 className=\"text-sm font-bold\">{title}</h3>\n {aside}\n </div>\n {children}\n </section>\n);\n\n/** A JSON text of a step with the mark of a cut one. */\nconst JsonSection = ({ title, json, isCut }: { title: string; json: string | null | undefined; isCut?: boolean }) => {\n const { t } = useTranslate();\n if (!json) return null;\n return (\n <DetailSection title={title} aside={isCut ? <Tag size=\"sm\">{t(\"shortened\", { context: \"agent-inspect\" })}</Tag> : undefined}>\n <CodeBlock code={formatJsonForReading(json)} language=\"json\" aria-label={title} />\n </DetailSection>\n );\n};\n\n/** The detail of a side decision: where, what decided, how it ended, and what went in and came out. */\nconst DecisionDetail = ({ step }: { step: AgentInspectStep }) => {\n const { t } = useTranslate();\n const { locale } = useAgentInspectScope();\n const format = useMemo(() => createTraceFormat(locale), [locale]);\n const decision = step.decision;\n if (!decision) return null;\n const words = describeAgentDecision(decision, (text, context) => t(text, { context }));\n const probabilities = decision.probabilities ?? [];\n return (\n <>\n {words.summary ? <p className=\"rounded-xl bg-muted px-3 py-2 text-sm font-semibold\">{words.summary}</p> : null}\n <FactList\n facts={[\n [t(\"Decision\", { context: \"agent-step-fact\" }), words.site],\n [t(\"Decided by\", { context: \"agent-step-fact\" }), words.engine],\n [t(\"Status\", { context: \"agent-step-fact\" }), words.status ? <StatusBadge tone={words.statusTone} label={words.status} /> : null],\n [t(\"Model\", { context: \"agent-step-fact\" }), decision.modelVersion ?? decision.modelName],\n [t(\"Duration\", { context: \"agent-step-fact\" }), decision.durationMs !== null ? format.duration(decision.durationMs) : null],\n [t(\"Confidence\", { context: \"agent-step-fact\" }), decision.confidence !== null ? formatUiNumber(decision.confidence, { maximumFractionDigits: 2 }) : null],\n [t(\"Mode\", { context: \"agent-step-fact\" }), decision.mode],\n [t(\"Subject\", { context: \"agent-step-fact\" }), decision.subject],\n [t(\"No action because\", { context: \"agent-step-fact\" }), decision.skipReason ? wordsOfIdentifier(decision.skipReason) : null],\n [t(\"Fallback because\", { context: \"agent-step-fact\" }), decision.fallbackReason],\n ]}\n />\n {probabilities.length > 0 ? (\n <DetailSection title={t(\"Probabilities\")}>\n <ul className=\"flex flex-col gap-1 text-xs\" data-slot=\"agent-decision-probabilities\">\n {probabilities.map((entry) => (\n <li key={entry.name} className=\"grid grid-cols-[minmax(0,14rem)_minmax(0,1fr)_3rem] items-center gap-2\">\n <span className=\"truncate font-mono\" title={entry.name}>\n {entry.name}\n </span>\n <span className=\"h-1.5 overflow-hidden rounded-full bg-muted\">\n <span className=\"block h-full rounded-full bg-brand\" style={{ width: `${Math.max(0, Math.min(1, entry.probability)) * 100}%` }} />\n </span>\n <span className=\"text-right tabular-nums\">{formatUiNumber(entry.probability, { maximumFractionDigits: 2 })}</span>\n </li>\n ))}\n </ul>\n </DetailSection>\n ) : null}\n <JsonSection title={t(\"Input\", { context: \"agent-step-section\" })} json={decision.inputJson} isCut={decision.isInputCut} />\n <JsonSection title={t(\"Questions\", { context: \"agent-step-section\" })} json={decision.questionsJson} isCut={decision.isQuestionsCut} />\n <JsonSection title={t(\"Output\", { context: \"agent-step-section\" })} json={decision.outputJson} isCut={decision.isOutputCut} />\n <JsonSection title={t(\"Outcome\", { context: \"agent-step-section\" })} json={decision.outcomeJson} isCut={decision.isOutcomeCut} />\n {!decision.inputJson && !decision.outputJson && !decision.outcomeJson ? (\n <p className=\"text-xs text-muted-foreground\">{t(\"The call behind this decision is not stored any more: only its result is kept.\")}</p>\n ) : null}\n </>\n );\n};\n\n/** The detail of a model call: its figures and the context of this call. */\nconst ModelCallDetail = ({ step }: { step: AgentInspectStep }) => {\n const { t } = useTranslate();\n const { api, conversationId, locale, formatCost, renderMarkdown, canReadModelContext, isDebug, openModelContext } = useAgentInspectScope();\n const format = useMemo(() => createTraceFormat(locale), [locale]);\n const modelCall = step.modelCall;\n const count = (value: number | null | undefined) => (value == null ? null : formatAgentInspectCount(value, locale));\n const contextMessageId = step.contextMessageId ?? step.messageId;\n return (\n <>\n <FactList\n facts={[\n [t(\"Model\", { context: \"agent-step-fact\" }), step.modelLabel ?? describeTraceModelName(modelCall?.modelName)],\n [t(\"Model name\", { context: \"agent-step-fact\" }), modelCall?.modelName ? <span className=\"font-mono text-xs\">{modelCall.modelName}</span> : null],\n [t(\"Effort\", { context: \"agent-step-fact\" }), modelCall?.effort],\n [t(\"Call in the turn\", { context: \"agent-step-fact\" }), modelCall?.callNumberInTurn],\n [t(\"Duration\", { context: \"agent-step-fact\" }), step.durationMs !== null ? format.duration(step.durationMs) : null],\n [t(\"Tokens in\", { context: \"agent-step-fact\" }), count(modelCall?.inputTokens)],\n [t(\"Tokens out\", { context: \"agent-step-fact\" }), count(modelCall?.outputTokens)],\n [\n t(\"From the cache\", { context: \"agent-step-fact\" }),\n modelCall?.cachedInputTokens != null\n ? `${count(modelCall.cachedInputTokens)}${modelCall.cachePercent != null ? ` (${formatUiNumber(modelCall.cachePercent, { maximumFractionDigits: 0 })} %)` : \"\"}`\n : null,\n ],\n [t(\"Written to the cache\", { context: \"agent-step-fact\" }), count(modelCall?.cacheWriteTokens)],\n [t(\"Reasoning tokens\", { context: \"agent-step-fact\" }), count(modelCall?.reasoningTokens)],\n [t(\"Cost\", { context: \"agent-step-fact\" }), modelCall?.costInUsd != null ? formatCost(modelCall.costInUsd) : null],\n [t(\"Provider time\", { context: \"agent-step-fact\" }), modelCall?.providerCallMs != null ? format.duration(modelCall.providerCallMs) : null],\n [t(\"Loop time\", { context: \"agent-step-fact\" }), modelCall?.loopOverheadMs != null ? format.duration(modelCall.loopOverheadMs) : null],\n [t(\"Wire API\", { context: \"agent-step-fact\" }), modelCall?.wireApi],\n [t(\"Ended with\", { context: \"agent-step-fact\" }), modelCall?.stopReason ? wordsOfIdentifier(modelCall.stopReason) : null],\n [t(\"Called tools\", { context: \"agent-step-fact\" }), (modelCall?.toolNames ?? []).length > 0 ? <span className=\"font-mono text-xs\">{(modelCall?.toolNames ?? []).join(\", \")}</span> : null],\n [t(\"Forced tool\", { context: \"agent-step-fact\" }), modelCall?.forcedToolChoice],\n [t(\"Tool delivery\", { context: \"agent-step-fact\" }), modelCall?.toolDelivery ? wordsOfIdentifier(modelCall.toolDelivery) : null],\n [t(\"Retries\", { context: \"agent-step-fact\" }), modelCall?.retryCount != null && modelCall.retryCount > 0 ? modelCall.retryCount : null],\n ]}\n />\n {(step.loadedSkills ?? []).length > 0 ? <LoadedSkillsDisclosure skills={step.loadedSkills ?? []} /> : null}\n {contextMessageId !== null && canReadModelContext ? (\n <DetailSection\n title={t(\"Context of this call\")}\n aside={\n isDebug ? (\n <button type=\"button\" className=\"text-xs font-semibold text-brand-emphasis hover:underline\" onClick={() => openModelContext(contextMessageId, \"payload\")}>\n {t(\"Sent payload\")}\n </button>\n ) : undefined\n }\n >\n <ContextCompositionPanel key={contextMessageId} api={api.context} conversationId={conversationId} messageId={contextMessageId} renderMarkdown={renderMarkdown} />\n </DetailSection>\n ) : null}\n </>\n );\n};\n\n/** The detail of a tool call, a skill load or a plan update: what was called with what, and what came back. */\nconst ToolCallDetail = ({ step }: { step: AgentInspectStep }) => {\n const { t } = useTranslate();\n const { locale, formatCost, describeMount, loadFullDiff, host } = useAgentInspectScope();\n const format = useMemo(() => createTraceFormat(locale), [locale]);\n const skillLoad = step.skillLoad;\n const skillEntries = skillLoad?.skills ?? [];\n const planItems = step.taskPlanItems ?? [];\n return (\n <>\n <FactList\n facts={[\n [t(\"Tool\", { context: \"agent-step-fact\" }), step.toolName ? <span className=\"font-mono text-xs\">{step.toolName}</span> : null],\n [t(\"Reached through\", { context: \"agent-step-fact\" }), step.deliveredThroughCallTool ? <span className=\"font-mono text-xs\">call_tool</span> : null],\n [t(\"Effect\", { context: \"agent-step-fact\" }), step.effect],\n [t(\"Duration\", { context: \"agent-step-fact\" }), step.durationMs !== null ? format.duration(step.durationMs) : null],\n [t(\"Brought by\", { context: \"agent-step-fact\" }), (step.toolSkillNames ?? []).length > 0 ? <span className=\"font-mono text-xs\">{(step.toolSkillNames ?? []).join(\", \")}</span> : null],\n [t(\"Execution cost\", { context: \"agent-step-fact\" }), step.executionCostInUsd !== null ? formatCost(step.executionCostInUsd) : null],\n [t(\"Plan\", { context: \"agent-step-fact\" }), step.taskPlanTitle],\n [\n t(\"Plan items done\", { context: \"agent-step-fact\" }),\n step.taskPlanItemCount != null ? t(\"%done% of %total%\", { replacements: { done: readTaskPlanCountsOfStep(step).done, total: step.taskPlanItemCount } }) : null,\n ],\n [t(\"Loaded\", { context: \"agent-step-fact\" }), skillLoad?.loadedCount],\n [t(\"Not loaded\", { context: \"agent-step-fact\" }), skillLoad?.notLoadedCount != null && skillLoad.notLoadedCount > 0 ? skillLoad.notLoadedCount : null],\n ]}\n />\n {step.line && step.line !== step.toolName ? <p className=\"text-sm text-muted-foreground\">{step.line}</p> : null}\n {skillEntries.length > 0 ? (\n <DetailSection title={t(\"Skills of this load\")}>\n <ul className=\"flex flex-col gap-1 text-xs\" data-slot=\"agent-step-skill-load\">\n {skillEntries.map((skill) => (\n <li key={skill.name} className=\"flex flex-wrap items-center gap-x-2 gap-y-0.5\">\n <span className=\"font-mono font-semibold\">{skill.name}</span>\n {skill.outcome ? <Tag size=\"sm\">{wordsOfIdentifier(skill.outcome.toLowerCase().replace(/_([a-z])/g, (_match, letter: string) => letter.toUpperCase()))}</Tag> : null}\n {skill.cause ? <span className=\"text-muted-foreground\">{wordsOfIdentifier(skill.cause.toLowerCase().replace(/_([a-z])/g, (_match, letter: string) => letter.toUpperCase()))}</span> : null}\n {skill.residentTokens !== null ? (\n <span className=\"text-muted-foreground tabular-nums\">{t(\"%count% tokens\", { replacements: { count: formatAgentInspectCount(skill.residentTokens, locale) } })}</span>\n ) : null}\n </li>\n ))}\n </ul>\n {skillLoad?.notLoadedText ? <p className=\"text-xs text-muted-foreground\">{skillLoad.notLoadedText}</p> : null}\n </DetailSection>\n ) : (step.loadedSkillNames ?? []).length > 0 ? (\n <DetailSection title={t(\"Skills of this load\")}>\n <p className=\"font-mono text-xs\">{(step.loadedSkillNames ?? []).join(\", \")}</p>\n </DetailSection>\n ) : null}\n {planItems.length > 0 ? (\n <DetailSection title={t(\"Items of the plan\")}>\n <ol className=\"flex flex-col gap-0.5 text-xs\" data-slot=\"agent-step-plan-items\">\n {planItems.map((item) => (\n <li key={item.key} className=\"flex items-baseline gap-2\" style={{ paddingLeft: `${Math.max(0, item.depth) * 14}px` }}>\n <span className=\"text-muted-foreground tabular-nums\">{item.numberPath}</span>\n <span className=\"min-w-0 flex-1\">{item.title}</span>\n {item.status ? <span className=\"text-muted-foreground\">{item.status.toLowerCase().replace(/_/g, \" \")}</span> : null}\n </li>\n ))}\n </ol>\n </DetailSection>\n ) : null}\n {step.terminal ? <TerminalBlock {...step.terminal} /> : null}\n {step.fileChanges.map((fileChange, index) => (\n <FileEditBlock key={`${fileChange.id ?? index}:${fileChange.path}`} fileChange={fileChange} describeMount={describeMount} onLoadFullDiff={loadFullDiff} onOpenInViewer={host.openFileInViewer} />\n ))}\n <ToolStepDetail\n argumentsJson={step.argumentsJson}\n isArgumentsCut={step.isArgumentsCut}\n result={step.terminal ? null : step.result}\n resultChars={step.resultChars}\n isResultCut={step.isResultCut}\n errorText={step.errorText}\n formatCost={formatCost}\n />\n </>\n );\n};\n\n/** The detail of a delegation: the task, where it stands, and the sub-agent's own trace. */\nconst SubAgentDetail = ({ step }: { step: AgentInspectStep }) => {\n const { t } = useTranslate();\n const { locale, formatCost, buildConversationHref, linkComponent: Link } = useAgentInspectScope();\n const subAgent = step.subAgent;\n if (!subAgent) return null;\n const childHref = subAgent.childConversationId !== null ? (buildConversationHref?.(subAgent.childConversationId) ?? null) : null;\n const newestRun = subAgent.runs[subAgent.runs.length - 1];\n return (\n <>\n <FactList\n facts={[\n [t(\"Sub-agent\", { context: \"agent-step-fact\" }), subAgent.label],\n [t(\"Status\", { context: \"agent-step-fact\" }), subAgent.status ? subAgent.status.toLowerCase().replace(/_/g, \" \") : null],\n [t(\"Model\", { context: \"agent-step-fact\" }), subAgent.modelName ? <span title={subAgent.modelName}>{describeTraceModelName(subAgent.modelName)}</span> : null],\n [t(\"Cost\", { context: \"agent-step-fact\" }), subAgent.costInUsd !== null ? formatCost(subAgent.costInUsd) : null],\n [\n t(\"Tokens\", { context: \"agent-step-fact\" }),\n subAgent.inputTokens !== null ? formatAgentInspectCount((subAgent.inputTokens ?? 0) + (subAgent.outputTokens ?? 0), locale) : null,\n ],\n [t(\"Runs\", { context: \"agent-step-fact\" }), subAgent.runs.length > 1 ? subAgent.runs.length : null],\n [t(\"Skills\", { context: \"agent-step-fact\" }), subAgent.skillNames.length > 0 ? <span className=\"font-mono text-xs\">{subAgent.skillNames.join(\", \")}</span> : null],\n [\n t(\"Conversation\", { context: \"agent-step-fact\" }),\n childHref !== null ? (\n <Link href={childHref} className=\"text-brand-emphasis hover:underline\">\n #{subAgent.childConversationId}\n </Link>\n ) : subAgent.childConversationId !== null ? (\n `#${subAgent.childConversationId}`\n ) : null,\n ],\n ]}\n />\n {subAgent.taskText ? (\n <DetailSection title={t(\"Task\", { context: \"agent-step-section\" })}>\n <p className=\"max-h-60 overflow-auto whitespace-pre-wrap break-words rounded-xl bg-muted px-3 py-2 text-xs leading-5\">{subAgent.taskText}</p>\n </DetailSection>\n ) : null}\n {newestRun?.verdict || newestRun?.failureReason ? (\n <DetailSection title={t(\"Verdict\", { context: \"agent-step-section\" })}>\n <p className=\"max-h-60 overflow-auto whitespace-pre-wrap break-words rounded-xl bg-muted px-3 py-2 text-xs leading-5\">{newestRun.verdict ?? newestRun.failureReason}</p>\n </DetailSection>\n ) : null}\n {subAgent.childConversationId !== null ? (\n <DetailSection title={t(\"Trace of the sub-agent\")}>\n <ChildConversationTrace conversationId={subAgent.childConversationId} />\n </DetailSection>\n ) : null}\n </>\n );\n};\n\n/** The detail of the kinds that carry one text or one block: a signal, a widget, a compaction, an error. */\nconst PlainStepDetail = ({ step }: { step: AgentInspectStep }) => {\n const { t } = useTranslate();\n const signalText = step.signal?.text ?? step.signalText;\n return (\n <>\n <FactList\n facts={[\n [t(\"Source\", { context: \"agent-step-fact\" }), step.signal?.source ?? step.signalSource],\n [t(\"Signal kind\", { context: \"agent-step-fact\" }), step.signal?.kind],\n [t(\"Widget\", { context: \"agent-step-fact\" }), step.widget?.type],\n [t(\"Written by\", { context: \"agent-step-fact\" }), step.widget?.emittedBy],\n [t(\"Title\", { context: \"agent-step-fact\" }), step.widget?.title],\n [t(\"Error code\", { context: \"agent-step-fact\" }), step.errorCode],\n [t(\"Turn went on\", { context: \"agent-step-fact\" }), step.kind === \"ERROR\" && step.wasRetried ? t(\"yes, with another model call\") : null],\n ]}\n />\n {step.widget?.summary ? <p className=\"text-sm text-muted-foreground\">{step.widget.summary}</p> : null}\n {step.widget && !step.widget.isValid ? <StatusCallout size=\"compact\" tone=\"warning\" title={t(\"not a readable widget\")} /> : null}\n {signalText ? (\n <DetailSection\n title={t(\"Text of the signal\")}\n aside={step.signal?.isTextCut ? <Tag size=\"sm\">{t(\"shortened\", { context: \"agent-inspect\" })}</Tag> : undefined}\n >\n <p className=\"max-h-96 overflow-auto whitespace-pre-wrap break-words rounded-xl bg-muted px-3 py-2 text-xs leading-5\">{signalText}</p>\n </DetailSection>\n ) : null}\n {step.compactionNode ? <CompactionNodeLine node={step.compactionNode} /> : null}\n <JsonSection title={t(\"Facts kept beside the summary\")} json={step.compaction?.preservedFactsJson} />\n <JsonSection title={t(\"Fields of the widget\")} json={step.widget?.payloadJson} isCut={step.widget?.isPayloadCut} />\n {step.errorText ? <StatusCallout size=\"compact\" tone=\"destructive\" title={step.errorText} /> : null}\n </>\n );\n};\n\nexport interface StepDetailDialogProps {\n /** The id a link names (`?step=`); null closes the dialog. */\n stepId: string | null;\n /** The step of that id among the loaded turns; null when it is not among them. */\n step: AgentInspectStep | null;\n /** The turns are still being read (or earlier pages are looked through), so a missing step may yet arrive. */\n isLoading: boolean;\n /** The reader may switch to the debug level and has not: the note of an unresolved step names it as a way. */\n canSwitchToDebug?: boolean;\n onClose: () => void;\n}\n\n/**\n * One step of a conversation in full, beside the conversation: a side decision with its input and output, a model\n * call with its figures and the context of that very call, a tool call with arguments, result, terminal and file\n * edits, a skill load, a delegation with the sub-agent's trace, a compaction, a signal, a widget. The link `?step=`\n * names it, so a step can be passed on.\n */\nexport const StepDetailDialog = ({ stepId, step, isLoading, canSwitchToDebug = false, onClose }: StepDetailDialogProps) => {\n const { t } = useTranslate();\n const { locale, frameAttributes } = useAgentInspectScope();\n const format = useMemo(() => createTraceFormat(locale), [locale]);\n const kindLabel = step !== null && Object.hasOwn(KIND_LABELS, step.kind) ? t(KIND_LABELS[step.kind], { context: KIND_CONTEXT }) : (step?.kind ?? \"\");\n const name =\n step === null\n ? null\n : step.kind === \"DECISION\"\n ? (step.decision?.siteLabel ?? (step.decision?.site ? wordsOfIdentifier(step.decision.site) : null))\n : step.kind === \"MODEL_CALL\" || step.kind === \"THINKING\"\n ? (step.modelLabel ?? describeTraceModelName(step.modelCall?.modelName))\n : step.kind === \"SUB_AGENT\"\n ? (step.subAgent?.label ?? null)\n : step.kind === \"WIDGET\"\n ? step.widgetType\n : step.toolName;\n const state = step !== null ? readTraceStepState(step) : null;\n const startedAt = step !== null ? readTraceMoment(step.startedAt) : null;\n const facts = [\n step?.turnNumber != null ? t(\"Turn %number%\", { replacements: { number: step.turnNumber } }) : null,\n startedAt !== null ? new Intl.DateTimeFormat(locale, { dateStyle: \"medium\", timeStyle: \"medium\" }).format(startedAt) : null,\n step?.durationMs != null ? format.duration(step.durationMs) : null,\n step?.messageId != null ? t(\"message #%id%\", { replacements: { id: step.messageId } }) : null,\n ].filter((fact): fact is string => fact !== null);\n const isModelStep = step?.kind === \"MODEL_CALL\" || step?.kind === \"THINKING\";\n const isToolStep = step?.kind === \"TOOL_CALL\" || step?.kind === \"SKILL_LOAD\" || step?.kind === \"TASK_PLAN\";\n\n return (\n <DetailModal\n open={stepId !== null}\n onOpenChange={(open) => !open && onClose()}\n presentation=\"sheet\"\n showViewControl={false}\n title={\n <span className=\"inline-flex flex-wrap items-center gap-2\" data-testid=\"agent-step-detail-title\">\n <span>{name ? `${kindLabel} · ${name}` : kindLabel || t(\"Step\", { context: \"agent-step-kind\" })}</span>\n {state !== null && Object.hasOwn(STATE_LABELS, state) && step?.kind !== \"DECISION\" ? (\n <StatusBadge tone={STATE_LABELS[state].tone} label={t(STATE_LABELS[state].label, { context: STATE_CONTEXT })} />\n ) : null}\n </span>\n }\n description={facts.length > 0 ? facts.join(\" · \") : undefined}\n >\n {stepId === null ? null : step === null ? (\n isLoading ? (\n <Skeleton className=\"h-40 w-full\" />\n ) : (\n <div data-testid=\"agent-step-detail-unresolved\" data-step-id={stepId}>\n <StatusCallout\n tone=\"info\"\n title={t(\"This step could not be found in the conversation.\")}\n description={\n <>\n <span className=\"font-mono text-xs break-all\">{stepId}</span>\n <span className=\"mt-1 block\">\n {canSwitchToDebug\n ? t(\"Some steps exist only with Debug switched on (a skill preload, a decision, a model call). It may also belong to a turn further back, to a truncated branch or to a sub-agent's own conversation.\")\n : t(\"It may belong to a turn further back (load earlier turns), to a truncated branch or to a sub-agent's own conversation.\")}\n </span>\n </>\n }\n />\n </div>\n )\n ) : (\n <div className=\"flex min-w-0 flex-col gap-4\" data-testid=\"agent-step-detail\" data-step-kind={step.kind} data-step-id={step.stepId}>\n {step.kind === \"DECISION\" ? <DecisionDetail step={step} /> : null}\n {isModelStep ? <ModelCallDetail step={step} /> : null}\n {isToolStep ? (\n <AgentTraceFrame frameAttributes={frameAttributes} className=\"flex min-w-0 flex-col gap-4\">\n <ToolCallDetail step={step} />\n </AgentTraceFrame>\n ) : null}\n {step.kind === \"SUB_AGENT\" ? (\n <AgentTraceFrame frameAttributes={frameAttributes} className=\"flex min-w-0 flex-col gap-4\">\n <SubAgentDetail step={step} />\n </AgentTraceFrame>\n ) : null}\n {!isModelStep && !isToolStep && step.kind !== \"DECISION\" && step.kind !== \"SUB_AGENT\" ? <PlainStepDetail step={step} /> : null}\n <InspectStepExtras step={step} showsDetailLink={false} showsModelCallFacts={false} />\n </div>\n )}\n </DetailModal>\n );\n};\n","import type { ApiQueryHook } from \"@mgamadeus/ddd-admin-ui/logic/pure\";\nimport { type ReactNode, useCallback, useEffect, useRef, useState } from \"react\";\n\ninterface PendingLoad<TArg> {\n key: string;\n arg: TArg;\n}\n\ninterface Settlers<TData> {\n resolve: (data: TData) => void;\n reject: (error: unknown) => void;\n}\n\ninterface QueryRunnerProps<TArg, TData> {\n useQuery: ApiQueryHook<TArg, TData>;\n arg: TArg;\n onSettled: (outcome: { data: TData } | { error: unknown }) => void;\n}\n\n/** Runs one query and reports its answer; draws nothing. */\nconst QueryRunner = <TArg, TData>({ useQuery, arg, onSettled }: QueryRunnerProps<TArg, TData>) => {\n const result = useQuery(arg);\n const { currentData, isError, error } = result;\n useEffect(() => {\n if (currentData !== undefined) onSettled({ data: currentData });\n else if (isError) onSettled({ error });\n }, [currentData, isError, error, onSettled]);\n return null;\n};\n\n/**\n * A query hook as a function that answers a promise, for a block that asks for data on a click (the whole diff of a\n * file change): `load(arg)` mounts a runner that calls the hook and settles the promise with its answer. Reads stay\n * queries (cached, never held back by a write lock). Render `runners` once, anywhere in the component.\n */\nexport const useQueryLoader = <TArg, TData>(\n useQuery: ApiQueryHook<TArg, TData>,\n keyOf: (arg: TArg) => string,\n): readonly [(arg: TArg) => Promise<TData>, ReactNode] => {\n const [pendingLoads, setPendingLoads] = useState<PendingLoad<TArg>[]>([]);\n const settlersByKey = useRef(new Map<string, Settlers<TData>[]>());\n\n const load = useCallback(\n (arg: TArg) =>\n new Promise<TData>((resolve, reject) => {\n const key = keyOf(arg);\n const settlers = settlersByKey.current.get(key) ?? [];\n settlers.push({ resolve, reject });\n settlersByKey.current.set(key, settlers);\n setPendingLoads((current) => (current.some((pendingLoad) => pendingLoad.key === key) ? current : [...current, { key, arg }]));\n }),\n [keyOf],\n );\n\n const settle = useCallback((key: string, outcome: { data: TData } | { error: unknown }) => {\n const settlers = settlersByKey.current.get(key) ?? [];\n settlersByKey.current.delete(key);\n for (const settler of settlers) {\n if (\"data\" in outcome) settler.resolve(outcome.data);\n else settler.reject(outcome.error);\n }\n setPendingLoads((current) => current.filter((pendingLoad) => pendingLoad.key !== key));\n }, []);\n\n const runners = pendingLoads.map((pendingLoad) => (\n <QueryRunner key={pendingLoad.key} useQuery={useQuery} arg={pendingLoad.arg} onSettled={(outcome) => settle(pendingLoad.key, outcome)} />\n ));\n return [load, runners] as const;\n};\n","import { normalizeDddError } from \"@mgamadeus/ddd-web/contract\";\nimport { formatUiNumber, m, useFormatLocale, useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { EmptyValue, StatusBadge, Tag } from \"@mgamadeus/ddd-admin-ui/list\";\nimport { type UrlStateAdapter, useUrlListState } from \"@mgamadeus/ddd-admin-ui/logic\";\nimport { type EntityDetailBack, EntityDetailShell, type EntityTab, EntityTabs, MoreActionsMenu, StatusCallout } from \"@mgamadeus/ddd-admin-ui/page\";\nimport { Button, cn, Label, type PageLinkComponent, Switch, useLinkComponent } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport type { CodeHighlighterLoader } from \"@mgamadeus/ddd-admin-ui/files\";\nimport { Bug, RefreshCw } from \"lucide-react\";\nimport { type ReactNode, useCallback, useEffect, useId, useMemo, useRef, useState } from \"react\";\nimport { createTraceFormat, describeTraceEffort, readTraceMoment } from \"../../chat/trace/trace-format\";\nimport type { TraceDescribeMount, TraceEntityDescription, TraceEntityReference, TraceFileChange, TraceHostBindings, TraceViewMode } from \"../../chat/trace/trace-types\";\nimport { TraceViewModeSwitch } from \"../../chat/trace/TraceViewModeSwitch\";\nimport type { ConversationTraceLevel } from \"../../contract/conversation-trace\";\nimport type { AgentQualityApi } from \"../quality/agent-quality-api\";\nimport { SaveAsEvalCaseDialog } from \"../quality/SaveAsEvalCaseDialog\";\nimport type { AgentInspectApi } from \"./agent-inspect-api\";\nimport { mapAgentInspectSandboxChronicle } from \"./agent-inspect-mappers\";\nimport type {\n AgentInspectConversationHeader,\n AgentInspectFileChange,\n AgentInspectFileChangeArg,\n AgentInspectFileChangeDiffResponse,\n AgentInspectStep,\n AgentInspectTrace,\n AgentInspectTurn,\n} from \"./agent-inspect-types\";\nimport { ContextPanel } from \"./ContextPanel\";\nimport { useConversationActions } from \"./ConversationActions\";\nimport { ConversationTurns } from \"./ConversationTurns\";\nimport { DebugBarSwitch, DebugSwitchBar } from \"./DebugSwitchBar\";\nimport {\n AGENT_INSPECT_DEBUG_SWITCH_DEFAULTS,\n type AgentInspectDebugSwitches,\n readAgentInspectDebugSwitches,\n writeAgentInspectDebugSwitches,\n} from \"./debug-switches\";\nimport { DelegationPanel } from \"./DelegationPanel\";\nimport { readAgentInspectModelLabel, readAgentInspectPlanProgress } from \"./header-facts\";\nimport {\n AGENT_LIVE_RUN_STATES,\n AGENT_ORIGIN_CONTEXT,\n AGENT_ORIGIN_LABELS,\n AGENT_CONVERSATION_RUN_STATE,\n AGENT_CONVERSATION_RUN_STATE_CONTEXT,\n agentOriginOf,\n formatAgentInspectCost,\n formatAgentInspectCount,\n isKnownAgentRunState,\n} from \"./inspect-format\";\nimport { AgentTraceFrame, type AgentTraceFrameAttributes, InspectFactCard, InspectMeter, LiveDot } from \"./inspect-parts\";\nimport { type AgentInspectFileSelection, type AgentInspectScope, AgentInspectScopeProvider } from \"./inspect-scope\";\nimport { ModelContextDialog, type ModelContextView } from \"./ModelContextDialog\";\nimport { RequestsPanel } from \"./RequestsPanel\";\nimport { FilesPanel, SandboxPanel } from \"./SandboxPanel\";\nimport { StepDetailDialog } from \"./StepDetailDialog\";\nimport { AGENT_INSPECT_TURN_PAGE_SIZE, collectAgentInspectModelCalls, findAgentInspectStep, newestAgentInspectModelCallMessageId } from \"./turn-paging\";\nimport { useQueryLoader } from \"./use-query-loader\";\n\n/** The tabs of the conversation detail, in order. */\nexport const AGENT_CONVERSATION_DETAIL_TABS = [\"conversation\", \"delegation\", \"sandbox\", \"files\", \"requests\", \"context\"] as const;\nexport type AgentConversationDetailTab = (typeof AGENT_CONVERSATION_DETAIL_TABS)[number];\n\n/**\n * What the detail keeps in the URL: the tab, the debug switch, the view mode of the steps, the switches of the debug\n * bar (unless the host keeps them, `debugSwitches`) and its truncated rows, the model call whose context is open (`call` = its message id, `callView` = `payload`), the message\n * a link names (`message`: its turn is marked and scrolled to), the step whose detail is open (`step` = its id) and\n * the file of the sandbox and files tabs (`file` = its path, `change` = the id of one of its changes).\n */\nexport const AGENT_CONVERSATION_DETAIL_KEYS = [\"tab\", \"debug\", \"view\", \"switches\", \"truncated\", \"call\", \"callView\", \"message\", \"step\", \"file\", \"change\"] as const;\n\n/**\n * The query of a link to a file of a conversation's sandbox tab: `tab=sandbox&file=<path>&change=<id>`. A host adds\n * it to its route of the conversation detail; the tab opens with that file picked and that change shown.\n */\nexport const buildAgentConversationSandboxQuery = ({ path, fileChangeId }: { path?: string | null; fileChangeId?: number | null }): string => {\n const query = new URLSearchParams({ tab: \"sandbox\" });\n if (path) query.set(\"file\", path);\n if (fileChangeId != null) query.set(\"change\", String(fileChangeId));\n return query.toString();\n};\n\nconst TAB_CONTEXT = \"agent-conversation-tab\";\n\nconst TAB_LABELS: Readonly<Record<AgentConversationDetailTab, string>> = {\n conversation: m(\"Conversation\", { context: \"agent-conversation-tab\" }),\n delegation: m(\"Delegation\", { context: \"agent-conversation-tab\" }),\n sandbox: m(\"Sandbox\", { context: \"agent-conversation-tab\" }),\n files: m(\"Files\", { context: \"agent-conversation-tab\" }),\n requests: m(\"Requests\", { context: \"agent-conversation-tab\" }),\n context: m(\"Context\", { context: \"agent-conversation-tab\" }),\n};\n\nconst TRACE_VIEW_MODES: readonly TraceViewMode[] = [\"summary\", \"normal\", \"verbose\"];\n\nconst diffKeyOf = (arg: AgentInspectFileChangeArg): string => `${arg.conversationId}:${arg.fileChangeId}`;\n\nexport interface AgentConversationDetailScreenProps {\n /** The hooks of the inspection routes (`createAgentInspectApi`, or `createStaticAgentInspectApi` over fixtures). */\n api: AgentInspectApi;\n conversationId: number;\n /** Where the tab, the debug switch and the open model call are kept (the host's URL adapter). */\n urlStateAdapter: UrlStateAdapter;\n /** The list the back button leads to. */\n back?: EntityDetailBack;\n /** The app's router link; default the admin UI provider's. */\n linkComponent?: PageLinkComponent;\n /** The detail route of another conversation (a sub-agent's, the parent's); without it they are not linked. */\n buildConversationHref?: (conversationId: number) => string | null;\n /** The record behind an id argument of a tool call, as a chip (`describeEntity` of the trace blocks). */\n describeEntity?: (reference: TraceEntityReference) => TraceEntityDescription | null;\n /** The detail route of the record behind an id argument (`worldId`, 12); null for an argument without a screen. */\n buildEntityHref?: (argumentName: string, id: number) => string | null;\n /** The host's label and tint of a mount of the sandbox. */\n describeMount?: TraceDescribeMount;\n /** Opens a changed file in the host's viewer. */\n openFileInViewer?: (fileChange: TraceFileChange) => void;\n /** Formats an amount in US dollars; default four digits for small amounts. */\n formatCost?: (costInUsd: number) => string;\n /** Draws the markdown of an answer; without it answers are shown as plain text. */\n renderMarkdown?: (source: string) => ReactNode;\n /**\n * The attributes of the element around the chat's trace blocks: the selector the host maps the package's\n * `--agents-*` properties to its theme below (`{ \"data-agent-window\": \"\" }` for a host that themes its chat window).\n */\n traceFrameAttributes?: AgentTraceFrameAttributes;\n /** How the agent is named beside its answers; default \"Agent\". */\n agentDisplayName?: string;\n /** The reader may switch to the debug level (arguments, results, costs, the sent payload). */\n isDebugAllowed?: boolean;\n /** The reader may drive the conversation: continue as admin, truncate, replay, stop, cancel. */\n isDriveAllowed?: boolean;\n /** False: the drive controls show, disabled (the environment locks writes). */\n writesAllowed?: boolean;\n /** The models \"Continue as admin\" offers beside the conversation's own. */\n selectableModelNames?: readonly string[];\n /** How often a running conversation is read again, in ms; 0 switches it off. Default 4000. */\n livePollingIntervalMs?: number;\n /** How many turns are read at once. Default 10, at most 100. */\n turnPageSize?: number;\n /** More actions right of the title, before the package's own. */\n headerActions?: ReactNode;\n /**\n * The preview of a changed file as it is stored, for the \"Preview\" side of the sandbox and files tabs (the host's\n * own file viewer on the stored version, read under the reader's rights). It answers null for a change without a\n * stored version; without the prop the tabs show the diff alone. Its second argument carries `fallback`: the file's\n * content rebuilt from the recorded change (null when the diff does not hold the whole file), which the host shows\n * in place of its own \"cannot show this file\" state (file gone, no read right, not released by the malware check);\n * for a change the host answers null for, the tabs show that fallback themselves.\n */\n renderFilePreview?: AgentInspectScope[\"renderFilePreview\"];\n /** The facts of the conversation's live workspace (state, usage, a link to its screen), above the sandbox tab. */\n renderSandboxFacts?: (header: AgentInspectConversationHeader) => ReactNode;\n /** The display name of a model by its catalog name (\"GPT-6 Luna\"), for the models the trace does not name itself. */\n describeModelName?: (modelName: string) => string | null;\n /** The hooks of the quality routes: with them a debug reader saves a turn as an evaluation case. */\n qualityApi?: Pick<AgentQualityApi, \"useDraftEvalCaseMutation\">;\n /** Colours the JSON of the evaluation case draft, and the source of a file rebuilt from a recorded change, with the host's highlighter. */\n loadCodeHighlighter?: CodeHighlighterLoader;\n /**\n * The switches of the debug bar, kept by the host (its stored preference, so they hold across conversations); with\n * `onDebugSwitchesChange` the bar is controlled, without it the switches live in the URL (`switches`).\n */\n debugSwitches?: AgentInspectDebugSwitches;\n onDebugSwitchesChange?: (switches: AgentInspectDebugSwitches) => void;\n}\n\ninterface HeaderCardsProps {\n header: AgentInspectConversationHeader;\n /** The loaded turns: the next step of the task plan comes from the newest plan among them. */\n turns: readonly AgentInspectTurn[];\n isRunLive: boolean;\n isDebug: boolean;\n locale: string | undefined;\n formatCost: (costInUsd: number) => string;\n}\n\n/** The facts of the conversation in five cards in one row: model, cost, state, progress, context. */\nconst HeaderCards = ({ header, turns, isRunLive, isDebug, locale, formatCost }: HeaderCardsProps) => {\n const { t } = useTranslate();\n const format = useMemo(() => createTraceFormat(locale), [locale]);\n const runState = header.runState ?? null;\n const heartbeatAt = readTraceMoment(header.runHeartbeatAt);\n const lastInboundAt = readTraceMoment(header.lastInboundMessageAt);\n const tokens = (header.treeInputTokens ?? 0) + (header.treeOutputTokens ?? 0);\n const failedRowCount = header.failedRowCount ?? 0;\n const contextFillPercent = header.contextFillPercent ?? null;\n const planProgress = useMemo(() => readAgentInspectPlanProgress(header, turns), [header, turns]);\n const shownModelName = header.modelNameOverride ?? header.modelName ?? null;\n const count = (value: number | null | undefined) => formatAgentInspectCount(value ?? 0, locale);\n // Token counts from 10,000 in thousands, so a card's lines fit its width: the locale's short form where it has one\n // (\"72K\"), else the translated word (\"72 Tsd.\"; German has no short form for thousands).\n const compactCount = (value: number | null | undefined) => {\n if ((value ?? 0) < 10_000) return count(value);\n const localeShortForm = new Intl.NumberFormat(locale, { notation: \"compact\", maximumFractionDigits: (value ?? 0) >= 1_000_000 ? 1 : 0 }).format(value ?? 0);\n return /\\p{L}/u.test(localeShortForm)\n ? localeShortForm\n : t(\"%count% thousand\", { context: \"agent-count-short\", replacements: { count: formatAgentInspectCount(Math.round((value ?? 0) / 1000), locale) } });\n };\n const runStateWords = isKnownAgentRunState(runState) ? t(AGENT_CONVERSATION_RUN_STATE[runState].label, { context: AGENT_CONVERSATION_RUN_STATE_CONTEXT }) : runState;\n const costParts: { value: number; label: string }[] = [\n { value: header.modelCallsCostInUSD, label: m(\"Model calls %cost%\", { context: \"agent-conversation-cost\" }) },\n { value: header.toolExecutionCostInUSD, label: m(\"Tools %cost%\", { context: \"agent-conversation-cost\" }) },\n { value: header.overheadCostInUSD, label: m(\"Overhead %cost%\", { context: \"agent-conversation-cost\" }) },\n { value: header.subAgentsCostInUSD, label: m(\"Sub-agents %cost%\", { context: \"agent-conversation-cost\" }) },\n ].flatMap((part) => (typeof part.value === \"number\" && part.value > 0 ? [{ value: part.value, label: part.label as string }] : []));\n\n return (\n <div className=\"grid grid-cols-2 gap-3 md:grid-cols-3 xl:grid-cols-5\" data-testid=\"agent-inspect-header-cards\">\n <InspectFactCard\n caption={t(\"Model\", { context: \"agent-conversation-fact\" })}\n value={\n shownModelName !== null ? (\n <span title={shownModelName}>\n {/* The server names the configured model; an override is another model, named from the loaded answers. */}\n {(header.modelNameOverride ? null : header.modelLabel) || readAgentInspectModelLabel(shownModelName, turns)}\n </span>\n ) : (\n <EmptyValue />\n )\n }\n detail={[\n header.reasoningEffort ? t(\"Effort %effort%\", { replacements: { effort: describeTraceEffort(header.reasoningEffort) ?? header.reasoningEffort } }) : null,\n header.modelNameOverride ? t(\"set by an admin\") : null,\n header.budgetBypass ? t(\"budget lifted\") : null,\n (header.runSettingsOverrideCount ?? 0) > 0\n ? t(\"{count, plural, one {# override} other {# overrides}}\", { count: header.runSettingsOverrideCount ?? 0 })\n : null,\n ]\n .filter(Boolean)\n .join(\" · \")}\n />\n <InspectFactCard\n caption={t(\"Cost\", { context: \"agent-conversation-fact\" })}\n value={header.treeCostInUSD != null ? formatCost(header.treeCostInUSD) : <EmptyValue />}\n detail={[\n t(\"{count, plural, one {# turn} other {# turns}}\", { count: header.turnCount ?? 0 }),\n t(\"{count, plural, one {# model call} other {# model calls}}\", { count: header.modelCallCount ?? 0 }),\n t(\"%count% tokens\", { replacements: { count: compactCount(tokens) } }),\n ].join(\" · \")}\n >\n {isDebug && costParts.length > 0 ? (\n <span\n className=\"text-xs leading-5 text-muted-foreground\"\n data-testid=\"agent-inspect-cost-split\"\n title={t(\"%input% in · %output% out · %cached% cached\", {\n replacements: { input: count(header.treeInputTokens), output: count(header.treeOutputTokens), cached: count(header.treeCachedInputTokens) },\n })}\n >\n {costParts.map((part) => t(part.label, { context: \"agent-conversation-cost\", replacements: { cost: formatCost(part.value) } })).join(\" · \")}\n </span>\n ) : null}\n </InspectFactCard>\n <InspectFactCard\n caption={t(\"State\", { context: \"agent-conversation-fact\" })}\n value={\n <span className=\"inline-flex items-center gap-2\">\n {isRunLive ? <LiveDot label={t(\"A turn runs right now\")} /> : null}\n {runStateWords ?? <EmptyValue />}\n </span>\n }\n detail={[\n isRunLive && heartbeatAt !== null\n ? t(\"Heartbeat %duration% ago\", { replacements: { duration: format.duration(Math.max(0, Date.now() - heartbeatAt)) } })\n : lastInboundAt !== null\n ? t(\"Last message %time%\", { replacements: { time: new Intl.DateTimeFormat(locale, { dateStyle: \"short\", timeStyle: \"short\" }).format(lastInboundAt) } })\n : null,\n (header.resumeAttempts ?? 0) > 0 ? t(\"{count, plural, one {resumed # time} other {resumed # times}}\", { count: header.resumeAttempts ?? 0 }) : null,\n ]\n .filter(Boolean)\n .join(\" · \")}\n tone={runState === \"FAILED\" || failedRowCount > 0 ? \"danger\" : runState === \"AWAITING_DELEGATES\" ? \"warning\" : undefined}\n >\n {failedRowCount > 0 ? (\n <span className=\"text-xs font-semibold text-destructive\">{t(\"{count, plural, one {# failed step} other {# failed steps}}\", { count: failedRowCount })}</span>\n ) : null}\n </InspectFactCard>\n <InspectFactCard\n caption={t(\"Progress\", { context: \"agent-conversation-fact\" })}\n value={\n planProgress !== null ? (\n t(\"%done% of %total%\", { replacements: { done: planProgress.doneCount, total: planProgress.itemCount } })\n ) : (\n <span className=\"text-muted-foreground\">{t(\"No task plan\")}</span>\n )\n }\n detail={\n planProgress === null\n ? t(\"The agent worked without a task plan.\")\n : planProgress.nextItemTitle !== null\n ? t(\"Next step: %step%\", { replacements: { step: planProgress.nextItemTitle } })\n : planProgress.doneCount >= planProgress.itemCount\n ? t(\"Every step is done.\")\n : planProgress.blockedCount > 0\n ? t(\"{count, plural, one {# step is blocked.} other {# steps are blocked.}}\", { count: planProgress.blockedCount })\n : (planProgress.title ?? undefined)\n }\n >\n {planProgress !== null ? (\n <InspectMeter\n percent={(planProgress.doneCount / planProgress.itemCount) * 100}\n label={t(\"%done% of %total% items of the task plan are done\", { replacements: { done: planProgress.doneCount, total: planProgress.itemCount } })}\n />\n ) : null}\n </InspectFactCard>\n <InspectFactCard\n caption={t(\"Context\", { context: \"agent-conversation-fact\" })}\n value={\n header.contextTokens != null && header.contextThresholdTokens != null\n ? t(\"%used% / %threshold%\", { replacements: { used: compactCount(header.contextTokens), threshold: compactCount(header.contextThresholdTokens) } })\n : contextFillPercent !== null\n ? `${formatUiNumber(Math.round(contextFillPercent))} %`\n : <EmptyValue />\n }\n detail={[\n t(\"{count, plural, =0 {not compacted} one {# compaction} other {# compactions}}\", { count: header.compactionNodeCount ?? 0 }),\n header.loadedSkillCount != null ? t(\"{count, plural, one {# skill loaded} other {# skills loaded}}\", { count: header.loadedSkillCount }) : null,\n ]\n .filter(Boolean)\n .join(\" · \")}\n tone={contextFillPercent !== null && contextFillPercent >= 90 ? \"warning\" : undefined}\n >\n {contextFillPercent !== null ? (\n <InspectMeter\n percent={contextFillPercent}\n tone={contextFillPercent >= 100 ? \"danger\" : contextFillPercent >= 90 ? \"warning\" : undefined}\n label={t(\"The context is %percent% % of the compaction threshold\", { replacements: { percent: Math.round(contextFillPercent) } })}\n />\n ) : null}\n </InspectFactCard>\n </div>\n );\n};\n\n/**\n * One agent conversation for an admin: its facts in the header, a Debug switch for a reader who may, and six tabs\n * kept in the URL.\n *\n * - **Conversation**: turn by turn — the message that started the turn, its steps in the chosen view mode with the\n * texts the assistant wrote between them, the answers. Every text comes from the trace read itself (a long one is\n * cut and read whole on demand), so a host needs no messages read of its own; a turn the owner stopped is marked. A tool reached through `call_tool` shows as that tool (with the quiet \"via call_tool\" mark in the\n * verbose view); a delegation shows inline at its delegate call and opens the sub-agent's own trace; every model\n * call and every answer opens what the model was sent (\"What the model saw\"), with Debug also the sent payload.\n * - **Delegation**: totals, batches, a swimlane per sub-agent, a card per sub-agent with its trace.\n * - **Sandbox** (only for a conversation that ran a command or changed a file): chronicle, touched files, the\n * history of the picked file with its preview or its diff. A link names the file and the change\n * (`buildAgentConversationSandboxQuery`).\n * - **Files**: every file change with its preview or its diff.\n * - **Requests** (only for a reader with the debug right): every model call as a row — model, effort, tokens, cache\n * share, cost, duration, how it ended, the tools it called — with the totals; a row opens what the model was sent.\n * - **Context**: the composition of the newest model call and the compaction nodes.\n *\n * Every step of a turn opens to its detail beside the conversation (`?step=<id>`): a side decision with its input and\n * output, a model call with the context of that very call, a tool call with arguments and result. A link to a step\n * the loaded level does not hold (a skill preload, a decision, a model call exist at the debug level only) switches a\n * reader who may to that level, looks through earlier pages, and says plainly when the step cannot be found.\n *\n * Styles: the admin parts use the host's Tailwind tokens. The steps, terminal and diff blocks are the chat's, so the\n * host imports the package stylesheet and its theme mapping once — `import \"@mgamadeus/ddd-agents/styles.css\"` and\n * the css file that maps the `--agents-*` properties to its tokens — and names the selector of that mapping in\n * `traceFrameAttributes`. The texts of the chat blocks come from the agents environment (`setAgentsEnvironment`).\n */\nexport const AgentConversationDetailScreen = ({\n api,\n conversationId,\n urlStateAdapter,\n back,\n linkComponent,\n buildConversationHref,\n describeEntity,\n buildEntityHref,\n describeMount,\n openFileInViewer,\n formatCost,\n renderMarkdown,\n traceFrameAttributes,\n agentDisplayName,\n isDebugAllowed = false,\n isDriveAllowed = false,\n writesAllowed = true,\n selectableModelNames = [],\n livePollingIntervalMs = 4000,\n turnPageSize = AGENT_INSPECT_TURN_PAGE_SIZE,\n headerActions,\n renderFilePreview,\n renderSandboxFacts,\n describeModelName,\n qualityApi,\n loadCodeHighlighter,\n debugSwitches: debugSwitchesOfHost,\n onDebugSwitchesChange,\n}: AgentConversationDetailScreenProps) => {\n const { t } = useTranslate();\n const locale = useFormatLocale();\n const providerLink = useLinkComponent();\n const Link = linkComponent ?? providerLink;\n const debugSwitchId = useId();\n const url = useUrlListState(AGENT_CONVERSATION_DETAIL_KEYS, { adapter: urlStateAdapter, pushKeys: [\"tab\", \"step\"], debounceMs: 0 });\n const isDebug = isDebugAllowed && url.values.debug === \"1\";\n const level: ConversationTraceLevel = isDebug ? \"DEBUG\" : \"STEPS\";\n const pageSize = Math.min(100, Math.max(1, Math.floor(turnPageSize)));\n const costOf = useMemo(() => formatCost ?? ((costInUsd: number) => formatAgentInspectCost(costInUsd, locale)), [formatCost, locale]);\n\n // The header is read again while a run is live; the first answer says whether it is.\n const [isRunLive, setIsRunLive] = useState(false);\n const conversationQuery = api.useConversationQuery({ conversationId }, { pollingInterval: isRunLive && livePollingIntervalMs > 0 ? Math.max(livePollingIntervalMs, 5000) : 0 });\n const header = conversationQuery.data?.header ?? null;\n const [trace, setTrace] = useState<AgentInspectTrace | null>(null);\n const isHeaderRunLive = header?.isRunLive === true || AGENT_LIVE_RUN_STATES.includes(header?.runState ?? \"\");\n useEffect(() => setIsRunLive(isHeaderRunLive || trace?.isRunLive === true), [isHeaderRunLive, trace]);\n\n const sandboxQuery = api.useSandboxQuery({ conversationId });\n const hasSandbox = useMemo(() => {\n if (!sandboxQuery.data) return false;\n const chronicle = mapAgentInspectSandboxChronicle(sandboxQuery.data);\n return chronicle.entries.length > 0 || chronicle.mounts.some((mount) => mount.files.length > 0);\n }, [sandboxQuery.data]);\n\n const [loadDiff, diffRunners] = useQueryLoader<AgentInspectFileChangeArg, AgentInspectFileChangeDiffResponse>(api.useFileChangeDiffQuery, diffKeyOf);\n const loadFullDiff = useCallback(\n async (fileChange: TraceFileChange): Promise<string> => {\n if (fileChange.id == null) return fileChange.diffPreview ?? \"\";\n const ownerConversationId = (fileChange as { conversationId?: number | null }).conversationId ?? conversationId;\n const answer = await loadDiff({ conversationId: ownerConversationId, fileChangeId: fileChange.id });\n return answer.diff ?? fileChange.diffPreview ?? \"\";\n },\n [conversationId, loadDiff],\n );\n\n const debugSwitches: AgentInspectDebugSwitches =\n onDebugSwitchesChange !== undefined ? (debugSwitchesOfHost ?? AGENT_INSPECT_DEBUG_SWITCH_DEFAULTS) : readAgentInspectDebugSwitches(url.values.switches);\n const setDebugSwitches = (switches: AgentInspectDebugSwitches) => {\n if (onDebugSwitchesChange !== undefined) onDebugSwitchesChange(switches);\n else url.setValue(\"switches\", writeAgentInspectDebugSwitches(switches));\n };\n // The turns are read again on \"Refresh\"; the counter tells the turns list to.\n const [refreshCount, setRefreshCount] = useState(0);\n\n const { actions, headerActions: driveActions, menuItems: driveMenuItems, dialogs } = useConversationActions({\n api,\n conversationId,\n isDriveAllowed,\n writesAllowed,\n selectableModelNames,\n configuredModelName: header?.modelNameOverride ?? header?.modelName ?? null,\n isRunActive: isRunLive,\n });\n\n const { setValues } = url;\n const openModelContext = useCallback(\n (messageId: number, view: ModelContextView = \"composition\") => setValues({ call: String(messageId), callView: view === \"composition\" ? \"\" : view }),\n [setValues],\n );\n\n const openStepDetail = useCallback((stepId: string) => setValues({ step: stepId }), [setValues]);\n const [evalCaseMessageId, setEvalCaseMessageId] = useState<number | null>(null);\n const openEvalCase = useMemo(() => (qualityApi && isDebug ? (messageId: number) => setEvalCaseMessageId(messageId) : undefined), [qualityApi, isDebug]);\n const selectedFilePath = url.values.file === \"\" ? null : url.values.file;\n const selectedFileChangeId = /^\\d+$/.test(url.values.change) ? Number(url.values.change) : null;\n const fileSelection = useMemo(\n (): AgentInspectFileSelection => ({\n filePath: selectedFilePath,\n fileChangeId: selectedFileChangeId,\n select: (filePath, fileChangeId = null) => setValues({ file: filePath ?? \"\", change: fileChangeId === null ? \"\" : String(fileChangeId) }),\n }),\n [selectedFilePath, selectedFileChangeId, setValues],\n );\n const sandboxFacts = useMemo(() => (renderSandboxFacts && header ? () => renderSandboxFacts(header) : undefined), [renderSandboxFacts, header]);\n\n const host = useMemo(\n (): TraceHostBindings => ({\n linkComponent: Link,\n describeEntity,\n buildEntityHref,\n describeMount,\n formatCost: costOf,\n loadFullDiff,\n openFileInViewer,\n buildChildConversationHref: buildConversationHref,\n }),\n [Link, describeEntity, buildEntityHref, describeMount, costOf, loadFullDiff, openFileInViewer, buildConversationHref],\n );\n const shownAgentName = agentDisplayName ?? t(\"Agent\", { context: \"agent-turn-author\" });\n const scope = useMemo(\n (): AgentInspectScope => ({\n api,\n conversationId,\n level,\n isDebug,\n locale,\n formatCost: costOf,\n linkComponent: Link,\n host,\n describeMount,\n loadFullDiff,\n renderMarkdown,\n frameAttributes: traceFrameAttributes,\n agentDisplayName: shownAgentName,\n buildConversationHref,\n actions,\n canReadModelContext: isDebugAllowed,\n openModelContext,\n openStepDetail,\n openEvalCase,\n fileSelection,\n renderFilePreview,\n loadCodeHighlighter,\n renderSandboxFacts: sandboxFacts,\n describeModelName,\n }),\n [\n api,\n conversationId,\n level,\n isDebug,\n locale,\n costOf,\n Link,\n host,\n describeMount,\n loadFullDiff,\n renderMarkdown,\n traceFrameAttributes,\n shownAgentName,\n buildConversationHref,\n actions,\n isDebugAllowed,\n openModelContext,\n openStepDetail,\n openEvalCase,\n fileSelection,\n renderFilePreview,\n loadCodeHighlighter,\n sandboxFacts,\n describeModelName,\n ],\n );\n\n const availableTabs = AGENT_CONVERSATION_DETAIL_TABS.filter((tab) => (tab !== \"sandbox\" || hasSandbox) && (tab !== \"requests\" || isDebugAllowed));\n const requestedTab = url.values.tab as AgentConversationDetailTab;\n const activeTab: AgentConversationDetailTab = availableTabs.includes(requestedTab) ? requestedTab : \"conversation\";\n const subAgentConversationCount = Math.max(0, (header?.treeConversationCount ?? 1) - 1);\n const tabs: EntityTab[] = availableTabs.map((tab) => ({\n id: tab,\n label: TAB_LABELS[tab],\n context: TAB_CONTEXT,\n count: tab === \"delegation\" && subAgentConversationCount > 0 ? subAgentConversationCount : tab === \"context\" && (header?.compactionNodeCount ?? 0) > 0 ? header?.compactionNodeCount : tab === \"requests\" && (header?.modelCallCount ?? 0) > 0 ? header?.modelCallCount : undefined,\n }));\n\n // With Debug on the steps always show verbose (the switches of the debug bar choose what); Short and Normal are the\n // views without Debug.\n const requestedViewMode = url.values.view as TraceViewMode;\n const viewMode: TraceViewMode = isDebug ? \"verbose\" : requestedViewMode === \"summary\" ? \"summary\" : \"normal\";\n const includeTruncated = isDebug && url.values.truncated === \"1\";\n const newestModelCallMessageId = useMemo(() => newestAgentInspectModelCallMessageId(trace?.turns ?? []), [trace]);\n // The model and effort of a model call for the request drawer: from its step, the model as the catalog names it.\n const describeModelCall = useCallback(\n (modelCall: { messageId: number }) => {\n const turns = trace?.turns ?? [];\n for (const turn of turns) {\n const step = turn.steps.find((candidate) => candidate.kind === \"MODEL_CALL\" && candidate.messageId === modelCall.messageId);\n if (step) return { modelLabel: readAgentInspectModelLabel(step.modelCall?.modelName ?? null, [turn]) ?? step.modelLabel, effort: step.modelCall?.effort ?? null };\n }\n return null;\n },\n [trace],\n );\n\n const openCallMessageId = /^\\d+$/.test(url.values.call) ? Number(url.values.call) : null;\n const modelCalls = useMemo(() => collectAgentInspectModelCalls(trace?.turns ?? []), [trace]);\n const openStepId = url.values.step === \"\" ? null : url.values.step;\n const openStep = useMemo((): AgentInspectStep | null => findAgentInspectStep(trace?.turns ?? [], openStepId), [openStepId, trace]);\n // A linked step that the loaded level does not hold (a skill preload, a side decision, a model call exist at the\n // debug level only): a reader who may switches to that level once per link; the turns then look for it in earlier\n // pages, and the detail says so plainly when it stays unresolved.\n const debugTriedForStepId = useRef<string | null>(null);\n const isStepMissing = activeTab === \"conversation\" && openStepId !== null && trace !== null && openStep === null;\n const switchesToDebugForStep = isStepMissing && !isDebug && isDebugAllowed && trace.level === \"STEPS\" && debugTriedForStepId.current !== openStepId;\n useEffect(() => {\n if (!switchesToDebugForStep) return;\n debugTriedForStepId.current = openStepId;\n setValues({ debug: \"1\", view: \"\", truncated: \"\" });\n }, [switchesToDebugForStep, openStepId, setValues]);\n const [isSearchingFocus, setIsSearchingFocus] = useState(false);\n const focusStepId = activeTab === \"conversation\" && !switchesToDebugForStep ? openStepId : null;\n // The trace of the level just switched to is still on its way while the held one is of the level before.\n const isStepStillLoading = trace === null || trace.level !== level || switchesToDebugForStep || isSearchingFocus;\n\n const accountLabel = conversationQuery.data?.accountLabel ?? null;\n const agentSpaceLabel = conversationQuery.data?.agentSpaceLabel ?? null;\n const origin = header ? agentOriginOf(header) : null;\n const parentHref = header?.rootConversationId != null && header.rootConversationId !== conversationId ? (buildConversationHref?.(header.rootConversationId) ?? null) : null;\n const fallbackTitle = t(\"Conversation #%id%\", { replacements: { id: conversationId } });\n const runState = header?.runState ?? null;\n const originWords = origin ? (Object.hasOwn(AGENT_ORIGIN_LABELS, origin) ? t(AGENT_ORIGIN_LABELS[origin], { context: AGENT_ORIGIN_CONTEXT }) : origin) : null;\n const refresh = () => {\n void conversationQuery.refetch();\n void sandboxQuery.refetch();\n setRefreshCount((current) => current + 1);\n };\n const moreActions = [\n ...driveMenuItems,\n {\n id: \"copyId\",\n label: t(\"Copy the conversation ID\"),\n onSelect: () => void navigator.clipboard?.writeText(String(conversationId)),\n separatorBefore: driveMenuItems.length > 0,\n },\n ];\n\n return (\n <AgentInspectScopeProvider value={scope}>\n <EntityDetailShell\n title={header?.title}\n fallbackTitle={fallbackTitle}\n back={back}\n linkComponent={Link}\n isLoading={conversationQuery.isLoading}\n error={\n conversationQuery.isError\n ? normalizeDddError(conversationQuery.error, t(\"The conversation could not be loaded.\")).message\n : !conversationQuery.isLoading && conversationQuery.data !== undefined && header === null\n ? t(\"The conversation does not exist.\")\n : undefined\n }\n description={\n header ? (\n <span className=\"inline-flex flex-wrap items-center justify-center gap-1.5\" data-testid=\"agent-inspect-chips\">\n {isRunLive ? <LiveDot label={t(\"A turn runs right now\")} /> : null}\n {isKnownAgentRunState(runState) ? (\n <StatusBadge\n tone={AGENT_CONVERSATION_RUN_STATE[runState].tone}\n label={t(AGENT_CONVERSATION_RUN_STATE[runState].label, { context: AGENT_CONVERSATION_RUN_STATE_CONTEXT })}\n />\n ) : runState ? (\n <StatusBadge tone=\"neutral\" label={runState} />\n ) : null}\n {agentSpaceLabel?.label ? <Tag size=\"sm\">{agentSpaceLabel.label}</Tag> : null}\n {accountLabel?.label ? (\n <Tag size=\"sm\">{t(\"started by %name%\", { replacements: { name: accountLabel.label } })}</Tag>\n ) : header.accountId != null ? (\n <Tag size=\"sm\">{t(\"started by account #%id%\", { replacements: { id: header.accountId } })}</Tag>\n ) : null}\n {header.purposeName ? (\n <Tag size=\"sm\" tone=\"brand\">\n {t(\"Purpose\", { context: \"agent-conversation-chip\" })} <span className=\"font-mono\">{header.purposeName}</span>\n </Tag>\n ) : null}\n {originWords ? <Tag size=\"sm\">{originWords}</Tag> : null}\n <Tag size=\"sm\">{t(\"ID %id%\", { replacements: { id: conversationId } })}</Tag>\n {header.storesFullRequestSnapshots ? <Tag size=\"sm\">{t(\"stores sent payloads\")}</Tag> : null}\n {parentHref !== null ? (\n <Link href={parentHref} className=\"text-xs font-semibold text-brand-emphasis hover:underline\">\n {t(\"Parent conversation #%id%\", { replacements: { id: header.rootConversationId ?? 0 } })}\n </Link>\n ) : null}\n </span>\n ) : undefined\n }\n actions={\n <div className=\"flex flex-wrap items-center justify-end gap-2\">\n {driveActions}\n {headerActions}\n <Button type=\"button\" variant=\"outline\" size=\"sm\" onClick={refresh} disabled={conversationQuery.isFetching} data-testid=\"agent-inspect-refresh\">\n <RefreshCw className={cn(conversationQuery.isFetching && \"animate-spin motion-reduce:animate-none\")} />\n {t(\"Refresh\")}\n </Button>\n {isDebugAllowed ? (\n <div className={cn(\"inline-flex h-8 items-center gap-2 rounded-full px-3 shadow-sm\", isDebug ? \"bg-foreground text-background dark:bg-muted dark:text-foreground\" : \"bg-card\")}>\n <Bug className={cn(\"size-3.5\", isDebug ? \"text-brand\" : \"text-muted-foreground\")} aria-hidden />\n <Label htmlFor={debugSwitchId} className=\"text-xs font-semibold\">\n {isDebug ? t(\"Debug on\", { context: \"agent-conversation-switch\" }) : t(\"Debug off\", { context: \"agent-conversation-switch\" })}\n </Label>\n <Switch\n id={debugSwitchId}\n size=\"sm\"\n checked={isDebug}\n onCheckedChange={(checked) => url.setValues({ debug: checked ? \"1\" : \"\", view: \"\", truncated: \"\", callView: \"\" })}\n data-testid=\"agent-inspect-debug-switch\"\n />\n </div>\n ) : null}\n <MoreActionsMenu items={moreActions} label={t(\"More actions on the conversation\")} />\n </div>\n }\n >\n {header ? (\n <div className=\"flex flex-col gap-4\" data-testid=\"agent-conversation-detail\" data-debug={isDebug ? \"on\" : \"off\"}>\n <HeaderCards header={header} turns={trace?.turns ?? []} isRunLive={isRunLive} isDebug={isDebug} locale={locale} formatCost={costOf} />\n <EntityTabs tabs={tabs} aria-label={t(\"Sections of the conversation\")} activeId={activeTab} onSelect={(tab) => url.setValue(\"tab\", tab === \"conversation\" ? \"\" : tab)} align=\"center\" />\n\n {activeTab === \"conversation\" ? (\n <>\n {isDebug ? (\n <DebugSwitchBar\n switches={debugSwitches}\n onSwitchChange={(name, isOn) => setDebugSwitches({ ...debugSwitches, [name]: isOn })}\n onViewRequest={newestModelCallMessageId !== null ? () => openModelContext(newestModelCallMessageId, \"composition\") : null}\n extraSwitches={\n <DebugBarSwitch\n label={t(\"Truncated rows\", { context: \"agent-conversation-switch\" })}\n checked={includeTruncated}\n onCheckedChange={(checked) => url.setValue(\"truncated\", checked ? \"1\" : \"\")}\n testId=\"agent-inspect-truncated-switch\"\n />\n }\n />\n ) : (\n <div className=\"flex flex-wrap items-center gap-x-4 gap-y-2\" data-testid=\"agent-inspect-toolbar\">\n <AgentTraceFrame frameAttributes={traceFrameAttributes}>\n <TraceViewModeSwitch viewMode={viewMode} onViewModeChange={(nextViewMode) => url.setValue(\"view\", nextViewMode === \"normal\" ? \"\" : nextViewMode)} isVerboseAllowed={false} />\n </AgentTraceFrame>\n {isDebugAllowed ? (\n <div className=\"flex min-w-0 flex-1 items-center gap-2 rounded-xl bg-muted px-3 py-2 text-xs text-muted-foreground\" data-testid=\"agent-inspect-debug-hint\">\n <Bug className=\"size-3.5 shrink-0\" aria-hidden />\n <span>\n {t(\"Debug shows skills, tool calls with arguments and results, compaction, model and effort per turn, tokens, costs, times, sub-agents and the request that was sent.\")}\n </span>\n </div>\n ) : null}\n </div>\n )}\n <ConversationTurns\n viewMode={viewMode}\n debugSwitches={isDebug ? debugSwitches : null}\n refreshCount={refreshCount}\n includeTruncated={includeTruncated}\n ownerLabel={accountLabel?.label ?? t(\"Owner\", { context: \"agent-turn-author\" })}\n focusStepId={focusStepId}\n onFocusSearchChange={setIsSearchingFocus}\n livePollingIntervalMs={livePollingIntervalMs}\n turnPageSize={pageSize}\n onTraceChange={setTrace}\n focusMessageId={/^\\d+$/.test(url.values.message) ? Number(url.values.message) : null}\n />\n </>\n ) : null}\n {activeTab === \"delegation\" ? <DelegationPanel /> : null}\n {activeTab === \"sandbox\" ? <SandboxPanel /> : null}\n {activeTab === \"files\" ? <FilesPanel /> : null}\n {activeTab === \"requests\" ? <RequestsPanel conversationCosts={header} subAgentConversationCount={subAgentConversationCount} livePollingIntervalMs={livePollingIntervalMs} /> : null}\n {activeTab === \"context\" ? <ContextPanel turnPageSize={pageSize} /> : null}\n </div>\n ) : conversationQuery.isLoading ? null : (\n <StatusCallout tone=\"info\" title={fallbackTitle} description={t(\"The conversation does not exist.\")} />\n )}\n <ModelContextDialog\n messageId={openCallMessageId}\n view={url.values.callView === \"payload\" || url.values.callView === \"diff\" ? url.values.callView : \"composition\"}\n modelCalls={modelCalls}\n onMessageIdChange={(messageId) => url.setValues(messageId === null ? { call: \"\", callView: \"\" } : { call: String(messageId) })}\n onViewChange={(view) => url.setValue(\"callView\", view === \"composition\" ? \"\" : view)}\n describeCall={describeModelCall}\n />\n <StepDetailDialog\n stepId={activeTab === \"conversation\" ? openStepId : null}\n step={openStep}\n isLoading={isStepStillLoading}\n canSwitchToDebug={isDebugAllowed && !isDebug}\n onClose={() => url.setValue(\"step\", \"\")}\n />\n {qualityApi ? (\n <SaveAsEvalCaseDialog\n api={qualityApi}\n conversationId={conversationId}\n messageId={evalCaseMessageId ?? undefined}\n open={evalCaseMessageId !== null}\n onOpenChange={(open) => !open && setEvalCaseMessageId(null)}\n loadCodeHighlighter={loadCodeHighlighter}\n />\n ) : null}\n {dialogs}\n {diffRunners}\n </EntityDetailShell>\n </AgentInspectScopeProvider>\n );\n};\n","import { readTraceMoment } from \"../../chat/trace/trace-format\";\nimport type { AgentInspectedConversation, AgentInspectLabel } from \"./agent-inspect-types\";\n\n// The export of the filtered conversations list as a CSV file: which columns it carries, how a cell is written and\n// how the file is named. Pure, so the text of the file is covered by tests; the screen reads the pages and downloads.\n\n/** Conversations per request of the export (the list route's cap). */\nexport const AGENT_CONVERSATION_EXPORT_PAGE_SIZE = 200;\n\n/** The most conversations one export carries; a filtered list beyond it is cut and the reader is told. */\nexport const AGENT_CONVERSATION_EXPORT_MAX_ROWS = 5000;\n\n/** The columns of the export, in order: the table's, with the tokens split and the two dates as moments. */\nexport const AGENT_CONVERSATION_EXPORT_COLUMNS = [\n \"id\",\n \"title\",\n \"firstOwnerText\",\n \"lastAnswerText\",\n \"space\",\n \"account\",\n \"purpose\",\n \"origin\",\n \"runState\",\n \"turns\",\n \"inputTokens\",\n \"outputTokens\",\n \"cachedInputTokens\",\n \"problems\",\n \"costInUsd\",\n \"models\",\n \"subAgents\",\n \"created\",\n \"lastActivity\",\n] as const;\n\nexport type AgentConversationExportColumn = (typeof AGENT_CONVERSATION_EXPORT_COLUMNS)[number];\n\nexport type AgentConversationExportCell = string | number | null | undefined;\n\nexport type AgentConversationExportRow = Readonly<Record<AgentConversationExportColumn, AgentConversationExportCell>>;\n\n/**\n * An excerpt of a message as one line: the Markdown marks of emphasis, code and headings left out (`**10 Welten**`\n * reads \"10 Welten\"), line breaks and runs of blanks as one blank; null for no text.\n */\nexport const readAgentConversationExcerpt = (text: string | null | undefined): string | null => {\n const line = (text ?? \"\")\n .replace(/(^|\\n)\\s{0,3}#{1,6}\\s+/g, \"$1\")\n .replace(/\\*\\*|__|`/g, \"\")\n .replace(/\\s+/g, \" \")\n .trim();\n return line === \"\" ? null : line;\n};\n\n/**\n * A text cell a spreadsheet must not run as a formula: a text that starts with `=`, `+`, `-`, `@`, a tab or a\n * carriage return gets a leading apostrophe.\n */\nexport const guardCsvText = (text: string): string => (/^[=+\\-@\\t\\r]/.test(text) ? `'${text}` : text);\n\n/**\n * One cell as RFC 4180 writes it: a number as it is (never guarded: `-3` is a number), a text guarded against\n * formulas and quoted when it holds a comma, a quote or a line break; nothing for no value.\n */\nexport const encodeCsvCell = (value: AgentConversationExportCell): string => {\n if (value === null || value === undefined) return \"\";\n if (typeof value === \"number\") return Number.isFinite(value) ? String(value) : \"\";\n const text = guardCsvText(value);\n return /[\",\\r\\n]/.test(text) ? `\"${text.replace(/\"/g, '\"\"')}\"` : text;\n};\n\n/** The byte order mark a spreadsheet reads the file as UTF-8 by. */\nexport const CSV_BYTE_ORDER_MARK = \"\";\n\n/** The text of a CSV file (RFC 4180: commas, CRLF line ends, a header line) with a byte order mark before it. */\nexport const buildCsvText = (header: readonly string[], rows: readonly (readonly AgentConversationExportCell[])[]): string =>\n `${CSV_BYTE_ORDER_MARK}${[header, ...rows].map((row) => row.map(encodeCsvCell).join(\",\")).join(\"\\r\\n\")}\\r\\n`;\n\n/** A date-time of the server (UTC without a zone) as an ISO moment (`2026-11-28T21:07:49Z`); nothing for none. */\nexport const formatAgentConversationExportMoment = (value: string | null | undefined): string | null => {\n const moment = readTraceMoment(value);\n return moment === null ? null : new Date(moment).toISOString().replace(/\\.\\d{3}Z$/, \"Z\");\n};\n\nexport interface AgentConversationExportWords {\n accountLabelById: ReadonlyMap<number, AgentInspectLabel>;\n agentSpaceLabelById: ReadonlyMap<number, AgentInspectLabel>;\n /** The origin of a conversation in the reader's words. */\n describeOrigin: (conversation: AgentInspectedConversation) => string;\n /** A run state in the reader's words. */\n describeRunState: (runState: string) => string;\n /** How a conversation at the level of its account (no space) is named. */\n accountLevelLabel: string;\n}\n\n/** One conversation as the cells of its export row. */\nexport const buildAgentConversationExportRow = (conversation: AgentInspectedConversation, words: AgentConversationExportWords): AgentConversationExportRow => {\n const spaceLabel = conversation.agentSpaceId ? words.agentSpaceLabelById.get(conversation.agentSpaceId)?.label : undefined;\n const accountLabel = conversation.accountId ? words.accountLabelById.get(conversation.accountId)?.label : undefined;\n return {\n id: conversation.aiConversationId ?? null,\n title: conversation.title ?? null,\n firstOwnerText: readAgentConversationExcerpt(conversation.firstOwnerTextExcerpt),\n lastAnswerText: readAgentConversationExcerpt(conversation.lastAnswerTextExcerpt),\n space: conversation.agentSpaceId ? spaceLabel || `#${conversation.agentSpaceId}` : words.accountLevelLabel,\n account: conversation.accountId ? accountLabel || `#${conversation.accountId}` : null,\n purpose: conversation.purposeName ?? null,\n origin: words.describeOrigin(conversation),\n runState: conversation.runState ? words.describeRunState(conversation.runState) : null,\n turns: conversation.turnCount ?? 0,\n inputTokens: conversation.inputTokens ?? 0,\n outputTokens: conversation.outputTokens ?? 0,\n cachedInputTokens: conversation.cachedInputTokens ?? 0,\n problems: conversation.failedRowCount ?? 0,\n costInUsd: conversation.costInUSD ?? 0,\n models: (conversation.modelNames ?? []).join(\", \") || null,\n subAgents: conversation.subAgentCount ?? 0,\n created: formatAgentConversationExportMoment(conversation.created),\n lastActivity: formatAgentConversationExportMoment(conversation.lastMessageAt ?? conversation.lastActivityAt ?? conversation.created),\n };\n};\n\n/** The CSV text of the export: the header in the reader's words, one line per conversation, columns in their order. */\nexport const buildAgentConversationExportCsv = (\n headerByColumn: Readonly<Record<AgentConversationExportColumn, string>>,\n rows: readonly AgentConversationExportRow[],\n): string =>\n buildCsvText(\n AGENT_CONVERSATION_EXPORT_COLUMNS.map((column) => headerByColumn[column]),\n rows.map((row) => AGENT_CONVERSATION_EXPORT_COLUMNS.map((column) => row[column])),\n );\n\n/**\n * The name of the export's file with its period: `agent-conversations_2026-11-22_2026-11-28.csv`, an open bound as\n * `from-…` or `until-…`, no bounds as `agent-conversations_all.csv`.\n */\nexport const buildAgentConversationExportFileName = ({ from, to }: { from?: string; to?: string }): string => {\n const period = from && to ? `${from}_${to}` : from ? `from-${from}` : to ? `until-${to}` : \"all\";\n return `agent-conversations_${period}.csv`;\n};\n\n/**\n * Whether the export goes on after a page, and from where: it stops at the last page (the route says no more, or\n * the page is empty) and at the cap, where it says that the list was cut.\n */\nexport const readAgentConversationExportProgress = (\n loadedRowCount: number,\n page: { rowCount: number; hasMore: boolean },\n maximumRows: number = AGENT_CONVERSATION_EXPORT_MAX_ROWS,\n): { isDone: boolean; wasCut: boolean } => {\n if (!page.hasMore || page.rowCount === 0) return { isDone: true, wasCut: loadedRowCount > maximumRows };\n if (loadedRowCount >= maximumRows) return { isDone: true, wasCut: true };\n return { isDone: false, wasCut: false };\n};\n","import {\n AGENT_INSPECT_RUN_STATES,\n AGENT_INSPECT_SEGMENTS,\n AGENT_INSPECT_SORT_ORDERS,\n type AgentInspectListArg,\n type AgentInspectSegment,\n type AgentInspectSortOrder,\n} from \"./agent-inspect-types\";\n\n/**\n * The filters of the conversations list as the URL holds them: one search parameter per key, each a string (`\"\"` =\n * unset), lists comma-separated. Pure, so the mapping between the URL and the request is covered by tests.\n */\nexport const AGENT_CONVERSATION_LIST_KEYS = [\n \"segment\",\n \"q\",\n \"period\",\n \"from\",\n \"to\",\n \"accounts\",\n \"spaces\",\n \"purpose\",\n \"states\",\n \"origin\",\n \"model\",\n \"tool\",\n \"skill\",\n \"minCost\",\n \"evalRuns\",\n \"sort\",\n \"page\",\n] as const;\n\nexport type AgentConversationListKey = (typeof AGENT_CONVERSATION_LIST_KEYS)[number];\nexport type AgentConversationListValues = Readonly<Record<AgentConversationListKey, string>>;\n\n/** The keys that are no filter of the toolbar's count: the search has its own clear button, the segment and the page are places, the order is no filter. */\nexport const AGENT_CONVERSATION_LIST_UNCOUNTED_KEYS: readonly AgentConversationListKey[] = [\"q\", \"segment\", \"sort\", \"page\"];\n\n/** The periods the list offers; `custom` shows the two day fields, `all` has no bounds. */\nexport const AGENT_CONVERSATION_LIST_PERIODS = [\"today\", \"7d\", \"30d\", \"all\", \"custom\"] as const;\nexport type AgentConversationListPeriod = (typeof AGENT_CONVERSATION_LIST_PERIODS)[number];\n\n/** The period of a list whose URL names none: the one the metrics default to. */\nexport const AGENT_CONVERSATION_LIST_DEFAULT_PERIOD: AgentConversationListPeriod = \"7d\";\n\nconst DAY_PATTERN = /^\\d{4}-\\d{2}-\\d{2}$/;\n\nconst isDay = (value: string): boolean => DAY_PATTERN.test(value) && !Number.isNaN(Date.parse(`${value}T00:00:00Z`));\n\n/** `day` moved by `days` calendar days (`YYYY-MM-DD`, no clock involved). */\nexport const shiftAgentInspectDay = (day: string, days: number): string => {\n const moment = Date.parse(`${day}T00:00:00Z`);\n return Number.isNaN(moment) ? \"\" : new Date(moment + days * 86_400_000).toISOString().slice(0, 10);\n};\n\n/** The period the values name: the URL's, else the default; a custom period needs at least one valid day. */\nexport const readAgentConversationListPeriod = (values: Pick<AgentConversationListValues, \"period\" | \"from\" | \"to\">): AgentConversationListPeriod => {\n const period = AGENT_CONVERSATION_LIST_PERIODS.find((candidate) => candidate === values.period);\n if (period !== undefined && period !== \"custom\") return period;\n if (isDay(values.from) || isDay(values.to)) return \"custom\";\n return period === \"custom\" ? \"custom\" : AGENT_CONVERSATION_LIST_DEFAULT_PERIOD;\n};\n\n/** The first and the last day (inclusive) of the values' period on `today`; an open bound is left out. */\nexport const resolveAgentConversationListPeriod = (\n values: Pick<AgentConversationListValues, \"period\" | \"from\" | \"to\">,\n today: string,\n): { from?: string; to?: string } => {\n switch (readAgentConversationListPeriod(values)) {\n case \"today\":\n return { from: today, to: today };\n case \"7d\":\n return { from: shiftAgentInspectDay(today, -6), to: today };\n case \"30d\":\n return { from: shiftAgentInspectDay(today, -29), to: today };\n case \"all\":\n return {};\n default:\n return { ...(isDay(values.from) ? { from: values.from } : {}), ...(isDay(values.to) ? { to: values.to } : {}) };\n }\n};\n\n/** The values of a comma-separated key, trimmed, without empty ones and repeats. */\nexport const readAgentConversationListValues = (value: string): string[] => [\n ...new Set(\n value\n .split(\",\")\n .map((part) => part.trim())\n .filter((part) => part !== \"\"),\n ),\n];\n\n/** The ids of a comma-separated key; anything that is no positive whole number is dropped. */\nexport const readAgentConversationListIds = (value: string): number[] =>\n readAgentConversationListValues(value)\n .filter((part) => /^\\d+$/.test(part))\n .map(Number)\n .filter((id) => id > 0);\n\n/** The segment the values name; an unknown one reads as all. */\nexport const readAgentConversationListSegment = (value: string): AgentInspectSegment =>\n AGENT_INSPECT_SEGMENTS.find((segment) => segment === value) ?? \"ALL\";\n\n/** The order the values name; an unknown one reads as last activity first. */\nexport const readAgentConversationListSort = (value: string): AgentInspectSortOrder =>\n AGENT_INSPECT_SORT_ORDERS.find((sortOrder) => sortOrder === value) ?? \"LAST_ACTIVITY\";\n\n/** The page the values name, from 1. */\nexport const readAgentConversationListPage = (value: string): number => {\n const page = /^\\d+$/.test(value) ? Number(value) : 1;\n return page >= 1 ? page : 1;\n};\n\n/** A cost threshold as typed (`0.10`, `0,10`); undefined for no or an unreadable value. */\nexport const readAgentConversationListCost = (value: string): number | undefined => {\n const text = value.trim().replace(\",\", \".\");\n if (text === \"\" || !/^\\d*\\.?\\d+$/.test(text)) return undefined;\n const cost = Number(text);\n return Number.isFinite(cost) && cost > 0 ? cost : undefined;\n};\n\nconst textOrUndefined = (value: string): string | undefined => (value.trim() === \"\" ? undefined : value.trim());\n\nexport interface AgentConversationListArgOptions {\n /** The viewer's day (`YYYY-MM-DD`) the periods are resolved on. */\n today: string;\n /** Conversations per page. */\n pageSize: number;\n}\n\n/**\n * The request of the list for the URL's values. A value the route would refuse (an unknown segment or run state, a\n * day that is none, a cost that is no number) is left out, so a hand-edited URL still lists.\n */\nexport const buildAgentConversationListArg = (values: AgentConversationListValues, { today, pageSize }: AgentConversationListArgOptions): AgentInspectListArg => {\n const segment = readAgentConversationListSegment(values.segment);\n const accountIds = readAgentConversationListIds(values.accounts);\n const agentSpaceIds = readAgentConversationListIds(values.spaces);\n const runStates = readAgentConversationListValues(values.states).filter((state) => (AGENT_INSPECT_RUN_STATES as readonly string[]).includes(state));\n const page = readAgentConversationListPage(values.page);\n const sortOrder = readAgentConversationListSort(values.sort);\n return {\n ...resolveAgentConversationListPeriod(values, today),\n ...(accountIds.length > 0 ? { accountIds } : {}),\n ...(agentSpaceIds.length > 0 ? { agentSpaceIds } : {}),\n ...(runStates.length > 0 ? { runStates } : {}),\n purposeName: textOrUndefined(values.purpose),\n origin: textOrUndefined(values.origin),\n modelName: textOrUndefined(values.model),\n toolName: textOrUndefined(values.tool),\n loadedSkillName: textOrUndefined(values.skill),\n minimumCostInUSD: readAgentConversationListCost(values.minCost),\n search: textOrUndefined(values.q),\n ...(segment === \"ALL\" ? {} : { segment }),\n ...(sortOrder === \"LAST_ACTIVITY\" ? {} : { sortBy: sortOrder }),\n ...(values.evalRuns === \"1\" ? { includeEvalRuns: true } : {}),\n limit: pageSize,\n offset: (page - 1) * pageSize,\n };\n};\n\n/**\n * The request of the metrics and the segment counts: the list's filters without its page and its order (neither\n * changes a figure). The segment stays: the metrics follow it, the counts ignore it.\n */\nexport const buildAgentConversationMetricsArg = (values: AgentConversationListValues, today: string): AgentInspectListArg => {\n const { limit: _limit, offset: _offset, sortBy: _sortBy, ...filters } = buildAgentConversationListArg(values, { today, pageSize: 1 });\n return filters;\n};\n\n/**\n * The URL values that stand for a request (the reverse of `buildAgentConversationListArg` for a custom period): what\n * a link to a filtered list carries. Keys the request does not set are `\"\"`.\n */\nexport const buildAgentConversationListValues = (arg: AgentInspectListArg): AgentConversationListValues => {\n const pageSize = arg.limit !== undefined && arg.limit > 0 ? arg.limit : 0;\n const page = pageSize > 0 && arg.offset !== undefined ? Math.floor(arg.offset / pageSize) + 1 : 1;\n const hasBounds = arg.from !== undefined || arg.to !== undefined;\n return {\n segment: arg.segment !== undefined && arg.segment !== \"ALL\" ? arg.segment : \"\",\n q: arg.search ?? \"\",\n period: hasBounds ? \"custom\" : \"all\",\n from: arg.from ?? \"\",\n to: arg.to ?? \"\",\n accounts: (arg.accountIds ?? []).join(\",\"),\n spaces: (arg.agentSpaceIds ?? []).join(\",\"),\n purpose: arg.purposeName ?? \"\",\n states: (arg.runStates ?? []).join(\",\"),\n origin: arg.origin ?? \"\",\n model: arg.modelName ?? \"\",\n tool: arg.toolName ?? \"\",\n skill: arg.loadedSkillName ?? \"\",\n minCost: arg.minimumCostInUSD !== undefined ? String(arg.minimumCostInUSD) : \"\",\n evalRuns: arg.includeEvalRuns === true ? \"1\" : \"\",\n sort: arg.sortBy !== undefined && arg.sortBy !== \"LAST_ACTIVITY\" ? arg.sortBy : \"\",\n page: page > 1 ? String(page) : \"\",\n };\n};\n\n/** The query string of a link to the list with these values (`?segment=RUNNING&q=…`), `\"\"` without any. */\nexport const buildAgentConversationListSearch = (values: Partial<AgentConversationListValues>): string => {\n const parameters = new URLSearchParams();\n for (const key of AGENT_CONVERSATION_LIST_KEYS) {\n const value = values[key];\n if (value !== undefined && value !== \"\") parameters.set(key, value);\n }\n const search = parameters.toString();\n return search === \"\" ? \"\" : `?${search}`;\n};\n","import { normalizeDddError } from \"@mgamadeus/ddd-web/contract\";\nimport { DeltaText, MetricGrid, MetricTile } from \"@mgamadeus/ddd-admin-ui/data\";\nimport { formatUiNumber, m, useFormatLocale, useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport {\n EmptyValue,\n EntityListBody,\n type EntityListColumn,\n EntityListToolbar,\n FilterDateRange,\n FilterField,\n type FilterOption,\n FilterMultiSelect,\n FilterPanel,\n FilterSelect,\n FilterText,\n StatusBadge,\n Tag,\n} from \"@mgamadeus/ddd-admin-ui/list\";\nimport { type DateRangePreset, localToday, notify, type UrlStateAdapter, useUrlListState } from \"@mgamadeus/ddd-admin-ui/logic\";\nimport { EntityListPage } from \"@mgamadeus/ddd-admin-ui/page\";\nimport {\n Button,\n cn,\n DropdownMenu,\n DropdownMenuCheckboxItem,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuLabel,\n DropdownMenuTrigger,\n type PageLinkComponent,\n SegmentedControl,\n Switch,\n useLinkComponent,\n} from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { AlertTriangle, Check, ChevronDown, ChevronLeft, ChevronRight, Columns3, CornerDownRight, Download, RefreshCw, User } from \"lucide-react\";\nimport { type ReactNode, useEffect, useId, useMemo, useRef, useState } from \"react\";\nimport { describeTraceModelName, readTraceMoment } from \"../../chat/trace/trace-format\";\nimport { wireElementsOf } from \"../wire/admin-wire\";\nimport type { AgentInspectApi } from \"./agent-inspect-api\";\nimport {\n AGENT_INSPECT_ORIGINS,\n AGENT_INSPECT_RUN_STATES,\n AGENT_INSPECT_SORT_ORDERS,\n type AgentInspectConversationsResponse,\n type AgentInspectedConversation,\n type AgentInspectLabel,\n type AgentInspectListArg,\n type AgentInspectMetric,\n type AgentInspectSegment,\n type AgentInspectSortOrder,\n} from \"./agent-inspect-types\";\nimport {\n AGENT_CONVERSATION_EXPORT_MAX_ROWS,\n AGENT_CONVERSATION_EXPORT_PAGE_SIZE,\n type AgentConversationExportColumn,\n type AgentConversationExportRow,\n buildAgentConversationExportCsv,\n buildAgentConversationExportFileName,\n buildAgentConversationExportRow,\n readAgentConversationExcerpt,\n readAgentConversationExportProgress,\n} from \"./conversation-list-export\";\nimport {\n AGENT_CONVERSATION_LIST_KEYS,\n AGENT_CONVERSATION_LIST_UNCOUNTED_KEYS,\n type AgentConversationListKey,\n buildAgentConversationListArg,\n buildAgentConversationMetricsArg,\n readAgentConversationListIds,\n readAgentConversationListPage,\n readAgentConversationListPeriod,\n readAgentConversationListSegment,\n readAgentConversationListSort,\n readAgentConversationListValues,\n resolveAgentConversationListPeriod,\n shiftAgentInspectDay,\n} from \"./conversation-list-filters\";\nimport {\n AGENT_ORIGIN_CONTEXT,\n AGENT_ORIGIN_LABELS,\n AGENT_CONVERSATION_RUN_STATE,\n AGENT_CONVERSATION_RUN_STATE_CONTEXT,\n agentInspectLabelsById,\n agentInspectMetricChange,\n agentInspectMetricRelativeChange,\n agentOriginOf,\n describeAgentInspectMomentRelative,\n formatAgentInspectCost,\n formatAgentInspectCount,\n formatAgentInspectSeconds,\n isAgentRunLive,\n isKnownAgentRunState,\n} from \"./inspect-format\";\nimport { LiveDot } from \"./inspect-parts\";\nimport { useQueryLoader } from \"./use-query-loader\";\n\nexport interface AgentConversationsScreenProps {\n /** `createAgentInspectApi(…)` of the host. */\n api: AgentInspectApi;\n /** The host's URL adapter (`useNextUrlStateAdapter({ listId })`): segment, search, filters and page live in the URL. */\n urlStateAdapter: UrlStateAdapter;\n /** Default \"Agent conversations\". Already translated. */\n title?: ReactNode;\n description?: ReactNode;\n headerActions?: ReactNode;\n /** The route of a conversation's detail; `null` = no link. */\n buildConversationHref?: (conversationId: number) => string | null;\n /** Opens a conversation from a click anywhere on its row (the host's `router.push`). */\n onOpenConversation?: (conversationId: number) => void;\n /** The host's router link; default `AdminUiProvider.linkComponent`, else a plain `<a>`. */\n linkComponent?: PageLinkComponent;\n /** A cost in the host's currency and format. Default: US dollars. */\n formatCost?: (costInUsd: number) => string;\n /** Conversations per page (default 50, at most 200). */\n pageSize?: number;\n /** The choices of a filter; without them the filter is a text field (purpose, model, tool, skill). */\n purposeOptions?: readonly FilterOption[];\n modelOptions?: readonly FilterOption[];\n toolOptions?: readonly FilterOption[];\n skillOptions?: readonly FilterOption[];\n /** The accounts and spaces to pick from; default: the ones of the listed page. */\n accountOptions?: readonly FilterOption[];\n agentSpaceOptions?: readonly FilterOption[];\n /** Origins of the application beside the package's (its own initiator types). */\n originOptions?: readonly FilterOption[];\n /** Refetches the list while it shows a running conversation, every n ms (default 15000; 0 = off). */\n livePollingIntervalMs?: number;\n /**\n * The columns the reader switched off (`AGENT_CONVERSATION_COLUMN_IDS`), kept by the host (its stored preference);\n * with `onHiddenColumnIdsChange` the column chooser is controlled, without it the screen keeps the choice itself.\n */\n hiddenColumnIds?: readonly string[];\n onHiddenColumnIdsChange?: (hiddenColumnIds: string[]) => void;\n}\n\n/** The columns a reader may switch off in the column chooser (the conversation column always shows). */\nexport const AGENT_CONVERSATION_COLUMN_IDS = [\"space\", \"purpose\", \"state\", \"turns\", \"errors\", \"cost\", \"lastActivity\"] as const;\n\n/** The most conversations one page shows (the route's cap). */\nexport const AGENT_CONVERSATIONS_MAX_PAGE_SIZE = 200;\n\n/** One page of the export is one request: its filters and its offset name it. */\nconst exportPageKeyOf = (arg: AgentInspectListArg): string => JSON.stringify(arg);\n\n/** Hands a text to the browser as a file to save. */\nconst downloadCsvFile = (fileName: string, text: string) => {\n const url = URL.createObjectURL(new Blob([text], { type: \"text/csv;charset=utf-8\" }));\n const anchor = document.createElement(\"a\");\n anchor.href = url;\n anchor.download = fileName;\n document.body.appendChild(anchor);\n anchor.click();\n anchor.remove();\n URL.revokeObjectURL(url);\n};\n\ninterface ExcerptLineProps {\n icon: ReactNode;\n /** Whose text it is, for a reader who does not see the icon. */\n label: string;\n text: string;\n className?: string;\n}\n\n/** One excerpt of a conversation's row: whose text it is as a small icon, the text on one line, all of it as the tooltip. */\nconst ExcerptLine = ({ icon, label, text, className }: ExcerptLineProps) => (\n <span className={cn(\"flex min-w-0 items-center gap-1.5 text-xs\", className)} title={text} data-slot=\"agent-conversation-excerpt\">\n {icon}\n <span className=\"sr-only\">{label}: </span>\n <span className=\"min-w-0 truncate\">{text}</span>\n </span>\n);\n\nconst SEGMENT_OPTIONS: readonly { value: AgentInspectSegment; label: string; context: string }[] = [\n { value: \"ALL\", label: m(\"All\", { context: \"agent-conversation-segment\" }), context: \"agent-conversation-segment\" },\n { value: \"RUNNING\", label: m(\"Running now\", { context: \"agent-conversation-segment\" }), context: \"agent-conversation-segment\" },\n { value: \"AWAITING_OWNER\", label: m(\"Waiting for the admin\", { context: \"agent-conversation-segment\" }), context: \"agent-conversation-segment\" },\n { value: \"WITH_PROBLEMS\", label: m(\"With problems\", { context: \"agent-conversation-segment\" }), context: \"agent-conversation-segment\" },\n { value: \"SCHEDULED\", label: m(\"Scheduled runs\", { context: \"agent-conversation-segment\" }), context: \"agent-conversation-segment\" },\n { value: \"SUB_AGENTS\", label: m(\"Sub-agents\", { context: \"agent-conversation-segment\" }), context: \"agent-conversation-segment\" },\n];\n\nconst SORT_CONTEXT = \"agent-conversation-sort\";\n\n/** The orders of the list in words, as the line above the table names them. */\nconst SORT_LABELS: Readonly<Record<AgentInspectSortOrder, string>> = {\n LAST_ACTIVITY: m(\"Last activity\", { context: \"agent-conversation-sort\" }),\n CREATED: m(\"Newest first\", { context: \"agent-conversation-sort\" }),\n COST: m(\"Highest cost\", { context: \"agent-conversation-sort\" }),\n};\n\nconst COLUMN_CONTEXT = \"agent-conversation-column\";\n\n/** The names of the columns of the chooser. */\nconst COLUMN_LABELS: Readonly<Record<(typeof AGENT_CONVERSATION_COLUMN_IDS)[number], string>> = {\n space: m(\"Space\", { context: \"agent-conversation-column\" }),\n purpose: m(\"Purpose\", { context: \"agent-conversation-column\" }),\n state: m(\"State\", { context: \"agent-conversation-column\" }),\n turns: m(\"Turns\", { context: \"agent-conversation-column\" }),\n errors: m(\"Errors\", { context: \"agent-conversation-column\" }),\n cost: m(\"Cost\", { context: \"agent-conversation-column\" }),\n lastActivity: m(\"Last activity\", { context: \"agent-conversation-column\" }),\n};\n\n/** The period of the metrics in words (the caption of a tile names it: \"Conversations · 7 days\"). */\nconst PERIOD_CAPTIONS: Readonly<Record<string, string>> = {\n today: m(\"today\", { context: \"agent-conversation-metric-period\" }),\n \"7d\": m(\"7 days\", { context: \"agent-conversation-metric-period\" }),\n \"30d\": m(\"30 days\", { context: \"agent-conversation-metric-period\" }),\n // the whole time: the list and the metrics read without bounds\n all: m(\"all time\", { context: \"agent-conversation-metric-period\" }),\n};\n\nconst PERIOD_PRESETS: readonly DateRangePreset[] = [\n { id: \"today\", label: m(\"Today\", { context: \"agent-conversation-period\" }), context: \"agent-conversation-period\", resolve: (today) => ({ from: today, to: today }) },\n {\n id: \"7d\",\n label: m(\"7 days\", { context: \"agent-conversation-period\" }),\n context: \"agent-conversation-period\",\n resolve: (today) => ({ from: shiftAgentInspectDay(today, -6), to: today }),\n },\n {\n id: \"30d\",\n label: m(\"30 days\", { context: \"agent-conversation-period\" }),\n context: \"agent-conversation-period\",\n resolve: (today) => ({ from: shiftAgentInspectDay(today, -29), to: today }),\n },\n { id: \"all\", label: m(\"All time\", { context: \"agent-conversation-period\" }), context: \"agent-conversation-period\", resolve: () => ({ from: \"\", to: \"\" }) },\n { id: \"custom\", label: m(\"Custom\", { context: \"agent-conversation-period\" }), context: \"agent-conversation-period\" },\n];\n\ninterface MetricTilesProps {\n metricOf: (name: MetricName) => AgentInspectMetric | null;\n isLoading: boolean;\n formatCost: (costInUsd: number) => string;\n locale: string | undefined;\n /** The period of the figures in words (\"7 days\"), already translated. */\n periodCaption: string;\n /** A quiet line under the cost (where it comes from, since when it is covered), already translated; null for none. */\n costHint: string | null;\n}\n\ntype MetricName = \"conversationCount\" | \"costInUSD\" | \"averageCostInUSD\" | \"conversationWithErrorsCount\" | \"cacheHitPercent\" | \"medianAnswerSeconds\";\n\n/** The six figures of the period, each with its change against the period of equal length before. */\nconst MetricTiles = ({ metricOf, isLoading, formatCost, locale, periodCaption, costHint }: MetricTilesProps) => {\n const { t } = useTranslate();\n const comparedWith = t(\"Against the period of equal length before.\");\n const valueOf = (name: MetricName, format: (value: number) => string): ReactNode => {\n const value = metricOf(name)?.value ?? null;\n return value === null ? <EmptyValue /> : format(value);\n };\n const secondsChange = agentInspectMetricChange(metricOf(\"medianAnswerSeconds\"));\n return (\n <MetricGrid columns={6} isLoading={isLoading} size=\"compact\">\n <MetricTile\n size=\"compact\"\n label={t(\"Conversations · %period%\", { context: \"agent-conversation-metric\", replacements: { period: periodCaption } })}\n value={valueOf(\"conversationCount\", (value) => formatUiNumber(value))}\n delta={<DeltaText value={agentInspectMetricRelativeChange(metricOf(\"conversationCount\"))} format=\"percent\" preference=\"none\" title={comparedWith} />}\n />\n <MetricTile\n size=\"compact\"\n label={t(\"Cost · %period%\", { context: \"agent-conversation-metric\", replacements: { period: periodCaption } })}\n value={valueOf(\"costInUSD\", formatCost)}\n delta={<DeltaText value={agentInspectMetricRelativeChange(metricOf(\"costInUSD\"))} format=\"percent\" preference=\"lower\" title={comparedWith} />}\n hint={costHint !== null ? <span data-testid=\"agent-conversations-cost-hint\">{costHint}</span> : undefined}\n />\n <MetricTile\n size=\"compact\"\n label={t(\"Avg. per conversation\", { context: \"agent-conversation-metric\" })}\n value={valueOf(\"averageCostInUSD\", formatCost)}\n delta={<DeltaText value={agentInspectMetricRelativeChange(metricOf(\"averageCostInUSD\"))} format=\"percent\" preference=\"lower\" title={comparedWith} />}\n />\n <MetricTile\n size=\"compact\"\n label={t(\"With errors\", { context: \"agent-conversation-metric\" })}\n value={valueOf(\"conversationWithErrorsCount\", (value) => formatUiNumber(value))}\n delta={<DeltaText value={agentInspectMetricChange(metricOf(\"conversationWithErrorsCount\"))} preference=\"lower\" title={comparedWith} />}\n className={(metricOf(\"conversationWithErrorsCount\")?.value ?? 0) > 0 ? \"shadow-[inset_3px_0_0_var(--destructive)]\" : undefined}\n />\n <MetricTile\n size=\"compact\"\n label={t(\"Cache hits\", { context: \"agent-conversation-metric\" })}\n value={valueOf(\"cacheHitPercent\", (value) => `${formatUiNumber(Math.round(value))} %`)}\n delta={\n <DeltaText\n value={agentInspectMetricChange(metricOf(\"cacheHitPercent\"))}\n format={{ maximumFractionDigits: 0 }}\n epsilon={0.5}\n title={comparedWith}\n />\n }\n />\n <MetricTile\n size=\"compact\"\n label={t(\"Answer time (p50)\", { context: \"agent-conversation-metric\" })}\n value={valueOf(\"medianAnswerSeconds\", (value) => formatAgentInspectSeconds(value, locale))}\n delta={\n secondsChange === null ? null : (\n <DeltaText\n text={`${secondsChange > 0 ? \"+\" : secondsChange < 0 ? \"−\" : \"\"}${formatAgentInspectSeconds(Math.abs(secondsChange), locale)}`}\n direction={Math.abs(secondsChange) < 0.05 ? \"flat\" : secondsChange > 0 ? \"up\" : \"down\"}\n preference=\"lower\"\n title={comparedWith}\n />\n )\n }\n />\n </MetricGrid>\n );\n};\n\n/**\n * The conversations of the agent as an analysis list: the figures of the period with their change against the period\n * before, the segments (all, running, awaiting owner, with problems, scheduled runs, sub-agents), a search, filters\n * (period, account, space, purpose, run state, origin, model, tool, skill, cost, evaluation runs) and a table with what each\n * conversation is about (its title, the start of the owner's first message and of the newest answer), whose it is,\n * what it cost and where it stands. Segment, search, filters and page live in the URL through `urlStateAdapter`; a row\n * opens the conversation's detail (`buildConversationHref`, `onOpenConversation`). The runs of evaluation suites are\n * left out unless the filter \"Include evaluation runs\" is on. \"Export CSV\" writes the filtered list as a file, every\n * page of it up to `AGENT_CONVERSATION_EXPORT_MAX_ROWS` conversations.\n * Needs `AdminAgentConversationsInspectTrait` mounted at the api's prefix; which conversations a reader sees is the\n * server's scope. Render it inside `<Suspense>` when the adapter reads search parameters.\n */\nexport const AgentConversationsScreen = ({\n api,\n urlStateAdapter,\n title,\n description,\n headerActions,\n buildConversationHref,\n onOpenConversation,\n linkComponent,\n formatCost: formatCostOfHost,\n pageSize = 50,\n purposeOptions,\n modelOptions,\n toolOptions,\n skillOptions,\n accountOptions,\n agentSpaceOptions,\n originOptions,\n livePollingIntervalMs = 15_000,\n hiddenColumnIds: hiddenColumnIdsOfHost,\n onHiddenColumnIdsChange,\n}: AgentConversationsScreenProps) => {\n const { t } = useTranslate();\n const locale = useFormatLocale();\n const evalRunsSwitchId = useId();\n const Link = useLinkComponent(linkComponent);\n const formatCost = useMemo(() => formatCostOfHost ?? ((costInUsd: number) => formatAgentInspectCost(costInUsd, locale)), [formatCostOfHost, locale]);\n const list = useUrlListState(AGENT_CONVERSATION_LIST_KEYS, { adapter: urlStateAdapter, uncounted: AGENT_CONVERSATION_LIST_UNCOUNTED_KEYS });\n const conversationsPerPage = Math.min(Math.max(Math.floor(pageSize), 1), AGENT_CONVERSATIONS_MAX_PAGE_SIZE);\n const today = localToday();\n\n const listArg = useMemo(\n () => buildAgentConversationListArg(list.debounced, { today, pageSize: conversationsPerPage }),\n [list.debounced, today, conversationsPerPage],\n );\n const metricsArg = useMemo(() => buildAgentConversationMetricsArg(list.debounced, today), [list.debounced, today]);\n const page = readAgentConversationListPage(list.debounced.page);\n const segment = readAgentConversationListSegment(list.values.segment);\n const period = readAgentConversationListPeriod(list.values);\n const shownRange = resolveAgentConversationListPeriod(list.values, today);\n // The period the reader picked last: a preset's bounds follow its id, and only a custom period stores days.\n const pickedPeriod = useRef(period);\n pickedPeriod.current = period;\n\n const sortOrder = readAgentConversationListSort(list.values.sort);\n const [ownHiddenColumnIds, setOwnHiddenColumnIds] = useState<readonly string[]>([]);\n const hiddenColumnIds = onHiddenColumnIdsChange !== undefined ? (hiddenColumnIdsOfHost ?? []) : ownHiddenColumnIds;\n const setHiddenColumnIds = (nextHiddenColumnIds: string[]) => {\n if (onHiddenColumnIdsChange !== undefined) onHiddenColumnIdsChange(nextHiddenColumnIds);\n else setOwnHiddenColumnIds(nextHiddenColumnIds);\n };\n const periodCaption =\n period === \"custom\"\n ? shownRange.from !== undefined && shownRange.to !== undefined\n ? t(\"{count, plural, one {# day} other {# days}}\", {\n count: Math.round((Date.parse(`${shownRange.to}T00:00:00Z`) - Date.parse(`${shownRange.from}T00:00:00Z`)) / 86_400_000) + 1,\n })\n : t(\"Custom\", { context: \"agent-conversation-period\" })\n : t(PERIOD_CAPTIONS[period] ?? PERIOD_CAPTIONS[\"7d\"], { context: \"agent-conversation-metric-period\" });\n\n const metricsQuery = api.useMetricsQuery(metricsArg);\n const segmentCountOf = (segmentOfCount: AgentInspectSegment): number | null => {\n const count = wireElementsOf(metricsQuery.data?.segmentCounts).find((segmentCount) => segmentCount.segment === segmentOfCount)?.conversationCount;\n return typeof count === \"number\" ? count : null;\n };\n const segmentOptions = SEGMENT_OPTIONS.map((option) => {\n const count = segmentCountOf(option.value);\n return count === null ? option : { ...option, badge: formatUiNumber(count), description: t(\"{count, plural, one {# conversation} other {# conversations}}\", { count }) };\n });\n const shownSegmentCount = segmentCountOf(segment);\n const listProbe = api.useConversationsQuery(listArg);\n const hasLiveRow = wireElementsOf(listProbe.data?.conversations).some((conversation) => isAgentRunLive(conversation.runState, conversation.runHeartbeatAt, Date.now()));\n // The same arguments answer from the same cache entry: the second subscription only adds the polling while a row is live.\n const listQuery = api.useConversationsQuery(listArg, { pollingInterval: hasLiveRow ? livePollingIntervalMs : 0 });\n\n const conversations = wireElementsOf(listQuery.data?.conversations);\n const hasMore = listQuery.data?.hasMore === true;\n const accountLabelById = useMemo(() => agentInspectLabelsById(listQuery.data?.accountLabels), [listQuery.data?.accountLabels]);\n const agentSpaceLabelById = useMemo(() => agentInspectLabelsById(listQuery.data?.agentSpaceLabels), [listQuery.data?.agentSpaceLabels]);\n const highestCost = conversations.reduce((highest, conversation) => Math.max(highest, conversation.costInUSD ?? 0), 0);\n\n /** A filter change starts at the first page again. */\n const setFilter = (key: AgentConversationListKey, value: string) => list.setValues({ [key]: value, page: \"\" });\n const setPage = (nextPage: number) => list.setValue(\"page\", nextPage > 1 ? String(nextPage) : \"\");\n\n const optionsWithPicked = (hostOptions: readonly FilterOption[] | undefined, labelById: Map<number, { label?: string | null }>, pickedIds: readonly number[]): FilterOption[] => {\n if (hostOptions !== undefined) return [...hostOptions];\n const options = new Map<string, FilterOption>();\n for (const [id, label] of labelById) options.set(String(id), { value: String(id), label: label.label || `#${id}` });\n for (const id of pickedIds) if (!options.has(String(id))) options.set(String(id), { value: String(id), label: `#${id}` });\n return [...options.values()];\n };\n const pickedAccountIds = readAgentConversationListIds(list.values.accounts);\n const pickedAgentSpaceIds = readAgentConversationListIds(list.values.spaces);\n\n const runStateOptions = AGENT_INSPECT_RUN_STATES.map((runState) => ({\n value: runState,\n label: t(AGENT_CONVERSATION_RUN_STATE[runState].label, { context: AGENT_CONVERSATION_RUN_STATE_CONTEXT }),\n }));\n const describeOrigin = (origin: string): string =>\n Object.hasOwn(AGENT_ORIGIN_LABELS, origin)\n ? t(AGENT_ORIGIN_LABELS[origin], { context: AGENT_ORIGIN_CONTEXT })\n : (originOptions?.find((option) => option.value === origin)?.label ?? origin);\n const allOriginOptions = [\n ...AGENT_INSPECT_ORIGINS.map((origin) => ({ value: origin as string, label: describeOrigin(origin) })),\n ...(originOptions ?? []).filter((option) => !(AGENT_INSPECT_ORIGINS as readonly string[]).includes(option.value)),\n ];\n\n const textOrSelect = (key: AgentConversationListKey, label: string, placeholder: string, options: readonly FilterOption[] | undefined) =>\n options !== undefined ? (\n <FilterSelect label={label} value={list.values[key]} onChange={(value) => setFilter(key, value)} options={options} allLabel={t(\"All\", { context: \"agent-conversation-filter\" })} />\n ) : (\n <FilterText label={label} placeholder={placeholder} value={list.values[key]} onChange={(value) => setFilter(key, value)} />\n );\n\n // The export reads the filtered list page by page, whatever page the table shows; a run that was overtaken (a new\n // export, the screen gone) stops at its next page.\n const [loadExportPage, exportRunners] = useQueryLoader<AgentInspectListArg, AgentInspectConversationsResponse>(api.useConversationsQuery, exportPageKeyOf);\n const [exportedCount, setExportedCount] = useState<number | null>(null);\n const exportRun = useRef(0);\n useEffect(\n () => () => {\n exportRun.current += 1;\n },\n [],\n );\n const exportCsv = async () => {\n exportRun.current += 1;\n const run = exportRun.current;\n setExportedCount(0);\n const exported: AgentInspectedConversation[] = [];\n const accountLabels = new Map<number, AgentInspectLabel>();\n const agentSpaceLabels = new Map<number, AgentInspectLabel>();\n let wasCut = false;\n try {\n for (let offset = 0; ; offset += AGENT_CONVERSATION_EXPORT_PAGE_SIZE) {\n const answer = await loadExportPage({\n ...metricsArg,\n ...(listArg.sortBy !== undefined ? { sortBy: listArg.sortBy } : {}),\n limit: AGENT_CONVERSATION_EXPORT_PAGE_SIZE,\n offset,\n });\n if (exportRun.current !== run) return;\n const pageConversations = wireElementsOf(answer.conversations);\n exported.push(...pageConversations);\n for (const [id, label] of agentInspectLabelsById(answer.accountLabels)) accountLabels.set(id, label);\n for (const [id, label] of agentInspectLabelsById(answer.agentSpaceLabels)) agentSpaceLabels.set(id, label);\n setExportedCount(Math.min(exported.length, AGENT_CONVERSATION_EXPORT_MAX_ROWS));\n const progress = readAgentConversationExportProgress(exported.length, { rowCount: pageConversations.length, hasMore: answer.hasMore === true });\n if (progress.isDone) {\n wasCut = progress.wasCut;\n break;\n }\n }\n } catch (caught) {\n if (exportRun.current === run) {\n setExportedCount(null);\n notify.error(normalizeDddError(caught, t(\"The conversations could not be exported.\")).message);\n }\n return;\n }\n const rows: AgentConversationExportRow[] = exported.slice(0, AGENT_CONVERSATION_EXPORT_MAX_ROWS).map((conversation) =>\n buildAgentConversationExportRow(conversation, {\n accountLabelById: accountLabels,\n agentSpaceLabelById: agentSpaceLabels,\n describeOrigin: (exportedConversation) => describeOrigin(agentOriginOf(exportedConversation)),\n describeRunState: (runState) =>\n isKnownAgentRunState(runState) ? t(AGENT_CONVERSATION_RUN_STATE[runState].label, { context: AGENT_CONVERSATION_RUN_STATE_CONTEXT }) : runState,\n accountLevelLabel: t(\"Account level\", { context: \"agent-conversation-space\" }),\n }),\n );\n const headerByColumn: Record<AgentConversationExportColumn, string> = {\n id: t(\"ID\", { context: \"agent-conversation-export\" }),\n title: t(\"Title\", { context: \"agent-conversation-export\" }),\n firstOwnerText: t(\"First message of the owner\", { context: \"agent-conversation-excerpt\" }),\n lastAnswerText: t(\"Last answer\", { context: \"agent-conversation-excerpt\" }),\n space: t(\"Space\", { context: \"agent-conversation-column\" }),\n account: t(\"Account\", { context: \"agent-conversation-filter\" }),\n purpose: t(\"Purpose\", { context: \"agent-conversation-column\" }),\n origin: t(\"Origin\", { context: \"agent-conversation-filter\" }),\n runState: t(\"State\", { context: \"agent-conversation-column\" }),\n turns: t(\"Turns\", { context: \"agent-conversation-column\" }),\n inputTokens: t(\"Tokens in\", { context: \"agent-conversation-export\" }),\n outputTokens: t(\"Tokens out\", { context: \"agent-conversation-export\" }),\n cachedInputTokens: t(\"Tokens from the cache\", { context: \"agent-conversation-export\" }),\n problems: t(\"Errors\", { context: \"agent-conversation-column\" }),\n costInUsd: t(\"Cost (USD)\", { context: \"agent-conversation-export\" }),\n models: t(\"Models\", { context: \"agent-conversation-export\" }),\n subAgents: t(\"Sub-agents\", { context: \"agent-conversation-segment\" }),\n created: t(\"Created\", { context: \"agent-conversation-export\" }),\n lastActivity: t(\"Last activity\", { context: \"agent-conversation-column\" }),\n };\n downloadCsvFile(buildAgentConversationExportFileName({ from: metricsArg.from, to: metricsArg.to }), buildAgentConversationExportCsv(headerByColumn, rows));\n setExportedCount(null);\n if (wasCut) {\n notify.info(\n t(\"The export holds the first %count% conversations of the filtered list. Narrow the filters to export the rest.\", {\n replacements: { count: formatUiNumber(rows.length) },\n }),\n );\n } else {\n notify.success(t(\"{count, plural, one {# conversation exported.} other {# conversations exported.}}\", { count: rows.length }));\n }\n };\n const isExporting = exportedCount !== null;\n\n const allColumns: EntityListColumn<AgentInspectedConversation>[] = [\n {\n id: \"conversation\",\n header: t(\"Conversation\", { context: \"agent-conversation-column\" }),\n width: \"2.4fr\",\n minWidth: 260,\n cell: (conversation) => {\n const conversationId = conversation.aiConversationId ?? 0;\n const href = buildConversationHref?.(conversationId) ?? null;\n const name = conversation.title || t(\"Conversation #%id%\", { replacements: { id: conversationId } });\n const firstOwnerText = readAgentConversationExcerpt(conversation.firstOwnerTextExcerpt);\n const lastAnswerText = readAgentConversationExcerpt(conversation.lastAnswerTextExcerpt);\n const modelNames = conversation.modelNames ?? [];\n return (\n <div className=\"flex min-w-0 flex-col gap-0.5\">\n {href !== null ? (\n <Link href={href} className=\"block truncate font-semibold text-foreground hover:underline\">\n {name}\n </Link>\n ) : (\n <span className=\"block truncate font-semibold\">{name}</span>\n )}\n {firstOwnerText !== null ? (\n <ExcerptLine\n icon={<User className=\"size-3 shrink-0 text-muted-foreground\" aria-hidden />}\n label={t(\"First message of the owner\", { context: \"agent-conversation-excerpt\" })}\n text={firstOwnerText}\n className=\"text-foreground/80\"\n />\n ) : null}\n {lastAnswerText !== null ? (\n <ExcerptLine\n icon={<CornerDownRight className=\"size-3 shrink-0 text-brand-emphasis\" aria-hidden />}\n label={t(\"Last answer\", { context: \"agent-conversation-excerpt\" })}\n text={lastAnswerText}\n className=\"text-muted-foreground\"\n />\n ) : null}\n <span className=\"block truncate text-[11px] text-muted-foreground\">\n #{conversationId}\n {(conversation.subAgentCount ?? 0) > 0 &&\n ` · ${t(\"{count, plural, one {# sub-agent} other {# sub-agents}}\", { count: conversation.subAgentCount ?? 0 })}`}\n {modelNames.length > 0 ? (\n <span title={modelNames.join(\", \")}>\n {\" · \"}\n {modelNames.map((modelName, position) => conversation.modelLabels?.[position] || describeTraceModelName(modelName) || modelName).join(\", \")}\n </span>\n ) : null}\n </span>\n </div>\n );\n },\n },\n {\n id: \"space\",\n header: t(\"Space\", { context: \"agent-conversation-column\" }),\n width: \"1.1fr\",\n minWidth: 165,\n cell: (conversation) => {\n const spaceLabel = conversation.agentSpaceId ? agentSpaceLabelById.get(conversation.agentSpaceId) : undefined;\n const accountLabel = conversation.accountId ? accountLabelById.get(conversation.accountId) : undefined;\n return (\n <div className=\"min-w-0 text-[13px]\">\n <span className=\"block truncate\">\n {conversation.agentSpaceId\n ? spaceLabel?.label || `#${conversation.agentSpaceId}`\n : t(\"Account level\", { context: \"agent-conversation-space\" })}\n {spaceLabel?.description && !(spaceLabel.label ?? \"\").toLowerCase().includes(spaceLabel.description.toLowerCase()) ? (\n <span className=\"text-muted-foreground\"> · {spaceLabel.description}</span>\n ) : null}\n </span>\n <span className=\"block truncate text-xs text-muted-foreground\">\n {conversation.accountId ? accountLabel?.label || `#${conversation.accountId}` : \"—\"}\n </span>\n </div>\n );\n },\n },\n {\n id: \"purpose\",\n header: t(\"Purpose\", { context: \"agent-conversation-column\" }),\n width: \"0.9fr\",\n minWidth: 110,\n cell: (conversation) => (\n <div className=\"flex min-w-0 flex-col items-start gap-1\">\n <Tag size=\"sm\">{describeOrigin(agentOriginOf(conversation))}</Tag>\n {conversation.purposeName ? (\n <span className=\"max-w-full truncate font-mono text-[11px] text-muted-foreground\" title={conversation.purposeName}>\n {conversation.purposeName}\n </span>\n ) : null}\n </div>\n ),\n },\n {\n id: \"state\",\n header: t(\"State\", { context: \"agent-conversation-column\" }),\n width: \"content\",\n cell: (conversation) => (\n <span className=\"inline-flex items-center gap-1.5\">\n {isAgentRunLive(conversation.runState, conversation.runHeartbeatAt, Date.now()) ? <LiveDot label={t(\"A turn runs right now\")} /> : null}\n {isKnownAgentRunState(conversation.runState) ? (\n <StatusBadge value={conversation.runState} map={AGENT_CONVERSATION_RUN_STATE} />\n ) : conversation.runState ? (\n <StatusBadge tone=\"neutral\" label={conversation.runState} />\n ) : (\n <EmptyValue />\n )}\n </span>\n ),\n },\n {\n id: \"turns\",\n header: t(\"Turns\", { context: \"agent-conversation-column\" }),\n width: \"content\",\n align: \"end\",\n cell: (conversation) => <span className=\"tabular-nums\">{formatUiNumber(conversation.turnCount ?? 0)}</span>,\n },\n {\n id: \"errors\",\n header: t(\"Errors\", { context: \"agent-conversation-column\" }),\n width: \"content\",\n align: \"end\",\n cell: (conversation) =>\n (conversation.failedRowCount ?? 0) > 0 ? (\n <span className=\"inline-flex items-center gap-1 font-semibold text-destructive tabular-nums\">\n <AlertTriangle className=\"size-3.5\" aria-hidden />\n {formatUiNumber(conversation.failedRowCount ?? 0)}\n </span>\n ) : (\n <EmptyValue />\n ),\n },\n {\n id: \"cost\",\n header: t(\"Cost\", { context: \"agent-conversation-column\" }),\n width: \"content\",\n align: \"end\",\n cell: (conversation) => {\n const cost = conversation.costInUSD ?? 0;\n const tokens = (conversation.inputTokens ?? 0) + (conversation.outputTokens ?? 0);\n return (\n <span className=\"inline-flex min-w-16 flex-col items-end gap-0.5\">\n <span className=\"tabular-nums\">{formatCost(cost)}</span>\n {tokens > 0 ? (\n <span\n className=\"text-[11px] whitespace-nowrap text-muted-foreground tabular-nums\"\n title={t(\"%input% in, %output% out, %cached% from the cache\", {\n replacements: {\n input: formatUiNumber(conversation.inputTokens ?? 0),\n output: formatUiNumber(conversation.outputTokens ?? 0),\n cached: formatUiNumber(conversation.cachedInputTokens ?? 0),\n },\n })}\n >\n {t(\"%count% tokens\", { replacements: { count: formatAgentInspectCount(tokens, locale) } })}\n </span>\n ) : null}\n <span\n className=\"block h-1 rounded-full bg-brand\"\n style={{ width: `${highestCost > 0 ? Math.max(4, Math.round((cost / highestCost) * 48)) : 0}px` }}\n aria-hidden\n />\n </span>\n );\n },\n },\n {\n id: \"lastActivity\",\n header: t(\"Last activity\", { context: \"agent-conversation-column\" }),\n width: \"content\",\n align: \"end\",\n cell: (conversation) => {\n const moment = readTraceMoment(conversation.lastMessageAt ?? conversation.lastActivityAt ?? conversation.created);\n if (moment === null) return <EmptyValue />;\n return (\n <span\n className=\"whitespace-nowrap text-xs text-muted-foreground tabular-nums\"\n title={new Intl.DateTimeFormat(locale, { dateStyle: \"medium\", timeStyle: \"short\" }).format(moment)}\n data-slot=\"agent-conversation-last-activity\"\n >\n {describeAgentInspectMomentRelative(moment, Date.now(), locale, t(\"just now\", { context: \"agent-conversation-moment\" }))}\n </span>\n );\n },\n },\n ];\n const columns = allColumns.filter((column) => !hiddenColumnIds.includes(column.id));\n const shownColumnIds = AGENT_CONVERSATION_COLUMN_IDS.filter((columnId) => !hiddenColumnIds.includes(columnId));\n\n const metrics = metricsQuery.data?.metrics ?? null;\n // The cost of the period comes from the usage log (the same figure as the statistics of the control panel), a\n // narrowed list sums the conversation trees instead; the log may start after the window does.\n const costCoveredFrom = metrics?.costDataAvailableFrom?.slice(0, 10) ?? null;\n const windowStart = metrics?.activeFrom?.slice(0, 10) ?? null;\n const costHintParts = [\n metrics?.costSource === \"CONVERSATION_TREES\" ? t(\"summed over the listed conversations\") : null,\n costCoveredFrom !== null && /^\\d{4}-\\d{2}-\\d{2}$/.test(costCoveredFrom) && (windowStart === null || costCoveredFrom > windowStart)\n ? t(\"covered since %date%\", {\n replacements: { date: new Intl.DateTimeFormat(locale, { dateStyle: \"medium\", timeZone: \"UTC\" }).format(new Date(`${costCoveredFrom}T00:00:00Z`)) },\n })\n : null,\n ].filter((part): part is string => part !== null);\n const costHint = costHintParts.length > 0 ? costHintParts.join(\" · \") : null;\n return (\n <EntityListPage\n title={title ?? t(\"Agent conversations\")}\n label={t(\"Agent conversations\")}\n description={description ?? t(\"Every conversation with the agent: whose it is, what it is about, what it cost and where it stands. A row opens the conversation.\")}\n headerActions={\n <div className=\"flex flex-wrap items-center gap-2\">\n {headerActions}\n <Button\n type=\"button\"\n variant=\"outline\"\n data-testid=\"agent-conversations-export\"\n data-exporting={isExporting ? \"true\" : undefined}\n onClick={() => void exportCsv()}\n disabled={isExporting || listQuery.isLoading || conversations.length === 0}\n title={t(\"Exports the filtered list, every page of it, up to %count% conversations.\", {\n replacements: { count: formatUiNumber(AGENT_CONVERSATION_EXPORT_MAX_ROWS) },\n })}\n >\n <Download className={cn(isExporting && \"animate-pulse motion-reduce:animate-none\")} />\n {isExporting\n ? t(\"Exporting… %count%\", { replacements: { count: formatUiNumber(exportedCount ?? 0) }, context: \"agent-conversation-export\" })\n : t(\"Export CSV\", { context: \"agent-conversation-export\" })}\n </Button>\n <Button\n type=\"button\"\n variant=\"outline\"\n data-testid=\"agent-conversations-refresh\"\n onClick={() => {\n void listQuery.refetch();\n void metricsQuery.refetch();\n }}\n disabled={listQuery.isFetching}\n >\n <RefreshCw className={cn(listQuery.isFetching && \"animate-spin\")} />\n {t(\"Refresh\")}\n </Button>\n </div>\n }\n belowHeader={\n <div className=\"space-y-3\" data-testid=\"agent-conversations-summary\">\n <MetricTiles\n metricOf={(name) => metrics?.[name] ?? null}\n isLoading={metricsQuery.isLoading}\n formatCost={formatCost}\n locale={locale}\n periodCaption={periodCaption}\n costHint={costHint}\n />\n <SegmentedControl\n aria-label={t(\"Segment of the conversations\")}\n value={segment}\n onValueChange={(value) => setFilter(\"segment\", value === \"ALL\" ? \"\" : value)}\n options={segmentOptions}\n height={36}\n />\n </div>\n }\n isRefetching={listQuery.isFetching && !listQuery.isLoading}\n toolbar={\n <EntityListToolbar\n search={{\n value: list.values.q,\n onChange: (value) => setFilter(\"q\", value),\n placeholder: t(\"Title, summary or conversation ID\"),\n }}\n activeFilterCount={list.activeFilterCount}\n onClearFilters={list.clear}\n filters={\n <FilterPanel>\n <FilterDateRange\n label={t(\"Last activity\", { context: \"agent-conversation-filter\" })}\n presets={PERIOD_PRESETS}\n preset={period}\n onPresetChange={(preset) => {\n pickedPeriod.current = readAgentConversationListPeriod({ period: preset, from: \"\", to: \"\" });\n list.setValues(preset === \"custom\" ? { period: preset, page: \"\" } : { period: preset, from: \"\", to: \"\", page: \"\" });\n }}\n from={shownRange.from ?? \"\"}\n to={shownRange.to ?? \"\"}\n onFromChange={(from) => pickedPeriod.current === \"custom\" && list.setValues({ from, page: \"\" })}\n onToChange={(to) => pickedPeriod.current === \"custom\" && list.setValues({ to, page: \"\" })}\n onRangeChange={(range) => pickedPeriod.current === \"custom\" && list.setValues({ from: range.from, to: range.to, page: \"\" })}\n today={today}\n />\n <FilterMultiSelect\n label={t(\"Account\", { context: \"agent-conversation-filter\" })}\n allLabel={t(\"All accounts\")}\n value={pickedAccountIds.map(String)}\n onChange={(values) => setFilter(\"accounts\", values.join(\",\"))}\n options={optionsWithPicked(accountOptions, accountLabelById, pickedAccountIds)}\n />\n <FilterMultiSelect\n label={t(\"Space\", { context: \"agent-conversation-filter\" })}\n allLabel={t(\"All spaces\")}\n value={pickedAgentSpaceIds.map(String)}\n onChange={(values) => setFilter(\"spaces\", values.join(\",\"))}\n options={optionsWithPicked(agentSpaceOptions, agentSpaceLabelById, pickedAgentSpaceIds)}\n />\n {textOrSelect(\"purpose\", t(\"Purpose\", { context: \"agent-conversation-filter\" }), t(\"Purpose name\"), purposeOptions)}\n <FilterMultiSelect\n label={t(\"Run state\", { context: \"agent-conversation-filter\" })}\n allLabel={t(\"All states\")}\n value={readAgentConversationListValues(list.values.states)}\n onChange={(values) => setFilter(\"states\", values.join(\",\"))}\n options={runStateOptions}\n />\n <FilterSelect\n label={t(\"Origin\", { context: \"agent-conversation-filter\" })}\n allLabel={t(\"All\", { context: \"agent-conversation-filter\" })}\n value={list.values.origin}\n onChange={(value) => setFilter(\"origin\", value)}\n options={allOriginOptions}\n />\n {textOrSelect(\"model\", t(\"Model\", { context: \"agent-conversation-filter\" }), t(\"Model name\"), modelOptions)}\n {textOrSelect(\"tool\", t(\"Tool\", { context: \"agent-conversation-filter\" }), t(\"Tool name\"), toolOptions)}\n {textOrSelect(\"skill\", t(\"Loaded skill\", { context: \"agent-conversation-filter\" }), t(\"Skill name\"), skillOptions)}\n <FilterText\n label={t(\"Cost at least (USD)\", { context: \"agent-conversation-filter\" })}\n placeholder=\"0.10\"\n value={list.values.minCost}\n onChange={(value) => setFilter(\"minCost\", value.replace(/[^\\d.,]/g, \"\"))}\n />\n <FilterField label={t(\"Include evaluation runs\", { context: \"agent-conversation-filter\" })} htmlFor={evalRunsSwitchId}>\n <div className=\"flex h-8 items-center\">\n <Switch\n id={evalRunsSwitchId}\n size=\"sm\"\n checked={list.values.evalRuns === \"1\"}\n onCheckedChange={(checked) => setFilter(\"evalRuns\", checked ? \"1\" : \"\")}\n data-testid=\"agent-conversations-eval-runs\"\n />\n </div>\n </FilterField>\n </FilterPanel>\n }\n trailing={\n page > 1 || hasMore ? (\n <div className=\"flex items-center gap-1.5\" data-testid=\"agent-conversations-pagination\">\n <span className=\"text-xs text-muted-foreground tabular-nums\">{t(\"Page %page%\", { replacements: { page: formatUiNumber(page) } })}</span>\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"icon-sm\"\n aria-label={t(\"Previous page\")}\n disabled={page <= 1 || listQuery.isFetching}\n onClick={() => setPage(page - 1)}\n >\n <ChevronLeft />\n </Button>\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"icon-sm\"\n aria-label={t(\"Next page\")}\n disabled={!hasMore || listQuery.isFetching}\n onClick={() => setPage(page + 1)}\n >\n <ChevronRight />\n </Button>\n </div>\n ) : undefined\n }\n />\n }\n >\n <div className=\"flex flex-wrap items-center gap-x-2 gap-y-1 px-2 pt-1 pb-2 text-[13px] tabular-nums\" data-testid=\"agent-conversations-order-line\">\n <span className=\"text-muted-foreground\">\n {shownSegmentCount !== null\n ? t(\"{count, plural, one {# conversation · sorted by} other {# conversations · sorted by}}\", { count: shownSegmentCount })\n : t(\"Sorted by\", { context: SORT_CONTEXT })}\n </span>\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <button type=\"button\" className=\"inline-flex items-center gap-1 font-semibold text-foreground hover:underline\" data-testid=\"agent-conversations-sort\">\n {t(SORT_LABELS[sortOrder], { context: SORT_CONTEXT })}\n <ChevronDown className=\"size-3.5\" aria-hidden />\n </button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"start\">\n {AGENT_INSPECT_SORT_ORDERS.map((order) => (\n <DropdownMenuItem key={order} onSelect={() => setFilter(\"sort\", order === \"LAST_ACTIVITY\" ? \"\" : order)}>\n <Check className={cn(\"size-3.5\", order === sortOrder ? \"opacity-100\" : \"opacity-0\")} aria-hidden />\n {t(SORT_LABELS[order], { context: SORT_CONTEXT })}\n </DropdownMenuItem>\n ))}\n </DropdownMenuContent>\n </DropdownMenu>\n <span className=\"grow\" />\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <button type=\"button\" className=\"inline-flex items-center gap-1.5 text-muted-foreground hover:text-foreground\" data-testid=\"agent-conversations-columns\">\n {t(\"Columns\", { context: COLUMN_CONTEXT })}\n <Columns3 className=\"size-3.5\" aria-hidden />\n </button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\">\n <DropdownMenuLabel>{t(\"Shown columns\", { context: COLUMN_CONTEXT })}</DropdownMenuLabel>\n {AGENT_CONVERSATION_COLUMN_IDS.map((columnId) => (\n <DropdownMenuCheckboxItem\n key={columnId}\n checked={shownColumnIds.includes(columnId)}\n onSelect={(event) => event.preventDefault()}\n onCheckedChange={(checked) =>\n setHiddenColumnIds(checked ? hiddenColumnIds.filter((hiddenColumnId) => hiddenColumnId !== columnId) : [...hiddenColumnIds, columnId])\n }\n >\n {t(COLUMN_LABELS[columnId], { context: COLUMN_CONTEXT })}\n </DropdownMenuCheckboxItem>\n ))}\n </DropdownMenuContent>\n </DropdownMenu>\n </div>\n <EntityListBody\n displayMode=\"table\"\n columns={columns}\n items={conversations}\n getRowKey={(conversation) => String(conversation.aiConversationId)}\n rowAction={onOpenConversation ? (conversation) => () => onOpenConversation(conversation.aiConversationId ?? 0) : undefined}\n isLoading={listQuery.isLoading}\n emptyMessage={t(\"No conversation in this period.\")}\n noResultsMessage={t(\"No conversation matches the search and the filters.\")}\n isSearchActive={list.isActive}\n onClearSearch={list.clear}\n loadingMessage={t(\"Loading the conversations\")}\n error={listQuery.isError ? normalizeDddError(listQuery.error, t(\"The conversations could not be loaded.\")).message : undefined}\n />\n {exportRunners}\n </EntityListPage>\n );\n};\n","import {\n type ApiMutationHook,\n type ApiQueryHook,\n type InjectableBaseApi,\n type InjectedEndpointDefinition,\n type InjectedRequest,\n injectEndpointsOnce,\n staticMutationHook,\n type StaticQueryFailure,\n staticQueryHook,\n toQueryString,\n trimApiPrefix,\n} from \"@mgamadeus/ddd-admin-ui/logic/pure\";\nimport type {\n AgentConnectionAccountLinkArg,\n AgentConnectionAddressArg,\n AgentConnectionApprovalAnswerArg,\n AgentConnectionApprovalsArg,\n AgentConnectionApprovalsResponse,\n AgentConnectionDetailResponse,\n AgentConnectionDriveItemsArg,\n AgentConnectionDriveItemsSearchArg,\n AgentConnectionDriveRootAddArg,\n AgentConnectionDriveRootItemArg,\n AgentConnectionDriveRootReleaseArg,\n AgentConnectionDriveRootReleaseRevokeArg,\n AgentConnectionDriveRootReleasesArg,\n AgentConnectionDriveRootRevokeArg,\n AgentConnectionDriveRootsArg,\n AgentConnectionDriveRootsResponse,\n AgentConnectionIdArg,\n AgentConnectionImapArg,\n AgentConnectionLevelArg,\n AgentConnectionOAuthStartArg,\n AgentConnectionOAuthStartResponse,\n AgentConnectionReleaseArg,\n AgentConnectionReleaseToAgentArg,\n AgentConnectionSettingsArg,\n AgentConnectionSlackArg,\n AgentConnectionsResponse,\n} from \"./agent-connections-types\";\n\n/** The cache tag type of the connection operations (ids `LIST`, `DETAIL`, `DRIVES`, `APPROVALS`). */\nexport const AGENT_CONNECTIONS_TAG = \"AdminUiAgentConnections\";\n\n/**\n * The hooks `createAgentConnectionsApi` returns: every route of `AdminAgentConnectionsTrait` a browser calls with the\n * session, and the drive routes of `AdminAgentConnectionDrivesTrait` (a host that does not mount that trait answers\n * 404 there: the panel then shows no drive section, see `AgentConnectionsPanelProps.driveRoots`). The OAuth callback\n * (`GET /oauth/{provider}/callback`) is opened by the provider's redirect, never by a hook.\n */\nexport interface AgentConnectionsApi {\n /** `GET /connections`: the connections the account sees, the connectable providers, the system right, the share targets. */\n useAgentConnectionsQuery: ApiQueryHook<void, AgentConnectionsResponse>;\n /** `GET /connections/{connectionId}`: levels, releases, channels, account links, granted scopes and levels, audit rows. */\n useAgentConnectionQuery: ApiQueryHook<AgentConnectionIdArg, AgentConnectionDetailResponse>;\n /** `POST /connections/{connectionId}/level`. */\n useSetAgentConnectionLevelMutation: ApiMutationHook<AgentConnectionLevelArg, AgentConnectionDetailResponse>;\n /** `POST /connections/{connectionId}/settings`: name, visibility, boundaries, default flag, pause. */\n useUpdateAgentConnectionSettingsMutation: ApiMutationHook<AgentConnectionSettingsArg, AgentConnectionDetailResponse>;\n /** `POST /connections/{connectionId}/release`: to an agent space, with ceilings and boundaries. */\n useReleaseAgentConnectionMutation: ApiMutationHook<AgentConnectionReleaseArg, AgentConnectionDetailResponse>;\n /** `POST /connections/{connectionId}/disconnect`. */\n useDisconnectAgentConnectionMutation: ApiMutationHook<AgentConnectionIdArg, AgentConnectionDetailResponse>;\n /** `POST /oauth/{provider}/start`: answers the consent URL and sets the browser nonce cookie. */\n useStartAgentConnectionOAuthMutation: ApiMutationHook<AgentConnectionOAuthStartArg, AgentConnectionOAuthStartResponse>;\n /** `POST /connections/imap`. */\n useConnectAgentConnectionImapMutation: ApiMutationHook<AgentConnectionImapArg, AgentConnectionDetailResponse>;\n /** `POST /system/slack`. */\n useConnectAgentConnectionSlackMutation: ApiMutationHook<AgentConnectionSlackArg, AgentConnectionDetailResponse>;\n /** `POST /connections/{connectionId}/addresses`. */\n useUpsertAgentConnectionAddressMutation: ApiMutationHook<AgentConnectionAddressArg, AgentConnectionDetailResponse>;\n /** `POST /connections/{connectionId}/accountLinks`. */\n useLinkAgentConnectionAccountMutation: ApiMutationHook<AgentConnectionAccountLinkArg, AgentConnectionDetailResponse>;\n /** `GET /approvals?includeAnswered`. */\n useAgentConnectionApprovalsQuery: ApiQueryHook<AgentConnectionApprovalsArg | void, AgentConnectionApprovalsResponse>;\n /** `POST /approvals/{approvalRequestId}/answer`. */\n useAnswerAgentConnectionApprovalMutation: ApiMutationHook<AgentConnectionApprovalAnswerArg, AgentConnectionApprovalsResponse>;\n /** `GET /connections/{connectionId}/driveRoots?includeRevoked`: the roots (the ended ones too by default) and their releases to agent spaces. */\n useAgentConnectionDriveRootsQuery: ApiQueryHook<AgentConnectionDriveRootsArg, AgentConnectionDriveRootsResponse>;\n /** `GET /connections/{connectionId}/driveItems?section&folderId&pageToken`: a top of the drive or the items of a folder, to pick roots. */\n useAgentConnectionDriveItemsQuery: ApiQueryHook<AgentConnectionDriveItemsArg, AgentConnectionDriveRootsResponse>;\n /** `GET /connections/{connectionId}/driveItems/search?query&pageToken`: folders and shared drives by name, to pick roots. */\n useSearchDriveItemsQuery: ApiQueryHook<AgentConnectionDriveItemsSearchArg, AgentConnectionDriveRootsResponse>;\n /** `POST /connections/{connectionId}/driveRoots`. */\n useAddAgentConnectionDriveRootMutation: ApiMutationHook<AgentConnectionDriveRootAddArg, AgentConnectionDriveRootsResponse>;\n /** `POST /connections/{connectionId}/driveRoots/remove`. */\n useRemoveAgentConnectionDriveRootMutation: ApiMutationHook<AgentConnectionDriveRootItemArg, AgentConnectionDriveRootsResponse>;\n /** `POST /connections/{connectionId}/driveRoots/assign`. */\n useAssignAgentConnectionDriveRootMutation: ApiMutationHook<AgentConnectionDriveRootItemArg, AgentConnectionDriveRootsResponse>;\n /** `POST /connections/{connectionId}/driveRoots/discover`. */\n useDiscoverAgentConnectionDriveItemsMutation: ApiMutationHook<AgentConnectionIdArg, AgentConnectionDriveRootsResponse>;\n /** `POST /connections/{connectionId}/releaseToAgent`. */\n useReleaseAgentConnectionDriveItemToAgentMutation: ApiMutationHook<AgentConnectionReleaseToAgentArg, AgentConnectionDriveRootsResponse>;\n /** `POST /driveRoots/{driveRootId}/revoke`. */\n useRevokeAgentConnectionDriveReleaseMutation: ApiMutationHook<AgentConnectionDriveRootRevokeArg, AgentConnectionDriveRootsResponse>;\n /** `POST /connections/{connectionId}/driveRoots/check`: asks the provider; a root it no longer has becomes `LOST`. */\n useCheckAgentConnectionDriveRootsMutation: ApiMutationHook<AgentConnectionIdArg, AgentConnectionDriveRootsResponse>;\n /** `GET /driveRoots/{driveRootId}/releases?includeRevoked`: the releases of one root to agent spaces. */\n useAgentConnectionDriveRootReleasesQuery: ApiQueryHook<AgentConnectionDriveRootReleasesArg, AgentConnectionDriveRootsResponse>;\n /** `POST /driveRoots/{driveRootId}/releases`: to one agent space; the first release restricts the root to its released spaces. */\n useReleaseAgentConnectionDriveRootToAgentSpaceMutation: ApiMutationHook<AgentConnectionDriveRootReleaseArg, AgentConnectionDriveRootsResponse>;\n /** `POST /driveRootReleases/{driveRootReleaseId}/revoke`. */\n useRevokeAgentConnectionDriveRootReleaseMutation: ApiMutationHook<AgentConnectionDriveRootReleaseRevokeArg, AgentConnectionDriveRootsResponse>;\n /** `POST /driveRoots/{driveRootId}/restrict`: no agent space uses the root until it is released to one. */\n useRestrictAgentConnectionDriveRootMutation: ApiMutationHook<AgentConnectionDriveRootRevokeArg, AgentConnectionDriveRootsResponse>;\n /** `POST /driveRoots/{driveRootId}/followConnection`: the root follows the connection's sharing again. */\n useFollowAgentConnectionSharingWithDriveRootMutation: ApiMutationHook<AgentConnectionDriveRootRevokeArg, AgentConnectionDriveRootsResponse>;\n}\n\nexport interface CreateAgentConnectionsApiOptions {\n /** The host's RTK Query api (`createApi` with the React hooks module). */\n baseApi: InjectableBaseApi;\n /** Where the host mounts `AdminAgentConnectionsTrait`, without a trailing slash (`/api/admin/agent-connections`). */\n apiPrefix: string;\n}\n\n/** The request of every operation, on `apiPrefix`. Pure: no RTK runtime. */\nexport const buildAgentConnectionsRequests = (apiPrefix: string) => {\n const prefix = trimApiPrefix(apiPrefix);\n const connectionUrl = (connectionId: number, action?: string) => `${prefix}/connections/${encodeURIComponent(String(connectionId))}${action !== undefined ? `/${action}` : \"\"}`;\n const driveRootUrl = (driveRootId: number, action: string) => `${prefix}/driveRoots/${encodeURIComponent(String(driveRootId))}/${action}`;\n const post = (url: string, body?: unknown): InjectedRequest => (body === undefined ? { url, method: \"POST\" } : { url, method: \"POST\", body });\n return {\n list: (): InjectedRequest => ({ url: `${prefix}/connections` }),\n detail: ({ connectionId }: AgentConnectionIdArg): InjectedRequest => ({ url: connectionUrl(connectionId) }),\n setLevel: ({ connectionId, ...body }: AgentConnectionLevelArg): InjectedRequest => post(connectionUrl(connectionId, \"level\"), body),\n updateSettings: ({ connectionId, ...body }: AgentConnectionSettingsArg): InjectedRequest => post(connectionUrl(connectionId, \"settings\"), body),\n release: ({ connectionId, ...body }: AgentConnectionReleaseArg): InjectedRequest => post(connectionUrl(connectionId, \"release\"), body),\n disconnect: ({ connectionId }: AgentConnectionIdArg): InjectedRequest => post(connectionUrl(connectionId, \"disconnect\")),\n startOAuth: ({ provider, ...body }: AgentConnectionOAuthStartArg): InjectedRequest => post(`${prefix}/oauth/${encodeURIComponent(provider.toLowerCase())}/start`, body),\n connectImap: (body: AgentConnectionImapArg): InjectedRequest => post(`${prefix}/connections/imap`, body),\n connectSlack: (body: AgentConnectionSlackArg): InjectedRequest => post(`${prefix}/system/slack`, body),\n upsertAddress: ({ connectionId, ...body }: AgentConnectionAddressArg): InjectedRequest => post(connectionUrl(connectionId, \"addresses\"), body),\n linkAccount: ({ connectionId, ...body }: AgentConnectionAccountLinkArg): InjectedRequest => post(connectionUrl(connectionId, \"accountLinks\"), body),\n approvals: (arg: AgentConnectionApprovalsArg | void): InjectedRequest => ({ url: `${prefix}/approvals${toQueryString({ includeAnswered: arg?.includeAnswered === true ? 1 : undefined })}` }),\n answerApproval: ({ approvalRequestId, option }: AgentConnectionApprovalAnswerArg): InjectedRequest => post(`${prefix}/approvals/${encodeURIComponent(String(approvalRequestId))}/answer`, { option }),\n driveRoots: ({ connectionId, includeRevoked }: AgentConnectionDriveRootsArg): InjectedRequest => ({\n // the server's default is true: only \"without the ended ones\" is sent\n url: `${connectionUrl(connectionId, \"driveRoots\")}${toQueryString({ includeRevoked: includeRevoked === false ? 0 : undefined })}`,\n }),\n // a filter is sent only with a value (the caller sends only the ones the server applies); the kinds as one list\n searchDriveItems: ({ connectionId, query, pageToken, modifiedFrom, modifiedTo, createdFrom, createdTo, types, minSizeBytes, maxSizeBytes, inFolderId }: AgentConnectionDriveItemsSearchArg): InjectedRequest => ({\n url: `${connectionUrl(connectionId, \"driveItems/search\")}${toQueryString({\n query,\n pageToken: pageToken ?? undefined,\n modifiedFrom: modifiedFrom || undefined,\n modifiedTo: modifiedTo || undefined,\n createdFrom: createdFrom || undefined,\n createdTo: createdTo || undefined,\n types: types != null && types.length > 0 ? types.join(\",\") : undefined,\n minSizeBytes: minSizeBytes ?? undefined,\n maxSizeBytes: maxSizeBytes ?? undefined,\n inFolderId: inFolderId || undefined,\n })}`,\n }),\n // the section names a top of the drive: a folder's children are asked for by the folder alone\n driveItems: ({ connectionId, section, folderId, pageToken }: AgentConnectionDriveItemsArg): InjectedRequest => ({\n url: `${connectionUrl(connectionId, \"driveItems\")}${toQueryString({ section: (folderId ?? \"\") === \"\" ? (section ?? undefined) : undefined, folderId: folderId ?? undefined, pageToken: pageToken ?? undefined })}`,\n }),\n addDriveRoot: ({ connectionId, ...body }: AgentConnectionDriveRootAddArg): InjectedRequest => post(connectionUrl(connectionId, \"driveRoots\"), body),\n // a rule root is named by its kind, an item by its id\n removeDriveRoot: ({ connectionId, itemId, rootKind }: AgentConnectionDriveRootItemArg): InjectedRequest => post(connectionUrl(connectionId, \"driveRoots/remove\"), rootKind !== undefined ? { rootKind } : { itemId }),\n assignDriveRoot: ({ connectionId, itemId }: AgentConnectionDriveRootItemArg): InjectedRequest => post(connectionUrl(connectionId, \"driveRoots/assign\"), { itemId }),\n discoverDriveItems: ({ connectionId }: AgentConnectionIdArg): InjectedRequest => post(connectionUrl(connectionId, \"driveRoots/discover\")),\n releaseDriveItemToAgent: ({ connectionId, ...body }: AgentConnectionReleaseToAgentArg): InjectedRequest => post(connectionUrl(connectionId, \"releaseToAgent\"), body),\n revokeDriveRelease: ({ driveRootId }: AgentConnectionDriveRootRevokeArg): InjectedRequest => post(driveRootUrl(driveRootId, \"revoke\")),\n checkDriveRoots: ({ connectionId }: AgentConnectionIdArg): InjectedRequest => post(connectionUrl(connectionId, \"driveRoots/check\")),\n driveRootReleases: ({ driveRootId, includeRevoked }: AgentConnectionDriveRootReleasesArg): InjectedRequest => ({\n url: `${driveRootUrl(driveRootId, \"releases\")}${toQueryString({ includeRevoked: includeRevoked === false ? 0 : undefined })}`,\n }),\n releaseDriveRootToAgentSpace: ({ driveRootId, agentSpaceId }: AgentConnectionDriveRootReleaseArg): InjectedRequest => post(driveRootUrl(driveRootId, \"releases\"), { agentSpaceId }),\n revokeDriveRootRelease: ({ driveRootReleaseId }: AgentConnectionDriveRootReleaseRevokeArg): InjectedRequest => post(`${prefix}/driveRootReleases/${encodeURIComponent(String(driveRootReleaseId))}/revoke`),\n restrictDriveRoot: ({ driveRootId }: AgentConnectionDriveRootRevokeArg): InjectedRequest => post(driveRootUrl(driveRootId, \"restrict\")),\n followConnectionWithDriveRoot: ({ driveRootId }: AgentConnectionDriveRootRevokeArg): InjectedRequest => post(driveRootUrl(driveRootId, \"followConnection\")),\n };\n};\n\nconst LIST = { type: AGENT_CONNECTIONS_TAG, id: \"LIST\" } as const;\nconst DETAIL = { type: AGENT_CONNECTIONS_TAG, id: \"DETAIL\" } as const;\nconst DRIVES = { type: AGENT_CONNECTIONS_TAG, id: \"DRIVES\" } as const;\nconst APPROVALS = { type: AGENT_CONNECTIONS_TAG, id: \"APPROVALS\" } as const;\n\n/** The operations as injected. A write on a connection refreshes the list and every open detail; a drive write the roots. */\nexport const agentConnectionsEndpointDefinitions = (apiPrefix: string) => {\n const requests = buildAgentConnectionsRequests(apiPrefix);\n return {\n adminUiAgentConnections: { kind: \"query\", request: requests.list, providesTags: [LIST] },\n adminUiAgentConnection: { kind: \"query\", request: requests.detail, providesTags: [DETAIL] },\n adminUiAgentConnectionSetLevel: { kind: \"mutation\", request: requests.setLevel, invalidatesTags: [LIST, DETAIL] },\n adminUiAgentConnectionUpdateSettings: { kind: \"mutation\", request: requests.updateSettings, invalidatesTags: [LIST, DETAIL] },\n adminUiAgentConnectionRelease: { kind: \"mutation\", request: requests.release, invalidatesTags: [LIST, DETAIL] },\n adminUiAgentConnectionDisconnect: { kind: \"mutation\", request: requests.disconnect, invalidatesTags: [LIST, DETAIL, DRIVES] },\n adminUiAgentConnectionStartOAuth: { kind: \"mutation\", request: requests.startOAuth, invalidatesTags: [LIST] },\n adminUiAgentConnectionConnectImap: { kind: \"mutation\", request: requests.connectImap, invalidatesTags: [LIST] },\n adminUiAgentConnectionConnectSlack: { kind: \"mutation\", request: requests.connectSlack, invalidatesTags: [LIST] },\n adminUiAgentConnectionUpsertAddress: { kind: \"mutation\", request: requests.upsertAddress, invalidatesTags: [DETAIL] },\n adminUiAgentConnectionLinkAccount: { kind: \"mutation\", request: requests.linkAccount, invalidatesTags: [DETAIL] },\n adminUiAgentConnectionApprovals: { kind: \"query\", request: requests.approvals, providesTags: [APPROVALS] },\n adminUiAgentConnectionAnswerApproval: { kind: \"mutation\", request: requests.answerApproval, invalidatesTags: [APPROVALS, DETAIL] },\n adminUiAgentConnectionDriveRoots: { kind: \"query\", request: requests.driveRoots, providesTags: [DRIVES] },\n adminUiAgentConnectionDriveItems: { kind: \"query\", request: requests.driveItems, providesTags: [DRIVES] },\n adminUiAgentConnectionAddDriveRoot: { kind: \"mutation\", request: requests.addDriveRoot, invalidatesTags: [DRIVES, DETAIL] },\n adminUiAgentConnectionRemoveDriveRoot: { kind: \"mutation\", request: requests.removeDriveRoot, invalidatesTags: [DRIVES, DETAIL] },\n adminUiAgentConnectionAssignDriveRoot: { kind: \"mutation\", request: requests.assignDriveRoot, invalidatesTags: [DRIVES, DETAIL] },\n adminUiAgentConnectionDiscoverDriveItems: { kind: \"mutation\", request: requests.discoverDriveItems, invalidatesTags: [DRIVES] },\n adminUiAgentConnectionReleaseDriveItemToAgent: { kind: \"mutation\", request: requests.releaseDriveItemToAgent, invalidatesTags: [DRIVES, DETAIL] },\n adminUiAgentConnectionRevokeDriveRelease: { kind: \"mutation\", request: requests.revokeDriveRelease, invalidatesTags: [DRIVES, DETAIL] },\n adminUiAgentConnectionSearchDriveItems: { kind: \"query\", request: requests.searchDriveItems, providesTags: [DRIVES] },\n adminUiAgentConnectionCheckDriveRoots: { kind: \"mutation\", request: requests.checkDriveRoots, invalidatesTags: [DRIVES, DETAIL] },\n adminUiAgentConnectionDriveRootReleases: { kind: \"query\", request: requests.driveRootReleases, providesTags: [DRIVES] },\n adminUiAgentConnectionReleaseDriveRootToAgentSpace: { kind: \"mutation\", request: requests.releaseDriveRootToAgentSpace, invalidatesTags: [DRIVES, DETAIL] },\n adminUiAgentConnectionRevokeDriveRootRelease: { kind: \"mutation\", request: requests.revokeDriveRootRelease, invalidatesTags: [DRIVES, DETAIL] },\n adminUiAgentConnectionRestrictDriveRoot: { kind: \"mutation\", request: requests.restrictDriveRoot, invalidatesTags: [DRIVES, DETAIL] },\n adminUiAgentConnectionFollowConnectionWithDriveRoot: { kind: \"mutation\", request: requests.followConnectionWithDriveRoot, invalidatesTags: [DRIVES, DETAIL] },\n } as const satisfies Record<string, InjectedEndpointDefinition<never>>;\n};\n\n/**\n * Injects the connection operations into the host's RTK Query api and returns their hooks. Call it once at module\n * scope: `export const agentConnectionsApi = createAgentConnectionsApi({ baseApi, apiPrefix: \"/api/admin/agent-connections\" });`\n */\nexport const createAgentConnectionsApi = ({ baseApi, apiPrefix }: CreateAgentConnectionsApiOptions): AgentConnectionsApi =>\n injectEndpointsOnce(baseApi, `agentConnections:${trimApiPrefix(apiPrefix)}`, [AGENT_CONNECTIONS_TAG], agentConnectionsEndpointDefinitions(apiPrefix), (hookOf) => ({\n useAgentConnectionsQuery: hookOf(\"adminUiAgentConnections\") as AgentConnectionsApi[\"useAgentConnectionsQuery\"],\n useAgentConnectionQuery: hookOf(\"adminUiAgentConnection\") as AgentConnectionsApi[\"useAgentConnectionQuery\"],\n useSetAgentConnectionLevelMutation: hookOf(\"adminUiAgentConnectionSetLevel\") as AgentConnectionsApi[\"useSetAgentConnectionLevelMutation\"],\n useUpdateAgentConnectionSettingsMutation: hookOf(\"adminUiAgentConnectionUpdateSettings\") as AgentConnectionsApi[\"useUpdateAgentConnectionSettingsMutation\"],\n useReleaseAgentConnectionMutation: hookOf(\"adminUiAgentConnectionRelease\") as AgentConnectionsApi[\"useReleaseAgentConnectionMutation\"],\n useDisconnectAgentConnectionMutation: hookOf(\"adminUiAgentConnectionDisconnect\") as AgentConnectionsApi[\"useDisconnectAgentConnectionMutation\"],\n useStartAgentConnectionOAuthMutation: hookOf(\"adminUiAgentConnectionStartOAuth\") as AgentConnectionsApi[\"useStartAgentConnectionOAuthMutation\"],\n useConnectAgentConnectionImapMutation: hookOf(\"adminUiAgentConnectionConnectImap\") as AgentConnectionsApi[\"useConnectAgentConnectionImapMutation\"],\n useConnectAgentConnectionSlackMutation: hookOf(\"adminUiAgentConnectionConnectSlack\") as AgentConnectionsApi[\"useConnectAgentConnectionSlackMutation\"],\n useUpsertAgentConnectionAddressMutation: hookOf(\"adminUiAgentConnectionUpsertAddress\") as AgentConnectionsApi[\"useUpsertAgentConnectionAddressMutation\"],\n useLinkAgentConnectionAccountMutation: hookOf(\"adminUiAgentConnectionLinkAccount\") as AgentConnectionsApi[\"useLinkAgentConnectionAccountMutation\"],\n useAgentConnectionApprovalsQuery: hookOf(\"adminUiAgentConnectionApprovals\") as AgentConnectionsApi[\"useAgentConnectionApprovalsQuery\"],\n useAnswerAgentConnectionApprovalMutation: hookOf(\"adminUiAgentConnectionAnswerApproval\") as AgentConnectionsApi[\"useAnswerAgentConnectionApprovalMutation\"],\n useAgentConnectionDriveRootsQuery: hookOf(\"adminUiAgentConnectionDriveRoots\") as AgentConnectionsApi[\"useAgentConnectionDriveRootsQuery\"],\n useAgentConnectionDriveItemsQuery: hookOf(\"adminUiAgentConnectionDriveItems\") as AgentConnectionsApi[\"useAgentConnectionDriveItemsQuery\"],\n useAddAgentConnectionDriveRootMutation: hookOf(\"adminUiAgentConnectionAddDriveRoot\") as AgentConnectionsApi[\"useAddAgentConnectionDriveRootMutation\"],\n useRemoveAgentConnectionDriveRootMutation: hookOf(\"adminUiAgentConnectionRemoveDriveRoot\") as AgentConnectionsApi[\"useRemoveAgentConnectionDriveRootMutation\"],\n useAssignAgentConnectionDriveRootMutation: hookOf(\"adminUiAgentConnectionAssignDriveRoot\") as AgentConnectionsApi[\"useAssignAgentConnectionDriveRootMutation\"],\n useDiscoverAgentConnectionDriveItemsMutation: hookOf(\"adminUiAgentConnectionDiscoverDriveItems\") as AgentConnectionsApi[\"useDiscoverAgentConnectionDriveItemsMutation\"],\n useReleaseAgentConnectionDriveItemToAgentMutation: hookOf(\"adminUiAgentConnectionReleaseDriveItemToAgent\") as AgentConnectionsApi[\"useReleaseAgentConnectionDriveItemToAgentMutation\"],\n useRevokeAgentConnectionDriveReleaseMutation: hookOf(\"adminUiAgentConnectionRevokeDriveRelease\") as AgentConnectionsApi[\"useRevokeAgentConnectionDriveReleaseMutation\"],\n useSearchDriveItemsQuery: hookOf(\"adminUiAgentConnectionSearchDriveItems\") as AgentConnectionsApi[\"useSearchDriveItemsQuery\"],\n useCheckAgentConnectionDriveRootsMutation: hookOf(\"adminUiAgentConnectionCheckDriveRoots\") as AgentConnectionsApi[\"useCheckAgentConnectionDriveRootsMutation\"],\n useAgentConnectionDriveRootReleasesQuery: hookOf(\"adminUiAgentConnectionDriveRootReleases\") as AgentConnectionsApi[\"useAgentConnectionDriveRootReleasesQuery\"],\n useReleaseAgentConnectionDriveRootToAgentSpaceMutation: hookOf(\"adminUiAgentConnectionReleaseDriveRootToAgentSpace\") as AgentConnectionsApi[\"useReleaseAgentConnectionDriveRootToAgentSpaceMutation\"],\n useRevokeAgentConnectionDriveRootReleaseMutation: hookOf(\"adminUiAgentConnectionRevokeDriveRootRelease\") as AgentConnectionsApi[\"useRevokeAgentConnectionDriveRootReleaseMutation\"],\n useRestrictAgentConnectionDriveRootMutation: hookOf(\"adminUiAgentConnectionRestrictDriveRoot\") as AgentConnectionsApi[\"useRestrictAgentConnectionDriveRootMutation\"],\n useFollowAgentConnectionSharingWithDriveRootMutation: hookOf(\"adminUiAgentConnectionFollowConnectionWithDriveRoot\") as AgentConnectionsApi[\"useFollowAgentConnectionSharingWithDriveRootMutation\"],\n }));\n\ntype Answer<TResponse> = TResponse | Promise<TResponse>;\n\n/** Fixed answers of a `createStaticAgentConnectionsApi`; a query without one stays loading, a write without one answers empty. */\nexport interface StaticAgentConnectionsData {\n list?: () => AgentConnectionsResponse | StaticQueryFailure | undefined;\n detail?: (arg: AgentConnectionIdArg) => AgentConnectionDetailResponse | StaticQueryFailure | undefined;\n setLevel?: (arg: AgentConnectionLevelArg) => Answer<AgentConnectionDetailResponse>;\n updateSettings?: (arg: AgentConnectionSettingsArg) => Answer<AgentConnectionDetailResponse>;\n release?: (arg: AgentConnectionReleaseArg) => Answer<AgentConnectionDetailResponse>;\n disconnect?: (arg: AgentConnectionIdArg) => Answer<AgentConnectionDetailResponse>;\n startOAuth?: (arg: AgentConnectionOAuthStartArg) => Answer<AgentConnectionOAuthStartResponse>;\n connectImap?: (arg: AgentConnectionImapArg) => Answer<AgentConnectionDetailResponse>;\n connectSlack?: (arg: AgentConnectionSlackArg) => Answer<AgentConnectionDetailResponse>;\n upsertAddress?: (arg: AgentConnectionAddressArg) => Answer<AgentConnectionDetailResponse>;\n linkAccount?: (arg: AgentConnectionAccountLinkArg) => Answer<AgentConnectionDetailResponse>;\n approvals?: (arg: AgentConnectionApprovalsArg) => AgentConnectionApprovalsResponse | StaticQueryFailure | undefined;\n answerApproval?: (arg: AgentConnectionApprovalAnswerArg) => Answer<AgentConnectionApprovalsResponse>;\n driveRoots?: (arg: AgentConnectionDriveRootsArg) => AgentConnectionDriveRootsResponse | StaticQueryFailure | undefined;\n searchDriveItems?: (arg: AgentConnectionDriveItemsSearchArg) => AgentConnectionDriveRootsResponse | StaticQueryFailure | undefined;\n driveRootReleases?: (arg: AgentConnectionDriveRootReleasesArg) => AgentConnectionDriveRootsResponse | StaticQueryFailure | undefined;\n checkDriveRoots?: (arg: AgentConnectionIdArg) => Answer<AgentConnectionDriveRootsResponse>;\n releaseDriveRootToAgentSpace?: (arg: AgentConnectionDriveRootReleaseArg) => Answer<AgentConnectionDriveRootsResponse>;\n revokeDriveRootRelease?: (arg: AgentConnectionDriveRootReleaseRevokeArg) => Answer<AgentConnectionDriveRootsResponse>;\n restrictDriveRoot?: (arg: AgentConnectionDriveRootRevokeArg) => Answer<AgentConnectionDriveRootsResponse>;\n followConnectionWithDriveRoot?: (arg: AgentConnectionDriveRootRevokeArg) => Answer<AgentConnectionDriveRootsResponse>;\n driveItems?: (arg: AgentConnectionDriveItemsArg) => AgentConnectionDriveRootsResponse | StaticQueryFailure | undefined;\n addDriveRoot?: (arg: AgentConnectionDriveRootAddArg) => Answer<AgentConnectionDriveRootsResponse>;\n removeDriveRoot?: (arg: AgentConnectionDriveRootItemArg) => Answer<AgentConnectionDriveRootsResponse>;\n assignDriveRoot?: (arg: AgentConnectionDriveRootItemArg) => Answer<AgentConnectionDriveRootsResponse>;\n discoverDriveItems?: (arg: AgentConnectionIdArg) => Answer<AgentConnectionDriveRootsResponse>;\n releaseDriveItemToAgent?: (arg: AgentConnectionReleaseToAgentArg) => Answer<AgentConnectionDriveRootsResponse>;\n revokeDriveRelease?: (arg: AgentConnectionDriveRootRevokeArg) => Answer<AgentConnectionDriveRootsResponse>;\n}\n\nconst EMPTY_DETAIL = (connectionId: number): AgentConnectionDetailResponse => ({ connection: { connectionId } });\n\n/** An `AgentConnectionsApi` answering fixed payloads, without a store or a request (previews, tests, reviews). */\nexport const createStaticAgentConnectionsApi = (data: StaticAgentConnectionsData): AgentConnectionsApi => ({\n useAgentConnectionsQuery: staticQueryHook(() => data.list?.()),\n useAgentConnectionQuery: staticQueryHook((arg) => data.detail?.(arg)),\n useSetAgentConnectionLevelMutation: staticMutationHook((arg) => data.setLevel?.(arg) ?? EMPTY_DETAIL(arg.connectionId)),\n useUpdateAgentConnectionSettingsMutation: staticMutationHook((arg) => data.updateSettings?.(arg) ?? EMPTY_DETAIL(arg.connectionId)),\n useReleaseAgentConnectionMutation: staticMutationHook((arg) => data.release?.(arg) ?? EMPTY_DETAIL(arg.connectionId)),\n useDisconnectAgentConnectionMutation: staticMutationHook((arg) => data.disconnect?.(arg) ?? EMPTY_DETAIL(arg.connectionId)),\n useStartAgentConnectionOAuthMutation: staticMutationHook((arg) => data.startOAuth?.(arg) ?? { connectionId: arg.connectionId ?? 0, authorizationUrl: \"\", redirectUri: \"\" }),\n useConnectAgentConnectionImapMutation: staticMutationHook((arg) => data.connectImap?.(arg) ?? EMPTY_DETAIL(0)),\n useConnectAgentConnectionSlackMutation: staticMutationHook((arg) => data.connectSlack?.(arg) ?? EMPTY_DETAIL(0)),\n useUpsertAgentConnectionAddressMutation: staticMutationHook((arg) => data.upsertAddress?.(arg) ?? EMPTY_DETAIL(arg.connectionId)),\n useLinkAgentConnectionAccountMutation: staticMutationHook((arg) => data.linkAccount?.(arg) ?? EMPTY_DETAIL(arg.connectionId)),\n useAgentConnectionApprovalsQuery: staticQueryHook((arg) => data.approvals?.(arg ?? {})),\n useAnswerAgentConnectionApprovalMutation: staticMutationHook((arg) => data.answerApproval?.(arg) ?? {}),\n useAgentConnectionDriveRootsQuery: staticQueryHook((arg) => data.driveRoots?.(arg)),\n useAgentConnectionDriveItemsQuery: staticQueryHook((arg) => data.driveItems?.(arg)),\n useAddAgentConnectionDriveRootMutation: staticMutationHook((arg) => data.addDriveRoot?.(arg) ?? {}),\n useRemoveAgentConnectionDriveRootMutation: staticMutationHook((arg) => data.removeDriveRoot?.(arg) ?? {}),\n useAssignAgentConnectionDriveRootMutation: staticMutationHook((arg) => data.assignDriveRoot?.(arg) ?? {}),\n useDiscoverAgentConnectionDriveItemsMutation: staticMutationHook((arg) => data.discoverDriveItems?.(arg) ?? {}),\n useReleaseAgentConnectionDriveItemToAgentMutation: staticMutationHook((arg) => data.releaseDriveItemToAgent?.(arg) ?? {}),\n useRevokeAgentConnectionDriveReleaseMutation: staticMutationHook((arg) => data.revokeDriveRelease?.(arg) ?? {}),\n useSearchDriveItemsQuery: staticQueryHook((arg) => data.searchDriveItems?.(arg)),\n useCheckAgentConnectionDriveRootsMutation: staticMutationHook((arg) => data.checkDriveRoots?.(arg) ?? {}),\n useAgentConnectionDriveRootReleasesQuery: staticQueryHook((arg) => data.driveRootReleases?.(arg)),\n useReleaseAgentConnectionDriveRootToAgentSpaceMutation: staticMutationHook((arg) => data.releaseDriveRootToAgentSpace?.(arg) ?? {}),\n useRevokeAgentConnectionDriveRootReleaseMutation: staticMutationHook((arg) => data.revokeDriveRootRelease?.(arg) ?? {}),\n useRestrictAgentConnectionDriveRootMutation: staticMutationHook((arg) => data.restrictDriveRoot?.(arg) ?? {}),\n useFollowAgentConnectionSharingWithDriveRootMutation: staticMutationHook((arg) => data.followConnectionWithDriveRoot?.(arg) ?? {}),\n});\n","import { m } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { defineStatusMap } from \"@mgamadeus/ddd-admin-ui/logic\";\nimport { CircleAlert, CircleCheck, CircleMinus, CirclePause, Clock, Loader } from \"lucide-react\";\nimport type { AgentConnectionCapability, AgentConnectionCapabilityLevel, AgentConnectionLevel, AgentConnectionSummary, AgentConnectionVisibility } from \"./agent-connections-types\";\n\n/** The levels by power, exactly `AgentConnectionPermission::LEVELS` (each one includes everything below it). */\nexport const AGENT_CONNECTION_LEVELS: readonly AgentConnectionLevel[] = [\"OFF\", \"READ\", \"DRAFT\", \"WRITE_WITH_APPROVAL\", \"DELETE_WITH_APPROVAL\", \"SEND_WITH_APPROVAL\", \"SEND_BY_RULE\"];\n\nexport const AGENT_CONNECTION_CAPABILITIES: readonly AgentConnectionCapability[] = [\"MAIL\", \"CALENDAR\", \"CONTACTS\", \"FILES\", \"CHAT\", \"MESSAGING\"];\n\n/** Translation context of the level names. */\nexport const AGENT_CONNECTION_LEVEL_CONTEXT = \"agent-connection-level\";\n\n/** Translation context of the capability names. */\nexport const AGENT_CONNECTION_CAPABILITY_CONTEXT = \"agent-connection-capability\";\n\n/** Translation context of the level explanations; they name the agent as `%agentName%`. */\nexport const AGENT_CONNECTION_LEVEL_HELP_CONTEXT = \"agent-connection-level-help\";\n\n/** What the agent may do with one capability, as a short name (English key, translated with its context). */\nexport const AGENT_CONNECTION_LEVEL_LABEL: Readonly<Record<AgentConnectionLevel, string>> = {\n OFF: m(\"Off\", { context: \"agent-connection-level\" }),\n READ: m(\"Read\", { context: \"agent-connection-level\" }),\n DRAFT: m(\"Drafts\", { context: \"agent-connection-level\" }),\n WRITE_WITH_APPROVAL: m(\"Change with approval\", { context: \"agent-connection-level\" }),\n DELETE_WITH_APPROVAL: m(\"Delete with approval\", { context: \"agent-connection-level\" }),\n SEND_WITH_APPROVAL: m(\"Send with approval\", { context: \"agent-connection-level\" }),\n SEND_BY_RULE: m(\"On its own\", { context: \"agent-connection-level\" }),\n};\n\n/** The capability's name (English key, translated with its context). */\nexport const AGENT_CONNECTION_CAPABILITY_LABEL: Readonly<Record<AgentConnectionCapability, string>> = {\n MAIL: m(\"Mail\", { context: \"agent-connection-capability\" }),\n CALENDAR: m(\"Calendar\", { context: \"agent-connection-capability\" }),\n CONTACTS: m(\"Contacts\", { context: \"agent-connection-capability\" }),\n FILES: m(\"Files\", { context: \"agent-connection-capability\" }),\n CHAT: m(\"Chat\", { context: \"agent-connection-capability\" }),\n MESSAGING: m(\"Messaging\", { context: \"agent-connection-capability\" }),\n};\n\n/** What a level allows, one line under the level choice (English key, `%agentName%` = the agent's name). */\nexport const AGENT_CONNECTION_LEVEL_HELP: Readonly<Record<AgentConnectionLevel, string>> = {\n OFF: m(\"%agentName% does not use it.\", { context: \"agent-connection-level-help\" }),\n READ: m(\"%agentName% reads, searches and lists. Nothing changes.\", { context: \"agent-connection-level-help\" }),\n DRAFT: m(\"Also drafts that reach nobody.\", { context: \"agent-connection-level-help\" }),\n WRITE_WITH_APPROVAL: m(\"Also creates and changes, each after your yes.\", { context: \"agent-connection-level-help\" }),\n DELETE_WITH_APPROVAL: m(\"Also deletes, each after your yes.\", { context: \"agent-connection-level-help\" }),\n SEND_WITH_APPROVAL: m(\"Also sends to people, each after your yes to the exact text.\", { context: \"agent-connection-level-help\" }),\n SEND_BY_RULE: m(\"Sends without asking where a rule allows it, otherwise %agentName% asks.\", { context: \"agent-connection-level-help\" }),\n};\n\n/** The level's text colour on a chip: read plain, \"with approval\" in the warning tone, \"on its own\" in the brand tone. */\nexport const agentConnectionLevelToneClass = (level: AgentConnectionLevel): string => {\n switch (level) {\n case \"OFF\":\n return \"text-muted-foreground\";\n case \"READ\":\n return \"text-foreground\";\n case \"SEND_BY_RULE\":\n return \"text-brand-emphasis\";\n default:\n return \"text-warning\";\n }\n};\n\n/** The position of a level in the order by power; -1 for an unknown one. */\nexport const agentConnectionLevelRank = (level: AgentConnectionLevel): number => AGENT_CONNECTION_LEVELS.indexOf(level);\n\n/** The capabilities a Google connect can ask for, in the order of the consent screen. */\nexport const GOOGLE_CONNECT_CAPABILITIES: readonly AgentConnectionCapability[] = [\"MAIL\", \"CALENDAR\", \"CONTACTS\", \"FILES\"];\n\n/** The quick filters of the list: connected, needs the viewer, paused, disconnected. */\nexport type AgentConnectionStatusGroup = \"connected\" | \"attention\" | \"paused\" | \"disconnected\";\n\nexport const AGENT_CONNECTION_STATUS_GROUPS: readonly AgentConnectionStatusGroup[] = [\"connected\", \"attention\", \"paused\", \"disconnected\"];\n\nexport const agentConnectionStatusGroupOf = (status: string | null | undefined): AgentConnectionStatusGroup => {\n switch (status) {\n case \"CONNECTED\":\n return \"connected\";\n case \"PAUSED\":\n return \"paused\";\n case \"REVOKED\":\n return \"disconnected\";\n default:\n return \"attention\";\n }\n};\n\nexport const isAgentConnectionStatusGroup = (value: string): value is AgentConnectionStatusGroup => AGENT_CONNECTION_STATUS_GROUPS.some((group) => group === value);\n\nexport const AGENT_CONNECTION_STATUS_GROUP_LABEL: Readonly<Record<AgentConnectionStatusGroup, string>> = {\n connected: m(\"Connected\", { context: \"agent-connection-status\" }),\n attention: m(\"Needs you\", { context: \"agent-connection-status-group\" }),\n paused: m(\"Paused\", { context: \"agent-connection-status\" }),\n disconnected: m(\"Disconnected\", { context: \"agent-connection-status\" }),\n};\n\n/** The translation context of a status group's label (`AGENT_CONNECTION_STATUS_GROUP_LABEL`). */\nexport const agentConnectionStatusGroupContextOf = (group: AgentConnectionStatusGroup): string => (group === \"attention\" ? \"agent-connection-status-group\" : \"agent-connection-status\");\n\nexport const isAgentConnectionLevel = (value: string): value is AgentConnectionLevel => AGENT_CONNECTION_LEVELS.some((level) => level === value);\n\nexport const isAgentConnectionCapability = (value: string): value is AgentConnectionCapability => AGENT_CONNECTION_CAPABILITIES.some((capability) => capability === value);\n\n/**\n * The levels of a connection from the summary's `levels` text (`\"MAIL=DRAFT (draft); CALENDAR=READ (read, free/busy)\"`);\n * a part with a capability or level this web does not know is left out.\n */\nexport const parseAgentConnectionLevels = (levels: string | null | undefined): AgentConnectionCapabilityLevel[] =>\n (levels ?? \"\")\n .split(\";\")\n .map((part) => /^\\s*([A-Z_]+)=([A-Z_]+)/.exec(part))\n .flatMap((match) => {\n if (match === null) return [];\n const capability = match[1] ?? \"\";\n const level = match[2] ?? \"\";\n return isAgentConnectionCapability(capability) && isAgentConnectionLevel(level) ? [{ capability, level }] : [];\n });\n\nexport const isAgentConnectionVisibility = (value: string | null | undefined): value is AgentConnectionVisibility => value === \"OWNER_ONLY\" || value === \"AGENT_SPACE\";\n\n/** The visibility of a connection as the dialogs start with it: `OWNER_ONLY` for anything unknown. */\nexport const agentConnectionVisibilityOf = (connection: Pick<AgentConnectionSummary, \"visibility\"> | null | undefined): AgentConnectionVisibility =>\n isAgentConnectionVisibility(connection?.visibility) ? connection.visibility : \"OWNER_ONLY\";\n\n/** The translation context of the visibility names. */\nexport const AGENT_CONNECTION_VISIBILITY_CONTEXT = \"agent-connection-visibility\";\n\n/** The name of the visibility `OWNER_ONLY`; the name of `AGENT_SPACE` is the host's (`AgentConnectionsTexts.sharedVisibilityLabel`). */\nexport const AGENT_CONNECTION_OWNER_ONLY_LABEL = m(\"Just for me\", { context: \"agent-connection-visibility\" });\n\n/** The status of a connection (`AgentConnection::STATUS_*`); an unknown value shows as a neutral badge. */\nexport const AGENT_CONNECTION_STATUS = defineStatusMap<string>(\n {\n IN_PROGRESS: { label: m(\"Connecting\", { context: \"agent-connection-status\" }), tone: \"warning\", icon: Loader },\n CONNECTED: { label: m(\"Connected\", { context: \"agent-connection-status\" }), tone: \"success\", icon: CircleCheck },\n EXPIRED: { label: m(\"Expired\", { context: \"agent-connection-status\" }), tone: \"warning\", icon: Clock },\n PAUSED: { label: m(\"Paused\", { context: \"agent-connection-status\" }), tone: \"neutral\", icon: CirclePause },\n REVOKED: { label: m(\"Disconnected\", { context: \"agent-connection-status\" }), tone: \"neutral\", icon: CircleMinus },\n ERROR: { label: m(\"Error\", { context: \"agent-connection-status\" }), tone: \"danger\", icon: CircleAlert },\n },\n { context: \"agent-connection-status\" },\n);\n\n/** The provider's name; provider names are brands and stay untranslated. */\nexport const agentConnectionProviderName = (provider: string | null | undefined): string => {\n switch (provider) {\n case \"GOOGLE\":\n return \"Google\";\n case \"IMAP\":\n return \"IMAP/SMTP\";\n case \"SLACK\":\n return \"Slack\";\n case \"FAKE\":\n return \"Test\";\n default:\n return provider ?? \"\";\n }\n};\n\n/** The connection's shown name: its own, else the provider's. */\nexport const agentConnectionNameOf = (connection: Pick<AgentConnectionSummary, \"name\" | \"provider\"> | null | undefined): string => connection?.name || agentConnectionProviderName(connection?.provider);\n\n/** Who looks at the connections: the signed-in account and whether it holds the system right. */\nexport interface AgentConnectionsViewer {\n accountId: number | string | null;\n mayManageSystemConnections: boolean;\n}\n\n/**\n * Whether the viewer may change a connection, as the server decides it (`requireManageableConnection`): the owner of\n * an account's own connection, a holder of the system right for a connection of the agent. The screens only hide what\n * the server would refuse.\n */\nexport const canManageAgentConnection = (connection: Pick<AgentConnectionSummary, \"ownership\" | \"ownerAccountId\">, viewer: AgentConnectionsViewer): boolean =>\n connection.ownership === \"AGENT_OWNED\"\n ? viewer.mayManageSystemConnections\n : viewer.accountId !== null && connection.ownerAccountId != null && String(connection.ownerAccountId) === String(viewer.accountId);\n\n/** Which connections a panel lists: all the account sees, or only the ones it may change. */\nexport type AgentConnectionsScope = \"all\" | \"manageable\";\n\nexport interface AgentConnectionsFilter {\n scope: AgentConnectionsScope;\n /** A status group, `\"\"` = every status. */\n statusGroup: AgentConnectionStatusGroup | \"\";\n /** Matched against name, account and provider name, case-insensitively. */\n searchTerm: string;\n}\n\n/** The connections of a scope (before status and search): the base of the quick filter counts. */\nexport const agentConnectionsOfScope = <TConnection extends AgentConnectionSummary>(connections: readonly TConnection[], scope: AgentConnectionsScope, viewer: AgentConnectionsViewer): TConnection[] =>\n scope === \"manageable\" ? connections.filter((connection) => canManageAgentConnection(connection, viewer)) : [...connections];\n\n/** The connections a filter keeps (client side: an account has a handful of connections). */\nexport const filterAgentConnections = <TConnection extends AgentConnectionSummary>(connections: readonly TConnection[], filter: AgentConnectionsFilter, viewer: AgentConnectionsViewer): TConnection[] => {\n const searchTerm = filter.searchTerm.trim().toLowerCase();\n return agentConnectionsOfScope(connections, filter.scope, viewer).filter((connection) => {\n if (filter.statusGroup !== \"\" && agentConnectionStatusGroupOf(connection.status) !== filter.statusGroup) return false;\n if (searchTerm === \"\") return true;\n return [connection.name, connection.externalAddress, agentConnectionProviderName(connection.provider)].some((text) => (text ?? \"\").toLowerCase().includes(searchTerm));\n });\n};\n\n/** How many connections each status group holds. */\nexport const countAgentConnectionsByStatusGroup = (connections: readonly Pick<AgentConnectionSummary, \"status\">[]): Record<AgentConnectionStatusGroup, number> => {\n const counts: Record<AgentConnectionStatusGroup, number> = { connected: 0, attention: 0, paused: 0, disconnected: 0 };\n for (const connection of connections) counts[agentConnectionStatusGroupOf(connection.status)] += 1;\n return counts;\n};\n\n/** Whether a connection lists the capability FILES at a level above OFF: it can carry drive roots. */\nexport const hasAgentConnectionDriveAccess = (connection: Pick<AgentConnectionSummary, \"levels\" | \"status\"> | null | undefined): boolean =>\n connection != null && connection.status !== \"REVOKED\" && parseAgentConnectionLevels(connection.levels).some((entry) => entry.capability === \"FILES\" && entry.level !== \"OFF\");\n\n/** The server refused a level whose scopes the provider has not granted (409, `consent_required: CAP at LEVEL`). */\nexport const isAgentConnectionConsentRequiredMessage = (message: string | null | undefined): boolean => (message ?? \"\").startsWith(\"consent_required:\");\n\n/** A port of a mail server from a form field: 1 to 5 digits, else `undefined`. */\nexport const agentConnectionPortOf = (value: string): number | undefined => (/^\\d{1,5}$/.test(value.trim()) ? Number(value.trim()) : undefined);\n","import type { AgentConnectionCapability, AgentConnectionLevel } from \"./agent-connections-types\";\nimport { isAgentConnectionCapability, isAgentConnectionLevel } from \"./agent-connection-format\";\n\n/**\n * The way to a provider's consent page and back, pure. A connect leaves the application: the start route answers the\n * consent URL (and sets the browser nonce cookie), the browser opens it, and the provider's callback redirects to ONE\n * route of the host (the server's settings page path) with `?connected=<id>` or `?connectError=<reason>`. What the way\n * back needs is stored first (`PendingAgentConnect`, this tab), with the surface that started the connect: the page of\n * the connections, or a panel in a dialog elsewhere. Whatever is mounted on the return route reads the parameters; a\n * panel takes them only when the pending connect is its own surface's, so the host can first reopen the dialog the\n * connect started in (`pendingAgentConnectSurfaceOf`) and the panel in it then shows the result.\n */\n\n/** The surface of a panel that names none: the page of the connections, where the provider's return lands. */\nexport const AGENT_CONNECTIONS_PAGE_SURFACE = \"page\";\n\n/** What a started OAuth connect remembers for the way back. */\nexport interface PendingAgentConnect {\n /** The row the start created (or, for an extension, the connection being extended). */\n startedConnectionId: number;\n /** The name the person typed; a consent merged into an existing connection does not use it. */\n typedName: string;\n /** The connection a \"Reconnect\" renews; the merge into it is the expected outcome. */\n reconnectOf: number | null;\n /** The connection whose levels an extension consent raises; `null` for a connect. */\n extendOf: number | null;\n /** The surface that started it (`AgentConnectionsPanelProps.surface`). */\n surface: string;\n}\n\nexport const serializePendingAgentConnect = (pending: PendingAgentConnect): string => JSON.stringify(pending);\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === \"object\" && value !== null;\n\n/** The stored pending connect; `null` for nothing stored or a value that cannot be read. */\nexport const parsePendingAgentConnect = (stored: string | null | undefined): PendingAgentConnect | null => {\n if (stored == null || stored === \"\") return null;\n let parsed: unknown;\n try {\n parsed = JSON.parse(stored);\n } catch {\n return null;\n }\n if (!isRecord(parsed) || typeof parsed.startedConnectionId !== \"number\") return null;\n return {\n startedConnectionId: parsed.startedConnectionId,\n typedName: typeof parsed.typedName === \"string\" ? parsed.typedName : \"\",\n reconnectOf: typeof parsed.reconnectOf === \"number\" ? parsed.reconnectOf : null,\n extendOf: typeof parsed.extendOf === \"number\" ? parsed.extendOf : null,\n surface: typeof parsed.surface === \"string\" && parsed.surface !== \"\" ? parsed.surface : AGENT_CONNECTIONS_PAGE_SURFACE,\n };\n};\n\n/** The surface a stored pending connect was started on; the page for none (a return without a stored start). */\nexport const pendingAgentConnectSurfaceOf = (stored: string | null | undefined): string => parsePendingAgentConnect(stored)?.surface ?? AGENT_CONNECTIONS_PAGE_SURFACE;\n\n/** What the callback appends to the return route; removed once read. */\nexport const AGENT_CONNECT_RETURN_PARAMETERS = [\"connected\", \"connectError\"] as const;\n\nexport interface AgentConnectReturnParameters {\n connected: string | null;\n connectError: string | null;\n}\n\n/** The return parameters of an address, `null` when it carries none. */\nexport const readAgentConnectReturnParameters = (parameters: Pick<URLSearchParams, \"get\">): AgentConnectReturnParameters | null => {\n const connected = parameters.get(\"connected\");\n const connectError = parameters.get(\"connectError\");\n return connected === null && connectError === null ? null : { connected, connectError };\n};\n\n/** What the OAuth callback sent the browser back with. */\nexport type AgentConnectReturn =\n /** `startedConnectionId`: the row the start created; connected but not shared when that row is connected. */\n | { kind: \"error\"; reason: string; startedConnectionId: number | null }\n | { kind: \"connected\"; connectionId: number }\n | { kind: \"renewed\"; connectionId: number }\n /** The consent was merged into an existing connection of the same account; the typed name was not used. */\n | { kind: \"merged\"; connectionId: number; typedName: string }\n /** More scopes for higher levels of an existing connection: granted (levels set) or partly refused at the provider. */\n | { kind: \"extended\"; connectionId: number }\n | { kind: \"extensionRefused\"; connectionId: number; reason: string };\n\n/**\n * Tells the outcomes apart from the return parameters and the pending connect: an error of an extension, an error of\n * a connect, a renewed connection (\"Reconnect\"), an extension, a consent merged into another row than the started\n * one, a new connection. `null` for parameters that say nothing (a `connected` that is no id).\n */\nexport const resolveAgentConnectReturn = (parameters: AgentConnectReturnParameters, pending: PendingAgentConnect | null): AgentConnectReturn | null => {\n const { connected, connectError } = parameters;\n if (connectError !== null && pending?.extendOf != null) return { kind: \"extensionRefused\", connectionId: pending.extendOf, reason: connectError };\n if (connectError !== null) return { kind: \"error\", reason: connectError, startedConnectionId: pending?.startedConnectionId ?? null };\n if (connected === null || !/^\\d+$/.test(connected)) return null;\n const connectionId = Number(connected);\n if (pending?.extendOf === connectionId) return { kind: \"extended\", connectionId };\n if (pending?.reconnectOf === connectionId) return { kind: \"renewed\", connectionId };\n if (pending !== null && pending.startedConnectionId !== connectionId) return { kind: \"merged\", connectionId, typedName: pending.typedName };\n return { kind: \"connected\", connectionId };\n};\n\n/** Whether the provider's reason says the person cancelled the consent. */\nexport const isAgentConnectCancelledReason = (reason: string): boolean => reason === \"access_denied\" || reason === \"cancelled\";\n\n/**\n * How a panel leaves for a provider and finds its way back: the host's storage, address and navigation. One object\n * for every panel of a host is fine; each panel names its own `surface`.\n */\nexport interface AgentConnectionsOAuthAdapter {\n /**\n * What the provider's return left in the address (`readAgentConnectReturnParameters` of the host's search\n * parameters), `null` on every other address. Reactive: it changes when the address does.\n */\n returnParameters: AgentConnectReturnParameters | null;\n /** Removes the return parameters from the address and keeps the others. */\n clearReturnParameters: () => void;\n /** The stored pending connect of this tab (the host's storage and key), `null` = none. */\n readPending: () => string | null;\n /** Stores the pending connect; `null` removes it. */\n writePending: (value: string | null) => void;\n /** Leaves for the provider's consent page. Default: `window.location.assign`. */\n openAuthorizationUrl?: (authorizationUrl: string) => void;\n}\n\n/** The search parameters of the deep link into the levels drawer of one connection. */\nexport const AGENT_CONNECTION_LEVELS_LINK_PARAMETERS = [\"levels\", \"capability\", \"level\"] as const;\n\n/** A request to open the levels drawer of a connection, with a suggested capability and level. */\nexport interface AgentConnectionLevelsRequest {\n connectionId: number;\n /** The capability and level to suggest; `null` opens the drawer as it is. */\n preset: { capability: AgentConnectionCapability; level: AgentConnectionLevel } | null;\n}\n\n/** The query string (without `?`) of a levels request: `levels=<id>&capability=…&level=…`. */\nexport const buildAgentConnectionLevelsSearch = ({ connectionId, preset }: AgentConnectionLevelsRequest): string => {\n const parameters = new URLSearchParams({ levels: String(connectionId) });\n if (preset !== null) {\n parameters.set(\"capability\", preset.capability);\n parameters.set(\"level\", preset.level);\n }\n return parameters.toString();\n};\n\n/** The levels request of an address, `null` without a valid `levels` id; an unknown capability or level drops the preset. */\nexport const readAgentConnectionLevelsRequest = (parameters: Pick<URLSearchParams, \"get\">): AgentConnectionLevelsRequest | null => {\n const levels = parameters.get(\"levels\");\n if (levels === null || !/^\\d+$/.test(levels)) return null;\n const capability = parameters.get(\"capability\") ?? \"\";\n const level = parameters.get(\"level\") ?? \"\";\n return { connectionId: Number(levels), preset: isAgentConnectionCapability(capability) && isAgentConnectionLevel(level) ? { capability, level } : null };\n};\n\n/** The search parameters of the deep link into the drive roots of one connection. */\nexport const AGENT_CONNECTION_DRIVE_LINK_PARAMETERS = [\"connection\", \"driveRoot\"] as const;\n\n/** The connection whose drive roots are open, and the root to scroll to and mark. */\nexport interface AgentConnectionDriveSelection {\n connectionId: number;\n driveRootId: number | null;\n}\n\n/** The query string (without `?`) of a drive selection: `connection=<id>[&driveRoot=<id>]`. */\nexport const buildAgentConnectionDriveSearch = ({ connectionId, driveRootId }: AgentConnectionDriveSelection): string => {\n const parameters = new URLSearchParams({ connection: String(connectionId) });\n if (driveRootId !== null) parameters.set(\"driveRoot\", String(driveRootId));\n return parameters.toString();\n};\n\n/**\n * The drive selection of an address, `null` without a valid `connection` id. An address that asks to reconnect\n * (`reconnect=1`, {@link readAgentConnectionReconnectRequest}) names the connection for that and opens no drives.\n */\nexport const readAgentConnectionDriveSelection = (parameters: Pick<URLSearchParams, \"get\">): AgentConnectionDriveSelection | null => {\n if (parameters.get(\"reconnect\") === \"1\") return null;\n const connection = parameters.get(\"connection\");\n if (connection === null || !/^\\d+$/.test(connection)) return null;\n const driveRoot = parameters.get(\"driveRoot\");\n return { connectionId: Number(connection), driveRootId: driveRoot !== null && /^\\d+$/.test(driveRoot) ? Number(driveRoot) : null };\n};\n\n/**\n * The search parameters of the deep link that renews a connection: `connection=<id>&reconnect=1`. A screen that finds\n * the connection expired links here (\"Reconnect\"); the panel scrolls to the connection and starts its reconnect once.\n */\nexport const AGENT_CONNECTION_RECONNECT_LINK_PARAMETERS = [\"connection\", \"reconnect\"] as const;\n\n/** A request to reconnect one connection (the deep link `connection=<id>&reconnect=1`). */\nexport interface AgentConnectionReconnectRequest {\n connectionId: number;\n}\n\n/** The query string (without `?`) of a reconnect request: `connection=<id>&reconnect=1`. */\nexport const buildAgentConnectionReconnectSearch = ({ connectionId }: AgentConnectionReconnectRequest): string =>\n new URLSearchParams({ connection: String(connectionId), reconnect: \"1\" }).toString();\n\n/** The reconnect request of an address, `null` unless `reconnect=1` names a valid `connection` id. */\nexport const readAgentConnectionReconnectRequest = (parameters: Pick<URLSearchParams, \"get\">): AgentConnectionReconnectRequest | null => {\n if (parameters.get(\"reconnect\") !== \"1\") return null;\n const connection = parameters.get(\"connection\");\n return connection !== null && /^\\d+$/.test(connection) ? { connectionId: Number(connection) } : null;\n};\n\n/** The DOM id of a root's row in the drive roots of a connection (the target of the deep link). */\nexport const agentConnectionDriveRootDomId = (connectionId: number, driveRootId: number | string): string => `connection-${connectionId}-drive-root-${driveRootId}`;\n","import { m } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { defineStatusMap } from \"@mgamadeus/ddd-admin-ui/logic\";\nimport { CircleCheck, CircleDashed, CircleMinus, CircleSlash } from \"lucide-react\";\nimport { type AgentConnectionsViewer, canManageAgentConnection, hasAgentConnectionDriveAccess } from \"./agent-connection-format\";\nimport type {\n AgentConnectionDriveItem,\n AgentConnectionDriveItemsSection,\n AgentConnectionDriveLabel,\n AgentConnectionDriveReleaseRole,\n AgentConnectionDriveRoot,\n AgentConnectionDriveRootKind,\n AgentConnectionDriveRootRelease,\n AgentConnectionSummary,\n} from \"./agent-connections-types\";\n\n/** The translation context of the drive texts that are single words. */\nexport const AGENT_CONNECTION_DRIVE_CONTEXT = \"agent-connection-drive\";\n\n/** The status of a root (`AgentConnectionDriveRoot::STATUS_*`). */\nexport const AGENT_CONNECTION_DRIVE_ROOT_STATUS = defineStatusMap<string>(\n {\n ACTIVE: { label: m(\"Active\", { context: \"agent-connection-drive\" }), tone: \"success\", icon: CircleCheck },\n UNASSIGNED: { label: m(\"Unassigned\", { context: \"agent-connection-drive\" }), tone: \"warning\", icon: CircleDashed },\n REVOKED: { label: m(\"Revoked\", { context: \"agent-connection-drive\" }), tone: \"neutral\", icon: CircleMinus },\n LOST: { label: m(\"Lost at the provider\", { context: \"agent-connection-drive\" }), tone: \"danger\", icon: CircleSlash },\n },\n { context: \"agent-connection-drive\" },\n);\n\n/** How a root came (`AgentConnectionDriveRoot::WAY_*`), as a short phrase; `%agentName%` = the agent's name. */\nexport const AGENT_CONNECTION_DRIVE_ROOT_WAY_LABEL: Readonly<Record<string, string>> = {\n OWN_IDENTITY: m(\"Shared with %agentName%’s own account\", { context: \"agent-connection-drive\" }),\n RELEASED_TO_AGENT: m(\"Released to %agentName%\", { context: \"agent-connection-drive\" }),\n PERSON_ROOT: m(\"Picked on this connection\", { context: \"agent-connection-drive\" }),\n PICKER: m(\"Chosen in the provider’s picker\", { context: \"agent-connection-drive\" }),\n};\n\n/** What a root is at the provider (`AgentConnectionDriveRoot::KIND_*`); a root of unknown kind has no label. */\nexport const AGENT_CONNECTION_DRIVE_ROOT_KIND_LABEL: Readonly<Record<string, string>> = {\n SHARED_DRIVE: m(\"Shared drive\", { context: \"agent-connection-drive\" }),\n FOLDER: m(\"Folder\", { context: \"agent-connection-drive\" }),\n FILE: m(\"File\", { context: \"agent-connection-drive\" }),\n};\n\n/** The kind a drive item would have as a root: a shared drive's own item carries its drive id, a folder opens, anything else is a file. */\nexport const agentConnectionDriveItemKindOf = (item: Pick<AgentConnectionDriveItem, \"itemId\" | \"kind\" | \"driveId\">): AgentConnectionDriveRootKind =>\n item.driveId != null && item.driveId !== \"\" && item.driveId === item.itemId ? \"SHARED_DRIVE\" : item.kind === \"FOLDER\" ? \"FOLDER\" : \"FILE\";\n\n/** The tops of a drive the picker lists, in the order of its switch (`section` of `driveItems`). */\nexport const AGENT_CONNECTION_DRIVE_ITEMS_SECTIONS: readonly AgentConnectionDriveItemsSection[] = [\"MY_DRIVE\", \"SHARED_DRIVES\", \"SHARED_WITH_ME\"];\n\n/** The name of each top as the provider's own screens call it. */\nexport const AGENT_CONNECTION_DRIVE_ITEMS_SECTION_LABEL: Readonly<Record<AgentConnectionDriveItemsSection, string>> = {\n MY_DRIVE: m(\"My Drive\", { context: \"agent-connection-drive\" }),\n SHARED_DRIVES: m(\"Shared drives\", { context: \"agent-connection-drive\" }),\n SHARED_WITH_ME: m(\"Shared with me\", { context: \"agent-connection-drive\" }),\n};\n\n/** The tops the picker offers: \"Shared drives\" only when the host's backend lists them. */\nexport const agentConnectionDriveItemsSectionsOf = (isSharedDrivesSectionAvailable: boolean): AgentConnectionDriveItemsSection[] =>\n AGENT_CONNECTION_DRIVE_ITEMS_SECTIONS.filter((section) => section !== \"SHARED_DRIVES\" || isSharedDrivesSectionAvailable);\n\n/** Whether the picker offers an item as a root: a folder or a shared drive. A single file is not picked there (a file that is a root already stays one). */\nexport const isAgentConnectionDriveItemAttachable = (item: Pick<AgentConnectionDriveItem, \"itemId\" | \"kind\" | \"driveId\">): boolean => agentConnectionDriveItemKindOf(item) !== \"FILE\";\n\n/** The rows of a picker listing: the folders and shared drives of a page, in its order; the files are left out. */\nexport const attachableAgentConnectionDriveItemsOf = <TItem extends Pick<AgentConnectionDriveItem, \"itemId\" | \"kind\" | \"driveId\">>(items: readonly TItem[]): TItem[] => items.filter(isAgentConnectionDriveItemAttachable);\n\n/** The groups the roots of a connection are listed in: the rules (no item) first. */\nexport type AgentConnectionDriveRootGroupKind = \"RULE\" | \"SHARED_DRIVE\" | \"FOLDER\" | \"FILE\";\n\n/** The heading of each group of roots. */\nexport const AGENT_CONNECTION_DRIVE_ROOT_GROUP_LABEL: Readonly<Record<AgentConnectionDriveRootGroupKind, string>> = {\n RULE: m(\"Automatic\", { context: \"agent-connection-drive\" }),\n SHARED_DRIVE: m(\"Shared drives\", { context: \"agent-connection-drive\" }),\n FOLDER: m(\"Folders\", { context: \"agent-connection-drive\" }),\n FILE: m(\"Files\", { context: \"agent-connection-drive\" }),\n};\n\nexport interface AgentConnectionDriveRootGroup<TRoot> {\n kind: AgentConnectionDriveRootGroupKind;\n roots: TRoot[];\n}\n\n/**\n * The roots of a connection by what they are at the provider: the rules first (all shared drives, the whole account),\n * then the shared drives, the folders (a root whose kind nobody stored counts as one), then the single files; a group\n * without roots is left out. Inside a group the roots in use come first, the ended ones (revoked, lost) after them,\n * each in the order given.\n */\nexport const agentConnectionDriveRootGroupsOf = <TRoot extends Pick<AgentConnectionDriveRoot, \"rootKind\" | \"status\">>(roots: readonly TRoot[]): AgentConnectionDriveRootGroup<TRoot>[] => {\n const groupKindOf = (root: TRoot): AgentConnectionDriveRootGroupKind =>\n root.rootKind === \"ALL_SHARED_DRIVES\" || root.rootKind === \"WHOLE_ACCOUNT\" ? \"RULE\" : root.rootKind === \"SHARED_DRIVE\" ? \"SHARED_DRIVE\" : root.rootKind === \"FILE\" ? \"FILE\" : \"FOLDER\";\n const groupKinds: readonly AgentConnectionDriveRootGroupKind[] = [\"RULE\", \"SHARED_DRIVE\", \"FOLDER\", \"FILE\"];\n return groupKinds\n .map((kind) => {\n const rootsOfKind = roots.filter((root) => groupKindOf(root) === kind);\n return { kind, roots: [...rootsOfKind.filter((root) => !isAgentConnectionDriveRootEnded(root)), ...rootsOfKind.filter(isAgentConnectionDriveRootEnded)] };\n })\n .filter((group) => group.roots.length > 0);\n};\n\n/** Whether a root ended: revoked by a person or lost at the provider. It stays listed and is used by nobody. */\nexport const isAgentConnectionDriveRootEnded = (root: Pick<AgentConnectionDriveRoot, \"status\">): boolean => root.status === \"REVOKED\" || root.status === \"LOST\";\n\n/** The shortest and longest name search the drive search route takes (`driveItems/search?query`). */\nexport const AGENT_CONNECTION_DRIVE_SEARCH_MIN_LENGTH = 2;\nexport const AGENT_CONNECTION_DRIVE_SEARCH_MAX_LENGTH = 200;\n\n/** The query a typed search text sends: trimmed and cut to the route's length, `null` while it is too short to search. */\nexport const agentConnectionDriveSearchQueryOf = (text: string): string | null => {\n const query = text.trim().slice(0, AGENT_CONNECTION_DRIVE_SEARCH_MAX_LENGTH);\n return query.length >= AGENT_CONNECTION_DRIVE_SEARCH_MIN_LENGTH ? query : null;\n};\n\n/** The roles a release to the agent may grant, weakest first (`AgentConnectionDriveReleasesService::RELEASE_ROLES`). */\nexport const AGENT_CONNECTION_DRIVE_RELEASE_ROLES: readonly AgentConnectionDriveReleaseRole[] = [\"reader\", \"commenter\", \"writer\", \"fileOrganizer\"];\n\n/** The provider's role as people know it from its share dialog. */\nexport const AGENT_CONNECTION_DRIVE_ROLE_LABEL: Readonly<Record<string, string>> = {\n reader: m(\"Viewer\", { context: \"agent-connection-drive\" }),\n commenter: m(\"Commenter\", { context: \"agent-connection-drive\" }),\n writer: m(\"Editor\", { context: \"agent-connection-drive\" }),\n fileOrganizer: m(\"Content manager\", { context: \"agent-connection-drive\" }),\n};\n\nexport const isAgentConnectionDriveReleaseRole = (value: string): value is AgentConnectionDriveReleaseRole => AGENT_CONNECTION_DRIVE_RELEASE_ROLES.some((role) => role === value);\n\n/** Whether an item of a drive listing can be opened (a folder; a shared drive is listed as one). */\nexport const isAgentConnectionDriveFolder = (item: Pick<AgentConnectionDriveItem, \"kind\">): boolean => item.kind === \"FOLDER\";\n\n/** Whether the provider lets the listing account share the item (a release to the agent needs it). */\nexport const canShareAgentConnectionDriveItem = (item: Pick<AgentConnectionDriveItem, \"canShare\" | \"canManageMembers\">): boolean => item.canShare === true || item.canManageMembers === true;\n\n/**\n * Whether \"release to the agent\" is offered for an item. A folder or file: when the provider lets the account share it\n * (`canShareAgentConnectionDriveItem`). A shared drive: the provider decides at the share, because a row of the tree\n * never carries the drive's capability; only a search result does, and one that says the account does not manage the\n * drive's members is refused here already.\n */\nexport const canReleaseAgentConnectionDriveItemToAgent = (item: Pick<AgentConnectionDriveItem, \"itemId\" | \"kind\" | \"driveId\" | \"canShare\" | \"canManageMembers\">, isSearchResult: boolean): boolean =>\n agentConnectionDriveItemKindOf(item) === \"SHARED_DRIVE\" ? !(isSearchResult && item.canManageMembers === false) : canShareAgentConnectionDriveItem(item);\n\n/** The root an item already is on the connection (ACTIVE or UNASSIGNED; never an ended one), else `null`. */\nexport const findAgentConnectionDriveRootOfItem = (roots: readonly AgentConnectionDriveRoot[], itemId: string): AgentConnectionDriveRoot | null =>\n roots.find((root) => root.itemId === itemId && !isAgentConnectionDriveRootEnded(root)) ?? null;\n\n/** The numeric id of a root row, `null` for a row without one. */\nexport const agentConnectionDriveRootIdOf = (root: Pick<AgentConnectionDriveRoot, \"id\">): number | null => {\n const id = typeof root.id === \"string\" ? Number(root.id) : root.id;\n return typeof id === \"number\" && Number.isFinite(id) ? id : null;\n};\n\n/** What the viewer may do with one root, as the server decides it; the screens only hide what it would refuse. */\nexport interface AgentConnectionDriveRootActions {\n /** `POST driveRoots/remove`: whoever manages the connection. */\n canRemove: boolean;\n /** `POST driveRoots/assign`: an unassigned share of the agent's identity, the system right. */\n canAssign: boolean;\n /** `POST /driveRoots/{id}/revoke`: a release to the agent, by the person who released it or the system right. */\n canRevokeRelease: boolean;\n /** `POST driveRoots` with the ended root's item: whoever manages the connection (a share of the agent's own account: the system right). */\n canAttachAgain: boolean;\n /** `POST /driveRoots/{id}/releases`: an active root, whoever manages the connection. */\n canReleaseToSpace: boolean;\n /** `POST /driveRoots/{id}/restrict`: an active root that still follows the connection, whoever manages it. */\n canRestrict: boolean;\n /** `POST /driveRoots/{id}/followConnection`: an active restricted root, whoever manages the connection. */\n canFollowConnection: boolean;\n}\n\nexport const agentConnectionDriveRootActionsOf = (root: AgentConnectionDriveRoot, connection: Pick<AgentConnectionSummary, \"ownership\" | \"ownerAccountId\">, viewer: AgentConnectionsViewer): AgentConnectionDriveRootActions => {\n const canManage = canManageAgentConnection(connection, viewer);\n const isReleasedToAgent = root.releaseWay === \"RELEASED_TO_AGENT\" && root.status === \"ACTIVE\";\n const isReleasedByViewer = viewer.accountId !== null && root.grantedByAccountId != null && String(root.grantedByAccountId) === String(viewer.accountId);\n const canRevokeRelease = isReleasedToAgent && agentConnectionDriveRootIdOf(root) !== null && (isReleasedByViewer || viewer.mayManageSystemConnections);\n const hasEnded = isAgentConnectionDriveRootEnded(root);\n // a rule (all shared drives, the whole account) follows the sharing of its connection: never released to single spaces\n const isRule = root.rootKind === \"ALL_SHARED_DRIVES\" || root.rootKind === \"WHOLE_ACCOUNT\";\n const canChangeSpaces = canManage && !isRule && root.status === \"ACTIVE\" && agentConnectionDriveRootIdOf(root) !== null;\n const isRestricted = root.restrictedToAgentSpaces === true;\n return {\n canRevokeRelease,\n canAssign: root.status === \"UNASSIGNED\" && canManage && viewer.mayManageSystemConnections,\n // a release is taken back (the share at the provider goes with it), never just removed\n canRemove: canManage && !isReleasedToAgent && !hasEnded,\n // a release to the agent comes back by releasing it again (the share at the provider is gone); a rule by its kind\n canAttachAgain: canManage && hasEnded && (isRule || (root.itemId ?? \"\") !== \"\") && root.releaseWay !== \"RELEASED_TO_AGENT\" && (root.releaseWay !== \"OWN_IDENTITY\" || viewer.mayManageSystemConnections),\n canReleaseToSpace: canChangeSpaces,\n canRestrict: canChangeSpaces && !isRestricted,\n canFollowConnection: canChangeSpaces && isRestricted,\n };\n};\n\n/** The way an ended root is attached again (`POST driveRoots`): the way it came, a picked root by default. */\nexport const agentConnectionDriveRootAttachWayOf = (root: Pick<AgentConnectionDriveRoot, \"releaseWay\">): \"PERSON_ROOT\" | \"PICKER\" | \"OWN_IDENTITY\" =>\n root.releaseWay === \"PICKER\" ? \"PICKER\" : root.releaseWay === \"OWN_IDENTITY\" ? \"OWN_IDENTITY\" : \"PERSON_ROOT\";\n\n/** The numeric id of a release row, `null` for a row without one. */\nexport const agentConnectionDriveRootReleaseIdOf = (release: Pick<AgentConnectionDriveRootRelease, \"id\">): number | null => agentConnectionDriveRootIdOf(release);\n\n/** The active releases of one root to agent spaces, oldest first (the releases taken back are the audit). */\nexport const activeAgentConnectionDriveRootReleasesOf = (root: Pick<AgentConnectionDriveRoot, \"id\">, releases: readonly AgentConnectionDriveRootRelease[]): AgentConnectionDriveRootRelease[] => {\n const driveRootId = agentConnectionDriveRootIdOf(root);\n if (driveRootId === null) return [];\n return releases.filter((release) => release.agentConnectionDriveRootId === driveRootId && (release.revokedAt ?? null) === null && release.agentSpaceId != null);\n};\n\n/** `POST /driveRootReleases/{id}/revoke`: the person who released the root to the space, or the system right. */\nexport const canRevokeAgentConnectionDriveRootRelease = (release: Pick<AgentConnectionDriveRootRelease, \"id\" | \"grantedByAccountId\" | \"revokedAt\">, viewer: AgentConnectionsViewer): boolean => {\n if ((release.revokedAt ?? null) !== null || agentConnectionDriveRootReleaseIdOf(release) === null) return false;\n const isReleasedByViewer = viewer.accountId !== null && release.grantedByAccountId != null && String(release.grantedByAccountId) === String(viewer.accountId);\n return isReleasedByViewer || viewer.mayManageSystemConnections;\n};\n\n/**\n * Which agent spaces use an active root: `connection` = it follows the connection's sharing (every space the\n * connection is shared with), `spaces` = only the spaces of its active releases, `none` = restricted with no space\n * (only the owner's own use is left).\n */\nexport type AgentConnectionDriveRootSpaceState = \"connection\" | \"spaces\" | \"none\";\n\nexport const agentConnectionDriveRootSpaceStateOf = (root: Pick<AgentConnectionDriveRoot, \"id\" | \"restrictedToAgentSpaces\">, releases: readonly AgentConnectionDriveRootRelease[]): AgentConnectionDriveRootSpaceState =>\n root.restrictedToAgentSpaces !== true ? \"connection\" : activeAgentConnectionDriveRootReleasesOf(root, releases).length > 0 ? \"spaces\" : \"none\";\n\n/** The spaces a root can still be released to: the viewer's releasable ones it is not released to yet. */\nexport const releasableAgentSpaceIdsOfDriveRoot = (root: Pick<AgentConnectionDriveRoot, \"id\">, releases: readonly AgentConnectionDriveRootRelease[], releasableAgentSpaceIds: readonly number[]): number[] => {\n const releasedIds = new Set(activeAgentConnectionDriveRootReleasesOf(root, releases).map((release) => release.agentSpaceId));\n return releasableAgentSpaceIds.filter((agentSpaceId) => !releasedIds.has(agentSpaceId));\n};\n\n/** The host's label of an agent space or account by id; `null` when the host supplied none (the screen then names the id). */\nexport const agentConnectionDriveLabelOf = (labels: readonly AgentConnectionDriveLabel[] | null | undefined, id: number | null | undefined): string | null => {\n if (id == null) return null;\n const label = labels?.find((entry) => Number(entry.id) === Number(id))?.label?.trim() ?? \"\";\n return label !== \"\" ? label : null;\n};\n\n/**\n * The agent's own drive identities an item of `source` can be released to: connected system connections of the same\n * provider with an address and drive access, never `source` itself. Empty for a system connection (only a person's\n * own connection releases its items, with that person's token).\n */\nexport const agentConnectionDriveReleaseTargetsOf = <TConnection extends AgentConnectionSummary>(source: AgentConnectionSummary, connections: readonly TConnection[], viewer: AgentConnectionsViewer): TConnection[] => {\n if (source.ownership === \"AGENT_OWNED\" || !canManageAgentConnection(source, viewer)) return [];\n return connections.filter(\n (connection) =>\n connection.connectionId !== source.connectionId &&\n connection.ownership === \"AGENT_OWNED\" &&\n connection.provider === source.provider &&\n connection.status === \"CONNECTED\" &&\n (connection.externalAddress ?? \"\") !== \"\" &&\n hasAgentConnectionDriveAccess(connection),\n );\n};\n","import { cn } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { CalendarDays, CircleHelp, Contact, FolderOpen, type LucideIcon, Mail, MessageCircle, MessageSquare, Plug } from \"lucide-react\";\nimport type { ComponentType } from \"react\";\nimport type { AgentConnectionCapability } from \"./agent-connections-types\";\nimport { useAgentConnectionsContext } from \"./agent-connections-context\";\n\n/*\n * The marks of the connection providers the package ships (Google, Slack) and of Google's products, inline (no request\n * to a third party). The colours are the brands' own and stay as they are in both themes (brand guidelines: a mark is\n * never recoloured), which is why these are the only literal colours of the area; every other colour is a token. A\n * host adds or replaces marks with `AgentConnectionsPanelProps.logos`.\n */\n\n/** A mark takes a class for its size. */\nexport interface AgentConnectionLogoProps {\n className?: string;\n}\n\n/** The Google \"G\" (multicolour). */\nexport const GoogleLogo = ({ className }: AgentConnectionLogoProps) => (\n <svg viewBox=\"0 0 48 48\" aria-hidden className={cn(\"size-5\", className)}>\n <path\n fill=\"#EA4335\"\n d=\"M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z\"\n />\n <path\n fill=\"#4285F4\"\n d=\"M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z\"\n />\n <path\n fill=\"#FBBC05\"\n d=\"M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z\"\n />\n <path\n fill=\"#34A853\"\n d=\"M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-4.92 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z\"\n />\n </svg>\n);\n\n/** The Slack mark (four colours). */\nexport const SlackLogo = ({ className }: AgentConnectionLogoProps) => (\n <svg viewBox=\"0 0 122.8 122.8\" aria-hidden className={cn(\"size-5\", className)}>\n <path\n fill=\"#E01E5A\"\n d=\"M25.8 77.6c0 7.1-5.8 12.9-12.9 12.9S0 84.7 0 77.6s5.8-12.9 12.9-12.9h12.9v12.9zm6.5 0c0-7.1 5.8-12.9 12.9-12.9s12.9 5.8 12.9 12.9v32.3c0 7.1-5.8 12.9-12.9 12.9s-12.9-5.8-12.9-12.9V77.6z\"\n />\n <path\n fill=\"#36C5F0\"\n d=\"M45.2 25.8c-7.1 0-12.9-5.8-12.9-12.9S38.1 0 45.2 0s12.9 5.8 12.9 12.9v12.9H45.2zm0 6.5c7.1 0 12.9 5.8 12.9 12.9s-5.8 12.9-12.9 12.9H12.9C5.8 58.1 0 52.3 0 45.2s5.8-12.9 12.9-12.9h32.3z\"\n />\n <path\n fill=\"#2EB67D\"\n d=\"M97 45.2c0-7.1 5.8-12.9 12.9-12.9s12.9 5.8 12.9 12.9-5.8 12.9-12.9 12.9H97V45.2zm-6.5 0c0 7.1-5.8 12.9-12.9 12.9s-12.9-5.8-12.9-12.9V12.9C64.7 5.8 70.5 0 77.6 0s12.9 5.8 12.9 12.9v32.3z\"\n />\n <path\n fill=\"#ECB22E\"\n d=\"M77.6 97c7.1 0 12.9 5.8 12.9 12.9s-5.8 12.9-12.9 12.9-12.9-5.8-12.9-12.9V97h12.9zm0-6.5c-7.1 0-12.9-5.8-12.9-12.9s5.8-12.9 12.9-12.9h32.3c7.1 0 12.9 5.8 12.9 12.9s-5.8 12.9-12.9 12.9H77.6z\"\n />\n </svg>\n);\n\n/** Gmail (the 2020 \"M\"). */\nexport const GmailLogo = ({ className }: AgentConnectionLogoProps) => (\n <svg viewBox=\"52 42 88 66\" aria-hidden className={cn(\"size-4\", className)}>\n <path fill=\"#4285F4\" d=\"M58 108h14V74L52 59v43c0 3.32 2.69 6 6 6\" />\n <path fill=\"#34A853\" d=\"M120 108h14c3.32 0 6-2.69 6-6V59l-20 15\" />\n <path fill=\"#FBBC04\" d=\"M120 48v26l20-15v-8c0-7.42-8.47-11.65-14.4-7.2\" />\n <path fill=\"#EA4335\" d=\"M72 74V48l24 18 24-18v26L96 92\" />\n <path fill=\"#C5221F\" d=\"M52 51v8l20 15V48l-5.6-4.2c-5.94-4.45-14.4-.22-14.4 7.2\" />\n </svg>\n);\n\n/** Google Calendar (the 2020 tile with \"31\"). */\nexport const GoogleCalendarLogo = ({ className }: AgentConnectionLogoProps) => (\n <svg viewBox=\"0 0 200 200\" aria-hidden className={cn(\"size-4\", className)}>\n <g transform=\"translate(3.75 3.75)\">\n <path fill=\"#FFFFFF\" d=\"M148.882 43.618l-47.368-5.263-57.895 5.263-5.264 52.632 5.263 52.632 52.632 6.579 52.632-6.579 5.263-53.947z\" />\n <path\n fill=\"#1A73E8\"\n d=\"M65.211 125.276c-3.934-2.658-6.658-6.539-8.145-11.671l9.132-3.763c.829 3.158 2.276 5.605 4.342 7.342 2.053 1.737 4.553 2.592 7.474 2.592 2.987 0 5.553-.908 7.697-2.724s3.224-4.132 3.224-6.934c0-2.868-1.132-5.211-3.395-7.026s-5.105-2.724-8.5-2.724h-5.276v-9.039H76.5c2.921 0 5.382-.789 7.382-2.368 2-1.579 3-3.737 3-6.487 0-2.447-.895-4.395-2.684-5.855s-4.053-2.197-6.803-2.197c-2.684 0-4.816.711-6.395 2.145s-2.724 3.197-3.447 5.276l-9.039-3.763c1.197-3.395 3.395-6.395 6.618-8.987 3.224-2.592 7.342-3.895 12.342-3.895 3.697 0 7.026.711 9.974 2.145 2.947 1.434 5.263 3.421 6.934 5.947 1.671 2.539 2.5 5.382 2.5 8.539 0 3.224-.776 5.947-2.329 8.184-1.553 2.237-3.461 3.947-5.724 5.145v.539c2.987 1.25 5.421 3.158 7.342 5.724 1.908 2.566 2.868 5.632 2.868 9.211s-.908 6.776-2.724 9.579c-1.816 2.803-4.329 5.013-7.513 6.618-3.197 1.605-6.789 2.421-10.776 2.421-4.618.013-8.881-1.316-12.815-3.974z\"\n />\n <path fill=\"#1A73E8\" d=\"M121.25 79.961l-9.974 7.25-5.013-7.605 17.987-12.974h6.895v61.197h-9.895z\" />\n <path fill=\"#EA4335\" d=\"M148.882 196.25l47.368-47.368-23.684-10.526-23.684 10.526-10.526 23.684z\" />\n <path fill=\"#34A853\" d=\"M33.092 172.566l10.526 23.684h105.263v-47.368H43.618z\" />\n <path\n fill=\"#4285F4\"\n d=\"M12.039-3.75C3.316-3.75-3.75 3.316-3.75 12.039v136.842l23.684 10.526 23.684-10.526V43.618h105.263l10.526-23.684L148.882-3.75z\"\n />\n <path fill=\"#188038\" d=\"M-3.75 148.882v31.579c0 8.724 7.066 15.789 15.789 15.789h31.579v-47.368z\" />\n <path fill=\"#FBBC04\" d=\"M148.882 43.618v105.263h47.368V43.618l-23.684-10.526z\" />\n <path fill=\"#1967D2\" d=\"M196.25 43.618V12.039c0-8.724-7.066-15.789-15.789-15.789h-31.579v47.368z\" />\n </g>\n </svg>\n);\n\n/** Google Contacts (the blue person). */\nexport const GoogleContactsLogo = ({ className }: AgentConnectionLogoProps) => (\n <svg viewBox=\"0 0 48 48\" aria-hidden className={cn(\"size-4\", className)}>\n <circle cx=\"24\" cy=\"15\" r=\"9\" fill=\"#1A73E8\" />\n <path fill=\"#4285F4\" d=\"M24 28c-8.3 0-17 4.1-17 10v4a2 2 0 0 0 2 2h30a2 2 0 0 0 2-2v-4c0-5.9-8.7-10-17-10z\" />\n <path fill=\"#185ABC\" d=\"M24 28c-8.3 0-17 4.1-17 10v4a2 2 0 0 0 2 2h15z\" opacity=\"0.35\" />\n </svg>\n);\n\n/** Google Drive (the triangle). */\nexport const GoogleDriveLogo = ({ className }: AgentConnectionLogoProps) => (\n <svg viewBox=\"0 0 87.3 78\" aria-hidden className={cn(\"size-4\", className)}>\n <path fill=\"#0066DA\" d=\"M6.6 66.85l3.85 6.65c.8 1.4 1.95 2.5 3.3 3.3l13.75-23.8H0c0 1.55.4 3.1 1.2 4.5z\" />\n <path fill=\"#00AC47\" d=\"M43.65 25L29.9 1.2c-1.35.8-2.5 1.9-3.3 3.3l-25.4 44A9.06 9.06 0 0 0 0 53h27.5z\" />\n <path\n fill=\"#EA4335\"\n d=\"M73.55 76.8c1.35-.8 2.5-1.9 3.3-3.3l1.6-2.75 7.65-13.25c.8-1.4 1.2-2.95 1.2-4.5H59.798l5.852 11.5z\"\n />\n <path fill=\"#00832D\" d=\"M43.65 25L57.4 1.2C56.05.4 54.5 0 52.9 0H34.4c-1.6 0-3.15.45-4.5 1.2z\" />\n <path fill=\"#2684FC\" d=\"M59.8 53H27.5L13.75 76.8c1.35.8 2.9 1.2 4.5 1.2h50.8c1.6 0 3.15-.45 4.5-1.2z\" />\n <path fill=\"#FFBA00\" d=\"M73.4 26.5l-12.7-22c-.8-1.4-1.95-2.5-3.3-3.3L43.65 25 59.8 53h27.45c0-1.55-.4-3.1-1.2-4.5z\" />\n </svg>\n);\n\n/** The neutral icon of a capability (a provider without product marks: IMAP, Slack, a test adapter). */\nconst CAPABILITY_ICON: Readonly<Record<AgentConnectionCapability, LucideIcon>> = {\n MAIL: Mail,\n CALENDAR: CalendarDays,\n CONTACTS: Contact,\n FILES: FolderOpen,\n CHAT: MessageSquare,\n MESSAGING: MessageCircle,\n};\n\n/** A mark component: a provider's or a product's. */\nexport type AgentConnectionLogo = ComponentType<AgentConnectionLogoProps>;\n\n/**\n * The marks by provider name (`GOOGLE`, `SLACK`, …): `providers` the provider's own mark, `capabilities` the product\n * mark of a capability on that provider (Gmail for MAIL on Google). A provider without a mark gets a neutral icon.\n */\nexport interface AgentConnectionLogos {\n providers?: Readonly<Record<string, AgentConnectionLogo | undefined>>;\n capabilities?: Readonly<Record<string, Partial<Record<AgentConnectionCapability, AgentConnectionLogo>> | undefined>>;\n}\n\n/** The marks the package ships: Google and Slack, and Google's products per capability. */\nexport const DEFAULT_AGENT_CONNECTION_LOGOS: Required<AgentConnectionLogos> = {\n providers: { GOOGLE: GoogleLogo, SLACK: SlackLogo },\n capabilities: { GOOGLE: { MAIL: GmailLogo, CALENDAR: GoogleCalendarLogo, CONTACTS: GoogleContactsLogo, FILES: GoogleDriveLogo } },\n};\n\n/** The package's marks with a host's on top (a host entry replaces the package's of the same provider or capability). */\nexport const mergeAgentConnectionLogos = (logos: AgentConnectionLogos | undefined): Required<AgentConnectionLogos> => {\n const capabilities: Record<string, Partial<Record<AgentConnectionCapability, AgentConnectionLogo>> | undefined> = { ...DEFAULT_AGENT_CONNECTION_LOGOS.capabilities };\n for (const [provider, marks] of Object.entries(logos?.capabilities ?? {})) capabilities[provider] = { ...capabilities[provider], ...marks };\n return { providers: { ...DEFAULT_AGENT_CONNECTION_LOGOS.providers, ...logos?.providers }, capabilities };\n};\n\ninterface CapabilityIconProps {\n provider: string | null | undefined;\n capability: AgentConnectionCapability;\n className?: string;\n}\n\n/** A capability's icon: the product mark of the provider (Gmail, Calendar, Contacts, Drive on Google), else neutral. */\nexport const CapabilityIcon = ({ provider, capability, className }: CapabilityIconProps) => {\n const { logos } = useAgentConnectionsContext();\n const ProductLogo = logos.capabilities[provider ?? \"\"]?.[capability];\n if (ProductLogo) return <ProductLogo className={cn(\"size-4 shrink-0\", className)} />;\n const Icon = CAPABILITY_ICON[capability] ?? CircleHelp;\n return <Icon aria-hidden className={cn(\"size-4 shrink-0 text-muted-foreground\", className)} />;\n};\n\n/** The provider's bare mark (a dialog title); nothing for a provider without one. */\nexport const ProviderLogo = ({ provider, className }: { provider: string; className?: string }) => {\n const { logos } = useAgentConnectionsContext();\n const Logo = logos.providers[provider];\n return Logo ? <Logo className={className} /> : null;\n};\n\ninterface ProviderMarkProps {\n provider: string | null | undefined;\n /** `md` 40 px (tiles, the connect menu), `sm` 32 px (table rows). */\n size?: \"sm\" | \"md\";\n className?: string;\n}\n\n/** The provider's mark in a rounded tile; a mail icon for IMAP/SMTP and a plug for a provider without a mark. */\nexport const ProviderMark = ({ provider, size = \"md\", className }: ProviderMarkProps) => {\n const { logos } = useAgentConnectionsContext();\n const ProviderLogo = logos.providers[provider ?? \"\"];\n const NeutralIcon = provider === \"IMAP\" ? Mail : Plug;\n return (\n <span aria-hidden className={cn(\"flex shrink-0 items-center justify-center rounded-xl border bg-card shadow-xs\", size === \"md\" ? \"size-10\" : \"size-8\", className)}>\n {ProviderLogo ? <ProviderLogo className={size === \"md\" ? \"size-5\" : \"size-4\"} /> : <NeutralIcon className={cn(\"text-muted-foreground\", size === \"md\" ? \"size-5\" : \"size-4\")} />}\n </span>\n );\n};\n","import { type TranslateFn, useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { createContext, type ReactNode, useContext, useMemo } from \"react\";\nimport type { AgentConnectionsApi } from \"./agent-connections-api\";\nimport { AGENT_CONNECTION_LEVEL_HELP, AGENT_CONNECTION_LEVEL_HELP_CONTEXT, AGENT_CONNECTION_OWNER_ONLY_LABEL, AGENT_CONNECTION_VISIBILITY_CONTEXT, type AgentConnectionsViewer } from \"./agent-connection-format\";\nimport type { AgentConnectionsOAuthAdapter } from \"./agent-connection-oauth\";\nimport type { AgentConnectionLevel, AgentConnectionVisibility } from \"./agent-connections-types\";\nimport { type AgentConnectionLogos, mergeAgentConnectionLogos } from \"./connection-logos\";\n\n/**\n * The texts of the connection screens a host words itself, already translated: the agent's name in the sentences, and\n * what \"shared\" means here (who works in the space a connection is shared with). Every entry has a generic default.\n */\nexport interface AgentConnectionsTexts {\n /** The agent's name in sentences (\"%agentName% reads, searches and lists.\"). Default \"The agent\". */\n agentName?: string;\n /** The name of the visibility `AGENT_SPACE` (badge, choice). Default \"For the shared space\". */\n sharedVisibilityLabel?: string;\n /** What sharing means, under the visibility choice. */\n sharedVisibilityHelp?: string;\n /** Under the visibility choice of a connect dialog when the account has no space to share with. */\n noShareTargetHelp?: string;\n /** The toast after a connection was shared. */\n sharedToast?: string;\n /** The description of the dialog that connects the agent's Slack bot. */\n slackBotDescription?: string;\n /** The placeholder of the Slack connection's name. */\n slackNamePlaceholder?: string;\n /** The placeholder of the mail address of an IMAP/SMTP mailbox. */\n imapAddressPlaceholder?: string;\n}\n\n/** What every part of the connections panel reads: the api, the viewer, the rights, the host's texts, marks and adapters. */\nexport interface AgentConnectionsContextValue {\n api: AgentConnectionsApi;\n writesAllowed: boolean;\n viewer: AgentConnectionsViewer;\n /** The space a connection is shared with (\"shared\"), `null` when the account has none. */\n sharedAgentSpaceId: number | null;\n texts: Required<AgentConnectionsTexts>;\n logos: Required<AgentConnectionLogos>;\n oauth: AgentConnectionsOAuthAdapter | null;\n /** The surface a connect started here is stored with (`PendingAgentConnect.surface`). */\n surface: string;\n}\n\nconst AgentConnectionsContext = createContext<AgentConnectionsContextValue | null>(null);\n\n/** The resolved texts: the host's, else the package's generic ones. */\nexport const resolveAgentConnectionsTexts = (texts: AgentConnectionsTexts | undefined, t: TranslateFn): Required<AgentConnectionsTexts> => {\n const agentName = texts?.agentName ?? t(\"The agent\", { context: \"agent-connection-agent-name\" });\n const sharedVisibilityLabel = texts?.sharedVisibilityLabel ?? t(\"For the shared space\", { context: \"agent-connection-visibility\" });\n return {\n agentName,\n sharedVisibilityLabel,\n sharedVisibilityHelp:\n texts?.sharedVisibilityHelp ??\n t(\"“%label%”: %agentName% also uses the account in the conversations of everyone working in the shared space, read only at first.\", {\n replacements: { label: sharedVisibilityLabel, agentName },\n }),\n noShareTargetHelp: texts?.noShareTargetHelp ?? t(\"There is no shared space to share with yet.\"),\n sharedToast: texts?.sharedToast ?? t(\"Shared with the space\"),\n slackBotDescription: texts?.slackBotDescription ?? t(\"A connection of %agentName% itself, for the shared space. The bot token is set on the server.\", { replacements: { agentName } }),\n slackNamePlaceholder: texts?.slackNamePlaceholder ?? \"Slack\",\n imapAddressPlaceholder: texts?.imapAddressPlaceholder ?? \"info@example.com\",\n };\n};\n\nexport interface AgentConnectionsProviderProps extends Omit<AgentConnectionsContextValue, \"texts\" | \"logos\"> {\n texts?: AgentConnectionsTexts;\n logos?: AgentConnectionLogos;\n children: ReactNode;\n}\n\n/** Hands the panel's api, rights, texts, marks and adapters to its parts. */\nexport const AgentConnectionsProvider = ({ api, writesAllowed, viewer, sharedAgentSpaceId, texts, logos, oauth, surface, children }: AgentConnectionsProviderProps) => {\n const { t } = useTranslate();\n const { accountId, mayManageSystemConnections } = viewer;\n const value = useMemo<AgentConnectionsContextValue>(\n () => ({\n api,\n writesAllowed,\n viewer: { accountId, mayManageSystemConnections },\n sharedAgentSpaceId,\n texts: resolveAgentConnectionsTexts(texts, t),\n logos: mergeAgentConnectionLogos(logos),\n oauth,\n surface,\n }),\n [api, writesAllowed, accountId, mayManageSystemConnections, sharedAgentSpaceId, texts, logos, oauth, surface, t],\n );\n return <AgentConnectionsContext.Provider value={value}>{children}</AgentConnectionsContext.Provider>;\n};\n\nexport const useAgentConnectionsContext = (): AgentConnectionsContextValue => {\n const value = useContext(AgentConnectionsContext);\n if (value === null) throw new Error(\"The parts of the connections panel render inside an AgentConnectionsProvider (AgentConnectionsPanel mounts one).\");\n return value;\n};\n\n/** The visibility choices of the connect, levels and sharing dialogs: \"Just for me\" and the host's name of \"shared\". */\nexport const useAgentConnectionVisibilityOptions = (): readonly { value: AgentConnectionVisibility; label: string; translate: false }[] => {\n const { t } = useTranslate();\n const { texts } = useAgentConnectionsContext();\n return useMemo(\n () => [\n { value: \"OWNER_ONLY\", label: t(AGENT_CONNECTION_OWNER_ONLY_LABEL, { context: AGENT_CONNECTION_VISIBILITY_CONTEXT }), translate: false },\n { value: \"AGENT_SPACE\", label: texts.sharedVisibilityLabel, translate: false },\n ],\n [t, texts.sharedVisibilityLabel],\n );\n};\n\n/** The explanation of a level with the agent's name in it. */\nexport const useAgentConnectionLevelHelp = (): ((level: AgentConnectionLevel) => string) => {\n const { t } = useTranslate();\n const { texts } = useAgentConnectionsContext();\n return (level) => t(AGENT_CONNECTION_LEVEL_HELP[level], { context: AGENT_CONNECTION_LEVEL_HELP_CONTEXT, replacements: { agentName: texts.agentName } });\n};\n","import { parseDddDateTime } from \"@mgamadeus/ddd-web/contract\";\nimport { useFormatLocale, useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { StatusBadge } from \"@mgamadeus/ddd-admin-ui/list\";\nimport { formatRelativeTime, notify, toFormSubmitError } from \"@mgamadeus/ddd-admin-ui/logic\";\nimport { Button, cn, DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger, Input } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { ChevronDown, FolderTree, Lock, MoreHorizontal, Pencil, Plus, RefreshCw, SlidersHorizontal, Unplug, Users } from \"lucide-react\";\nimport { useEffect, useRef, useState } from \"react\";\nimport {\n AGENT_CONNECTION_CAPABILITY_CONTEXT,\n AGENT_CONNECTION_CAPABILITY_LABEL,\n AGENT_CONNECTION_LEVEL_CONTEXT,\n AGENT_CONNECTION_LEVEL_LABEL,\n AGENT_CONNECTION_OWNER_ONLY_LABEL,\n AGENT_CONNECTION_STATUS,\n AGENT_CONNECTION_VISIBILITY_CONTEXT,\n agentConnectionLevelToneClass,\n} from \"./agent-connection-format\";\nimport { useAgentConnectionLevelHelp, useAgentConnectionsContext } from \"./agent-connections-context\";\nimport type { AgentConnectionCapabilityLevel } from \"./agent-connections-types\";\nimport { CapabilityIcon, ProviderMark } from \"./connection-logos\";\n\n/** Who may let the agent use the connection: only its owner (lock) or the shared space (people, brand tint). */\nexport const AgentConnectionVisibilityBadge = ({ visibility }: { visibility: string | null | undefined }) => {\n const { t } = useTranslate();\n const { texts } = useAgentConnectionsContext();\n const isShared = visibility === \"AGENT_SPACE\";\n return (\n <StatusBadge\n tone={isShared ? \"brand\" : \"neutral\"}\n icon={isShared ? Users : Lock}\n label={isShared ? texts.sharedVisibilityLabel : t(AGENT_CONNECTION_OWNER_ONLY_LABEL, { context: AGENT_CONNECTION_VISIBILITY_CONTEXT })}\n />\n );\n};\n\n/** The connection's status (connected, expired, paused, error, disconnected, connecting). */\nexport const AgentConnectionStatusBadge = ({ status }: { status: string | null | undefined }) => <StatusBadge value={status} map={AGENT_CONNECTION_STATUS} />;\n\n/** \"5 minutes ago\" of an offsetless UTC backend time; `fallback` without one. */\nexport const AgentConnectionRelativeTime = ({ value, fallback }: { value: string | null | undefined; fallback: string }) => {\n const locale = useFormatLocale();\n const date = parseDddDateTime(value ?? null);\n if (!date) return <>{fallback}</>;\n return (\n <time dateTime={date.toISOString()} title={date.toLocaleString(locale ?? undefined)}>\n {formatRelativeTime(date, undefined, locale ?? undefined)}\n </time>\n );\n};\n\nexport interface CapabilityLevelChipsProps {\n provider: string | null | undefined;\n levels: readonly AgentConnectionCapabilityLevel[];\n /** Table rows: smaller chips. */\n compact?: boolean;\n className?: string;\n}\n\n/**\n * The capabilities of a connection with the agent's level per capability (\"Mail · with approval\"): the product mark\n * (Gmail, Calendar, Contacts, Drive on Google; neutral icons elsewhere), the capability and the level in its tone. The\n * level's meaning is the chip's tooltip.\n */\nexport const CapabilityLevelChips = ({ provider, levels, compact = false, className }: CapabilityLevelChipsProps) => {\n const { t } = useTranslate();\n const levelHelp = useAgentConnectionLevelHelp();\n if (levels.length === 0) return null;\n return (\n <ul className={cn(\"flex flex-wrap gap-1.5\", className)} aria-label={t(\"Levels\", { context: \"agent-connection\" })}>\n {levels.map((entry) => {\n const capabilityLabel = t(AGENT_CONNECTION_CAPABILITY_LABEL[entry.capability], { context: AGENT_CONNECTION_CAPABILITY_CONTEXT });\n const levelLabel = t(AGENT_CONNECTION_LEVEL_LABEL[entry.level], { context: AGENT_CONNECTION_LEVEL_CONTEXT });\n return (\n <li\n key={entry.capability}\n title={`${capabilityLabel} · ${levelLabel}: ${levelHelp(entry.level)}`}\n className={cn(\"inline-flex items-center gap-1.5 rounded-lg border bg-card\", compact ? \"h-7 px-2 text-xs\" : \"h-8 px-2.5 text-[13px]\", entry.level === \"OFF\" && \"opacity-60\")}\n data-testid=\"agent-connection-capability\"\n >\n <CapabilityIcon provider={provider} capability={entry.capability} className={compact ? \"size-3.5\" : \"size-4\"} />\n <span className=\"font-semibold\">{capabilityLabel}</span>\n <span aria-hidden className=\"text-muted-foreground\">\n ·\n </span>\n <span className={cn(\"font-medium\", agentConnectionLevelToneClass(entry.level))}>{levelLabel}</span>\n </li>\n );\n })}\n </ul>\n );\n};\n\n/** A rename opened from outside the name (the \"…\" menu, the merge banner), with an optional suggested name. */\nexport interface AgentConnectionNameEditRequest {\n suggestedName: string | null;\n requestKey: number;\n}\n\nexport interface AgentConnectionNameProps {\n connectionId: number | undefined;\n name: string;\n canRename: boolean;\n editRequest: AgentConnectionNameEditRequest | null;\n onEditRequestHandled: () => void;\n size?: \"md\" | \"sm\";\n}\n\n/**\n * The connection's name, renamed in place: the pencil opens a field with Save / Cancel, Enter saves, Esc cancels. Only\n * the name is sent (`POST connections/{id}/settings`, `displayName`): the route leaves every field it does not get\n * unchanged.\n */\nexport const AgentConnectionName = ({ connectionId, name, canRename, editRequest, onEditRequestHandled, size = \"md\" }: AgentConnectionNameProps) => {\n const { t } = useTranslate();\n const { api, writesAllowed } = useAgentConnectionsContext();\n const [isEditing, setIsEditing] = useState(false);\n const [draft, setDraft] = useState(name);\n const inputRef = useRef<HTMLInputElement>(null);\n const [saveSettings, saveState] = api.useUpdateAgentConnectionSettingsMutation();\n\n useEffect(() => {\n if (editRequest === null) return;\n setDraft(editRequest.suggestedName ?? name);\n setIsEditing(true);\n onEditRequestHandled();\n }, [editRequest, name, onEditRequestHandled]);\n\n useEffect(() => {\n if (!isEditing) return;\n inputRef.current?.focus();\n inputRef.current?.select();\n }, [isEditing]);\n\n const cancel = () => {\n setDraft(name);\n setIsEditing(false);\n };\n\n const save = async () => {\n const trimmed = draft.trim();\n if (connectionId === undefined || !writesAllowed || trimmed === \"\" || trimmed === name) {\n cancel();\n return;\n }\n try {\n await saveSettings({ connectionId, displayName: trimmed }).unwrap();\n notify.success(t(\"Name saved\"));\n setIsEditing(false);\n } catch (error) {\n notify.submitError(toFormSubmitError(error, t(\"The name could not be saved\")));\n }\n };\n\n if (isEditing) {\n return (\n <form\n className=\"flex min-w-0 flex-wrap items-center gap-2\"\n onSubmit={(event) => {\n event.preventDefault();\n event.stopPropagation();\n void save();\n }}\n >\n <Input\n ref={inputRef}\n value={draft}\n onChange={(event) => setDraft(event.target.value)}\n onKeyDown={(event) => {\n if (event.key === \"Escape\") {\n event.stopPropagation();\n cancel();\n }\n }}\n maxLength={100}\n aria-label={t(\"Name\", { context: \"agent-connection\" })}\n className={cn(\"min-w-0 flex-1\", size === \"md\" ? \"h-9 max-w-80\" : \"h-8 max-w-64\")}\n />\n <Button type=\"submit\" size=\"sm\" disabled={!writesAllowed || saveState.isLoading}>\n {t(\"Save\")}\n </Button>\n <Button type=\"button\" size=\"sm\" variant=\"ghost\" onClick={cancel} disabled={saveState.isLoading}>\n {t(\"Cancel\")}\n </Button>\n </form>\n );\n }\n\n return (\n <div className=\"flex min-w-0 items-center gap-1\">\n <span className={cn(\"truncate font-semibold\", size === \"md\" ? \"text-base\" : \"text-sm\")}>{name}</span>\n {canRename && (\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon-sm\"\n className=\"size-7 shrink-0 text-muted-foreground\"\n onClick={() => {\n setDraft(name);\n setIsEditing(true);\n }}\n disabled={!writesAllowed}\n aria-label={t(\"Rename %name%\", { replacements: { name } })}\n >\n <Pencil className=\"size-3.5\" />\n </Button>\n )}\n </div>\n );\n};\n\nexport interface AgentConnectionActionHandlers {\n onChangeLevels: () => void;\n onChangeSharing: () => void;\n onRename: () => void;\n /** Left out where the connection cannot be renewed here (only an OAuth provider connects again from the browser). */\n onReconnect?: () => void;\n /** Left out where the connection carries no drive (no capability FILES) or the host has no drive routes. */\n onOpenDrives?: () => void;\n onDisconnect: () => void;\n}\n\ninterface AgentConnectionActionsMenuProps extends AgentConnectionActionHandlers {\n name: string;\n}\n\n/**\n * The actions of one connection: change levels, sharing, drives and folders, rename, reconnect, and disconnect last\n * (destructive, confirmed). One ghost \"…\" button on the tile and in the table row.\n */\nexport const AgentConnectionActionsMenu = ({ name, onChangeLevels, onChangeSharing, onRename, onReconnect, onOpenDrives, onDisconnect }: AgentConnectionActionsMenuProps) => {\n const { t } = useTranslate();\n const { writesAllowed } = useAgentConnectionsContext();\n return (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button variant=\"ghost\" size=\"icon-sm\" aria-label={t(\"Actions for %name%\", { replacements: { name } })} data-testid=\"agent-connection-actions\">\n <MoreHorizontal />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\" className=\"min-w-56\">\n <DropdownMenuItem onSelect={onChangeLevels} disabled={!writesAllowed}>\n <SlidersHorizontal aria-hidden />\n {t(\"Change levels\")}\n </DropdownMenuItem>\n <DropdownMenuItem onSelect={onChangeSharing} disabled={!writesAllowed}>\n <Users aria-hidden />\n {t(\"Sharing\", { context: \"agent-connection\" })}\n </DropdownMenuItem>\n {onOpenDrives && (\n <DropdownMenuItem onSelect={onOpenDrives}>\n <FolderTree aria-hidden />\n {t(\"Drives and folders\", { context: \"agent-connection\" })}\n </DropdownMenuItem>\n )}\n <DropdownMenuItem onSelect={onRename} disabled={!writesAllowed}>\n <Pencil aria-hidden />\n {t(\"Rename\", { context: \"agent-connection\" })}\n </DropdownMenuItem>\n {onReconnect && (\n <DropdownMenuItem onSelect={onReconnect} disabled={!writesAllowed}>\n <RefreshCw aria-hidden />\n {t(\"Reconnect\")}\n </DropdownMenuItem>\n )}\n <DropdownMenuSeparator />\n <DropdownMenuItem variant=\"destructive\" onSelect={onDisconnect} disabled={!writesAllowed}>\n <Unplug aria-hidden />\n {t(\"Disconnect\", { context: \"agent-connection\" })}\n </DropdownMenuItem>\n </DropdownMenuContent>\n </DropdownMenu>\n );\n};\n\n/** The providers the add menu can offer: an OAuth account (Google), a mailbox (IMAP/SMTP), the agent's Slack bot. */\nexport type AgentConnectProvider = \"GOOGLE\" | \"IMAP\" | \"SLACK\";\n\nexport const AGENT_CONNECT_PROVIDERS: readonly AgentConnectProvider[] = [\"GOOGLE\", \"IMAP\", \"SLACK\"];\n\ninterface AddConnectionMenuProps {\n /** The providers the host offers here, in this order. */\n providers: readonly AgentConnectProvider[];\n /** The providers the server can connect here (`connectableProviders`). */\n connectableProviders: readonly string[];\n disabled: boolean;\n onChoose: (provider: AgentConnectProvider) => void;\n /** `sm` under the empty state and in a panel, default in a page header. */\n size?: \"sm\" | \"default\";\n}\n\n/**\n * \"Add connection\": the one primary action, a menu of the providers with their marks. Google and IMAP/SMTP connect an\n * account of the person; Slack is the agent's own bot (only with the system right). A provider the server cannot\n * connect here is shown but off.\n */\nexport const AddConnectionMenu = ({ providers, connectableProviders, disabled, onChoose, size = \"default\" }: AddConnectionMenuProps) => {\n const { t } = useTranslate();\n const { viewer, texts } = useAgentConnectionsContext();\n const entries = providers.flatMap((provider): { provider: AgentConnectProvider; label: string; description: string; available: boolean }[] => {\n if (provider === \"GOOGLE\") return [{ provider, label: \"Google\", description: t(\"Gmail, Calendar, Contacts, Drive\"), available: connectableProviders.includes(\"GOOGLE\") }];\n if (provider === \"IMAP\") return [{ provider, label: \"IMAP / SMTP\", description: t(\"Any other mailbox\"), available: connectableProviders.includes(\"IMAP\") }];\n return viewer.mayManageSystemConnections ? [{ provider, label: \"Slack\", description: t(\"%agentName%’s bot in your Slack\", { replacements: { agentName: texts.agentName } }), available: true }] : [];\n });\n\n return (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button size={size} disabled={disabled} data-testid=\"agent-connection-add\">\n <Plus aria-hidden />\n {t(\"Add connection\")}\n <ChevronDown aria-hidden className=\"opacity-70\" />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\" className=\"w-72\">\n <DropdownMenuLabel className=\"text-xs text-muted-foreground\">{t(\"New connection\")}</DropdownMenuLabel>\n {entries.map((entry) => (\n <DropdownMenuItem key={entry.provider} disabled={!entry.available} onSelect={() => onChoose(entry.provider)} className=\"gap-3 py-2\">\n <ProviderMark provider={entry.provider} size=\"sm\" />\n <span className=\"min-w-0 flex-1\">\n <span className=\"block font-semibold\">{entry.label}</span>\n <span className=\"block truncate text-xs text-muted-foreground\">{entry.available ? entry.description : t(\"Not set up on this server\")}</span>\n </span>\n </DropdownMenuItem>\n ))}\n </DropdownMenuContent>\n </DropdownMenu>\n );\n};\n","import { wireElementsOf } from \"../wire/admin-wire\";\nimport { m } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { parseAgentConnectionLevels } from \"./agent-connection-format\";\nimport type {\n AgentConnectionDriveItemsSearchArg,\n AgentConnectionDriveRoot,\n AgentConnectionDriveRootRuleKind,\n AgentConnectionDriveRootRuleResolution,\n AgentConnectionDriveRootsResponse,\n AgentConnectionLevel,\n AgentConnectionSummary,\n AgentConnectionVisibility,\n} from \"./agent-connections-types\";\n\n/**\n * What the agent may see of a drive connection (the dialog \"What may the agent see?\") and the extended search of the\n * picker, pure. The one typed place of both server capabilities: the rule kinds a root may be added as\n * (`supportedRootKinds` of every drive answer) and the filters the item search applies (`supportedSearchFilters`). A\n * capability the server does not list is shown off (\"comes soon\") and never sent.\n */\n\n// ---- rule roots ----------------------------------------------------------------------------------------------------\n\n/** The rule kinds, in the order the dialog offers them (`AdminAgentConnectionDriveRootPostRequestDto::RULE_ROOT_KINDS`). */\nexport const AGENT_CONNECTION_DRIVE_RULE_KINDS: readonly AgentConnectionDriveRootRuleKind[] = [\"ALL_SHARED_DRIVES\", \"WHOLE_ACCOUNT\"];\n\nexport const isAgentConnectionDriveRuleKind = (value: string | null | undefined): value is AgentConnectionDriveRootRuleKind => AGENT_CONNECTION_DRIVE_RULE_KINDS.some((kind) => kind === value);\n\n/** Whether a root is a rule (no item) rather than one folder, shared drive or file. */\nexport const isAgentConnectionDriveRuleRoot = (root: Pick<AgentConnectionDriveRoot, \"rootKind\">): boolean => isAgentConnectionDriveRuleKind(root.rootKind);\n\n/** The name of a rule root (the server's `itemName` of a rule is the same key). */\nexport const AGENT_CONNECTION_DRIVE_RULE_LABEL: Readonly<Record<AgentConnectionDriveRootRuleKind, string>> = {\n ALL_SHARED_DRIVES: m(\"All shared drives\", {\n context: \"agent-connection-drive\",\n }),\n WHOLE_ACCOUNT: m(\"Whole account\", { context: \"agent-connection-drive\" }),\n};\n\n/** The rule kinds a drive answer says the connection supports; absent = none. */\nexport const supportedAgentConnectionDriveRuleKindsOf = (response: Pick<AgentConnectionDriveRootsResponse, \"supportedRootKinds\"> | null | undefined): AgentConnectionDriveRootRuleKind[] =>\n AGENT_CONNECTION_DRIVE_RULE_KINDS.filter((kind) => (response?.supportedRootKinds ?? []).includes(kind));\n\n/** What an active rule root covers now (`driveRootRuleResolutions` of the drive answer), `null` without an answer for it. */\nexport const agentConnectionDriveRuleResolutionOf = (\n response: Pick<AgentConnectionDriveRootsResponse, \"driveRootRuleResolutions\"> | null | undefined,\n root: Pick<AgentConnectionDriveRoot, \"id\">,\n): AgentConnectionDriveRootRuleResolution | null => {\n const driveRootId = typeof root.id === \"string\" ? Number(root.id) : root.id;\n return wireElementsOf(response?.driveRootRuleResolutions).find((resolution) => Number(resolution.agentConnectionDriveRootId) === driveRootId) ?? null;\n};\n\n/** The active rule root of a kind, `null` without one (one active rule per kind and connection). */\nexport const findActiveAgentConnectionDriveRuleRoot = <TRoot extends Pick<AgentConnectionDriveRoot, \"rootKind\" | \"status\">>(\n roots: readonly TRoot[],\n kind: AgentConnectionDriveRootRuleKind,\n): TRoot | null => roots.find((root) => root.rootKind === kind && root.status === \"ACTIVE\") ?? null;\n\n// ---- the dialog \"What may the agent see?\" -------------------------------------------------------------------------\n\n/** The choices of the dialog: certain areas (picked next), a rule, or nothing now. */\nexport type AgentConnectionDriveScopeChoice = \"AREAS\" | AgentConnectionDriveRootRuleKind | \"LATER\";\n\nexport const AGENT_CONNECTION_DRIVE_SCOPE_CHOICES: readonly AgentConnectionDriveScopeChoice[] = [\"AREAS\", \"ALL_SHARED_DRIVES\", \"WHOLE_ACCOUNT\", \"LATER\"];\n\n/** The levels of the capability Files the dialog offers, lowest first (`AgentConnectionPermission::LEVELS` of a drive). */\nexport const AGENT_CONNECTION_DRIVE_FILES_LEVELS: readonly AgentConnectionLevel[] = [\"OFF\", \"READ\", \"WRITE_WITH_APPROVAL\", \"DELETE_WITH_APPROVAL\"];\n\n/** The choice the dialog opens with: the active rule (the whole account first), else certain areas (the default). */\nexport const agentConnectionDriveScopeChoiceOf = (roots: readonly Pick<AgentConnectionDriveRoot, \"rootKind\" | \"status\">[]): AgentConnectionDriveScopeChoice =>\n findActiveAgentConnectionDriveRuleRoot(roots, \"WHOLE_ACCOUNT\") !== null\n ? \"WHOLE_ACCOUNT\"\n : findActiveAgentConnectionDriveRuleRoot(roots, \"ALL_SHARED_DRIVES\") !== null\n ? \"ALL_SHARED_DRIVES\"\n : \"AREAS\";\n\n/**\n * Why a choice cannot be taken, `null` when it can: `comingSoon` = the server does not support the rule kind for this\n * connection yet; `onlyMe` = the whole account only while the connection is visible to its owner alone (never a\n * system connection of the agent).\n */\nexport type AgentConnectionDriveScopeBlocker = \"comingSoon\" | \"onlyMe\";\n\nexport const agentConnectionDriveScopeBlockerOf = (\n choice: AgentConnectionDriveScopeChoice,\n facts: {\n supportedRuleKinds: readonly AgentConnectionDriveRootRuleKind[];\n visibility: AgentConnectionVisibility;\n isAgentOwned: boolean;\n },\n): AgentConnectionDriveScopeBlocker | null => {\n if (choice === \"AREAS\" || choice === \"LATER\") return null;\n if (!facts.supportedRuleKinds.includes(choice)) return \"comingSoon\";\n if (choice === \"WHOLE_ACCOUNT\" && (facts.isAgentOwned || facts.visibility !== \"OWNER_ONLY\")) return \"onlyMe\";\n return null;\n};\n\n/** What saving the dialog does, in this order (removals, visibility, level, rule, picker); a step is left out when nothing changes. */\nexport interface AgentConnectionDriveScopePlan {\n /** `POST settings` with the new visibility. */\n visibility: AgentConnectionVisibility | null;\n /** `POST level` (or the provider's consent, when the grant does not cover it) for Files. */\n filesLevel: AgentConnectionLevel | null;\n /**\n * `POST driveRoots/remove` with these rule kinds, first of all: the active rules the choice ends (certain areas end\n * both, everything ends the narrower all shared drives, all shared drives ends everything)\n */\n removeRuleKinds: AgentConnectionDriveRootRuleKind[];\n /** `POST driveRoots` with this rule kind and no item (`releaseWay` as the connection's own roots). */\n ruleKind: AgentConnectionDriveRootRuleKind | null;\n /** Open the picker of \"Drives and folders\" afterwards. */\n pickAreas: boolean;\n}\n\nexport const planAgentConnectionDriveScope = (input: {\n choice: AgentConnectionDriveScopeChoice;\n visibility: AgentConnectionVisibility;\n savedVisibility: AgentConnectionVisibility;\n filesLevel: AgentConnectionLevel;\n savedFilesLevel: AgentConnectionLevel;\n roots: readonly Pick<AgentConnectionDriveRoot, \"rootKind\" | \"status\">[];\n}): AgentConnectionDriveScopePlan => ({\n removeRuleKinds: input.choice === \"LATER\" ? [] : AGENT_CONNECTION_DRIVE_RULE_KINDS.filter((kind) => kind !== input.choice && findActiveAgentConnectionDriveRuleRoot(input.roots, kind) !== null),\n visibility: input.visibility !== input.savedVisibility ? input.visibility : null,\n filesLevel: input.filesLevel !== input.savedFilesLevel ? input.filesLevel : null,\n ruleKind: isAgentConnectionDriveRuleKind(input.choice) && findActiveAgentConnectionDriveRuleRoot(input.roots, input.choice) === null ? input.choice : null,\n pickAreas: input.choice === \"AREAS\" && input.filesLevel !== \"OFF\",\n});\n\n/** Whether the dialog opens by itself after a connect: a new connection of a drive provider that lists Files. */\nexport const isAgentConnectionDriveScopeAsked = (connection: Pick<AgentConnectionSummary, \"levels\" | \"status\"> | null | undefined): boolean =>\n connection != null && connection.status !== \"REVOKED\" && parseAgentConnectionLevels(connection.levels).some((entry) => entry.capability === \"FILES\");\n\n/** The saved level of Files of a connection; OFF when it lists none. */\nexport const agentConnectionFilesLevelOf = (connection: Pick<AgentConnectionSummary, \"levels\"> | null | undefined): AgentConnectionLevel =>\n parseAgentConnectionLevels(connection?.levels).find((entry) => entry.capability === \"FILES\")?.level ?? \"OFF\";\n\n// ---- the extended search of the picker ----------------------------------------------------------------------------\n\n/** The filters of the item search (`AdminAgentConnectionDriveItemsSearchGetRequestDto::FILTERS`). */\nexport type AgentConnectionDriveSearchFilterName = \"modifiedFrom\" | \"modifiedTo\" | \"createdFrom\" | \"createdTo\" | \"types\" | \"minSizeBytes\" | \"maxSizeBytes\" | \"inFolderId\";\n\nexport const AGENT_CONNECTION_DRIVE_SEARCH_FILTER_NAMES: readonly AgentConnectionDriveSearchFilterName[] = [\n \"modifiedFrom\",\n \"modifiedTo\",\n \"createdFrom\",\n \"createdTo\",\n \"types\",\n \"minSizeBytes\",\n \"maxSizeBytes\",\n \"inFolderId\",\n];\n\n/** The kinds `types` names (`AdminAgentConnectionDriveItemsSearchGetRequestDto::TYPES`). */\nexport type AgentConnectionDriveSearchType = \"FOLDER\" | \"SHARED_DRIVE\" | \"PDF\" | \"DOCUMENT\" | \"SPREADSHEET\" | \"PRESENTATION\" | \"IMAGE\" | \"TEXT\" | \"GOOGLE_DOC\" | \"GOOGLE_SHEET\" | \"GOOGLE_SLIDES\";\n\nexport const AGENT_CONNECTION_DRIVE_SEARCH_TYPES: readonly AgentConnectionDriveSearchType[] = [\n \"FOLDER\",\n \"SHARED_DRIVE\",\n \"PDF\",\n \"DOCUMENT\",\n \"SPREADSHEET\",\n \"PRESENTATION\",\n \"IMAGE\",\n \"TEXT\",\n \"GOOGLE_DOC\",\n \"GOOGLE_SHEET\",\n \"GOOGLE_SLIDES\",\n];\n\n/** The kinds the picker offers: only folders and shared drives become roots there. */\nexport const AGENT_CONNECTION_DRIVE_PICKER_SEARCH_TYPES: readonly AgentConnectionDriveSearchType[] = [\"FOLDER\", \"SHARED_DRIVE\"];\n\nexport const AGENT_CONNECTION_DRIVE_SEARCH_TYPE_LABEL: Readonly<Record<AgentConnectionDriveSearchType, string>> = {\n FOLDER: m(\"Folder\", { context: \"agent-connection-drive\" }),\n SHARED_DRIVE: m(\"Shared drive\", { context: \"agent-connection-drive\" }),\n PDF: m(\"PDF\", { context: \"agent-connection-drive-type\" }),\n DOCUMENT: m(\"Text document\", { context: \"agent-connection-drive-type\" }),\n SPREADSHEET: m(\"Spreadsheet\", { context: \"agent-connection-drive-type\" }),\n PRESENTATION: m(\"Presentation\", { context: \"agent-connection-drive-type\" }),\n IMAGE: m(\"Image\", { context: \"agent-connection-drive-type\" }),\n TEXT: m(\"Plain text\", { context: \"agent-connection-drive-type\" }),\n GOOGLE_DOC: m(\"Google Doc\", { context: \"agent-connection-drive-type\" }),\n GOOGLE_SHEET: m(\"Google Sheet\", { context: \"agent-connection-drive-type\" }),\n GOOGLE_SLIDES: m(\"Google Slides\", { context: \"agent-connection-drive-type\" }),\n};\n\n/** The filter values as the controls hold them: days `YYYY-MM-DD`, sizes in megabytes as typed, `\"\"` = not set. */\nexport interface AgentConnectionDriveSearchFilters {\n modifiedFrom: string;\n modifiedTo: string;\n createdFrom: string;\n createdTo: string;\n types: readonly AgentConnectionDriveSearchType[];\n minSizeMegabytes: string;\n maxSizeMegabytes: string;\n /** The folder or shared drive the search stays below, `null` = everywhere. */\n inFolderId: string | null;\n}\n\nexport const EMPTY_AGENT_CONNECTION_DRIVE_SEARCH_FILTERS: AgentConnectionDriveSearchFilters = {\n modifiedFrom: \"\",\n modifiedTo: \"\",\n createdFrom: \"\",\n createdTo: \"\",\n types: [],\n minSizeMegabytes: \"\",\n maxSizeMegabytes: \"\",\n inFolderId: null,\n};\n\n/** The groups of controls; each is on when the server applies at least one of its filters. */\nexport type AgentConnectionDriveSearchFilterField = \"modified\" | \"created\" | \"types\" | \"size\" | \"location\";\n\nconst FILTERS_OF_FIELD: Readonly<Record<AgentConnectionDriveSearchFilterField, readonly AgentConnectionDriveSearchFilterName[]>> = {\n modified: [\"modifiedFrom\", \"modifiedTo\"],\n created: [\"createdFrom\", \"createdTo\"],\n types: [\"types\"],\n size: [\"minSizeBytes\", \"maxSizeBytes\"],\n location: [\"inFolderId\"],\n};\n\nexport const AGENT_CONNECTION_DRIVE_SEARCH_FILTER_FIELDS: readonly AgentConnectionDriveSearchFilterField[] = [\"modified\", \"created\", \"types\", \"size\", \"location\"];\n\n/** The filters a drive answer says the search applies; absent = none. */\nexport const supportedAgentConnectionDriveSearchFiltersOf = (response: Pick<AgentConnectionDriveRootsResponse, \"supportedSearchFilters\"> | null | undefined): AgentConnectionDriveSearchFilterName[] =>\n AGENT_CONNECTION_DRIVE_SEARCH_FILTER_NAMES.filter((name) => (response?.supportedSearchFilters ?? []).includes(name));\n\n/** The controls of the picker's search: its items are folders and shared drives, which have no size. */\nexport const AGENT_CONNECTION_DRIVE_PICKER_SEARCH_FILTER_FIELDS: readonly AgentConnectionDriveSearchFilterField[] = [\"modified\", \"created\", \"types\", \"location\"];\n\n/**\n * Whether the search leaves shared drives out (`AgentConnectionDriveSearchFilters::allowsSharedDrives()`): a day range, a\n * place or a size, since the provider answers neither dates nor a parent folder for a shared drive.\n */\nexport const isAgentConnectionDriveSearchLeavingSharedDrivesOut = (args: Pick<AgentConnectionDriveItemsSearchArg, AgentConnectionDriveSearchFilterName>): boolean =>\n args.modifiedFrom != null || args.modifiedTo != null || args.createdFrom != null || args.createdTo != null || args.inFolderId != null || args.minSizeBytes != null || args.maxSizeBytes != null;\n\nexport const isAgentConnectionDriveSearchFilterFieldSupported = (field: AgentConnectionDriveSearchFilterField, supported: readonly AgentConnectionDriveSearchFilterName[]): boolean =>\n FILTERS_OF_FIELD[field].some((name) => supported.includes(name));\n\nconst BYTES_PER_MEGABYTE = 1024 * 1024;\n\n/** Megabytes as typed (a comma counts as the decimal point) in bytes, `null` for nothing or no number of zero or more. */\nexport const agentConnectionDriveSizeBytesOf = (megabytes: string): number | null => {\n const text = megabytes.trim().replace(\",\", \".\");\n if (text === \"\" || !/^\\d+(\\.\\d+)?$/.test(text)) return null;\n return Math.round(Number(text) * BYTES_PER_MEGABYTE);\n};\n\nconst DAY = /^\\d{4}-\\d{2}-\\d{2}$/;\nconst dayOrNull = (value: string): string | null => (DAY.test(value) ? value : null);\n\n/**\n * The request fields of the filters: only the ones the server applies and that hold a value (the route refuses the\n * others); the kinds as the given list in their fixed order.\n */\nexport const agentConnectionDriveSearchFilterArgsOf = (\n filters: AgentConnectionDriveSearchFilters,\n supported: readonly AgentConnectionDriveSearchFilterName[],\n): Pick<AgentConnectionDriveItemsSearchArg, AgentConnectionDriveSearchFilterName> => {\n const values: Record<AgentConnectionDriveSearchFilterName, string | number | readonly string[] | null> = {\n modifiedFrom: dayOrNull(filters.modifiedFrom),\n modifiedTo: dayOrNull(filters.modifiedTo),\n createdFrom: dayOrNull(filters.createdFrom),\n createdTo: dayOrNull(filters.createdTo),\n types: filters.types.length > 0 ? AGENT_CONNECTION_DRIVE_SEARCH_TYPES.filter((type) => filters.types.includes(type)) : null,\n minSizeBytes: agentConnectionDriveSizeBytesOf(filters.minSizeMegabytes),\n maxSizeBytes: agentConnectionDriveSizeBytesOf(filters.maxSizeMegabytes),\n inFolderId: filters.inFolderId !== null && filters.inFolderId !== \"\" ? filters.inFolderId : null,\n };\n const args: Pick<AgentConnectionDriveItemsSearchArg, AgentConnectionDriveSearchFilterName> = {};\n for (const name of AGENT_CONNECTION_DRIVE_SEARCH_FILTER_NAMES) {\n const value = values[name];\n if (value === null || !supported.includes(name)) continue;\n Object.assign(args, { [name]: value });\n }\n return args;\n};\n\n/** How many groups of controls hold a value the search sends. */\nexport const countActiveAgentConnectionDriveSearchFilters = (filters: AgentConnectionDriveSearchFilters, supported: readonly AgentConnectionDriveSearchFilterName[]): number => {\n const args = agentConnectionDriveSearchFilterArgsOf(filters, supported);\n return AGENT_CONNECTION_DRIVE_SEARCH_FILTER_FIELDS.filter((field) => FILTERS_OF_FIELD[field].some((name) => args[name] != null)).length;\n};\n\n/** A range whose start lies after its end (days compare as text; sizes as numbers): the control says so, the search still runs. */\nexport const isAgentConnectionDriveSearchRangeReversed = (from: string, to: string, kind: \"day\" | \"size\"): boolean => {\n if (kind === \"day\") return dayOrNull(from) !== null && dayOrNull(to) !== null && from > to;\n const fromBytes = agentConnectionDriveSizeBytesOf(from);\n const toBytes = agentConnectionDriveSizeBytesOf(to);\n return fromBytes !== null && toBytes !== null && fromBytes > toBytes;\n};\n","import { useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { StatusCallout, StatusCalloutAction } from \"@mgamadeus/ddd-admin-ui/page\";\nimport { Button, Card, CardContent, cn } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { FolderTree, RefreshCw } from \"lucide-react\";\nimport { agentConnectionNameOf, agentConnectionProviderName, parseAgentConnectionLevels } from \"./agent-connection-format\";\nimport { useAgentConnectionsContext } from \"./agent-connections-context\";\nimport type { AgentConnectionSummary } from \"./agent-connections-types\";\nimport { ProviderMark } from \"./connection-logos\";\nimport {\n type AgentConnectionActionHandlers,\n AgentConnectionActionsMenu,\n AgentConnectionName,\n type AgentConnectionNameEditRequest,\n AgentConnectionRelativeTime,\n AgentConnectionStatusBadge,\n AgentConnectionVisibilityBadge,\n CapabilityLevelChips,\n} from \"./connection-parts\";\n\nexport interface AgentConnectionCardProps {\n connection: AgentConnectionSummary;\n /** The signed-in account may change it (its owner, or a holder of the system right for a connection of the agent). */\n canManage: boolean;\n handlers: AgentConnectionActionHandlers;\n nameEditRequest: AgentConnectionNameEditRequest | null;\n onNameEditRequestHandled: () => void;\n /** The grid's row key, set on the tile's root (`data-row-key`). */\n rowKey?: string;\n}\n\n/** The secondary line: the account, the provider and, for the agent's own connections, that note. */\nexport const useAgentConnectionSubline = (connection: AgentConnectionSummary): string => {\n const { t } = useTranslate();\n const { texts } = useAgentConnectionsContext();\n return [\n connection.externalAddress,\n agentConnectionProviderName(connection.provider),\n connection.ownership === \"AGENT_OWNED\" ? t(\"%agentName%’s own connection\", { replacements: { agentName: texts.agentName } }) : null,\n ]\n .filter(Boolean)\n .join(\" · \");\n};\n\n/**\n * One connection as a tile: the provider's mark, the name (renamed in place), the account, visibility and status, the\n * level per capability with the product marks, what needs doing (expired access, a failing login), the drives and\n * folders of a drive connection, when it was connected and last used; the actions in the \"…\" menu. Expired and failing\n * connections get a coloured edge.\n */\nexport const AgentConnectionCard = ({ connection, canManage, handlers, nameEditRequest, onNameEditRequestHandled, rowKey }: AgentConnectionCardProps) => {\n const { t } = useTranslate();\n const { writesAllowed, texts } = useAgentConnectionsContext();\n const levels = parseAgentConnectionLevels(connection.levels);\n const subline = useAgentConnectionSubline(connection);\n const isRevoked = connection.status === \"REVOKED\";\n const name = agentConnectionNameOf(connection);\n\n return (\n <Card\n className={cn(\n \"h-full gap-0 py-0 transition-shadow hover:shadow-md\",\n connection.status === \"EXPIRED\" && \"border-l-4 border-l-warning\",\n connection.status === \"ERROR\" && \"border-l-4 border-l-destructive\",\n isRevoked && \"opacity-70\",\n )}\n data-connection-id={connection.connectionId}\n data-row-key={rowKey}\n >\n <CardContent className=\"flex flex-1 flex-col gap-4 p-4 sm:p-5\">\n <div className=\"flex items-start gap-3\">\n <ProviderMark provider={connection.provider} />\n <div className=\"min-w-0 flex-1\">\n <AgentConnectionName connectionId={connection.connectionId} name={name} canRename={canManage && !isRevoked} editRequest={nameEditRequest} onEditRequestHandled={onNameEditRequestHandled} />\n <p className=\"truncate text-sm text-muted-foreground\" title={subline}>\n {subline}\n </p>\n </div>\n {canManage && !isRevoked && <AgentConnectionActionsMenu name={name} {...handlers} />}\n </div>\n\n <div className=\"flex flex-wrap items-center gap-1.5\">\n <AgentConnectionVisibilityBadge visibility={connection.visibility} />\n <AgentConnectionStatusBadge status={connection.status} />\n </div>\n\n {!isRevoked && <CapabilityLevelChips provider={connection.provider} levels={levels} />}\n\n {connection.status === \"EXPIRED\" && (\n <StatusCallout\n size=\"compact\"\n tone=\"warning\"\n title={t(\"Access expired\")}\n description={t(\"%agentName% can use this account again once you reconnect it.\", { replacements: { agentName: texts.agentName } })}\n actions={\n handlers.onReconnect && canManage ? (\n <StatusCalloutAction onClick={handlers.onReconnect} disabled={!writesAllowed}>\n <RefreshCw aria-hidden />\n {t(\"Reconnect\")}\n </StatusCalloutAction>\n ) : undefined\n }\n />\n )}\n {connection.status === \"ERROR\" && connection.lastErrorText && (\n <StatusCallout\n size=\"compact\"\n tone=\"destructive\"\n title={t(\"Last error\")}\n description={connection.lastErrorText}\n actions={\n handlers.onReconnect && canManage ? (\n <StatusCalloutAction onClick={handlers.onReconnect} disabled={!writesAllowed}>\n {t(\"Renew access\")}\n </StatusCalloutAction>\n ) : undefined\n }\n />\n )}\n\n {handlers.onOpenDrives && !isRevoked && (\n <div>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" onClick={handlers.onOpenDrives} data-testid=\"agent-connection-drives\">\n <FolderTree aria-hidden />\n {t(\"Drives and folders\", { context: \"agent-connection\" })}\n </Button>\n </div>\n )}\n\n <dl className=\"mt-auto flex flex-wrap gap-x-5 gap-y-1 border-t pt-3 text-xs text-muted-foreground\">\n <div className=\"flex gap-1\">\n <dt>{t(\"Connected\", { context: \"agent-connection-date\" })}</dt>\n <dd className=\"font-medium text-foreground\">\n <AgentConnectionRelativeTime value={connection.connectedAt} fallback=\"—\" />\n </dd>\n </div>\n <div className=\"flex gap-1\">\n <dt>{t(\"Last used\")}</dt>\n <dd className=\"font-medium text-foreground\">\n <AgentConnectionRelativeTime value={connection.lastUsedAt} fallback={t(\"never\", { context: \"agent-connection-last-used\" })} />\n </dd>\n </div>\n </dl>\n </CardContent>\n </Card>\n );\n};\n","import { useCallback, useState } from \"react\";\nimport { type PendingAgentConnect, serializePendingAgentConnect } from \"./agent-connection-oauth\";\nimport { useAgentConnectionsContext } from \"./agent-connections-context\";\nimport type { AgentConnectionCapability, AgentConnectionCapabilityLevel, AgentConnectionVisibility } from \"./agent-connections-types\";\n\nexport interface StartAgentConnectArgs {\n /** The provider in upper case (`GOOGLE`). */\n provider: string;\n displayName: string;\n /** The capabilities to ask the provider for; empty = all the adapter offers. */\n capabilities: readonly AgentConnectionCapability[];\n /** `AGENT_SPACE`: the server releases the connection when the consent completes. */\n visibility: AgentConnectionVisibility;\n /** The space to share with; `null` = the server's only shareable space. */\n targetAgentSpaceId?: number | null;\n /** The connection a \"Reconnect\" renews (the consent is then merged into it by the server). */\n reconnectOf?: number | null;\n}\n\n/**\n * Starts a provider's consent (`POST oauth/{provider}/start`): the answer sets the HttpOnly nonce cookie on this\n * origin and holds the consent URL, which this browser then opens (`AgentConnectionsOAuthAdapter.openAuthorizationUrl`,\n * default `window.location.assign`). What the way back needs is stored first (`PendingAgentConnect`, with the panel's\n * surface). `isPending` stays true while the browser leaves.\n */\nexport const useAgentConnect = () => {\n const { api, oauth, surface } = useAgentConnectionsContext();\n const [startOAuth, startState] = api.useStartAgentConnectionOAuthMutation();\n const [isLeaving, setIsLeaving] = useState(false);\n\n const leave = useCallback(\n (pending: Omit<PendingAgentConnect, \"surface\">, authorizationUrl: string) => {\n oauth?.writePending(serializePendingAgentConnect({ ...pending, surface }));\n setIsLeaving(true);\n if (oauth?.openAuthorizationUrl) oauth.openAuthorizationUrl(authorizationUrl);\n else window.location.assign(authorizationUrl);\n },\n [oauth, surface],\n );\n\n const start = useCallback(\n async ({ provider, displayName, capabilities, visibility, targetAgentSpaceId = null, reconnectOf = null }: StartAgentConnectArgs) => {\n const response = await startOAuth({\n provider: provider.toLowerCase(),\n displayName: displayName.trim() || null,\n ...(capabilities.length > 0 ? { capabilities: [...capabilities] } : {}),\n visibility,\n ...(visibility === \"AGENT_SPACE\" && targetAgentSpaceId !== null ? { targetAgentSpaceId } : {}),\n }).unwrap();\n leave({ startedConnectionId: response.connectionId, typedName: displayName.trim(), reconnectOf, extendOf: null }, response.authorizationUrl);\n },\n [startOAuth, leave],\n );\n\n /**\n * Asks the provider for the scopes of higher levels of an existing connection (incremental consent): the callback\n * sets `requestedLevels` once their scopes are granted and returns with `?connected=<connectionId>`, or with\n * `?connectError=` when a permission was unticked.\n */\n const extend = useCallback(\n async (provider: string, connectionId: number, requestedLevels: readonly AgentConnectionCapabilityLevel[]) => {\n const response = await startOAuth({\n provider: provider.toLowerCase(),\n connectionId,\n requestedLevels: requestedLevels.map((entry) => ({ capability: entry.capability, level: entry.level })),\n }).unwrap();\n leave({ startedConnectionId: response.connectionId, typedName: \"\", reconnectOf: null, extendOf: connectionId }, response.authorizationUrl);\n },\n [startOAuth, leave],\n );\n\n return { start, extend, isPending: startState.isLoading || isLeaving };\n};\n","import { FormDialog, FormErrors, FormFieldFrame } from \"@mgamadeus/ddd-admin-ui/form\";\nimport { useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { type FormSubmitError, notify, toFormSubmitError } from \"@mgamadeus/ddd-admin-ui/logic\";\nimport { StatusCallout } from \"@mgamadeus/ddd-admin-ui/page\";\nimport { cn, SegmentedControl, Select, SelectContent, SelectItem, SelectTrigger, SelectValue, Skeleton } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { CalendarClock, FolderTree, Globe, HardDrive, ShieldAlert, type LucideIcon } from \"lucide-react\";\nimport { useEffect, useId, useMemo, useState } from \"react\";\nimport { wireElementsOf } from \"../wire/admin-wire\";\nimport {\n AGENT_CONNECTION_DRIVE_FILES_LEVELS,\n AGENT_CONNECTION_DRIVE_RULE_LABEL,\n AGENT_CONNECTION_DRIVE_SCOPE_CHOICES,\n type AgentConnectionDriveScopeBlocker,\n type AgentConnectionDriveScopeChoice,\n agentConnectionDriveRuleResolutionOf,\n agentConnectionDriveScopeBlockerOf,\n agentConnectionDriveScopeChoiceOf,\n agentConnectionFilesLevelOf,\n findActiveAgentConnectionDriveRuleRoot,\n planAgentConnectionDriveScope,\n supportedAgentConnectionDriveRuleKindsOf,\n} from \"./agent-connection-drive-scope\";\nimport { AGENT_CONNECTION_DRIVE_CONTEXT, AGENT_CONNECTION_DRIVE_ITEMS_SECTION_LABEL, AGENT_CONNECTION_DRIVE_ITEMS_SECTIONS, isAgentConnectionDriveRootEnded } from \"./agent-connection-drives\";\nimport {\n AGENT_CONNECTION_LEVEL_CONTEXT,\n AGENT_CONNECTION_LEVEL_LABEL,\n agentConnectionLevelRank,\n agentConnectionNameOf,\n agentConnectionVisibilityOf,\n canManageAgentConnection,\n isAgentConnectionConsentRequiredMessage,\n isAgentConnectionLevel,\n} from \"./agent-connection-format\";\nimport { useAgentConnectionLevelHelp, useAgentConnectionsContext, useAgentConnectionVisibilityOptions } from \"./agent-connections-context\";\nimport type { AgentConnectionLevel, AgentConnectionSummary, AgentConnectionVisibility } from \"./agent-connections-types\";\nimport { useAgentConnect } from \"./use-agent-connect\";\n\nconst CHOICE_ICON: Readonly<Record<AgentConnectionDriveScopeChoice, LucideIcon>> = {\n AREAS: FolderTree,\n ALL_SHARED_DRIVES: HardDrive,\n WHOLE_ACCOUNT: Globe,\n LATER: CalendarClock,\n};\n\nexport interface AgentConnectionDriveScopeDialogProps {\n /** The drive connection the dialog decides for, `null` = closed. */\n connection: AgentConnectionSummary | null;\n /** \"Certain areas\" was saved: the host opens the picker of \"Drives and folders\" of this connection. */\n onPickAreas: (connectionId: number) => void;\n onClose: () => void;\n}\n\n/**\n * \"What may the agent see?\" of one drive connection, right after it was connected and again from \"Drives and\n * folders\": certain areas (the default; picked next in the three sections of the picker), all shared drives (a rule:\n * new ones automatically), everything (the account's own drive and all shared drives; only with a warning and only\n * while the connection is visible to its owner alone), or later; with the visibility and the level of Files in the\n * same form. A rule the server does not support for the connection (`supportedRootKinds`) is shown off as \"comes\n * soon\". Saving runs in this order: the visibility (`POST settings`), the level (`POST level`; a level the grant does\n * not cover goes through the provider's consent last, the browser leaves), the rule (`POST driveRoots` with\n * `rootKind`), then the picker opens for certain areas. Only whoever manages the connection changes anything (as in\n * the drawer); without write access the form is read only.\n */\nexport const AgentConnectionDriveScopeDialog = ({ connection, onPickAreas, onClose }: AgentConnectionDriveScopeDialogProps) => {\n const { t } = useTranslate();\n const { api, writesAllowed, viewer, sharedAgentSpaceId, texts } = useAgentConnectionsContext();\n const visibilityOptions = useAgentConnectionVisibilityOptions();\n const levelHelp = useAgentConnectionLevelHelp();\n const connect = useAgentConnect();\n const groupName = useId();\n const connectionId = connection?.connectionId;\n const isOpen = connection !== null;\n const rootsQuery = api.useAgentConnectionDriveRootsQuery({ connectionId: connectionId ?? 0 }, { skip: connectionId === undefined });\n const isGoogle = connection?.provider === \"GOOGLE\";\n const { currentData: detail } = api.useAgentConnectionQuery({ connectionId: connectionId ?? 0 }, { skip: connectionId === undefined || !isGoogle });\n const [saveSettings, settingsState] = api.useUpdateAgentConnectionSettingsMutation();\n const [saveLevel, levelState] = api.useSetAgentConnectionLevelMutation();\n const [addRoot, addState] = api.useAddAgentConnectionDriveRootMutation();\n const [removeRoot, removeState] = api.useRemoveAgentConnectionDriveRootMutation();\n const [submitError, setSubmitError] = useState<FormSubmitError | null>(null);\n\n const roots = useMemo(() => wireElementsOf(rootsQuery.currentData?.driveRoots), [rootsQuery.currentData]);\n const supportedRuleKinds = useMemo(() => supportedAgentConnectionDriveRuleKindsOf(rootsQuery.currentData), [rootsQuery.currentData]);\n const savedVisibility = agentConnectionVisibilityOf(connection);\n const savedFilesLevel = agentConnectionFilesLevelOf(connection);\n const savedChoice = agentConnectionDriveScopeChoiceOf(roots);\n const [choice, setChoice] = useState<AgentConnectionDriveScopeChoice>(\"AREAS\");\n const [visibility, setVisibility] = useState<AgentConnectionVisibility>(savedVisibility);\n const [filesLevel, setFilesLevel] = useState<AgentConnectionLevel>(savedFilesLevel);\n const isLoaded = rootsQuery.currentData !== undefined;\n\n // a connection opened, or its roots arrived: start from what is saved\n useEffect(() => {\n if (!isOpen) return;\n setVisibility(savedVisibility);\n setFilesLevel(savedFilesLevel);\n setSubmitError(null);\n }, [isOpen, savedVisibility, savedFilesLevel]);\n useEffect(() => {\n if (isOpen && isLoaded) setChoice(savedChoice);\n }, [isOpen, isLoaded, savedChoice]);\n\n const isAgentOwned = connection?.ownership === \"AGENT_OWNED\";\n const canManage = connection !== null && canManageAgentConnection(connection, viewer);\n const blockerOf = (option: AgentConnectionDriveScopeChoice): AgentConnectionDriveScopeBlocker | null =>\n agentConnectionDriveScopeBlockerOf(option, {\n supportedRuleKinds,\n visibility,\n isAgentOwned,\n });\n // the whole account keeps the connection its owner's: sharing is off while it is chosen (an active one ends first otherwise)\n const hasWholeAccountRoot = findActiveAgentConnectionDriveRuleRoot(roots, \"WHOLE_ACCOUNT\") !== null;\n const keepsWholeAccount = choice === \"WHOLE_ACCOUNT\" || (choice === \"LATER\" && hasWholeAccountRoot);\n\n // a choice that became impossible (the visibility changed) falls back to certain areas\n useEffect(() => {\n if (\n choice === \"WHOLE_ACCOUNT\" &&\n !hasWholeAccountRoot &&\n agentConnectionDriveScopeBlockerOf(choice, {\n supportedRuleKinds,\n visibility,\n isAgentOwned,\n }) !== null\n )\n setChoice(\"AREAS\");\n }, [choice, hasWholeAccountRoot, supportedRuleKinds, visibility, isAgentOwned]);\n\n const grantedFilesLevel = useMemo(() => {\n const entry = detail?.grantedLevels?.find((granted) => granted.capability === \"FILES\");\n return entry?.level !== undefined && isAgentConnectionLevel(entry.level) ? entry.level : null;\n }, [detail]);\n const needsConsent = isGoogle && detail !== undefined && filesLevel !== \"OFF\" && (grantedFilesLevel === null || agentConnectionLevelRank(filesLevel) > agentConnectionLevelRank(grantedFilesLevel));\n const plan = planAgentConnectionDriveScope({\n choice,\n visibility,\n savedVisibility,\n filesLevel,\n savedFilesLevel,\n roots,\n });\n const isPending = settingsState.isLoading || levelState.isLoading || addState.isLoading || removeState.isLoading || connect.isPending;\n const isDirty = plan.visibility !== null || plan.filesLevel !== null || plan.ruleKind !== null || plan.removeRuleKinds.length > 0;\n const itemRootCount = roots.filter((root) => !isAgentConnectionDriveRootEnded(root) && root.rootKind !== \"ALL_SHARED_DRIVES\" && root.rootKind !== \"WHOLE_ACCOUNT\").length;\n const agentName = texts.agentName;\n // a saved level outside the usual ones (a provider of its own) stays choosable, else the select would be empty\n const filesLevelOptions = AGENT_CONNECTION_DRIVE_FILES_LEVELS.includes(savedFilesLevel) ? AGENT_CONNECTION_DRIVE_FILES_LEVELS : [...AGENT_CONNECTION_DRIVE_FILES_LEVELS, savedFilesLevel];\n const levelLabel = (level: AgentConnectionLevel) =>\n t(AGENT_CONNECTION_LEVEL_LABEL[level], {\n context: AGENT_CONNECTION_LEVEL_CONTEXT,\n });\n\n const handleSubmit = async () => {\n if (connectionId === undefined || !writesAllowed || !canManage) return;\n setSubmitError(null);\n try {\n for (const ruleKind of plan.removeRuleKinds) {\n await removeRoot({ connectionId, rootKind: ruleKind }).unwrap();\n }\n if (plan.visibility !== null) {\n await saveSettings({\n connectionId,\n visibility: plan.visibility,\n targetAgentSpaceId: plan.visibility === \"AGENT_SPACE\" ? sharedAgentSpaceId : null,\n }).unwrap();\n }\n let consentLevel: AgentConnectionLevel | null = plan.filesLevel !== null && needsConsent ? plan.filesLevel : null;\n if (plan.filesLevel !== null && consentLevel === null) {\n try {\n await saveLevel({\n connectionId,\n capability: \"FILES\",\n level: plan.filesLevel,\n }).unwrap();\n } catch (error) {\n if (!isGoogle || !isAgentConnectionConsentRequiredMessage(toFormSubmitError(error, \"\").message)) throw error;\n consentLevel = plan.filesLevel;\n }\n }\n if (plan.ruleKind !== null) {\n await addRoot({\n connectionId,\n rootKind: plan.ruleKind,\n releaseWay: isAgentOwned ? \"OWN_IDENTITY\" : \"PERSON_ROOT\",\n }).unwrap();\n }\n if (consentLevel !== null) {\n // the browser leaves for the provider: the picker is opened from \"Drives and folders\" after the return\n await connect.extend(\"GOOGLE\", connectionId, [{ capability: \"FILES\", level: consentLevel }]);\n return;\n }\n if (isDirty)\n notify.success(\n t(\"Saved: %agentName% sees what you chose\", {\n replacements: { agentName },\n }),\n );\n onClose();\n if (plan.pickAreas) onPickAreas(connectionId);\n } catch (error) {\n const failure = toFormSubmitError(error, t(\"The choice could not be saved\"));\n setSubmitError(failure);\n notify.submitError(failure);\n }\n };\n\n const submitLabel =\n needsConsent && plan.filesLevel !== null\n ? t(\"Save and ask Google\")\n : plan.pickAreas\n ? t(\"Continue to the folders\", {\n context: \"agent-connection-drive-scope\",\n })\n : isDirty\n ? t(\"Save\")\n : t(\"Done\", { context: \"agent-connection-drive-scope\" });\n\n const choiceTexts: Readonly<Record<AgentConnectionDriveScopeChoice, { title: string; description: string }>> = {\n AREAS: {\n title: t(\"Certain areas\", { context: \"agent-connection-drive-scope\" }),\n description: t(\"You pick folders and shared drives next. Only these, nothing else.\", { context: \"agent-connection-drive-scope\" }),\n },\n ALL_SHARED_DRIVES: {\n title: t(\"All shared drives\", {\n context: \"agent-connection-drive-scope\",\n }),\n description: t(\"Every shared drive of this account, new ones automatically. My Drive and what was shared with you stay out.\", { context: \"agent-connection-drive-scope\" }),\n },\n WHOLE_ACCOUNT: {\n title: t(\"Everything\", { context: \"agent-connection-drive-scope\" }),\n description: t(\"My Drive and every shared drive of this account, new ones automatically.\", { context: \"agent-connection-drive-scope\" }),\n },\n LATER: {\n title: t(\"Later\", { context: \"agent-connection-drive-scope\" }),\n description:\n itemRootCount > 0 || savedChoice !== \"AREAS\"\n ? t(\"Nothing changes now. You decide in “Drives and folders” whenever you like.\", { context: \"agent-connection-drive-scope\" })\n : t(\"%agentName% sees no file of this drive until you add folders in “Drives and folders”.\", {\n context: \"agent-connection-drive-scope\",\n replacements: { agentName },\n }),\n },\n };\n\n const blockerText = (blocker: AgentConnectionDriveScopeBlocker): string =>\n blocker === \"comingSoon\"\n ? t(\"Comes soon for this connection.\", {\n context: \"agent-connection-drive-scope\",\n })\n : isAgentOwned\n ? t(\"Never for a connection of %agentName% itself.\", {\n context: \"agent-connection-drive-scope\",\n replacements: { agentName },\n })\n : t(\"Only while the connection is visible to you alone (“%label%”).\", {\n context: \"agent-connection-drive-scope\",\n replacements: { label: visibilityOptions[0]?.label ?? \"\" },\n });\n\n const factOf = (option: AgentConnectionDriveScopeChoice): string | null => {\n if (option === \"AREAS\")\n return itemRootCount > 0\n ? t(\"{count, plural, one {Now: # folder or shared drive} other {Now: # folders and shared drives}}\", { context: \"agent-connection-drive-scope\", count: itemRootCount })\n : null;\n if (option !== \"ALL_SHARED_DRIVES\" && option !== \"WHOLE_ACCOUNT\") return null;\n const activeRule = findActiveAgentConnectionDriveRuleRoot(roots, option);\n if (activeRule === null) return null;\n const count = agentConnectionDriveRuleResolutionOf(rootsQuery.currentData, activeRule)?.resolvedDriveCount;\n return count == null\n ? t(\"Active\", { context: \"agent-connection-drive-scope\" })\n : t(\"{count, plural, one {Active · now # shared drive} other {Active · now # shared drives}}\", { context: \"agent-connection-drive-scope\", count });\n };\n\n return (\n <FormDialog\n open={isOpen}\n onOpenChange={(open) => {\n if (!open) onClose();\n }}\n title={t(\"What may %agentName% see?\", { replacements: { agentName } })}\n description={[agentConnectionNameOf(connection), connection?.externalAddress].filter(Boolean).join(\" · \")}\n submitLabel={submitLabel}\n pendingLabel={t(\"Saving…\")}\n isPending={isPending}\n isDirty={isDirty}\n submitDisabled={!writesAllowed || !canManage || !isLoaded}\n className=\"sm:max-w-xl\"\n data-testid=\"agent-connection-drive-scope-dialog\"\n onSubmit={(event) => {\n event.preventDefault();\n event.stopPropagation();\n void handleSubmit();\n }}\n >\n <div className=\"space-y-5\">\n <FormErrors error={submitError} />\n {!canManage && <p className=\"text-sm text-muted-foreground\">{t(\"Only whoever manages this connection decides what %agentName% sees.\", { replacements: { agentName } })}</p>}\n {rootsQuery.isError ? (\n <StatusCallout size=\"compact\" tone=\"destructive\" title={t(\"The folders could not be loaded\")} description={toFormSubmitError(rootsQuery.error, \"\").message} />\n ) : !isLoaded ? (\n <div className=\"space-y-2\">\n <Skeleton className=\"h-16 w-full\" />\n <Skeleton className=\"h-16 w-full\" />\n <Skeleton className=\"h-16 w-full\" />\n </div>\n ) : (\n <div\n role=\"radiogroup\"\n aria-label={t(\"What may %agentName% see?\", {\n replacements: { agentName },\n })}\n className=\"space-y-2\"\n data-testid=\"agent-connection-drive-scope-choices\"\n >\n {AGENT_CONNECTION_DRIVE_SCOPE_CHOICES.map((option) => {\n const blocker = option === savedChoice && option !== \"AREAS\" ? null : blockerOf(option);\n const isChosen = choice === option;\n const isDisabled = blocker !== null || !canManage || !writesAllowed;\n const ChoiceIcon = CHOICE_ICON[option];\n const fact = factOf(option);\n return (\n <label\n key={option}\n className={cn(\n \"flex cursor-pointer gap-3 rounded-xl border p-3 transition-colors\",\n isChosen ? \"border-brand-emphasis bg-brand-light/40\" : \"bg-card hover:bg-muted/40\",\n isDisabled && !isChosen && \"cursor-not-allowed opacity-60 hover:bg-card\",\n )}\n data-scope-choice={option}\n data-blocker={blocker ?? undefined}\n >\n <input\n type=\"radio\"\n name={groupName}\n value={option}\n checked={isChosen}\n disabled={isDisabled}\n onChange={() => setChoice(option)}\n className=\"mt-1 size-4 shrink-0 accent-brand-emphasis\"\n />\n <ChoiceIcon aria-hidden className=\"mt-0.5 size-5 shrink-0 text-muted-foreground\" />\n <span className=\"min-w-0 flex-1 space-y-1\">\n <span className=\"flex flex-wrap items-center gap-x-2 gap-y-1\">\n <span className=\"text-sm font-semibold\">{choiceTexts[option].title}</span>\n {option === \"AREAS\" && (\n <span className=\"rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground\">\n {t(\"Recommended\", {\n context: \"agent-connection-drive-scope\",\n })}\n </span>\n )}\n {blocker === \"comingSoon\" && (\n <span className=\"rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground\">\n {t(\"comes soon\", {\n context: \"agent-connection-drive-search\",\n })}\n </span>\n )}\n </span>\n <span className=\"block text-sm text-muted-foreground\">{choiceTexts[option].description}</span>\n {option === \"AREAS\" && (\n <span className=\"flex flex-wrap gap-1.5 pt-1\" data-testid=\"agent-connection-drive-scope-sections\">\n {AGENT_CONNECTION_DRIVE_ITEMS_SECTIONS.map((section) => (\n <span key={section} className=\"rounded-md border bg-background px-2 py-0.5 text-xs font-medium\">\n {t(AGENT_CONNECTION_DRIVE_ITEMS_SECTION_LABEL[section], { context: AGENT_CONNECTION_DRIVE_CONTEXT })}\n </span>\n ))}\n </span>\n )}\n {fact !== null && <span className=\"block text-xs font-medium text-foreground\">{fact}</span>}\n {blocker !== null && blocker !== \"comingSoon\" && <span className=\"block text-xs text-muted-foreground\">{blockerText(blocker)}</span>}\n {blocker === \"comingSoon\" && <span className=\"block text-xs text-muted-foreground\">{blockerText(blocker)}</span>}\n </span>\n </label>\n );\n })}\n </div>\n )}\n {choice === \"WHOLE_ACCOUNT\" && (\n <StatusCallout\n size=\"compact\"\n tone=\"warning\"\n icon={ShieldAlert}\n title={t(\"%agentName% may then open every file of this account\", {\n context: \"agent-connection-drive-scope\",\n replacements: { agentName },\n })}\n description={t(\"Private documents too. It stays visible to you alone: sharing the connection is off while “Everything” is chosen.\", { context: \"agent-connection-drive-scope\" })}\n />\n )}\n <div className=\"grid gap-4 border-t pt-4 sm:grid-cols-2\">\n <FormFieldFrame\n label={t(\"Visible to\", { context: \"agent-connection\" })}\n description={\n keepsWholeAccount\n ? t(\"“Everything” keeps the connection yours alone.\", {\n context: \"agent-connection-drive-scope\",\n })\n : texts.sharedVisibilityHelp\n }\n >\n {() => (\n <SegmentedControl\n aria-label={t(\"Visible to\", { context: \"agent-connection\" })}\n value={visibility}\n onValueChange={setVisibility}\n options={visibilityOptions.map((option) => {\n const isOff =\n !canManage || !writesAllowed || (option.value === \"OWNER_ONLY\" && isAgentOwned) || (option.value === \"AGENT_SPACE\" && (sharedAgentSpaceId === null || keepsWholeAccount));\n return isOff ? { ...option, disabled: true } : option;\n })}\n height={36}\n fullWidth\n />\n )}\n </FormFieldFrame>\n <FormFieldFrame\n label={t(\"Level of Files\", {\n context: \"agent-connection-drive-scope\",\n })}\n description={levelHelp(filesLevel)}\n >\n {(control) => (\n <Select\n value={filesLevel}\n disabled={!canManage || !writesAllowed}\n onValueChange={(value) => {\n if (isAgentConnectionLevel(value)) setFilesLevel(value);\n }}\n >\n <SelectTrigger {...control} className=\"w-full\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {filesLevelOptions.map((level) => (\n <SelectItem key={level} value={level}>\n {levelLabel(level)}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n )}\n </FormFieldFrame>\n </div>\n {plan.removeRuleKinds.length > 0 && (\n <p className=\"text-xs text-muted-foreground\" data-testid=\"agent-connection-drive-scope-ends\">\n {t(\"Saving ends: %names%\", {\n context: \"agent-connection-drive-scope\",\n replacements: {\n names: plan.removeRuleKinds\n .map((kind) =>\n t(AGENT_CONNECTION_DRIVE_RULE_LABEL[kind], {\n context: AGENT_CONNECTION_DRIVE_CONTEXT,\n }),\n )\n .join(\", \"),\n },\n })}\n </p>\n )}\n {needsConsent && plan.filesLevel !== null && (\n <p className=\"flex items-center gap-1.5 text-xs font-medium text-warning\">\n <ShieldAlert aria-hidden className=\"size-3.5 shrink-0\" />\n {t(\"Needs your consent at Google\")}\n </p>\n )}\n {plan.pickAreas === false && choice === \"AREAS\" && filesLevel === \"OFF\" && (\n <p className=\"text-xs text-muted-foreground\">\n {t(\"With Files off %agentName% sees no file, whatever is chosen above.\", {\n context: \"agent-connection-drive-scope\",\n replacements: { agentName },\n })}\n </p>\n )}\n </div>\n </FormDialog>\n );\n};\n","import { useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { Button, cn, Input, Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { SlidersHorizontal } from \"lucide-react\";\nimport { type ReactNode, useId } from \"react\";\nimport {\n AGENT_CONNECTION_DRIVE_SEARCH_FILTER_FIELDS,\n AGENT_CONNECTION_DRIVE_SEARCH_TYPE_LABEL,\n type AgentConnectionDriveSearchFilterField,\n type AgentConnectionDriveSearchFilterName,\n type AgentConnectionDriveSearchFilters,\n type AgentConnectionDriveSearchType,\n countActiveAgentConnectionDriveSearchFilters,\n EMPTY_AGENT_CONNECTION_DRIVE_SEARCH_FILTERS,\n isAgentConnectionDriveSearchFilterFieldSupported,\n isAgentConnectionDriveSearchRangeReversed,\n} from \"./agent-connection-drive-scope\";\n\n/** A place the search can stay below; `null` = everywhere. */\nexport interface AgentConnectionDriveSearchLocation {\n folderId: string | null;\n label: string;\n}\n\nconst EVERYWHERE = \"__everywhere__\";\n\ninterface FilterToggleProps {\n isOpen: boolean;\n activeCount: number;\n onToggle: () => void;\n controlsId: string;\n}\n\n/** \"Filters\" beside the search field: opens and closes the filters, the number says how many are set. */\nexport const AgentConnectionDriveSearchFilterToggle = ({ isOpen, activeCount, onToggle, controlsId }: FilterToggleProps) => {\n const { t } = useTranslate();\n return (\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n className={cn((isOpen || activeCount > 0) && \"border-brand-emphasis\")}\n aria-expanded={isOpen}\n aria-controls={controlsId}\n onClick={onToggle}\n data-testid=\"agent-connection-drive-search-filters-toggle\"\n >\n <SlidersHorizontal aria-hidden />\n {t(\"Filters\", { context: \"agent-connection-drive-search\" })}\n {activeCount > 0 && <span className=\"rounded-full bg-primary px-1.5 text-xs font-semibold text-primary-foreground\">{activeCount}</span>}\n </Button>\n );\n};\n\ninterface FilterFieldProps {\n field: AgentConnectionDriveSearchFilterField;\n label: string;\n supported: readonly AgentConnectionDriveSearchFilterName[];\n warning?: string | null;\n children: (isDisabled: boolean) => ReactNode;\n}\n\nconst FilterField = ({ field, label, supported, warning = null, children }: FilterFieldProps) => {\n const { t } = useTranslate();\n const isSupported = isAgentConnectionDriveSearchFilterFieldSupported(field, supported);\n return (\n <fieldset className=\"min-w-0 space-y-1.5\" disabled={!isSupported} data-search-filter={field} data-supported={isSupported ? \"\" : undefined}>\n <legend className=\"flex flex-wrap items-baseline gap-x-2 text-xs font-medium text-muted-foreground\">\n <span>{label}</span>\n {!isSupported && <span className=\"font-normal\">{t(\"comes soon\", { context: \"agent-connection-drive-search\" })}</span>}\n </legend>\n {children(!isSupported)}\n {warning !== null && isSupported && <p className=\"text-xs text-warning\">{warning}</p>}\n </fieldset>\n );\n};\n\nexport interface AgentConnectionDriveSearchFiltersPanelProps {\n id: string;\n filters: AgentConnectionDriveSearchFilters;\n onChange: (filters: AgentConnectionDriveSearchFilters) => void;\n /** The filters the server applies (`supportedSearchFilters`); the others are shown off. */\n supported: readonly AgentConnectionDriveSearchFilterName[];\n /** The kinds offered (the picker: folders and shared drives). */\n typeOptions: readonly AgentConnectionDriveSearchType[];\n /** The places the search can stay below, after \"Everywhere\". */\n locations: readonly AgentConnectionDriveSearchLocation[];\n /** The controls shown (default all; the picker leaves out the size, folders have none). */\n fields?: readonly AgentConnectionDriveSearchFilterField[];\n}\n\n/**\n * The filters of a drive search: changed and created between two days, kind, size in megabytes, and the place it stays\n * below. A filter the server does not apply (`supportedSearchFilters`) is shown off with \"comes soon\" and never sent;\n * a range whose start lies after its end is named, the search still runs.\n */\nexport const AgentConnectionDriveSearchFiltersPanel = ({\n id,\n filters,\n onChange,\n supported,\n typeOptions,\n locations,\n fields = AGENT_CONNECTION_DRIVE_SEARCH_FILTER_FIELDS,\n}: AgentConnectionDriveSearchFiltersPanelProps) => {\n const { t } = useTranslate();\n const idPrefix = useId();\n const set = (changes: Partial<AgentConnectionDriveSearchFilters>) => onChange({ ...filters, ...changes });\n const activeCount = countActiveAgentConnectionDriveSearchFilters(filters, supported);\n const reversedDays = t(\"The start lies after the end.\", {\n context: \"agent-connection-drive-search\",\n });\n const dayRange = (fromKey: \"modifiedFrom\" | \"createdFrom\", toKey: \"modifiedTo\" | \"createdTo\", isDisabled: boolean) => (\n <div className=\"grid grid-cols-2 gap-2\">\n <Input\n type=\"date\"\n aria-label={t(\"From\", { context: \"agent-connection-drive-search\" })}\n value={filters[fromKey]}\n max={filters[toKey] || undefined}\n disabled={isDisabled}\n onChange={(event) => set({ [fromKey]: event.target.value })}\n />\n <Input\n type=\"date\"\n aria-label={t(\"To\", { context: \"agent-connection-drive-search\" })}\n value={filters[toKey]}\n min={filters[fromKey] || undefined}\n disabled={isDisabled}\n onChange={(event) => set({ [toKey]: event.target.value })}\n />\n </div>\n );\n\n return (\n <div id={id} className=\"space-y-3 rounded-xl border bg-muted/30 p-3\" data-testid=\"agent-connection-drive-search-filters\">\n <div className=\"grid gap-3 sm:grid-cols-2\">\n {fields.includes(\"modified\") && (\n <FilterField\n field=\"modified\"\n label={t(\"Changed\", { context: \"agent-connection-drive-search\" })}\n supported={supported}\n warning={isAgentConnectionDriveSearchRangeReversed(filters.modifiedFrom, filters.modifiedTo, \"day\") ? reversedDays : null}\n >\n {(isDisabled) => dayRange(\"modifiedFrom\", \"modifiedTo\", isDisabled)}\n </FilterField>\n )}\n {fields.includes(\"created\") && (\n <FilterField\n field=\"created\"\n label={t(\"Created\", { context: \"agent-connection-drive-search\" })}\n supported={supported}\n warning={isAgentConnectionDriveSearchRangeReversed(filters.createdFrom, filters.createdTo, \"day\") ? reversedDays : null}\n >\n {(isDisabled) => dayRange(\"createdFrom\", \"createdTo\", isDisabled)}\n </FilterField>\n )}\n {fields.includes(\"types\") && (\n <FilterField field=\"types\" label={t(\"Kind\", { context: \"agent-connection-drive-search\" })} supported={supported}>\n {(isDisabled) => (\n <div className=\"flex flex-wrap gap-1.5\">\n {typeOptions.map((type) => {\n const isOn = filters.types.includes(type);\n return (\n <button\n key={type}\n type=\"button\"\n aria-pressed={isOn}\n disabled={isDisabled}\n className={cn(\n \"rounded-full border px-2.5 py-1 text-xs font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50\",\n isOn ? \"border-brand-emphasis bg-brand-light/60 text-foreground\" : \"bg-card text-muted-foreground hover:text-foreground\",\n )}\n onClick={() =>\n set({\n types: isOn ? filters.types.filter((entry) => entry !== type) : [...filters.types, type],\n })\n }\n >\n {t(AGENT_CONNECTION_DRIVE_SEARCH_TYPE_LABEL[type], {\n context: type === \"FOLDER\" || type === \"SHARED_DRIVE\" ? \"agent-connection-drive\" : \"agent-connection-drive-type\",\n })}\n </button>\n );\n })}\n </div>\n )}\n </FilterField>\n )}\n {fields.includes(\"size\") && (\n <FilterField\n field=\"size\"\n label={t(\"Size in MB\", { context: \"agent-connection-drive-search\" })}\n supported={supported}\n warning={\n isAgentConnectionDriveSearchRangeReversed(filters.minSizeMegabytes, filters.maxSizeMegabytes, \"size\")\n ? t(\"The smallest size is above the largest.\", {\n context: \"agent-connection-drive-search\",\n })\n : null\n }\n >\n {(isDisabled) => (\n <div className=\"grid grid-cols-2 gap-2\">\n <Input\n inputMode=\"decimal\"\n placeholder={t(\"at least\", {\n context: \"agent-connection-drive-search\",\n })}\n aria-label={t(\"At least (MB)\", {\n context: \"agent-connection-drive-search\",\n })}\n value={filters.minSizeMegabytes}\n disabled={isDisabled}\n onChange={(event) => set({ minSizeMegabytes: event.target.value })}\n />\n <Input\n inputMode=\"decimal\"\n placeholder={t(\"at most\", {\n context: \"agent-connection-drive-search\",\n })}\n aria-label={t(\"At most (MB)\", {\n context: \"agent-connection-drive-search\",\n })}\n value={filters.maxSizeMegabytes}\n disabled={isDisabled}\n onChange={(event) => set({ maxSizeMegabytes: event.target.value })}\n />\n </div>\n )}\n </FilterField>\n )}\n {fields.includes(\"location\") && (\n <FilterField field=\"location\" label={t(\"Place\", { context: \"agent-connection-drive-search\" })} supported={supported}>\n {(isDisabled) => (\n <Select value={filters.inFolderId ?? EVERYWHERE} disabled={isDisabled} onValueChange={(value) => set({ inFolderId: value === EVERYWHERE ? null : value })}>\n <SelectTrigger\n id={`${idPrefix}-place`}\n className=\"w-full\"\n aria-label={t(\"Place\", {\n context: \"agent-connection-drive-search\",\n })}\n >\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n <SelectItem value={EVERYWHERE}>\n {t(\"Everywhere\", {\n context: \"agent-connection-drive-search\",\n })}\n </SelectItem>\n {locations.map((location) =>\n location.folderId === null ? null : (\n <SelectItem key={location.folderId} value={location.folderId}>\n {t(\"In “%name%”\", {\n context: \"agent-connection-drive-search\",\n replacements: { name: location.label },\n })}\n </SelectItem>\n ),\n )}\n </SelectContent>\n </Select>\n )}\n </FilterField>\n )}\n </div>\n <div className=\"flex flex-wrap items-center justify-between gap-2\">\n <p className=\"text-xs text-muted-foreground\">\n {supported.length === 0\n ? t(\"The provider’s search of this connection matches names only for now.\", { context: \"agent-connection-drive-search\" })\n : t(\"Filters narrow the search by name.\", {\n context: \"agent-connection-drive-search\",\n })}\n </p>\n {activeCount > 0 && (\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" onClick={() => onChange(EMPTY_AGENT_CONNECTION_DRIVE_SEARCH_FILTERS)}>\n {t(\"Clear filters\", { context: \"agent-connection-drive-search\" })}\n </Button>\n )}\n </div>\n </div>\n );\n};\n","import { FormDialog, FormErrors, FormFieldFrame } from \"@mgamadeus/ddd-admin-ui/form\";\nimport { useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { type FormSubmitError, notify, toFormSubmitError, useConfirm } from \"@mgamadeus/ddd-admin-ui/logic\";\nimport { Button, Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { Lock, Share2, Undo2, Users, X } from \"lucide-react\";\nimport { useEffect, useState } from \"react\";\nimport {\n type AgentConnectionDriveRootActions,\n activeAgentConnectionDriveRootReleasesOf,\n agentConnectionDriveLabelOf,\n agentConnectionDriveRootIdOf,\n agentConnectionDriveRootReleaseIdOf,\n agentConnectionDriveRootSpaceStateOf,\n canRevokeAgentConnectionDriveRootRelease,\n releasableAgentSpaceIdsOfDriveRoot,\n} from \"./agent-connection-drives\";\nimport { useAgentConnectionsContext } from \"./agent-connections-context\";\nimport type { AgentConnectionDriveLabel, AgentConnectionDriveRoot, AgentConnectionDriveRootRelease, AgentConnectionSummary } from \"./agent-connections-types\";\n\n/** What a drive answer says about agent spaces: the releases of the roots, where the viewer may release to, what the connection is shared with, the host's names. */\nexport interface AgentConnectionDriveSpaces {\n releases: readonly AgentConnectionDriveRootRelease[];\n releasableAgentSpaceIds: readonly number[];\n connectionAgentSpaceIds: readonly number[];\n agentSpaceLabels: readonly AgentConnectionDriveLabel[];\n}\n\ninterface ReleaseToSpaceDialogProps {\n root: AgentConnectionDriveRoot;\n rootName: string;\n isOpen: boolean;\n /** The first release of a root that still follows the connection: it restricts the root to its released spaces. */\n isFirstRelease: boolean;\n /** The spaces the root can still be released to. */\n agentSpaceIds: readonly number[];\n connectionAgentSpaceIds: readonly number[];\n spaceNameOf: (agentSpaceId: number) => string;\n onClose: () => void;\n}\n\n/**\n * \"Release to a space\": one root of the connection for one agent space (`POST driveRoots/{id}/releases`). The dialog\n * names the effect (the first release takes the root from the connection's other spaces); its submit is the\n * confirmation.\n */\nconst ReleaseToSpaceDialog = ({ root, rootName, isOpen, isFirstRelease, agentSpaceIds, connectionAgentSpaceIds, spaceNameOf, onClose }: ReleaseToSpaceDialogProps) => {\n const { t } = useTranslate();\n const { api, writesAllowed } = useAgentConnectionsContext();\n const [release, releaseState] = api.useReleaseAgentConnectionDriveRootToAgentSpaceMutation();\n const firstAgentSpaceId = agentSpaceIds[0] ?? null;\n const [agentSpaceId, setAgentSpaceId] = useState<number | null>(firstAgentSpaceId);\n const [submitError, setSubmitError] = useState<FormSubmitError | null>(null);\n\n useEffect(() => {\n if (!isOpen) return;\n setAgentSpaceId(firstAgentSpaceId);\n setSubmitError(null);\n }, [isOpen, firstAgentSpaceId]);\n\n const driveRootId = agentConnectionDriveRootIdOf(root);\n const isSharedWithSpace = agentSpaceId === null || connectionAgentSpaceIds.includes(agentSpaceId);\n\n const handleSubmit = async () => {\n if (driveRootId === null || agentSpaceId === null || !writesAllowed) return;\n setSubmitError(null);\n try {\n await release({ driveRootId, agentSpaceId }).unwrap();\n notify.success(t(\"“%name%” released to %spaceName%\", { replacements: { name: rootName, spaceName: spaceNameOf(agentSpaceId) } }));\n onClose();\n } catch (error) {\n const failure = toFormSubmitError(error, t(\"The release to the space could not be created\"));\n setSubmitError(failure);\n notify.submitError(failure);\n }\n };\n\n return (\n <FormDialog\n open={isOpen}\n onOpenChange={(open) => {\n if (!open) onClose();\n }}\n title={t(\"Release “%name%” to a space\", { replacements: { name: rootName } })}\n description={\n isFirstRelease\n ? t(\"From now on only the spaces you release it to use “%name%”; the connection’s other spaces lose it.\", { replacements: { name: rootName } })\n : t(\"The space uses “%name%” through this connection, beside the spaces it is released to already.\", { replacements: { name: rootName } })\n }\n submitLabel={t(\"Release\", { context: \"agent-connection-drive\" })}\n pendingLabel={t(\"Releasing…\")}\n isPending={releaseState.isLoading}\n isDirty={false}\n submitDisabled={!writesAllowed || agentSpaceId === null || driveRootId === null}\n data-testid=\"agent-connection-drive-release-to-space\"\n onSubmit={(event) => {\n event.preventDefault();\n event.stopPropagation();\n void handleSubmit();\n }}\n >\n <div className=\"space-y-4\">\n <FormErrors error={submitError} />\n <FormFieldFrame\n label={t(\"Space\", { context: \"agent-connection-drive\" })}\n description={isSharedWithSpace ? undefined : t(\"The connection is not shared with this space yet: it uses “%name%” only once the connection is shared with it too.\", { replacements: { name: rootName } })}\n >\n {(control) => (\n <Select value={agentSpaceId === null ? \"\" : String(agentSpaceId)} onValueChange={(value) => setAgentSpaceId(Number(value))}>\n <SelectTrigger {...control} className=\"w-full\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {agentSpaceIds.map((id) => (\n <SelectItem key={id} value={String(id)}>\n {spaceNameOf(id)}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n )}\n </FormFieldFrame>\n </div>\n </FormDialog>\n );\n};\n\nexport interface AgentConnectionDriveRootSpacesProps {\n /** An ACTIVE root. */\n root: AgentConnectionDriveRoot;\n connection: AgentConnectionSummary;\n /** What the viewer may do with the root (`agentConnectionDriveRootActionsOf`). */\n actions: AgentConnectionDriveRootActions;\n spaces: AgentConnectionDriveSpaces;\n}\n\n/**\n * \"Released to\" of one active root: which agent spaces use it. By default it follows the connection's sharing; once\n * released to a space or set to \"only for the owner\" it is restricted to the spaces of its active releases. Whoever\n * manages the connection releases it to a space, restricts it and lets it follow the connection again; a release is\n * taken back by the person who released it or with the system right. Every write names its effect and is off without\n * write access.\n */\nexport const AgentConnectionDriveRootSpaces = ({ root, connection, actions, spaces }: AgentConnectionDriveRootSpacesProps) => {\n const { t } = useTranslate();\n const confirm = useConfirm();\n const { api, writesAllowed, viewer } = useAgentConnectionsContext();\n const [revokeRelease, revokeState] = api.useRevokeAgentConnectionDriveRootReleaseMutation();\n const [restrict, restrictState] = api.useRestrictAgentConnectionDriveRootMutation();\n const [followConnection, followState] = api.useFollowAgentConnectionSharingWithDriveRootMutation();\n const [isReleasing, setIsReleasing] = useState(false);\n\n const driveRootId = agentConnectionDriveRootIdOf(root);\n const name = root.itemName || root.itemId || \"\";\n const state = agentConnectionDriveRootSpaceStateOf(root, spaces.releases);\n const activeReleases = activeAgentConnectionDriveRootReleasesOf(root, spaces.releases);\n const releasableAgentSpaceIds = releasableAgentSpaceIdsOfDriveRoot(root, spaces.releases, spaces.releasableAgentSpaceIds);\n const isBusy = revokeState.isLoading || restrictState.isLoading || followState.isLoading;\n const isOwnConnection = viewer.accountId !== null && connection.ownerAccountId != null && String(connection.ownerAccountId) === String(viewer.accountId);\n\n const spaceNameOf = (agentSpaceId: number): string => agentConnectionDriveLabelOf(spaces.agentSpaceLabels, agentSpaceId) ?? t(\"Space #%id%\", { replacements: { id: agentSpaceId } });\n const connectionSpaceNames = spaces.connectionAgentSpaceIds.map(spaceNameOf);\n const unsharedReleases = activeReleases.filter((release) => release.agentSpaceId != null && !spaces.connectionAgentSpaceIds.includes(release.agentSpaceId));\n\n const handleRevokeRelease = async (release: AgentConnectionDriveRootRelease) => {\n const driveRootReleaseId = agentConnectionDriveRootReleaseIdOf(release);\n if (driveRootReleaseId === null || release.agentSpaceId == null || !writesAllowed) return;\n const spaceName = spaceNameOf(release.agentSpaceId);\n const isLastRelease = activeReleases.length === 1;\n const confirmed = await confirm({\n title: t(\"Take “%name%” back from %spaceName%?\", { replacements: { name, spaceName } }),\n description: isLastRelease\n ? t(\"%spaceName% stops using “%name%” at once. It is the last space: afterwards only the owner uses it.\", { replacements: { name, spaceName } })\n : t(\"%spaceName% stops using “%name%” at once. The other spaces it is released to keep it.\", { replacements: { name, spaceName } }),\n confirmLabel: t(\"Take back\", { context: \"agent-connection-drive\" }),\n confirmVariant: \"destructive\",\n });\n if (!confirmed) return;\n try {\n await revokeRelease({ driveRootReleaseId }).unwrap();\n notify.success(t(\"“%name%” taken back from %spaceName%\", { replacements: { name, spaceName } }));\n } catch (error) {\n notify.submitError(toFormSubmitError(error, t(\"The release to the space could not be taken back\")));\n }\n };\n\n const handleRestrict = async () => {\n if (driveRootId === null || !writesAllowed) return;\n const confirmed = await confirm({\n title: t(\"Use “%name%” only for the owner?\", { replacements: { name } }),\n description: t(\"No space uses “%name%” any more, the spaces the connection is shared with included. The owner’s own use stays as it is.\", { replacements: { name } }),\n confirmLabel: t(\"Only for the owner\", { context: \"agent-connection-drive\" }),\n confirmVariant: \"destructive\",\n });\n if (!confirmed) return;\n try {\n await restrict({ driveRootId }).unwrap();\n notify.success(t(\"“%name%” is only for the owner now\", { replacements: { name } }));\n } catch (error) {\n notify.submitError(toFormSubmitError(error, t(\"The folder could not be restricted\")));\n }\n };\n\n const handleFollowConnection = async () => {\n if (driveRootId === null || !writesAllowed) return;\n const confirmed = await confirm({\n title: t(\"Let “%name%” follow the connection again?\", { replacements: { name } }),\n description: t(\"Every space the connection is shared with uses “%name%” again, and its own releases to spaces end.\", { replacements: { name } }),\n confirmLabel: t(\"Follow the connection again\", { context: \"agent-connection-drive\" }),\n });\n if (!confirmed) return;\n try {\n await followConnection({ driveRootId }).unwrap();\n notify.success(t(\"“%name%” follows the connection again\", { replacements: { name } }));\n } catch (error) {\n notify.submitError(toFormSubmitError(error, t(\"The folder could not be set to follow the connection\")));\n }\n };\n\n const hasActions = actions.canReleaseToSpace || actions.canRestrict || actions.canFollowConnection;\n\n return (\n <div className=\"mt-3 space-y-2 border-t pt-2 text-xs\" data-testid=\"agent-connection-drive-root-spaces\" data-space-state={state}>\n <div className=\"flex min-w-0 flex-wrap items-center gap-1.5\">\n <span className=\"font-medium text-muted-foreground\">{t(\"Released to\", { context: \"agent-connection-drive\" })}</span>\n {state === \"connection\" && (\n <span className=\"min-w-0\">\n {t(\"Follows the connection’s sharing\")}\n <span className=\"text-muted-foreground\">\n {\" · \"}\n {connectionSpaceNames.length > 0\n ? connectionSpaceNames.join(\", \")\n : isOwnConnection\n ? t(\"only you\", { context: \"agent-connection-drive\" })\n : t(\"only the owner\", { context: \"agent-connection-drive\" })}\n </span>\n </span>\n )}\n {state === \"none\" && (\n <span className=\"inline-flex items-center gap-1\">\n <Lock aria-hidden className=\"size-3 text-muted-foreground\" />\n {t(\"No space — only the owner uses it\")}\n </span>\n )}\n {state === \"spaces\" &&\n activeReleases.map((release) => {\n const driveRootReleaseId = agentConnectionDriveRootReleaseIdOf(release);\n const spaceName = release.agentSpaceId == null ? \"\" : spaceNameOf(release.agentSpaceId);\n return (\n <span key={driveRootReleaseId ?? spaceName} className=\"inline-flex max-w-full items-center gap-1 rounded-full border bg-muted px-2 py-0.5 font-medium\" data-drive-root-release={driveRootReleaseId ?? undefined}>\n <Users aria-hidden className=\"size-3 shrink-0 text-muted-foreground\" />\n <span className=\"truncate\">{spaceName}</span>\n {canRevokeAgentConnectionDriveRootRelease(release, viewer) && (\n <button\n type=\"button\"\n className=\"shrink-0 rounded-full p-0.5 text-muted-foreground hover:text-foreground disabled:pointer-events-none disabled:opacity-50\"\n aria-label={t(\"Take “%name%” back from %spaceName%\", { replacements: { name, spaceName } })}\n disabled={!writesAllowed || isBusy}\n onClick={() => void handleRevokeRelease(release)}\n >\n <X aria-hidden className=\"size-3\" />\n </button>\n )}\n </span>\n );\n })}\n </div>\n {unsharedReleases.map((release) => (\n <p key={agentConnectionDriveRootReleaseIdOf(release) ?? release.agentSpaceId} className=\"text-muted-foreground\">\n {t(\"%spaceName%: the connection is not shared with this space yet\", { replacements: { spaceName: release.agentSpaceId == null ? \"\" : spaceNameOf(release.agentSpaceId) } })}\n </p>\n ))}\n {hasActions && (\n <div className=\"flex flex-wrap items-center gap-1.5\">\n {actions.canReleaseToSpace && (\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n disabled={!writesAllowed || isBusy || releasableAgentSpaceIds.length === 0}\n title={releasableAgentSpaceIds.length === 0 ? t(\"There is no further space you can release it to.\") : undefined}\n onClick={() => setIsReleasing(true)}\n >\n <Share2 aria-hidden />\n {t(\"Release to a space\")}\n </Button>\n )}\n {actions.canRestrict && (\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" disabled={!writesAllowed || isBusy} onClick={() => void handleRestrict()}>\n <Lock aria-hidden />\n {t(\"Only for the owner\", { context: \"agent-connection-drive\" })}\n </Button>\n )}\n {actions.canFollowConnection && (\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" disabled={!writesAllowed || isBusy} onClick={() => void handleFollowConnection()}>\n <Undo2 aria-hidden />\n {t(\"Follow the connection again\", { context: \"agent-connection-drive\" })}\n </Button>\n )}\n </div>\n )}\n {actions.canReleaseToSpace && (\n <ReleaseToSpaceDialog\n root={root}\n rootName={name}\n isOpen={isReleasing}\n isFirstRelease={state === \"connection\"}\n agentSpaceIds={releasableAgentSpaceIds}\n connectionAgentSpaceIds={spaces.connectionAgentSpaceIds}\n spaceNameOf={spaceNameOf}\n onClose={() => setIsReleasing(false)}\n />\n )}\n </div>\n );\n};\n","import { FormDialog, FormDrawer, FormErrors, FormFieldFrame } from \"@mgamadeus/ddd-admin-ui/form\";\nimport { useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { SearchField, StatusBadge } from \"@mgamadeus/ddd-admin-ui/list\";\nimport { type FormSubmitError, notify, toFormSubmitError, useConfirm, useDebouncedValue } from \"@mgamadeus/ddd-admin-ui/logic\";\nimport { StatusCallout } from \"@mgamadeus/ddd-admin-ui/page\";\nimport { Button, cn, SegmentedControl, Select, SelectContent, SelectItem, SelectTrigger, SelectValue, Skeleton } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { ArrowLeft, ChevronRight, Eye, File, Folder, FolderOpen, FolderPlus, HardDrive, Layers, type LucideIcon, RefreshCw, SearchCheck, Share2 } from \"lucide-react\";\nimport { useEffect, useId, useMemo, useState } from \"react\";\nimport { wireElementsOf } from \"../wire/admin-wire\";\nimport {\n AGENT_CONNECTION_DRIVE_PICKER_SEARCH_FILTER_FIELDS,\n AGENT_CONNECTION_DRIVE_PICKER_SEARCH_TYPES,\n AGENT_CONNECTION_DRIVE_RULE_LABEL,\n type AgentConnectionDriveSearchFilterName,\n type AgentConnectionDriveSearchFilters,\n agentConnectionDriveRuleResolutionOf,\n agentConnectionDriveSearchFilterArgsOf,\n countActiveAgentConnectionDriveSearchFilters,\n EMPTY_AGENT_CONNECTION_DRIVE_SEARCH_FILTERS,\n isAgentConnectionDriveRuleKind,\n isAgentConnectionDriveSearchLeavingSharedDrivesOut,\n supportedAgentConnectionDriveSearchFiltersOf,\n} from \"./agent-connection-drive-scope\";\nimport { AgentConnectionDriveSearchFiltersPanel, AgentConnectionDriveSearchFilterToggle } from \"./AgentConnectionDriveSearchFilters\";\nimport {\n AGENT_CONNECTION_DRIVE_CONTEXT,\n AGENT_CONNECTION_DRIVE_ITEMS_SECTION_LABEL,\n AGENT_CONNECTION_DRIVE_RELEASE_ROLES,\n AGENT_CONNECTION_DRIVE_ROLE_LABEL,\n AGENT_CONNECTION_DRIVE_ROOT_GROUP_LABEL,\n AGENT_CONNECTION_DRIVE_ROOT_KIND_LABEL,\n AGENT_CONNECTION_DRIVE_ROOT_STATUS,\n AGENT_CONNECTION_DRIVE_ROOT_WAY_LABEL,\n AGENT_CONNECTION_DRIVE_SEARCH_MAX_LENGTH,\n AGENT_CONNECTION_DRIVE_SEARCH_MIN_LENGTH,\n agentConnectionDriveItemKindOf,\n agentConnectionDriveItemsSectionsOf,\n agentConnectionDriveLabelOf,\n agentConnectionDriveReleaseTargetsOf,\n agentConnectionDriveRootActionsOf,\n agentConnectionDriveRootAttachWayOf,\n agentConnectionDriveRootGroupsOf,\n agentConnectionDriveRootIdOf,\n agentConnectionDriveSearchQueryOf,\n attachableAgentConnectionDriveItemsOf,\n canReleaseAgentConnectionDriveItemToAgent,\n findAgentConnectionDriveRootOfItem,\n isAgentConnectionDriveReleaseRole,\n isAgentConnectionDriveRootEnded,\n} from \"./agent-connection-drives\";\nimport { agentConnectionNameOf, canManageAgentConnection } from \"./agent-connection-format\";\nimport { agentConnectionDriveRootDomId } from \"./agent-connection-oauth\";\nimport { useAgentConnectionsContext } from \"./agent-connections-context\";\nimport { AgentConnectionDriveRootSpaces, type AgentConnectionDriveSpaces } from \"./AgentConnectionDriveRootSpaces\";\nimport type {\n AgentConnectionDriveItem,\n AgentConnectionDriveItemsSection,\n AgentConnectionDriveReleaseRole,\n AgentConnectionDriveRoot,\n AgentConnectionDriveRootRuleResolution,\n AgentConnectionSummary,\n} from \"./agent-connections-types\";\nimport { ProviderMark } from \"./connection-logos\";\nimport { AgentConnectionRelativeTime } from \"./connection-parts\";\n\n/** The mark of what a root or an item is at the provider; a folder for a kind nobody stored. */\nconst DRIVE_KIND_ICON: Readonly<Record<string, LucideIcon>> = { SHARED_DRIVE: HardDrive, FOLDER: Folder, FILE: File };\n\ninterface DriveFolderStep {\n itemId: string;\n name: string;\n}\n\ninterface ReleaseToAgentDialogProps {\n source: AgentConnectionSummary;\n /** The item to release, `null` = closed. */\n item: AgentConnectionDriveItem | null;\n targets: readonly AgentConnectionSummary[];\n onClose: () => void;\n}\n\n/**\n * \"Release to the agent\": shares a folder or shared drive of the person's own connection with the agent's own drive\n * identity at a role (`POST connections/{id}/releaseToAgent`; the share is created at the provider with the person's\n * token) and adds it as a root of the agent's connection. The dialog names the effect; its submit is the confirmation.\n */\nconst ReleaseToAgentDialog = ({ source, item, targets, onClose }: ReleaseToAgentDialogProps) => {\n const { t } = useTranslate();\n const { api, writesAllowed, texts } = useAgentConnectionsContext();\n const [release, releaseState] = api.useReleaseAgentConnectionDriveItemToAgentMutation();\n const [role, setRole] = useState<AgentConnectionDriveReleaseRole>(\"reader\");\n const [targetId, setTargetId] = useState<number | null>(targets[0]?.connectionId ?? null);\n const [submitError, setSubmitError] = useState<FormSubmitError | null>(null);\n const firstTargetId = targets[0]?.connectionId ?? null;\n\n useEffect(() => {\n if (item === null) return;\n setRole(\"reader\");\n setTargetId(firstTargetId);\n setSubmitError(null);\n }, [item, firstTargetId]);\n\n const target = targets.find((connection) => connection.connectionId === targetId) ?? null;\n const itemName = item?.name || item?.itemId || \"\";\n\n const handleSubmit = async () => {\n if (item === null || target === null || !writesAllowed) return;\n setSubmitError(null);\n try {\n await release({ connectionId: source.connectionId, itemId: item.itemId, agentConnectionId: target.connectionId, role }).unwrap();\n notify.success(t(\"“%name%” released to %agentName%\", { replacements: { name: itemName, agentName: texts.agentName } }));\n onClose();\n } catch (error) {\n const failure = toFormSubmitError(error, t(\"The release could not be created\"));\n setSubmitError(failure);\n notify.submitError(failure);\n }\n };\n\n return (\n <FormDialog\n open={item !== null}\n onOpenChange={(open) => {\n if (!open) onClose();\n }}\n title={t(\"Release “%name%” to %agentName%\", { replacements: { name: itemName, agentName: texts.agentName } })}\n description={t(\"The item is shared with %agentName%’s own account (%address%) at the provider, with your access, and becomes one of its folders. Everyone who may use that connection reaches it through %agentName%.\", {\n replacements: { agentName: texts.agentName, address: target?.externalAddress ?? \"–\" },\n })}\n submitLabel={t(\"Release\", { context: \"agent-connection-drive\" })}\n pendingLabel={t(\"Releasing…\")}\n isPending={releaseState.isLoading}\n isDirty={false}\n submitDisabled={!writesAllowed || target === null}\n onSubmit={(event) => {\n event.preventDefault();\n event.stopPropagation();\n void handleSubmit();\n }}\n >\n <div className=\"space-y-4\">\n <FormErrors error={submitError} />\n {targets.length > 1 && (\n <FormFieldFrame label={t(\"Account of %agentName%\", { replacements: { agentName: texts.agentName } })}>\n {(control) => (\n <Select value={targetId === null ? \"\" : String(targetId)} onValueChange={(value) => setTargetId(Number(value))}>\n <SelectTrigger {...control} className=\"w-full\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {targets.map((connection) => (\n <SelectItem key={connection.connectionId} value={String(connection.connectionId)}>\n {[agentConnectionNameOf(connection), connection.externalAddress].filter(Boolean).join(\" · \")}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n )}\n </FormFieldFrame>\n )}\n <FormFieldFrame label={t(\"Role at the provider\", { context: \"agent-connection-drive\" })} description={t(\"What %agentName%’s account may do with the item. The level of the connection can only narrow it.\", { replacements: { agentName: texts.agentName } })}>\n {(control) => (\n <Select\n value={role}\n onValueChange={(value) => {\n if (isAgentConnectionDriveReleaseRole(value)) setRole(value);\n }}\n >\n <SelectTrigger {...control} className=\"w-full\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {AGENT_CONNECTION_DRIVE_RELEASE_ROLES.map((option) => (\n <SelectItem key={option} value={option}>\n {t(AGENT_CONNECTION_DRIVE_ROLE_LABEL[option] ?? option, { context: AGENT_CONNECTION_DRIVE_CONTEXT })}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n )}\n </FormFieldFrame>\n </div>\n </FormDialog>\n );\n};\n\ninterface DriveItemPickerProps {\n connection: AgentConnectionSummary;\n roots: readonly AgentConnectionDriveRoot[];\n releaseTargets: readonly AgentConnectionSummary[];\n /** The search field over the names of folders and shared drives (`AgentConnectionDrivesDrawerProps.isItemSearchAvailable`). */\n isItemSearchAvailable: boolean;\n /** The section \"Shared drives\" of the switch (`AgentConnectionDrivesDrawerProps.isSharedDrivesSectionAvailable`). */\n isSharedDrivesSectionAvailable: boolean;\n /** The filters the item search applies (`supportedSearchFilters` of the drive answers); the others are shown off. */\n supportedSearchFilters: readonly AgentConnectionDriveSearchFilterName[];\n onBack: () => void;\n}\n\n/** What an empty top of a section says; a folder level and a page between others say \"No folders here.\" */\nconst EMPTY_SECTION_TEXT: Readonly<Record<AgentConnectionDriveItemsSection, string>> = {\n MY_DRIVE: \"No folders here.\",\n SHARED_DRIVES: \"This account is in no shared drive.\",\n SHARED_WITH_ME: \"Nothing was shared with this account as a folder.\",\n};\n\n/**\n * The folders and shared drives of the connection as its own account sees them (`GET connections/{id}/driveItems`,\n * page by page), to pick a root. A switch picks the top that is listed: the account's own drive, the shared drives it\n * is a member of (each added as a whole or opened to pick a folder in it), the folders shared with it; the trail\n * starts at that section and leads back up. Only folders and shared drives are offered: a folder opens, \"Add\" makes\n * it a root of this connection, \"Release\" shares it with the agent's own account; single files of a level are left\n * out. With the search switched on, a name of two characters or more lists the matching shared drives and folders of\n * every section instead (`GET connections/{id}/driveItems/search`), page by page; a result is added like a row of a\n * listing and opens as a folder.\n */\nconst DriveItemPicker = ({ connection, roots, releaseTargets, isItemSearchAvailable, isSharedDrivesSectionAvailable, supportedSearchFilters, onBack }: DriveItemPickerProps) => {\n const { t } = useTranslate();\n const confirm = useConfirm();\n const { api, writesAllowed, texts } = useAgentConnectionsContext();\n const [section, setSection] = useState<AgentConnectionDriveItemsSection>(\"MY_DRIVE\");\n const [trail, setTrail] = useState<DriveFolderStep[]>([]);\n const [pageTokens, setPageTokens] = useState<string[]>([]);\n const [releaseItem, setReleaseItem] = useState<AgentConnectionDriveItem | null>(null);\n const [searchText, setSearchText] = useState(\"\");\n const [searchPageTokens, setSearchPageTokens] = useState<string[]>([]);\n const [searchFilters, setSearchFilters] = useState<AgentConnectionDriveSearchFilters>(EMPTY_AGENT_CONNECTION_DRIVE_SEARCH_FILTERS);\n const [isFilterPanelOpen, setFilterPanelOpen] = useState(false);\n const filterPanelId = useId();\n // only what the server applies is sent; a place below a folder the trail left is dropped\n const searchFilterArgs = useMemo(() => agentConnectionDriveSearchFilterArgsOf(searchFilters, supportedSearchFilters), [searchFilters, supportedSearchFilters]);\n const activeFilterCount = countActiveAgentConnectionDriveSearchFilters(searchFilters, supportedSearchFilters);\n // an emptied field leaves the search at once, typing waits for a pause\n const settledSearchText = useDebouncedValue(searchText, 350, searchText.trim() === \"\");\n const searchQueryText = isItemSearchAvailable ? agentConnectionDriveSearchQueryOf(settledSearchText) : null;\n const isSearching = searchQueryText !== null;\n const folderId = trail[trail.length - 1]?.itemId ?? null;\n // the section names the top that is listed; below it the folder alone says what is asked for\n const folderQuery = api.useAgentConnectionDriveItemsQuery(\n { connectionId: connection.connectionId, section: folderId === null ? section : null, folderId, pageToken: pageTokens[pageTokens.length - 1] ?? null },\n { skip: isSearching },\n );\n const searchQuery = api.useSearchDriveItemsQuery(\n { connectionId: connection.connectionId, query: searchQueryText ?? \"\", pageToken: searchPageTokens[searchPageTokens.length - 1] ?? null, ...searchFilterArgs },\n { skip: !isSearching },\n );\n const query = isSearching ? searchQuery : folderQuery;\n const shownPageTokens = isSearching ? searchPageTokens : pageTokens;\n const setShownPageTokens = isSearching ? setSearchPageTokens : setPageTokens;\n const [addRoot, addState] = api.useAddAgentConnectionDriveRootMutation();\n const listedItems = query.currentData?.driveItems?.elements ?? null;\n // single files are not picked here: only folders and shared drives become roots in the picker\n const items = useMemo(() => (listedItems === null ? null : attachableAgentConnectionDriveItemsOf(listedItems)), [listedItems]);\n const nextPageToken = query.currentData?.driveItems?.nextPageToken ?? null;\n const isAgentOwned = connection.ownership === \"AGENT_OWNED\";\n const isSearchTextTooShort = isItemSearchAvailable && searchText.trim() !== \"\" && agentConnectionDriveSearchQueryOf(searchText) === null;\n const sections = agentConnectionDriveItemsSectionsOf(isSharedDrivesSectionAvailable);\n const sectionOptions = sections.map((value) => ({ value, label: AGENT_CONNECTION_DRIVE_ITEMS_SECTION_LABEL[value], context: AGENT_CONNECTION_DRIVE_CONTEXT }));\n // a page between others can hold no folder; only the whole top of a section is empty in the section's own words\n const isOnlyPage = shownPageTokens.length === 0 && nextPageToken === null;\n const emptyText = isSearching\n ? activeFilterCount > 0\n ? t(\"No folder or shared drive matches the name and the filters.\", { context: \"agent-connection-drive-search\" })\n : t(\"No folder or shared drive has a name with a word that begins like this.\")\n : folderId === null && isOnlyPage\n ? t(EMPTY_SECTION_TEXT[section])\n : t(\"No folders here.\");\n\n const handleSearchTextChange = (text: string) => {\n setSearchText(text);\n setSearchPageTokens([]);\n };\n\n const handleSearchFiltersChange = (filters: AgentConnectionDriveSearchFilters) => {\n setSearchFilters(filters);\n setSearchPageTokens([]);\n };\n\n // the places a search can stay below: the folders of the trail; one the trail left is no place any more\n const searchLocations = useMemo(() => trail.map((step) => ({ folderId: step.itemId, label: step.name })), [trail]);\n useEffect(() => {\n if (searchFilters.inFolderId !== null && !trail.some((step) => step.itemId === searchFilters.inFolderId)) setSearchFilters((current) => ({ ...current, inFolderId: null }));\n }, [trail, searchFilters.inFolderId]);\n\n // a folder opens below its section, also from a search result: the search ends\n const openFolder = (step: DriveFolderStep | null, depth: number) => {\n setTrail((current) => (step === null ? current.slice(0, depth) : [...current.slice(0, depth), step]));\n setPageTokens([]);\n handleSearchTextChange(\"\");\n };\n\n // another section starts at its top\n const handleSectionChange = (next: AgentConnectionDriveItemsSection) => {\n setSection(next);\n setTrail([]);\n setPageTokens([]);\n };\n\n const handleAdd = async (item: AgentConnectionDriveItem) => {\n if (!writesAllowed) return;\n const name = item.name || item.itemId;\n const confirmed = await confirm({\n title: t(\"Add “%name%”?\", { replacements: { name } }),\n description: t(\"%agentName% may use “%name%” and everything in it through this connection, at the level of the capability Files. Nothing outside the listed folders is read.\", {\n replacements: { agentName: texts.agentName, name },\n }),\n confirmLabel: t(\"Add\", { context: \"agent-connection-drive\" }),\n });\n if (!confirmed) return;\n try {\n await addRoot({ connectionId: connection.connectionId, itemId: item.itemId, releaseWay: isAgentOwned ? \"OWN_IDENTITY\" : \"PERSON_ROOT\" }).unwrap();\n notify.success(t(\"“%name%” added\", { replacements: { name } }));\n } catch (error) {\n notify.submitError(toFormSubmitError(error, t(\"The folder could not be added\")));\n }\n };\n\n return (\n <div className=\"space-y-4\" data-testid=\"agent-connection-drive-picker\">\n <div className=\"flex flex-wrap items-center gap-2\">\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" onClick={onBack}>\n <ArrowLeft aria-hidden />\n {t(\"Back to the folders of the connection\")}\n </Button>\n </div>\n {isItemSearchAvailable && (\n <div className=\"space-y-1.5\" data-testid=\"agent-connection-drive-search\">\n <div className=\"flex items-center gap-2\">\n <div className=\"min-w-0 flex-1\">\n <SearchField\n value={searchText}\n onChange={handleSearchTextChange}\n clearable\n size=\"sm\"\n maxLength={AGENT_CONNECTION_DRIVE_SEARCH_MAX_LENGTH}\n placeholder={t(\"Search folders and shared drives by name\")}\n aria-label={t(\"Search folders and shared drives by name\")}\n />\n </div>\n <AgentConnectionDriveSearchFilterToggle isOpen={isFilterPanelOpen} activeCount={activeFilterCount} controlsId={filterPanelId} onToggle={() => setFilterPanelOpen((current) => !current)} />\n </div>\n <p className=\"text-xs text-muted-foreground\">\n {isSearchTextTooShort\n ? t(\"Type at least %count% characters to search.\", { replacements: { count: AGENT_CONNECTION_DRIVE_SEARCH_MIN_LENGTH } })\n : t(\"The provider matches the beginnings of words in names: “off” finds “Offers 2027”, “fers” does not.\")}\n </p>\n {isFilterPanelOpen && (\n <AgentConnectionDriveSearchFiltersPanel\n id={filterPanelId}\n filters={searchFilters}\n onChange={handleSearchFiltersChange}\n supported={supportedSearchFilters}\n typeOptions={AGENT_CONNECTION_DRIVE_PICKER_SEARCH_TYPES}\n locations={searchLocations}\n fields={AGENT_CONNECTION_DRIVE_PICKER_SEARCH_FILTER_FIELDS}\n />\n )}\n {isAgentConnectionDriveSearchLeavingSharedDrivesOut(searchFilterArgs) && (\n <p className=\"text-xs text-muted-foreground\" data-testid=\"agent-connection-drive-search-no-shared-drives\">\n {t(\"Shared drives are left out while a date or place filter is set: the provider tells no dates or places for them.\", { context: \"agent-connection-drive-search\" })}\n </p>\n )}\n </div>\n )}\n {isSearching ? (\n <p className=\"text-sm font-medium\" data-testid=\"agent-connection-drive-search-results\">\n {t(\"Folders and shared drives matching “%query%”\", { replacements: { query: searchQueryText } })}\n </p>\n ) : (\n <>\n <div data-testid=\"agent-connection-drive-sections\">\n <SegmentedControl<AgentConnectionDriveItemsSection> aria-label={t(\"Part of the drive\")} value={section} onValueChange={handleSectionChange} options={sectionOptions} height={36} fullWidth />\n </div>\n <nav aria-label={t(\"Folder path\")} className=\"flex flex-wrap items-center gap-1 text-sm\">\n <button type=\"button\" className={cn(\"rounded px-1 font-medium hover:underline\", trail.length === 0 && \"text-foreground\")} onClick={() => openFolder(null, 0)}>\n {t(AGENT_CONNECTION_DRIVE_ITEMS_SECTION_LABEL[section], { context: AGENT_CONNECTION_DRIVE_CONTEXT })}\n </button>\n {trail.map((step, index) => (\n <span key={step.itemId} className=\"flex items-center gap-1\">\n <ChevronRight aria-hidden className=\"size-3.5 text-muted-foreground\" />\n <button type=\"button\" className=\"max-w-56 truncate rounded px-1 font-medium hover:underline\" onClick={() => openFolder(null, index + 1)}>\n {step.name}\n </button>\n </span>\n ))}\n </nav>\n </>\n )}\n {query.isError ? (\n <StatusCallout size=\"compact\" tone=\"destructive\" title={isSearching ? t(\"The search could not be run\") : t(\"The folder could not be listed\")} description={toFormSubmitError(query.error, \"\").message} />\n ) : items === null ? (\n <div className=\"space-y-2\">\n <Skeleton className=\"h-11 w-full\" />\n <Skeleton className=\"h-11 w-full\" />\n <Skeleton className=\"h-11 w-full\" />\n </div>\n ) : items.length === 0 ? (\n <p className=\"py-6 text-center text-sm text-muted-foreground\" data-testid=\"agent-connection-drive-picker-empty\">\n {emptyText}\n </p>\n ) : (\n <ul className=\"divide-y rounded-xl border\">\n {items.map((item) => {\n const itemKind = agentConnectionDriveItemKindOf(item);\n const KindIcon = DRIVE_KIND_ICON[itemKind] ?? Folder;\n const existingRoot = findAgentConnectionDriveRootOfItem(roots, item.itemId);\n const name = item.name || item.itemId;\n const canShare = canReleaseAgentConnectionDriveItemToAgent(item, isSearching);\n // a result of the search opens at the top of its section's trail, a row of a listing below its folder\n const open = () => openFolder({ itemId: item.itemId, name }, isSearching ? 0 : trail.length);\n // every row of the section \"Shared drives\" is one: the word is said only where kinds are mixed\n const isKindNamed = itemKind === \"SHARED_DRIVE\" && (isSearching || folderId !== null || section !== \"SHARED_DRIVES\");\n return (\n <li key={item.itemId} className=\"flex min-w-0 flex-wrap items-center gap-2 px-3 py-2\" data-drive-item={item.itemId} data-drive-item-kind={itemKind}>\n <KindIcon aria-hidden className=\"size-4 shrink-0 text-muted-foreground\" />\n <button type=\"button\" className=\"min-w-0 flex-1 truncate text-left text-sm font-medium hover:underline\" onClick={open}>\n {name}\n </button>\n {isKindNamed && <span className=\"shrink-0 text-xs text-muted-foreground\">{t(AGENT_CONNECTION_DRIVE_ROOT_KIND_LABEL.SHARED_DRIVE ?? \"\", { context: AGENT_CONNECTION_DRIVE_CONTEXT })}</span>}\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" aria-label={t(\"Open “%name%”\", { replacements: { name } })} onClick={open}>\n <FolderOpen aria-hidden />\n {t(\"Open\", { context: \"agent-connection-drive\" })}\n </Button>\n {existingRoot !== null ? (\n <StatusBadge value={existingRoot.status ?? null} map={AGENT_CONNECTION_DRIVE_ROOT_STATUS} />\n ) : (\n <span className=\"flex shrink-0 items-center gap-1.5\">\n {releaseTargets.length > 0 && (\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n disabled={!writesAllowed || !canShare}\n title={canShare ? undefined : itemKind === \"SHARED_DRIVE\" ? t(\"Releasing it needs the manager role of the shared drive.\") : t(\"The provider does not let you share this item.\")}\n onClick={() => setReleaseItem(item)}\n >\n <Share2 aria-hidden />\n {t(\"Release\", { context: \"agent-connection-drive\" })}\n </Button>\n )}\n <Button type=\"button\" variant=\"outline\" size=\"sm\" disabled={!writesAllowed || addState.isLoading} onClick={() => void handleAdd(item)}>\n {t(\"Add\", { context: \"agent-connection-drive\" })}\n </Button>\n </span>\n )}\n </li>\n );\n })}\n </ul>\n )}\n {(shownPageTokens.length > 0 || nextPageToken !== null) && (\n <div className=\"flex justify-between gap-2\">\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" disabled={shownPageTokens.length === 0} onClick={() => setShownPageTokens((current) => current.slice(0, -1))}>\n {t(\"Previous page\")}\n </Button>\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" disabled={nextPageToken === null} onClick={() => nextPageToken !== null && setShownPageTokens((current) => [...current, nextPageToken])}>\n {t(\"Next page\")}\n </Button>\n </div>\n )}\n <ReleaseToAgentDialog source={connection} item={releaseItem} targets={releaseTargets} onClose={() => setReleaseItem(null)} />\n </div>\n );\n};\n\nexport interface AgentConnectionDrivesDrawerProps {\n /** The connection whose drives and folders are open, `null` = closed. */\n connection: AgentConnectionSummary | null;\n /** Every connection the viewer sees: the names of releasing connections and the agent's own drive identities. */\n connections: readonly AgentConnectionSummary[];\n /** The root to scroll to and mark (a deep link). */\n highlightedDriveRootId: number | null;\n /**\n * EXTENSION POINT (item search): true shows the search field of the picker (folders and shared drives by name,\n * `GET connections/{id}/driveItems/search` through `useSearchDriveItemsQuery`). A host passes true once its backend\n * mounts that route; until then the picker only browses. Default false.\n */\n isItemSearchAvailable?: boolean;\n /**\n * EXTENSION POINT (shared drives): true shows the section \"Shared drives\" in the switch of the picker (the shared\n * drives the account is a member of, `GET connections/{id}/driveItems?section=SHARED_DRIVES`). A host passes true\n * once its backend lists them; until then the picker offers the account's own drive and what was shared with it.\n * Default false.\n */\n isSharedDrivesSectionAvailable?: boolean;\n /** \"What may the agent see?\" for this connection (`AgentConnectionDriveScopeDialog`); without it the drawer offers no button. */\n onOpenScope?: () => void;\n /** A request to open the picker (a changing number, e.g. a time stamp): \"Certain areas\" of that dialog was saved. */\n pickerRequest?: number | null;\n onClose: () => void;\n}\n\ninterface DriveRuleRootDetailsProps {\n root: AgentConnectionDriveRoot;\n resolution: AgentConnectionDriveRootRuleResolution | null;\n}\n\n/**\n * What a rule root covers now (`driveRootRuleResolutions` of the answer): \"automatic, now N shared drives\", and on\n * request the drives themselves (for the whole account the account's own drive first).\n */\nconst DriveRuleRootDetails = ({ root, resolution }: DriveRuleRootDetailsProps) => {\n const { t } = useTranslate();\n const [isExpanded, setExpanded] = useState(false);\n const items = wireElementsOf(resolution?.resolvedItems);\n const count = resolution?.resolvedDriveCount ?? null;\n if (root.status !== \"ACTIVE\") return null;\n return (\n <div className=\"mt-2 space-y-2\" data-testid=\"agent-connection-drive-rule-items\">\n <div className=\"flex flex-wrap items-center gap-2 text-xs text-muted-foreground\">\n <span>\n {count === null\n ? t(\"Automatic · the provider could not be asked just now\", { context: \"agent-connection-drive\" })\n : t(\"{count, plural, one {Automatic · now # shared drive} other {Automatic · now # shared drives}}\", { context: \"agent-connection-drive\", count })}\n </span>\n {items.length > 0 && (\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" aria-expanded={isExpanded} onClick={() => setExpanded((current) => !current)}>\n <ChevronRight aria-hidden className={cn(\"transition-transform\", isExpanded && \"rotate-90\")} />\n {isExpanded ? t(\"Hide the drives\", { context: \"agent-connection-drive\" }) : t(\"Show the drives\", { context: \"agent-connection-drive\" })}\n </Button>\n )}\n </div>\n {isExpanded && (\n <ul className=\"divide-y rounded-lg border bg-background\">\n {items.map((item) => {\n const isSharedDrive = item.driveId != null && item.driveId === item.itemId;\n const ItemIcon = isSharedDrive ? HardDrive : FolderOpen;\n return (\n <li key={item.itemId} className=\"flex min-w-0 items-center gap-2 px-3 py-1.5 text-sm\" data-rule-item={item.itemId}>\n <ItemIcon aria-hidden className=\"size-4 shrink-0 text-muted-foreground\" />\n <span className=\"min-w-0 flex-1 truncate\">{item.name || item.itemId}</span>\n <span className=\"shrink-0 text-xs text-muted-foreground\">\n {isSharedDrive ? t(\"Shared drive\", { context: \"agent-connection-drive\" }) : t(\"My Drive\", { context: \"agent-connection-drive\" })}\n </span>\n </li>\n );\n })}\n </ul>\n )}\n <p className=\"text-xs text-muted-foreground\">{t(\"Follows the sharing of the connection: it is not released to single spaces.\", { context: \"agent-connection-drive\" })}</p>\n </div>\n );\n};\n\n/**\n * \"Drives and folders\" of one drive connection: its roots (`GET connections/{id}/driveRoots`), the only places the\n * agent reaches through the connection: name, kind (shared drive, folder, file), how each came, the provider's role,\n * its status, and for an active root which agent spaces use it (`AgentConnectionDriveRootSpaces`). They are grouped\n * by kind, the shared drives first; the ended roots (revoked by a person, lost at the provider) stay listed below the\n * others of their group, greyed, with who and when. Whoever manages\n * the connection adds a root from the drive's folders, removes one, attaches an ended one again, has the provider\n * checked, and with the system right assigns the unassigned shares of the agent's own account and looks for new ones;\n * a release to the agent is taken back by the person who released it or with the system right. Every write is\n * confirmed with its effect and is off without write access.\n */\nexport const AgentConnectionDrivesDrawer = ({\n connection,\n connections,\n highlightedDriveRootId,\n isItemSearchAvailable = false,\n isSharedDrivesSectionAvailable = false,\n onOpenScope,\n pickerRequest = null,\n onClose,\n}: AgentConnectionDrivesDrawerProps) => {\n const { t } = useTranslate();\n const confirm = useConfirm();\n const { api, writesAllowed, viewer, texts } = useAgentConnectionsContext();\n const connectionId = connection?.connectionId;\n const query = api.useAgentConnectionDriveRootsQuery({ connectionId: connectionId ?? 0 }, { skip: connectionId === undefined });\n const [removeRoot, removeState] = api.useRemoveAgentConnectionDriveRootMutation();\n const [assignRoot, assignState] = api.useAssignAgentConnectionDriveRootMutation();\n const [revokeRelease, revokeState] = api.useRevokeAgentConnectionDriveReleaseMutation();\n const [discover, discoverState] = api.useDiscoverAgentConnectionDriveItemsMutation();\n const [addRoot, addState] = api.useAddAgentConnectionDriveRootMutation();\n const [checkRoots, checkState] = api.useCheckAgentConnectionDriveRootsMutation();\n const [isPicking, setIsPicking] = useState(false);\n\n // biome-ignore lint/correctness/useExhaustiveDependencies: another connection starts on its roots\n useEffect(() => {\n setIsPicking(false);\n }, [connectionId]);\n // after the reset above: a request of the host opens the picker\n useEffect(() => {\n if (pickerRequest !== null) setIsPicking(true);\n }, [pickerRequest]);\n\n const roots = useMemo(() => (connectionId === undefined ? null : query.currentData === undefined ? null : wireElementsOf(query.currentData.driveRoots)), [connectionId, query.currentData]);\n // by what they are at the provider, shared drives first; in a group the roots in use first, the ended ones below them\n const rootGroups = useMemo(() => (roots === null ? null : agentConnectionDriveRootGroupsOf(roots)), [roots]);\n const spaces = useMemo<AgentConnectionDriveSpaces>(\n () => ({\n releases: wireElementsOf(query.currentData?.driveRootReleases),\n releasableAgentSpaceIds: query.currentData?.releasableAgentSpaceIds ?? [],\n connectionAgentSpaceIds: query.currentData?.connectionAgentSpaceIds ?? [],\n agentSpaceLabels: wireElementsOf(query.currentData?.agentSpaceLabels),\n }),\n [query.currentData],\n );\n const accountLabels = query.currentData?.accountLabels == null ? null : wireElementsOf(query.currentData.accountLabels);\n const canManage = connection !== null && canManageAgentConnection(connection, viewer);\n const isAgentOwned = connection?.ownership === \"AGENT_OWNED\";\n const releaseTargets = useMemo(() => (connection === null ? [] : agentConnectionDriveReleaseTargetsOf(connection, connections, viewer)), [connection, connections, viewer]);\n const isBusy = removeState.isLoading || assignState.isLoading || revokeState.isLoading || discoverState.isLoading || addState.isLoading || checkState.isLoading;\n const usedRootCount = roots?.filter((root) => !isAgentConnectionDriveRootEnded(root)).length ?? 0;\n const agentName = texts.agentName;\n\n // the deep link's root: into view once its row is there\n useEffect(() => {\n if (connectionId === undefined || highlightedDriveRootId === null || roots === null || isPicking) return;\n document.getElementById(agentConnectionDriveRootDomId(connectionId, highlightedDriveRootId))?.scrollIntoView({ block: \"center\" });\n }, [connectionId, highlightedDriveRootId, roots, isPicking]);\n\n // a rule root is named by its kind (the stored name is the same English key)\n const nameOf = (root: AgentConnectionDriveRoot): string =>\n isAgentConnectionDriveRuleKind(root.rootKind) ? t(AGENT_CONNECTION_DRIVE_RULE_LABEL[root.rootKind], { context: AGENT_CONNECTION_DRIVE_CONTEXT }) : root.itemName || root.itemId || \"\";\n const supportedSearchFilters = useMemo(() => supportedAgentConnectionDriveSearchFiltersOf(query.currentData), [query.currentData]);\n const accountNameOf = (accountId: number): string => agentConnectionDriveLabelOf(accountLabels, accountId) ?? t(\"Account #%id%\", { replacements: { id: accountId } });\n\n const handleRemove = async (root: AgentConnectionDriveRoot) => {\n const ruleKind = isAgentConnectionDriveRuleKind(root.rootKind) ? root.rootKind : null;\n if (connectionId === undefined || !writesAllowed || (ruleKind === null && !root.itemId)) return;\n const name = nameOf(root);\n const confirmed = await confirm({\n title: t(\"Remove “%name%”?\", { replacements: { name } }),\n description:\n ruleKind !== null\n ? t(\"%agentName% loses the drives of “%name%” through this connection at once, except the ones you added on their own. Nothing at the provider is touched.\", { replacements: { agentName, name } })\n : t(\"%agentName% loses access to “%name%” through this connection at once. The folder itself and its files are not touched.\", { replacements: { agentName, name } }),\n confirmLabel: t(\"Remove\", { context: \"agent-connection-drive\" }),\n confirmVariant: \"destructive\",\n });\n if (!confirmed) return;\n try {\n await removeRoot(ruleKind !== null ? { connectionId, rootKind: ruleKind } : { connectionId, itemId: root.itemId ?? \"\" }).unwrap();\n notify.success(t(\"“%name%” removed\", { replacements: { name } }));\n } catch (error) {\n notify.submitError(toFormSubmitError(error, t(\"The folder could not be removed\")));\n }\n };\n\n const handleAssign = async (root: AgentConnectionDriveRoot) => {\n if (connectionId === undefined || !writesAllowed || !root.itemId) return;\n const name = nameOf(root);\n const confirmed = await confirm({\n title: t(\"Assign “%name%”?\", { replacements: { name } }),\n description: t(\"“%name%” was shared with %agentName%’s own account and nobody can use it yet. Assigned, %agentName% reaches it through this connection for everyone who may use the connection.\", {\n replacements: { agentName, name },\n }),\n confirmLabel: t(\"Assign\", { context: \"agent-connection-drive\" }),\n });\n if (!confirmed) return;\n try {\n await assignRoot({ connectionId, itemId: root.itemId }).unwrap();\n notify.success(t(\"“%name%” assigned\", { replacements: { name } }));\n } catch (error) {\n notify.submitError(toFormSubmitError(error, t(\"The item could not be assigned\")));\n }\n };\n\n const handleRevokeRelease = async (root: AgentConnectionDriveRoot) => {\n const driveRootId = agentConnectionDriveRootIdOf(root);\n if (driveRootId === null || !writesAllowed) return;\n const name = nameOf(root);\n const confirmed = await confirm({\n title: t(\"Take the release of “%name%” back?\", { replacements: { name } }),\n description: t(\"The share with %agentName%’s own account is deleted at the provider (while the releasing connection still works) and %agentName% loses “%name%” at once.\", { replacements: { agentName, name } }),\n confirmLabel: t(\"Take back\", { context: \"agent-connection-drive\" }),\n confirmVariant: \"destructive\",\n });\n if (!confirmed) return;\n try {\n const response = await revokeRelease({ driveRootId }).unwrap();\n // the server's sentence says whether the share at the provider could be deleted\n notify.success(response.note?.trim() || t(\"Release taken back\"));\n } catch (error) {\n notify.submitError(toFormSubmitError(error, t(\"The release could not be taken back\")));\n }\n };\n\n const handleDiscover = async () => {\n if (connectionId === undefined || !writesAllowed) return;\n const confirmed = await confirm({\n title: t(\"Look for new shares?\"),\n description: t(\"Items that were shared with %agentName%’s own account at the provider are listed here as unassigned. Nobody can use them until you assign them.\", { replacements: { agentName } }),\n confirmLabel: t(\"Look for shares\"),\n });\n if (!confirmed) return;\n const knownCount = roots?.length ?? 0;\n try {\n const response = await discover({ connectionId }).unwrap();\n const newCount = Math.max(0, wireElementsOf(response.driveRoots).length - knownCount);\n notify.success(newCount === 0 ? t(\"No new shares found\") : t(\"%count% new shares found, unassigned\", { replacements: { count: newCount } }));\n } catch (error) {\n notify.submitError(toFormSubmitError(error, t(\"The shares could not be read\")));\n }\n };\n\n const handleAttachAgain = async (root: AgentConnectionDriveRoot) => {\n const ruleKind = isAgentConnectionDriveRuleKind(root.rootKind) ? root.rootKind : null;\n if (connectionId === undefined || !writesAllowed || (ruleKind === null && !root.itemId)) return;\n const name = nameOf(root);\n const confirmed = await confirm({\n title: t(\"Attach “%name%” again?\", { replacements: { name } }),\n description:\n root.restrictedToAgentSpaces === true\n ? t(\"%agentName% uses “%name%” and everything in it through this connection again. It stays restricted: no space uses it until you release it to one again.\", { replacements: { agentName, name } })\n : t(\"%agentName% uses “%name%” and everything in it through this connection again, for everyone who may use the connection.\", { replacements: { agentName, name } }),\n confirmLabel: t(\"Attach again\", { context: \"agent-connection-drive\" }),\n });\n if (!confirmed) return;\n try {\n await addRoot(ruleKind !== null ? { connectionId, rootKind: ruleKind, releaseWay: agentConnectionDriveRootAttachWayOf(root) } : { connectionId, itemId: root.itemId ?? \"\", releaseWay: agentConnectionDriveRootAttachWayOf(root) }).unwrap();\n notify.success(t(\"“%name%” attached again\", { replacements: { name } }));\n } catch (error) {\n notify.submitError(toFormSubmitError(error, t(\"The folder could not be attached again\")));\n }\n };\n\n const handleCheck = async () => {\n if (connectionId === undefined || !writesAllowed) return;\n const confirmed = await confirm({\n title: t(\"Check the folders at the provider?\"),\n description: t(\"The provider is asked for every folder listed here. One it no longer has is marked “Lost at the provider” and %agentName% stops using it.\", { replacements: { agentName } }),\n confirmLabel: t(\"Check at the provider\"),\n });\n if (!confirmed) return;\n const lostCountOf = (list: readonly AgentConnectionDriveRoot[]) => list.filter((root) => root.status === \"LOST\").length;\n const knownLostCount = lostCountOf(roots ?? []);\n try {\n const response = await checkRoots({ connectionId }).unwrap();\n const newLostCount = Math.max(0, lostCountOf(wireElementsOf(response.driveRoots)) - knownLostCount);\n notify.success(newLostCount === 0 ? t(\"Every folder is still there at the provider\") : t(\"%count% folders are lost at the provider\", { replacements: { count: newLostCount } }));\n } catch (error) {\n notify.submitError(toFormSubmitError(error, t(\"The folders could not be checked at the provider\")));\n }\n };\n\n const name = agentConnectionNameOf(connection);\n\n return (\n <FormDrawer\n open={connection !== null}\n onClose={onClose}\n title={\n <span className=\"flex items-center gap-3\">\n <ProviderMark provider={connection?.provider} size=\"sm\" />\n <span className=\"min-w-0\">\n <span className=\"block\">{t(\"Drives and folders\", { context: \"agent-connection\" })}</span>\n <span className=\"block truncate text-sm font-normal text-muted-foreground\">{[name, connection?.externalAddress].filter(Boolean).join(\" · \")}</span>\n </span>\n </span>\n }\n >\n <div className=\"space-y-5\" data-testid=\"agent-connection-drives-drawer\">\n {connection !== null && isPicking && roots !== null ? (\n <DriveItemPicker\n connection={connection}\n roots={roots}\n releaseTargets={releaseTargets}\n isItemSearchAvailable={isItemSearchAvailable}\n isSharedDrivesSectionAvailable={isSharedDrivesSectionAvailable}\n supportedSearchFilters={supportedSearchFilters}\n onBack={() => setIsPicking(false)}\n />\n ) : (\n <>\n <p className=\"text-sm text-muted-foreground\">\n {t(\"The shared drives and folders %agentName% reaches through this connection. Nothing outside them is listed, searched or read.\", { replacements: { agentName } })}\n </p>\n {query.isError ? (\n <StatusCallout size=\"compact\" tone=\"destructive\" title={t(\"The folders could not be loaded\")} description={toFormSubmitError(query.error, \"\").message} />\n ) : rootGroups === null ? (\n <div className=\"space-y-2\">\n <Skeleton className=\"h-16 w-full\" />\n <Skeleton className=\"h-16 w-full\" />\n </div>\n ) : rootGroups.length === 0 ? (\n <div className=\"flex flex-col items-center gap-2 rounded-2xl border border-dashed px-6 py-8 text-center\">\n <HardDrive aria-hidden className=\"size-7 text-muted-foreground\" />\n <p className=\"text-sm font-medium\">{t(\"No folder yet\")}</p>\n <p className=\"max-w-md text-sm text-muted-foreground\">{t(\"Without a folder %agentName% reads no file of this drive. Add the shared drives and folders it should work in.\", { replacements: { agentName } })}</p>\n </div>\n ) : (\n <div className=\"space-y-4\">\n {rootGroups.map((group) => (\n <section key={group.kind} className=\"space-y-2\" data-drive-root-group={group.kind}>\n <h3 className=\"text-sm font-medium text-muted-foreground\">{t(AGENT_CONNECTION_DRIVE_ROOT_GROUP_LABEL[group.kind], { context: AGENT_CONNECTION_DRIVE_CONTEXT })}</h3>\n <ul className=\"space-y-2\">\n {group.roots.map((root) => {\n const driveRootId = agentConnectionDriveRootIdOf(root);\n const hasEnded = isAgentConnectionDriveRootEnded(root);\n const isRule = group.kind === \"RULE\";\n const KindIcon = isRule ? Layers : (DRIVE_KIND_ICON[root.rootKind ?? \"\"] ?? Folder);\n const kindLabel = isRule ? undefined : AGENT_CONNECTION_DRIVE_ROOT_KIND_LABEL[root.rootKind ?? \"\"];\n const actions = connection === null ? null : agentConnectionDriveRootActionsOf(root, connection, viewer);\n const isHighlighted = highlightedDriveRootId !== null && driveRootId === highlightedDriveRootId;\n const source = root.sourceAgentConnectionId != null ? (connections.find((entry) => entry.connectionId === root.sourceAgentConnectionId) ?? null) : null;\n const wayLabel = AGENT_CONNECTION_DRIVE_ROOT_WAY_LABEL[root.releaseWay ?? \"\"];\n const roleLabel = AGENT_CONNECTION_DRIVE_ROLE_LABEL[root.providerRole ?? \"\"];\n // a rule says what it stands for; an item how it came, from where and the provider's role\n const facts = isRule\n ? [root.rootKind === \"WHOLE_ACCOUNT\" ? t(\"My Drive and every shared drive, new ones automatically\", { context: \"agent-connection-drive\" }) : t(\"Every shared drive, new ones automatically\", { context: \"agent-connection-drive\" })]\n : [\n wayLabel !== undefined ? t(wayLabel, { context: AGENT_CONNECTION_DRIVE_CONTEXT, replacements: { agentName } }) : (root.releaseWay ?? null),\n source !== null ? t(\"from “%name%”\", { context: \"agent-connection-drive\", replacements: { name: agentConnectionNameOf(source) } }) : null,\n root.providerRole ? (roleLabel !== undefined ? t(roleLabel, { context: AGENT_CONNECTION_DRIVE_CONTEXT }) : root.providerRole) : null,\n ].filter(Boolean);\n return (\n <li\n key={root.itemId || `${root.rootKind ?? \"\"}-${String(root.id)}`}\n id={connectionId !== undefined && driveRootId !== null ? agentConnectionDriveRootDomId(connectionId, driveRootId) : undefined}\n className={cn(\"min-w-0 rounded-xl border p-3\", hasEnded ? \"bg-muted/40\" : \"bg-card\", isHighlighted && \"ring-2 ring-brand-emphasis\")}\n data-drive-root={driveRootId ?? undefined}\n data-drive-root-status={root.status ?? undefined}\n data-highlighted={isHighlighted ? \"\" : undefined}\n >\n <div className=\"flex min-w-0 flex-wrap items-center gap-3\">\n <KindIcon aria-hidden className={cn(\"size-5 shrink-0 text-muted-foreground\", hasEnded && \"opacity-60\")} />\n <div className=\"min-w-0 flex-1 basis-48\">\n <p className={cn(\"truncate text-sm font-semibold\", hasEnded && \"text-muted-foreground\")} title={nameOf(root)}>\n {nameOf(root)}\n </p>\n <p className=\"truncate text-xs text-muted-foreground\" title={facts.join(\" · \")}>\n {facts.join(\" · \")}\n </p>\n </div>\n {kindLabel !== undefined && <StatusBadge tone=\"neutral\" label={t(kindLabel, { context: AGENT_CONNECTION_DRIVE_CONTEXT })} />}\n <StatusBadge value={root.status ?? null} map={AGENT_CONNECTION_DRIVE_ROOT_STATUS} />\n {actions !== null && (actions.canAssign || actions.canRevokeRelease || actions.canRemove || actions.canAttachAgain) && (\n <span className=\"flex shrink-0 items-center gap-1.5\">\n {actions.canAttachAgain && (\n <Button type=\"button\" variant=\"outline\" size=\"sm\" disabled={!writesAllowed || isBusy} onClick={() => void handleAttachAgain(root)}>\n {t(\"Attach again\", { context: \"agent-connection-drive\" })}\n </Button>\n )}\n {actions.canAssign && (\n <Button type=\"button\" size=\"sm\" disabled={!writesAllowed || isBusy} onClick={() => void handleAssign(root)}>\n {t(\"Assign\", { context: \"agent-connection-drive\" })}\n </Button>\n )}\n {actions.canRevokeRelease && (\n <Button type=\"button\" variant=\"outline\" size=\"sm\" disabled={!writesAllowed || isBusy} onClick={() => void handleRevokeRelease(root)}>\n {t(\"Take back\", { context: \"agent-connection-drive\" })}\n </Button>\n )}\n {actions.canRemove && (\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" disabled={!writesAllowed || isBusy} onClick={() => void handleRemove(root)}>\n {t(\"Remove\", { context: \"agent-connection-drive\" })}\n </Button>\n )}\n </span>\n )}\n </div>\n {hasEnded && (\n <div className=\"mt-2 space-y-1 text-xs text-muted-foreground\" data-testid=\"agent-connection-drive-root-ended\">\n <p>\n <span>\n {root.status === \"LOST\"\n ? t(\"The provider no longer has it; noticed at a check\")\n : root.revokedByAccountId != null\n ? t(\"Revoked by %name%\", { replacements: { name: accountNameOf(root.revokedByAccountId) } })\n : t(\"Revoked; %agentName% no longer uses it\", { replacements: { agentName } })}\n </span>\n {root.revokedAt != null && (\n <>\n {\" · \"}\n <AgentConnectionRelativeTime value={root.revokedAt} fallback=\"\" />\n </>\n )}\n </p>\n {root.releaseWay === \"RELEASED_TO_AGENT\" && <p>{t(\"To bring it back, release it to %agentName% again from the connection it came from.\", { replacements: { agentName } })}</p>}\n </div>\n )}\n {isRule && <DriveRuleRootDetails root={root} resolution={agentConnectionDriveRuleResolutionOf(query.currentData, root)} />}\n {!isRule && root.status === \"ACTIVE\" && connection !== null && actions !== null && <AgentConnectionDriveRootSpaces root={root} connection={connection} actions={actions} spaces={spaces} />}\n </li>\n );\n\n })}\n </ul>\n </section>\n ))}\n </div>\n )}\n {canManage && (\n <div className=\"flex flex-wrap gap-2 border-t pt-4\">\n {onOpenScope !== undefined && (\n <Button type=\"button\" variant=\"outline\" disabled={roots === null} onClick={onOpenScope} data-testid=\"agent-connection-drive-scope-open\">\n <Eye aria-hidden />\n {t(\"What may %agentName% see?\", { replacements: { agentName } })}\n </Button>\n )}\n <Button type=\"button\" disabled={!writesAllowed || roots === null} onClick={() => setIsPicking(true)} data-testid=\"agent-connection-drive-add\">\n <FolderPlus aria-hidden />\n {t(\"Add a folder or shared drive\")}\n </Button>\n <Button type=\"button\" variant=\"outline\" disabled={!writesAllowed || isBusy || usedRootCount === 0} onClick={() => void handleCheck()} data-testid=\"agent-connection-drive-check\">\n <SearchCheck aria-hidden />\n {t(\"Check at the provider\")}\n </Button>\n {isAgentOwned && viewer.mayManageSystemConnections && (\n <Button type=\"button\" variant=\"outline\" disabled={!writesAllowed || isBusy} onClick={() => void handleDiscover()}>\n <RefreshCw aria-hidden />\n {t(\"Look for shares\")}\n </Button>\n )}\n </div>\n )}\n {!canManage && connection !== null && <p className=\"text-xs text-muted-foreground\">{t(\"Only whoever manages this connection changes its folders.\")}</p>}\n </>\n )}\n </div>\n </FormDrawer>\n );\n};\n","import { FormActions, FormDrawer, FormErrors } from \"@mgamadeus/ddd-admin-ui/form\";\nimport { useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { type FormSubmitError, notify, toFormSubmitError } from \"@mgamadeus/ddd-admin-ui/logic\";\nimport { Button, cn, SegmentedControl, Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { Check, ShieldAlert, Sparkles } from \"lucide-react\";\nimport { useEffect, useMemo, useState } from \"react\";\nimport {\n AGENT_CONNECTION_CAPABILITY_CONTEXT,\n AGENT_CONNECTION_CAPABILITY_LABEL,\n AGENT_CONNECTION_LEVEL_CONTEXT,\n AGENT_CONNECTION_LEVEL_LABEL,\n AGENT_CONNECTION_LEVELS,\n agentConnectionLevelRank,\n agentConnectionLevelToneClass,\n agentConnectionNameOf,\n agentConnectionVisibilityOf,\n isAgentConnectionConsentRequiredMessage,\n isAgentConnectionLevel,\n parseAgentConnectionLevels,\n} from \"./agent-connection-format\";\nimport { useAgentConnectionLevelHelp, useAgentConnectionsContext, useAgentConnectionVisibilityOptions } from \"./agent-connections-context\";\nimport type { AgentConnectionCapability, AgentConnectionLevel, AgentConnectionSummary, AgentConnectionVisibility } from \"./agent-connections-types\";\nimport { CapabilityIcon, ProviderMark } from \"./connection-logos\";\nimport { useAgentConnect } from \"./use-agent-connect\";\n\n/** The server refused a level whose scopes the provider has not granted. */\nconst isConsentRequired = (error: unknown): boolean => isAgentConnectionConsentRequiredMessage(toFormSubmitError(error, \"\").message);\n\ninterface AgentConnectionLevelsDrawerProps {\n /** The connection being edited, `null` = closed. */\n connection: AgentConnectionSummary | null;\n /**\n * A capability and level the agent suggests (a deep link from the chat): shown as a suggestion beside the saved\n * level, saved only with its own \"Apply\"; the choice keeps the saved level.\n */\n preset?: { capability: AgentConnectionCapability; level: AgentConnectionLevel } | null;\n onClose: () => void;\n}\n\n/**\n * \"Change levels\": per capability the level the agent works with (the order by power, each level includes the ones\n * before it; the line under the choice says what it allows), and who sees the connection. Only what changed is sent:\n * the visibility with `POST connections/{id}/settings`, each changed level with `POST connections/{id}/level`. On a\n * Google connection a level above the current grant is marked and saved through Google's consent (\"Save and ask\n * Google\").\n *\n * Opened with a suggestion, the row of its capability carries it: the saved level and the suggested one with its own\n * \"Apply\", which saves that one level at once (Google: through the consent when the grant does not cover it). A check\n * in the level list only ever marks the saved level; a chosen but unsaved level names the saved one beside it.\n */\nexport const AgentConnectionLevelsDrawer = ({ connection, preset = null, onClose }: AgentConnectionLevelsDrawerProps) => {\n const { t } = useTranslate();\n const { api, writesAllowed, sharedAgentSpaceId, texts } = useAgentConnectionsContext();\n const visibilityOptions = useAgentConnectionVisibilityOptions();\n const levelHelp = useAgentConnectionLevelHelp();\n const [saveSettings, settingsState] = api.useUpdateAgentConnectionSettingsMutation();\n const [saveLevel, levelState] = api.useSetAgentConnectionLevelMutation();\n const [submitError, setSubmitError] = useState<FormSubmitError | null>(null);\n const connect = useAgentConnect();\n const connectionId = connection?.connectionId;\n // What Google's current grant covers per capability (`grantedLevels`; Google only: a connect asks for read scopes, a\n // higher level needs a consent first).\n const isGoogle = connection?.provider === \"GOOGLE\";\n const { currentData: detail } = api.useAgentConnectionQuery({ connectionId: connectionId ?? 0 }, { skip: connectionId === undefined || !isGoogle });\n const grantedLevelOf = useMemo(() => {\n const granted = new Map<string, AgentConnectionLevel>();\n for (const entry of detail?.grantedLevels ?? []) {\n if (entry.capability !== undefined && entry.level !== undefined && isAgentConnectionLevel(entry.level)) granted.set(entry.capability, entry.level);\n }\n return granted;\n }, [detail]);\n /** The level needs Google's consent first: above what the grant covers (nothing granted = only OFF is free). */\n const needsConsent = (capability: AgentConnectionCapability, level: AgentConnectionLevel): boolean => {\n if (!isGoogle || detail === undefined || level === \"OFF\") return false;\n const granted = grantedLevelOf.get(capability);\n return granted === undefined || agentConnectionLevelRank(level) > agentConnectionLevelRank(granted);\n };\n\n const initialVisibility = agentConnectionVisibilityOf(connection);\n // The connection's capabilities, plus the preset's when the connection does not list it yet (a new capability: off).\n const initialLevels = useMemo(() => {\n const parsed = parseAgentConnectionLevels(connection?.levels);\n if (preset === null || parsed.some((entry) => entry.capability === preset.capability)) return parsed;\n return [...parsed, { capability: preset.capability, level: \"OFF\" as const }];\n }, [connection?.levels, preset]);\n const [visibility, setVisibility] = useState<AgentConnectionVisibility>(initialVisibility);\n const [levels, setLevels] = useState<Partial<Record<AgentConnectionCapability, AgentConnectionLevel>>>({});\n const [isSuggestionApplied, setSuggestionApplied] = useState(false);\n\n useEffect(() => {\n if (connection === null) return;\n setVisibility(initialVisibility);\n setLevels(Object.fromEntries(initialLevels.map((entry) => [entry.capability, entry.level])));\n setSubmitError(null);\n }, [connection, initialVisibility, initialLevels]);\n // a new suggestion or connection shows the suggestion again\n // biome-ignore lint/correctness/useExhaustiveDependencies: the dependencies are the triggers\n useEffect(() => {\n setSuggestionApplied(false);\n }, [preset, connectionId]);\n\n const savedLevelOf = (capability: AgentConnectionCapability): AgentConnectionLevel => initialLevels.find((entry) => entry.capability === capability)?.level ?? \"OFF\";\n /** The suggestion while it is above the saved level and was not applied here. */\n const suggestion = preset !== null && !isSuggestionApplied && agentConnectionLevelRank(preset.level) > agentConnectionLevelRank(savedLevelOf(preset.capability)) ? preset : null;\n /** The suggestion the saved level already covers (an older chat button): the row says so instead of offering it. */\n const coveredSuggestion = preset !== null && !isSuggestionApplied && agentConnectionLevelRank(preset.level) <= agentConnectionLevelRank(savedLevelOf(preset.capability)) ? preset : null;\n\n const isSystemConnection = connection?.ownership === \"AGENT_OWNED\";\n const visibilityChanged = visibility !== initialVisibility;\n const changedLevels = initialLevels.filter((entry) => {\n const level = levels[entry.capability];\n return level !== undefined && level !== entry.level;\n });\n const isDirty = visibilityChanged || changedLevels.length > 0;\n const consentLevels = changedLevels.flatMap((entry) => {\n const level = levels[entry.capability];\n return level !== undefined && needsConsent(entry.capability, level) ? [{ capability: entry.capability, level }] : [];\n });\n const isPending = settingsState.isLoading || levelState.isLoading || connect.isPending;\n const levelLabel = (level: AgentConnectionLevel) => t(AGENT_CONNECTION_LEVEL_LABEL[level], { context: AGENT_CONNECTION_LEVEL_CONTEXT });\n\n /**\n * \"Apply\": saves the suggested level alone (`POST level`), or asks Google first when the grant does not cover it\n * (also when the server answers `consent_required:`). Other unsaved changes in the drawer stay as they are.\n */\n const applySuggestion = async () => {\n if (connectionId === undefined || suggestion === null || !writesAllowed) return;\n const request = { capability: suggestion.capability, level: suggestion.level };\n setSubmitError(null);\n try {\n if (needsConsent(request.capability, request.level)) {\n await connect.extend(\"GOOGLE\", connectionId, [request]);\n return;\n }\n try {\n await saveLevel({ connectionId, ...request }).unwrap();\n } catch (error) {\n if (!isGoogle || !isConsentRequired(error)) throw error;\n await connect.extend(\"GOOGLE\", connectionId, [request]);\n return;\n }\n setSuggestionApplied(true);\n setLevels((current) => ({ ...current, [request.capability]: request.level }));\n notify.success(t(\"Level saved\", { context: \"agent-connection\" }));\n } catch (error) {\n const failure = toFormSubmitError(error, t(\"The level could not be saved\"));\n setSubmitError(failure);\n notify.submitError(failure);\n }\n };\n\n /**\n * Saves in this order: the visibility, the levels the grant covers (`POST level`), then, when a level needs more\n * scopes, Google's consent for those (`POST oauth/google/start` with `connectionId` + `requestedLevels`; the browser\n * leaves, the callback sets them). A level the server refuses with `consent_required:` (the grant changed since the\n * drawer read it) joins the consent.\n */\n const handleSubmit = async () => {\n if (connectionId === undefined || !writesAllowed || !isDirty) return;\n setSubmitError(null);\n try {\n if (visibilityChanged) {\n await saveSettings({ connectionId, visibility, targetAgentSpaceId: visibility === \"AGENT_SPACE\" ? sharedAgentSpaceId : null }).unwrap();\n }\n const toConsent = [...consentLevels];\n for (const entry of changedLevels) {\n const level = levels[entry.capability];\n if (level === undefined || toConsent.some((consent) => consent.capability === entry.capability)) continue;\n try {\n await saveLevel({ connectionId, capability: entry.capability, level }).unwrap();\n } catch (error) {\n if (!isGoogle || !isConsentRequired(error)) throw error;\n toConsent.push({ capability: entry.capability, level });\n }\n }\n if (toConsent.length > 0) {\n await connect.extend(\"GOOGLE\", connectionId, toConsent);\n return;\n }\n notify.success(t(\"Connection saved\"));\n onClose();\n } catch (error) {\n const failure = toFormSubmitError(error, t(\"The connection could not be saved\"));\n setSubmitError(failure);\n notify.submitError(failure);\n }\n };\n\n const name = agentConnectionNameOf(connection);\n const consentNote = (\n <p className=\"flex items-center gap-1.5 text-xs font-medium text-warning\">\n <ShieldAlert aria-hidden className=\"size-3.5 shrink-0\" />\n {t(\"Needs your consent at Google\")}\n </p>\n );\n\n return (\n <FormDrawer\n open={connection !== null}\n onClose={onClose}\n title={\n <span className=\"flex items-center gap-3\">\n <ProviderMark provider={connection?.provider} size=\"sm\" />\n <span className=\"min-w-0\">\n <span className=\"block\">{t(\"Change levels\")}</span>\n <span className=\"block truncate text-sm font-normal text-muted-foreground\">{[name, connection?.externalAddress].filter(Boolean).join(\" · \")}</span>\n </span>\n </span>\n }\n >\n <form\n className=\"space-y-5\"\n onSubmit={(event) => {\n event.preventDefault();\n event.stopPropagation();\n void handleSubmit();\n }}\n >\n <FormErrors error={submitError} />\n <ul className=\"divide-y\">\n {initialLevels.map((entry) => {\n const level = levels[entry.capability] ?? entry.level;\n const savedLevel = entry.level;\n const rowSuggestion = suggestion?.capability === entry.capability ? suggestion : null;\n const capabilityLabel = t(AGENT_CONNECTION_CAPABILITY_LABEL[entry.capability], { context: AGENT_CONNECTION_CAPABILITY_CONTEXT });\n return (\n <li\n key={entry.capability}\n className={cn(\"grid gap-2 py-4 first:pt-0 sm:grid-cols-[9rem_1fr] sm:items-start\", rowSuggestion !== null && \"rounded-lg bg-brand-light/40 px-2 first:pt-4\")}\n data-suggestion={rowSuggestion !== null ? \"\" : undefined}\n >\n <span className=\"flex items-center gap-2 pt-2 font-semibold\">\n <CapabilityIcon provider={connection?.provider} capability={entry.capability} />\n {capabilityLabel}\n </span>\n <div className=\"space-y-1.5\">\n <Select\n name={`level-${entry.capability}`}\n value={level}\n onValueChange={(value) => {\n if (isAgentConnectionLevel(value)) setLevels((current) => ({ ...current, [entry.capability]: value }));\n }}\n >\n <SelectTrigger className=\"w-full\" aria-label={capabilityLabel}>\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {AGENT_CONNECTION_LEVELS.map((option) => (\n <SelectItem key={option} value={option} className={option !== savedLevel ? \"[&>[data-slot=select-item-indicator]]:hidden\" : undefined}>\n {levelLabel(option)}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <p className=\"text-xs text-muted-foreground\">{levelHelp(level)}</p>\n {level !== savedLevel && (\n <p className=\"text-xs text-muted-foreground\" data-testid=\"connection-level-current\">\n {t(\"Current: %level%\", { context: \"agent-connection-level\", replacements: { level: levelLabel(savedLevel) } })}\n </p>\n )}\n {needsConsent(entry.capability, level) && consentNote}\n {coveredSuggestion?.capability === entry.capability && (\n <p className=\"flex items-center gap-1.5 text-xs text-muted-foreground\" data-testid=\"connection-level-suggestion-covered\">\n <Check aria-hidden className=\"size-3.5 shrink-0 text-success\" />\n {t(\"%agentName%'s suggestion (%level%) is already covered.\", {\n context: \"agent-connection-level\",\n replacements: { agentName: texts.agentName, level: levelLabel(coveredSuggestion.level) },\n })}\n </p>\n )}\n {rowSuggestion !== null && (\n <div className=\"mt-3 space-y-2 rounded-lg border border-brand-emphasis/50 bg-card p-3\" data-testid=\"connection-level-suggestion\">\n <p className=\"flex items-center gap-1.5 text-sm\">\n <Sparkles aria-hidden className=\"size-4 shrink-0 text-brand-emphasis\" />\n <span>\n {t(\"Suggestion\", { context: \"agent-connection-level\" })}: <span className={cn(\"font-semibold\", agentConnectionLevelToneClass(rowSuggestion.level))}>{levelLabel(rowSuggestion.level)}</span>\n </span>\n </p>\n <p className=\"text-xs text-muted-foreground\">{levelHelp(rowSuggestion.level)}</p>\n <p className=\"text-xs text-muted-foreground\">{t(\"Current: %level%\", { context: \"agent-connection-level\", replacements: { level: levelLabel(savedLevel) } })}</p>\n {needsConsent(rowSuggestion.capability, rowSuggestion.level) && consentNote}\n <Button type=\"button\" size=\"sm\" onClick={() => void applySuggestion()} disabled={!writesAllowed || isPending} data-testid=\"connection-level-suggestion-apply\">\n {needsConsent(rowSuggestion.capability, rowSuggestion.level) ? t(\"Apply and ask Google\", { context: \"agent-connection-suggestion\" }) : t(\"Apply\", { context: \"agent-connection-suggestion\" })}\n </Button>\n </div>\n )}\n </div>\n </li>\n );\n })}\n </ul>\n <div className=\"grid gap-2 border-t pt-4 sm:grid-cols-[9rem_1fr] sm:items-start\">\n <span className=\"pt-2 font-semibold\">{t(\"Visible to\", { context: \"agent-connection\" })}</span>\n <div className=\"space-y-1.5\">\n <SegmentedControl\n aria-label={t(\"Visible to\", { context: \"agent-connection\" })}\n value={visibility}\n onValueChange={setVisibility}\n options={visibilityOptions.map((option) => {\n if (option.value === \"OWNER_ONLY\" && isSystemConnection) return { ...option, disabled: true };\n if (option.value === \"AGENT_SPACE\" && sharedAgentSpaceId === null) return { ...option, disabled: true };\n return option;\n })}\n height={36}\n />\n <p className=\"text-xs text-muted-foreground\">{texts.sharedVisibilityHelp}</p>\n </div>\n </div>\n <FormActions\n isDirty={isDirty}\n secondary={\n <Button type=\"button\" variant=\"outline\" onClick={onClose} disabled={isPending}>\n {t(\"Cancel\")}\n </Button>\n }\n primary={\n <Button type=\"submit\" disabled={!writesAllowed || !isDirty || isPending}>\n {isPending ? t(\"Saving…\") : consentLevels.length > 0 ? t(\"Save and ask Google\") : t(\"Save\")}\n </Button>\n }\n />\n </form>\n </FormDrawer>\n );\n};\n","import { FormDialog, FormErrors } from \"@mgamadeus/ddd-admin-ui/form\";\nimport { useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { type FormSubmitError, notify, toFormSubmitError } from \"@mgamadeus/ddd-admin-ui/logic\";\nimport { SegmentedControl } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { useEffect, useState } from \"react\";\nimport { agentConnectionVisibilityOf } from \"./agent-connection-format\";\nimport { useAgentConnectionsContext, useAgentConnectionVisibilityOptions } from \"./agent-connections-context\";\nimport type { AgentConnectionSummary, AgentConnectionVisibility } from \"./agent-connections-types\";\n\ninterface AgentConnectionSharingDialogProps {\n /** The connection whose sharing is open, `null` = closed. */\n connection: AgentConnectionSummary | null;\n onClose: () => void;\n}\n\n/**\n * \"Sharing\": who may let the agent use the connection: only its owner, or everyone working in the shared space (a\n * release to that space, read only at first). Sends the visibility alone (`POST connections/{id}/settings`).\n */\nexport const AgentConnectionSharingDialog = ({ connection, onClose }: AgentConnectionSharingDialogProps) => {\n const { t } = useTranslate();\n const { api, writesAllowed, sharedAgentSpaceId, texts } = useAgentConnectionsContext();\n const visibilityOptions = useAgentConnectionVisibilityOptions();\n const initial = agentConnectionVisibilityOf(connection);\n const [visibility, setVisibility] = useState<AgentConnectionVisibility>(initial);\n const [submitError, setSubmitError] = useState<FormSubmitError | null>(null);\n const [saveSettings, saveState] = api.useUpdateAgentConnectionSettingsMutation();\n\n useEffect(() => {\n if (connection === null) return;\n setVisibility(initial);\n setSubmitError(null);\n }, [connection, initial]);\n\n const handleSubmit = async () => {\n if (connection === null || !writesAllowed || visibility === initial) return;\n setSubmitError(null);\n try {\n await saveSettings({ connectionId: connection.connectionId, visibility, targetAgentSpaceId: visibility === \"AGENT_SPACE\" ? sharedAgentSpaceId : null }).unwrap();\n notify.success(visibility === \"AGENT_SPACE\" ? texts.sharedToast : t(\"Only you see it now\"));\n onClose();\n } catch (error) {\n const failure = toFormSubmitError(error, t(\"The connection could not be saved\"));\n setSubmitError(failure);\n notify.submitError(failure);\n }\n };\n\n return (\n <FormDialog\n open={connection !== null}\n onOpenChange={(open) => {\n if (!open) onClose();\n }}\n title={t(\"Sharing\", { context: \"agent-connection\" })}\n description={connection?.name ?? undefined}\n submitLabel={t(\"Save\")}\n pendingLabel={t(\"Saving…\")}\n isPending={saveState.isLoading}\n isDirty={visibility !== initial}\n submitDisabled={!writesAllowed || visibility === initial}\n onSubmit={(event) => {\n event.preventDefault();\n event.stopPropagation();\n void handleSubmit();\n }}\n >\n <div className=\"space-y-3\">\n <FormErrors error={submitError} />\n <SegmentedControl\n aria-label={t(\"Visible to\", { context: \"agent-connection\" })}\n value={visibility}\n onValueChange={setVisibility}\n options={visibilityOptions.map((option) => {\n if (option.value === \"OWNER_ONLY\" && connection?.ownership === \"AGENT_OWNED\") return { ...option, disabled: true };\n if (option.value === \"AGENT_SPACE\" && sharedAgentSpaceId === null) return { ...option, disabled: true };\n return option;\n })}\n height={36}\n fullWidth\n />\n <p className=\"text-sm text-muted-foreground\">{texts.sharedVisibilityHelp}</p>\n </div>\n </FormDialog>\n );\n};\n","import { FormDialog, FormErrors, FormFieldFrame } from \"@mgamadeus/ddd-admin-ui/form\";\nimport { useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { type FormSubmitError, notify, toFormSubmitError } from \"@mgamadeus/ddd-admin-ui/logic\";\nimport { cn, Input, SegmentedControl } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { Check } from \"lucide-react\";\nimport { useEffect, useState } from \"react\";\nimport { AGENT_CONNECTION_CAPABILITY_CONTEXT, AGENT_CONNECTION_CAPABILITY_LABEL, agentConnectionPortOf, GOOGLE_CONNECT_CAPABILITIES } from \"./agent-connection-format\";\nimport { useAgentConnectionsContext, useAgentConnectionVisibilityOptions } from \"./agent-connections-context\";\nimport type { AgentConnectionCapability, AgentConnectionVisibility } from \"./agent-connections-types\";\nimport { CapabilityIcon, ProviderLogo } from \"./connection-logos\";\nimport { useAgentConnect } from \"./use-agent-connect\";\n\ninterface ConnectDialogProps {\n open: boolean;\n onOpenChange: (open: boolean) => void;\n}\n\n/**\n * \"Connect Google\": a name, what Google is asked for (Gmail, Calendar, Contacts, Drive; all by default) and who sees\n * the connection, all sent with the start; then Google's consent. Google returns to the host's return route with\n * `?connected=<id>` (or `?connectError=`); the panel of the surface that started it tells the outcome.\n */\nexport const ConnectGoogleDialog = ({ open, onOpenChange }: ConnectDialogProps) => {\n const { t } = useTranslate();\n const { writesAllowed, sharedAgentSpaceId, texts } = useAgentConnectionsContext();\n const visibilityOptions = useAgentConnectionVisibilityOptions();\n const [name, setName] = useState(\"\");\n const [capabilities, setCapabilities] = useState<AgentConnectionCapability[]>([...GOOGLE_CONNECT_CAPABILITIES]);\n const [visibility, setVisibility] = useState<AgentConnectionVisibility>(\"OWNER_ONLY\");\n const [submitError, setSubmitError] = useState<FormSubmitError | null>(null);\n const connect = useAgentConnect();\n\n // A fresh start per opening.\n useEffect(() => {\n if (!open) return;\n setName(\"\");\n setCapabilities([...GOOGLE_CONNECT_CAPABILITIES]);\n setVisibility(\"OWNER_ONLY\");\n setSubmitError(null);\n }, [open]);\n\n const handleSubmit = async () => {\n if (!writesAllowed || capabilities.length === 0) return;\n setSubmitError(null);\n try {\n await connect.start({ provider: \"GOOGLE\", displayName: name, capabilities, visibility, targetAgentSpaceId: sharedAgentSpaceId });\n } catch (error) {\n const failure = toFormSubmitError(error, t(\"Google could not be connected\"));\n setSubmitError(failure);\n notify.submitError(failure);\n }\n };\n\n return (\n <FormDialog\n open={open}\n onOpenChange={onOpenChange}\n title={\n <span className=\"flex items-center gap-2\">\n <ProviderLogo provider=\"GOOGLE\" className=\"size-5\" />\n {t(\"Connect Google\")}\n </span>\n }\n description={t(\"%agentName% starts with read access. You raise the levels once the account is connected.\", { replacements: { agentName: texts.agentName } })}\n submitLabel={t(\"Continue to Google\")}\n pendingLabel={t(\"Opening Google…\")}\n isPending={connect.isPending}\n isDirty={name.trim() !== \"\"}\n submitDisabled={!writesAllowed || capabilities.length === 0}\n onSubmit={(event) => {\n event.preventDefault();\n event.stopPropagation();\n void handleSubmit();\n }}\n >\n <div className=\"space-y-4\">\n <FormErrors error={submitError} />\n <FormFieldFrame label={t(\"Name\", { context: \"agent-connection\" })} description={t(\"What %agentName% calls this connection\", { replacements: { agentName: texts.agentName } })}>\n {(control) => <Input {...control} name=\"displayName\" value={name} onChange={(event) => setName(event.target.value)} maxLength={100} autoComplete=\"off\" placeholder={t(\"e.g. Mail & Calendar\")} />}\n </FormFieldFrame>\n <FormFieldFrame\n label={t(\"Access to\", { context: \"agent-connection\" })}\n description={t(\"Google asks you to confirm exactly these.\")}\n error={capabilities.length === 0 ? t(\"Choose at least one.\") : undefined}\n >\n {() => (\n <fieldset aria-label={t(\"Access to\", { context: \"agent-connection\" })} className=\"m-0 flex min-w-0 flex-wrap gap-2 border-0 p-0\">\n {GOOGLE_CONNECT_CAPABILITIES.map((capability) => {\n const isPicked = capabilities.includes(capability);\n return (\n <button\n key={capability}\n type=\"button\"\n aria-pressed={isPicked}\n onClick={() => setCapabilities((current) => (isPicked ? current.filter((entry) => entry !== capability) : GOOGLE_CONNECT_CAPABILITIES.filter((entry) => entry === capability || current.includes(entry))))}\n className={cn(\n \"inline-flex h-9 items-center gap-2 rounded-lg border px-3 text-sm font-medium transition-colors\",\n \"focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none\",\n isPicked ? \"border-primary bg-primary/10 text-foreground\" : \"bg-card text-muted-foreground hover:bg-muted\",\n )}\n >\n <CapabilityIcon provider=\"GOOGLE\" capability={capability} className={isPicked ? undefined : \"opacity-50 grayscale\"} />\n {t(AGENT_CONNECTION_CAPABILITY_LABEL[capability], { context: AGENT_CONNECTION_CAPABILITY_CONTEXT })}\n {isPicked && <Check aria-hidden className=\"size-3.5 text-primary\" />}\n </button>\n );\n })}\n </fieldset>\n )}\n </FormFieldFrame>\n <FormFieldFrame label={t(\"Visible to\", { context: \"agent-connection\" })} description={sharedAgentSpaceId !== null ? texts.sharedVisibilityHelp : texts.noShareTargetHelp}>\n {() => (\n <SegmentedControl\n aria-label={t(\"Visible to\", { context: \"agent-connection\" })}\n value={visibility}\n onValueChange={setVisibility}\n options={visibilityOptions.map((option) => (option.value === \"AGENT_SPACE\" && sharedAgentSpaceId === null ? { ...option, disabled: true } : option))}\n height={36}\n />\n )}\n </FormFieldFrame>\n </div>\n </FormDialog>\n );\n};\n\ninterface ImapForm {\n displayName: string;\n fromAddress: string;\n username: string;\n password: string;\n imapHost: string;\n imapPort: string;\n smtpHost: string;\n smtpPort: string;\n}\n\nconst EMPTY_IMAP_FORM: ImapForm = { displayName: \"\", fromAddress: \"\", username: \"\", password: \"\", imapHost: \"\", imapPort: \"993\", smtpHost: \"\", smtpPort: \"587\" };\n\n/**\n * \"IMAP / SMTP\" (any other mailbox): the server checks the login before it stores the connection\n * (`POST connections/imap`, the password stored encrypted). Sharing is a second request once the connection exists\n * (`POST connections/{id}/settings`), as the connect takes no visibility.\n */\nexport const ConnectImapDialog = ({ open, onOpenChange }: ConnectDialogProps) => {\n const { t } = useTranslate();\n const { api, writesAllowed, sharedAgentSpaceId, texts } = useAgentConnectionsContext();\n const visibilityOptions = useAgentConnectionVisibilityOptions();\n const [form, setForm] = useState<ImapForm>(EMPTY_IMAP_FORM);\n const [visibility, setVisibility] = useState<AgentConnectionVisibility>(\"OWNER_ONLY\");\n const [submitError, setSubmitError] = useState<FormSubmitError | null>(null);\n const [connectImap, connectState] = api.useConnectAgentConnectionImapMutation();\n const [saveSettings, settingsState] = api.useUpdateAgentConnectionSettingsMutation();\n\n useEffect(() => {\n if (!open) return;\n setForm(EMPTY_IMAP_FORM);\n setVisibility(\"OWNER_ONLY\");\n setSubmitError(null);\n }, [open]);\n\n const setField = (field: keyof ImapForm) => (value: string) => setForm((current) => ({ ...current, [field]: value }));\n const isComplete =\n form.fromAddress.trim() !== \"\" &&\n form.password !== \"\" &&\n form.imapHost.trim() !== \"\" &&\n form.smtpHost.trim() !== \"\" &&\n agentConnectionPortOf(form.imapPort) !== undefined &&\n agentConnectionPortOf(form.smtpPort) !== undefined;\n\n const handleSubmit = async () => {\n if (!writesAllowed || !isComplete) return;\n setSubmitError(null);\n try {\n const response = await connectImap({\n displayName: form.displayName.trim() || null,\n fromAddress: form.fromAddress.trim(),\n username: form.username.trim() || form.fromAddress.trim(),\n password: form.password,\n imapHost: form.imapHost.trim(),\n imapPort: agentConnectionPortOf(form.imapPort),\n smtpHost: form.smtpHost.trim(),\n smtpPort: agentConnectionPortOf(form.smtpPort),\n }).unwrap();\n const connectionId = response.connection?.connectionId;\n if (visibility === \"AGENT_SPACE\" && connectionId !== undefined && sharedAgentSpaceId !== null) {\n await saveSettings({ connectionId, visibility, targetAgentSpaceId: sharedAgentSpaceId }).unwrap();\n }\n notify.success(t(\"Mailbox connected\"));\n onOpenChange(false);\n } catch (error) {\n const failure = toFormSubmitError(error, t(\"The mailbox could not be connected\"));\n setSubmitError(failure);\n notify.submitError(failure);\n }\n };\n\n const textField = (field: keyof ImapForm, label: string, options: { type?: string; placeholder?: string; required?: boolean } = {}) => (\n <FormFieldFrame label={label} required={options.required}>\n {(control) => (\n <Input\n {...control}\n name={field}\n type={options.type ?? \"text\"}\n value={form[field]}\n onChange={(event) => setField(field)(event.target.value)}\n placeholder={options.placeholder}\n autoComplete={options.type === \"password\" ? \"new-password\" : \"off\"}\n />\n )}\n </FormFieldFrame>\n );\n\n return (\n <FormDialog\n open={open}\n onOpenChange={onOpenChange}\n title={t(\"Connect a mailbox (IMAP / SMTP)\")}\n description={t(\"The server checks the login first. The password is stored encrypted.\")}\n submitLabel={t(\"Connect\", { context: \"agent-connection\" })}\n pendingLabel={t(\"Checking the login…\")}\n isPending={connectState.isLoading || settingsState.isLoading}\n isDirty={form.fromAddress !== \"\" || form.password !== \"\"}\n submitDisabled={!writesAllowed || !isComplete}\n className=\"sm:max-w-xl\"\n onSubmit={(event) => {\n event.preventDefault();\n event.stopPropagation();\n void handleSubmit();\n }}\n >\n <div className=\"space-y-4\">\n <FormErrors error={submitError} />\n {textField(\"displayName\", t(\"Name\", { context: \"agent-connection\" }), { placeholder: t(\"e.g. Info mailbox\") })}\n <div className=\"grid gap-4 sm:grid-cols-2\">\n {textField(\"fromAddress\", t(\"Mail address\"), { type: \"email\", placeholder: texts.imapAddressPlaceholder, required: true })}\n {textField(\"username\", t(\"User name\"), { placeholder: t(\"Default: the mail address\") })}\n </div>\n {textField(\"password\", t(\"Password\"), { type: \"password\", required: true })}\n <div className=\"grid grid-cols-[1fr_6rem] gap-4\">\n {textField(\"imapHost\", t(\"IMAP server\"), { placeholder: \"imap.example.com\", required: true })}\n {textField(\"imapPort\", t(\"Port\"), { required: true })}\n </div>\n <div className=\"grid grid-cols-[1fr_6rem] gap-4\">\n {textField(\"smtpHost\", t(\"SMTP server\"), { placeholder: \"smtp.example.com\", required: true })}\n {textField(\"smtpPort\", t(\"Port\"), { required: true })}\n </div>\n <FormFieldFrame label={t(\"Visible to\", { context: \"agent-connection\" })}>\n {() => (\n <SegmentedControl\n aria-label={t(\"Visible to\", { context: \"agent-connection\" })}\n value={visibility}\n onValueChange={setVisibility}\n options={visibilityOptions.map((option) => (option.value === \"AGENT_SPACE\" && sharedAgentSpaceId === null ? { ...option, disabled: true } : option))}\n height={36}\n />\n )}\n </FormFieldFrame>\n </div>\n </FormDialog>\n );\n};\n\n/**\n * \"Slack\": the agent's Slack bot as a system connection of the shared space (`POST system/slack`, the system right\n * only). The bot's token is a server secret; this only names the connection.\n */\nexport const ConnectSlackDialog = ({ open, onOpenChange }: ConnectDialogProps) => {\n const { t } = useTranslate();\n const { api, writesAllowed, texts } = useAgentConnectionsContext();\n const [name, setName] = useState(\"\");\n const [submitError, setSubmitError] = useState<FormSubmitError | null>(null);\n const [connectSlack, connectState] = api.useConnectAgentConnectionSlackMutation();\n\n useEffect(() => {\n if (!open) return;\n setName(\"\");\n setSubmitError(null);\n }, [open]);\n\n const handleSubmit = async () => {\n if (!writesAllowed) return;\n setSubmitError(null);\n try {\n await connectSlack({ displayName: name.trim() || null }).unwrap();\n notify.success(t(\"Slack connected\"));\n onOpenChange(false);\n } catch (error) {\n const failure = toFormSubmitError(error, t(\"Slack could not be connected\"));\n setSubmitError(failure);\n notify.submitError(failure);\n }\n };\n\n return (\n <FormDialog\n open={open}\n onOpenChange={onOpenChange}\n title={\n <span className=\"flex items-center gap-2\">\n <ProviderLogo provider=\"SLACK\" className=\"size-5\" />\n {t(\"Connect %agentName%’s Slack bot\", { replacements: { agentName: texts.agentName } })}\n </span>\n }\n description={texts.slackBotDescription}\n submitLabel={t(\"Connect\", { context: \"agent-connection\" })}\n pendingLabel={t(\"Saving…\")}\n isPending={connectState.isLoading}\n isDirty={name.trim() !== \"\"}\n submitDisabled={!writesAllowed}\n onSubmit={(event) => {\n event.preventDefault();\n event.stopPropagation();\n void handleSubmit();\n }}\n >\n <div className=\"space-y-4\">\n <FormErrors error={submitError} />\n <FormFieldFrame label={t(\"Name\", { context: \"agent-connection\" })} description={t(\"What %agentName% calls this connection\", { replacements: { agentName: texts.agentName } })}>\n {(control) => <Input {...control} name=\"displayName\" value={name} onChange={(event) => setName(event.target.value)} maxLength={100} autoComplete=\"off\" placeholder={texts.slackNamePlaceholder} />}\n </FormFieldFrame>\n </div>\n </FormDialog>\n );\n};\n","import { QuickFilterPills } from \"@mgamadeus/ddd-admin-ui/glass\";\nimport { useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { EntityListBody, EntityListCard, type EntityListColumn, EntityListToolbar, EntityListViewToggle } from \"@mgamadeus/ddd-admin-ui/list\";\nimport { type ListDisplayMode, notify, toFormSubmitError, type UrlStateAdapter, useConfirm, useMemoryUrlState, useUrlListState } from \"@mgamadeus/ddd-admin-ui/logic\";\nimport { StatusCallout, StatusCalloutAction } from \"@mgamadeus/ddd-admin-ui/page\";\nimport { cn } from \"@mgamadeus/ddd-admin-ui/primitives\";\nimport { Plug } from \"lucide-react\";\nimport { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport {\n AGENT_CONNECTION_STATUS_GROUP_LABEL,\n AGENT_CONNECTION_STATUS_GROUPS,\n type AgentConnectionsScope,\n agentConnectionNameOf,\n agentConnectionProviderName,\n agentConnectionsOfScope,\n agentConnectionStatusGroupContextOf,\n agentConnectionVisibilityOf,\n canManageAgentConnection,\n countAgentConnectionsByStatusGroup,\n filterAgentConnections,\n hasAgentConnectionDriveAccess,\n isAgentConnectionStatusGroup,\n parseAgentConnectionLevels,\n} from \"./agent-connection-format\";\nimport {\n AGENT_CONNECTIONS_PAGE_SURFACE,\n type AgentConnectionDriveSelection,\n type AgentConnectionLevelsRequest,\n type AgentConnectionReconnectRequest,\n type AgentConnectionsOAuthAdapter,\n type AgentConnectReturn,\n isAgentConnectCancelledReason,\n parsePendingAgentConnect,\n resolveAgentConnectReturn,\n} from \"./agent-connection-oauth\";\nimport type { AgentConnectionsApi } from \"./agent-connections-api\";\nimport { AgentConnectionsProvider, type AgentConnectionsTexts, useAgentConnectionsContext } from \"./agent-connections-context\";\nimport type { AgentConnectionSummary } from \"./agent-connections-types\";\nimport { isAgentConnectionDriveScopeAsked } from \"./agent-connection-drive-scope\";\nimport { AgentConnectionCard } from \"./AgentConnectionCard\";\nimport { AgentConnectionDriveScopeDialog } from \"./AgentConnectionDriveScopeDialog\";\nimport { AgentConnectionDrivesDrawer } from \"./AgentConnectionDrivesDrawer\";\nimport { AgentConnectionLevelsDrawer } from \"./AgentConnectionLevelsDrawer\";\nimport { AgentConnectionSharingDialog } from \"./AgentConnectionSharingDialog\";\nimport { ConnectGoogleDialog, ConnectImapDialog, ConnectSlackDialog } from \"./ConnectDialogs\";\nimport { type AgentConnectionLogos, ProviderMark } from \"./connection-logos\";\nimport {\n AddConnectionMenu,\n AGENT_CONNECT_PROVIDERS,\n type AgentConnectionActionHandlers,\n AgentConnectionActionsMenu,\n AgentConnectionName,\n AgentConnectionRelativeTime,\n AgentConnectionStatusBadge,\n AgentConnectionVisibilityBadge,\n type AgentConnectProvider,\n CapabilityLevelChips,\n} from \"./connection-parts\";\nimport { useAgentConnect } from \"./use-agent-connect\";\n\n/** The URL state of the panel: the status quick filter and the search. */\nexport const AGENT_CONNECTIONS_URL_KEYS = [\"status\", \"q\"] as const;\n\nconst EMPTY_CONNECTIONS: AgentConnectionSummary[] = [];\n\n/** The parts of the panel, for a host frame that places them itself (`AgentConnectionsPanelProps.renderFrame`). */\nexport interface AgentConnectionsPanelParts {\n /** \"Add connection\" with the providers; `size` as the place needs it. */\n addMenu: (size: \"sm\" | \"default\") => ReactNode;\n /** The result of a provider's return (connected, renewed, merged, refused), `null` without one. */\n banner: ReactNode;\n /** The status quick filters, `null` without a connection. */\n filters: ReactNode;\n /** Search and the view toggle. */\n toolbar: ReactNode;\n /** The connections as tiles or table rows, with their loading, empty and error states. */\n body: ReactNode;\n /** The dialogs and drawers; they render nothing while closed. */\n overlays: ReactNode;\n}\n\nexport interface AgentConnectionsPanelProps {\n /** `createAgentConnectionsApi(…)` of the host. */\n api: AgentConnectionsApi;\n /** The signed-in account: its own connections are the ones it may change. */\n accountId: number | string | null;\n /** False: every control that changes something is off. Default true. */\n writesAllowed?: boolean;\n /** `all` (default): every connection the account sees; `manageable`: only the ones it may change. */\n scope?: AgentConnectionsScope;\n /** The providers the add menu offers, in this order. Default: Google, IMAP/SMTP, Slack (the system right). */\n connectProviders?: readonly AgentConnectProvider[];\n /**\n * The way to a provider and back (storage, address, navigation). Without it the OAuth connects are off: the add menu\n * offers no OAuth provider and no connection reconnects or asks for more scopes.\n */\n oauth?: AgentConnectionsOAuthAdapter | null;\n /**\n * Which panel this is on the way back from a provider: a connect started here is stored with it, and only a panel\n * of the same surface shows its result. Default: the page of the connections.\n */\n surface?: string;\n /** The host's words: the agent's name, what \"shared\" means here. */\n texts?: AgentConnectionsTexts;\n /** Marks of providers and products beside the package's (Google, Slack). */\n logos?: AgentConnectionLogos;\n /** Search and status filter in the host's URL; default: in the panel's own state. */\n urlStateAdapter?: UrlStateAdapter;\n /** Tiles or table, when the host keeps the choice; default: the panel's own state, starting with tiles. */\n displayMode?: ListDisplayMode;\n onDisplayModeChange?: (displayMode: ListDisplayMode) => void;\n /** False: tiles only, no view toggle (a narrow column). Default true. */\n tableView?: boolean;\n /** A request to open the levels drawer of a connection (a deep link); handled once the list is loaded. */\n levelsRequest?: AgentConnectionLevelsRequest | null;\n onLevelsRequestHandled?: () => void;\n /**\n * A request to reconnect a connection (the deep link `?connection=<id>&reconnect=1`, e.g. \"Reconnect\" of a screen that\n * found the connection expired): once the list is loaded the panel scrolls to the connection and starts its\n * reconnect once; `onReconnectRequestHandled` then lets the host drop the parameters, so a reload does not start it\n * again.\n */\n reconnectRequest?: AgentConnectionReconnectRequest | null;\n onReconnectRequestHandled?: () => void;\n /** False: no \"Drives and folders\" (a host that does not mount the drive routes). Default true. */\n driveRoots?: boolean;\n /** The connection whose drives and folders are open, when the host keeps it (the URL); with it pass the callback. */\n selectedDrive?: AgentConnectionDriveSelection | null;\n onSelectedDriveChange?: (selection: AgentConnectionDriveSelection | null) => void;\n /**\n * EXTENSION POINT (item search): true shows the search field in the picker of \"Drives and folders\" (folders and\n * shared drives by name, `GET connections/{id}/driveItems/search`). A host passes true once its backend mounts that\n * route; until then the picker only browses. Default false.\n */\n isItemSearchAvailable?: boolean;\n /**\n * EXTENSION POINT (shared drives): true shows the section \"Shared drives\" in the picker of \"Drives and folders\" (the\n * shared drives the account is a member of, `GET connections/{id}/driveItems?section=SHARED_DRIVES`). A host passes\n * true once its backend lists them; until then the picker offers the account's own drive and what was shared with\n * it. Default false.\n */\n isSharedDrivesSectionAvailable?: boolean;\n /** Places the parts itself (a page puts the add menu into its header). Default: stacked, the add menu above the list. */\n renderFrame?: (parts: AgentConnectionsPanelParts) => ReactNode;\n className?: string;\n}\n\ninterface NameEditRequest {\n connectionId: number;\n suggestedName: string | null;\n requestKey: number;\n}\n\nconst LastUsedCell = ({ lastUsedAt }: { lastUsedAt: string | null | undefined }) => {\n const { t } = useTranslate();\n return (\n <span className=\"text-sm whitespace-nowrap text-muted-foreground\">\n <AgentConnectionRelativeTime value={lastUsedAt} fallback={t(\"never\", { context: \"agent-connection-last-used\" })} />\n </span>\n );\n};\n\ninterface PanelContentProps extends Pick<\n AgentConnectionsPanelProps,\n \"scope\" | \"connectProviders\" | \"urlStateAdapter\" | \"displayMode\" | \"onDisplayModeChange\" | \"tableView\" | \"levelsRequest\" | \"onLevelsRequestHandled\" | \"reconnectRequest\" | \"onReconnectRequestHandled\" | \"driveRoots\" | \"selectedDrive\" | \"onSelectedDriveChange\" | \"isItemSearchAvailable\" | \"isSharedDrivesSectionAvailable\" | \"renderFrame\" | \"className\"\n> {\n connections: AgentConnectionSummary[];\n connectableProviders: readonly string[];\n isLoading: boolean;\n isSuccess: boolean;\n loadError: unknown;\n}\n\nconst PanelContent = ({\n connections,\n connectableProviders,\n isLoading,\n isSuccess,\n loadError,\n scope = \"all\",\n connectProviders = AGENT_CONNECT_PROVIDERS,\n urlStateAdapter,\n displayMode: hostDisplayMode,\n onDisplayModeChange,\n tableView = true,\n levelsRequest: hostLevelsRequest = null,\n onLevelsRequestHandled,\n reconnectRequest = null,\n onReconnectRequestHandled,\n driveRoots = true,\n selectedDrive: hostSelectedDrive,\n onSelectedDriveChange,\n isItemSearchAvailable = false,\n isSharedDrivesSectionAvailable = false,\n renderFrame,\n className,\n}: PanelContentProps) => {\n const { t } = useTranslate();\n const confirm = useConfirm();\n const { api, writesAllowed, viewer, sharedAgentSpaceId, texts, oauth, surface } = useAgentConnectionsContext();\n const agentName = texts.agentName;\n const memory = useMemoryUrlState();\n const listState = useUrlListState(AGENT_CONNECTIONS_URL_KEYS, { adapter: urlStateAdapter ?? memory.urlStateAdapter, uncounted: [\"status\", \"q\"] });\n const { values, debounced, setValue } = listState;\n const [ownDisplayMode, setOwnDisplayMode] = useState<ListDisplayMode>(\"grid\");\n const displayMode: ListDisplayMode = !tableView ? \"grid\" : (hostDisplayMode ?? ownDisplayMode);\n const setDisplayMode = (mode: ListDisplayMode) => {\n setOwnDisplayMode(mode);\n onDisplayModeChange?.(mode);\n };\n\n const [connectProvider, setConnectProvider] = useState<AgentConnectProvider | null>(null);\n const [levelsRequest, setLevelsRequest] = useState<AgentConnectionLevelsRequest | null>(null);\n const setLevelsId = (connectionId: number | null) => setLevelsRequest(connectionId === null ? null : { connectionId, preset: null });\n const [sharingId, setSharingId] = useState<number | null>(null);\n const [nameEditRequest, setNameEditRequest] = useState<NameEditRequest | null>(null);\n const [ownSelectedDrive, setOwnSelectedDrive] = useState<AgentConnectionDriveSelection | null>(null);\n const selectedDrive = !driveRoots ? null : hostSelectedDrive !== undefined ? hostSelectedDrive : ownSelectedDrive;\n const setSelectedDrive = (selection: AgentConnectionDriveSelection | null) => {\n setOwnSelectedDrive(selection);\n onSelectedDriveChange?.(selection);\n };\n const findConnection = (connectionId: number | null) => connections.find((connection) => connection.connectionId === connectionId) ?? null;\n // \"What may the agent see?\" of a drive connection, and the picker request it leaves when \"Certain areas\" was saved\n const [scopeConnectionId, setScopeConnectionId] = useState<number | null>(null);\n const [pickerRequest, setPickerRequest] = useState<number | null>(null);\n\n const [disconnect] = api.useDisconnectAgentConnectionMutation();\n const connect = useAgentConnect();\n const isOAuthAvailable = oauth !== null;\n\n // ---- the way back from the provider: read once, by the panel of the surface that started the connect\n const [connectReturn, setConnectReturn] = useState<AgentConnectReturn | null>(null);\n const returnParameters = oauth?.returnParameters ?? null;\n const returnConnected = returnParameters?.connected ?? null;\n const returnConnectError = returnParameters?.connectError ?? null;\n const hasReturn = returnParameters !== null;\n const readReturnOf = useRef<string | null>(null);\n useEffect(() => {\n if (oauth === null || !hasReturn) return;\n const signature = `${returnConnected ?? \"\"}|${returnConnectError ?? \"\"}`;\n if (readReturnOf.current === signature) return;\n const pending = parsePendingAgentConnect(oauth.readPending());\n if ((pending?.surface ?? AGENT_CONNECTIONS_PAGE_SURFACE) !== surface) return;\n readReturnOf.current = signature;\n oauth.writePending(null);\n setConnectReturn(resolveAgentConnectReturn({ connected: returnConnected, connectError: returnConnectError }, pending));\n oauth.clearReturnParameters();\n }, [oauth, hasReturn, returnConnected, returnConnectError, surface]);\n\n // A new drive connection asks at once what the agent may see (once per return; the list must know the connection)\n const askedScopeOf = useRef<number | null>(null);\n useEffect(() => {\n if (!driveRoots || !isSuccess || connectReturn?.kind !== \"connected\" || askedScopeOf.current === connectReturn.connectionId) return;\n const connected = connections.find((connection) => connection.connectionId === connectReturn.connectionId) ?? null;\n if (connected === null || !isAgentConnectionDriveScopeAsked(connected) || !canManageAgentConnection(connected, viewer)) return;\n askedScopeOf.current = connectReturn.connectionId;\n setScopeConnectionId(connectReturn.connectionId);\n }, [driveRoots, isSuccess, connectReturn, connections, viewer]);\n\n // A levels request of the host (the chat's deep link): the drawer of that connection with the suggestion, once the\n // list is there; then the host drops the request.\n useEffect(() => {\n if (!isSuccess || hostLevelsRequest === null) return;\n onLevelsRequestHandled?.();\n if (connections.some((connection) => connection.connectionId === hostLevelsRequest.connectionId)) setLevelsRequest(hostLevelsRequest);\n else notify.error(t(\"This connection is not in your list.\"));\n }, [isSuccess, hostLevelsRequest, connections, onLevelsRequestHandled, t]);\n\n // ---- rights and actions\n const canManage = (connection: AgentConnectionSummary): boolean => canManageAgentConnection(connection, viewer);\n\n const requestRename = useCallback((connectionId: number, suggestedName: string | null) => {\n setNameEditRequest({ connectionId, suggestedName, requestKey: Date.now() });\n }, []);\n const clearNameEditRequest = useCallback(() => setNameEditRequest(null), []);\n\n const handleDisconnect = async (connection: AgentConnectionSummary) => {\n if (!writesAllowed) return;\n const confirmed = await confirm({\n title: t(\"Disconnect %name%?\", { replacements: { name: connection.name ?? \"\" } }),\n description: t(\"%agentName% loses access at once. The access is revoked at the provider and the stored keys are deleted.\", { replacements: { agentName } }),\n confirmLabel: t(\"Disconnect\", { context: \"agent-connection\" }),\n confirmVariant: \"destructive\",\n });\n if (!confirmed) return;\n try {\n await disconnect({ connectionId: connection.connectionId }).unwrap();\n notify.success(t(\"Connection disconnected\"));\n } catch (error) {\n notify.submitError(toFormSubmitError(error, t(\"The connection could not be disconnected\")));\n }\n };\n\n const handleReconnect = async (connection: AgentConnectionSummary) => {\n if (!writesAllowed) return;\n try {\n await connect.start({\n provider: \"GOOGLE\",\n displayName: connection.name ?? \"\",\n capabilities: parseAgentConnectionLevels(connection.levels).map((entry) => entry.capability),\n visibility: agentConnectionVisibilityOf(connection),\n targetAgentSpaceId: sharedAgentSpaceId,\n reconnectOf: connection.connectionId,\n });\n } catch (error) {\n notify.submitError(toFormSubmitError(error, t(\"Google could not be connected\")));\n }\n };\n\n // A reconnect request of the host (the deep link `?connection=<id>&reconnect=1`): once the list is there, scroll to\n // the connection and start its reconnect once; the host then drops the parameters (a reload starts nothing).\n const startedReconnectOf = useRef<number | null>(null);\n useEffect(() => {\n if (!isSuccess || reconnectRequest === null || startedReconnectOf.current === reconnectRequest.connectionId) return;\n startedReconnectOf.current = reconnectRequest.connectionId;\n onReconnectRequestHandled?.();\n const connection = connections.find((candidate) => candidate.connectionId === reconnectRequest.connectionId) ?? null;\n if (connection === null) {\n notify.error(t(\"This connection is not in your list.\"));\n return;\n }\n if (typeof document !== \"undefined\") document.querySelector(`[data-connection-id=\"${connection.connectionId}\"]`)?.scrollIntoView?.({ block: \"center\", behavior: \"smooth\" });\n if (!writesAllowed || !canManageAgentConnection(connection, viewer) || connection.provider !== \"GOOGLE\" || !isOAuthAvailable) {\n notify.error(t(\"This connection cannot be reconnected here.\"));\n return;\n }\n void handleReconnect(connection);\n // handleReconnect is a plain function of this render; the request and the list decide when it runs\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [isSuccess, reconnectRequest, connections, onReconnectRequestHandled, writesAllowed, viewer, isOAuthAvailable, t]);\n\n const handlersFor = (connection: AgentConnectionSummary): AgentConnectionActionHandlers => ({\n onChangeLevels: () => setLevelsId(connection.connectionId),\n onChangeSharing: () => setSharingId(connection.connectionId),\n onRename: () => requestRename(connection.connectionId, null),\n onReconnect: connection.provider === \"GOOGLE\" && isOAuthAvailable ? () => void handleReconnect(connection) : undefined,\n onOpenDrives: driveRoots && hasAgentConnectionDriveAccess(connection) ? () => setSelectedDrive({ connectionId: connection.connectionId, driveRootId: null }) : undefined,\n onDisconnect: () => void handleDisconnect(connection),\n });\n\n const editRequestFor = (connection: AgentConnectionSummary) => (nameEditRequest !== null && nameEditRequest.connectionId === connection.connectionId ? nameEditRequest : null);\n\n // ---- filters (client side: an account has a handful of connections)\n const statusFilter = isAgentConnectionStatusGroup(values.status) ? values.status : \"\";\n const scopedConnections = useMemo(() => agentConnectionsOfScope(connections, scope, viewer), [connections, scope, viewer]);\n const countByGroup = useMemo(() => countAgentConnectionsByStatusGroup(scopedConnections), [scopedConnections]);\n const shownConnections = useMemo(\n () => filterAgentConnections(connections, { scope, statusGroup: statusFilter, searchTerm: debounced.q }, viewer),\n [connections, scope, statusFilter, debounced.q, viewer],\n );\n\n const offeredProviders = isOAuthAvailable ? connectProviders : connectProviders.filter((provider) => provider !== \"GOOGLE\");\n const addMenu = (size: \"sm\" | \"default\") => (\n <AddConnectionMenu providers={offeredProviders} connectableProviders={connectableProviders} disabled={!writesAllowed || !isSuccess} onChoose={setConnectProvider} size={size} />\n );\n\n const columns: EntityListColumn<AgentConnectionSummary>[] = [\n { id: \"provider\", header: <span className=\"sr-only\">{t(\"Provider\")}</span>, cell: (connection) => <ProviderMark provider={connection.provider} size=\"sm\" />, className: \"w-14\" },\n {\n id: \"name\",\n header: t(\"Name\", { context: \"column-header\" }),\n cell: (connection) => (\n <AgentConnectionName\n connectionId={connection.connectionId}\n name={agentConnectionNameOf(connection)}\n canRename={canManage(connection) && connection.status !== \"REVOKED\"}\n editRequest={editRequestFor(connection)}\n onEditRequestHandled={clearNameEditRequest}\n size=\"sm\"\n />\n ),\n className: \"min-w-56\",\n },\n { id: \"account\", header: t(\"Account\", { context: \"agent-connection\" }), cell: (connection) => <span className=\"text-sm\">{connection.externalAddress ?? \"—\"}</span>, className: \"min-w-48\" },\n { id: \"providerName\", header: t(\"Provider\"), cell: (connection) => <span className=\"text-sm text-muted-foreground\">{agentConnectionProviderName(connection.provider)}</span> },\n {\n id: \"levels\",\n header: t(\"Levels\", { context: \"agent-connection\" }),\n cell: (connection) => <CapabilityLevelChips provider={connection.provider} levels={parseAgentConnectionLevels(connection.levels)} compact />,\n className: \"min-w-80\",\n },\n { id: \"visibility\", header: t(\"Visible to\", { context: \"agent-connection\" }), cell: (connection) => <AgentConnectionVisibilityBadge visibility={connection.visibility} /> },\n { id: \"status\", header: t(\"Status\"), cell: (connection) => <AgentConnectionStatusBadge status={connection.status} /> },\n { id: \"lastUsed\", header: t(\"Last used\"), cell: (connection) => <LastUsedCell lastUsedAt={connection.lastUsedAt} /> },\n {\n id: \"actions\",\n header: <span className=\"sr-only\">{t(\"Actions\")}</span>,\n className: \"w-14 text-right\",\n cell: (connection) =>\n canManage(connection) && connection.status !== \"REVOKED\" ? (\n <div className=\"flex justify-end\">\n <AgentConnectionActionsMenu name={connection.name ?? \"\"} {...handlersFor(connection)} />\n </div>\n ) : null,\n },\n ];\n\n const returnedConnection = connectReturn !== null && connectReturn.kind !== \"error\" ? findConnection(connectReturn.connectionId) : null;\n const returnedName = returnedConnection?.name ?? \"\";\n // The callback's rare refusal after the consent: the started connection exists (connected), only the share failed.\n const startedConnection = connectReturn?.kind === \"error\" ? findConnection(connectReturn.startedConnectionId) : null;\n const connectedButNotShared = startedConnection?.status === \"CONNECTED\" ? startedConnection : null;\n const hideBanner = <StatusCalloutAction onClick={() => setConnectReturn(null)}>{t(\"Hide\")}</StatusCalloutAction>;\n\n const banner =\n connectReturn === null ? null : connectReturn.kind === \"extensionRefused\" ? (\n <StatusCallout\n tone=\"warning\"\n title={t(\"Google did not grant everything\")}\n description={connectReturn.reason}\n actions={\n <StatusCalloutAction\n onClick={() => {\n setLevelsId(connectReturn.connectionId);\n setConnectReturn(null);\n }}\n disabled={!writesAllowed}\n >\n {t(\"Change levels\")}\n </StatusCalloutAction>\n }\n />\n ) : connectReturn.kind === \"error\" && connectedButNotShared !== null ? (\n <StatusCallout\n tone=\"warning\"\n title={t(\"Connected as “%name%”, but not shared\", { replacements: { name: connectedButNotShared.name ?? \"\" } })}\n description={connectReturn.reason}\n actions={\n <StatusCalloutAction\n onClick={() => {\n setSharingId(connectedButNotShared.connectionId);\n setConnectReturn(null);\n }}\n disabled={!writesAllowed}\n >\n {t(\"Sharing\", { context: \"agent-connection\" })}\n </StatusCalloutAction>\n }\n />\n ) : connectReturn.kind === \"error\" ? (\n <StatusCallout\n tone=\"destructive\"\n title={t(\"Google could not be connected\")}\n description={isAgentConnectCancelledReason(connectReturn.reason) ? t(\"The consent at Google was cancelled.\") : connectReturn.reason}\n actions={hideBanner}\n />\n ) : connectReturn.kind === \"merged\" ? (\n <StatusCallout\n tone=\"info\"\n title={t(\"Already connected as “%name%”\", { replacements: { name: returnedName } })}\n description={\n connectReturn.typedName !== \"\" && connectReturn.typedName !== returnedName\n ? t(\"Google confirmed the account again: the permissions are updated. Name and levels stay; the name you typed (“%typed%”) was not used.\", { replacements: { typed: connectReturn.typedName } })\n : t(\"Google confirmed the account again: the permissions are updated. Name and levels stay.\")\n }\n actions={\n <StatusCalloutAction\n onClick={() => {\n requestRename(connectReturn.connectionId, connectReturn.typedName !== \"\" ? connectReturn.typedName : null);\n setConnectReturn(null);\n }}\n disabled={!writesAllowed || returnedConnection === null}\n >\n {connectReturn.typedName !== \"\" && connectReturn.typedName !== returnedName ? t(\"Rename to “%typed%”\", { replacements: { typed: connectReturn.typedName } }) : t(\"Rename\", { context: \"agent-connection\" })}\n </StatusCalloutAction>\n }\n />\n ) : (\n <StatusCallout\n tone=\"success\"\n title={connectReturn.kind === \"extended\" ? t(\"Permissions extended\") : connectReturn.kind === \"renewed\" ? t(\"Access renewed\") : t(\"Google account connected\")}\n description={\n connectReturn.kind === \"extended\"\n ? t(\"Google confirmed the new permissions; %agentName% works with the new levels of “%name%”.\", { replacements: { agentName, name: returnedName } })\n : connectReturn.kind === \"renewed\"\n ? t(\"%agentName% can use “%name%” again.\", { replacements: { agentName, name: returnedName } })\n : t(\"%agentName% starts with read access. Raise the levels under “Change levels”.\", { replacements: { agentName } })\n }\n actions={hideBanner}\n />\n );\n\n const filters =\n scopedConnections.length > 0 ? (\n <QuickFilterPills\n aria-label={t(\"Status quick filters\")}\n allLabel={t(\"All (%count%)\", { replacements: { count: scopedConnections.length } })}\n translate={false}\n size=\"sm\"\n options={AGENT_CONNECTION_STATUS_GROUPS.filter((group) => countByGroup[group] > 0 || group === statusFilter).map((group) => ({\n value: group,\n label: t(AGENT_CONNECTION_STATUS_GROUP_LABEL[group], { context: agentConnectionStatusGroupContextOf(group) }),\n count: countByGroup[group],\n }))}\n value={statusFilter}\n onChange={(value) => setValue(\"status\", value)}\n />\n ) : null;\n\n const toolbar = (\n <EntityListToolbar\n search={{ value: values.q, onChange: (value) => setValue(\"q\", value), placeholder: t(\"Search by name or account…\"), \"aria-label\": t(\"Search connections\") }}\n activeFilterCount={listState.activeFilterCount}\n onClearFilters={listState.clear}\n viewToggle={tableView ? <EntityListViewToggle displayMode={displayMode} onDisplayModeChange={(mode) => setDisplayMode(mode)} /> : undefined}\n />\n );\n\n const body = (\n <EntityListBody\n displayMode={displayMode}\n renderCard={({ item, rowKey }) => (\n <AgentConnectionCard connection={item} rowKey={rowKey} canManage={canManage(item)} handlers={handlersFor(item)} nameEditRequest={editRequestFor(item)} onNameEditRequestHandled={clearNameEditRequest} />\n )}\n columns={columns}\n items={shownConnections}\n getRowKey={(connection) => String(connection.connectionId)}\n isLoading={isLoading}\n emptyMessage={t(\"No connections yet. Connect your Google account so %agentName% can read your mail, calendar, contacts and files for you.\", { replacements: { agentName } })}\n emptyIcon={<Plug className=\"size-8 text-muted-foreground\" aria-hidden />}\n emptyAction={addMenu(\"sm\")}\n noResultsMessage={t(\"No connection matches.\")}\n isSearchActive={listState.isActive}\n onClearSearch={listState.clear}\n loadingMessage={t(\"Loading connections\")}\n error={loadError !== undefined ? toFormSubmitError(loadError, t(\"The connections could not be loaded\")).message : undefined}\n />\n );\n\n const drivesConnection = selectedDrive !== null && isSuccess ? findConnection(selectedDrive.connectionId) : null;\n const overlays = (\n <>\n <ConnectGoogleDialog open={connectProvider === \"GOOGLE\"} onOpenChange={(open) => setConnectProvider(open ? \"GOOGLE\" : null)} />\n <ConnectImapDialog open={connectProvider === \"IMAP\"} onOpenChange={(open) => setConnectProvider(open ? \"IMAP\" : null)} />\n <ConnectSlackDialog open={connectProvider === \"SLACK\"} onOpenChange={(open) => setConnectProvider(open ? \"SLACK\" : null)} />\n <AgentConnectionLevelsDrawer connection={findConnection(levelsRequest?.connectionId ?? null)} preset={levelsRequest?.preset ?? null} onClose={() => setLevelsRequest(null)} />\n <AgentConnectionSharingDialog connection={findConnection(sharingId)} onClose={() => setSharingId(null)} />\n {driveRoots && (\n <AgentConnectionDrivesDrawer\n connection={drivesConnection}\n connections={connections}\n highlightedDriveRootId={selectedDrive?.driveRootId ?? null}\n isItemSearchAvailable={isItemSearchAvailable}\n isSharedDrivesSectionAvailable={isSharedDrivesSectionAvailable}\n onOpenScope={drivesConnection !== null ? () => setScopeConnectionId(drivesConnection.connectionId) : undefined}\n pickerRequest={pickerRequest}\n onClose={() => setSelectedDrive(null)}\n />\n )}\n {driveRoots && (\n <AgentConnectionDriveScopeDialog\n connection={isSuccess ? findConnection(scopeConnectionId) : null}\n onPickAreas={(connectionId) => {\n setSelectedDrive({ connectionId, driveRootId: null });\n setPickerRequest(Date.now());\n }}\n onClose={() => setScopeConnectionId(null)}\n />\n )}\n </>\n );\n\n // a selected drive of the host (a deep link) that is not in the list: say so once and drop it\n const hostSelectedConnectionId = hostSelectedDrive?.connectionId ?? null;\n useEffect(() => {\n if (!isSuccess || hostSelectedConnectionId === null || !driveRoots) return;\n if (connections.some((connection) => connection.connectionId === hostSelectedConnectionId)) return;\n notify.error(t(\"This connection is not in your list.\"));\n onSelectedDriveChange?.(null);\n }, [isSuccess, hostSelectedConnectionId, driveRoots, connections, onSelectedDriveChange, t]);\n\n const parts: AgentConnectionsPanelParts = { addMenu, banner, filters, toolbar, body, overlays };\n if (renderFrame) return <>{renderFrame(parts)}</>;\n return (\n <div className={cn(\"flex min-w-0 flex-col gap-3\", className)} data-slot=\"agent-connections-panel\">\n <div className=\"flex flex-wrap items-center justify-between gap-3\">\n <div className=\"min-w-0\">{filters}</div>\n <div className=\"ml-auto shrink-0\">{addMenu(\"sm\")}</div>\n </div>\n {banner}\n <EntityListCard label={t(\"Connections\")} toolbar={toolbar}>\n {body}\n </EntityListCard>\n {overlays}\n </div>\n );\n};\n\n/**\n * The connections of the signed-in account as one embeddable block, without a page header: the accounts the agent\n * works with for it (`GET connections`: its own, the ones released to a space it belongs to, and with the system right\n * the agent's system connections), as tiles (default; the provider's mark is the identity) or as a table. Quick\n * filters by status, search by name and account. \"Add connection\" connects Google (consent), an IMAP/SMTP mailbox or\n * the agent's Slack bot; per connection: rename in place, levels and visibility, sharing, the drives and folders of a\n * drive connection, reconnect, disconnect. What the account may not change has no control: the rights are the server's\n * (`canManageAgentConnection` mirrors them), the panel only hides what the server would refuse.\n *\n * The same block serves a page (`AgentConnectionsScreen`) and a column of a dialog (~640 px). A provider's return\n * lands on one route of the host; the panel whose `surface` started the connect shows the result (a new connection, a\n * renewed one, a consent merged into an existing connection, a refusal, a connection the server could not share),\n * wherever it is mounted, and then removes the return parameters through the adapter.\n */\nexport const AgentConnectionsPanel = ({ api, accountId, writesAllowed = true, oauth = null, surface = AGENT_CONNECTIONS_PAGE_SURFACE, texts, logos, ...content }: AgentConnectionsPanelProps) => {\n const query = api.useAgentConnectionsQuery();\n const connections = query.data?.connections ?? EMPTY_CONNECTIONS;\n const viewer = useMemo(() => ({ accountId, mayManageSystemConnections: query.data?.mayManageSystemConnections ?? false }), [accountId, query.data?.mayManageSystemConnections]);\n return (\n <AgentConnectionsProvider api={api} writesAllowed={writesAllowed} viewer={viewer} sharedAgentSpaceId={query.data?.shareableAgentSpaceIds?.[0] ?? null} texts={texts} logos={logos} oauth={oauth} surface={surface}>\n <PanelContent\n {...content}\n connections={connections}\n connectableProviders={query.data?.connectableProviders ?? []}\n isLoading={query.isLoading}\n isSuccess={query.isSuccess}\n loadError={query.isError ? query.error : undefined}\n />\n </AgentConnectionsProvider>\n );\n};\n","import { useTranslate } from \"@mgamadeus/ddd-admin-ui/i18n\";\nimport { EntityListPage, PageToolbar } from \"@mgamadeus/ddd-admin-ui/page\";\nimport type { ReactNode } from \"react\";\nimport { AgentConnectionsPanel, type AgentConnectionsPanelProps } from \"./AgentConnectionsPanel\";\n\nexport interface AgentConnectionsScreenProps extends Omit<AgentConnectionsPanelProps, \"renderFrame\" | \"className\"> {\n /** Default \"Connections\". Already translated. */\n title?: ReactNode;\n /** Default: one sentence on what the connections are, with the agent's name. Already translated. */\n description?: ReactNode;\n /** Further page actions before \"Add connection\". */\n headerActions?: ReactNode;\n}\n\n/**\n * The page of the connections: the page header (title, description, \"Add connection\" as the one primary action) around\n * `AgentConnectionsPanel`, whose parts fill the list page (the result of a provider's return and the status filters\n * under the header, search and view toggle as the list's toolbar, the tiles or the table as its body). Every prop of\n * the panel applies. A host mounts it on the route the provider returns to and renders it inside `<Suspense>` when its\n * adapters read the URL.\n */\nexport const AgentConnectionsScreen = ({ title, description, headerActions, ...panel }: AgentConnectionsScreenProps) => {\n const { t } = useTranslate();\n const agentName = panel.texts?.agentName ?? t(\"The agent\", { context: \"agent-connection-agent-name\" });\n return (\n <AgentConnectionsPanel\n {...panel}\n renderFrame={({ addMenu, banner, filters, toolbar, body, overlays }) => (\n <EntityListPage\n title={title ?? t(\"Connections\")}\n description={description ?? t(\"Your accounts %agentName% works with for you. Per capability you decide whether it only reads, asks first or acts on its own.\", { replacements: { agentName } })}\n headerActions={<PageToolbar primaryAction={addMenu(\"default\")}>{headerActions}</PageToolbar>}\n belowHeader={\n <div className=\"grid gap-3\">\n {banner}\n {filters}\n </div>\n }\n toolbar={toolbar}\n >\n {body}\n {overlays}\n </EntityListPage>\n )}\n />\n );\n};\n"],"names":["VIEW_OPTIONS","row","column","Fragment","freeTotal","freeWidth","hasEntries","DAY_PATTERN","isRecord","section","formatBucketTitle","TAB_LABELS","LIST","defineStatusMap","turns","window","sumOrNull","STATE_CONTEXT","pages","keyOf","localToday","FilterField","ProviderLogo","nameOf","name"],"mappings":";;;;;;;;;;;;;;;;;;AAkCO,MAAM,YAAY,CAAC;AAAA,EACxB;AAAA,EACA,WAAW;AAAA,EACX;AAAA,EACA,cAAc;AAAA,EACd,iBAAiB;AAAA,EACjB,iBAAiB;AAAA,EACjB;AAAA,EACA,SAAS;AAAA,EACT,cAAc;AAAA,EACd;AACF,MAAsB;AACpB,QAAM,EAAE,EAAA,IAAM,aAAA;AACd,QAAM,CAAC,WAAW,YAAY,IAAI,SAAS,WAAW;AACtD,QAAM,SAAS,kBAAkB,kBAAmB,YAAY,UAAa,YAAY;AACzF,SACE;AAAA,IAAC;AAAA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