@leitwerk-dev/ui 0.1.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 (170) hide show
  1. package/dist/LICENSE +13 -0
  2. package/dist/assets/ChronicleMarkdown-BLgtHeEE.js +16 -0
  3. package/dist/assets/ChronicleMarkdown-D6hFzERy.css +1 -0
  4. package/dist/assets/FutureLaunchDetailPage-KrXSGzHM.js +1 -0
  5. package/dist/assets/FutureLaunchDetailPage-VPMBtpYc.css +1 -0
  6. package/dist/assets/GenericLauncher-Cv38FByt.js +1 -0
  7. package/dist/assets/GenericLauncher-D_GMtsQ5.css +1 -0
  8. package/dist/assets/HomePage-Cd3lEtwZ.js +1 -0
  9. package/dist/assets/HomePage-DYh_QHXv.css +1 -0
  10. package/dist/assets/PageHeader-6PdvYODN.css +1 -0
  11. package/dist/assets/PageHeader-D6pP4hIh.js +1 -0
  12. package/dist/assets/ProcessActionsMenu-1QySGNy9.js +1 -0
  13. package/dist/assets/ProcessActionsMenu-BT2r9vO8.css +1 -0
  14. package/dist/assets/ProcessDetailPage-BLuc7sjV.js +12 -0
  15. package/dist/assets/ProcessDetailPage-CSrjzajF.css +1 -0
  16. package/dist/assets/ProcessFlowDiagram-BAh_M_rb.js +2 -0
  17. package/dist/assets/ProcessFlowDiagram-Cz8wNicU.css +1 -0
  18. package/dist/assets/ProcessesPage-BcM38HMs.css +1 -0
  19. package/dist/assets/ProcessesPage-DtPweRU-.js +1 -0
  20. package/dist/assets/ScheduleDateTimePicker-CQGvY-Rc.js +1 -0
  21. package/dist/assets/ScheduleDateTimePicker-CadXN9z7.css +1 -0
  22. package/dist/assets/SkillsPage-B30FAFia.css +1 -0
  23. package/dist/assets/SkillsPage-bXuv0kEE.js +2 -0
  24. package/dist/assets/WatchersPage-DNyUsU1y.js +1 -0
  25. package/dist/assets/WatchersPage-Dnfi1zUK.css +1 -0
  26. package/dist/assets/api-CqECFdii.js +1 -0
  27. package/dist/assets/browser-storage-LbKCyf_w.js +1 -0
  28. package/dist/assets/dist-B7WNbObw.js +2 -0
  29. package/dist/assets/index-66T4Gmbl.css +1 -0
  30. package/dist/assets/index-C8qCggeq.js +7 -0
  31. package/dist/assets/index-client-BqF3_t3P.js +2 -0
  32. package/dist/assets/mermaid-render.worker-DAVgiVRG.js +6393 -0
  33. package/dist/assets/retry-config.svelte-DFKCJtCe.js +1 -0
  34. package/dist/assets/router.svelte-COr45o9R.js +1 -0
  35. package/dist/fonts/OFL-Public-Sans.txt +115 -0
  36. package/dist/fonts/OFL-Spectral.txt +93 -0
  37. package/dist/fonts/README.md +38 -0
  38. package/dist/fonts/fonts.css +85 -0
  39. package/dist/fonts/public-sans-latin-cd00287f.woff2 +0 -0
  40. package/dist/fonts/public-sans-latin-ext-d025d4ba.woff2 +0 -0
  41. package/dist/fonts/spectral-latin-89d48951.woff2 +0 -0
  42. package/dist/fonts/spectral-latin-b7578f14.woff2 +0 -0
  43. package/dist/fonts/spectral-latin-c4e0a00d.woff2 +0 -0
  44. package/dist/fonts/spectral-latin-ext-260738f4.woff2 +0 -0
  45. package/dist/fonts/spectral-latin-ext-ab18ac17.woff2 +0 -0
  46. package/dist/fonts/spectral-latin-ext-f58c1db3.woff2 +0 -0
  47. package/dist/index.html +32 -0
  48. package/package.json +47 -0
  49. package/src/App.svelte +257 -0
  50. package/src/chronicle/components/ChronicleActionSection.svelte +1035 -0
  51. package/src/chronicle/components/ChronicleExpandButton.svelte +70 -0
  52. package/src/chronicle/components/ChronicleFlow.svelte +289 -0
  53. package/src/chronicle/components/ChronicleLeafOutcomePlaceholder.svelte +44 -0
  54. package/src/chronicle/components/ChronicleLeafOutcomeRendererHost.svelte +408 -0
  55. package/src/chronicle/components/ChronicleLeafOutcomeSection.svelte +253 -0
  56. package/src/chronicle/components/ChronicleLiveChip.svelte +96 -0
  57. package/src/chronicle/components/ChronicleLiveTail.svelte +376 -0
  58. package/src/chronicle/components/ChronicleMarkdown.svelte +168 -0
  59. package/src/chronicle/components/ChronicleOperatorInputSection.svelte +41 -0
  60. package/src/chronicle/components/ChronicleProcessErrorSection.svelte +131 -0
  61. package/src/chronicle/components/ChroniclePromptSection.svelte +54 -0
  62. package/src/chronicle/components/ChronicleQuestionRequest.svelte +167 -0
  63. package/src/chronicle/components/ChronicleReasoningDetailsOverlay.svelte +893 -0
  64. package/src/chronicle/components/ChronicleRecoverySection.svelte +338 -0
  65. package/src/chronicle/components/ChronicleScheduledActionSection.svelte +192 -0
  66. package/src/chronicle/components/ChronicleSectionHeader.svelte +135 -0
  67. package/src/chronicle/components/ChronicleStartupRecoverySection.svelte +138 -0
  68. package/src/chronicle/components/ChronicleTerminalSummary.svelte +127 -0
  69. package/src/chronicle/components/ChronicleThinkingSection.svelte +191 -0
  70. package/src/chronicle/components/ChronicleThinkingText.svelte +46 -0
  71. package/src/chronicle/components/ChronicleToolCallItem.svelte +477 -0
  72. package/src/chronicle/components/ChronicleTurnCluster.svelte +325 -0
  73. package/src/chronicle/components/ChronicleTurnRail.svelte +584 -0
  74. package/src/chronicle/components/ChronicleUsageStats.svelte +107 -0
  75. package/src/chronicle/components/CompactActionComposer.svelte +417 -0
  76. package/src/chronicle/components/ModelProfileOptions.svelte +20 -0
  77. package/src/chronicle/components/ProviderOptionsEditor.svelte +171 -0
  78. package/src/chronicle/components/RecoveryModelControl.svelte +95 -0
  79. package/src/chronicle/lib/action-bindings.ts +90 -0
  80. package/src/chronicle/lib/action-model-display.ts +133 -0
  81. package/src/chronicle/lib/action-preview.ts +16 -0
  82. package/src/chronicle/lib/chronicle-projection.ts +1342 -0
  83. package/src/chronicle/lib/chronicle-selectable-items.ts +352 -0
  84. package/src/chronicle/lib/chronicle-view-model.ts +121 -0
  85. package/src/chronicle/lib/formatting.ts +18 -0
  86. package/src/chronicle/lib/leaf-outcome-loader.ts +214 -0
  87. package/src/chronicle/lib/leaf-outcome-runtime.ts +37 -0
  88. package/src/chronicle/lib/prompt-highlighting.ts +78 -0
  89. package/src/chronicle/lib/scroll-sync.ts +88 -0
  90. package/src/chronicle/lib/tool-call-summary.ts +64 -0
  91. package/src/components/BrowserUiExtensionIndicatorHost.svelte +34 -0
  92. package/src/components/ConversationTreeDiagram.svelte +393 -0
  93. package/src/components/FormFieldRenderer.svelte +359 -0
  94. package/src/components/GenericLauncher.svelte +1970 -0
  95. package/src/components/KeyboardShortcutsModal.svelte +52 -0
  96. package/src/components/ModalShell.svelte +105 -0
  97. package/src/components/PageHeader.svelte +146 -0
  98. package/src/components/ProcessActionsMenu.svelte +514 -0
  99. package/src/components/ProcessInfoOverlay.svelte +1229 -0
  100. package/src/components/ScheduleDateTimePicker.svelte +155 -0
  101. package/src/components/SkillSelector.svelte +45 -0
  102. package/src/components/ToastContainer.svelte +192 -0
  103. package/src/components/launcher-form-copy.ts +172 -0
  104. package/src/components/launcher-model-config.ts +263 -0
  105. package/src/components/launcher-schedule.ts +127 -0
  106. package/src/extension-ui-dev-server.ts +98 -0
  107. package/src/lib/api.ts +970 -0
  108. package/src/lib/beautiful-mermaid-elk-instance.ts +54 -0
  109. package/src/lib/browser-storage.ts +11 -0
  110. package/src/lib/cost-estimates.ts +41 -0
  111. package/src/lib/elk-bundled-worker.ts +41 -0
  112. package/src/lib/flow-layout.ts +326 -0
  113. package/src/lib/format.ts +96 -0
  114. package/src/lib/future-executions-logic.ts +12 -0
  115. package/src/lib/future-launch-detail.ts +145 -0
  116. package/src/lib/instance-tree-layout.ts +158 -0
  117. package/src/lib/keyboard-shortcuts-help.ts +20 -0
  118. package/src/lib/keyboard.ts +40 -0
  119. package/src/lib/launcher-recent-values.ts +68 -0
  120. package/src/lib/markdown.ts +94 -0
  121. package/src/lib/mermaid-render.worker.ts +36 -0
  122. package/src/lib/pi-stream.ts +3 -0
  123. package/src/lib/primary-path-detail.ts +337 -0
  124. package/src/lib/primary-path-replay.ts +27 -0
  125. package/src/lib/process-browser.ts +179 -0
  126. package/src/lib/process-initial-prompt.ts +7 -0
  127. package/src/lib/process-launch-notices.svelte.ts +25 -0
  128. package/src/lib/process-row-view.ts +60 -0
  129. package/src/lib/process-terminal-display.ts +17 -0
  130. package/src/lib/process-toast-focus.svelte.ts +18 -0
  131. package/src/lib/processes-logic.ts +2 -0
  132. package/src/lib/processes.svelte.ts +334 -0
  133. package/src/lib/request-guard.ts +20 -0
  134. package/src/lib/retry-config.svelte.ts +19 -0
  135. package/src/lib/rich-markdown-elements.ts +173 -0
  136. package/src/lib/router-logic.ts +190 -0
  137. package/src/lib/router.svelte.ts +56 -0
  138. package/src/lib/runtime-config.ts +96 -0
  139. package/src/lib/test-fixtures.ts +13 -0
  140. package/src/lib/toasts.svelte.ts +104 -0
  141. package/src/lib/tool-call-rendering.ts +66 -0
  142. package/src/lib/ui-extensions.svelte.ts +381 -0
  143. package/src/lib/usage-snapshot.ts +9 -0
  144. package/src/lib/ws-classifier.ts +80 -0
  145. package/src/lib/ws.svelte.ts +281 -0
  146. package/src/main.ts +8 -0
  147. package/src/pages/FutureLaunchDetailPage.svelte +479 -0
  148. package/src/pages/HomePage.svelte +306 -0
  149. package/src/pages/ProcessCard.svelte +99 -0
  150. package/src/pages/ProcessDetailPage.svelte +599 -0
  151. package/src/pages/ProcessFlowDiagram.svelte +696 -0
  152. package/src/pages/ProcessGallery.svelte +252 -0
  153. package/src/pages/ProcessesPage.svelte +994 -0
  154. package/src/pages/SkillsPage.svelte +665 -0
  155. package/src/pages/WatchersPage.svelte +330 -0
  156. package/src/pages/process-detail/OverlayFrame.svelte +58 -0
  157. package/src/pages/process-detail/ProcessDetailChronicle.svelte +460 -0
  158. package/src/pages/process-detail/ProcessDetailHeader.svelte +167 -0
  159. package/src/pages/process-detail/process-detail-action-drafts.svelte.ts +211 -0
  160. package/src/pages/process-detail/process-detail-actions.svelte.ts +548 -0
  161. package/src/pages/process-detail/process-detail-chronicle-dom.ts +102 -0
  162. package/src/pages/process-detail/process-detail-chronicle-scroll.svelte.ts +711 -0
  163. package/src/pages/process-detail/process-detail-mutations.svelte.ts +91 -0
  164. package/src/pages/process-detail/process-detail-view-model.ts +149 -0
  165. package/src/shell/AppShell.svelte +249 -0
  166. package/src/shell/RouteLoadBoundary.svelte +43 -0
  167. package/src/shell/Sidebar.svelte +1358 -0
  168. package/src/shell/test-fixtures/RouteLoadTestComponent.svelte +5 -0
  169. package/src/vite-env.d.ts +2 -0
  170. package/src/vite-server-config.ts +27 -0
