@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.
Files changed (227) hide show
  1. package/README.md +138 -6
  2. package/boundary.json +5 -0
  3. package/dist/admin.js +13839 -0
  4. package/dist/admin.js.map +1 -0
  5. package/dist/chat.js +1627 -109
  6. package/dist/chat.js.map +1 -1
  7. package/dist/chunks/{AgentsConversationClientContext-C4T7g_Qk.js → AgentsConversationClientContext-B_UJSLXU.js} +2 -2
  8. package/dist/chunks/{AgentsConversationClientContext-C4T7g_Qk.js.map → AgentsConversationClientContext-B_UJSLXU.js.map} +1 -1
  9. package/dist/chunks/{ConversationMarkdown-D-aP3Ssl.js → ConversationMarkdown-DlvwT3Qk.js} +5 -4
  10. package/dist/chunks/{ConversationMarkdown-D-aP3Ssl.js.map → ConversationMarkdown-DlvwT3Qk.js.map} +1 -1
  11. package/dist/chunks/{ConversationMessageInputComposerWidgets-7HNAmZE1.js → ConversationMessageInputComposerWidgets-TchR1lPj.js} +6 -6
  12. package/dist/chunks/{ConversationMessageInputComposerWidgets-7HNAmZE1.js.map → ConversationMessageInputComposerWidgets-TchR1lPj.js.map} +1 -1
  13. package/dist/chunks/{VoiceBarsIcon-FhLAcgLG.js → VoiceBarsIcon-y3mgSqbn.js} +4 -4
  14. package/dist/chunks/{VoiceBarsIcon-FhLAcgLG.js.map → VoiceBarsIcon-y3mgSqbn.js.map} +1 -1
  15. package/dist/chunks/{WebSearchResultsConversationWidget-dEq19U7k.js → WebSearchResultsConversationWidget-l9Aek_lG.js} +3 -2
  16. package/dist/chunks/WebSearchResultsConversationWidget-l9Aek_lG.js.map +1 -0
  17. package/dist/chunks/agents-http-trace-mappers-LWNi-3a4.js +759 -0
  18. package/dist/chunks/agents-http-trace-mappers-LWNi-3a4.js.map +1 -0
  19. package/dist/chunks/{browser-request-interception-ydNOzeUL.js → browser-request-interception-D678IemW.js} +2 -2
  20. package/dist/chunks/{browser-request-interception-ydNOzeUL.js.map → browser-request-interception-D678IemW.js.map} +1 -1
  21. package/dist/chunks/{canvas-reducers-BInd3xNz.js → canvas-reducers-BYArW_Ji.js} +2 -2
  22. package/dist/chunks/{canvas-reducers-BInd3xNz.js.map → canvas-reducers-BYArW_Ji.js.map} +1 -1
  23. package/dist/chunks/{canvas-title-slot-context-BI1PLnPn.js → canvas-title-slot-context-BRGnFzYP.js} +3 -3
  24. package/dist/chunks/{canvas-title-slot-context-BI1PLnPn.js.map → canvas-title-slot-context-BRGnFzYP.js.map} +1 -1
  25. package/dist/chunks/{canvasBodies-CRVh8pCw.js → canvasBodies-BjXypuHf.js} +4 -4
  26. package/dist/chunks/{canvasBodies-CRVh8pCw.js.map → canvasBodies-BjXypuHf.js.map} +1 -1
  27. package/dist/chunks/{canvasStorage-Cr3omZeI.js → canvasStorage-DSspwRMg.js} +2 -2
  28. package/dist/chunks/{canvasStorage-Cr3omZeI.js.map → canvasStorage-DSspwRMg.js.map} +1 -1
  29. package/dist/chunks/content-from-unified-diff-CovnmG2Q.js +2927 -0
  30. package/dist/chunks/content-from-unified-diff-CovnmG2Q.js.map +1 -0
  31. package/dist/chunks/{contract-C18owGKs.js → contract-886XjdID.js} +2 -2
  32. package/dist/chunks/{contract-C18owGKs.js.map → contract-886XjdID.js.map} +1 -1
  33. package/dist/chunks/{conversation-CbWEHPbL.js → conversation-B7-evdj_.js} +4 -4
  34. package/dist/chunks/{conversation-CbWEHPbL.js.map → conversation-B7-evdj_.js.map} +1 -1
  35. package/dist/chunks/{icon-names-Di6c4zLo.js → icon-names-C5PeVvkJ.js} +32 -1
  36. package/dist/chunks/icon-names-C5PeVvkJ.js.map +1 -0
  37. package/dist/chunks/{link-navigation-DRHt6g7U.js → index-DZovGMpG.js} +65 -106
  38. package/dist/chunks/index-DZovGMpG.js.map +1 -0
  39. package/dist/chunks/link-navigation-a_sRfmsj.js +49 -0
  40. package/dist/chunks/link-navigation-a_sRfmsj.js.map +1 -0
  41. package/dist/chunks/{widget-name-resolver-Dq6Ejo7d.js → widget-name-resolver-DS3zH_5W.js} +5 -4
  42. package/dist/chunks/{widget-name-resolver-Dq6Ejo7d.js.map → widget-name-resolver-DS3zH_5W.js.map} +1 -1
  43. package/dist/chunks/{withPollingChangeSubscription-ClyOABgu.js → withPollingChangeSubscription-XvCpjGmd.js} +13 -2
  44. package/dist/chunks/{withPollingChangeSubscription-ClyOABgu.js.map → withPollingChangeSubscription-XvCpjGmd.js.map} +1 -1
  45. package/dist/client-testing.js +5 -5
  46. package/dist/client.js +50 -231
  47. package/dist/client.js.map +1 -1
  48. package/dist/contract.js +5 -5
  49. package/dist/files/i18n-keys.json +18277 -1298
  50. package/dist/files/widgets/DriveFilesConversationWidget/DriveFilesConversationWidget.md +3 -3
  51. package/dist/image-render.js +7 -7
  52. package/dist/index.js +62 -61
  53. package/dist/index.js.map +1 -1
  54. package/dist/kit.js +2 -2
  55. package/dist/preview.js +7 -7
  56. package/dist/provider.js +57 -56
  57. package/dist/provider.js.map +1 -1
  58. package/dist/renderer.js +15 -15
  59. package/dist/styles.css +2962 -15
  60. package/dist/types/admin/blocks/CodeBlock.d.ts +28 -0
  61. package/dist/types/admin/blocks/DetailModal.d.ts +34 -0
  62. package/dist/types/admin/blocks/Disclosure.d.ts +25 -0
  63. package/dist/types/admin/blocks/JsonTree.d.ts +18 -0
  64. package/dist/types/admin/blocks/LineDiffView.d.ts +18 -0
  65. package/dist/types/admin/blocks/ProportionBar.d.ts +43 -0
  66. package/dist/types/admin/blocks/TokenFigure.d.ts +14 -0
  67. package/dist/types/admin/blocks/json-tree.d.ts +40 -0
  68. package/dist/types/admin/blocks/line-diff.d.ts +46 -0
  69. package/dist/types/admin/blocks/proportion-bar.d.ts +34 -0
  70. package/dist/types/admin/blocks/series-fill-classes.d.ts +13 -0
  71. package/dist/types/admin/blocks/token-figure.d.ts +8 -0
  72. package/dist/types/admin/connections/AgentConnectionCard.d.ts +21 -0
  73. package/dist/types/admin/connections/AgentConnectionDriveRootSpaces.d.ts +25 -0
  74. package/dist/types/admin/connections/AgentConnectionDriveScopeDialog.d.ts +20 -0
  75. package/dist/types/admin/connections/AgentConnectionDriveSearchFilters.d.ts +34 -0
  76. package/dist/types/admin/connections/AgentConnectionDrivesDrawer.d.ts +39 -0
  77. package/dist/types/admin/connections/AgentConnectionLevelsDrawer.d.ts +27 -0
  78. package/dist/types/admin/connections/AgentConnectionSharingDialog.d.ts +12 -0
  79. package/dist/types/admin/connections/AgentConnectionsPanel.d.ts +105 -0
  80. package/dist/types/admin/connections/AgentConnectionsScreen.d.ts +18 -0
  81. package/dist/types/admin/connections/ConnectDialogs.d.ts +22 -0
  82. package/dist/types/admin/connections/agent-connection-drive-scope.d.ts +112 -0
  83. package/dist/types/admin/connections/agent-connection-drives.d.ts +107 -0
  84. package/dist/types/admin/connections/agent-connection-format.d.ts +82 -0
  85. package/dist/types/admin/connections/agent-connection-oauth.d.ts +138 -0
  86. package/dist/types/admin/connections/agent-connections-api.d.ts +420 -0
  87. package/dist/types/admin/connections/agent-connections-context.d.ts +60 -0
  88. package/dist/types/admin/connections/agent-connections-types.d.ts +447 -0
  89. package/dist/types/admin/connections/connection-logos.d.ts +53 -0
  90. package/dist/types/admin/connections/connection-parts.d.ts +84 -0
  91. package/dist/types/admin/connections/use-agent-connect.d.ts +25 -0
  92. package/dist/types/admin/context/CompactionThresholdBanner.d.ts +13 -0
  93. package/dist/types/admin/context/ContextCompositionPanel.d.ts +27 -0
  94. package/dist/types/admin/context/ContextSegmentList.d.ts +20 -0
  95. package/dist/types/admin/context/SentPayloadPanel.d.ts +37 -0
  96. package/dist/types/admin/context/agent-inspect-context-api.d.ts +53 -0
  97. package/dist/types/admin/context/agent-inspect-context-types.d.ts +98 -0
  98. package/dist/types/admin/context/context-composition-grouping.d.ts +78 -0
  99. package/dist/types/admin/context/context-segment-families.d.ts +18 -0
  100. package/dist/types/admin/context/context-segment-label-texts.d.ts +19 -0
  101. package/dist/types/admin/context/context-segment-labels.d.ts +18 -0
  102. package/dist/types/admin/control-panel/AgentControlPanelScreen.d.ts +71 -0
  103. package/dist/types/admin/control-panel/BudgetsTab.d.ts +13 -0
  104. package/dist/types/admin/control-panel/SettingsTab.d.ts +22 -0
  105. package/dist/types/admin/control-panel/SpacesTab.d.ts +24 -0
  106. package/dist/types/admin/control-panel/StatisticsTab.d.ts +26 -0
  107. package/dist/types/admin/control-panel/TimeSeriesChartCard.d.ts +37 -0
  108. package/dist/types/admin/control-panel/ToolResponseSamplesDrawer.d.ts +22 -0
  109. package/dist/types/admin/control-panel/agent-control-panel-api.d.ts +104 -0
  110. package/dist/types/admin/control-panel/agent-control-panel-types.d.ts +241 -0
  111. package/dist/types/admin/control-panel/budget-meters.d.ts +35 -0
  112. package/dist/types/admin/control-panel/control-panel-statistics.d.ts +49 -0
  113. package/dist/types/admin/control-panel/runtime-settings-form.d.ts +44 -0
  114. package/dist/types/admin/control-panel/time-series-chart.d.ts +54 -0
  115. package/dist/types/admin/conversations/AgentConversationDetailScreen.d.ts +128 -0
  116. package/dist/types/admin/conversations/AgentConversationsScreen.d.ts +60 -0
  117. package/dist/types/admin/conversations/ContextPanel.d.ts +9 -0
  118. package/dist/types/admin/conversations/ConversationActions.d.ts +32 -0
  119. package/dist/types/admin/conversations/ConversationTurns.d.ts +56 -0
  120. package/dist/types/admin/conversations/DebugSwitchBar.d.ts +23 -0
  121. package/dist/types/admin/conversations/DelegationPanel.d.ts +6 -0
  122. package/dist/types/admin/conversations/ModelContextDialog.d.ts +31 -0
  123. package/dist/types/admin/conversations/RequestCompositionRows.d.ts +14 -0
  124. package/dist/types/admin/conversations/RequestsPanel.d.ts +21 -0
  125. package/dist/types/admin/conversations/SandboxPanel.d.ts +42 -0
  126. package/dist/types/admin/conversations/StepDetailDialog.d.ts +19 -0
  127. package/dist/types/admin/conversations/agent-inspect-api.d.ts +259 -0
  128. package/dist/types/admin/conversations/agent-inspect-mappers.d.ts +23 -0
  129. package/dist/types/admin/conversations/agent-inspect-types.d.ts +517 -0
  130. package/dist/types/admin/conversations/conversation-list-export.d.ts +64 -0
  131. package/dist/types/admin/conversations/conversation-list-filters.d.ts +59 -0
  132. package/dist/types/admin/conversations/debug-switches.d.ts +27 -0
  133. package/dist/types/admin/conversations/delegation-swimlanes.d.ts +78 -0
  134. package/dist/types/admin/conversations/header-facts.d.ts +23 -0
  135. package/dist/types/admin/conversations/inspect-format.d.ts +44 -0
  136. package/dist/types/admin/conversations/inspect-parts.d.ts +42 -0
  137. package/dist/types/admin/conversations/inspect-scope.d.ts +92 -0
  138. package/dist/types/admin/conversations/model-call-rows.d.ts +78 -0
  139. package/dist/types/admin/conversations/step-descriptions.d.ts +43 -0
  140. package/dist/types/admin/conversations/touched-files-tree.d.ts +47 -0
  141. package/dist/types/admin/conversations/turn-paging.d.ts +56 -0
  142. package/dist/types/admin/conversations/turn-segments.d.ts +36 -0
  143. package/dist/types/admin/conversations/turn-timeline.d.ts +22 -0
  144. package/dist/types/admin/conversations/use-query-loader.d.ts +8 -0
  145. package/dist/types/admin/period/AdminPeriodControl.d.ts +15 -0
  146. package/dist/types/admin/period/admin-period.d.ts +51 -0
  147. package/dist/types/admin/quality/AgentQualityEvalRunScreen.d.ts +30 -0
  148. package/dist/types/admin/quality/AgentQualityScreen.d.ts +38 -0
  149. package/dist/types/admin/quality/SaveAsEvalCaseDialog.d.ts +27 -0
  150. package/dist/types/admin/quality/agent-quality-api.d.ts +86 -0
  151. package/dist/types/admin/quality/agent-quality-format.d.ts +52 -0
  152. package/dist/types/admin/quality/agent-quality-types.d.ts +161 -0
  153. package/dist/types/admin/schedules/AgentSchedulesPanel.d.ts +43 -0
  154. package/dist/types/admin/schedules/agent-schedules-api.d.ts +116 -0
  155. package/dist/types/admin/schedules/agent-schedules-format.d.ts +25 -0
  156. package/dist/types/admin/schedules/agent-schedules-types.d.ts +113 -0
  157. package/dist/types/admin/shared/AdminHrefLink.d.ts +13 -0
  158. package/dist/types/admin/skills/AgentSkillCatalogScreen.d.ts +51 -0
  159. package/dist/types/admin/skills/SharedBlocksPanel.d.ts +14 -0
  160. package/dist/types/admin/skills/SkillLoadSourcesPanel.d.ts +20 -0
  161. package/dist/types/admin/skills/SkillPurposesPanel.d.ts +16 -0
  162. package/dist/types/admin/skills/SkillTreeRowView.d.ts +31 -0
  163. package/dist/types/admin/skills/ToolSchemaDrawer.d.ts +21 -0
  164. package/dist/types/admin/skills/agent-skill-catalog-api.d.ts +101 -0
  165. package/dist/types/admin/skills/agent-skill-catalog-types.d.ts +259 -0
  166. package/dist/types/admin/skills/skill-catalog-colors.d.ts +10 -0
  167. package/dist/types/admin/skills/skill-catalog-tree.d.ts +159 -0
  168. package/dist/types/admin/skills/skill-purpose-texts.d.ts +11 -0
  169. package/dist/types/admin/wire/admin-wire.d.ts +21 -0
  170. package/dist/types/chat/controller/AgentChatController.d.ts +22 -0
  171. package/dist/types/chat/controller/turn-initiators.d.ts +21 -0
  172. package/dist/types/chat/trace/BackgroundTasksList.d.ts +35 -0
  173. package/dist/types/chat/trace/ChangeSetCard.d.ts +34 -0
  174. package/dist/types/chat/trace/ChangedFilesPane.d.ts +33 -0
  175. package/dist/types/chat/trace/ChangedRecordsList.d.ts +34 -0
  176. package/dist/types/chat/trace/ConsentRequestCard.d.ts +23 -0
  177. package/dist/types/chat/trace/ContextRing.d.ts +19 -0
  178. package/dist/types/chat/trace/ConversationChildTrace.d.ts +18 -0
  179. package/dist/types/chat/trace/ConversationTurnTrace.d.ts +48 -0
  180. package/dist/types/chat/trace/EntityChip.d.ts +23 -0
  181. package/dist/types/chat/trace/FileChangesSummary.d.ts +14 -0
  182. package/dist/types/chat/trace/FileEditBlock.d.ts +42 -0
  183. package/dist/types/chat/trace/LoadedSkillsDisclosure.d.ts +16 -0
  184. package/dist/types/chat/trace/QueuedMessageChip.d.ts +17 -0
  185. package/dist/types/chat/trace/RunStatusLine.d.ts +27 -0
  186. package/dist/types/chat/trace/StepKindDetails.d.ts +59 -0
  187. package/dist/types/chat/trace/SubAgentStepGroup.d.ts +53 -0
  188. package/dist/types/chat/trace/TaskPlanPane.d.ts +31 -0
  189. package/dist/types/chat/trace/TaskPlanRow.d.ts +28 -0
  190. package/dist/types/chat/trace/TerminalBlock.d.ts +16 -0
  191. package/dist/types/chat/trace/ThinkingBlock.d.ts +19 -0
  192. package/dist/types/chat/trace/ToolStepDetail.d.ts +49 -0
  193. package/dist/types/chat/trace/ToolStepGroup.d.ts +58 -0
  194. package/dist/types/chat/trace/ToolStepRow.d.ts +52 -0
  195. package/dist/types/chat/trace/TraceViewModeSwitch.d.ts +14 -0
  196. package/dist/types/chat/trace/TurnMetaLine.d.ts +27 -0
  197. package/dist/types/chat/trace/content-from-unified-diff.d.ts +25 -0
  198. package/dist/types/chat/trace/conversation-trace-loader.d.ts +133 -0
  199. package/dist/types/chat/trace/index.d.ts +34 -0
  200. package/dist/types/chat/trace/parse-unified-diff.d.ts +51 -0
  201. package/dist/types/chat/trace/task-plan-counts.d.ts +41 -0
  202. package/dist/types/chat/trace/trace-collect.d.ts +91 -0
  203. package/dist/types/chat/trace/trace-counts.d.ts +21 -0
  204. package/dist/types/chat/trace/trace-format.d.ts +73 -0
  205. package/dist/types/chat/trace/trace-labels.d.ts +60 -0
  206. package/dist/types/chat/trace/trace-parts.d.ts +63 -0
  207. package/dist/types/chat/trace/trace-step-focus.d.ts +12 -0
  208. package/dist/types/chat/trace/trace-types.d.ts +370 -0
  209. package/dist/types/chat/trace/use-conversation-trace.d.ts +47 -0
  210. package/dist/types/client/AgentsConversationClient.d.ts +20 -0
  211. package/dist/types/client/http/agents-http-trace-mappers.d.ts +31 -0
  212. package/dist/types/client/http/agents-http-trace-wire.d.ts +433 -0
  213. package/dist/types/contract/conversation-trace.d.ts +594 -0
  214. package/dist/types/entries/admin.d.ts +86 -0
  215. package/dist/types/entries/chat.d.ts +3 -1
  216. package/dist/types/entries/client.d.ts +2 -0
  217. package/dist/types/entries/contract.d.ts +1 -0
  218. package/dist/types/provider/components/icon-names.d.ts +4 -2
  219. package/dist/types/provider/components/types.d.ts +3 -1
  220. package/dist/types/widgets/DriveFilesConversationWidget/shared/drive-files.d.ts +1 -1
  221. package/dist/voice.js +3 -3
  222. package/dist/widgets.js +6 -6
  223. package/package.json +7 -3
  224. package/public-api.json +1047 -3
  225. package/dist/chunks/WebSearchResultsConversationWidget-dEq19U7k.js.map +0 -1
  226. package/dist/chunks/icon-names-Di6c4zLo.js.map +0 -1
  227. package/dist/chunks/link-navigation-DRHt6g7U.js.map +0 -1