@@ -0,0 +1,1342 @@
1
+ import {
2
+ formatPathTypeLabel,
3
+ type ProcessInput,
4
+ type ProcessLeafOutcomeSnapshot,
5
+ type ProcessTurnRecord,
6
+ trimToNull,
7
+ } from "@leitwerk-dev/domain";
8
+ import {
9
+ buildTrailingLinePreview,
10
+ type PrimaryPathActiveTurnSnapshot,
11
+ type ProcessTimelineTurnSummary,
12
+ type TurnPiInputPart,
13
+ type TurnTracePreview,
14
+ type TurnTraceSnapshot,
15
+ type TurnUsageSnapshot,
16
+ } from "@leitwerk-dev/protocol";
17
+
18
+ type ChronicleInput = Pick<
19
+ ProcessInput,
20
+ "id" | "sequence" | "source" | "kind" | "bodyMarkdown" | "receivedAt" | "consumedAt"
21
+ >;
22
+
23
+ import type { ProcessRunDetailsView } from "@leitwerk-dev/protocol/http-contracts";
24
+ import { formatDefinition } from "../../lib/format";
25
+ import { markdownToPlainText, truncateText } from "../../lib/markdown";
26
+ import { hasDisplayableText } from "../../lib/pi-stream.js";
27
+ import {
28
+ getProcessTerminalRailTitle,
29
+ type ProcessTerminalStatus,
30
+ } from "../../lib/process-terminal-display.js";
31
+
32
+ type TurnRecordView = ProcessTimelineTurnSummary;
33
+
34
+ import {
35
+ buildChronicleTurnRailItem,
36
+ type ChronicleTurnPresentation,
37
+ type ChronicleTurnRailItem,
38
+ formatChronicleTurnLabel,
39
+ getChronicleTurnKindLabel,
40
+ getChronicleTurnPresentation,
41
+ getChronicleTurnPreview,
42
+ } from "./chronicle-view-model.js";
43
+
44
+ export type ChronicleProjectedTurnRailItem = ChronicleTurnRailItem & {
45
+ anchorId: string;
46
+ retryLineageRootTurnRecordId?: string;
47
+ };
48
+
49
+ export interface ChronicleTerminalRailItem {
50
+ terminalStatus: ProcessTerminalStatus;
51
+ anchorId: string;
52
+ title: string;
53
+ }
54
+
55
+ export interface ChronicleReasoningThinkingItem {
56
+ kind: "thinking_chunk";
57
+ text: string;
58
+ }
59
+
60
+ export interface ChronicleReasoningToolItem {
61
+ kind: "tool_call";
62
+ toolCall: TurnTraceSnapshot["toolCalls"][number];
63
+ }
64
+
65
+ export interface ChronicleReasoningOperationalEventItem {
66
+ kind: "operational_event";
67
+ event: Extract<TurnTraceSnapshot["traceItems"][number], { kind: "operational_event" }>;
68
+ }
69
+
70
+ export type ChronicleReasoningTimelineItem =
71
+ | ChronicleReasoningThinkingItem
72
+ | ChronicleReasoningToolItem
73
+ | ChronicleReasoningOperationalEventItem;
74
+
75
+ export interface ChronicleThinkingSection {
76
+ kind: "thinking_preview";
77
+ text: string;
78
+ preview: string;
79
+ previewTruncated: boolean;
80
+ items: ChronicleReasoningTimelineItem[];
81
+ toolCallCount: number;
82
+ traceItemCount: number;
83
+ }
84
+
85
+ export type ChronicleTriggeringInputSource = ProcessInput["source"] | "initial_prompt";
86
+
87
+ export interface ChronicleTriggeringInputSummary {
88
+ inputId: string;
89
+ source: ChronicleTriggeringInputSource;
90
+ sourceLabel: string;
91
+ bodyMarkdown: string;
92
+ receivedAt: string;
93
+ consumedAt: string;
94
+ }
95
+
96
+ export interface ChroniclePiInputSummary {
97
+ parts: TurnPiInputPart[];
98
+ fullPrompt: string;
99
+ createdAt: string;
100
+ userInput: string | null;
101
+ }
102
+
103
+ export type ChronicleTriggerSource = "external_event" | "user_action" | "unknown";
104
+ export type ChronicleRunMode = "scheduled" | "immediate" | "unknown";
105
+
106
+ export interface ChronicleTurnFacts {
107
+ startedAt: string | null;
108
+ endedAt: string | null;
109
+ triggerSource: ChronicleTriggerSource;
110
+ runMode: ChronicleRunMode;
111
+ activeToolNames: readonly string[];
112
+ }
113
+
114
+ export interface ChronicleOperatorDecisionSection {
115
+ kind: "operator_decision";
116
+ text: string;
117
+ }
118
+
119
+ export interface ChronicleTurnResultSection {
120
+ kind: "turn_result";
121
+ markdown: string;
122
+ }
123
+
124
+ export type ChronicleTurnClusterSection =
125
+ | ChronicleThinkingSection
126
+ | ChronicleOperatorDecisionSection
127
+ | ChronicleTurnResultSection;
128
+
129
+ export interface ChronicleTurnClusterItem {
130
+ kind: "turn_cluster";
131
+ chronologyAt: string;
132
+ anchorId: string;
133
+ turnRecordId: string;
134
+ turnId: string;
135
+ turnType?: ProcessTurnRecord["turnType"];
136
+ title: string;
137
+ turnLabel: string;
138
+ pathLabel: string | null;
139
+ createdAt: string;
140
+ preview: string;
141
+ isOperatorDecision: boolean;
142
+ turnPresentation: ChronicleTurnPresentation;
143
+ turnKindLabel: string;
144
+ terminalStatus: "completed" | "aborted" | null;
145
+ sections: ChronicleTurnClusterSection[];
146
+ modelProfileId: string | null;
147
+ usage: TurnUsageSnapshot | null;
148
+ triggeringInput: ChronicleTriggeringInputSummary | null;
149
+ piInput: ChroniclePiInputSummary | null;
150
+ facts: ChronicleTurnFacts;
151
+ }
152
+
153
+ export interface ChroniclePromptItem {
154
+ kind: "prompt";
155
+ anchorId: string;
156
+ createdAt: string | null;
157
+ text: string;
158
+ preview: string;
159
+ }
160
+
161
+ export interface ChronicleOperatorInputItem {
162
+ kind: "operator_input";
163
+ chronologyAt: string;
164
+ inputId: string;
165
+ source: ProcessInput["source"];
166
+ sourceLabel: string;
167
+ bodyMarkdown: string;
168
+ receivedAt: string;
169
+ }
170
+
171
+ export interface ChronicleLeafOutcomeItem {
172
+ kind: "leaf_outcome";
173
+ chronologyAt: string;
174
+ anchorId: string;
175
+ instanceId: string;
176
+ snapshotId: string;
177
+ leafEntryId: string;
178
+ turnRecordId: string | null;
179
+ title: string;
180
+ ownerTurnTitle: string | null;
181
+ rendererId: string | null;
182
+ schemaVersion: number | null;
183
+ props: ProcessLeafOutcomeSnapshot["props"];
184
+ fallbackMarkdown: string | null;
185
+ status: ProcessLeafOutcomeSnapshot["status"];
186
+ warningCode: string | null;
187
+ warningMessage: string | null;
188
+ anchoredAt: string;
189
+ createdAt: string;
190
+ processLifecycleStatus: string | null;
191
+ processSelectedTurnId: string | null;
192
+ processUpdatedAt: string | null;
193
+ }
194
+
195
+ export interface ChronicleLeafOutcomePlaceholderItem {
196
+ kind: "leaf_outcome_placeholder";
197
+ latestTurnTitle: string | null;
198
+ }
199
+
200
+ export interface ChronicleLiveTailItem {
201
+ kind: "live_tail";
202
+ anchorId: string;
203
+ turnRecordId: string;
204
+ turnId: string;
205
+ turnType?: ProcessTurnRecord["turnType"];
206
+ title: string;
207
+ turnLabel: string;
208
+ pathLabel: string | null;
209
+ state: "tool_running" | "thinking" | "streaming" | "waiting";
210
+ stateLabel: string;
211
+ copy: string;
212
+ reasoningSection: ChronicleThinkingSection | null;
213
+ toolCall: PrimaryPathActiveTurnSnapshot["toolCalls"][number] | null;
214
+ usage: TurnUsageSnapshot | null;
215
+ eventWindowTruncated: boolean;
216
+ modelProfileId: string | null;
217
+ triggeringInput: ChronicleTriggeringInputSummary | null;
218
+ piInput: ChroniclePiInputSummary | null;
219
+ facts: ChronicleTurnFacts;
220
+ }
221
+
222
+ function formatPiTreePathLabel(
223
+ turnRecord: Pick<ProcessTurnRecord, "turnType" | "pathType">,
224
+ ): string | null {
225
+ return turnRecord.turnType === "llm" ? formatPathTypeLabel(turnRecord.pathType) : null;
226
+ }
227
+
228
+ export type ChronicleTimelineItem =
229
+ | ChroniclePromptItem
230
+ | ChronicleTurnClusterItem
231
+ | ChronicleOperatorInputItem
232
+ | ChronicleLeafOutcomeItem
233
+ | ChronicleLeafOutcomePlaceholderItem
234
+ | ChronicleLiveTailItem;
235
+
236
+ export interface ChronicleProjection {
237
+ promptItem: ChroniclePromptItem | null;
238
+ turnRailItems: ChronicleProjectedTurnRailItem[];
239
+ terminalRailItem: ChronicleTerminalRailItem | null;
240
+ timelineItems: ChronicleTimelineItem[];
241
+ initialAnchorId: string | null;
242
+ initialFocusedTurnId: string | null;
243
+ liveTail: ChronicleLiveTailItem | null;
244
+ latestCompletedTurnTitle: string | null;
245
+ }
246
+
247
+ export interface ChronicleReasoningDetailEntry {
248
+ entryId: string;
249
+ turnRecordId: string;
250
+ turnId: string;
251
+ title: string;
252
+ turnLabel: string;
253
+ stateLabel: string | null;
254
+ isLive: boolean;
255
+ modelProfileId: string | null;
256
+ usage: TurnUsageSnapshot | null;
257
+ triggeringInput: ChronicleTriggeringInputSummary | null;
258
+ piInput: ChroniclePiInputSummary | null;
259
+ facts: ChronicleTurnFacts;
260
+ reasoningSection: ChronicleThinkingSection;
261
+ }
262
+
263
+ export interface BuildChronicleProjectionInput {
264
+ turnRecords: readonly TurnRecordView[];
265
+ turnTraceIndex: Record<string, TurnTraceSnapshot | undefined>;
266
+ turnTracePreviewIndex?: Record<string, TurnTracePreview | undefined>;
267
+ runDetails?: ProcessRunDetailsView | null;
268
+ initialUserInputText?: string | null;
269
+ inputs: readonly ChronicleInput[];
270
+ leafOutcomeSnapshots: readonly ProcessLeafOutcomeSnapshot[];
271
+ definesLeafOutcome: boolean;
272
+ activeTurn: PrimaryPathActiveTurnSnapshot | null | undefined;
273
+ lifecycleStatus?: string | null;
274
+ selectedTurnId?: string | null;
275
+ processUpdatedAt?: string | null;
276
+ promptText?: string | null;
277
+ promptCreatedAt?: string | null;
278
+ }
279
+
280
+ // Tunable inline reasoning window: keep the preview calm, recent, and line-based.
281
+ export const THINKING_PREVIEW_LINE_COUNT = 3;
282
+ const THINKING_PREVIEW_MAX_LENGTH = 320;
283
+
284
+ function sanitizeDomToken(value: string): string {
285
+ return value.replace(/[^a-zA-Z0-9_-]/g, "_");
286
+ }
287
+
288
+ function buildTurnAnchorId(turnRecordId: string): string {
289
+ return `chronicle-turn-${sanitizeDomToken(turnRecordId)}`;
290
+ }
291
+
292
+ function buildLiveTailAnchorId(turnRecordId: string): string {
293
+ return `chronicle-live-${sanitizeDomToken(turnRecordId)}`;
294
+ }
295
+
296
+ function buildPromptAnchorId(): string {
297
+ return "chronicle-prompt";
298
+ }
299
+
300
+ function buildLeafOutcomeAnchorId(snapshotId: string): string {
301
+ return `chronicle-leaf-outcome-${sanitizeDomToken(snapshotId)}`;
302
+ }
303
+
304
+ function buildTerminalAnchorId(status: ProcessTerminalStatus): string {
305
+ return `chronicle-terminal-${sanitizeDomToken(status)}`;
306
+ }
307
+
308
+ function normalizeComparableText(value: string): string {
309
+ return value.replace(/\s+/g, " ").trim();
310
+ }
311
+
312
+ function buildReasoningTimelineItems(
313
+ turnTrace: TurnTraceSnapshot | undefined,
314
+ ): ChronicleReasoningTimelineItem[] {
315
+ const traceItems = turnTrace?.traceItems ?? [];
316
+ const toolCalls = turnTrace?.toolCalls ?? [];
317
+ const toolCallsById = new Map(toolCalls.map((toolCall) => [toolCall.toolCallId, toolCall]));
318
+ const resolvedItems: ChronicleReasoningTimelineItem[] = [];
319
+ const seenToolCallIds = new Set<string>();
320
+
321
+ for (const traceItem of traceItems) {
322
+ if (traceItem.kind === "thinking") {
323
+ if (!hasDisplayableText(traceItem.text)) {
324
+ continue;
325
+ }
326
+ resolvedItems.push({
327
+ kind: "thinking_chunk",
328
+ text: traceItem.text,
329
+ });
330
+ continue;
331
+ }
332
+ if (traceItem.kind === "operational_event") {
333
+ resolvedItems.push({
334
+ kind: "operational_event",
335
+ event: traceItem,
336
+ });
337
+ continue;
338
+ }
339
+ const toolCall = toolCallsById.get(traceItem.toolCallId);
340
+ if (!toolCall) {
341
+ continue;
342
+ }
343
+ seenToolCallIds.add(toolCall.toolCallId);
344
+ resolvedItems.push({
345
+ kind: "tool_call",
346
+ toolCall,
347
+ });
348
+ }
349
+
350
+ if (resolvedItems.length === 0) {
351
+ const thinkingText = turnTrace?.assistant.thinking ?? "";
352
+ if (hasDisplayableText(thinkingText)) {
353
+ resolvedItems.push({
354
+ kind: "thinking_chunk",
355
+ text: thinkingText,
356
+ });
357
+ }
358
+ for (const toolCall of toolCalls) {
359
+ resolvedItems.push({
360
+ kind: "tool_call",
361
+ toolCall,
362
+ });
363
+ seenToolCallIds.add(toolCall.toolCallId);
364
+ }
365
+ return resolvedItems;
366
+ }
367
+
368
+ for (const toolCall of toolCalls) {
369
+ if (seenToolCallIds.has(toolCall.toolCallId)) {
370
+ continue;
371
+ }
372
+ resolvedItems.push({
373
+ kind: "tool_call",
374
+ toolCall,
375
+ });
376
+ seenToolCallIds.add(toolCall.toolCallId);
377
+ }
378
+
379
+ return resolvedItems;
380
+ }
381
+
382
+ interface TurnTraceProjectionSource {
383
+ trace: TurnTraceSnapshot | undefined;
384
+ preview: TurnTracePreview | undefined;
385
+ }
386
+
387
+ function buildEmptyReasoningSection(source: TurnTraceProjectionSource): ChronicleThinkingSection {
388
+ return {
389
+ kind: "thinking_preview",
390
+ text: "",
391
+ preview: "",
392
+ previewTruncated: source.preview?.thinkingPreviewTruncated ?? false,
393
+ items: [],
394
+ toolCallCount: source.trace?.toolCalls.length ?? source.preview?.toolCallCount ?? 0,
395
+ traceItemCount: source.trace?.traceItems.length ?? source.preview?.traceItemCount ?? 0,
396
+ };
397
+ }
398
+
399
+ function buildReasoningSection(source: TurnTraceProjectionSource): ChronicleThinkingSection | null {
400
+ const thinkingText = source.trace?.assistant.thinking ?? source.preview?.thinkingPreview ?? "";
401
+ const items = buildReasoningTimelineItems(source.trace);
402
+ const hasPreviewDetails =
403
+ source.trace === undefined && source.preview?.hasReasoningDetails === true;
404
+ if (!hasDisplayableText(thinkingText) && items.length === 0 && !hasPreviewDetails) {
405
+ return null;
406
+ }
407
+ const thinkingPreview = source.trace
408
+ ? buildTrailingLinePreview(
409
+ thinkingText,
410
+ THINKING_PREVIEW_LINE_COUNT,
411
+ THINKING_PREVIEW_MAX_LENGTH,
412
+ )
413
+ : {
414
+ text: source.preview?.thinkingPreview ?? "",
415
+ truncated: source.preview?.thinkingPreviewTruncated ?? false,
416
+ };
417
+ return {
418
+ kind: "thinking_preview",
419
+ text: thinkingText,
420
+ preview: thinkingPreview.text,
421
+ previewTruncated: thinkingPreview.truncated,
422
+ items,
423
+ toolCallCount: source.trace?.toolCalls.length ?? source.preview?.toolCallCount ?? 0,
424
+ traceItemCount: source.trace?.traceItems.length ?? source.preview?.traceItemCount ?? 0,
425
+ };
426
+ }
427
+
428
+ function sourceLabel(source: ProcessInput["source"]): string {
429
+ switch (source) {
430
+ case "app_steer":
431
+ return "Operator note";
432
+ case "external_comment":
433
+ return "External comment";
434
+ case "action_prompt":
435
+ return "Action prompt";
436
+ default:
437
+ return "Input";
438
+ }
439
+ }
440
+
441
+ type ChronicleActionSource = ProcessTimelineTurnSummary["actionSource"];
442
+
443
+ function uniqueNonEmptyToolNames(values: readonly string[]): string[] {
444
+ const names = new Set<string>();
445
+ for (const value of values) {
446
+ const toolName = value.trim();
447
+ if (toolName !== "") {
448
+ names.add(toolName);
449
+ }
450
+ }
451
+ return [...names];
452
+ }
453
+
454
+ function activeToolNamesForTurn(
455
+ runDetails: ProcessRunDetailsView | null | undefined,
456
+ turnId: string,
457
+ ): readonly string[] {
458
+ const turn = runDetails?.turns.find((candidate) => candidate.turnId === turnId);
459
+ return uniqueNonEmptyToolNames([
460
+ ...(turn?.activePiToolNames ?? []),
461
+ ...(turn?.outcomeActions.map((action) => action.name) ?? []),
462
+ ]);
463
+ }
464
+
465
+ function triggerSourceFor(
466
+ triggeringInput: ChronicleTriggeringInputSummary | null,
467
+ actionSource: ChronicleActionSource | null,
468
+ ): ChronicleTriggerSource {
469
+ if (actionSource === "ui") {
470
+ return "user_action";
471
+ }
472
+ if (actionSource === "external" || actionSource === "scheduled") {
473
+ return "external_event";
474
+ }
475
+ if (!triggeringInput) {
476
+ return "unknown";
477
+ }
478
+ switch (triggeringInput.source) {
479
+ case "external_comment":
480
+ case "watcher_event":
481
+ return "external_event";
482
+ case "app_steer":
483
+ case "action_prompt":
484
+ case "initial_prompt":
485
+ return "user_action";
486
+ default:
487
+ return "unknown";
488
+ }
489
+ }
490
+
491
+ function runModeFor(
492
+ triggeringInput: ChronicleTriggeringInputSummary | null,
493
+ actionSource: ChronicleActionSource | null,
494
+ ): ChronicleRunMode {
495
+ if (actionSource === "scheduled") {
496
+ return "scheduled";
497
+ }
498
+ if (actionSource === "ui" || actionSource === "external") {
499
+ return "immediate";
500
+ }
501
+ if (
502
+ triggeringInput?.source === "initial_prompt" ||
503
+ triggeringInput?.source === "app_steer" ||
504
+ triggeringInput?.source === "external_comment" ||
505
+ triggeringInput?.source === "action_prompt" ||
506
+ triggeringInput?.source === "watcher_event"
507
+ ) {
508
+ return "immediate";
509
+ }
510
+ return "unknown";
511
+ }
512
+
513
+ function toPiInputSummary(input: {
514
+ traceSource: TurnTraceProjectionSource;
515
+ triggeringInput: ChronicleTriggeringInputSummary | null;
516
+ initialUserInputText?: string | null;
517
+ }): ChroniclePiInputSummary | null {
518
+ const piInput = input.traceSource.trace?.piInput;
519
+ const previewInput = input.traceSource.preview?.piInput;
520
+ const fullPrompt = piInput?.fullPrompt ?? previewInput?.userInputPreview ?? "";
521
+ if (fullPrompt.trim() === "") {
522
+ return null;
523
+ }
524
+ return {
525
+ parts: piInput ? [...piInput.parts] : [],
526
+ fullPrompt,
527
+ createdAt: piInput?.createdAt ?? previewInput?.createdAt ?? "",
528
+ userInput:
529
+ trimToNull(input.triggeringInput?.bodyMarkdown) ??
530
+ trimToNull(input.initialUserInputText) ??
531
+ null,
532
+ };
533
+ }
534
+
535
+ function buildTurnFacts(input: {
536
+ turnId: string;
537
+ durableTurnRecord: TurnRecordView | undefined;
538
+ activeTurn?: PrimaryPathActiveTurnSnapshot | null;
539
+ triggeringInput: ChronicleTriggeringInputSummary | null;
540
+ actionSource: ChronicleActionSource | null;
541
+ runDetails?: ProcessRunDetailsView | null;
542
+ }): ChronicleTurnFacts {
543
+ return {
544
+ startedAt: input.durableTurnRecord?.startedAt ?? input.activeTurn?.startedAt ?? null,
545
+ endedAt: input.durableTurnRecord?.endedAt ?? null,
546
+ triggerSource: triggerSourceFor(input.triggeringInput, input.actionSource),
547
+ runMode: runModeFor(input.triggeringInput, input.actionSource),
548
+ activeToolNames: activeToolNamesForTurn(input.runDetails, input.turnId),
549
+ };
550
+ }
551
+
552
+ function hasChronicleInputBody(input: ChronicleInput): boolean {
553
+ return hasDisplayableText(input.bodyMarkdown);
554
+ }
555
+
556
+ function isChronicleTriggeringInput(input: ChronicleInput): boolean {
557
+ if (!hasChronicleInputBody(input)) {
558
+ return false;
559
+ }
560
+ return (
561
+ input.source === "app_steer" ||
562
+ input.source === "external_comment" ||
563
+ input.source === "action_prompt"
564
+ );
565
+ }
566
+
567
+ function isStandaloneChronicleOperatorInput(input: ChronicleInput): boolean {
568
+ if (!hasChronicleInputBody(input)) {
569
+ return false;
570
+ }
571
+ return input.source === "app_steer" || input.source === "external_comment";
572
+ }
573
+
574
+ function hasDistinctTurnResult(
575
+ turnRecord: TurnRecordView,
576
+ assistantOutputText: string,
577
+ assistantOutputTruncated = false,
578
+ ): boolean {
579
+ if (!hasDisplayableText(turnRecord.turnResultMarkdown)) {
580
+ return false;
581
+ }
582
+ const markdownText = normalizeComparableText(markdownToPlainText(turnRecord.turnResultMarkdown));
583
+ const assistantText = normalizeComparableText(assistantOutputText);
584
+ if (markdownText.length === 0) {
585
+ return false;
586
+ }
587
+ if (assistantOutputTruncated && assistantText.length > 0) {
588
+ return !markdownText.startsWith(assistantText);
589
+ }
590
+ return markdownText !== assistantText;
591
+ }
592
+
593
+ function hasRenderableLeafOutcomeForTurn(
594
+ turnRecordId: string,
595
+ leafOutcomeSnapshots: readonly ProcessLeafOutcomeSnapshot[],
596
+ ): boolean {
597
+ return leafOutcomeSnapshots.some(
598
+ (snapshot) =>
599
+ snapshot.turnRecordId === turnRecordId &&
600
+ snapshot.status === "ready" &&
601
+ ((typeof snapshot.rendererId === "string" && snapshot.rendererId.trim() !== "") ||
602
+ hasDisplayableText(snapshot.fallbackMarkdown ?? "")),
603
+ );
604
+ }
605
+
606
+ function shouldExposeEmptyReasoningDetails(
607
+ turnRecord: Pick<TurnRecordView, "turnType" | "modelProfileId">,
608
+ traceSource: TurnTraceProjectionSource,
609
+ ): boolean {
610
+ return (
611
+ turnRecord.turnType === "llm" &&
612
+ (Boolean(traceSource.trace?.piInput) ||
613
+ traceSource.trace?.usage != null ||
614
+ traceSource.preview?.hasReasoningDetails === true ||
615
+ turnRecord.modelProfileId !== null)
616
+ );
617
+ }
618
+
619
+ function buildTurnClusterItem(input: {
620
+ turnRecord: TurnRecordView;
621
+ turnTrace: TurnTraceSnapshot | undefined;
622
+ turnTracePreview: TurnTracePreview | undefined;
623
+ terminalStatus: "completed" | "aborted" | null;
624
+ hasRenderableLeafOutcome: boolean;
625
+ triggeringInput: ChronicleTriggeringInputSummary | null;
626
+ facts: ChronicleTurnFacts;
627
+ initialUserInputText?: string | null;
628
+ }): ChronicleTurnClusterItem {
629
+ const { turnRecord, turnTrace, turnTracePreview, triggeringInput } = input;
630
+ const traceSource = { trace: turnTrace, preview: turnTracePreview };
631
+ const sections: ChronicleTurnClusterSection[] = [];
632
+ const turnPresentation = getChronicleTurnPresentation(turnRecord);
633
+ const reasoningSection =
634
+ buildReasoningSection(traceSource) ??
635
+ (shouldExposeEmptyReasoningDetails(turnRecord, traceSource)
636
+ ? buildEmptyReasoningSection(traceSource)
637
+ : null);
638
+ if (reasoningSection) {
639
+ sections.push(reasoningSection);
640
+ }
641
+
642
+ const assistantText =
643
+ turnTrace?.assistant.text?.trim() ?? turnTracePreview?.assistantTextPreview.trim() ?? "";
644
+ const fallbackText =
645
+ !hasDisplayableText(turnRecord.turnResultMarkdown) && hasDisplayableText(turnRecord.output)
646
+ ? turnRecord.output.trim()
647
+ : "";
648
+
649
+ if (assistantText.length === 0 && fallbackText.length > 0) {
650
+ sections.push({
651
+ kind: "operator_decision",
652
+ text: fallbackText,
653
+ });
654
+ }
655
+
656
+ if (
657
+ !input.hasRenderableLeafOutcome &&
658
+ hasDistinctTurnResult(
659
+ turnRecord,
660
+ assistantText || fallbackText,
661
+ turnTrace === undefined && turnTracePreview?.assistantTextTruncated === true,
662
+ )
663
+ ) {
664
+ sections.push({
665
+ kind: "turn_result",
666
+ markdown: turnRecord.turnResultMarkdown,
667
+ });
668
+ }
669
+
670
+ return {
671
+ kind: "turn_cluster",
672
+ chronologyAt: turnRecord.createdAt,
673
+ anchorId: buildTurnAnchorId(turnRecord.id),
674
+ turnRecordId: turnRecord.id,
675
+ turnId: turnRecord.turnId,
676
+ turnType: turnRecord.turnType,
677
+ title: formatChronicleTurnLabel(turnRecord.displayTurn),
678
+ turnLabel: turnRecord.turnId,
679
+ pathLabel: formatPiTreePathLabel(turnRecord),
680
+ createdAt: turnRecord.createdAt,
681
+ preview: getChronicleTurnPreview(turnRecord, 320),
682
+ isOperatorDecision: turnPresentation === "operator_decision",
683
+ turnPresentation,
684
+ turnKindLabel: getChronicleTurnKindLabel(turnRecord),
685
+ terminalStatus: input.terminalStatus,
686
+ sections,
687
+ modelProfileId: turnRecord.modelProfileId,
688
+ usage: turnTrace?.usage ?? turnTracePreview?.usage ?? null,
689
+ triggeringInput,
690
+ piInput: toPiInputSummary({
691
+ traceSource,
692
+ triggeringInput,
693
+ initialUserInputText: input.initialUserInputText,
694
+ }),
695
+ facts: input.facts,
696
+ };
697
+ }
698
+
699
+ function buildLeafOutcomeItems(
700
+ snapshots: readonly ProcessLeafOutcomeSnapshot[],
701
+ turnTitlesByTurnRecordId: ReadonlyMap<string, string>,
702
+ processState: {
703
+ lifecycleStatus: string | null;
704
+ selectedTurnId: string | null;
705
+ updatedAt: string | null;
706
+ },
707
+ ): ChronicleLeafOutcomeItem[] {
708
+ return snapshots.map((snapshot) => ({
709
+ kind: "leaf_outcome",
710
+ chronologyAt: snapshot.anchoredAt,
711
+ anchorId: buildLeafOutcomeAnchorId(snapshot.id),
712
+ instanceId: snapshot.instanceId,
713
+ snapshotId: snapshot.id,
714
+ leafEntryId: snapshot.leafEntryId,
715
+ turnRecordId: snapshot.turnRecordId,
716
+ title: "Result",
717
+ ownerTurnTitle: snapshot.turnRecordId
718
+ ? (turnTitlesByTurnRecordId.get(snapshot.turnRecordId) ?? null)
719
+ : null,
720
+ rendererId: snapshot.rendererId,
721
+ schemaVersion: snapshot.schemaVersion,
722
+ props: snapshot.props,
723
+ fallbackMarkdown: snapshot.fallbackMarkdown,
724
+ status: snapshot.status,
725
+ warningCode: snapshot.warningCode,
726
+ warningMessage: snapshot.warningMessage,
727
+ anchoredAt: snapshot.anchoredAt,
728
+ createdAt: snapshot.createdAt,
729
+ processLifecycleStatus: processState.lifecycleStatus,
730
+ processSelectedTurnId: processState.selectedTurnId,
731
+ processUpdatedAt: processState.updatedAt,
732
+ }));
733
+ }
734
+
735
+ function buildPromptItem(
736
+ text: string | null | undefined,
737
+ createdAt: string | null | undefined,
738
+ ): ChroniclePromptItem {
739
+ const resolvedText = typeof text === "string" ? text.trim() : "";
740
+ return {
741
+ kind: "prompt",
742
+ anchorId: buildPromptAnchorId(),
743
+ createdAt: typeof createdAt === "string" && createdAt.trim() !== "" ? createdAt : null,
744
+ text: resolvedText,
745
+ preview: truncateText(resolvedText || "No prompt recorded.", 120),
746
+ };
747
+ }
748
+
749
+ function compareChronicleTimestamps(left: string, right: string): number {
750
+ return left.localeCompare(right);
751
+ }
752
+
753
+ function sortInputsByConsumedAt(left: ChronicleInput, right: ChronicleInput): number {
754
+ const leftTimestamp = left.consumedAt ?? left.receivedAt;
755
+ const rightTimestamp = right.consumedAt ?? right.receivedAt;
756
+ const timestampComparison = compareChronicleTimestamps(leftTimestamp, rightTimestamp);
757
+ if (timestampComparison !== 0) {
758
+ return timestampComparison;
759
+ }
760
+ return left.sequence - right.sequence;
761
+ }
762
+
763
+ function sortInputsByReceivedAt(left: ChronicleInput, right: ChronicleInput): number {
764
+ const timestampComparison = compareChronicleTimestamps(left.receivedAt, right.receivedAt);
765
+ if (timestampComparison !== 0) {
766
+ return timestampComparison;
767
+ }
768
+ return left.sequence - right.sequence;
769
+ }
770
+
771
+ function sortTurnRecordsByStartedAt(
772
+ left: Pick<TurnRecordView, "startedAt" | "id">,
773
+ right: Pick<TurnRecordView, "startedAt" | "id">,
774
+ ): number {
775
+ const startedAtComparison = compareChronicleTimestamps(left.startedAt, right.startedAt);
776
+ if (startedAtComparison !== 0) {
777
+ return startedAtComparison;
778
+ }
779
+ return left.id.localeCompare(right.id);
780
+ }
781
+
782
+ function isConsumedTriggeringInputCandidate(input: ChronicleInput): boolean {
783
+ return (
784
+ isChronicleTriggeringInput(input) &&
785
+ typeof input.consumedAt === "string" &&
786
+ input.consumedAt !== ""
787
+ );
788
+ }
789
+
790
+ function isReceivedTriggeringInputCandidate(input: ChronicleInput): boolean {
791
+ return isChronicleTriggeringInput(input);
792
+ }
793
+
794
+ function toTriggeringInputSummary(
795
+ input: ChronicleInput,
796
+ fallbackConsumedAt?: string,
797
+ ): ChronicleTriggeringInputSummary | null {
798
+ const consumedAt = input.consumedAt ?? fallbackConsumedAt ?? input.receivedAt;
799
+ if (!consumedAt) {
800
+ return null;
801
+ }
802
+ return {
803
+ inputId: input.id,
804
+ source: input.source,
805
+ sourceLabel: sourceLabel(input.source),
806
+ bodyMarkdown: input.bodyMarkdown,
807
+ receivedAt: input.receivedAt,
808
+ consumedAt,
809
+ };
810
+ }
811
+
812
+ function buildInitialPromptTriggeringInputSummary(
813
+ initialUserInputText: string | null | undefined,
814
+ promptCreatedAt: string | null | undefined,
815
+ fallbackTimestamp: string,
816
+ ): ChronicleTriggeringInputSummary | null {
817
+ const normalizedPrompt = trimToNull(initialUserInputText) ?? "";
818
+ if (!hasDisplayableText(normalizedPrompt)) {
819
+ return null;
820
+ }
821
+ const timestamp =
822
+ typeof promptCreatedAt === "string" && promptCreatedAt.trim() !== ""
823
+ ? promptCreatedAt
824
+ : fallbackTimestamp;
825
+ return {
826
+ inputId: "chronicle-initial-prompt",
827
+ source: "initial_prompt",
828
+ sourceLabel: "Initial prompt",
829
+ bodyMarkdown: normalizedPrompt,
830
+ receivedAt: timestamp,
831
+ consumedAt: timestamp,
832
+ };
833
+ }
834
+
835
+ function buildTriggeringInputIndex(
836
+ input: BuildChronicleProjectionInput,
837
+ ): Map<string, ChronicleTriggeringInputSummary> {
838
+ const consumedCandidates = input.inputs
839
+ .filter(isConsumedTriggeringInputCandidate)
840
+ .sort(sortInputsByConsumedAt);
841
+ const receivedCandidates = input.inputs
842
+ .filter(isReceivedTriggeringInputCandidate)
843
+ .sort(sortInputsByReceivedAt);
844
+
845
+ const turnRecords = [...input.turnRecords].sort(sortTurnRecordsByStartedAt);
846
+ if (turnRecords.length === 0) {
847
+ return new Map();
848
+ }
849
+
850
+ const firstTurnRecordId = turnRecords[0]?.id ?? null;
851
+ const initialPromptSummary = buildInitialPromptTriggeringInputSummary(
852
+ input.initialUserInputText,
853
+ input.promptCreatedAt,
854
+ turnRecords[0]?.startedAt ?? "",
855
+ );
856
+ const index = new Map<string, ChronicleTriggeringInputSummary>();
857
+ const assignedInputIds = new Set<string>();
858
+ let nextConsumedCandidateIndex = 0;
859
+ let windowStartExclusive: string | null = null;
860
+
861
+ for (const turnRecord of turnRecords) {
862
+ while (nextConsumedCandidateIndex < consumedCandidates.length) {
863
+ const candidate = consumedCandidates[nextConsumedCandidateIndex];
864
+ const consumedAt = candidate.consumedAt;
865
+ if (!consumedAt) {
866
+ nextConsumedCandidateIndex += 1;
867
+ continue;
868
+ }
869
+ if (
870
+ windowStartExclusive &&
871
+ compareChronicleTimestamps(consumedAt, windowStartExclusive) <= 0
872
+ ) {
873
+ nextConsumedCandidateIndex += 1;
874
+ continue;
875
+ }
876
+ if (compareChronicleTimestamps(consumedAt, turnRecord.startedAt) > 0) {
877
+ break;
878
+ }
879
+ const summary = toTriggeringInputSummary(candidate);
880
+ if (summary) {
881
+ index.set(turnRecord.id, summary);
882
+ assignedInputIds.add(candidate.id);
883
+ }
884
+ nextConsumedCandidateIndex += 1;
885
+ break;
886
+ }
887
+
888
+ if (turnRecord.id === firstTurnRecordId && !index.has(turnRecord.id) && initialPromptSummary) {
889
+ index.set(turnRecord.id, initialPromptSummary);
890
+ }
891
+
892
+ if (!index.has(turnRecord.id)) {
893
+ for (
894
+ let receivedIndex = receivedCandidates.length - 1;
895
+ receivedIndex >= 0;
896
+ receivedIndex -= 1
897
+ ) {
898
+ const candidate = receivedCandidates[receivedIndex];
899
+ if (assignedInputIds.has(candidate.id)) {
900
+ continue;
901
+ }
902
+ if (
903
+ windowStartExclusive &&
904
+ compareChronicleTimestamps(candidate.receivedAt, windowStartExclusive) <= 0
905
+ ) {
906
+ break;
907
+ }
908
+ if (compareChronicleTimestamps(candidate.receivedAt, turnRecord.startedAt) > 0) {
909
+ continue;
910
+ }
911
+ const summary = toTriggeringInputSummary(candidate, candidate.receivedAt);
912
+ if (summary) {
913
+ index.set(turnRecord.id, summary);
914
+ assignedInputIds.add(candidate.id);
915
+ }
916
+ break;
917
+ }
918
+ }
919
+
920
+ windowStartExclusive = turnRecord.endedAt ?? turnRecord.startedAt;
921
+ }
922
+
923
+ return index;
924
+ }
925
+
926
+ function mergeLiveToolCallsWithSessionDetails(
927
+ activeToolCalls: ReadonlyArray<PrimaryPathActiveTurnSnapshot["toolCalls"][number]>,
928
+ sessionToolCalls: ReadonlyArray<TurnTraceSnapshot["toolCalls"][number]> | undefined,
929
+ ): TurnTraceSnapshot["toolCalls"] {
930
+ const sessionToolCallsById = new Map(
931
+ (sessionToolCalls ?? []).map((toolCall) => [toolCall.toolCallId, toolCall]),
932
+ );
933
+ const seenToolCallIds = new Set<string>();
934
+ const mergedToolCalls: TurnTraceSnapshot["toolCalls"] = activeToolCalls.map((toolCall) => {
935
+ seenToolCallIds.add(toolCall.toolCallId);
936
+ const sessionToolCall = sessionToolCallsById.get(toolCall.toolCallId);
937
+ if (!sessionToolCall) {
938
+ return toolCall;
939
+ }
940
+ return {
941
+ ...toolCall,
942
+ arguments: toolCall.arguments ?? sessionToolCall.arguments,
943
+ resultText: sessionToolCall.resultText,
944
+ truncated: sessionToolCall.truncated,
945
+ };
946
+ });
947
+ for (const sessionToolCall of sessionToolCalls ?? []) {
948
+ if (!seenToolCallIds.has(sessionToolCall.toolCallId)) {
949
+ mergedToolCalls.push(sessionToolCall);
950
+ }
951
+ }
952
+ return mergedToolCalls;
953
+ }
954
+
955
+ function buildLiveTail(input: {
956
+ turnRecord: TurnRecordView | null;
957
+ activeTurn: PrimaryPathActiveTurnSnapshot | null | undefined;
958
+ turnTrace: TurnTraceSnapshot | undefined;
959
+ turnTracePreview: TurnTracePreview | undefined;
960
+ triggeringInput: ChronicleTriggeringInputSummary | null;
961
+ facts: ChronicleTurnFacts | null;
962
+ runDetails?: ProcessRunDetailsView | null;
963
+ initialUserInputText?: string | null;
964
+ }): ChronicleLiveTailItem | null {
965
+ const { turnRecord, activeTurn, turnTrace, turnTracePreview, triggeringInput } = input;
966
+ if (!turnRecord) {
967
+ return null;
968
+ }
969
+ const liveToolCalls = activeTurn
970
+ ? mergeLiveToolCallsWithSessionDetails(activeTurn.toolCalls, turnTrace?.toolCalls)
971
+ : [];
972
+ const runningToolCall = activeTurn
973
+ ? ([...liveToolCalls].reverse().find((toolCall) => toolCall.status === "running") ?? null)
974
+ : null;
975
+ const thinkingText = activeTurn?.assistant.thinking ?? "";
976
+ const assistantText = activeTurn?.assistant.text.trim() ?? "";
977
+ const hasThinkingText = thinkingText.trim().length > 0;
978
+ const reasoningSection = activeTurn
979
+ ? buildReasoningSection({
980
+ trace: {
981
+ assistant: activeTurn.assistant,
982
+ toolCalls: liveToolCalls,
983
+ traceItems: activeTurn.traceItems,
984
+ usage: activeTurn.usage,
985
+ piInput: turnTrace?.piInput ?? null,
986
+ },
987
+ preview: turnTracePreview,
988
+ })
989
+ : null;
990
+ const state = runningToolCall
991
+ ? "tool_running"
992
+ : hasThinkingText
993
+ ? "thinking"
994
+ : assistantText.length > 0
995
+ ? "streaming"
996
+ : "waiting";
997
+ const thinkingPreview = buildTrailingLinePreview(
998
+ thinkingText,
999
+ THINKING_PREVIEW_LINE_COUNT,
1000
+ THINKING_PREVIEW_MAX_LENGTH,
1001
+ );
1002
+ const copy =
1003
+ state === "tool_running"
1004
+ ? `Running ${formatDefinition(runningToolCall?.toolName ?? "tool")}…`
1005
+ : state === "thinking"
1006
+ ? thinkingPreview.text
1007
+ : state === "streaming"
1008
+ ? truncateText(assistantText, 320)
1009
+ : getChronicleTurnPreview(turnRecord, 220) || "Waiting for more activity…";
1010
+ const stateLabel =
1011
+ state === "tool_running"
1012
+ ? "Running action"
1013
+ : state === "thinking"
1014
+ ? "Reasoning"
1015
+ : state === "streaming"
1016
+ ? "Writing response"
1017
+ : "Waiting for activity";
1018
+
1019
+ return {
1020
+ kind: "live_tail",
1021
+ anchorId: buildLiveTailAnchorId(turnRecord.id),
1022
+ turnRecordId: turnRecord.id,
1023
+ turnId: turnRecord.turnId,
1024
+ turnType: turnRecord.turnType,
1025
+ title: formatChronicleTurnLabel(turnRecord.displayTurn),
1026
+ turnLabel: turnRecord.turnId,
1027
+ pathLabel: activeTurn ? formatPiTreePathLabel(activeTurn) : formatPiTreePathLabel(turnRecord),
1028
+ state,
1029
+ stateLabel,
1030
+ copy,
1031
+ reasoningSection,
1032
+ toolCall: runningToolCall,
1033
+ usage: activeTurn?.usage ?? null,
1034
+ eventWindowTruncated: activeTurn?.eventWindowTruncated ?? false,
1035
+ modelProfileId: turnRecord.modelProfileId,
1036
+ triggeringInput,
1037
+ piInput: toPiInputSummary({
1038
+ traceSource: { trace: turnTrace, preview: turnTracePreview },
1039
+ triggeringInput,
1040
+ initialUserInputText: input.initialUserInputText,
1041
+ }),
1042
+ facts:
1043
+ input.facts ??
1044
+ buildTurnFacts({
1045
+ turnId: turnRecord.turnId,
1046
+ durableTurnRecord: undefined,
1047
+ activeTurn: activeTurn ?? null,
1048
+ triggeringInput,
1049
+ actionSource: null,
1050
+ runDetails: input.runDetails,
1051
+ }),
1052
+ };
1053
+ }
1054
+
1055
+ function buildRetryLineageRootIndex(turnRecords: readonly TurnRecordView[]): Map<string, string> {
1056
+ const durableById = new Map(turnRecords.map((turnRecord) => [turnRecord.id, turnRecord]));
1057
+ const rootByTurnRecordId = new Map<string, string>();
1058
+
1059
+ const resolveRootTurnRecordId = (turnRecordId: string): string => {
1060
+ const cached = rootByTurnRecordId.get(turnRecordId);
1061
+ if (cached) {
1062
+ return cached;
1063
+ }
1064
+ let currentTurnRecordId = turnRecordId;
1065
+ const seenTurnRecordIds = new Set<string>();
1066
+ while (!seenTurnRecordIds.has(currentTurnRecordId)) {
1067
+ seenTurnRecordIds.add(currentTurnRecordId);
1068
+ const currentTurnRecord = durableById.get(currentTurnRecordId);
1069
+ const parentTurnRecordId = currentTurnRecord?.parentTurnRecordId ?? null;
1070
+ if (!parentTurnRecordId) {
1071
+ break;
1072
+ }
1073
+ currentTurnRecordId = parentTurnRecordId;
1074
+ }
1075
+ rootByTurnRecordId.set(turnRecordId, currentTurnRecordId);
1076
+ return currentTurnRecordId;
1077
+ };
1078
+
1079
+ for (const turnRecord of turnRecords) {
1080
+ resolveRootTurnRecordId(turnRecord.id);
1081
+ }
1082
+
1083
+ return rootByTurnRecordId;
1084
+ }
1085
+
1086
+ function buildTurnRailItems(
1087
+ turnRecords: readonly TurnRecordView[],
1088
+ liveTail: ChronicleLiveTailItem | null,
1089
+ ): ChronicleProjectedTurnRailItem[] {
1090
+ const retryLineageRootByTurnRecordId = buildRetryLineageRootIndex(turnRecords);
1091
+ return turnRecords.map((turnRecord) => ({
1092
+ ...buildChronicleTurnRailItem(turnRecord),
1093
+ anchorId:
1094
+ turnRecord.status === "in_progress" && liveTail
1095
+ ? liveTail.anchorId
1096
+ : buildTurnAnchorId(turnRecord.id),
1097
+ retryLineageRootTurnRecordId:
1098
+ retryLineageRootByTurnRecordId.get(turnRecord.id) ?? turnRecord.id,
1099
+ }));
1100
+ }
1101
+
1102
+ function buildTerminalRailItem(
1103
+ terminalStatus: ProcessTerminalStatus | null,
1104
+ ): ChronicleTerminalRailItem | null {
1105
+ if (!terminalStatus) {
1106
+ return null;
1107
+ }
1108
+ return {
1109
+ terminalStatus,
1110
+ anchorId: buildTerminalAnchorId(terminalStatus),
1111
+ title: getProcessTerminalRailTitle(terminalStatus),
1112
+ };
1113
+ }
1114
+
1115
+ function chronicleItemOrder(item: ChronicleTimelineItem): number {
1116
+ switch (item.kind) {
1117
+ case "prompt":
1118
+ return -1;
1119
+ case "operator_input":
1120
+ return 0;
1121
+ case "turn_cluster":
1122
+ return 1;
1123
+ case "leaf_outcome":
1124
+ return 2;
1125
+ default:
1126
+ return 3;
1127
+ }
1128
+ }
1129
+
1130
+ function compareChronicleItems(left: ChronicleTimelineItem, right: ChronicleTimelineItem): number {
1131
+ if (!("chronologyAt" in left) || !("chronologyAt" in right)) {
1132
+ return 0;
1133
+ }
1134
+ const timestampComparison = left.chronologyAt.localeCompare(right.chronologyAt);
1135
+ if (timestampComparison !== 0) {
1136
+ return timestampComparison;
1137
+ }
1138
+ return chronicleItemOrder(left) - chronicleItemOrder(right);
1139
+ }
1140
+
1141
+ function findReasoningSection(
1142
+ sections: readonly ChronicleTurnClusterSection[],
1143
+ ): ChronicleThinkingSection | null {
1144
+ for (const section of sections) {
1145
+ if (section.kind === "thinking_preview") {
1146
+ return section;
1147
+ }
1148
+ }
1149
+ return null;
1150
+ }
1151
+
1152
+ export function extractChronicleReasoningDetailEntries(
1153
+ projection: ChronicleProjection,
1154
+ ): ChronicleReasoningDetailEntry[] {
1155
+ const entries: ChronicleReasoningDetailEntry[] = [];
1156
+ for (const item of projection.timelineItems) {
1157
+ if (item.kind === "turn_cluster") {
1158
+ const reasoningSection = findReasoningSection(item.sections);
1159
+ if (!reasoningSection) {
1160
+ continue;
1161
+ }
1162
+ entries.push({
1163
+ entryId: item.turnRecordId,
1164
+ turnRecordId: item.turnRecordId,
1165
+ turnId: item.turnId,
1166
+ title: item.title,
1167
+ turnLabel: item.turnLabel,
1168
+ stateLabel: null,
1169
+ isLive: false,
1170
+ modelProfileId: item.modelProfileId,
1171
+ usage: item.usage,
1172
+ triggeringInput: item.triggeringInput,
1173
+ piInput: item.piInput,
1174
+ facts: item.facts,
1175
+ reasoningSection,
1176
+ });
1177
+ continue;
1178
+ }
1179
+ if (item.kind !== "live_tail" || !item.reasoningSection) {
1180
+ continue;
1181
+ }
1182
+ entries.push({
1183
+ entryId: item.turnRecordId,
1184
+ turnRecordId: item.turnRecordId,
1185
+ turnId: item.turnId,
1186
+ title: item.title,
1187
+ turnLabel: item.turnLabel,
1188
+ stateLabel: item.stateLabel,
1189
+ isLive: true,
1190
+ modelProfileId: item.modelProfileId,
1191
+ usage: item.usage,
1192
+ triggeringInput: item.triggeringInput,
1193
+ piInput: item.piInput,
1194
+ facts: item.facts,
1195
+ reasoningSection: item.reasoningSection,
1196
+ });
1197
+ }
1198
+ return entries;
1199
+ }
1200
+
1201
+ export function buildChronicleProjection(
1202
+ input: BuildChronicleProjectionInput,
1203
+ ): ChronicleProjection {
1204
+ const isTerminal = input.lifecycleStatus === "completed" || input.lifecycleStatus === "aborted";
1205
+ const resolvedTerminalStatus: ProcessTerminalStatus | null = isTerminal
1206
+ ? (input.lifecycleStatus as ProcessTerminalStatus)
1207
+ : null;
1208
+ const displayPromptText = trimToNull(input.initialUserInputText) ?? trimToNull(input.promptText);
1209
+ const promptItem = displayPromptText
1210
+ ? buildPromptItem(displayPromptText, input.promptCreatedAt)
1211
+ : null;
1212
+ const triggeringInputIndex = buildTriggeringInputIndex(input);
1213
+ const durableTurnRecordById = new Map(
1214
+ input.turnRecords.map((turnRecord) => [turnRecord.id, turnRecord]),
1215
+ );
1216
+ const completedTurnRecords = input.turnRecords.filter(
1217
+ (turnRecord) => turnRecord.status === "completed",
1218
+ );
1219
+ const lastCompletedId = completedTurnRecords.at(-1)?.id ?? null;
1220
+ const completedTurnClusters = completedTurnRecords.map((turnRecord) => {
1221
+ const isLast = turnRecord.id === lastCompletedId;
1222
+ const triggeringInput = triggeringInputIndex.get(turnRecord.id) ?? null;
1223
+ return buildTurnClusterItem({
1224
+ turnRecord,
1225
+ turnTrace: input.turnTraceIndex[turnRecord.id],
1226
+ turnTracePreview: input.turnTracePreviewIndex?.[turnRecord.id],
1227
+ terminalStatus: isLast ? resolvedTerminalStatus : null,
1228
+ hasRenderableLeafOutcome: hasRenderableLeafOutcomeForTurn(
1229
+ turnRecord.id,
1230
+ input.leafOutcomeSnapshots,
1231
+ ),
1232
+ triggeringInput,
1233
+ facts: buildTurnFacts({
1234
+ turnId: turnRecord.turnId,
1235
+ durableTurnRecord: durableTurnRecordById.get(turnRecord.id),
1236
+ triggeringInput,
1237
+ actionSource: turnRecord.actionSource,
1238
+ runDetails: input.runDetails,
1239
+ }),
1240
+ initialUserInputText: input.initialUserInputText,
1241
+ });
1242
+ });
1243
+ const operatorInputs = input.inputs
1244
+ .filter(isStandaloneChronicleOperatorInput)
1245
+ .map<ChronicleOperatorInputItem>((processInput) => ({
1246
+ kind: "operator_input",
1247
+ chronologyAt: processInput.receivedAt,
1248
+ inputId: processInput.id,
1249
+ source: processInput.source,
1250
+ sourceLabel: sourceLabel(processInput.source),
1251
+ bodyMarkdown: processInput.bodyMarkdown,
1252
+ receivedAt: processInput.receivedAt,
1253
+ }));
1254
+ const turnTitlesByTurnRecordId = new Map(
1255
+ input.turnRecords.map((turnRecord) => [
1256
+ turnRecord.id,
1257
+ formatChronicleTurnLabel(turnRecord.displayTurn),
1258
+ ]),
1259
+ );
1260
+ const leafOutcomeItems = buildLeafOutcomeItems(
1261
+ input.leafOutcomeSnapshots,
1262
+ turnTitlesByTurnRecordId,
1263
+ {
1264
+ lifecycleStatus: input.lifecycleStatus ?? null,
1265
+ selectedTurnId: input.selectedTurnId ?? null,
1266
+ updatedAt: input.processUpdatedAt ?? null,
1267
+ },
1268
+ );
1269
+ const activeTurnRecord =
1270
+ input.turnRecords.find((turnRecord) => turnRecord.status === "in_progress") ?? null;
1271
+ const liveTailTriggeringInput =
1272
+ (activeTurnRecord && triggeringInputIndex.get(activeTurnRecord.id)) ?? null;
1273
+ const liveTail = buildLiveTail({
1274
+ turnRecord: activeTurnRecord,
1275
+ activeTurn: input.activeTurn,
1276
+ turnTrace: activeTurnRecord ? input.turnTraceIndex[activeTurnRecord.id] : undefined,
1277
+ turnTracePreview: activeTurnRecord
1278
+ ? input.turnTracePreviewIndex?.[activeTurnRecord.id]
1279
+ : undefined,
1280
+ triggeringInput: liveTailTriggeringInput,
1281
+ facts: activeTurnRecord
1282
+ ? buildTurnFacts({
1283
+ turnId: activeTurnRecord.turnId,
1284
+ durableTurnRecord: durableTurnRecordById.get(activeTurnRecord.id),
1285
+ activeTurn: input.activeTurn ?? null,
1286
+ triggeringInput: liveTailTriggeringInput,
1287
+ actionSource: activeTurnRecord.actionSource,
1288
+ runDetails: input.runDetails,
1289
+ })
1290
+ : null,
1291
+ runDetails: input.runDetails,
1292
+ initialUserInputText: input.initialUserInputText,
1293
+ });
1294
+ const terminalRailItem = buildTerminalRailItem(resolvedTerminalStatus);
1295
+ const timelineItems = [
1296
+ ...(promptItem ? [promptItem] : []),
1297
+ ...completedTurnClusters,
1298
+ ...operatorInputs,
1299
+ ...leafOutcomeItems,
1300
+ ].sort(compareChronicleItems);
1301
+
1302
+ if (liveTail) {
1303
+ timelineItems.push(liveTail);
1304
+ } else if (
1305
+ input.definesLeafOutcome &&
1306
+ completedTurnClusters.length > 0 &&
1307
+ leafOutcomeItems.length === 0
1308
+ ) {
1309
+ timelineItems.push({
1310
+ kind: "leaf_outcome_placeholder",
1311
+ latestTurnTitle: completedTurnClusters.at(-1)?.title ?? null,
1312
+ });
1313
+ }
1314
+
1315
+ const latestAnchorableTimelineItem = [...timelineItems]
1316
+ .reverse()
1317
+ .find(
1318
+ (item): item is Extract<ChronicleTimelineItem, { anchorId: string }> => "anchorId" in item,
1319
+ );
1320
+ const latestFocusedTurnId = [...timelineItems].reverse().find((item) => {
1321
+ return (
1322
+ ((item.kind === "turn_cluster" || item.kind === "live_tail") &&
1323
+ typeof item.turnRecordId === "string") ||
1324
+ item.kind === "leaf_outcome"
1325
+ );
1326
+ });
1327
+
1328
+ return {
1329
+ promptItem,
1330
+ turnRailItems: buildTurnRailItems(input.turnRecords, liveTail),
1331
+ terminalRailItem,
1332
+ timelineItems,
1333
+ initialAnchorId: terminalRailItem?.anchorId ?? latestAnchorableTimelineItem?.anchorId ?? null,
1334
+ initialFocusedTurnId:
1335
+ activeTurnRecord?.id ??
1336
+ (latestFocusedTurnId && "turnRecordId" in latestFocusedTurnId
1337
+ ? latestFocusedTurnId.turnRecordId
1338
+ : (input.turnRecords.at(-1)?.id ?? null)),
1339
+ liveTail,
1340
+ latestCompletedTurnTitle: completedTurnClusters.at(-1)?.title ?? null,
1341
+ };
1342
+ }