@@ -0,0 +1,2927 @@
1
+ "use client";
2
+ import { jsx, jsxs, Fragment } from "react/jsx-runtime";
3
+ import { a0 as translateText, a6 as useAgentsOwnerSettings, I as Icon, E as classNames } from "./index-DZovGMpG.js";
4
+ import { useMemo, useState, useRef, useEffect, useCallback, useId } from "react";
5
+ import { t as textKey } from "./text-key-DnoZ4lAk.js";
6
+ const readTraceMoment = (value) => {
7
+ if (!value) return null;
8
+ const hasZone = /(?:Z|[+-]\d{2}:?\d{2})$/.test(value);
9
+ const moment = Date.parse(hasZone ? value : `${value.replace(" ", "T")}Z`);
10
+ return Number.isFinite(moment) ? moment : null;
11
+ };
12
+ const formatTraceClock = (elapsedMs) => {
13
+ const elapsedSeconds = Math.max(0, Math.floor(elapsedMs / 1e3));
14
+ return `${Math.floor(elapsedSeconds / 60)}:${String(elapsedSeconds % 60).padStart(2, "0")}`;
15
+ };
16
+ const createTraceFormat = (locale, timeZone) => {
17
+ const localeOrDefault = locale ?? void 0;
18
+ const oneDecimal = new Intl.NumberFormat(localeOrDefault, { minimumFractionDigits: 1, maximumFractionDigits: 1 });
19
+ const upToOneDecimal = new Intl.NumberFormat(localeOrDefault, { maximumFractionDigits: 1 });
20
+ const whole = new Intl.NumberFormat(localeOrDefault, { maximumFractionDigits: 0 });
21
+ const compact2 = new Intl.NumberFormat(localeOrDefault, { notation: "compact", maximumFractionDigits: 1 });
22
+ const smallCost = new Intl.NumberFormat(localeOrDefault, { style: "currency", currency: "USD", minimumFractionDigits: 3, maximumFractionDigits: 3 });
23
+ const largeCost = new Intl.NumberFormat(localeOrDefault, { style: "currency", currency: "USD", minimumFractionDigits: 2, maximumFractionDigits: 2 });
24
+ const clockTime = new Intl.DateTimeFormat(localeOrDefault, { hour: "2-digit", minute: "2-digit", timeZone: timeZone ?? void 0 });
25
+ return {
26
+ duration: (durationMs) => {
27
+ const safeDurationMs = Math.max(0, durationMs);
28
+ if (safeDurationMs < 1e3) return `${whole.format(Math.round(safeDurationMs))} ms`;
29
+ if (safeDurationMs < 1e4) return `${oneDecimal.format(safeDurationMs / 1e3)} s`;
30
+ if (safeDurationMs < 6e4) return `${upToOneDecimal.format(safeDurationMs / 1e3)} s`;
31
+ return `${formatTraceClock(safeDurationMs)} min`;
32
+ },
33
+ count: (value) => Math.abs(value) < 1e3 ? whole.format(value) : compact2.format(value),
34
+ number: (value) => whole.format(value),
35
+ bytes: (sizeInBytes) => {
36
+ if (sizeInBytes < 1024) return `${whole.format(sizeInBytes)} B`;
37
+ const sizeInKilobytes = sizeInBytes / 1024;
38
+ if (sizeInKilobytes < 10) return `${oneDecimal.format(sizeInKilobytes)} KB`;
39
+ if (sizeInKilobytes < 1024) return `${whole.format(Math.round(sizeInKilobytes))} KB`;
40
+ return `${oneDecimal.format(sizeInKilobytes / 1024)} MB`;
41
+ },
42
+ cost: (costInUsd) => Math.abs(costInUsd) < 1 ? smallCost.format(costInUsd) : largeCost.format(costInUsd),
43
+ time: (moment) => clockTime.format(moment)
44
+ };
45
+ };
46
+ const useTraceFormat = () => {
47
+ const { locale, timeZone } = useAgentsOwnerSettings();
48
+ return useMemo(() => createTraceFormat(locale, timeZone), [locale, timeZone]);
49
+ };
50
+ const describeTraceModelName = (modelName) => {
51
+ if (!modelName) return null;
52
+ const dotPosition = modelName.indexOf(".");
53
+ const nameWithoutProvider = dotPosition !== -1 && dotPosition < modelName.length - 1 ? modelName.slice(dotPosition + 1) : modelName;
54
+ const label2 = nameWithoutProvider.replace(/_/g, " ").trim();
55
+ return label2 === "" ? null : label2;
56
+ };
57
+ const describeTraceEffort = (effort) => {
58
+ if (!effort) return null;
59
+ switch (effort) {
60
+ case "minimal":
61
+ return translateText("Minimal", void 0, "agent-effort");
62
+ case "low":
63
+ return translateText("Low", void 0, "agent-effort");
64
+ case "medium":
65
+ return translateText("Medium", void 0, "agent-effort");
66
+ case "high":
67
+ return translateText("High", void 0, "agent-effort");
68
+ case "xhigh":
69
+ return translateText("Very high", void 0, "agent-effort");
70
+ default:
71
+ return effort;
72
+ }
73
+ };
74
+ const formatShortSha256 = (sha256) => {
75
+ if (!sha256) return null;
76
+ return sha256.length <= 12 ? sha256 : `${sha256.slice(0, 4)}…${sha256.slice(-4)}`;
77
+ };
78
+ const RUNNING_STATUSES = ["RUNNING", "CANCEL_REQUESTED"];
79
+ const DONE_STATUSES$1 = ["COMPLETED", "DONE", "SUCCEEDED"];
80
+ const FAILED_STATUSES = ["FAILED", "ERROR", "TIMED_OUT"];
81
+ const WAITING_STATUSES = ["PENDING", "QUEUED", "WAITING"];
82
+ const readTraceStateOfStatus = (status) => {
83
+ const normalizedStatus = (status ?? "").toUpperCase();
84
+ if (RUNNING_STATUSES.includes(normalizedStatus)) return "running";
85
+ if (FAILED_STATUSES.includes(normalizedStatus)) return "failed";
86
+ if (WAITING_STATUSES.includes(normalizedStatus)) return "waiting";
87
+ if (normalizedStatus === "CANCELLED") return "cancelled";
88
+ if (DONE_STATUSES$1.includes(normalizedStatus)) return "done";
89
+ return "done";
90
+ };
91
+ const readTraceStepState = (step) => {
92
+ if (step.isHeldForConsent) return "waiting";
93
+ if (step.kind === "ERROR") return "failed";
94
+ if (step.isRefused || (step.status ?? "").toUpperCase() === "REFUSED") return "cancelled";
95
+ const state = readTraceStateOfStatus(step.status);
96
+ if (state === "done" && step.terminal && ((step.terminal.exitCode ?? 0) !== 0 || step.terminal.timedOut)) return "failed";
97
+ return state;
98
+ };
99
+ const readTraceSubAgentState = (subAgent) => {
100
+ const runs = subAgent.runs ?? [];
101
+ return readTraceStateOfStatus(subAgent.status ?? runs[runs.length - 1]?.status ?? null);
102
+ };
103
+ const readTraceStepIcon = (step) => {
104
+ switch (step.kind) {
105
+ case "THINKING":
106
+ return "thinking";
107
+ case "MODEL_CALL":
108
+ return "model";
109
+ case "SKILL_LOAD":
110
+ return "skill";
111
+ case "SUB_AGENT":
112
+ return "subAgent";
113
+ case "WIDGET":
114
+ return "widget";
115
+ case "COMPACTION":
116
+ return "compaction";
117
+ case "SIGNAL":
118
+ return "signal";
119
+ case "DECISION":
120
+ return "decision";
121
+ case "TASK_PLAN":
122
+ return "steps";
123
+ case "ERROR":
124
+ return "stepError";
125
+ }
126
+ if (step.terminal) return "terminal";
127
+ const firstFileChange = step.fileChanges?.[0];
128
+ if (firstFileChange) return readTraceFileChangeIcon(firstFileChange.changeType ?? null);
129
+ if (step.effect === "DELETE") return "fileDelete";
130
+ if (step.effect === "WRITE") return "toolWrite";
131
+ if (step.effect === "WORKSPACE") return "terminal";
132
+ return "toolRead";
133
+ };
134
+ const readTraceFileChangeIcon = (changeType) => {
135
+ switch (changeType) {
136
+ case "ADDED":
137
+ return "fileAdd";
138
+ case "DELETED":
139
+ return "fileDelete";
140
+ case "RENAMED":
141
+ return "fileMove";
142
+ case "DIRECTORY_CREATED":
143
+ return "folderAdd";
144
+ default:
145
+ return "fileEdit";
146
+ }
147
+ };
148
+ const readTraceFileChangeLetter = (changeType) => {
149
+ switch (changeType) {
150
+ case "ADDED":
151
+ return "A";
152
+ case "DELETED":
153
+ return "D";
154
+ case "RENAMED":
155
+ return "R";
156
+ case "DIRECTORY_CREATED":
157
+ return "+";
158
+ default:
159
+ return "M";
160
+ }
161
+ };
162
+ const readTraceFileChangeWord = (changeType) => {
163
+ switch (changeType) {
164
+ case "ADDED":
165
+ return translateText("New file");
166
+ case "DELETED":
167
+ return translateText("Deleted");
168
+ case "RENAMED":
169
+ return translateText("Renamed");
170
+ case "DIRECTORY_CREATED":
171
+ return translateText("New folder");
172
+ default:
173
+ return translateText("Edited");
174
+ }
175
+ };
176
+ const DEFAULT_MOUNT_TONES = {
177
+ OWN_DRIVE: "own",
178
+ SHARED_DRIVE: "shared",
179
+ EXTERNAL_DRIVE: "external"
180
+ };
181
+ const describeTraceMount = (describeMount, mountKind, mountName, driveSpaceId) => {
182
+ const defaultTone = DEFAULT_MOUNT_TONES[mountKind ?? ""] ?? "neutral";
183
+ const described = describeMount?.(mountKind ?? null, mountName ?? null, driveSpaceId ?? null);
184
+ if (typeof described === "string") return described === "" ? null : { label: described, tone: defaultTone };
185
+ if (described) return { label: described.label, tone: described.tone ?? defaultTone };
186
+ if (describeMount) return null;
187
+ const label2 = mountName ?? mountKind ?? null;
188
+ return label2 ? { label: label2, tone: defaultTone } : null;
189
+ };
190
+ const readTraceFileName = (path2) => {
191
+ const segments = path2.split("/").filter((segment) => segment !== "");
192
+ return segments[segments.length - 1] ?? path2;
193
+ };
194
+ const prettyPrintTraceJson = (text) => {
195
+ const trimmedText = text.trim();
196
+ if (trimmedText === "" || !/^[[{"]|^-?\d|^(?:true|false|null)$/.test(trimmedText)) return text;
197
+ try {
198
+ return JSON.stringify(JSON.parse(trimmedText), null, 2);
199
+ } catch {
200
+ return text;
201
+ }
202
+ };
203
+ const readTraceIdInWords = (id) => id.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_.]+/g, " ").trim().toLowerCase();
204
+ const SKILL_CAUSE_LABELS = {
205
+ MODEL: () => translateText("asked for by the model", void 0, "skill-cause"),
206
+ PRELOAD: () => translateText("loaded without a call", void 0, "skill-cause"),
207
+ TOOL_CALL: () => translateText("loaded by a tool call", void 0, "skill-cause"),
208
+ DECISION_MODEL: () => translateText("decision model", void 0, "skill-cause"),
209
+ PLAN_ITEM: () => translateText("plan item", void 0, "skill-cause"),
210
+ STRUCTURAL: () => translateText("conversation setup", void 0, "skill-cause"),
211
+ ALWAYS_LOADED: () => translateText("always loaded", void 0, "skill-cause")
212
+ };
213
+ const describeTraceSkillCause = (cause) => {
214
+ if (!cause) return null;
215
+ const key = cause.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toUpperCase();
216
+ return SKILL_CAUSE_LABELS[key]?.() ?? readTraceIdInWords(cause);
217
+ };
218
+ const readTraceRunResultText = (result) => {
219
+ if (result == null) return null;
220
+ const trimmed = result.trim();
221
+ if (trimmed === "") return null;
222
+ if (!trimmed.startsWith("{") || !trimmed.endsWith("}")) return result;
223
+ let parsed;
224
+ try {
225
+ parsed = JSON.parse(trimmed);
226
+ } catch {
227
+ return result;
228
+ }
229
+ const content = parsed?.content;
230
+ if (!Array.isArray(content)) return result;
231
+ const texts = content.flatMap((part) => {
232
+ const text = part?.text;
233
+ return part?.type === "text" && typeof text === "string" && text !== "" ? [text] : [];
234
+ });
235
+ return texts.length > 0 ? texts.join("\n\n") : result;
236
+ };
237
+ const steps = "agents_steps_I-blad";
238
+ const row = "agents_row_4Is8pD";
239
+ const rowInteractive = "agents_rowInteractive_W4b-Rw";
240
+ const rowToggle = "agents_rowToggle_oQpxwH";
241
+ const chips = "agents_chips_J66HR1";
242
+ const meta = "agents_meta_yg7Aog";
243
+ const rowOpen = "agents_rowOpen_0tl9t7";
244
+ const rowIcon = "agents_rowIcon_UuFSep";
245
+ const label = "agents_label_y6rdIJ";
246
+ const labelRegular = "agents_labelRegular_QyRWqK";
247
+ const labelLead = "agents_labelLead_yrblKv";
248
+ const target = "agents_target_Xk4AQi";
249
+ const targetText = "agents_targetText_YvPOR5";
250
+ const entityChip = "agents_entityChip_pIP5-r";
251
+ const viaCallTool = "agents_viaCallTool_l3vL7V";
252
+ const chevron$1 = "agents_chevron_AtCxYH";
253
+ const rowFold = "agents_rowFold_Ubf2M4";
254
+ const rowThinking = "agents_rowThinking_nZRFho";
255
+ const rowWaiting = "agents_rowWaiting_Ukl6oG";
256
+ const added$1 = "agents_added_YpJLEI";
257
+ const removed$1 = "agents_removed_7vqELx";
258
+ const stateDone = "agents_stateDone_-6CBFF";
259
+ const stateFailed = "agents_stateFailed_eD2OxW";
260
+ const stateWaiting = "agents_stateWaiting_X4Tsne";
261
+ const stateCancelled = "agents_stateCancelled_dZHc32";
262
+ const spinner = "agents_spinner_q2z5Pe";
263
+ const spinnerWaiting = "agents_spinnerWaiting_tujcJX";
264
+ const body = "agents_body_J5k63T";
265
+ const nest = "agents_nest_Zo4gHK";
266
+ const compact = "agents_compact_WvKySe";
267
+ const entityChipLabel = "agents_entityChipLabel_dO3IUZ";
268
+ const entityChipIcon = "agents_entityChipIcon_w0Zp-i";
269
+ const badge = "agents_badge_T-BPQ-";
270
+ const badgeWarning = "agents_badgeWarning_wS-qkz";
271
+ const badgeSuccess = "agents_badgeSuccess_p24Cf5";
272
+ const badgeDanger = "agents_badgeDanger_XlMCcm";
273
+ const detail = "agents_detail_PnA2S9";
274
+ const detailPanels = "agents_detailPanels_oC-3dw";
275
+ const detailPanelsSingle = "agents_detailPanelsSingle_nuS9o3";
276
+ const panel = "agents_panel_rl-W-t";
277
+ const panelHead = "agents_panelHead_RPl6oA";
278
+ const panelTitle = "agents_panelTitle_ATBMan";
279
+ const panelCut = "agents_panelCut_XVJbjz";
280
+ const panelGrow = "agents_panelGrow_dbSBCj";
281
+ const copyButton = "agents_copyButton_udE31m";
282
+ const code = "agents_code_mrFprJ";
283
+ const facts$1 = "agents_facts_NcVC01";
284
+ const metaLine = "agents_metaLine_vpvhan";
285
+ const metaLineCompact = "agents_metaLineCompact_ljQV2w";
286
+ const pill = "agents_pill_ZnJbFD";
287
+ const pillIcon = "agents_pillIcon_Omlq5G";
288
+ const pillModel = "agents_pillModel_LN-h1J";
289
+ const pillWarning = "agents_pillWarning_dMTCba";
290
+ const pillDanger = "agents_pillDanger_6BQ3GD";
291
+ const pillCode = "agents_pillCode_eBuZMO";
292
+ const pillSuccess = "agents_pillSuccess_NjkXvL";
293
+ const detailText = "agents_detailText_H9HE7e";
294
+ const detailQuiet = "agents_detailQuiet_-GfVIx";
295
+ const metaGrow = "agents_metaGrow_MZ4T-q";
296
+ const metaLinks = "agents_metaLinks_Lrgvrq";
297
+ const link = "agents_link_tP0BeZ";
298
+ const viewModes = "agents_viewModes_Gwx-bq";
299
+ const viewMode = "agents_viewMode_GXBqc1";
300
+ const viewModeOn = "agents_viewModeOn_Ap40XO";
301
+ const viewModeVerboseOn = "agents_viewModeVerboseOn_RjqDsj";
302
+ const viewModesCompact = "agents_viewModesCompact_30PoWY";
303
+ const turnTrace = "agents_turnTrace_aw5PNy";
304
+ const turnTraceCompact = "agents_turnTraceCompact_-zAeYK";
305
+ const summaryChip = "agents_summaryChip_d0a9km";
306
+ const statusLine = "agents_statusLine_I8ZJ-R";
307
+ const statusText = "agents_statusText_CVIck0";
308
+ const statusWord = "agents_statusWord_HyzN0J";
309
+ const stopButton = "agents_stopButton_O86m4X";
310
+ const stopSquare = "agents_stopSquare_3wJObt";
311
+ const queued = "agents_queued_qDHG-l";
312
+ const queuedInThread = "agents_queuedInThread_yuh1Ta";
313
+ const consentCard = "agents_consentCard_7meL-c";
314
+ const consentCardCompact = "agents_consentCardCompact_ObUEXF";
315
+ const consentHead = "agents_consentHead_-WSYv2";
316
+ const consentTitle = "agents_consentTitle_QS1ZRS";
317
+ const consentCalls = "agents_consentCalls_RrUE62";
318
+ const consentActions = "agents_consentActions_Ecv8p4";
319
+ const consentApprove = "agents_consentApprove_z8v3q5";
320
+ const consentDecline = "agents_consentDecline_bUQkez";
321
+ const consentNote = "agents_consentNote_zxqcPR";
322
+ const queuedTakenUp = "agents_queuedTakenUp_lZdona";
323
+ const queuedText = "agents_queuedText_-Jbytg";
324
+ const queuedQuote = "agents_queuedQuote_jgrb8Y";
325
+ const plan = "agents_plan_5TCJ74";
326
+ const planHead = "agents_planHead_pbIOE4";
327
+ const planHeadStatic = "agents_planHeadStatic_dIx5pa";
328
+ const planTitle = "agents_planTitle_1MmqIt";
329
+ const planProgress = "agents_planProgress_bFpejt";
330
+ const planItems = "agents_planItems_QjfAs8";
331
+ const planItem = "agents_planItem_k-RwI4";
332
+ const planItemDone = "agents_planItemDone_o2fmrB";
333
+ const planItemCurrent = "agents_planItemCurrent_5d49Iv";
334
+ const planBox = "agents_planBox_aWgl36";
335
+ const ring = "agents_ring_U2U3ls";
336
+ const ringInteractive = "agents_ringInteractive_mtDinx";
337
+ const ringSvg = "agents_ringSvg_KUZ9g6";
338
+ const ringTrack = "agents_ringTrack_sv2lLQ";
339
+ const ringArc = "agents_ringArc_6Ji7Po";
340
+ const ringArcHigh = "agents_ringArcHigh_Z7VyCo";
341
+ const ringArcFull = "agents_ringArcFull_y98X1l";
342
+ const visuallyHidden = "agents_visuallyHidden_Qio4MD";
343
+ const anchor = "agents_anchor_UQ3Ufq";
344
+ const styles$1 = {
345
+ steps,
346
+ row,
347
+ rowInteractive,
348
+ rowToggle,
349
+ chips,
350
+ meta,
351
+ rowOpen,
352
+ rowIcon,
353
+ label,
354
+ labelRegular,
355
+ labelLead,
356
+ target,
357
+ targetText,
358
+ entityChip,
359
+ viaCallTool,
360
+ chevron: chevron$1,
361
+ rowFold,
362
+ rowThinking,
363
+ rowWaiting,
364
+ added: added$1,
365
+ removed: removed$1,
366
+ stateDone,
367
+ stateFailed,
368
+ stateWaiting,
369
+ stateCancelled,
370
+ spinner,
371
+ spinnerWaiting,
372
+ body,
373
+ nest,
374
+ compact,
375
+ entityChipLabel,
376
+ entityChipIcon,
377
+ badge,
378
+ badgeWarning,
379
+ badgeSuccess,
380
+ badgeDanger,
381
+ detail,
382
+ detailPanels,
383
+ detailPanelsSingle,
384
+ panel,
385
+ panelHead,
386
+ panelTitle,
387
+ panelCut,
388
+ panelGrow,
389
+ copyButton,
390
+ code,
391
+ facts: facts$1,
392
+ metaLine,
393
+ metaLineCompact,
394
+ pill,
395
+ pillIcon,
396
+ pillModel,
397
+ pillWarning,
398
+ pillDanger,
399
+ pillCode,
400
+ pillSuccess,
401
+ detailText,
402
+ detailQuiet,
403
+ metaGrow,
404
+ metaLinks,
405
+ link,
406
+ viewModes,
407
+ viewMode,
408
+ viewModeOn,
409
+ viewModeVerboseOn,
410
+ viewModesCompact,
411
+ turnTrace,
412
+ turnTraceCompact,
413
+ summaryChip,
414
+ statusLine,
415
+ statusText,
416
+ statusWord,
417
+ stopButton,
418
+ stopSquare,
419
+ queued,
420
+ queuedInThread,
421
+ consentCard,
422
+ consentCardCompact,
423
+ consentHead,
424
+ consentTitle,
425
+ consentCalls,
426
+ consentActions,
427
+ consentApprove,
428
+ consentDecline,
429
+ consentNote,
430
+ queuedTakenUp,
431
+ queuedText,
432
+ queuedQuote,
433
+ plan,
434
+ planHead,
435
+ planHeadStatic,
436
+ planTitle,
437
+ planProgress,
438
+ planItems,
439
+ planItem,
440
+ planItemDone,
441
+ planItemCurrent,
442
+ planBox,
443
+ ring,
444
+ ringInteractive,
445
+ ringSvg,
446
+ ringTrack,
447
+ ringArc,
448
+ ringArcHigh,
449
+ ringArcFull,
450
+ visuallyHidden,
451
+ anchor
452
+ };
453
+ const TraceViewModeSwitch = (props) => {
454
+ const { viewMode: viewMode2, onViewModeChange, isVerboseAllowed = false, isCompact = false, className } = props;
455
+ const options = [
456
+ { viewMode: "summary", label: translateText("Short") },
457
+ { viewMode: "normal", label: translateText("Normal") },
458
+ ...isVerboseAllowed ? [{ viewMode: "verbose", label: translateText("Verbose") }] : []
459
+ ];
460
+ const shownViewMode = viewMode2 === "verbose" && !isVerboseAllowed ? "normal" : viewMode2;
461
+ const moveBy = (offset, group) => {
462
+ const position = options.findIndex((option) => option.viewMode === shownViewMode);
463
+ const next = options[(position + offset + options.length) % options.length];
464
+ if (!next) return;
465
+ onViewModeChange(next.viewMode);
466
+ group?.querySelector(`[data-view-mode="${next.viewMode}"]`)?.focus();
467
+ };
468
+ return /* @__PURE__ */ jsx(
469
+ "div",
470
+ {
471
+ className: classNames(styles$1.viewModes, isCompact && styles$1.viewModesCompact, className),
472
+ role: "radiogroup",
473
+ "aria-label": translateText("Detail of the steps"),
474
+ "data-testid": "trace-view-mode-switch",
475
+ children: options.map((option) => {
476
+ const isOn = option.viewMode === shownViewMode;
477
+ return /* @__PURE__ */ jsxs(
478
+ "button",
479
+ {
480
+ type: "button",
481
+ role: "radio",
482
+ "aria-checked": isOn,
483
+ tabIndex: isOn ? 0 : -1,
484
+ className: classNames(styles$1.viewMode, isOn && (option.viewMode === "verbose" ? styles$1.viewModeVerboseOn : styles$1.viewModeOn)),
485
+ "data-view-mode": option.viewMode,
486
+ onClick: () => onViewModeChange(option.viewMode),
487
+ onKeyDown: (event) => {
488
+ if (event.key === "ArrowRight" || event.key === "ArrowDown") {
489
+ event.preventDefault();
490
+ moveBy(1, event.currentTarget.parentElement);
491
+ } else if (event.key === "ArrowLeft" || event.key === "ArrowUp") {
492
+ event.preventDefault();
493
+ moveBy(-1, event.currentTarget.parentElement);
494
+ }
495
+ },
496
+ children: [
497
+ option.viewMode === "verbose" ? /* @__PURE__ */ jsx(Icon, { name: "code", pixelSize: 12 }) : null,
498
+ option.label
499
+ ]
500
+ },
501
+ option.viewMode
502
+ );
503
+ })
504
+ }
505
+ );
506
+ };
507
+ const describeStepCount = (count, format) => {
508
+ const replacements = { count: format.number(count) };
509
+ return count === 1 ? translateText("%count% step", replacements, "one") : translateText("%count% steps", replacements, "other");
510
+ };
511
+ const describeFileCount = (count, format) => {
512
+ const replacements = { count: format.number(count) };
513
+ return count === 1 ? translateText("%count% file", replacements, "one") : translateText("%count% files", replacements, "other");
514
+ };
515
+ const describeCommandCount = (count, format) => {
516
+ const replacements = { count: format.number(count) };
517
+ return count === 1 ? translateText("%count% command", replacements, "one") : translateText("%count% commands", replacements, "other");
518
+ };
519
+ const describeSubAgentCount = (count, format) => {
520
+ const replacements = { count: format.number(count) };
521
+ return count === 1 ? translateText("%count% sub-agent", replacements, "one") : translateText("%count% sub-agents", replacements, "other");
522
+ };
523
+ const describeLoadedSkillCount = (count, format) => {
524
+ const replacements = { count: format.number(count) };
525
+ return count === 1 ? translateText("%count% skill loaded", replacements, "one") : translateText("%count% skills loaded", replacements, "other");
526
+ };
527
+ const describeToolCount = (count, format) => {
528
+ const replacements = { count: format.number(count) };
529
+ return count === 1 ? translateText("%count% tool", replacements, "one") : translateText("%count% tools", replacements, "other");
530
+ };
531
+ const describeMessageCount = (count, format) => {
532
+ const replacements = { count: format.number(count) };
533
+ return count === 1 ? translateText("%count% message", replacements, "one") : translateText("%count% messages", replacements, "other");
534
+ };
535
+ const describeHiddenLineCount = (count, format) => {
536
+ const replacements = { count: format.number(count) };
537
+ return count === 1 ? translateText("… %count% more line", replacements, "one") : translateText("… %count% more lines", replacements, "other");
538
+ };
539
+ const describeShowMoreLines = (count, format) => {
540
+ const replacements = { count: format.number(count) };
541
+ return count === 1 ? translateText("Show %count% more line", replacements, "one") : translateText("Show %count% more lines", replacements, "other");
542
+ };
543
+ const terminal = "agents_terminal_PfB-G1";
544
+ const terminalHead = "agents_terminalHead_ahwvUe";
545
+ const prompt = "agents_prompt_YhgKyC";
546
+ const command = "agents_command_Fm0jvp";
547
+ const terminalMeta = "agents_terminalMeta_4OYH4m";
548
+ const cwd = "agents_cwd_n-7-bt";
549
+ const terminalSans = "agents_terminalSans_jg0vWY";
550
+ const exit = "agents_exit_RbIRnu";
551
+ const exitOk = "agents_exitOk_lmEh9U";
552
+ const exitBad = "agents_exitBad_zDjnbO";
553
+ const exitRunning = "agents_exitRunning_GeZ9yb";
554
+ const output = "agents_output_aWdBzj";
555
+ const outputError = "agents_outputError_QKOQBa";
556
+ const outputErrorColour = "agents_outputErrorColour_t4x6Ag";
557
+ const terminalNote = "agents_terminalNote_Dv3s1Z";
558
+ const terminalMore = "agents_terminalMore_0De52F";
559
+ const fileBlock = "agents_fileBlock_Lo-ZIg";
560
+ const fileHead = "agents_fileHead_-2NNZW";
561
+ const fileHeadWithBody = "agents_fileHeadWithBody_471l9K";
562
+ const fileHeadMain = "agents_fileHeadMain_Xj-XU4";
563
+ const fileHeadActions = "agents_fileHeadActions_hc9UAz";
564
+ const previewLink = "agents_previewLink_J7xyPe";
565
+ const fileTitle = "agents_fileTitle_EuNNvY";
566
+ const fileStats = "agents_fileStats_55fALQ";
567
+ const fileIcon = "agents_fileIcon_M4Zpd2";
568
+ const path = "agents_path_xrWHSu";
569
+ const pathFolders = "agents_pathFolders_-3xiCo";
570
+ const pathName = "agents_pathName_QvM82R";
571
+ const pathMono = "agents_pathMono_bI-QJq";
572
+ const pathArrow = "agents_pathArrow_9dklb9";
573
+ const pathRemoved = "agents_pathRemoved_9yBdP-";
574
+ const mount = "agents_mount_BWPgMz";
575
+ const mountLabel = "agents_mountLabel_kO9CZJ";
576
+ const mountOwn = "agents_mountOwn_qTmxB3";
577
+ const mountShared = "agents_mountShared_KYj2eC";
578
+ const mountExternal = "agents_mountExternal_TLv3oV";
579
+ const added = "agents_added_6T73vU";
580
+ const removed = "agents_removed_GHOKfw";
581
+ const fileFact = "agents_fileFact_FsDWts";
582
+ const sha = "agents_sha_mNke4L";
583
+ const grow = "agents_grow_xTws3B";
584
+ const operation = "agents_operation_6ybi5K";
585
+ const operationLetter = "agents_operationLetter_vJwQDv";
586
+ const operationAdded = "agents_operationAdded_MsHeOp";
587
+ const operationModified = "agents_operationModified_5j0WzD";
588
+ const operationDeleted = "agents_operationDeleted_fiSPxF";
589
+ const operationRenamed = "agents_operationRenamed_gmIK-K";
590
+ const diffModesRow = "agents_diffModesRow_xIbE5C";
591
+ const diffModes = "agents_diffModes_hOEL59";
592
+ const diffMode = "agents_diffMode_uXnCSa";
593
+ const diffModeOn = "agents_diffModeOn_WASKP-";
594
+ const diffScroll = "agents_diffScroll_HEyJUm";
595
+ const diffTable = "agents_diffTable_n0CoAV";
596
+ const line = "agents_line_HZik-x";
597
+ const lineNumber = "agents_lineNumber_fswbkG";
598
+ const sign = "agents_sign_XHNWDx";
599
+ const lineText = "agents_lineText_rC5KNn";
600
+ const lineAdded = "agents_lineAdded_G0K707";
601
+ const lineRemoved = "agents_lineRemoved_PK0YP0";
602
+ const noNewline = "agents_noNewline_6UWo9Q";
603
+ const hunk = "agents_hunk_Rguoli";
604
+ const sideBySide = "agents_sideBySide_H1J-u-";
605
+ const sideLeft = "agents_sideLeft_-6zJsZ";
606
+ const lineEmpty = "agents_lineEmpty_8Cbh5r";
607
+ const moreLines = "agents_moreLines_3GHqiE";
608
+ const note = "agents_note_rrrlyT";
609
+ const noteDanger = "agents_noteDanger_CAyLSE";
610
+ const preview = "agents_preview_vJ8S5S";
611
+ const thumbnail = "agents_thumbnail_Mp-pkK";
612
+ const thumbnailHost = "agents_thumbnailHost_4BVmw1";
613
+ const thumbnailLine = "agents_thumbnailLine_sexLuU";
614
+ const thumbnailLineShort = "agents_thumbnailLineShort_td3L8l";
615
+ const thumbnailBand = "agents_thumbnailBand_p3udlE";
616
+ const previewFacts = "agents_previewFacts_RXLZQP";
617
+ const previewName = "agents_previewName_0frzn0";
618
+ const previewMeta = "agents_previewMeta_1uPV7v";
619
+ const summary = "agents_summary_d4G02k";
620
+ const summaryPart = "agents_summaryPart_IU0VHy";
621
+ const pane = "agents_pane_SNK52G";
622
+ const paneHead = "agents_paneHead_lOUURm";
623
+ const paneTitle = "agents_paneTitle_Oi3Txq";
624
+ const paneList = "agents_paneList_Bk-5hD";
625
+ const paneFile = "agents_paneFile_QVARtz";
626
+ const paneFileRow = "agents_paneFileRow_OG7rv4";
627
+ const paneFileLink = "agents_paneFileLink_0KKsfO";
628
+ const paneFileOn = "agents_paneFileOn_y5wwy6";
629
+ const paneFileExtra = "agents_paneFileExtra_fu06T9";
630
+ const paneDetail = "agents_paneDetail_QmPLof";
631
+ const paneEmpty = "agents_paneEmpty_MMsadq";
632
+ const styles = {
633
+ terminal,
634
+ terminalHead,
635
+ prompt,
636
+ command,
637
+ terminalMeta,
638
+ cwd,
639
+ terminalSans,
640
+ exit,
641
+ exitOk,
642
+ exitBad,
643
+ exitRunning,
644
+ output,
645
+ outputError,
646
+ outputErrorColour,
647
+ terminalNote,
648
+ terminalMore,
649
+ fileBlock,
650
+ fileHead,
651
+ fileHeadWithBody,
652
+ fileHeadMain,
653
+ fileHeadActions,
654
+ previewLink,
655
+ fileTitle,
656
+ fileStats,
657
+ fileIcon,
658
+ path,
659
+ pathFolders,
660
+ pathName,
661
+ pathMono,
662
+ pathArrow,
663
+ pathRemoved,
664
+ mount,
665
+ mountLabel,
666
+ mountOwn,
667
+ mountShared,
668
+ mountExternal,
669
+ added,
670
+ removed,
671
+ fileFact,
672
+ sha,
673
+ grow,
674
+ operation,
675
+ operationLetter,
676
+ operationAdded,
677
+ operationModified,
678
+ operationDeleted,
679
+ operationRenamed,
680
+ diffModesRow,
681
+ diffModes,
682
+ diffMode,
683
+ diffModeOn,
684
+ diffScroll,
685
+ diffTable,
686
+ line,
687
+ lineNumber,
688
+ sign,
689
+ lineText,
690
+ lineAdded,
691
+ lineRemoved,
692
+ noNewline,
693
+ hunk,
694
+ sideBySide,
695
+ sideLeft,
696
+ lineEmpty,
697
+ moreLines,
698
+ note,
699
+ noteDanger,
700
+ preview,
701
+ thumbnail,
702
+ thumbnailHost,
703
+ thumbnailLine,
704
+ thumbnailLineShort,
705
+ thumbnailBand,
706
+ previewFacts,
707
+ previewName,
708
+ previewMeta,
709
+ summary,
710
+ summaryPart,
711
+ pane,
712
+ paneHead,
713
+ paneTitle,
714
+ paneList,
715
+ paneFile,
716
+ paneFileRow,
717
+ paneFileLink,
718
+ paneFileOn,
719
+ paneFileExtra,
720
+ paneDetail,
721
+ paneEmpty
722
+ };
723
+ const FileChangesSummary = (props) => {
724
+ const { commandCount, fileCount, linesAdded, linesRemoved, className } = props;
725
+ const format = useTraceFormat();
726
+ const parts = [];
727
+ if (commandCount) {
728
+ parts.push(describeCommandCount(commandCount, format));
729
+ }
730
+ if (fileCount) {
731
+ parts.push(describeFileCount(fileCount, format));
732
+ }
733
+ const hasLines = (linesAdded ?? 0) > 0 || (linesRemoved ?? 0) > 0;
734
+ if (parts.length === 0 && !hasLines) return null;
735
+ return /* @__PURE__ */ jsxs("span", { className: classNames(styles.summary, className), "data-testid": "trace-file-changes-summary", children: [
736
+ parts.length > 0 ? /* @__PURE__ */ jsx("span", { className: styles.summaryPart, children: parts.join(" · ") }) : null,
737
+ hasLines ? /* @__PURE__ */ jsxs(Fragment, { children: [
738
+ parts.length > 0 ? /* @__PURE__ */ jsx("span", { "aria-hidden": true, children: "·" }) : null,
739
+ /* @__PURE__ */ jsxs("span", { className: styles.added, children: [
740
+ "+",
741
+ format.number(linesAdded ?? 0)
742
+ ] }),
743
+ /* @__PURE__ */ jsxs("span", { className: styles.removed, children: [
744
+ "−",
745
+ format.number(linesRemoved ?? 0)
746
+ ] })
747
+ ] }) : null
748
+ ] });
749
+ };
750
+ const STATE_LABELS = {
751
+ running: () => translateText("Running"),
752
+ done: () => translateText("Done"),
753
+ failed: () => translateText("Failed"),
754
+ waiting: () => translateText("Waiting"),
755
+ // "Cancelled" alone is also a contract's state in host apps: the context keeps the two translations apart.
756
+ cancelled: () => translateText("Cancelled", void 0, "step-state")
757
+ };
758
+ const readTraceStateLabel = (state) => STATE_LABELS[state]();
759
+ const TraceStateIcon = (props) => {
760
+ const { state, size = 15 } = props;
761
+ const label2 = readTraceStateLabel(state);
762
+ if (state === "running") {
763
+ return /* @__PURE__ */ jsx("span", { className: styles$1.spinner, role: "img", "aria-label": label2, "data-trace-state": state });
764
+ }
765
+ const iconName = state === "done" ? "stepDone" : state === "waiting" ? "stepWaiting" : "stepFailed";
766
+ const stateClassName = state === "done" ? styles$1.stateDone : state === "failed" ? styles$1.stateFailed : state === "waiting" ? styles$1.stateWaiting : styles$1.stateCancelled;
767
+ return /* @__PURE__ */ jsx("span", { role: "img", "aria-label": label2, "data-trace-state": state, className: classNames(styles$1.rowIcon, stateClassName), style: { display: "inline-flex" }, children: /* @__PURE__ */ jsx(Icon, { name: iconName, pixelSize: size }) });
768
+ };
769
+ const TraceChevron = (props) => /* @__PURE__ */ jsx(Icon, { name: props.isOpen ? "chevronDown" : "chevronRight", pixelSize: 13, className: props.className ?? styles$1.chevron });
770
+ const useTraceDisclosure = (isOpen, defaultOpen, onOpenChange) => {
771
+ const [ownIsOpen, setOwnIsOpen] = useState(defaultOpen);
772
+ const shownIsOpen = isOpen ?? ownIsOpen;
773
+ const toggle = useCallback(() => {
774
+ setOwnIsOpen(!shownIsOpen);
775
+ onOpenChange?.(!shownIsOpen);
776
+ }, [shownIsOpen, onOpenChange]);
777
+ return [shownIsOpen, toggle];
778
+ };
779
+ const TraceLink = (props) => {
780
+ const { href, onClick, linkComponent: LinkComponent, className = styles$1.link, title, children } = props;
781
+ if (href) {
782
+ if (LinkComponent) {
783
+ return /* @__PURE__ */ jsx(LinkComponent, { href, className, title, children });
784
+ }
785
+ return /* @__PURE__ */ jsx("a", { href, className, title, onClick, children });
786
+ }
787
+ if (!onClick) return null;
788
+ return /* @__PURE__ */ jsx("button", { type: "button", className, title, onClick, children });
789
+ };
790
+ const TracePath = (props) => {
791
+ const { path: path2, isMonospaced = false, isRemoved = false, className } = props;
792
+ const lastSlash = path2.replace(/\/+$/, "").lastIndexOf("/");
793
+ const folders = lastSlash >= 0 ? path2.slice(0, lastSlash + 1) : "";
794
+ const name = lastSlash >= 0 ? path2.slice(lastSlash + 1) : path2;
795
+ return /* @__PURE__ */ jsxs(
796
+ "span",
797
+ {
798
+ className: classNames(styles.path, isMonospaced && styles.pathMono, isRemoved && styles.pathRemoved, className),
799
+ title: path2,
800
+ children: [
801
+ folders !== "" ? /* @__PURE__ */ jsx("span", { className: styles.pathFolders, children: folders }) : null,
802
+ /* @__PURE__ */ jsx("span", { className: styles.pathName, children: name })
803
+ ]
804
+ }
805
+ );
806
+ };
807
+ const TraceMountChip = (props) => {
808
+ const mount2 = describeTraceMount(props.describeMount, props.mountKind, props.mountName, props.driveSpaceId);
809
+ if (mount2 === null) return null;
810
+ const toneClassName = mount2.tone === "own" ? styles.mountOwn : mount2.tone === "shared" ? styles.mountShared : mount2.tone === "external" ? styles.mountExternal : void 0;
811
+ return /* @__PURE__ */ jsx("span", { className: classNames(styles.mount, toneClassName), title: mount2.label, children: /* @__PURE__ */ jsx("span", { className: styles.mountLabel, children: mount2.label }) });
812
+ };
813
+ const copyTraceText = async (text) => {
814
+ try {
815
+ await navigator.clipboard.writeText(text);
816
+ return true;
817
+ } catch {
818
+ return false;
819
+ }
820
+ };
821
+ const TraceCopyButton = (props) => {
822
+ const { text, label: label2 } = props;
823
+ const [isCopied, setIsCopied] = useState(false);
824
+ const resetTimer = useRef(null);
825
+ useEffect(
826
+ () => () => {
827
+ if (resetTimer.current !== null) clearTimeout(resetTimer.current);
828
+ },
829
+ []
830
+ );
831
+ const handleCopy = async () => {
832
+ if (!await copyTraceText(text)) return;
833
+ setIsCopied(true);
834
+ if (resetTimer.current !== null) clearTimeout(resetTimer.current);
835
+ resetTimer.current = setTimeout(() => setIsCopied(false), 1600);
836
+ };
837
+ return /* @__PURE__ */ jsxs("button", { type: "button", className: styles$1.copyButton, "aria-label": label2, title: label2, onClick: () => void handleCopy(), children: [
838
+ /* @__PURE__ */ jsx(Icon, { name: isCopied ? "stepDone" : "copy", pixelSize: 13 }),
839
+ /* @__PURE__ */ jsx("span", { "aria-live": "polite", children: isCopied ? translateText("Copied") : translateText("Copy") })
840
+ ] });
841
+ };
842
+ const useTraceNow = (isTicking) => {
843
+ const [now, setNow] = useState(() => Date.now());
844
+ useEffect(() => {
845
+ if (!isTicking) return void 0;
846
+ setNow(Date.now());
847
+ const interval = setInterval(() => setNow(Date.now()), 1e3);
848
+ return () => clearInterval(interval);
849
+ }, [isTicking]);
850
+ return now;
851
+ };
852
+ const subAgentCard = "agents_subAgentCard_CAqARJ";
853
+ const facts = "agents_facts_NnIsio";
854
+ const factName = "agents_factName_8od223";
855
+ const factValue = "agents_factValue_BFQuDY";
856
+ const factStrong = "agents_factStrong_Jw5sBC";
857
+ const factDanger = "agents_factDanger_pxttT2";
858
+ const cardFoot = "agents_cardFoot_EJtK2Y";
859
+ const quiet = "agents_quiet_p3bgcv";
860
+ const childTrace = "agents_childTrace_RtyDRm";
861
+ const skills = "agents_skills_S2dWAp";
862
+ const skillsHead = "agents_skillsHead_rkD8vs";
863
+ const skillsTitle = "agents_skillsTitle_mYy5Zf";
864
+ const skillsList = "agents_skillsList_sBxU2a";
865
+ const skillRow = "agents_skillRow_Eii452";
866
+ const skillRowInteractive = "agents_skillRowInteractive_KZYpsf";
867
+ const skillName = "agents_skillName_tLI964";
868
+ const skillMark = "agents_skillMark_yW5HWt";
869
+ const skillMarkNew = "agents_skillMarkNew_uw6NgM";
870
+ const weight = "agents_weight_t2scWJ";
871
+ const chevron = "agents_chevron_C-WLQq";
872
+ const chevronSpace = "agents_chevronSpace_zowt-t";
873
+ const tools = "agents_tools_kGk1Iz";
874
+ const toolRow = "agents_toolRow_ldxbtz";
875
+ const toolName = "agents_toolName_WzSMl2";
876
+ const toolUsage = "agents_toolUsage_WYg0Ia";
877
+ const tasks = "agents_tasks_j7Le5M";
878
+ const tasksHead = "agents_tasksHead_x9aDpj";
879
+ const tasksTitle = "agents_tasksTitle_kccMlT";
880
+ const tasksList = "agents_tasksList_-yO7-5";
881
+ const task = "agents_task_rs5mqv";
882
+ const taskInteractive = "agents_taskInteractive_fpH-iJ";
883
+ const taskState = "agents_taskState_pmEiYE";
884
+ const taskTexts = "agents_taskTexts_0J5y3d";
885
+ const taskTitle = "agents_taskTitle_3xfqia";
886
+ const taskDetail = "agents_taskDetail_xZrND6";
887
+ const taskType = "agents_taskType_Bq51Gf";
888
+ const tasksEmpty = "agents_tasksEmpty_3E-dXL";
889
+ const changeSet = "agents_changeSet_8b7LW3";
890
+ const changeSetPending = "agents_changeSetPending_-FwNBv";
891
+ const changeSetHead = "agents_changeSetHead_fR3cwX";
892
+ const changeSetTitle = "agents_changeSetTitle_WqGXZt";
893
+ const changeSetGrow = "agents_changeSetGrow_q5nzdi";
894
+ const changes = "agents_changes_ZOZdUz";
895
+ const changeName = "agents_changeName_nWU2tX";
896
+ const changeValue = "agents_changeValue_re7bP1";
897
+ const changeOld = "agents_changeOld_jvoRb2";
898
+ const changeNew = "agents_changeNew_WY68fj";
899
+ const changeArrow = "agents_changeArrow_wf6eh9";
900
+ const changeUnchanged = "agents_changeUnchanged_P-spK7";
901
+ const changeSetNote = "agents_changeSetNote_3Nj3nO";
902
+ const changeSetFoot = "agents_changeSetFoot_ZWl4Ek";
903
+ const agentStyles = {
904
+ subAgentCard,
905
+ facts,
906
+ factName,
907
+ factValue,
908
+ factStrong,
909
+ factDanger,
910
+ cardFoot,
911
+ quiet,
912
+ childTrace,
913
+ skills,
914
+ skillsHead,
915
+ skillsTitle,
916
+ skillsList,
917
+ skillRow,
918
+ skillRowInteractive,
919
+ skillName,
920
+ skillMark,
921
+ skillMarkNew,
922
+ weight,
923
+ chevron,
924
+ chevronSpace,
925
+ tools,
926
+ toolRow,
927
+ toolName,
928
+ toolUsage,
929
+ tasks,
930
+ tasksHead,
931
+ tasksTitle,
932
+ tasksList,
933
+ task,
934
+ taskInteractive,
935
+ taskState,
936
+ taskTexts,
937
+ taskTitle,
938
+ taskDetail,
939
+ taskType,
940
+ tasksEmpty,
941
+ changeSet,
942
+ changeSetPending,
943
+ changeSetHead,
944
+ changeSetTitle,
945
+ changeSetGrow,
946
+ changes,
947
+ changeName,
948
+ changeValue,
949
+ changeOld,
950
+ changeNew,
951
+ changeArrow,
952
+ changeUnchanged,
953
+ changeSetNote,
954
+ changeSetFoot
955
+ };
956
+ const LoadedSkillsDisclosure = (props) => {
957
+ const { skills: skills2, isOpen, defaultOpen = false, onOpenChange, className } = props;
958
+ const format = useTraceFormat();
959
+ const [shownIsOpen, toggle] = useTraceDisclosure(isOpen, defaultOpen, onOpenChange);
960
+ const [openSkillNames, setOpenSkillNames] = useState(/* @__PURE__ */ new Set());
961
+ const residentTokens = skills2.reduce((sum, skill) => sum + (skill.residentTokens ?? 0), 0);
962
+ const toggleSkill = (skillName2) => setOpenSkillNames((previous) => {
963
+ const next = new Set(previous);
964
+ if (next.has(skillName2)) next.delete(skillName2);
965
+ else next.add(skillName2);
966
+ return next;
967
+ });
968
+ return /* @__PURE__ */ jsxs("div", { className: classNames(agentStyles.skills, className), "data-testid": "trace-loaded-skills", children: [
969
+ /* @__PURE__ */ jsxs("button", { type: "button", className: agentStyles.skillsHead, "aria-expanded": shownIsOpen, onClick: toggle, children: [
970
+ /* @__PURE__ */ jsx(Icon, { name: "skill", pixelSize: 14, className: agentStyles.chevron }),
971
+ /* @__PURE__ */ jsx("span", { className: agentStyles.skillsTitle, children: describeLoadedSkillCount(skills2.length, format) }),
972
+ /* @__PURE__ */ jsx("span", { className: agentStyles.weight, children: translateText("%count% tokens", { count: format.count(residentTokens) }) }),
973
+ /* @__PURE__ */ jsx(TraceChevron, { isOpen: shownIsOpen, className: agentStyles.chevron })
974
+ ] }),
975
+ shownIsOpen ? /* @__PURE__ */ jsx("ul", { className: agentStyles.skillsList, children: skills2.map((skill) => {
976
+ const tools2 = skill.tools ?? [];
977
+ const isSkillOpen = openSkillNames.has(skill.name);
978
+ const cause = skill.isAlwaysLoaded || skill.cause === "ALWAYS_LOADED" ? null : describeTraceSkillCause(skill.cause);
979
+ const row2 = /* @__PURE__ */ jsxs(Fragment, { children: [
980
+ tools2.length > 0 ? /* @__PURE__ */ jsx(TraceChevron, { isOpen: isSkillOpen, className: agentStyles.chevron }) : /* @__PURE__ */ jsx("span", { className: agentStyles.chevronSpace }),
981
+ /* @__PURE__ */ jsx("span", { className: agentStyles.skillName, title: skill.name, children: skill.name }),
982
+ skill.isNew ? /* @__PURE__ */ jsx("span", { className: classNames(agentStyles.skillMark, agentStyles.skillMarkNew), children: translateText("new") }) : null,
983
+ skill.isAlwaysLoaded ? /* @__PURE__ */ jsx("span", { className: agentStyles.skillMark, children: translateText("always loaded") }) : null,
984
+ skill.outcome === "ALREADY_LOADED" ? /* @__PURE__ */ jsx("span", { className: agentStyles.skillMark, children: translateText("already loaded") }) : null,
985
+ skill.outcome === "NOT_LOADED" ? /* @__PURE__ */ jsx("span", { className: agentStyles.skillMark, children: translateText("not loaded") }) : null,
986
+ cause !== null ? /* @__PURE__ */ jsx("span", { className: agentStyles.skillMark, children: cause }) : null,
987
+ /* @__PURE__ */ jsxs("span", { className: agentStyles.weight, children: [
988
+ tools2.length > 0 ? describeToolCount(tools2.length, format) : null,
989
+ tools2.length > 0 && skill.residentTokens != null ? " · " : null,
990
+ skill.residentTokens != null ? translateText("%count% tokens", { count: format.count(skill.residentTokens) }) : null
991
+ ] })
992
+ ] });
993
+ return /* @__PURE__ */ jsxs("li", { children: [
994
+ tools2.length > 0 ? /* @__PURE__ */ jsx(
995
+ "button",
996
+ {
997
+ type: "button",
998
+ className: classNames(agentStyles.skillRow, agentStyles.skillRowInteractive),
999
+ "aria-expanded": isSkillOpen,
1000
+ onClick: () => toggleSkill(skill.name),
1001
+ children: row2
1002
+ }
1003
+ ) : /* @__PURE__ */ jsx("div", { className: agentStyles.skillRow, children: row2 }),
1004
+ tools2.length > 0 && isSkillOpen ? /* @__PURE__ */ jsx("ul", { className: agentStyles.tools, children: tools2.map((tool) => /* @__PURE__ */ jsxs("li", { className: agentStyles.toolRow, children: [
1005
+ /* @__PURE__ */ jsx("span", { className: agentStyles.toolName, title: tool.name, children: tool.name }),
1006
+ tool.usageCount ? /* @__PURE__ */ jsxs("span", { className: agentStyles.toolUsage, title: translateText("Calls in this conversation"), children: [
1007
+ format.number(tool.usageCount),
1008
+ "×"
1009
+ ] }) : null,
1010
+ tool.residentTokens != null ? /* @__PURE__ */ jsx("span", { className: agentStyles.weight, children: translateText("%count% tokens", { count: format.count(tool.residentTokens) }) }) : null
1011
+ ] }, tool.name)) }) : null
1012
+ ] }, skill.name);
1013
+ }) }) : null
1014
+ ] });
1015
+ };
1016
+ const EntityChip = (props) => {
1017
+ const { label: label2, icon, href, argumentName, id, buildEntityHref, linkComponent: LinkComponent, className } = props;
1018
+ const resolvedHref = href ?? (argumentName !== void 0 && id !== void 0 ? buildEntityHref?.(argumentName, id) ?? null : null);
1019
+ const chipClassName = classNames(styles$1.entityChip, className);
1020
+ const content = /* @__PURE__ */ jsxs(Fragment, { children: [
1021
+ icon ? /* @__PURE__ */ jsx("span", { className: styles$1.entityChipIcon, "aria-hidden": true, children: icon }) : null,
1022
+ /* @__PURE__ */ jsx("span", { className: styles$1.entityChipLabel, children: label2 })
1023
+ ] });
1024
+ if (!resolvedHref) {
1025
+ return /* @__PURE__ */ jsx("span", { className: chipClassName, title: label2, "data-testid": "trace-entity-chip", children: content });
1026
+ }
1027
+ if (LinkComponent) {
1028
+ return /* @__PURE__ */ jsx(LinkComponent, { href: resolvedHref, className: chipClassName, title: label2, children: content });
1029
+ }
1030
+ return /* @__PURE__ */ jsx("a", { href: resolvedHref, className: chipClassName, title: label2, "data-testid": "trace-entity-chip", children: content });
1031
+ };
1032
+ const HUNK_HEADER = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@ ?(.*)$/;
1033
+ const NO_NEWLINE_MARKER = /^\\ /;
1034
+ const readHeaderPath = (headerLine) => {
1035
+ const path2 = headerLine.slice(4).split(" ")[0].trim();
1036
+ if (path2 === "" || path2 === "/dev/null") return null;
1037
+ return /^[ab]\//.test(path2) ? path2.slice(2) : path2;
1038
+ };
1039
+ const parseUnifiedDiff = (text) => {
1040
+ const diff = { oldPath: null, newPath: null, hunks: [], linesAdded: 0, linesRemoved: 0, isBinary: false };
1041
+ if (!text) return diff;
1042
+ const rawLines = text.split("\n").map((line2) => line2.endsWith("\r") ? line2.slice(0, -1) : line2);
1043
+ if (rawLines[rawLines.length - 1] === "") rawLines.pop();
1044
+ let hunk2 = null;
1045
+ let remainingOldLines = 0;
1046
+ let remainingNewLines = 0;
1047
+ let oldLineNumber = 0;
1048
+ let newLineNumber = 0;
1049
+ for (const rawLine of rawLines) {
1050
+ const isInsideHunk = hunk2 !== null && (remainingOldLines > 0 || remainingNewLines > 0);
1051
+ if (NO_NEWLINE_MARKER.test(rawLine)) {
1052
+ const lastLine = hunk2?.lines[hunk2.lines.length - 1];
1053
+ if (lastLine) lastLine.hasNoNewlineAtEnd = true;
1054
+ continue;
1055
+ }
1056
+ const headerMatch = HUNK_HEADER.exec(rawLine);
1057
+ if (headerMatch || !isInsideHunk) {
1058
+ if (headerMatch) {
1059
+ hunk2 = {
1060
+ header: rawLine,
1061
+ oldStart: Number(headerMatch[1]),
1062
+ oldLineCount: headerMatch[2] === void 0 ? 1 : Number(headerMatch[2]),
1063
+ newStart: Number(headerMatch[3]),
1064
+ newLineCount: headerMatch[4] === void 0 ? 1 : Number(headerMatch[4]),
1065
+ sectionHeading: headerMatch[5] ?? "",
1066
+ lines: []
1067
+ };
1068
+ diff.hunks.push(hunk2);
1069
+ remainingOldLines = hunk2.oldLineCount;
1070
+ remainingNewLines = hunk2.newLineCount;
1071
+ oldLineNumber = hunk2.oldStart;
1072
+ newLineNumber = hunk2.newStart;
1073
+ continue;
1074
+ }
1075
+ if (rawLine.startsWith("--- ")) diff.oldPath = readHeaderPath(rawLine);
1076
+ else if (rawLine.startsWith("+++ ")) diff.newPath = readHeaderPath(rawLine);
1077
+ else if (/^Binary files .* differ$/.test(rawLine) || rawLine.startsWith("GIT binary patch")) diff.isBinary = true;
1078
+ continue;
1079
+ }
1080
+ const currentHunk = hunk2;
1081
+ const marker = rawLine.charAt(0);
1082
+ const lineText2 = rawLine.slice(1);
1083
+ if (marker === "+" && remainingNewLines > 0) {
1084
+ currentHunk.lines.push({ kind: "added", oldLineNumber: null, newLineNumber, text: lineText2, hasNoNewlineAtEnd: false });
1085
+ newLineNumber += 1;
1086
+ remainingNewLines -= 1;
1087
+ diff.linesAdded += 1;
1088
+ } else if (marker === "-" && remainingOldLines > 0) {
1089
+ currentHunk.lines.push({ kind: "removed", oldLineNumber, newLineNumber: null, text: lineText2, hasNoNewlineAtEnd: false });
1090
+ oldLineNumber += 1;
1091
+ remainingOldLines -= 1;
1092
+ diff.linesRemoved += 1;
1093
+ } else {
1094
+ currentHunk.lines.push({
1095
+ kind: "context",
1096
+ oldLineNumber,
1097
+ newLineNumber,
1098
+ text: marker === " " ? lineText2 : rawLine,
1099
+ hasNoNewlineAtEnd: false
1100
+ });
1101
+ oldLineNumber += 1;
1102
+ newLineNumber += 1;
1103
+ remainingOldLines = Math.max(0, remainingOldLines - 1);
1104
+ remainingNewLines = Math.max(0, remainingNewLines - 1);
1105
+ }
1106
+ }
1107
+ return diff;
1108
+ };
1109
+ const buildSideBySideDiffRows = (lines) => {
1110
+ const rows = [];
1111
+ let position = 0;
1112
+ while (position < lines.length) {
1113
+ const line2 = lines[position];
1114
+ if (line2.kind === "context") {
1115
+ rows.push({ left: line2, right: line2 });
1116
+ position += 1;
1117
+ continue;
1118
+ }
1119
+ const removedLines = [];
1120
+ while (position < lines.length && lines[position].kind === "removed") {
1121
+ removedLines.push(lines[position]);
1122
+ position += 1;
1123
+ }
1124
+ const addedLines = [];
1125
+ while (position < lines.length && lines[position].kind === "added") {
1126
+ addedLines.push(lines[position]);
1127
+ position += 1;
1128
+ }
1129
+ for (let pair = 0; pair < Math.max(removedLines.length, addedLines.length); pair += 1) {
1130
+ rows.push({ left: removedLines[pair] ?? null, right: addedLines[pair] ?? null });
1131
+ }
1132
+ }
1133
+ return rows;
1134
+ };
1135
+ const SIGNS = { context: " ", added: "+", removed: "−" };
1136
+ const lineClassName = (line2) => classNames(
1137
+ styles.line,
1138
+ line2 === null && styles.lineEmpty,
1139
+ line2?.kind === "added" && styles.lineAdded,
1140
+ line2?.kind === "removed" && styles.lineRemoved
1141
+ );
1142
+ const renderLineText = (line2) => /* @__PURE__ */ jsxs("span", { className: styles.lineText, children: [
1143
+ line2.text === "" ? " " : line2.text,
1144
+ line2.hasNoNewlineAtEnd ? /* @__PURE__ */ jsxs("span", { className: styles.noNewline, children: [
1145
+ " ",
1146
+ translateText("(no line break at the end)")
1147
+ ] }) : null
1148
+ ] });
1149
+ const readExtensionWord = (path2) => {
1150
+ const name = readTraceFileName(path2);
1151
+ const dot = name.lastIndexOf(".");
1152
+ return dot > 0 && dot < name.length - 1 ? name.slice(dot + 1).toUpperCase() : null;
1153
+ };
1154
+ const FileEditBlock = (props) => {
1155
+ const {
1156
+ fileChange,
1157
+ describeMount,
1158
+ isNarrow = false,
1159
+ diffModesBelowHead = false,
1160
+ maxLines = isNarrow ? 12 : void 0,
1161
+ diffMode: diffMode2,
1162
+ defaultDiffMode = "unified",
1163
+ onDiffModeChange,
1164
+ onLoadFullDiff,
1165
+ onOpenInViewer,
1166
+ sandboxHref,
1167
+ linkComponent,
1168
+ thumbnail: thumbnail2,
1169
+ describeFileType,
1170
+ className
1171
+ } = props;
1172
+ const format = useTraceFormat();
1173
+ const [ownDiffMode, setOwnDiffMode] = useState(defaultDiffMode);
1174
+ const shownDiffMode = isNarrow && !diffModesBelowHead ? "unified" : diffMode2 ?? ownDiffMode;
1175
+ const [isExpanded, setIsExpanded] = useState(false);
1176
+ const [fullDiff, setFullDiff] = useState(null);
1177
+ const [fullDiffState, setFullDiffState] = useState("idle");
1178
+ const fileChangeKey = `${fileChange.id ?? ""}:${fileChange.path}:${fileChange.sha256After ?? ""}`;
1179
+ useEffect(() => {
1180
+ setIsExpanded(false);
1181
+ setFullDiff(null);
1182
+ setFullDiffState("idle");
1183
+ }, [fileChangeKey]);
1184
+ const changeType = fileChange.changeType ?? "MODIFIED";
1185
+ const diffState = fileChange.diffState ?? (fileChange.diffPreview ? "INLINE" : "NONE");
1186
+ const isBinary = diffState === "BINARY" || fileChange.isBinary === true && !fileChange.diffPreview;
1187
+ const diffText = fullDiff ?? fileChange.diffPreview ?? null;
1188
+ const diff = useMemo(() => isBinary ? null : parseUnifiedDiff(diffText), [diffText, isBinary]);
1189
+ const hasDiff = diff !== null && diff.hunks.length > 0;
1190
+ const unifiedRows = useMemo(
1191
+ () => (diff?.hunks ?? []).flatMap((hunk2, hunkPosition) => [
1192
+ { kind: "hunk", key: `hunk-${hunkPosition}`, text: hunk2.header },
1193
+ ...hunk2.lines.map((line2, linePosition) => ({ kind: "line", key: `line-${hunkPosition}-${linePosition}`, line: line2 }))
1194
+ ]),
1195
+ [diff]
1196
+ );
1197
+ const sideRows = useMemo(
1198
+ () => (diff?.hunks ?? []).flatMap((hunk2, hunkPosition) => [
1199
+ { kind: "hunk", key: `hunk-${hunkPosition}`, text: hunk2.header },
1200
+ ...buildSideBySideDiffRows(hunk2.lines).map((pair, pairPosition) => ({ kind: "pair", key: `pair-${hunkPosition}-${pairPosition}`, pair }))
1201
+ ]),
1202
+ [diff]
1203
+ );
1204
+ const rowCount = shownDiffMode === "sideBySide" ? sideRows.length : unifiedRows.length;
1205
+ const shownRowCount = isExpanded || maxLines === void 0 || rowCount <= maxLines + 2 ? rowCount : maxLines;
1206
+ const hiddenRowCount = rowCount - shownRowCount;
1207
+ const canLoadFullDiff = fullDiff === null && onLoadFullDiff !== void 0 && (diffState === "STORED" || diffState === "INLINE" && !fileChange.diffPreview);
1208
+ const handleDiffModeChange = (nextDiffMode) => {
1209
+ setOwnDiffMode(nextDiffMode);
1210
+ onDiffModeChange?.(nextDiffMode);
1211
+ };
1212
+ const handleLoadFullDiff = async () => {
1213
+ if (!onLoadFullDiff) return;
1214
+ setFullDiffState("loading");
1215
+ try {
1216
+ const loadedDiff = await onLoadFullDiff(fileChange);
1217
+ setFullDiff(loadedDiff);
1218
+ setIsExpanded(true);
1219
+ setFullDiffState("idle");
1220
+ } catch {
1221
+ setFullDiffState("failed");
1222
+ }
1223
+ };
1224
+ const linesAdded = fileChange.linesAdded ?? (hasDiff && fullDiff !== null ? diff?.linesAdded ?? null : null);
1225
+ const linesRemoved = fileChange.linesRemoved ?? (hasDiff && fullDiff !== null ? diff?.linesRemoved ?? null : null);
1226
+ const sizes = fileChange.sizeBefore != null && fileChange.sizeAfter != null && changeType === "MODIFIED" ? `${format.bytes(fileChange.sizeBefore)} → ${format.bytes(fileChange.sizeAfter)}` : fileChange.sizeAfter != null ? format.bytes(fileChange.sizeAfter) : fileChange.sizeBefore != null ? format.bytes(fileChange.sizeBefore) : null;
1227
+ const shortSha256 = formatShortSha256(fileChange.sha256After ?? fileChange.sha256Before);
1228
+ const fileTypeWord = describeFileType?.(fileChange) ?? readExtensionWord(fileChange.path);
1229
+ const hasStats = linesAdded != null || linesRemoved != null || (sizes !== null || shortSha256 !== null && !isNarrow) && !isBinary;
1230
+ const showsOpenButton = onOpenInViewer !== void 0 && !isBinary && changeType !== "DELETED" && changeType !== "DIRECTORY_CREATED";
1231
+ const showsDiffModes = hasDiff && (!isNarrow || diffModesBelowHead);
1232
+ const diffModeSwitch = /* @__PURE__ */ jsx("span", { className: styles.diffModes, role: "radiogroup", "aria-label": translateText("Layout of the diff"), children: ["unified", "sideBySide"].map((mode) => /* @__PURE__ */ jsx(
1233
+ "button",
1234
+ {
1235
+ type: "button",
1236
+ role: "radio",
1237
+ "aria-checked": shownDiffMode === mode,
1238
+ className: classNames(styles.diffMode, shownDiffMode === mode && styles.diffModeOn),
1239
+ onClick: () => handleDiffModeChange(mode),
1240
+ children: mode === "unified" ? translateText("Unified") : translateText("Side by side")
1241
+ },
1242
+ mode
1243
+ )) });
1244
+ const body2 = isBinary ? /* @__PURE__ */ jsxs("div", { className: styles.preview, "data-testid": "trace-file-preview", children: [
1245
+ thumbnail2 ? /* @__PURE__ */ jsx("div", { className: classNames(styles.thumbnail, styles.thumbnailHost), children: thumbnail2 }) : /* @__PURE__ */ jsxs("div", { className: styles.thumbnail, "aria-hidden": true, children: [
1246
+ /* @__PURE__ */ jsx("span", { className: styles.thumbnailBand }),
1247
+ /* @__PURE__ */ jsx("span", { className: styles.thumbnailLine }),
1248
+ /* @__PURE__ */ jsx("span", { className: classNames(styles.thumbnailLine, styles.thumbnailLineShort) }),
1249
+ /* @__PURE__ */ jsx("span", { className: styles.thumbnailLine }),
1250
+ /* @__PURE__ */ jsx("span", { className: classNames(styles.thumbnailLine, styles.thumbnailLineShort) }),
1251
+ /* @__PURE__ */ jsx("span", { className: styles.thumbnailLine })
1252
+ ] }),
1253
+ /* @__PURE__ */ jsxs("div", { className: styles.previewFacts, children: [
1254
+ /* @__PURE__ */ jsx("span", { className: styles.previewName, title: fileChange.path, children: readTraceFileName(fileChange.path) }),
1255
+ /* @__PURE__ */ jsx("span", { className: styles.previewMeta, children: [fileTypeWord, sizes, shortSha256 ? `sha256 ${shortSha256}` : null].filter(Boolean).join(" · ") }),
1256
+ onOpenInViewer ? /* @__PURE__ */ jsxs("button", { type: "button", className: styles.previewLink, onClick: () => onOpenInViewer(fileChange), children: [
1257
+ /* @__PURE__ */ jsx(Icon, { name: "preview", pixelSize: 13 }),
1258
+ translateText("Open in the viewer")
1259
+ ] }) : null,
1260
+ /* @__PURE__ */ jsx("span", { className: styles.previewMeta, children: translateText("A preview instead of a diff (binary file)") })
1261
+ ] })
1262
+ ] }) : hasDiff ? /* @__PURE__ */ jsxs(Fragment, { children: [
1263
+ shownDiffMode === "sideBySide" ? /* @__PURE__ */ jsx("div", { className: styles.sideBySide, "data-testid": "trace-file-diff", "data-diff-mode": "sideBySide", children: sideRows.slice(0, shownRowCount).map(
1264
+ (row2) => row2.kind === "hunk" ? /* @__PURE__ */ jsx("div", { className: styles.hunk, children: row2.text }, row2.key) : [
1265
+ /* @__PURE__ */ jsxs("div", { className: classNames(lineClassName(row2.pair.left), styles.sideLeft), "data-line-kind": row2.pair.left?.kind ?? "empty", children: [
1266
+ /* @__PURE__ */ jsx("span", { className: styles.lineNumber, children: row2.pair.left?.oldLineNumber ?? "" }),
1267
+ /* @__PURE__ */ jsx("span", { className: styles.sign, children: row2.pair.left?.kind === "removed" ? SIGNS.removed : " " }),
1268
+ row2.pair.left ? renderLineText(row2.pair.left) : /* @__PURE__ */ jsx("span", { className: styles.lineText, children: " " })
1269
+ ] }, `${row2.key}-left`),
1270
+ /* @__PURE__ */ jsxs("div", { className: lineClassName(row2.pair.right), "data-line-kind": row2.pair.right?.kind ?? "empty", children: [
1271
+ /* @__PURE__ */ jsx("span", { className: styles.lineNumber, children: row2.pair.right?.newLineNumber ?? "" }),
1272
+ /* @__PURE__ */ jsx("span", { className: styles.sign, children: row2.pair.right?.kind === "added" ? SIGNS.added : " " }),
1273
+ row2.pair.right ? renderLineText(row2.pair.right) : /* @__PURE__ */ jsx("span", { className: styles.lineText, children: " " })
1274
+ ] }, `${row2.key}-right`)
1275
+ ]
1276
+ ) }) : /* @__PURE__ */ jsx("div", { className: styles.diffScroll, "data-testid": "trace-file-diff", "data-diff-mode": "unified", tabIndex: 0, children: /* @__PURE__ */ jsx("div", { className: styles.diffTable, children: unifiedRows.slice(0, shownRowCount).map(
1277
+ (row2) => row2.kind === "hunk" ? /* @__PURE__ */ jsx("div", { className: styles.hunk, children: row2.text }, row2.key) : /* @__PURE__ */ jsxs("div", { className: lineClassName(row2.line), "data-line-kind": row2.line.kind, children: [
1278
+ /* @__PURE__ */ jsx("span", { className: styles.lineNumber, children: row2.line.oldLineNumber ?? "" }),
1279
+ /* @__PURE__ */ jsx("span", { className: styles.lineNumber, children: row2.line.newLineNumber ?? "" }),
1280
+ /* @__PURE__ */ jsx("span", { className: styles.sign, children: SIGNS[row2.line.kind] }),
1281
+ renderLineText(row2.line)
1282
+ ] }, row2.key)
1283
+ ) }) }),
1284
+ hiddenRowCount > 0 ? /* @__PURE__ */ jsx("button", { type: "button", className: styles.moreLines, onClick: () => setIsExpanded(true), children: describeHiddenLineCount(hiddenRowCount, format) }) : null,
1285
+ hiddenRowCount === 0 && canLoadFullDiff ? /* @__PURE__ */ jsx("button", { type: "button", className: styles.moreLines, disabled: fullDiffState === "loading", onClick: () => void handleLoadFullDiff(), children: fullDiffState === "loading" ? translateText("Loading the full diff…") : translateText("This is the start of the diff. Load the full diff") }) : null,
1286
+ fullDiffState === "failed" ? /* @__PURE__ */ jsx("div", { className: classNames(styles.note, styles.noteDanger), children: translateText("The full diff could not be loaded.") }) : null
1287
+ ] }) : diffState === "TOO_LARGE" ? /* @__PURE__ */ jsx("div", { className: styles.note, children: translateText("The file is too large for a diff.") }) : diffState === "UNAVAILABLE" ? /* @__PURE__ */ jsx("div", { className: styles.note, children: translateText("No diff was recorded for this change.") }) : canLoadFullDiff ? /* @__PURE__ */ jsxs(Fragment, { children: [
1288
+ /* @__PURE__ */ jsx("button", { type: "button", className: styles.moreLines, disabled: fullDiffState === "loading", onClick: () => void handleLoadFullDiff(), children: fullDiffState === "loading" ? translateText("Loading the full diff…") : translateText("Load the full diff") }),
1289
+ fullDiffState === "failed" ? /* @__PURE__ */ jsx("div", { className: classNames(styles.note, styles.noteDanger), children: translateText("The full diff could not be loaded.") }) : null
1290
+ ] }) : null;
1291
+ return /* @__PURE__ */ jsxs("div", { className: classNames(styles.fileBlock, className), "data-testid": "trace-file-edit", "data-change-type": changeType, "data-narrow": isNarrow || void 0, children: [
1292
+ /* @__PURE__ */ jsxs("div", { className: classNames(styles.fileHead, body2 !== null && styles.fileHeadWithBody), children: [
1293
+ /* @__PURE__ */ jsxs("div", { className: styles.fileHeadMain, children: [
1294
+ /* @__PURE__ */ jsxs("span", { className: styles.fileTitle, children: [
1295
+ /* @__PURE__ */ jsx(Icon, { name: readTraceFileChangeIcon(changeType), pixelSize: 14, className: styles.fileIcon }),
1296
+ changeType === "RENAMED" && fileChange.previousPath ? /* @__PURE__ */ jsxs(Fragment, { children: [
1297
+ /* @__PURE__ */ jsx(TracePath, { path: fileChange.previousPath, isRemoved: true }),
1298
+ /* @__PURE__ */ jsx("span", { className: styles.pathArrow, "aria-hidden": true, children: "→" })
1299
+ ] }) : null,
1300
+ /* @__PURE__ */ jsx(TracePath, { path: fileChange.path, isRemoved: changeType === "DELETED" })
1301
+ ] }),
1302
+ /* @__PURE__ */ jsx(
1303
+ TraceMountChip,
1304
+ {
1305
+ mountKind: fileChange.mountKind,
1306
+ mountName: fileChange.mountName,
1307
+ driveSpaceId: fileChange.driveSpaceId,
1308
+ describeMount
1309
+ }
1310
+ ),
1311
+ changeType !== "MODIFIED" ? /* @__PURE__ */ jsx(
1312
+ "span",
1313
+ {
1314
+ className: classNames(
1315
+ styles.operation,
1316
+ changeType === "ADDED" && styles.operationAdded,
1317
+ changeType === "DELETED" && styles.operationDeleted,
1318
+ changeType === "RENAMED" && styles.operationRenamed
1319
+ ),
1320
+ children: readTraceFileChangeWord(changeType)
1321
+ }
1322
+ ) : null,
1323
+ hasStats ? /* @__PURE__ */ jsxs("span", { className: styles.fileStats, children: [
1324
+ linesAdded != null ? /* @__PURE__ */ jsxs("span", { className: styles.added, children: [
1325
+ "+",
1326
+ format.number(linesAdded)
1327
+ ] }) : null,
1328
+ linesRemoved != null ? /* @__PURE__ */ jsxs("span", { className: styles.removed, children: [
1329
+ "−",
1330
+ format.number(linesRemoved)
1331
+ ] }) : null,
1332
+ sizes !== null && !isBinary ? /* @__PURE__ */ jsx("span", { className: styles.fileFact, children: sizes }) : null,
1333
+ shortSha256 !== null && !isBinary && !isNarrow ? /* @__PURE__ */ jsx("span", { className: styles.sha, title: fileChange.sha256After ?? fileChange.sha256Before ?? void 0, children: shortSha256 }) : null
1334
+ ] }) : null,
1335
+ fileChange.externalRevisionId && !isNarrow ? /* @__PURE__ */ jsx("span", { className: styles.fileFact, children: translateText("Revision %revision%", { revision: formatShortSha256(fileChange.externalRevisionId) ?? "" }) }) : null
1336
+ ] }),
1337
+ showsOpenButton || showsDiffModes || sandboxHref ? /* @__PURE__ */ jsxs("div", { className: styles.fileHeadActions, children: [
1338
+ sandboxHref ? /* @__PURE__ */ jsxs(TraceLink, { href: sandboxHref, linkComponent, className: styles.previewLink, title: translateText("Show this file in the sandbox"), children: [
1339
+ /* @__PURE__ */ jsx(Icon, { name: "terminal", pixelSize: 13 }),
1340
+ isNarrow ? null : translateText("Sandbox")
1341
+ ] }) : null,
1342
+ showsOpenButton ? /* @__PURE__ */ jsxs(
1343
+ "button",
1344
+ {
1345
+ type: "button",
1346
+ className: styles.previewLink,
1347
+ title: translateText("Open in the viewer"),
1348
+ "aria-label": isNarrow ? translateText("Open in the viewer") : void 0,
1349
+ onClick: () => onOpenInViewer?.(fileChange),
1350
+ children: [
1351
+ /* @__PURE__ */ jsx(Icon, { name: "preview", pixelSize: 13 }),
1352
+ isNarrow ? null : translateText("Open", void 0, "open-file")
1353
+ ]
1354
+ }
1355
+ ) : null,
1356
+ showsDiffModes && !diffModesBelowHead ? diffModeSwitch : null
1357
+ ] }) : null
1358
+ ] }),
1359
+ showsDiffModes && diffModesBelowHead ? /* @__PURE__ */ jsx("div", { className: styles.diffModesRow, children: diffModeSwitch }) : null,
1360
+ body2
1361
+ ] });
1362
+ };
1363
+ const ITEM_STATE_LABELS = {
1364
+ done: () => translateText("Done"),
1365
+ current: () => translateText("In progress"),
1366
+ open: () => translateText("Not started")
1367
+ };
1368
+ const TaskPlanRow = (props) => {
1369
+ const { title, items, isOpen, defaultOpen = true, onOpenChange, className } = props;
1370
+ const [shownIsOpen, toggle] = useTraceDisclosure(isOpen, defaultOpen, onOpenChange);
1371
+ const listId = useId();
1372
+ if (items.length === 0) {
1373
+ if (props.totalCount == null || props.totalCount <= 0) return null;
1374
+ return /* @__PURE__ */ jsx("div", { className: classNames(styles$1.plan, className), "data-testid": "trace-task-plan", children: /* @__PURE__ */ jsxs("div", { className: classNames(styles$1.planHead, styles$1.planHeadStatic), children: [
1375
+ /* @__PURE__ */ jsx(Icon, { name: "steps", pixelSize: 14, className: styles$1.rowIcon }),
1376
+ /* @__PURE__ */ jsx("span", { className: styles$1.planTitle, children: title || translateText("Plan") }),
1377
+ /* @__PURE__ */ jsx("span", { className: styles$1.planProgress, children: translateText("%done% of %total%", { done: Math.min(props.doneCount ?? 0, props.totalCount), total: props.totalCount }) })
1378
+ ] }) });
1379
+ }
1380
+ const doneCount = items.filter((item) => item.state === "done").length;
1381
+ return /* @__PURE__ */ jsxs("div", { className: classNames(styles$1.plan, className), "data-testid": "trace-task-plan", children: [
1382
+ /* @__PURE__ */ jsxs("button", { type: "button", className: styles$1.planHead, "aria-expanded": shownIsOpen, "aria-controls": listId, onClick: toggle, children: [
1383
+ /* @__PURE__ */ jsx(Icon, { name: "steps", pixelSize: 14, className: styles$1.rowIcon }),
1384
+ /* @__PURE__ */ jsx("span", { className: styles$1.planTitle, children: title || translateText("Plan") }),
1385
+ /* @__PURE__ */ jsx("span", { className: styles$1.planProgress, children: translateText("%done% of %total%", { done: doneCount, total: items.length }) }),
1386
+ /* @__PURE__ */ jsx("span", { className: styles$1.metaGrow }),
1387
+ /* @__PURE__ */ jsx(TraceChevron, { isOpen: shownIsOpen })
1388
+ ] }),
1389
+ shownIsOpen ? /* @__PURE__ */ jsx("ul", { id: listId, className: styles$1.planItems, children: items.map((item, index) => /* @__PURE__ */ jsxs(
1390
+ "li",
1391
+ {
1392
+ className: classNames(
1393
+ styles$1.planItem,
1394
+ item.state === "done" && styles$1.planItemDone,
1395
+ item.state === "current" && styles$1.planItemCurrent
1396
+ ),
1397
+ "data-plan-item-state": item.state,
1398
+ "aria-current": item.state === "current" ? "step" : void 0,
1399
+ children: [
1400
+ /* @__PURE__ */ jsx("span", { className: styles$1.planBox, role: "img", "aria-label": ITEM_STATE_LABELS[item.state](), children: item.state === "done" ? /* @__PURE__ */ jsx(Icon, { name: "stepDone", pixelSize: 11 }) : null }),
1401
+ /* @__PURE__ */ jsx("span", { children: item.text })
1402
+ ]
1403
+ },
1404
+ item.key ?? index
1405
+ )) }) : null
1406
+ ] });
1407
+ };
1408
+ const TraceCodePanel = (props) => {
1409
+ const { title, copyLabel = translateText("Copy the text"), text, totalChars = text.length, isCut = false, testId } = props;
1410
+ const format = useTraceFormat();
1411
+ return /* @__PURE__ */ jsxs("section", { className: styles$1.panel, "data-testid": testId, children: [
1412
+ /* @__PURE__ */ jsxs("header", { className: styles$1.panelHead, children: [
1413
+ /* @__PURE__ */ jsx("span", { className: styles$1.panelTitle, children: title }),
1414
+ /* @__PURE__ */ jsx("span", { children: translateText("%count% characters", { count: format.count(totalChars) }) }),
1415
+ isCut ? /* @__PURE__ */ jsx("span", { className: styles$1.panelCut, children: translateText("shortened") }) : null,
1416
+ /* @__PURE__ */ jsx("span", { className: styles$1.panelGrow }),
1417
+ /* @__PURE__ */ jsx(TraceCopyButton, { text, label: copyLabel })
1418
+ ] }),
1419
+ /* @__PURE__ */ jsx("pre", { className: styles$1.code, tabIndex: 0, children: text })
1420
+ ] });
1421
+ };
1422
+ const ToolStepDetail = (props) => {
1423
+ const {
1424
+ argumentsJson,
1425
+ isArgumentsCut = false,
1426
+ result,
1427
+ resultChars,
1428
+ isResultCut = false,
1429
+ errorText,
1430
+ loadedSkillNames = [],
1431
+ loadedSkills,
1432
+ modelCall,
1433
+ modelLabel: modelLabelOfStep,
1434
+ durationMs,
1435
+ formatCost,
1436
+ toolSkillNames = [],
1437
+ onOpenContext,
1438
+ children
1439
+ } = props;
1440
+ const format = useTraceFormat();
1441
+ const shownArguments = useMemo(() => argumentsJson ? prettyPrintTraceJson(argumentsJson) : null, [argumentsJson]);
1442
+ const hasResult = result !== null && result !== void 0 && result !== "";
1443
+ const panelCount = (shownArguments !== null ? 1 : 0) + (hasResult ? 1 : 0);
1444
+ const tokens = modelCall && (modelCall.inputTokens != null || modelCall.outputTokens != null) ? translateText("%input% in · %output% out", {
1445
+ input: format.count(modelCall.inputTokens ?? 0),
1446
+ output: format.count(modelCall.outputTokens ?? 0)
1447
+ }) : null;
1448
+ const modelLabel = modelLabelOfStep ?? describeTraceModelName(modelCall?.modelName);
1449
+ const model = modelLabel ? [modelLabel, describeTraceEffort(modelCall?.effort)].filter(Boolean).join(" · ") : null;
1450
+ const hasFacts = model !== null || tokens !== null || modelCall?.cachePercent != null || modelCall?.reasoningTokens != null || modelCall?.costInUsd != null || durationMs != null || loadedSkillNames.length > 0 || toolSkillNames.length > 0 || onOpenContext !== void 0;
1451
+ const stopReasonWords = {
1452
+ toolCalls: () => translateText("called tools", void 0, "model-call-end"),
1453
+ answer: () => translateText("answered", void 0, "model-call-end"),
1454
+ empty: () => translateText("empty answer", void 0, "model-call-end")
1455
+ };
1456
+ const calledToolNames = modelCall?.toolNames ?? [];
1457
+ return /* @__PURE__ */ jsxs("div", { className: styles$1.detail, "data-testid": "trace-step-detail", children: [
1458
+ errorText ? /* @__PURE__ */ jsx("div", { className: classNames(styles$1.pill, styles$1.pillDanger), style: { height: "auto", whiteSpace: "normal", padding: "4px 10px" }, children: errorText }) : null,
1459
+ panelCount > 0 ? /* @__PURE__ */ jsxs("div", { className: classNames(styles$1.detailPanels, panelCount === 1 && styles$1.detailPanelsSingle), children: [
1460
+ shownArguments !== null ? /* @__PURE__ */ jsx(
1461
+ TraceCodePanel,
1462
+ {
1463
+ title: translateText("Arguments"),
1464
+ copyLabel: translateText("Copy arguments"),
1465
+ text: shownArguments,
1466
+ totalChars: (argumentsJson ?? "").length,
1467
+ isCut: isArgumentsCut,
1468
+ testId: "trace-step-arguments"
1469
+ }
1470
+ ) : null,
1471
+ hasResult ? /* @__PURE__ */ jsx(
1472
+ TraceCodePanel,
1473
+ {
1474
+ title: translateText("Result"),
1475
+ copyLabel: translateText("Copy result"),
1476
+ text: result,
1477
+ totalChars: resultChars ?? result.length,
1478
+ isCut: isResultCut,
1479
+ testId: "trace-step-result"
1480
+ }
1481
+ ) : null
1482
+ ] }) : null,
1483
+ hasFacts ? /* @__PURE__ */ jsxs("div", { className: styles$1.facts, children: [
1484
+ model !== null ? /* @__PURE__ */ jsxs("span", { className: classNames(styles$1.pill, styles$1.pillModel), title: modelCall?.modelName ?? void 0, children: [
1485
+ /* @__PURE__ */ jsx(Icon, { name: "model", pixelSize: 12, className: styles$1.pillIcon }),
1486
+ model
1487
+ ] }) : null,
1488
+ tokens !== null ? /* @__PURE__ */ jsx("span", { className: styles$1.pill, children: tokens }) : null,
1489
+ modelCall?.cachePercent != null ? /* @__PURE__ */ jsx("span", { className: styles$1.pill, children: translateText("%percent% % cached", { percent: format.number(Math.round(modelCall.cachePercent)) }) }) : null,
1490
+ modelCall?.reasoningTokens != null && modelCall.reasoningTokens > 0 ? /* @__PURE__ */ jsx("span", { className: styles$1.pill, children: translateText("%count% reasoning tokens", { count: format.count(modelCall.reasoningTokens) }) }) : null,
1491
+ modelCall?.costInUsd != null ? /* @__PURE__ */ jsxs("span", { className: styles$1.pill, children: [
1492
+ /* @__PURE__ */ jsx(Icon, { name: "cost", pixelSize: 12, className: styles$1.pillIcon }),
1493
+ (formatCost ?? format.cost)(modelCall.costInUsd)
1494
+ ] }) : null,
1495
+ durationMs != null ? /* @__PURE__ */ jsxs("span", { className: styles$1.pill, children: [
1496
+ /* @__PURE__ */ jsx(Icon, { name: "stepWaiting", pixelSize: 12, className: styles$1.pillIcon }),
1497
+ format.duration(durationMs)
1498
+ ] }) : null,
1499
+ loadedSkillNames.map((skillName2) => /* @__PURE__ */ jsxs("span", { className: styles$1.pill, children: [
1500
+ /* @__PURE__ */ jsx(Icon, { name: "skill", pixelSize: 12, className: styles$1.pillIcon }),
1501
+ skillName2
1502
+ ] }, skillName2)),
1503
+ modelCall?.callNumberInTurn != null ? /* @__PURE__ */ jsx("span", { className: styles$1.pill, children: translateText("Call %number% of the turn", { number: format.number(modelCall.callNumberInTurn) }) }) : null,
1504
+ modelCall?.stopReason ? /* @__PURE__ */ jsx("span", { className: styles$1.pill, children: stopReasonWords[modelCall.stopReason]?.() ?? modelCall.stopReason }) : null,
1505
+ modelCall?.cacheWriteTokens != null && modelCall.cacheWriteTokens > 0 ? /* @__PURE__ */ jsx("span", { className: styles$1.pill, children: translateText("%count% written to the cache", { count: format.count(modelCall.cacheWriteTokens) }) }) : null,
1506
+ modelCall?.providerCallMs != null ? /* @__PURE__ */ jsx("span", { className: styles$1.pill, title: translateText("Time the provider took, and time the loop spent around the call"), children: modelCall.loopOverheadMs != null ? translateText("%provider% provider · %loop% loop", {
1507
+ provider: format.duration(modelCall.providerCallMs),
1508
+ loop: format.duration(modelCall.loopOverheadMs)
1509
+ }) : format.duration(modelCall.providerCallMs) }) : null,
1510
+ modelCall?.retryCount != null && modelCall.retryCount > 0 ? /* @__PURE__ */ jsx("span", { className: classNames(styles$1.pill, styles$1.pillWarning), children: translateText("%count% retried", { count: format.number(modelCall.retryCount) }) }) : null,
1511
+ modelCall?.forcedToolChoice ? /* @__PURE__ */ jsx("span", { className: classNames(styles$1.pill, styles$1.pillCode), children: translateText("forced: %tool%", { tool: modelCall.forcedToolChoice }) }) : null,
1512
+ modelCall?.wireApi ? /* @__PURE__ */ jsx("span", { className: classNames(styles$1.pill, styles$1.pillCode), children: modelCall.wireApi }) : null,
1513
+ calledToolNames.length > 0 ? /* @__PURE__ */ jsxs("span", { className: classNames(styles$1.pill, styles$1.pillCode), children: [
1514
+ "→ ",
1515
+ calledToolNames.join(", ")
1516
+ ] }) : null,
1517
+ toolSkillNames.map((skillName2) => /* @__PURE__ */ jsxs("span", { className: styles$1.pill, title: translateText("The skill that brought this tool"), children: [
1518
+ /* @__PURE__ */ jsx(Icon, { name: "skill", pixelSize: 12, className: styles$1.pillIcon }),
1519
+ skillName2
1520
+ ] }, `tool-skill:${skillName2}`)),
1521
+ onOpenContext ? /* @__PURE__ */ jsxs(TraceLink, { onClick: onOpenContext, children: [
1522
+ /* @__PURE__ */ jsx(Icon, { name: "code", pixelSize: 13 }),
1523
+ translateText("Context of this call")
1524
+ ] }) : null
1525
+ ] }) : null,
1526
+ loadedSkills && loadedSkills.length > 0 ? /* @__PURE__ */ jsx(LoadedSkillsDisclosure, { skills: loadedSkills }) : null,
1527
+ children
1528
+ ] });
1529
+ };
1530
+ const translateWithChatTexts = (text, replacements) => translateText(text, replacements);
1531
+ const readLabel = (labels, value) => {
1532
+ if (!value) return null;
1533
+ return Object.prototype.hasOwnProperty.call(labels, value) ? labels[value] ?? null : null;
1534
+ };
1535
+ const readText = (text) => {
1536
+ const trimmedText = (text ?? "").trim();
1537
+ return trimmedText === "" ? null : trimmedText;
1538
+ };
1539
+ const readValueInWords = (value) => {
1540
+ const words = value.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_.-]+/g, " ").trim().toLowerCase();
1541
+ return words.charAt(0).toUpperCase() + words.slice(1);
1542
+ };
1543
+ const TRACE_DECISION_SITE_LABELS = {
1544
+ replyLanguage: textKey("Reply language"),
1545
+ skillPreload: textKey("Skill preload"),
1546
+ planItemSkillPreload: textKey("Skills for a plan item"),
1547
+ reasoningEffort: textKey("Reasoning effort"),
1548
+ planDynamics: textKey("Working plan"),
1549
+ directWidget: textKey("Direct widget"),
1550
+ turnStartLine: textKey("Opening line"),
1551
+ turnClosing: textKey("Turn closing"),
1552
+ stallRecovery: textKey("Stall recovery"),
1553
+ ownerConsent: textKey("Owner consent"),
1554
+ ownerMessageInjection: textKey("Injection check of the message"),
1555
+ toolResultInjection: textKey("Injection check of a tool result"),
1556
+ eviction: textKey("Skill eviction"),
1557
+ forcedReDrive: textKey("Forced tool call"),
1558
+ delegationAdmission: textKey("Sub-agent admission"),
1559
+ doneCriterionRecheck: textKey("Done criteria re-check"),
1560
+ preloadOutcome: textKey("Preload outcome")
1561
+ };
1562
+ const describeTraceDecisionSite = (site, fallbackLabel, translate = translateWithChatTexts) => {
1563
+ const key = readLabel(TRACE_DECISION_SITE_LABELS, site);
1564
+ if (key !== null) return translate(key);
1565
+ return readText(fallbackLabel) ?? (site ? readValueInWords(site) : null);
1566
+ };
1567
+ const TRACE_SIGNAL_TAG_LABELS = {
1568
+ ui: textKey("Screen of the owner"),
1569
+ situation: textKey("Situation of the owner"),
1570
+ "client-context": textKey("Context of the client"),
1571
+ "tool-expected": textKey("Tool call expected"),
1572
+ "time-zone": textKey("Time zone"),
1573
+ plan: textKey("Task plan"),
1574
+ widget: textKey("Widget note"),
1575
+ skills: textKey("Loaded skills"),
1576
+ "reply-language": textKey("Reply language"),
1577
+ "answer-step": textKey("Answer step"),
1578
+ "standing-instructions": textKey("Standing instructions"),
1579
+ "owner-addressing": textKey("Form of address"),
1580
+ clock: textKey("Current time"),
1581
+ "plan-of-the-product": textKey("Product plan"),
1582
+ "tool-images": textKey("Images of a tool result"),
1583
+ "answer-content": textKey("Answer content")
1584
+ };
1585
+ const TRACE_SIGNAL_SOURCE_LABELS = {
1586
+ LOOP_NUDGE: textKey("Nudge of the loop"),
1587
+ INJECTION_REMOVED: textKey("Injection removed"),
1588
+ MID_TURN_OWNER_INBOUND: textKey("Message during the run"),
1589
+ KICKOFF_OWNER_INBOUND: textKey("Message at the start of the run"),
1590
+ MID_TURN_SIGNAL_REPLAY: textKey("Signal repeated after a model call"),
1591
+ MEMORY_CONFLICT: textKey("Memory conflict"),
1592
+ MEMORY_CLARIFY: textKey("Memory question"),
1593
+ FRONTEND_WIDGET_CLICK: textKey("Click in a widget"),
1594
+ FRONTEND_CHANNEL_CONNECTION: textKey("Chat window connected"),
1595
+ FRONTEND_NAVIGATION: textKey("Page change in the app"),
1596
+ OWNER_ACTION_CONFIRM: textKey("Confirmation of an action"),
1597
+ CONNECTION_APPROVAL: textKey("Approval of a connection"),
1598
+ OWNER_REPORT: textKey("Report to the owner"),
1599
+ SUPERVISOR_STEERING: textKey("Steering by the supervisor"),
1600
+ SUPERVISOR_CORRECTION: textKey("Correction by the supervisor"),
1601
+ PURPOSE_CONSEQUENCE: textKey("Consequence of the purpose"),
1602
+ FRONTEND_WIDGET_INVALID: textKey("Invalid widget"),
1603
+ FRONTEND_WIDGET_RENDER_REPORT: textKey("Render report of the widgets"),
1604
+ DASHBOARD_WIDGET_CONTEXT: textKey("Context of a dashboard widget"),
1605
+ PURPOSE_KICKOFF: textKey("Start of the purpose"),
1606
+ DELEGATIONS_SETTLED: textKey("Sub-agents finished"),
1607
+ BACKGROUND_WORK_FINISHED: textKey("Background work finished"),
1608
+ TURN_CONTINUATION: textKey("Run continued"),
1609
+ TASK_PLAN_OPEN_BOUNCE: textKey("Open plan items"),
1610
+ TASK_PLAN_OPEN_BOUNCE_DECISION: textKey("Decision on open plan items"),
1611
+ TURN_OBLIGATION_BOUNCE: textKey("Open obligation of the run"),
1612
+ PLAN_BOOKKEEPING: textKey("Plan bookkeeping"),
1613
+ OWNER_QUESTION_PICK: textKey("Answer picked by the owner"),
1614
+ OWNER_WIDGET_EDIT_APPLIED: textKey("Edit in a widget applied"),
1615
+ OWNER_CARD_EDIT_APPLIED: textKey("Edit in a widget applied"),
1616
+ PLATFORM_WIDGET_EMITTED: textKey("Widget of the platform"),
1617
+ CONTINUE_AFTER_PAUSE: textKey("Continued after a pause"),
1618
+ BUDGET_CLOSING: textKey("Budget almost used up"),
1619
+ OWNER_REPORT_FORCED_CALL: textKey("Forced report to the owner"),
1620
+ OWNER_REPORT_WITH_QUESTION: textKey("Report with a question"),
1621
+ TURN_STOPPED_BY_OWNER: textKey("Stopped by the owner"),
1622
+ REPEATED_TEXT_SUPPRESSED: textKey("Repeated text held back"),
1623
+ WIDGET_TREE_FINDINGS: textKey("Findings in a widget"),
1624
+ SUB_AGENT_RUN_ENDED: textKey("Sub-agent finished"),
1625
+ SUB_AGENT_RUN_ENDED_WITHOUT_RESUME: textKey("Sub-agent finished, read later"),
1626
+ ORCHESTRATOR_MESSAGE: textKey("Message of the main agent"),
1627
+ SUB_AGENT_RUN_ENDED_REPLAY: textKey("Sub-agent finished (repeated)"),
1628
+ SUB_AGENT_RUN_ENDED_WITHOUT_RESUME_REPLAY: textKey("Sub-agent finished, read later (repeated)"),
1629
+ PHONE_VOICEMAIL: textKey("Voicemail"),
1630
+ PHONE_CALL_STARTED: textKey("Call started"),
1631
+ PHONE_CALL_ENDED: textKey("Call ended"),
1632
+ PHONE_DELEGATION: textKey("Task from a call"),
1633
+ PHONE_CALL_UNANSWERED_FOLLOW_UP: textKey("Follow-up of an unanswered call")
1634
+ };
1635
+ const readSignalSourceOfWords = (words) => words.trim().replace(/[\s-]+/g, "_").toUpperCase();
1636
+ const describeTraceSignal = (kind, source, fallbackLabel, translate = translateWithChatTexts) => {
1637
+ const key = readLabel(TRACE_SIGNAL_TAG_LABELS, kind) ?? readLabel(TRACE_SIGNAL_SOURCE_LABELS, source) ?? readLabel(TRACE_SIGNAL_SOURCE_LABELS, kind) ?? (kind ? readLabel(TRACE_SIGNAL_SOURCE_LABELS, readSignalSourceOfWords(kind)) : null);
1638
+ if (key !== null) return translate(key);
1639
+ return readText(fallbackLabel) ?? readText(kind) ?? (source ? readValueInWords(source) : null);
1640
+ };
1641
+ const TRACE_WAKE_CONDITION_LABELS = {
1642
+ ALL: textKey("Continues when all sub-agents are done"),
1643
+ ANY: textKey("Continues as soon as one sub-agent is done"),
1644
+ QUORUM: textKey("Continues when enough sub-agents are done"),
1645
+ BACKGROUND: textKey("Runs in the background, the conversation does not wait")
1646
+ };
1647
+ const describeTraceWakeCondition = (value, translate = translateWithChatTexts) => {
1648
+ const condition = readText(value);
1649
+ if (condition === null) return null;
1650
+ const key = readLabel(TRACE_WAKE_CONDITION_LABELS, condition.toUpperCase());
1651
+ return key !== null ? translate(key) : translate(textKey("Continues on the condition %condition%"), { condition });
1652
+ };
1653
+ const TRACE_CONTEXT_SEGMENT_LABELS = {
1654
+ BASE_PROMPT: textKey("System prompt"),
1655
+ SUB_AGENT_DIRECTIVE: textKey("Sub-agent directive"),
1656
+ PURPOSE_DIRECTIVE: textKey("Directive of the conversation purpose"),
1657
+ CONVERSATION_SUBJECT: textKey("Record of this conversation"),
1658
+ SCHEDULED_RUN_DIRECTIVE: textKey("Directive of the scheduled run"),
1659
+ TIME_RULE: textKey("Time rule"),
1660
+ OWNER_PRESENCE: textKey("Who the agent is talking to"),
1661
+ MEMORY_DIRECTIVES: textKey("Standing instructions"),
1662
+ EPISODIC_HISTORY: textKey("Recent sessions"),
1663
+ DAY_CONTEXT: textKey("Context of the day"),
1664
+ LOCAL_SITUATION: textKey("Local situation"),
1665
+ PRODUCT_CAPABILITIES: textKey("Product plan and capabilities"),
1666
+ RESTRICTED_CAPABILITIES: textKey("Restricted for this user"),
1667
+ AI_BUDGET_AWARENESS: textKey("AI budget"),
1668
+ SKILL_CATALOG: textKey("Skill catalog"),
1669
+ LOADED_SKILLS: textKey("Loaded skills"),
1670
+ QUERY_OPTIONS_SYNTAX: textKey("Query syntax"),
1671
+ SHARED_PARAMS: textKey("Shared request parameters"),
1672
+ ALREADY_FETCHED_READS: textKey("Data already fetched"),
1673
+ TASK_PLAN: textKey("Task plan"),
1674
+ ANSWER_CONTRACT: textKey("Answer contract"),
1675
+ COMPACTION_SUMMARY: textKey("Compaction summary"),
1676
+ META_TOOL_SCHEMAS: textKey("Schemas of the meta tools"),
1677
+ TOOL_SCHEMAS: textKey("Schemas of the skill tools"),
1678
+ USER_MESSAGE: textKey("User message"),
1679
+ ASSISTANT_MESSAGE: textKey("Reply of the assistant"),
1680
+ TOOL_CALL: textKey("Tool call"),
1681
+ TOOL_RESULT: textKey("Tool result"),
1682
+ SIGNAL: textKey("Signal"),
1683
+ REPLY_LANGUAGE_CUE: textKey("Cue for the reply language")
1684
+ };
1685
+ const describeTraceContextSegment = (type, fallbackLabel, translate = translateWithChatTexts) => {
1686
+ const key = readLabel(TRACE_CONTEXT_SEGMENT_LABELS, type);
1687
+ if (key !== null) return translate(key);
1688
+ return readText(fallbackLabel) ?? readText(type);
1689
+ };
1690
+ const BACKGROUND_TOOL_JOB_PREFIX = /^\s*Background job:\s*run tool\s*/i;
1691
+ const BACKGROUND_JOB_PREFIX = /^\s*Background job:\s*/i;
1692
+ const describeTraceBackgroundJob = (toolName2, translate = translateWithChatTexts) => {
1693
+ const text = readText(toolName2);
1694
+ if (text === null) return translate(textKey("Background job"));
1695
+ if (BACKGROUND_TOOL_JOB_PREFIX.test(text)) {
1696
+ const name = text.replace(BACKGROUND_TOOL_JOB_PREFIX, "").trim();
1697
+ return name === "" ? translate(textKey("Background job")) : translate(textKey("Background job: runs the tool %toolName%"), { toolName: name });
1698
+ }
1699
+ if (BACKGROUND_JOB_PREFIX.test(text)) {
1700
+ const operation2 = text.replace(BACKGROUND_JOB_PREFIX, "").trim();
1701
+ return operation2 === "" ? translate(textKey("Background job")) : translate(textKey("Background job: %operation%"), { operation: operation2 });
1702
+ }
1703
+ return translate(textKey("Background job: runs the tool %toolName%"), { toolName: text });
1704
+ };
1705
+ const isTraceBackgroundJobLabel = (label2) => BACKGROUND_JOB_PREFIX.test(label2 ?? "");
1706
+ const OWNER_INBOUND_HEADS = [
1707
+ { head: /^\s*While you were working, the owner sent:\s*/, key: textKey("Sent during the run: %message%") },
1708
+ { head: /^\s*While your opener was being delivered, the owner sent:\s*/, key: textKey("Sent while the opening line was delivered: %message%") },
1709
+ { head: /^\s*The owner typed before your opener was delivered:\s*/, key: textKey("Sent before the opening line was delivered: %message%") }
1710
+ ];
1711
+ const OWNER_INBOUND_INSTRUCTION = / — (?:take it into account now|the greeting is delivered|compose ONE message)/;
1712
+ const OWNER_INBOUND_ROW = /^\(message \d+\) "([\s\S]*)"$/;
1713
+ const readOwnerInboundNote = (text, translate) => {
1714
+ for (const { head, key } of OWNER_INBOUND_HEADS) {
1715
+ if (!head.test(text)) continue;
1716
+ const afterHead = text.replace(head, "");
1717
+ const instructionStart = afterHead.search(OWNER_INBOUND_INSTRUCTION);
1718
+ const rowsText = (instructionStart === -1 ? afterHead : afterHead.slice(0, instructionStart)).trim();
1719
+ const message = rowsText.split(/ · (?=\(message \d+\) ")/).map((row2) => OWNER_INBOUND_ROW.exec(row2.trim())?.[1] ?? row2.trim()).filter((row2) => row2 !== "").join(" · ");
1720
+ return message === "" ? null : translate(key, { message });
1721
+ }
1722
+ return null;
1723
+ };
1724
+ const SUB_AGENT_RUN_END_KEYS = {
1725
+ COMPLETED: textKey("Sub-agent %name% is done (run %run%)."),
1726
+ FAILED: textKey("Sub-agent %name% failed (run %run%)."),
1727
+ CANCELLED: textKey("Sub-agent %name% was cancelled (run %run%)."),
1728
+ "ENDED WITHOUT A RECORDED RESULT": textKey("Sub-agent %name% ended without a result (run %run%).")
1729
+ };
1730
+ const SUB_AGENT_END_KEYS_WITHOUT_RUN = {
1731
+ FAILED: textKey("Sub-agent %name% failed."),
1732
+ CANCELLED: textKey("Sub-agent %name% was cancelled."),
1733
+ "NOT RUN": textKey("Sub-agent %name% did not run."),
1734
+ "ENDED WITHOUT A RECORDED RESULT": textKey("Sub-agent %name% ended without a result.")
1735
+ };
1736
+ const SUB_AGENT_RUN_END = /^\s*Sub-agent ((?:#\d+ )?«.*») (COMPLETED|FAILED|CANCELLED|NOT RUN|ENDED WITHOUT A RECORDED RESULT)(?: \(run (\d+)(?:, [^)]*)?\)\.)?/;
1737
+ const SUB_AGENT_ENDED = /^\s*Sub-agent ((?:#\d+ )?«.*») ended\. No result\./;
1738
+ const readSubAgentRunEndNote = (firstLine, translate) => {
1739
+ const ended = SUB_AGENT_ENDED.exec(firstLine);
1740
+ if (ended !== null) return translate(textKey("Sub-agent %name% ended."), { name: ended[1] });
1741
+ const runEnd = SUB_AGENT_RUN_END.exec(firstLine);
1742
+ if (runEnd === null) return null;
1743
+ const [, name, status, runNumber] = runEnd;
1744
+ const key = runNumber !== void 0 ? SUB_AGENT_RUN_END_KEYS[status] : SUB_AGENT_END_KEYS_WITHOUT_RUN[status];
1745
+ if (key === void 0) return null;
1746
+ return runNumber !== void 0 ? translate(key, { name, run: runNumber }) : translate(key, { name });
1747
+ };
1748
+ const describeTraceSignalText = (text, translate = translateWithChatTexts) => {
1749
+ const note2 = readText(text);
1750
+ if (note2 === null) return null;
1751
+ const ownerInbound = readOwnerInboundNote(note2, translate);
1752
+ if (ownerInbound !== null) return ownerInbound;
1753
+ return readSubAgentRunEndNote(note2.split("\n")[0] ?? "", translate);
1754
+ };
1755
+ const NAMES = "(.+?)";
1756
+ const readEffortWords = (effort) => describeTraceEffort(effort) ?? effort;
1757
+ const readNames = (names, translate) => names.replace(/ \+(\d+) more$/, (_match, count) => ` ${translate(textKey("+%count% more"), { count })}`);
1758
+ const REPLY_LANGUAGE_SOURCE_KEYS = {
1759
+ "asked for by the owner": textKey("asked for by the owner"),
1760
+ "written by the owner": textKey("written by the owner"),
1761
+ "kept from earlier": textKey("kept from earlier"),
1762
+ "a standing directive": textKey("a standing directive"),
1763
+ configured: textKey("configured")
1764
+ };
1765
+ const DECISION_SUMMARY_RULES = [
1766
+ { pattern: /^admitted (\d+) of (\d+) sub-agents?/, key: textKey("Sub-agents admitted: %admitted% of %requested%"), values: (match) => ({ admitted: match[1], requested: match[2] }) },
1767
+ { pattern: new RegExp(`^preloaded ${NAMES} for the next plan item`), key: textKey("Preloaded for the next plan item: %skills%"), values: (match, translate) => ({ skills: readNames(match[1], translate) }) },
1768
+ { pattern: new RegExp(`^would preload ${NAMES} for the next plan item`), key: textKey("Would preload for the next plan item: %skills%"), values: (match, translate) => ({ skills: readNames(match[1], translate) }) },
1769
+ { pattern: new RegExp(`^preloaded ${NAMES}(?= · | \\(|$)`), key: textKey("Preloaded: %skills%"), values: (match, translate) => ({ skills: readNames(match[1], translate) }) },
1770
+ { pattern: new RegExp(`^would preload ${NAMES}(?= · | \\(|$)`), key: textKey("Would preload: %skills%"), values: (match, translate) => ({ skills: readNames(match[1], translate) }) },
1771
+ { pattern: /^pick (\S+) not admitted/, key: textKey("Picked %skill%, not admitted"), values: (match) => ({ skill: match[1] }) },
1772
+ { pattern: /^no preload/, key: textKey("No preload") },
1773
+ { pattern: /^not admitted: (.+)$/, key: textKey("Not admitted: %skills%"), values: (match, translate) => ({ skills: readNames(match[1], translate) }) },
1774
+ { pattern: /^nothing loaded of (.+)$/, key: textKey("Nothing loaded of: %skills%"), values: (match, translate) => ({ skills: readNames(match[1], translate) }) },
1775
+ { pattern: /^nothing to load/, key: textKey("Nothing to load") },
1776
+ { pattern: /^effort (\w+) → (\w+)/, key: textKey("Effort %from% → %to%"), values: (match) => ({ from: readEffortWords(match[1]), to: readEffortWords(match[2]) }) },
1777
+ { pattern: /^effort (\w+)/, key: textKey("Effort %effort%"), values: (match) => ({ effort: readEffortWords(match[1]) }) },
1778
+ { pattern: /^finished plan with (\d+) items retired/, key: textKey("Finished plan with %count% items retired"), values: (match) => ({ count: match[1] }) },
1779
+ { pattern: /^finished plan retired/, key: textKey("Finished plan retired") },
1780
+ { pattern: /^would retire the finished plan with (\d+) items/, key: textKey("Would retire the finished plan with %count% items"), values: (match) => ({ count: match[1] }) },
1781
+ { pattern: /^would retire the finished plan/, key: textKey("Would retire the finished plan") },
1782
+ { pattern: /^finished plan with (\d+) items reopened/, key: textKey("Finished plan with %count% items reopened"), values: (match) => ({ count: match[1] }) },
1783
+ { pattern: /^finished plan reopened/, key: textKey("Finished plan reopened") },
1784
+ { pattern: /^plan first/, key: textKey("Plan first") },
1785
+ { pattern: /^no plan needed/, key: textKey("No plan needed") },
1786
+ { pattern: /^plan optional/, key: textKey("Plan optional") },
1787
+ { pattern: /^widget (\S+) announced/, key: textKey("Widget %type% announced"), values: (match) => ({ type: match[1] }) },
1788
+ { pattern: /^widget (\S+) not announced/, key: textKey("Widget %type% not announced"), values: (match) => ({ type: match[1] }) },
1789
+ { pattern: /^no widget/, key: textKey("No widget") },
1790
+ { pattern: /^opening line shown/, key: textKey("Opening line shown") },
1791
+ { pattern: /^would show an opening line/, key: textKey("Would show an opening line") },
1792
+ { pattern: /^no opening line/, key: textKey("No opening line") },
1793
+ { pattern: /^answer bounced/, key: textKey("Answer sent back") },
1794
+ { pattern: /^would bounce the answer/, key: textKey("Would send the answer back") },
1795
+ { pattern: /^answer accepted/, key: textKey("Answer accepted") },
1796
+ { pattern: /^applied: (.+)$/, key: textKey("Applied: %move%"), values: (match) => ({ move: match[1] }) },
1797
+ { pattern: /^would apply: (.+)$/, key: textKey("Would apply: %move%"), values: (match) => ({ move: match[1] }) },
1798
+ { pattern: /^chose (.+) \(not applied\)$/, key: textKey("Chose %move%, not applied"), values: (match) => ({ move: match[1] }) },
1799
+ { pattern: /^(.+) \(by rule, not asked\)$/, key: textKey("%move%, by rule, not asked"), values: (match) => ({ move: match[1] }) },
1800
+ { pattern: /^no move/, key: textKey("No move") },
1801
+ { pattern: /^consent given by mandate #(\d+)/, key: textKey("Consent given by mandate #%mandateId%"), values: (match) => ({ mandateId: match[1] }) },
1802
+ { pattern: /^consent given/, key: textKey("Consent given") },
1803
+ { pattern: /^consent refused/, key: textKey("Consent refused") },
1804
+ { pattern: /^message filtered/, key: textKey("Message filtered") },
1805
+ { pattern: /^would filter the message/, key: textKey("Would filter the message") },
1806
+ { pattern: /^message passed/, key: textKey("Message passed") },
1807
+ { pattern: /^evicted (\S+)/, key: textKey("Evicted: %subject%"), values: (match) => ({ subject: match[1] }) },
1808
+ { pattern: /^forced a tool call \((\d+) calls?\)/, key: textKey("Forced a tool call (%count% calls)"), values: (match) => ({ count: match[1] }) },
1809
+ { pattern: /^forced a tool call/, key: textKey("Forced a tool call") },
1810
+ { pattern: /^forced call produced no tool call/, key: textKey("The forced call produced no tool call") },
1811
+ {
1812
+ pattern: /^re-checked (\d+) criteri(?:on|a) after (\S+), (\d+) resolved/,
1813
+ key: textKey("Re-checked %count% done criteria after %tool%, %resolved% resolved"),
1814
+ values: (match) => ({ count: match[1], tool: match[2], resolved: match[3] })
1815
+ },
1816
+ {
1817
+ pattern: /^re-checked (\d+) criteri(?:on|a) at the turn start, (\d+) resolved/,
1818
+ key: textKey("Re-checked %count% done criteria at the start of the turn, %resolved% resolved"),
1819
+ values: (match) => ({ count: match[1], resolved: match[2] })
1820
+ },
1821
+ { pattern: /^no answer \(([^)]*)\)$/, key: textKey("No answer (%reason%)"), values: (match) => ({ reason: match[1] }) },
1822
+ {
1823
+ pattern: /^kept (\S+) · resolved (\S+) \(([^)]+)\)$/,
1824
+ key: textKey("Kept %configured%, resolved %language% (%source%)"),
1825
+ values: (match, translate) => ({ configured: match[1], language: match[2], source: readReplyLanguageSource(match[3], translate) })
1826
+ },
1827
+ {
1828
+ pattern: /^([a-z]{2,3}(?:-[A-Za-z0-9]{2,8})?) \(([^)]+)\)$/,
1829
+ key: textKey("%language% (%source%)"),
1830
+ values: (match, translate) => ({ language: match[1], source: readReplyLanguageSource(match[2], translate) })
1831
+ }
1832
+ ];
1833
+ const readReplyLanguageSource = (words, translate) => {
1834
+ const key = readLabel(REPLY_LANGUAGE_SOURCE_KEYS, words);
1835
+ return key !== null ? translate(key) : words;
1836
+ };
1837
+ const DECISION_SUMMARY_TAILS = [
1838
+ { pattern: / \(lock [^)]*\)/, render: () => "" },
1839
+ { pattern: / · pass (\d+) under (\S+)/, render: (match, translate) => ` · ${translate(textKey("round %pass% under %skill%"), { pass: match[1], skill: match[2] })}` },
1840
+ { pattern: / · pass (\d+)/, render: (match, translate) => ` · ${translate(textKey("round %pass%"), { pass: match[1] })}` },
1841
+ { pattern: / \(not told to the model\)/, render: (_match, translate) => ` (${translate(textKey("not told to the model"))})` },
1842
+ { pattern: / \(kept, no answer\)/, render: (_match, translate) => ` (${translate(textKey("kept, no answer"))})` },
1843
+ { pattern: / \(not applied\)/, render: (_match, translate) => ` (${translate(textKey("not applied"))})` },
1844
+ { pattern: / \(not asked: ([^)]+)\)/, render: (match, translate) => ` (${translate(textKey("not asked: %reason%"), { reason: match[1] })})` },
1845
+ { pattern: / \(not asked\)/, render: (_match, translate) => ` (${translate(textKey("not asked"))})` }
1846
+ ];
1847
+ const readSummaryTail = (tail, translate) => DECISION_SUMMARY_TAILS.reduce((text, { pattern, render }) => {
1848
+ const match = pattern.exec(text);
1849
+ return match === null ? text : text.slice(0, match.index) + render(match, translate) + text.slice(match.index + match[0].length);
1850
+ }, tail);
1851
+ const describeTraceDecisionSummary = (summary2, translate = translateWithChatTexts) => {
1852
+ const text = readText(summary2);
1853
+ if (text === null) return null;
1854
+ for (const rule of DECISION_SUMMARY_RULES) {
1855
+ const match = rule.pattern.exec(text);
1856
+ if (match === null) continue;
1857
+ const tail = text.slice(match[0].length);
1858
+ if (tail !== "" && !tail.startsWith(" · ") && !tail.startsWith(" (")) continue;
1859
+ const head = rule.values ? translate(rule.key, rule.values(match, translate)) : translate(rule.key);
1860
+ return head + readSummaryTail(tail, translate);
1861
+ }
1862
+ return null;
1863
+ };
1864
+ const describeTraceDecision = (decision) => describeTraceDecisionSite(decision.site, decision.siteLabel);
1865
+ const DECISION_STATUS_LABELS = {
1866
+ APPLIED: () => translateText("applied", void 0, "decision-status"),
1867
+ DECIDED: () => translateText("decided", void 0, "decision-status"),
1868
+ SHADOW: () => translateText("recorded only", void 0, "decision-status"),
1869
+ FALLBACK: () => translateText("fallback", void 0, "decision-status"),
1870
+ SKIPPED: () => translateText("not asked", void 0, "decision-status")
1871
+ };
1872
+ const describeTraceDecisionStatus = (status) => status ? DECISION_STATUS_LABELS[status]?.() ?? readTraceIdInWords(status) : null;
1873
+ const readTraceDecisionStatusClassName = (status) => classNames(styles$1.badge, status === "APPLIED" && styles$1.badgeSuccess, status === "FALLBACK" && styles$1.badgeWarning);
1874
+ const DecisionDetail = (props) => {
1875
+ const { decision } = props;
1876
+ const format = useTraceFormat();
1877
+ const statusWords = describeTraceDecisionStatus(decision.status);
1878
+ const model = [decision.modelName, decision.modelVersion].filter(Boolean).join(" · ") || null;
1879
+ const probabilities = (decision.probabilities ?? []).slice(0, 6);
1880
+ const panels = useMemo(
1881
+ () => [
1882
+ { key: "input", title: translateText("Sent state"), text: decision.inputJson, isCut: decision.isInputCut },
1883
+ { key: "questions", title: translateText("Questions"), text: decision.questionsJson, isCut: decision.isQuestionsCut },
1884
+ { key: "output", title: translateText("Answers"), text: decision.outputJson, isCut: decision.isOutputCut },
1885
+ { key: "outcome", title: translateText("Outcome"), text: decision.outcomeJson, isCut: decision.isOutcomeCut }
1886
+ ].flatMap((panel2) => panel2.text ? [{ ...panel2, text: prettyPrintTraceJson(panel2.text), isCut: panel2.isCut === true }] : []),
1887
+ [decision]
1888
+ );
1889
+ return /* @__PURE__ */ jsxs("div", { className: styles$1.detail, "data-testid": "trace-decision-detail", children: [
1890
+ decision.resultSummary ? /* @__PURE__ */ jsx("div", { className: styles$1.detailText, title: decision.resultSummary, children: describeTraceDecisionSummary(decision.resultSummary) ?? decision.resultSummary }) : null,
1891
+ /* @__PURE__ */ jsxs("div", { className: styles$1.facts, children: [
1892
+ statusWords !== null ? /* @__PURE__ */ jsx("span", { className: readTraceDecisionStatusClassName(decision.status), children: statusWords }) : null,
1893
+ decision.engineLabel || decision.engine ? /* @__PURE__ */ jsxs("span", { className: styles$1.pill, children: [
1894
+ /* @__PURE__ */ jsx(Icon, { name: "decision", pixelSize: 12, className: styles$1.pillIcon }),
1895
+ decision.engineLabel || readTraceIdInWords(decision.engine ?? "")
1896
+ ] }) : null,
1897
+ model !== null ? /* @__PURE__ */ jsxs("span", { className: classNames(styles$1.pill, styles$1.pillModel), children: [
1898
+ /* @__PURE__ */ jsx(Icon, { name: "model", pixelSize: 12, className: styles$1.pillIcon }),
1899
+ model
1900
+ ] }) : null,
1901
+ decision.confidence != null ? /* @__PURE__ */ jsx("span", { className: styles$1.pill, children: translateText("%percent% % sure", { percent: format.number(Math.round(decision.confidence * 100)) }) }) : null,
1902
+ decision.durationMs != null ? /* @__PURE__ */ jsxs("span", { className: styles$1.pill, "data-testid": "trace-decision-duration", children: [
1903
+ /* @__PURE__ */ jsx(Icon, { name: "stepWaiting", pixelSize: 12, className: styles$1.pillIcon }),
1904
+ (decision.sharedRequestDecisionCount ?? 0) > 1 ? translateText("%duration% for %count% decisions together", {
1905
+ duration: format.duration(decision.durationMs),
1906
+ count: format.number(decision.sharedRequestDecisionCount ?? 0)
1907
+ }) : format.duration(decision.durationMs)
1908
+ ] }) : null,
1909
+ decision.mode && decision.mode !== "on" ? /* @__PURE__ */ jsx("span", { className: classNames(styles$1.pill, styles$1.pillCode), children: decision.mode }) : null,
1910
+ decision.subject ? /* @__PURE__ */ jsx("span", { className: classNames(styles$1.pill, styles$1.pillCode), children: decision.subject }) : null
1911
+ ] }),
1912
+ decision.fallbackReason ? /* @__PURE__ */ jsx("div", { className: styles$1.detailQuiet, children: translateText("No answer: %reason%. The turn went on as without this decision.", { reason: decision.fallbackReason }) }) : null,
1913
+ decision.skipReason ? /* @__PURE__ */ jsx("div", { className: styles$1.detailQuiet, children: translateText("No action: %reason%", { reason: readTraceIdInWords(decision.skipReason) }) }) : null,
1914
+ probabilities.length > 0 ? /* @__PURE__ */ jsx("div", { className: styles$1.facts, "data-testid": "trace-decision-probabilities", children: probabilities.map((entry) => /* @__PURE__ */ jsxs("span", { className: classNames(styles$1.pill, styles$1.pillCode), children: [
1915
+ entry.name,
1916
+ " ",
1917
+ entry.probability.toFixed(2)
1918
+ ] }, entry.name)) }) : null,
1919
+ panels.length > 0 ? /* @__PURE__ */ jsx("div", { className: classNames(styles$1.detailPanels, panels.length === 1 && styles$1.detailPanelsSingle), children: panels.map((panel2) => /* @__PURE__ */ jsx(TraceCodePanel, { title: panel2.title, text: panel2.text, isCut: panel2.isCut, testId: `trace-decision-${panel2.key}` }, panel2.key)) }) : null
1920
+ ] });
1921
+ };
1922
+ const describeTraceCompaction = (compaction, format) => {
1923
+ const parts = [];
1924
+ if (compaction.foldedMessageCount != null) parts.push(describeMessageCount(compaction.foldedMessageCount, format));
1925
+ if (compaction.tokensBefore != null && compaction.tokensAfter != null) {
1926
+ parts.push(translateText("%before% → %after% tokens", { before: format.count(compaction.tokensBefore), after: format.count(compaction.tokensAfter) }));
1927
+ }
1928
+ return parts.length > 0 ? parts.join(" · ") : null;
1929
+ };
1930
+ const CompactionDetail = (props) => {
1931
+ const { compaction } = props;
1932
+ const format = useTraceFormat();
1933
+ const hasRange = compaction.foldedFromMessageIndex != null && compaction.foldedToMessageIndex != null;
1934
+ return /* @__PURE__ */ jsxs("div", { className: styles$1.detail, "data-testid": "trace-compaction-detail", children: [
1935
+ /* @__PURE__ */ jsxs("div", { className: styles$1.facts, children: [
1936
+ compaction.foldedMessageCount != null ? /* @__PURE__ */ jsxs("span", { className: styles$1.pill, children: [
1937
+ /* @__PURE__ */ jsx(Icon, { name: "compaction", pixelSize: 12, className: styles$1.pillIcon }),
1938
+ describeMessageCount(compaction.foldedMessageCount, format),
1939
+ hasRange ? ` (#${compaction.foldedFromMessageIndex}–#${compaction.foldedToMessageIndex})` : null
1940
+ ] }) : null,
1941
+ compaction.tokensBefore != null && compaction.tokensAfter != null ? /* @__PURE__ */ jsx("span", { className: styles$1.pill, children: translateText("%before% → %after% tokens", { before: format.count(compaction.tokensBefore), after: format.count(compaction.tokensAfter) }) }) : null,
1942
+ compaction.compressionPercent != null ? /* @__PURE__ */ jsx("span", { className: classNames(styles$1.pill, styles$1.pillSuccess), children: translateText("%percent% % saved", { percent: format.number(Math.round(compaction.compressionPercent)) }) }) : null,
1943
+ compaction.level != null && compaction.level > 1 ? /* @__PURE__ */ jsx("span", { className: styles$1.pill, children: translateText("Summary of summaries, level %level%", { level: compaction.level }) }) : null,
1944
+ compaction.modelName ? /* @__PURE__ */ jsxs("span", { className: classNames(styles$1.pill, styles$1.pillModel), children: [
1945
+ /* @__PURE__ */ jsx(Icon, { name: "model", pixelSize: 12, className: styles$1.pillIcon }),
1946
+ compaction.modelName
1947
+ ] }) : null
1948
+ ] }),
1949
+ compaction.summaryText ? /* @__PURE__ */ jsx(TraceCodePanel, { title: translateText("Summary"), text: compaction.summaryText, isCut: compaction.isSummaryCut === true, testId: "trace-compaction-summary" }) : null,
1950
+ compaction.preservedFactsJson ? /* @__PURE__ */ jsx(TraceCodePanel, { title: translateText("Kept facts"), text: prettyPrintTraceJson(compaction.preservedFactsJson), testId: "trace-compaction-facts" }) : null
1951
+ ] });
1952
+ };
1953
+ const SignalDetail = (props) => {
1954
+ const { signal } = props;
1955
+ return /* @__PURE__ */ jsxs("div", { className: styles$1.detail, "data-testid": "trace-signal-detail", children: [
1956
+ signal.source || signal.kind ? /* @__PURE__ */ jsxs("div", { className: styles$1.facts, children: [
1957
+ signal.kind ? /* @__PURE__ */ jsx("span", { className: classNames(styles$1.pill, styles$1.pillCode), children: signal.kind }) : null,
1958
+ signal.source ? /* @__PURE__ */ jsxs("span", { className: styles$1.pill, children: [
1959
+ /* @__PURE__ */ jsx(Icon, { name: "signal", pixelSize: 12, className: styles$1.pillIcon }),
1960
+ describeTraceSignal(null, signal.source)
1961
+ ] }) : null
1962
+ ] }) : null,
1963
+ signal.text ? /* @__PURE__ */ jsx(TraceCodePanel, { title: translateText("Signal text"), text: signal.text, isCut: signal.isTextCut === true, testId: "trace-signal-text" }) : null
1964
+ ] });
1965
+ };
1966
+ const WidgetDetail = (props) => {
1967
+ const { widget } = props;
1968
+ return /* @__PURE__ */ jsxs("div", { className: styles$1.detail, "data-testid": "trace-widget-detail", children: [
1969
+ widget.title ? /* @__PURE__ */ jsx("div", { className: styles$1.detailText, children: widget.title }) : null,
1970
+ widget.summary ? /* @__PURE__ */ jsx("div", { className: styles$1.detailQuiet, children: widget.summary }) : null,
1971
+ /* @__PURE__ */ jsxs("div", { className: styles$1.facts, children: [
1972
+ widget.type ? /* @__PURE__ */ jsxs("span", { className: classNames(styles$1.pill, styles$1.pillCode), children: [
1973
+ /* @__PURE__ */ jsx(Icon, { name: "widget", pixelSize: 12, className: styles$1.pillIcon }),
1974
+ widget.type
1975
+ ] }) : null,
1976
+ widget.emittedBy ? /* @__PURE__ */ jsx("span", { className: styles$1.pill, children: translateText("emitted by: %source%", { source: readTraceIdInWords(widget.emittedBy) }) }) : null,
1977
+ widget.isValid === false ? /* @__PURE__ */ jsx("span", { className: classNames(styles$1.pill, styles$1.pillDanger), children: translateText("Invalid widget data") }) : null
1978
+ ] }),
1979
+ widget.payloadJson ? /* @__PURE__ */ jsx(TraceCodePanel, { title: translateText("Widget data"), text: prettyPrintTraceJson(widget.payloadJson), isCut: widget.isPayloadCut === true, testId: "trace-widget-payload" }) : null
1980
+ ] });
1981
+ };
1982
+ const SkillLoadDetail = (props) => {
1983
+ const { skillLoad } = props;
1984
+ const format = useTraceFormat();
1985
+ const causeWords = describeTraceSkillCause(skillLoad.cause);
1986
+ const skills2 = useMemo(
1987
+ () => (skillLoad.skills ?? []).map((entry) => ({
1988
+ name: entry.name,
1989
+ residentTokens: entry.residentTokensWithTools ?? entry.residentTokens,
1990
+ isNew: entry.outcome === "LOADED",
1991
+ cause: entry.cause,
1992
+ outcome: entry.outcome,
1993
+ tools: entry.tools
1994
+ })),
1995
+ [skillLoad.skills]
1996
+ );
1997
+ const requestedNames = skillLoad.requestedNames ?? [];
1998
+ return /* @__PURE__ */ jsxs("div", { className: styles$1.detail, "data-testid": "trace-skill-load-detail", children: [
1999
+ /* @__PURE__ */ jsxs("div", { className: styles$1.facts, children: [
2000
+ causeWords !== null ? /* @__PURE__ */ jsxs("span", { className: styles$1.pill, children: [
2001
+ /* @__PURE__ */ jsx(Icon, { name: "skill", pixelSize: 12, className: styles$1.pillIcon }),
2002
+ causeWords
2003
+ ] }) : null,
2004
+ skillLoad.notLoadedCount != null && skillLoad.notLoadedCount > 0 ? /* @__PURE__ */ jsx("span", { className: classNames(styles$1.pill, styles$1.pillWarning), children: translateText("%count% not loaded", { count: format.number(skillLoad.notLoadedCount) }) }) : null,
2005
+ requestedNames.map((name) => /* @__PURE__ */ jsx("span", { className: classNames(styles$1.pill, styles$1.pillCode), title: translateText("The model asked for this name"), children: name }, name))
2006
+ ] }),
2007
+ skills2.length > 0 ? /* @__PURE__ */ jsx(LoadedSkillsDisclosure, { skills: skills2, defaultOpen: true }) : null,
2008
+ skillLoad.notLoadedText ? /* @__PURE__ */ jsx("div", { className: styles$1.detailQuiet, children: skillLoad.notLoadedText }) : null
2009
+ ] });
2010
+ };
2011
+ const buildTaskPlanItems = (items) => items.map((item) => ({
2012
+ key: item.key,
2013
+ text: item.numberPath ? `${item.numberPath} ${item.title}` : item.title,
2014
+ state: item.status === "done" || item.status === "not_applicable" ? "done" : "open"
2015
+ }));
2016
+ const TaskPlanStepDetail = (props) => /* @__PURE__ */ jsx(TaskPlanRow, { title: props.title, items: buildTaskPlanItems(props.items), defaultOpen: true });
2017
+ const EFFECT_LABELS = {
2018
+ READ: () => translateText("reads", void 0, "tool-effect"),
2019
+ WORKSPACE: () => translateText("works in the workspace", void 0, "tool-effect"),
2020
+ WRITE: () => translateText("changes data", void 0, "tool-effect"),
2021
+ DELETE: () => translateText("deletes data", void 0, "tool-effect")
2022
+ };
2023
+ const StepFactsLine = (props) => {
2024
+ const { step } = props;
2025
+ const format = useTraceFormat();
2026
+ const startedAt = readTraceMoment(step.startedAt);
2027
+ const toolWords = step.toolNameInWords || step.toolName || null;
2028
+ const state = readTraceStepState(step);
2029
+ return /* @__PURE__ */ jsxs("div", { className: styles$1.facts, "data-testid": "trace-step-facts", children: [
2030
+ toolWords !== null ? /* @__PURE__ */ jsxs("span", { className: styles$1.pill, children: [
2031
+ /* @__PURE__ */ jsx(Icon, { name: readTraceStepIcon(step), pixelSize: 12, className: styles$1.pillIcon }),
2032
+ toolWords
2033
+ ] }) : null,
2034
+ step.effect && EFFECT_LABELS[step.effect] ? /* @__PURE__ */ jsx("span", { className: styles$1.pill, children: EFFECT_LABELS[step.effect]() }) : null,
2035
+ step.kind === "TOOL_CALL" || step.kind === "SKILL_LOAD" ? /* @__PURE__ */ jsx("span", { className: classNames(styles$1.pill, state === "failed" && styles$1.pillDanger), children: readTraceStateLabel(state) }) : null,
2036
+ startedAt !== null ? /* @__PURE__ */ jsx("span", { className: styles$1.pill, children: format.time(startedAt) }) : null,
2037
+ step.durationMs != null ? /* @__PURE__ */ jsxs("span", { className: styles$1.pill, children: [
2038
+ /* @__PURE__ */ jsx(Icon, { name: "stepWaiting", pixelSize: 12, className: styles$1.pillIcon }),
2039
+ format.duration(step.durationMs)
2040
+ ] }) : null,
2041
+ (step.toolSkillNames ?? []).map((skillName2) => /* @__PURE__ */ jsxs("span", { className: styles$1.pill, title: translateText("The skill that brought this tool"), children: [
2042
+ /* @__PURE__ */ jsx(Icon, { name: "skill", pixelSize: 12, className: styles$1.pillIcon }),
2043
+ skillName2
2044
+ ] }, skillName2))
2045
+ ] });
2046
+ };
2047
+ const ToolStepRow = (props) => {
2048
+ const {
2049
+ icon,
2050
+ iconSlot,
2051
+ state,
2052
+ showsStateInLead = false,
2053
+ label: label2,
2054
+ labelWeight = "strong",
2055
+ target: target2,
2056
+ targetKind = "code",
2057
+ chips: chips2,
2058
+ deliveredThroughCallTool = false,
2059
+ meta: meta2,
2060
+ variant = "step",
2061
+ children,
2062
+ hasPlainBody = false,
2063
+ isOpen,
2064
+ defaultOpen = false,
2065
+ onOpenChange,
2066
+ isCompact = false,
2067
+ className,
2068
+ testId,
2069
+ anchorId
2070
+ } = props;
2071
+ const hasDetail = children !== void 0 && children !== null && children !== false;
2072
+ const [shownIsOpen, toggle] = useTraceDisclosure(isOpen, defaultOpen, onOpenChange);
2073
+ const bodyId = useId();
2074
+ const hasTarget = target2 !== void 0 && target2 !== null && target2 !== "";
2075
+ const showsState = state !== void 0 && (showsStateInLead || state === "running" || state === "waiting");
2076
+ const lead = showsState ? /* @__PURE__ */ jsx(TraceStateIcon, { state }) : iconSlot ?? (icon ? /* @__PURE__ */ jsx(Icon, { name: icon, pixelSize: 15, className: styles$1.rowIcon }) : null);
2077
+ const rowClassName = classNames(
2078
+ styles$1.row,
2079
+ hasDetail && styles$1.rowInteractive,
2080
+ hasDetail && shownIsOpen && styles$1.rowOpen,
2081
+ variant === "fold" && styles$1.rowFold,
2082
+ variant === "thinking" && styles$1.rowThinking,
2083
+ variant === "waiting" && styles$1.rowWaiting,
2084
+ className
2085
+ );
2086
+ const content = /* @__PURE__ */ jsxs(Fragment, { children: [
2087
+ lead,
2088
+ /* @__PURE__ */ jsx("span", { className: classNames(styles$1.label, labelWeight === "regular" && styles$1.labelRegular, (hasTarget || Boolean(chips2)) && styles$1.labelLead), children: label2 }),
2089
+ deliveredThroughCallTool ? /* @__PURE__ */ jsx("span", { className: styles$1.viaCallTool, title: translateText("The model called this tool through call_tool"), "data-testid": "trace-via-call-tool", children: translateText("via call_tool") }) : null,
2090
+ chips2 ? /* @__PURE__ */ jsx("span", { className: styles$1.chips, children: chips2 }) : null,
2091
+ hasTarget ? /* @__PURE__ */ jsx("span", { className: classNames(styles$1.target, targetKind === "text" && styles$1.targetText), children: target2 }) : null,
2092
+ meta2 !== void 0 || hasDetail ? /* @__PURE__ */ jsxs("span", { className: styles$1.meta, children: [
2093
+ !showsState && state === "failed" ? /* @__PURE__ */ jsx(TraceStateIcon, { state: "failed", size: 13 }) : null,
2094
+ meta2,
2095
+ hasDetail ? /* @__PURE__ */ jsx(TraceChevron, { isOpen: shownIsOpen }) : null
2096
+ ] }) : null
2097
+ ] });
2098
+ return /* @__PURE__ */ jsxs("div", { className: classNames(styles$1.anchor, isCompact && styles$1.compact), "data-testid": testId, "data-trace-row": variant, "data-trace-step-anchor": anchorId ?? void 0, children: [
2099
+ /* @__PURE__ */ jsxs("div", { className: rowClassName, children: [
2100
+ hasDetail ? (
2101
+ // The toggle covers the row; the chips (links) lie above it, so a link in a row is never inside a button.
2102
+ /* @__PURE__ */ jsx(
2103
+ "button",
2104
+ {
2105
+ type: "button",
2106
+ className: styles$1.rowToggle,
2107
+ "aria-expanded": shownIsOpen,
2108
+ "aria-controls": bodyId,
2109
+ "aria-label": typeof target2 === "string" && target2 !== "" ? `${label2} ${target2}` : label2,
2110
+ onClick: toggle
2111
+ }
2112
+ )
2113
+ ) : null,
2114
+ content
2115
+ ] }),
2116
+ hasDetail && shownIsOpen ? /* @__PURE__ */ jsx("div", { id: bodyId, className: hasPlainBody ? void 0 : styles$1.body, children }) : null
2117
+ ] });
2118
+ };
2119
+ const readSubAgentDurationMs = (subAgent, now) => {
2120
+ const runs = subAgent.runs ?? [];
2121
+ const newestRun = runs[runs.length - 1];
2122
+ const startedAt = readTraceMoment(newestRun?.startedAt);
2123
+ if (startedAt === null) return null;
2124
+ const finishedAt = readTraceMoment(newestRun?.finishedAt);
2125
+ return Math.max(0, (finishedAt ?? now) - startedAt);
2126
+ };
2127
+ const describeSubAgentCounts = (subAgents, format) => {
2128
+ const countByState = { running: 0, done: 0, failed: 0, waiting: 0, cancelled: 0 };
2129
+ for (const subAgent of subAgents) countByState[readTraceSubAgentState(subAgent)] += 1;
2130
+ const parts = [
2131
+ describeSubAgentCount(subAgents.length, format)
2132
+ ];
2133
+ if (countByState.done > 0) parts.push(translateText("%count% done", { count: format.number(countByState.done) }));
2134
+ if (countByState.running > 0) parts.push(translateText("%count% running", { count: format.number(countByState.running) }));
2135
+ if (countByState.waiting > 0) parts.push(translateText("%count% waiting", { count: format.number(countByState.waiting) }));
2136
+ if (countByState.failed > 0) parts.push(translateText("%count% failed", { count: format.number(countByState.failed) }));
2137
+ if (countByState.cancelled > 0) parts.push(translateText("%count% cancelled", { count: format.number(countByState.cancelled) }));
2138
+ return parts.join(" · ");
2139
+ };
2140
+ const SubAgentStepRow = (props) => {
2141
+ const {
2142
+ subAgent,
2143
+ viewMode: viewMode2 = "normal",
2144
+ defaultOpen = false,
2145
+ buildChildConversationHref,
2146
+ openChildConversation,
2147
+ renderChildTrace,
2148
+ linkComponent,
2149
+ formatCost,
2150
+ isCompact = false
2151
+ } = props;
2152
+ const format = useTraceFormat();
2153
+ const state = readTraceSubAgentState(subAgent);
2154
+ const now = useTraceNow(state === "running");
2155
+ const isVerbose = viewMode2 === "verbose";
2156
+ const durationMs = readSubAgentDurationMs(subAgent, now);
2157
+ const runs = subAgent.runs ?? [];
2158
+ const newestRun = runs[runs.length - 1];
2159
+ const costInUsd = subAgent.costInUsd ?? newestRun?.costInUsd ?? null;
2160
+ const inputTokens = subAgent.inputTokens ?? newestRun?.inputTokens ?? null;
2161
+ const outputTokens = subAgent.outputTokens ?? newestRun?.outputTokens ?? null;
2162
+ const childConversationId = subAgent.childConversationId ?? null;
2163
+ const childConversationHref = childConversationId !== null ? buildChildConversationHref?.(childConversationId) ?? null : null;
2164
+ const modelWords = subAgent.modelLabel || describeTraceModelName(subAgent.modelName);
2165
+ const metaParts = [
2166
+ isVerbose && !isCompact ? modelWords : null,
2167
+ durationMs === null || durationMs === 0 && state !== "running" ? null : state === "running" ? translateText("running %clock%", { clock: formatTraceClock(durationMs) }) : format.duration(durationMs),
2168
+ isVerbose && costInUsd !== null && costInUsd > 0 ? (formatCost ?? format.cost)(costInUsd) : null
2169
+ ].filter((part) => part !== null);
2170
+ const isBackgroundJob = subAgent.taskKind === "toolRun" || isTraceBackgroundJobLabel(subAgent.taskText);
2171
+ const taskText = isBackgroundJob ? describeTraceBackgroundJob(subAgent.toolName ?? subAgent.taskText) : subAgent.taskText;
2172
+ const result = readTraceRunResultText(newestRun?.verdict);
2173
+ const failureReason = newestRun?.failureReason ?? null;
2174
+ return /* @__PURE__ */ jsx(
2175
+ ToolStepRow,
2176
+ {
2177
+ state,
2178
+ showsStateInLead: true,
2179
+ label: subAgent.number != null ? `#${subAgent.number} ${subAgent.label}` : subAgent.label,
2180
+ meta: metaParts.length > 0 ? metaParts.join(" · ") : void 0,
2181
+ defaultOpen,
2182
+ isCompact,
2183
+ testId: "trace-sub-agent",
2184
+ children: /* @__PURE__ */ jsxs("div", { className: agentStyles.subAgentCard, children: [
2185
+ /* @__PURE__ */ jsxs("dl", { className: agentStyles.facts, children: [
2186
+ taskText ? /* @__PURE__ */ jsxs(Fragment, { children: [
2187
+ /* @__PURE__ */ jsx("dt", { className: agentStyles.factName, children: translateText("Task") }),
2188
+ /* @__PURE__ */ jsx("dd", { className: agentStyles.factValue, children: taskText })
2189
+ ] }) : null,
2190
+ isVerbose && (subAgent.modelName || subAgent.modelLabel) ? /* @__PURE__ */ jsxs(Fragment, { children: [
2191
+ /* @__PURE__ */ jsx("dt", { className: agentStyles.factName, children: translateText("Model") }),
2192
+ /* @__PURE__ */ jsx("dd", { className: `${agentStyles.factValue} ${agentStyles.factStrong}`, title: subAgent.modelName ?? void 0, children: modelWords })
2193
+ ] }) : null,
2194
+ (subAgent.skillNames ?? []).length > 0 ? /* @__PURE__ */ jsxs(Fragment, { children: [
2195
+ /* @__PURE__ */ jsx("dt", { className: agentStyles.factName, children: translateText("Skills") }),
2196
+ /* @__PURE__ */ jsx("dd", { className: `${agentStyles.factValue} ${agentStyles.factStrong}`, children: (subAgent.skillNames ?? []).join(", ") })
2197
+ ] }) : null,
2198
+ /* @__PURE__ */ jsx("dt", { className: agentStyles.factName, children: translateText("Result") }),
2199
+ /* @__PURE__ */ jsx("dd", { className: `${agentStyles.factValue} ${failureReason && !result ? agentStyles.factDanger : ""}`, children: result ?? failureReason ?? /* @__PURE__ */ jsx("span", { className: agentStyles.quiet, children: translateText("No result yet") }) }),
2200
+ isVerbose && (inputTokens !== null || outputTokens !== null) ? /* @__PURE__ */ jsxs(Fragment, { children: [
2201
+ /* @__PURE__ */ jsx("dt", { className: agentStyles.factName, children: translateText("Tokens") }),
2202
+ /* @__PURE__ */ jsx("dd", { className: agentStyles.factValue, children: translateText("%input% in · %output% out", { input: format.count(inputTokens ?? 0), output: format.count(outputTokens ?? 0) }) })
2203
+ ] }) : null
2204
+ ] }),
2205
+ /* @__PURE__ */ jsxs("div", { className: agentStyles.cardFoot, children: [
2206
+ childConversationId !== null && (childConversationHref !== null || openChildConversation) ? /* @__PURE__ */ jsxs(
2207
+ TraceLink,
2208
+ {
2209
+ href: childConversationHref,
2210
+ onClick: childConversationHref === null && openChildConversation ? () => openChildConversation(childConversationId) : void 0,
2211
+ linkComponent,
2212
+ children: [
2213
+ /* @__PURE__ */ jsx(Icon, { name: "external", pixelSize: 13 }),
2214
+ translateText("Open conversation #%id%", { id: childConversationId })
2215
+ ]
2216
+ }
2217
+ ) : null,
2218
+ isVerbose && newestRun ? /* @__PURE__ */ jsx("span", { className: agentStyles.quiet, children: translateText("Run %number% · %status%", { number: newestRun.runNumber ?? runs.length, status: readTraceStateLabel(state) }) }) : null
2219
+ ] }),
2220
+ childConversationId !== null && renderChildTrace ? /* @__PURE__ */ jsx("div", { className: agentStyles.childTrace, "data-testid": "trace-sub-agent-child-trace", children: renderChildTrace(childConversationId) }) : null
2221
+ ] })
2222
+ }
2223
+ );
2224
+ };
2225
+ const SubAgentStepGroup = (props) => {
2226
+ const {
2227
+ subAgents,
2228
+ viewMode: viewMode2 = "normal",
2229
+ isOpen,
2230
+ defaultOpen,
2231
+ onOpenChange,
2232
+ defaultOpenSubAgentIndex,
2233
+ meta: meta2,
2234
+ waiting,
2235
+ isCompact = false,
2236
+ ...rowProps
2237
+ } = props;
2238
+ const format = useTraceFormat();
2239
+ const [shownIsOpen, toggle] = useTraceDisclosure(isOpen, defaultOpen ?? viewMode2 === "verbose", onOpenChange);
2240
+ if (viewMode2 === "summary" || subAgents.length === 0) return null;
2241
+ const rows = subAgents.map((subAgent, index) => /* @__PURE__ */ jsx(
2242
+ SubAgentStepRow,
2243
+ {
2244
+ subAgent,
2245
+ viewMode: viewMode2,
2246
+ defaultOpen: defaultOpenSubAgentIndex === index,
2247
+ isCompact,
2248
+ ...rowProps
2249
+ },
2250
+ subAgent.childConversationId ?? `${subAgent.number ?? index}:${subAgent.label}`
2251
+ ));
2252
+ const deadline = readTraceMoment(waiting?.deadlineAt);
2253
+ const waitingDetail = [
2254
+ deadline !== null ? translateText("Deadline %time%", { time: format.time(deadline) }) : null,
2255
+ waiting?.wakeConditionText ?? null
2256
+ ].filter((part) => part !== null && part !== "");
2257
+ const waitingRow = waiting ? /* @__PURE__ */ jsx(
2258
+ ToolStepRow,
2259
+ {
2260
+ variant: "waiting",
2261
+ iconSlot: /* @__PURE__ */ jsx("span", { className: `${styles$1.spinner} ${styles$1.spinnerWaiting}`, "aria-hidden": true }),
2262
+ label: translateText("Waiting for the sub-agents"),
2263
+ target: waitingDetail.length > 0 ? waitingDetail.join(" · ") : void 0,
2264
+ targetKind: "text",
2265
+ isCompact,
2266
+ testId: "trace-sub-agents-waiting"
2267
+ }
2268
+ ) : null;
2269
+ if (subAgents.length === 1) {
2270
+ return /* @__PURE__ */ jsxs("div", { className: styles$1.steps, "data-testid": "trace-sub-agent-group", children: [
2271
+ rows,
2272
+ waitingRow
2273
+ ] });
2274
+ }
2275
+ return /* @__PURE__ */ jsxs("div", { className: styles$1.steps, "data-testid": "trace-sub-agent-group", children: [
2276
+ /* @__PURE__ */ jsx(
2277
+ ToolStepRow,
2278
+ {
2279
+ icon: "branch",
2280
+ variant: "fold",
2281
+ label: describeSubAgentCounts(subAgents, format),
2282
+ meta: meta2,
2283
+ isOpen: shownIsOpen,
2284
+ onOpenChange: toggle,
2285
+ hasPlainBody: true,
2286
+ isCompact,
2287
+ testId: "trace-sub-agent-group-head",
2288
+ children: /* @__PURE__ */ jsx("div", { className: styles$1.nest, children: rows })
2289
+ }
2290
+ ),
2291
+ waitingRow
2292
+ ] });
2293
+ };
2294
+ const splitOutputLines = (output2) => {
2295
+ if (!output2) return [];
2296
+ const lines = output2.replace(/\r\n/g, "\n").split("\n");
2297
+ if (lines[lines.length - 1] === "") lines.pop();
2298
+ return lines;
2299
+ };
2300
+ const TerminalBlock = (props) => {
2301
+ const {
2302
+ command: command2,
2303
+ cwd: cwd2,
2304
+ exitCode,
2305
+ durationMs,
2306
+ output: output2,
2307
+ errorOutput,
2308
+ isTruncated = false,
2309
+ isBackground = false,
2310
+ timedOut = false,
2311
+ isRunning = false,
2312
+ isNarrow = false,
2313
+ maxLines = isNarrow ? 8 : 12,
2314
+ className
2315
+ } = props;
2316
+ const format = useTraceFormat();
2317
+ const [isExpanded, setIsExpanded] = useState(false);
2318
+ const outputLines = splitOutputLines(output2);
2319
+ const errorLines = splitOutputLines(errorOutput);
2320
+ const hiddenLineCount = Math.max(0, outputLines.length - maxLines) + Math.max(0, errorLines.length - maxLines);
2321
+ const shownOutputLines = isExpanded ? outputLines : outputLines.slice(0, maxLines);
2322
+ const shownErrorLines = isExpanded ? errorLines : errorLines.slice(0, maxLines);
2323
+ const exitChip = timedOut ? /* @__PURE__ */ jsx("span", { className: classNames(styles.exit, styles.exitBad, styles.terminalSans), children: translateText("timed out") }) : exitCode != null ? /* @__PURE__ */ jsx("span", { className: classNames(styles.exit, exitCode === 0 ? styles.exitOk : styles.exitBad, styles.terminalSans), "data-testid": "trace-terminal-exit", children: translateText("exit %code%", { code: exitCode }) }) : isRunning || isBackground ? /* @__PURE__ */ jsx("span", { className: classNames(styles.exit, styles.exitRunning, styles.terminalSans), children: isBackground ? translateText("in the background") : translateText("running") }) : null;
2324
+ return /* @__PURE__ */ jsxs("div", { className: classNames(styles.terminal, className), "data-testid": "trace-terminal", "data-narrow": isNarrow || void 0, children: [
2325
+ /* @__PURE__ */ jsxs("div", { className: styles.terminalHead, children: [
2326
+ /* @__PURE__ */ jsx("span", { className: styles.prompt, "aria-hidden": true, children: "$" }),
2327
+ /* @__PURE__ */ jsx("span", { className: styles.command, children: command2 ?? "" }),
2328
+ /* @__PURE__ */ jsxs("span", { className: styles.terminalMeta, children: [
2329
+ !isNarrow && cwd2 ? /* @__PURE__ */ jsx("span", { className: styles.cwd, title: cwd2, children: cwd2 }) : null,
2330
+ durationMs != null ? /* @__PURE__ */ jsx("span", { className: styles.terminalSans, children: format.duration(durationMs) }) : null,
2331
+ exitChip
2332
+ ] })
2333
+ ] }),
2334
+ shownOutputLines.length > 0 ? /* @__PURE__ */ jsx("pre", { className: styles.output, children: shownOutputLines.join("\n") }) : null,
2335
+ shownErrorLines.length > 0 ? /* @__PURE__ */ jsx("pre", { className: classNames(styles.output, shownOutputLines.length > 0 && styles.outputError, styles.outputErrorColour), "data-testid": "trace-terminal-error", children: shownErrorLines.join("\n") }) : null,
2336
+ hiddenLineCount > 0 ? /* @__PURE__ */ jsx("button", { type: "button", className: classNames(styles.terminalMore, styles.terminalSans), "aria-expanded": isExpanded, onClick: () => setIsExpanded(!isExpanded), children: isExpanded ? translateText("Show fewer lines") : describeShowMoreLines(hiddenLineCount, format) }) : null,
2337
+ isTruncated ? /* @__PURE__ */ jsx("div", { className: classNames(styles.terminalNote, styles.terminalSans), children: translateText("The output was shortened when it was recorded.") }) : null
2338
+ ] });
2339
+ };
2340
+ const ThinkingBlock = (props) => {
2341
+ const { durationMs, reasoningTokens, summary: summary2, isRunning = false, isOpen, defaultOpen, onOpenChange, isCompact } = props;
2342
+ const format = useTraceFormat();
2343
+ const figures = [
2344
+ durationMs != null ? format.duration(durationMs) : null,
2345
+ reasoningTokens != null && reasoningTokens > 0 ? translateText("%count% tokens", { count: format.count(reasoningTokens) }) : null
2346
+ ].filter((figure) => figure !== null);
2347
+ return /* @__PURE__ */ jsx(
2348
+ ToolStepRow,
2349
+ {
2350
+ icon: "thinking",
2351
+ state: isRunning ? "running" : void 0,
2352
+ variant: "thinking",
2353
+ label: isRunning ? translateText("Thinking…") : translateText("Thought"),
2354
+ meta: figures.length > 0 ? figures.join(" · ") : void 0,
2355
+ isOpen,
2356
+ defaultOpen,
2357
+ onOpenChange,
2358
+ isCompact,
2359
+ testId: "trace-thinking",
2360
+ children: summary2 ? /* @__PURE__ */ jsx("div", { className: styles$1.panel, children: /* @__PURE__ */ jsx("div", { className: styles$1.code, style: { paddingTop: 10, fontFamily: "inherit", fontStyle: "normal" }, children: summary2 }) }) : null
2361
+ }
2362
+ );
2363
+ };
2364
+ const DONE_STATUSES = ["done", "not_applicable", "completed", "skipped", "cancelled"];
2365
+ const clampCount = (count, total) => Math.max(0, Math.min(total, Math.round(count)));
2366
+ const readTaskPlanCounts = (source) => {
2367
+ const topLevelItems = (source.items ?? []).filter((item) => (item.depth ?? 0) <= 0);
2368
+ const total = Math.max(0, source.itemCount ?? topLevelItems.length);
2369
+ let done;
2370
+ let blocked;
2371
+ if (source.doneItemCount != null) {
2372
+ done = clampCount(source.doneItemCount, total);
2373
+ blocked = clampCount(source.blockedItemCount ?? 0, total - done);
2374
+ } else if (topLevelItems.length > 0) {
2375
+ done = clampCount(topLevelItems.filter((item) => DONE_STATUSES.includes((item.status ?? "").toLowerCase())).length, total);
2376
+ blocked = clampCount(topLevelItems.filter((item) => (item.status ?? "").toLowerCase() === "blocked").length, total - done);
2377
+ } else {
2378
+ done = clampCount(total - (source.openItemCount ?? total), total);
2379
+ blocked = 0;
2380
+ }
2381
+ return { total, done, blocked, open: Math.max(0, total - done - blocked) };
2382
+ };
2383
+ const describeTaskPlanProgress = (counts, format) => {
2384
+ const doneText = translateText("%done% of %total% done", { done: format.number(counts.done), total: format.number(counts.total) });
2385
+ if (counts.blocked <= 0) return doneText;
2386
+ const replacements = { count: format.number(counts.blocked) };
2387
+ const blockedText = counts.blocked === 1 ? translateText("%count% blocked", replacements, "plan-progress-one") : translateText("%count% blocked", replacements, "plan-progress-other");
2388
+ return `${doneText} · ${blockedText}`;
2389
+ };
2390
+ const readTaskPlanCountsOfStep = (step) => readTaskPlanCounts({
2391
+ itemCount: step.taskPlanItemCount,
2392
+ openItemCount: step.taskPlanOpenItemCount,
2393
+ doneItemCount: step.taskPlanDoneItemCount,
2394
+ blockedItemCount: step.taskPlanBlockedItemCount,
2395
+ items: step.taskPlanItems
2396
+ });
2397
+ const VERBOSE_ONLY_KINDS = ["THINKING", "MODEL_CALL", "COMPACTION", "SIGNAL", "DECISION"];
2398
+ const selectVisibleTraceSteps = (steps2, viewMode2) => {
2399
+ if (viewMode2 === "summary") return [];
2400
+ if (viewMode2 === "verbose") return steps2;
2401
+ return steps2.filter((step) => !VERBOSE_ONLY_KINDS.includes(step.kind));
2402
+ };
2403
+ const describeStepKind = (step) => {
2404
+ switch (step.kind) {
2405
+ case "THINKING":
2406
+ return translateText("Thought");
2407
+ case "MODEL_CALL":
2408
+ return translateText("Model call");
2409
+ case "SKILL_LOAD":
2410
+ return translateText("Loaded skills");
2411
+ case "SUB_AGENT":
2412
+ return translateText("Sub-agent");
2413
+ case "WIDGET":
2414
+ return translateText("Showed a widget");
2415
+ case "COMPACTION":
2416
+ return translateText("Compacted the conversation");
2417
+ case "SIGNAL":
2418
+ return translateText("Signal");
2419
+ case "DECISION":
2420
+ return translateText("Decision");
2421
+ case "TASK_PLAN":
2422
+ return translateText("Updated the plan");
2423
+ case "ERROR":
2424
+ return translateText("Error");
2425
+ }
2426
+ if (step.terminal) return translateText("Ran a command");
2427
+ if ((step.fileChanges ?? []).length > 0) return translateText("Changed files");
2428
+ return translateText("Used a tool");
2429
+ };
2430
+ const readStepTarget = (step, format) => {
2431
+ if (step.terminal?.command) return step.terminal.command;
2432
+ const fileChanges = step.fileChanges ?? [];
2433
+ if (fileChanges.length === 1) return fileChanges[0].path;
2434
+ if (fileChanges.length > 1) return describeFileCount(fileChanges.length, format);
2435
+ if (step.kind === "SKILL_LOAD" && (step.loadedSkillNames ?? []).length > 0) return (step.loadedSkillNames ?? []).join(", ");
2436
+ if (step.kind === "SKILL_LOAD" && (step.skillLoad?.skills ?? []).length > 0) return (step.skillLoad?.skills ?? []).map((skill) => skill.name).join(", ");
2437
+ if (step.kind === "MODEL_CALL" && (step.modelCall?.toolNames ?? []).length > 0) return `→ ${(step.modelCall?.toolNames ?? []).join(", ")}`;
2438
+ if (step.kind === "WIDGET" && (step.widget?.type ?? step.widgetType)) return step.widget?.type ?? step.widgetType ?? null;
2439
+ if (step.kind === "TASK_PLAN" && step.taskPlanTitle) return step.taskPlanTitle;
2440
+ return null;
2441
+ };
2442
+ const readFirstLine = (text) => {
2443
+ const firstLine = (text ?? "").split("\n").find((line2) => line2.trim() !== "");
2444
+ return firstLine ? firstLine.trim() : null;
2445
+ };
2446
+ const TraceStepRow = (props) => {
2447
+ const { step, viewMode: viewMode2 = "normal", host, conversationId = null, isCompact = false, defaultOpen } = props;
2448
+ const format = useTraceFormat();
2449
+ const isVerbose = viewMode2 === "verbose";
2450
+ const state = readTraceStepState(step);
2451
+ if (step.kind === "THINKING") {
2452
+ return /* @__PURE__ */ jsx(
2453
+ ThinkingBlock,
2454
+ {
2455
+ durationMs: step.durationMs,
2456
+ reasoningTokens: step.modelCall?.reasoningTokens,
2457
+ summary: step.thinkingSummary,
2458
+ isRunning: state === "running",
2459
+ isCompact
2460
+ }
2461
+ );
2462
+ }
2463
+ if (step.kind === "MODEL_CALL" && step.thinkingSummary) {
2464
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
2465
+ /* @__PURE__ */ jsx(
2466
+ ThinkingBlock,
2467
+ {
2468
+ durationMs: null,
2469
+ reasoningTokens: step.modelCall?.reasoningTokens,
2470
+ summary: step.thinkingSummary,
2471
+ isCompact
2472
+ }
2473
+ ),
2474
+ /* @__PURE__ */ jsx(TraceStepRow, { ...props, step: { ...step, thinkingSummary: null } })
2475
+ ] });
2476
+ }
2477
+ if (step.kind === "SUB_AGENT" && step.subAgent) {
2478
+ return /* @__PURE__ */ jsx(
2479
+ SubAgentStepRow,
2480
+ {
2481
+ subAgent: step.subAgent,
2482
+ viewMode: viewMode2,
2483
+ defaultOpen,
2484
+ isCompact,
2485
+ buildChildConversationHref: host?.buildChildConversationHref,
2486
+ openChildConversation: host?.openChildConversation,
2487
+ renderChildTrace: host?.renderChildTrace,
2488
+ linkComponent: host?.linkComponent,
2489
+ formatCost: host?.formatCost
2490
+ }
2491
+ );
2492
+ }
2493
+ const narratedLine = step.line || null;
2494
+ const words = step.toolNameInWords || null;
2495
+ const target2 = readStepTarget(step, format);
2496
+ const fileChanges = step.fileChanges ?? [];
2497
+ const linesAdded = fileChanges.reduce((sum, fileChange) => sum + (fileChange.linesAdded ?? 0), 0);
2498
+ const linesRemoved = fileChanges.reduce((sum, fileChange) => sum + (fileChange.linesRemoved ?? 0), 0);
2499
+ const decision = step.kind === "DECISION" ? step.decision ?? null : null;
2500
+ const compaction = step.kind === "COMPACTION" ? step.compaction ?? null : null;
2501
+ const signal = step.kind === "SIGNAL" ? step.signal ?? null : null;
2502
+ const isNamedByKind = step.kind === "DECISION" || step.kind === "COMPACTION" || step.kind === "SIGNAL" || step.kind === "SKILL_LOAD" && !step.toolName;
2503
+ const kindName = decision !== null ? describeTraceDecision(decision) ?? describeStepKind(step) : signal !== null && (signal.kind || signal.source) ? `${describeStepKind(step)} · ${describeTraceSignal(signal.kind, signal.source)}` : describeStepKind(step);
2504
+ const kindOutcome = decision !== null ? describeTraceDecisionSummary(decision.resultSummary) ?? decision.resultSummary ?? decision.subject ?? null : compaction !== null ? describeTraceCompaction(compaction, format) ?? narratedLine : signal !== null ? describeTraceSignalText(signal.text) ?? readFirstLine(signal.text) ?? narratedLine : step.kind === "SKILL_LOAD" ? null : narratedLine;
2505
+ const verboseName = isNamedByKind ? kindName : step.kind === "MODEL_CALL" ? step.modelLabel ?? describeTraceModelName(step.modelCall?.modelName) : step.toolName ?? null;
2506
+ const label2 = isVerbose || isNamedByKind ? verboseName ?? narratedLine ?? words ?? describeStepKind(step) : narratedLine ?? words ?? describeStepKind(step);
2507
+ const isSentence = !isVerbose && !isNamedByKind && narratedLine !== null;
2508
+ const sentenceTarget = step.kind === "ERROR" ? step.errorText ?? null : isNamedByKind ? kindOutcome : isVerbose && verboseName !== null ? narratedLine : null;
2509
+ const codeTarget = isSentence && !isVerbose ? null : target2;
2510
+ const shownTarget = codeTarget ?? sentenceTarget;
2511
+ const chips2 = (step.entityReferences ?? []).map((reference) => {
2512
+ const description = host?.describeEntity?.(reference) ?? null;
2513
+ if (description === null) return null;
2514
+ return /* @__PURE__ */ jsx(
2515
+ EntityChip,
2516
+ {
2517
+ label: description.label,
2518
+ icon: description.icon,
2519
+ href: description.href,
2520
+ argumentName: reference.argumentName,
2521
+ id: reference.id,
2522
+ buildEntityHref: host?.buildEntityHref,
2523
+ linkComponent: host?.linkComponent
2524
+ },
2525
+ `${reference.argumentName}:${reference.id}`
2526
+ );
2527
+ }).filter((chip) => chip !== null);
2528
+ const metaParts = [];
2529
+ if (step.isHeldForConsent) {
2530
+ metaParts.push(
2531
+ /* @__PURE__ */ jsx("span", { className: classNames(styles$1.badge, styles$1.badgeWarning), children: translateText("waits for approval") }, "consent")
2532
+ );
2533
+ }
2534
+ if (!step.isHeldForConsent && (step.isRefused || (step.status ?? "").toUpperCase() === "REFUSED")) {
2535
+ metaParts.push(
2536
+ /* @__PURE__ */ jsx("span", { className: styles$1.badge, children: translateText("not run") }, "refused")
2537
+ );
2538
+ }
2539
+ const decisionStatusWords = decision !== null ? describeTraceDecisionStatus(decision.status ?? step.status) : null;
2540
+ if (decisionStatusWords !== null) {
2541
+ metaParts.push(
2542
+ /* @__PURE__ */ jsx("span", { className: readTraceDecisionStatusClassName(decision?.status ?? step.status), children: decisionStatusWords }, "decision-status")
2543
+ );
2544
+ }
2545
+ if (step.kind === "TASK_PLAN" && step.taskPlanItemCount != null) {
2546
+ metaParts.push(
2547
+ /* @__PURE__ */ jsx("span", { children: translateText("%done% of %total%", {
2548
+ done: readTaskPlanCountsOfStep(step).done,
2549
+ total: step.taskPlanItemCount
2550
+ }) }, "plan")
2551
+ );
2552
+ }
2553
+ if (linesAdded > 0 || linesRemoved > 0) {
2554
+ metaParts.push(
2555
+ /* @__PURE__ */ jsxs("span", { children: [
2556
+ /* @__PURE__ */ jsxs("span", { className: styles$1.added, children: [
2557
+ "+",
2558
+ format.number(linesAdded)
2559
+ ] }),
2560
+ " ",
2561
+ /* @__PURE__ */ jsxs("span", { className: styles$1.removed, children: [
2562
+ "−",
2563
+ format.number(linesRemoved)
2564
+ ] })
2565
+ ] }, "lines")
2566
+ );
2567
+ }
2568
+ if (isVerbose && step.kind === "MODEL_CALL" && step.modelCall?.costInUsd != null) {
2569
+ metaParts.push(/* @__PURE__ */ jsx("span", { children: (host?.formatCost ?? format.cost)(step.modelCall.costInUsd) }, "cost"));
2570
+ }
2571
+ if (step.durationMs != null && state !== "running") metaParts.push(/* @__PURE__ */ jsx("span", { children: format.duration(step.durationMs) }, "duration"));
2572
+ const stepExtras = host?.renderStepExtras?.(step, viewMode2) ?? null;
2573
+ const hasStepExtras = stepExtras !== null && stepExtras !== false;
2574
+ const taskPlanItems = step.kind === "TASK_PLAN" ? step.taskPlanItems ?? [] : [];
2575
+ const widget = step.kind === "WIDGET" ? step.widget ?? null : null;
2576
+ const skillLoad = step.skillLoad ?? null;
2577
+ const contextMessageId = step.kind === "MODEL_CALL" ? step.modelCall?.contextMessageId ?? step.messageId ?? null : null;
2578
+ const openModelCallContext = host?.openModelCallContext;
2579
+ const hasToolFacts = Boolean(step.argumentsJson) || Boolean(step.result) || step.modelCall != null || (step.loadedSkills ?? []).length > 0 || (step.loadedSkillNames ?? []).length > 0 && step.kind !== "SKILL_LOAD" && skillLoad === null;
2580
+ const verboseDetail = !isVerbose ? null : /* @__PURE__ */ jsxs(Fragment, { children: [
2581
+ decision !== null ? /* @__PURE__ */ jsx(DecisionDetail, { decision }) : null,
2582
+ compaction !== null ? /* @__PURE__ */ jsx(CompactionDetail, { compaction }) : null,
2583
+ signal !== null ? /* @__PURE__ */ jsx(SignalDetail, { signal }) : null,
2584
+ widget !== null ? /* @__PURE__ */ jsx(WidgetDetail, { widget }) : null,
2585
+ skillLoad !== null ? /* @__PURE__ */ jsx(SkillLoadDetail, { skillLoad }) : null,
2586
+ hasToolFacts || step.errorText ? /* @__PURE__ */ jsx(
2587
+ ToolStepDetail,
2588
+ {
2589
+ argumentsJson: step.argumentsJson,
2590
+ isArgumentsCut: step.isArgumentsCut,
2591
+ result: step.terminal ? null : step.result,
2592
+ resultChars: step.resultChars,
2593
+ isResultCut: step.isResultCut,
2594
+ errorText: step.errorText,
2595
+ loadedSkillNames: step.kind === "SKILL_LOAD" || skillLoad !== null ? [] : step.loadedSkillNames,
2596
+ loadedSkills: step.loadedSkills,
2597
+ modelCall: step.modelCall,
2598
+ modelLabel: step.modelLabel,
2599
+ durationMs: step.modelCall ? step.durationMs : null,
2600
+ formatCost: host?.formatCost,
2601
+ toolSkillNames: step.toolSkillNames,
2602
+ onOpenContext: openModelCallContext && contextMessageId !== null ? () => openModelCallContext(contextMessageId) : void 0
2603
+ }
2604
+ ) : null
2605
+ ] });
2606
+ const hasVerboseDetail = isVerbose && (decision !== null || compaction !== null || signal !== null || widget !== null || skillLoad !== null || hasToolFacts || Boolean(step.errorText));
2607
+ const hasPlainFacts = Boolean(step.toolNameInWords || step.toolName) || step.durationMs != null || Boolean(step.startedAt) || (step.toolSkillNames ?? []).length > 0;
2608
+ const showsPlainFacts = !hasVerboseDetail && hasPlainFacts;
2609
+ const showsWidgetWords = !isVerbose && widget !== null && Boolean(widget.title || widget.summary);
2610
+ const hasDetail = step.terminal != null || fileChanges.length > 0 || taskPlanItems.length > 0 || hasVerboseDetail || Boolean(step.errorText) || showsWidgetWords || showsPlainFacts || hasStepExtras;
2611
+ const sandboxHrefOf = (path2, fileChangeId) => conversationId === null ? null : host?.buildSandboxHref?.(conversationId, fileChangeId != null ? { path: path2, fileChangeId } : { path: path2 }) ?? null;
2612
+ return /* @__PURE__ */ jsx(
2613
+ ToolStepRow,
2614
+ {
2615
+ icon: host?.resolveToolIcon?.(step) ?? readTraceStepIcon(step),
2616
+ state,
2617
+ label: label2,
2618
+ labelWeight: isSentence ? "regular" : "strong",
2619
+ target: shownTarget ?? void 0,
2620
+ targetKind: codeTarget === null ? "text" : "code",
2621
+ chips: chips2.length > 0 ? chips2 : void 0,
2622
+ deliveredThroughCallTool: isVerbose && step.deliveredThroughCallTool === true,
2623
+ meta: metaParts.length > 0 ? metaParts : void 0,
2624
+ variant: state === "waiting" ? "waiting" : "step",
2625
+ defaultOpen,
2626
+ isCompact,
2627
+ testId: "trace-step",
2628
+ anchorId: step.stepId ?? null,
2629
+ children: hasDetail ? /* @__PURE__ */ jsxs(Fragment, { children: [
2630
+ step.terminal ? /* @__PURE__ */ jsx(TerminalBlock, { ...step.terminal, isRunning: state === "running", isNarrow: isCompact }) : null,
2631
+ fileChanges.map((fileChange, index) => /* @__PURE__ */ jsx(
2632
+ FileEditBlock,
2633
+ {
2634
+ fileChange,
2635
+ describeMount: host?.describeMount,
2636
+ onLoadFullDiff: host?.loadFullDiff,
2637
+ onOpenInViewer: host?.canOpenFileInViewer?.(fileChange) ?? true ? host?.openFileInViewer : void 0,
2638
+ thumbnail: host?.renderFileThumbnail?.(fileChange),
2639
+ sandboxHref: sandboxHrefOf(fileChange.path, fileChange.id),
2640
+ linkComponent: host?.linkComponent,
2641
+ isNarrow: isCompact,
2642
+ maxLines: isCompact ? void 0 : 24
2643
+ },
2644
+ `${fileChange.id ?? index}:${fileChange.path}`
2645
+ )),
2646
+ taskPlanItems.length > 0 ? /* @__PURE__ */ jsx(TaskPlanStepDetail, { title: step.taskPlanTitle, items: taskPlanItems }) : null,
2647
+ verboseDetail,
2648
+ !isVerbose && step.errorText ? /* @__PURE__ */ jsx("div", { className: classNames(styles$1.badge, styles$1.badgeDanger), style: { height: "auto", whiteSpace: "normal", padding: "4px 10px", borderRadius: 8 }, children: step.errorText }) : null,
2649
+ showsWidgetWords ? /* @__PURE__ */ jsxs("div", { className: styles$1.detail, children: [
2650
+ widget?.title ? /* @__PURE__ */ jsx("div", { className: styles$1.detailText, children: widget.title }) : null,
2651
+ widget?.summary ? /* @__PURE__ */ jsx("div", { className: styles$1.detailQuiet, children: widget.summary }) : null
2652
+ ] }) : null,
2653
+ showsPlainFacts ? /* @__PURE__ */ jsx(StepFactsLine, { step }) : null,
2654
+ hasStepExtras ? stepExtras : null
2655
+ ] }) : null
2656
+ }
2657
+ );
2658
+ };
2659
+ const buildGroupEntries = (steps2) => {
2660
+ const entries = [];
2661
+ let subAgentRun = [];
2662
+ const flushSubAgentRun = () => {
2663
+ if (subAgentRun.length >= 2) entries.push({ kind: "subAgents", key: `sub-agents:${subAgentRun[0].key}`, steps: subAgentRun });
2664
+ else for (const step of subAgentRun) entries.push({ kind: "step", step });
2665
+ subAgentRun = [];
2666
+ };
2667
+ for (const step of steps2) {
2668
+ if (step.kind === "SUB_AGENT" && step.subAgent) {
2669
+ subAgentRun.push(step);
2670
+ continue;
2671
+ }
2672
+ flushSubAgentRun();
2673
+ entries.push({ kind: "step", step });
2674
+ }
2675
+ flushSubAgentRun();
2676
+ return entries;
2677
+ };
2678
+ const ToolStepGroup = (props) => {
2679
+ const {
2680
+ steps: steps2,
2681
+ viewMode: viewMode2 = "normal",
2682
+ durationMs,
2683
+ isRunning = false,
2684
+ isOpen,
2685
+ defaultOpen,
2686
+ onOpenChange,
2687
+ summary: summary2,
2688
+ metaLine: metaLine2,
2689
+ result,
2690
+ host,
2691
+ conversationId = null,
2692
+ isCompact = false,
2693
+ className
2694
+ } = props;
2695
+ const format = useTraceFormat();
2696
+ const visibleSteps = selectVisibleTraceSteps(steps2, viewMode2);
2697
+ const workedInSandbox = steps2.some((step) => step.terminal != null || (step.fileChanges ?? []).length > 0);
2698
+ const sandboxHref = workedInSandbox && conversationId !== null ? host?.buildSandboxHref?.(conversationId, {}) ?? null : null;
2699
+ const isVerbose = viewMode2 === "verbose";
2700
+ const hasSteps = visibleSteps.length > 0 || isRunning && viewMode2 !== "summary";
2701
+ if (!hasSteps && !result && !(isVerbose && metaLine2)) return null;
2702
+ const stepCount = visibleSteps.length;
2703
+ const label2 = stepCount === 0 ? translateText("Working…") : describeStepCount(stepCount, format);
2704
+ const headMeta = [];
2705
+ if (sandboxHref !== null) {
2706
+ headMeta.push(
2707
+ /* @__PURE__ */ jsx(TraceLink, { href: sandboxHref, linkComponent: host?.linkComponent, title: translateText("Open the sandbox of this conversation"), children: translateText("Sandbox") }, "sandbox")
2708
+ );
2709
+ }
2710
+ if (summary2) headMeta.push(/* @__PURE__ */ jsx("span", { children: summary2 }, "summary"));
2711
+ if (durationMs != null && !isRunning) headMeta.push(/* @__PURE__ */ jsx("span", { children: format.duration(durationMs) }, "duration"));
2712
+ return /* @__PURE__ */ jsxs("div", { className: classNames(styles$1.steps, isCompact && styles$1.compact, className), "data-testid": "trace-step-group", "data-view-mode": viewMode2, children: [
2713
+ hasSteps ? /* @__PURE__ */ jsx(
2714
+ ToolStepRow,
2715
+ {
2716
+ icon: "steps",
2717
+ state: isRunning ? "running" : void 0,
2718
+ variant: "fold",
2719
+ label: label2,
2720
+ meta: headMeta.length > 0 ? headMeta : void 0,
2721
+ isOpen,
2722
+ defaultOpen: defaultOpen ?? (isVerbose || isRunning),
2723
+ onOpenChange,
2724
+ hasPlainBody: true,
2725
+ isCompact,
2726
+ testId: "trace-step-group-head",
2727
+ children: stepCount > 0 ? /* @__PURE__ */ jsx("div", { className: styles$1.nest, children: buildGroupEntries(visibleSteps).map(
2728
+ (entry) => entry.kind === "step" ? /* @__PURE__ */ jsx(TraceStepRow, { step: entry.step, viewMode: viewMode2, host, conversationId, isCompact }, entry.step.key) : /* @__PURE__ */ jsx(
2729
+ SubAgentStepGroup,
2730
+ {
2731
+ subAgents: entry.steps.flatMap((step) => step.subAgent ? [step.subAgent] : []),
2732
+ viewMode: viewMode2,
2733
+ isCompact,
2734
+ buildChildConversationHref: host?.buildChildConversationHref,
2735
+ openChildConversation: host?.openChildConversation,
2736
+ renderChildTrace: host?.renderChildTrace,
2737
+ linkComponent: host?.linkComponent,
2738
+ formatCost: host?.formatCost
2739
+ },
2740
+ entry.key
2741
+ )
2742
+ ) }) : null
2743
+ },
2744
+ `${viewMode2}:${isRunning}`
2745
+ ) : null,
2746
+ isVerbose ? metaLine2 : null,
2747
+ result
2748
+ ] });
2749
+ };
2750
+ const TurnMetaLine = (props) => {
2751
+ const {
2752
+ modelName,
2753
+ modelLabel,
2754
+ effort,
2755
+ inputTokens,
2756
+ outputTokens,
2757
+ cachePercent,
2758
+ costInUsd,
2759
+ durationMs,
2760
+ stateLabel,
2761
+ stateTone = "warning",
2762
+ onOpenContext,
2763
+ contextHref,
2764
+ onOpenAnalysis,
2765
+ analysisHref,
2766
+ linkComponent,
2767
+ formatCost,
2768
+ isCompact = false,
2769
+ children,
2770
+ className
2771
+ } = props;
2772
+ const format = useTraceFormat();
2773
+ const hasTokens = inputTokens != null || outputTokens != null;
2774
+ const tokens = hasTokens ? translateText("%count% tokens", { count: format.count((inputTokens ?? 0) + (outputTokens ?? 0)) }) : null;
2775
+ const cache = cachePercent != null ? translateText("%percent% % cached", { percent: format.number(Math.round(cachePercent)) }) : null;
2776
+ const tokensAndCache = [tokens, cache].filter(Boolean).join(" · ");
2777
+ return /* @__PURE__ */ jsxs("div", { className: classNames(styles$1.metaLine, isCompact && styles$1.metaLineCompact, className), "data-testid": "trace-turn-meta", children: [
2778
+ modelName ? /* @__PURE__ */ jsxs("span", { className: classNames(styles$1.pill, styles$1.pillModel), title: modelName, children: [
2779
+ /* @__PURE__ */ jsx(Icon, { name: "model", pixelSize: 12, className: styles$1.pillIcon }),
2780
+ [modelLabel ?? describeTraceModelName(modelName), describeTraceEffort(effort)].filter(Boolean).join(" · ")
2781
+ ] }) : null,
2782
+ tokensAndCache !== "" ? /* @__PURE__ */ jsx("span", { className: styles$1.pill, children: tokensAndCache }) : null,
2783
+ costInUsd != null ? /* @__PURE__ */ jsxs("span", { className: styles$1.pill, children: [
2784
+ /* @__PURE__ */ jsx(Icon, { name: "cost", pixelSize: 12, className: styles$1.pillIcon }),
2785
+ (formatCost ?? format.cost)(costInUsd)
2786
+ ] }) : null,
2787
+ durationMs != null ? /* @__PURE__ */ jsxs("span", { className: styles$1.pill, children: [
2788
+ /* @__PURE__ */ jsx(Icon, { name: "stepWaiting", pixelSize: 12, className: styles$1.pillIcon }),
2789
+ format.duration(durationMs)
2790
+ ] }) : null,
2791
+ stateLabel ? /* @__PURE__ */ jsx("span", { className: classNames(styles$1.pill, stateTone === "warning" && styles$1.pillWarning, stateTone === "danger" && styles$1.pillDanger), children: stateLabel }) : null,
2792
+ children,
2793
+ /* @__PURE__ */ jsx("span", { className: styles$1.metaGrow }),
2794
+ /* @__PURE__ */ jsxs("span", { className: styles$1.metaLinks, "data-testid": "trace-turn-meta-links", children: [
2795
+ /* @__PURE__ */ jsxs(TraceLink, { href: contextHref, onClick: onOpenContext, linkComponent, children: [
2796
+ /* @__PURE__ */ jsx(Icon, { name: "code", pixelSize: 13 }),
2797
+ translateText("What the model saw")
2798
+ ] }),
2799
+ /* @__PURE__ */ jsxs(TraceLink, { href: analysisHref, onClick: onOpenAnalysis, linkComponent, children: [
2800
+ /* @__PURE__ */ jsx(Icon, { name: "external", pixelSize: 13 }),
2801
+ translateText("Open in analysis")
2802
+ ] })
2803
+ ] })
2804
+ ] });
2805
+ };
2806
+ const readNewSideLines = (hunk2) => hunk2.lines.filter((line2) => line2.kind !== "removed");
2807
+ const isHunkWhole = (hunk2) => {
2808
+ const newLineCount = readNewSideLines(hunk2).length;
2809
+ const oldLineCount = hunk2.lines.filter((line2) => line2.kind !== "added").length;
2810
+ return newLineCount === hunk2.newLineCount && oldLineCount === hunk2.oldLineCount;
2811
+ };
2812
+ const byteLengthOf = (text) => new TextEncoder().encode(text).length;
2813
+ const readContentFromUnifiedDiff = (diffText, options = {}) => {
2814
+ const { changeType = null, sizeAfter = null } = options;
2815
+ if (!diffText || changeType === "DELETED" || changeType === "DIRECTORY_CREATED") return null;
2816
+ const diff = parseUnifiedDiff(diffText);
2817
+ if (diff.isBinary || diff.hunks.length === 0) return null;
2818
+ if (!diff.hunks.every(isHunkWhole)) return null;
2819
+ const [firstHunk] = diff.hunks;
2820
+ if (firstHunk.newLineCount === 0 || firstHunk.newStart !== 1) return null;
2821
+ if (firstHunk.oldLineCount === 0 ? firstHunk.oldStart !== 0 : firstHunk.oldStart !== 1) return null;
2822
+ let nextOldStart = firstHunk.oldStart + firstHunk.oldLineCount;
2823
+ let nextNewStart = firstHunk.newStart + firstHunk.newLineCount;
2824
+ for (const hunk2 of diff.hunks.slice(1)) {
2825
+ const oldStart = hunk2.oldLineCount === 0 ? hunk2.oldStart + 1 : hunk2.oldStart;
2826
+ const newStart = hunk2.newLineCount === 0 ? hunk2.newStart + 1 : hunk2.newStart;
2827
+ if (oldStart !== nextOldStart || newStart !== nextNewStart) return null;
2828
+ nextOldStart = oldStart + hunk2.oldLineCount;
2829
+ nextNewStart = newStart + hunk2.newLineCount;
2830
+ }
2831
+ const newLines = diff.hunks.flatMap(readNewSideLines);
2832
+ if (newLines.length === 0) return null;
2833
+ if (newLines.slice(0, -1).some((line2) => line2.hasNoNewlineAtEnd)) return null;
2834
+ const endsWithoutLineEnd = newLines[newLines.length - 1].hasNoNewlineAtEnd;
2835
+ const isNewFile = diff.hunks.length === 1 && firstHunk.oldLineCount === 0 && firstHunk.lines.every((line2) => line2.kind === "added");
2836
+ if (changeType === "ADDED" && !isNewFile) return null;
2837
+ const texts = newLines.map((line2) => line2.text);
2838
+ const buildContent = (lineEnd) => texts.join(lineEnd) + (endsWithoutLineEnd ? "" : lineEnd);
2839
+ const hasCrlfLines = /\r\n/.test(diffText);
2840
+ const preferredContent = buildContent(hasCrlfLines ? "\r\n" : "\n");
2841
+ if (sizeAfter !== null && sizeAfter >= 0) {
2842
+ if (byteLengthOf(preferredContent) === sizeAfter) return preferredContent;
2843
+ const otherContent = buildContent(hasCrlfLines ? "\n" : "\r\n");
2844
+ if (byteLengthOf(otherContent) === sizeAfter) return otherContent;
2845
+ }
2846
+ return isNewFile || endsWithoutLineEnd ? preferredContent : null;
2847
+ };
2848
+ export {
2849
+ buildSideBySideDiffRows as $,
2850
+ describeTraceBackgroundJob as A,
2851
+ readTraceStepState as B,
2852
+ CompactionDetail as C,
2853
+ DecisionDetail as D,
2854
+ EntityChip as E,
2855
+ FileChangesSummary as F,
2856
+ SkillLoadDetail as G,
2857
+ StepFactsLine as H,
2858
+ SubAgentStepGroup as I,
2859
+ SubAgentStepRow as J,
2860
+ TRACE_CONTEXT_SEGMENT_LABELS as K,
2861
+ LoadedSkillsDisclosure as L,
2862
+ TRACE_DECISION_SITE_LABELS as M,
2863
+ TRACE_SIGNAL_SOURCE_LABELS as N,
2864
+ TRACE_SIGNAL_TAG_LABELS as O,
2865
+ TRACE_WAKE_CONDITION_LABELS as P,
2866
+ TaskPlanStepDetail as Q,
2867
+ TerminalBlock as R,
2868
+ SignalDetail as S,
2869
+ TraceStateIcon as T,
2870
+ ThinkingBlock as U,
2871
+ ToolStepDetail as V,
2872
+ ToolStepRow as W,
2873
+ TraceCodePanel as X,
2874
+ TraceCopyButton as Y,
2875
+ TraceViewModeSwitch as Z,
2876
+ WidgetDetail as _,
2877
+ useTraceNow as a,
2878
+ createTraceFormat as a0,
2879
+ describeSubAgentCounts as a1,
2880
+ describeTraceCompaction as a2,
2881
+ describeTraceContextSegment as a3,
2882
+ describeTraceDecision as a4,
2883
+ describeTraceDecisionSite as a5,
2884
+ describeTraceDecisionStatus as a6,
2885
+ describeTraceModelName as a7,
2886
+ describeTraceMount as a8,
2887
+ describeTraceSignal as a9,
2888
+ describeTraceSkillCause as aa,
2889
+ describeTraceWakeCondition as ab,
2890
+ formatShortSha256 as ac,
2891
+ parseUnifiedDiff as ad,
2892
+ prettyPrintTraceJson as ae,
2893
+ readContentFromUnifiedDiff as af,
2894
+ readTraceFileChangeIcon as ag,
2895
+ readTraceIdInWords as ah,
2896
+ readTraceRunResultText as ai,
2897
+ readTraceStateOfStatus as aj,
2898
+ readTraceStepIcon as ak,
2899
+ describeTraceEffort as al,
2900
+ readTraceFileName as am,
2901
+ agentStyles as b,
2902
+ readTraceStateLabel as c,
2903
+ styles as d,
2904
+ readTraceFileChangeLetter as e,
2905
+ formatTraceClock as f,
2906
+ readTraceFileChangeWord as g,
2907
+ TracePath as h,
2908
+ TraceMountChip as i,
2909
+ TraceLink as j,
2910
+ FileEditBlock as k,
2911
+ selectVisibleTraceSteps as l,
2912
+ TraceStepRow as m,
2913
+ TaskPlanRow as n,
2914
+ readTaskPlanCountsOfStep as o,
2915
+ buildTaskPlanItems as p,
2916
+ describeStepCount as q,
2917
+ readTraceMoment as r,
2918
+ styles$1 as s,
2919
+ TurnMetaLine as t,
2920
+ useTraceFormat as u,
2921
+ ToolStepGroup as v,
2922
+ readTaskPlanCounts as w,
2923
+ describeTaskPlanProgress as x,
2924
+ isTraceBackgroundJobLabel as y,
2925
+ readTraceSubAgentState as z
2926
+ };
2927
+ //# sourceMappingURL=content-from-unified-diff-CovnmG2Q.js.map