@zyro-sec/session-ui 0.0.0-stage → 1.0.4

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 (261) hide show
  1. package/AGENTS.md +25 -0
  2. package/bunfig.toml +2 -0
  3. package/component-tests/basic-tool.fixture.tsx +46 -0
  4. package/component-tests/basic-tool.spec.ts +63 -0
  5. package/component-tests/file-media.fixture.tsx +39 -0
  6. package/component-tests/file-media.spec.ts +13 -0
  7. package/component-tests/file-tool.spec.ts +62 -0
  8. package/component-tests/file-viewer.fixture.tsx +109 -0
  9. package/component-tests/file-viewer.spec.ts +134 -0
  10. package/component-tests/file.spec.ts +33 -0
  11. package/component-tests/line-comment-v2.spec.ts +15 -0
  12. package/component-tests/markdown-code-wrap.spec.ts +94 -0
  13. package/component-tests/markdown-readiness.spec.ts +95 -0
  14. package/component-tests/markdown.fixture.tsx +104 -0
  15. package/component-tests/markdown.spec.ts +1564 -0
  16. package/component-tests/mermaid-preview.spec.ts +43 -0
  17. package/component-tests/patch-group.spec.ts +79 -0
  18. package/component-tests/read-group.spec.ts +72 -0
  19. package/component-tests/read-image.fixture.tsx +66 -0
  20. package/component-tests/read-image.spec.ts +154 -0
  21. package/component-tests/session-compaction.spec.ts +254 -0
  22. package/component-tests/session-lifecycle.spec.ts +190 -0
  23. package/component-tests/session-message-projection.spec.ts +639 -0
  24. package/component-tests/session-notice-projection.spec.ts +20 -0
  25. package/component-tests/session-review-comments.spec.ts +179 -0
  26. package/component-tests/session-shell.spec.ts +93 -0
  27. package/component-tests/session-timeline-mobile.spec.ts +201 -0
  28. package/component-tests/session-timeline-notices.spec.ts +38 -0
  29. package/component-tests/session-timeline-reasoning.spec.ts +107 -0
  30. package/component-tests/session-timeline.spec.ts +157 -0
  31. package/component-tests/session-tool-projection.spec.ts +323 -0
  32. package/component-tests/text-lifecycle.fixture.tsx +26 -0
  33. package/component-tests/text-lifecycle.spec.ts +42 -0
  34. package/component-tests/timeline-subagent-rows.spec.ts +33 -0
  35. package/component-tests/tool-disclosure.spec.ts +48 -0
  36. package/component-tests/tool-group-sticky.spec.ts +37 -0
  37. package/component-tests/tool-group.spec.ts +290 -0
  38. package/component-tests/tool-status-title.fixture.tsx +22 -0
  39. package/component-tests/tool-status-title.spec.ts +30 -0
  40. package/component-tests/user-message-quotes.spec.ts +111 -0
  41. package/package.json +91 -4
  42. package/playwright.components.config.ts +4 -0
  43. package/playwright.local.config.ts +2 -0
  44. package/src/actions.ts +54 -0
  45. package/src/components/apply-patch-file.ts +122 -0
  46. package/src/components/basic-tool.css +487 -0
  47. package/src/components/basic-tool.tsx +258 -0
  48. package/src/components/copy-machine.ts +78 -0
  49. package/src/components/copy.ts +85 -0
  50. package/src/components/diagram-preview.tsx +28 -0
  51. package/src/components/disclosure-machine.ts +188 -0
  52. package/src/components/disclosure.ts +129 -0
  53. package/src/components/dock-prompt.stories.tsx +73 -0
  54. package/src/components/dock-prompt.tsx +29 -0
  55. package/src/components/file-comment-selection.tsx +146 -0
  56. package/src/components/file-media-machine.ts +165 -0
  57. package/src/components/file-media.stories.tsx +112 -0
  58. package/src/components/file-media.tsx +323 -0
  59. package/src/components/file-search.tsx +73 -0
  60. package/src/components/file.css +59 -0
  61. package/src/components/file.tsx +1300 -0
  62. package/src/components/image-preview.tsx +35 -0
  63. package/src/components/line-comment-annotations.tsx +580 -0
  64. package/src/components/line-comment-machine.ts +262 -0
  65. package/src/components/line-comment-styles.ts +293 -0
  66. package/src/components/line-comment.stories.tsx +152 -0
  67. package/src/components/line-comment.tsx +448 -0
  68. package/src/components/link-segments.ts +20 -0
  69. package/src/components/linked-text.tsx +21 -0
  70. package/src/components/markdown-cache-machine.ts +257 -0
  71. package/src/components/markdown-cache.tsx +556 -0
  72. package/src/components/markdown-clipboard.ts +101 -0
  73. package/src/components/markdown-code-machine.ts +200 -0
  74. package/src/components/markdown-code-state.ts +22 -0
  75. package/src/components/markdown-fragment-links.ts +74 -0
  76. package/src/components/markdown-github.svg +3 -0
  77. package/src/components/markdown-globe.svg +5 -0
  78. package/src/components/markdown-image-machine.ts +170 -0
  79. package/src/components/markdown-image.ts +156 -0
  80. package/src/components/markdown-inline-code-kind.ts +39 -0
  81. package/src/components/markdown-mermaid.ts +18 -0
  82. package/src/components/markdown-phase-machine.ts +102 -0
  83. package/src/components/markdown-projection.ts +13 -0
  84. package/src/components/markdown-session-links.ts +183 -0
  85. package/src/components/markdown-solid.test.tsx +92 -0
  86. package/src/components/markdown-solid.tsx +113 -0
  87. package/src/components/markdown-stream.ts +95 -0
  88. package/src/components/markdown-worker-machine.ts +516 -0
  89. package/src/components/markdown-worker-protocol.ts +73 -0
  90. package/src/components/markdown-worker.ts +250 -0
  91. package/src/components/markdown.css +672 -0
  92. package/src/components/markdown.stories.tsx +199 -0
  93. package/src/components/markdown.tsx +1612 -0
  94. package/src/components/markdown.worker.ts +188 -0
  95. package/src/components/message-file.ts +102 -0
  96. package/src/components/message-nav.css +134 -0
  97. package/src/components/message-nav.tsx +159 -0
  98. package/src/components/message-part.css +2109 -0
  99. package/src/components/message-part.tsx +3 -0
  100. package/src/components/question-prompt-experimental.css +576 -0
  101. package/src/components/question-prompt.css +527 -0
  102. package/src/components/quote-highlight.css +59 -0
  103. package/src/components/review-focus-driver.ts +142 -0
  104. package/src/components/review-focus-machine.ts +95 -0
  105. package/src/components/session-compaction.css +270 -0
  106. package/src/components/session-diff.ts +358 -0
  107. package/src/components/session-error.tsx +41 -0
  108. package/src/components/session-retry.tsx +92 -0
  109. package/src/components/session-review-machine.ts +241 -0
  110. package/src/components/session-review.css +264 -0
  111. package/src/components/session-review.stories.tsx +232 -0
  112. package/src/components/session-review.tsx +733 -0
  113. package/src/components/session-turn.css +282 -0
  114. package/src/components/shell-submessage.css +24 -0
  115. package/src/components/timeline-separator.tsx +69 -0
  116. package/src/components/tool-count-label.css +57 -0
  117. package/src/components/tool-count-label.tsx +76 -0
  118. package/src/components/tool-count-summary.css +102 -0
  119. package/src/components/tool-count-summary.stories.tsx +99 -0
  120. package/src/components/tool-count-summary.tsx +44 -0
  121. package/src/components/tool-error-card.css +178 -0
  122. package/src/components/tool-error-card.stories.tsx +113 -0
  123. package/src/components/tool-error-card.tsx +202 -0
  124. package/src/components/tool-status-title-machine.ts +128 -0
  125. package/src/components/tool-status-title.css +89 -0
  126. package/src/components/tool-status-title.tsx +163 -0
  127. package/src/context/data.tsx +107 -0
  128. package/src/context/index.ts +1 -0
  129. package/src/context/markdown.tsx +129 -0
  130. package/src/context/sources.tsx +34 -0
  131. package/src/document.ts +8 -0
  132. package/src/file-presentation.ts +34 -0
  133. package/src/message/action-machine.ts +72 -0
  134. package/src/message/agent-label.ts +3 -0
  135. package/src/message/attachment-card.css +119 -0
  136. package/src/message/attachment-card.tsx +40 -0
  137. package/src/message/attachment-media-machine.ts +213 -0
  138. package/src/message/comment-card.tsx +155 -0
  139. package/src/message/compaction-entrance-machine.ts +93 -0
  140. package/src/message/current-message.tsx +157 -0
  141. package/src/message/current-tool-state.ts +161 -0
  142. package/src/message/message-content.tsx +1391 -0
  143. package/src/message/paced-text-machine.ts +73 -0
  144. package/src/message/prompt-message.stories.tsx +149 -0
  145. package/src/message/relative-time.ts +45 -0
  146. package/src/message/user-message-quote-parts.ts +16 -0
  147. package/src/message/user-message-quotes.stories.tsx +797 -0
  148. package/src/message/user-message-quotes.tsx +135 -0
  149. package/src/pierre/comment-hover-machine.ts +53 -0
  150. package/src/pierre/comment-hover.ts +131 -0
  151. package/src/pierre/comment-selection-machine.ts +257 -0
  152. package/src/pierre/commented-lines.ts +106 -0
  153. package/src/pierre/diff-selection.ts +91 -0
  154. package/src/pierre/file-find-machine.ts +323 -0
  155. package/src/pierre/file-find.ts +537 -0
  156. package/src/pierre/file-runtime.ts +42 -0
  157. package/src/pierre/file-selection.ts +140 -0
  158. package/src/pierre/index.ts +344 -0
  159. package/src/pierre/media.ts +140 -0
  160. package/src/pierre/render-machine.ts +381 -0
  161. package/src/pierre/selection-bridge.ts +82 -0
  162. package/src/pierre/selection-machine.ts +198 -0
  163. package/src/pierre/virtualizer.ts +114 -0
  164. package/src/pierre/worker.ts +46 -0
  165. package/src/sources/experiment.ts +59 -0
  166. package/src/sources/site-icon.tsx +53 -0
  167. package/src/sources/sources-chip.tsx +57 -0
  168. package/src/sources/sources-expand-machine.ts +101 -0
  169. package/src/sources/sources-panel.tsx +249 -0
  170. package/src/sources/sources-title.tsx +21 -0
  171. package/src/sources/sources.css +266 -0
  172. package/src/sources/sources.ts +141 -0
  173. package/src/storybook/current-session-fixtures.ts +1492 -0
  174. package/src/storybook/current-session-scenarios.ts +76 -0
  175. package/src/storybook/current-session-story.tsx +154 -0
  176. package/src/storybook/index.ts +43 -0
  177. package/src/styles/index.css +19 -0
  178. package/src/timeline/__snapshots__/group-labels.test.ts.snap +110 -0
  179. package/src/timeline/__snapshots__/placement.test.ts.snap +1041 -0
  180. package/src/timeline/code-blocks.stories.tsx +105 -0
  181. package/src/timeline/commentary.stories.tsx +70 -0
  182. package/src/timeline/commentary.ts +38 -0
  183. package/src/timeline/detail.ts +111 -0
  184. package/src/timeline/error-card.stories.tsx +134 -0
  185. package/src/timeline/error-spacing.stories.tsx +71 -0
  186. package/src/timeline/facts.ts +493 -0
  187. package/src/timeline/file-changes.stories.tsx +436 -0
  188. package/src/timeline/group-label-fixtures.ts +97 -0
  189. package/src/timeline/mermaid.stories.tsx +131 -0
  190. package/src/timeline/place.ts +280 -0
  191. package/src/timeline/placement-fixtures.ts +365 -0
  192. package/src/timeline/placement-reactivity.ts +133 -0
  193. package/src/timeline/projection.ts +1261 -0
  194. package/src/timeline/research-and-agents.stories.tsx +461 -0
  195. package/src/timeline/session-timeline-row.tsx +1675 -0
  196. package/src/timeline/session-timeline.tsx +68 -0
  197. package/src/timeline/steer-arrival-machine.ts +134 -0
  198. package/src/timeline/terminal-work.stories.tsx +464 -0
  199. package/src/timeline/timeline-row.stories.tsx +1069 -0
  200. package/src/timeline/timeline-row.ts +238 -0
  201. package/src/timeline/turn-phase-machine.ts +112 -0
  202. package/src/timeline/user-message-fold.stories.tsx +194 -0
  203. package/src/timeline/user-runs.ts +87 -0
  204. package/src/timeline-next/__snapshots__/placement.test.ts.snap +990 -0
  205. package/src/timeline-next/compaction.tsx +236 -0
  206. package/src/timeline-next/errors.ts +101 -0
  207. package/src/timeline-next/event-row.tsx +168 -0
  208. package/src/timeline-next/events.ts +103 -0
  209. package/src/timeline-next/index.ts +10 -0
  210. package/src/timeline-next/nested-rail.ts +125 -0
  211. package/src/timeline-next/projection.ts +1028 -0
  212. package/src/timeline-next/row.tsx +1728 -0
  213. package/src/timeline-next/rules.ts +89 -0
  214. package/src/timeline-next/separator.tsx +73 -0
  215. package/src/timeline-next/spacing.ts +127 -0
  216. package/src/timeline-next/status-line.tsx +41 -0
  217. package/src/timeline-next/status.ts +33 -0
  218. package/src/timeline-next/stories/compare-renderer.stories.tsx +190 -0
  219. package/src/timeline-next/stories/compare-sessions/.gitignore +3 -0
  220. package/src/timeline-next/stories/compare.stories.tsx +486 -0
  221. package/src/timeline-next/stories/playground.stories.tsx +297 -0
  222. package/src/timeline-next/stories/session-replay.ts +1156 -0
  223. package/src/timeline-next/stories/session-timeline.tsx +50 -0
  224. package/src/timeline-next/stories/subagent-status.stories.tsx +132 -0
  225. package/src/timeline-next/timeline-next.css +649 -0
  226. package/src/timeline-next/tools/__snapshots__/activity-label.test.ts.snap +39 -0
  227. package/src/timeline-next/tools/activity-label.ts +166 -0
  228. package/src/timeline-next/tools/assistant-content.tsx +84 -0
  229. package/src/timeline-next/tools/context-group.tsx +619 -0
  230. package/src/timeline-next/tools/error-card.tsx +147 -0
  231. package/src/timeline-next/tools/explore.tsx +119 -0
  232. package/src/timeline-next/tools/file-group.tsx +128 -0
  233. package/src/timeline-next/tools/patch.tsx +174 -0
  234. package/src/timeline-next/tools/shell.tsx +186 -0
  235. package/src/timeline-next/tools/thought.tsx +87 -0
  236. package/src/timeline-next/tools/tool-display.tsx +119 -0
  237. package/src/tools/ansi.ts +8 -0
  238. package/src/tools/context-group-label.ts +123 -0
  239. package/src/tools/file-runs.ts +35 -0
  240. package/src/tools/project-path.ts +18 -0
  241. package/src/tools/read-group.stories.tsx +159 -0
  242. package/src/tools/run-machine.ts +185 -0
  243. package/src/tools/shell-output-machine.ts +233 -0
  244. package/src/tools/shell-output.ts +91 -0
  245. package/src/tools/subagent-row-variants.stories.tsx +129 -0
  246. package/src/tools/tool-group.stories.tsx +345 -0
  247. package/src/tools/tool-renderer.tsx +2876 -0
  248. package/src/v2/components/line-comment-annotations-v2.tsx +215 -0
  249. package/src/v2/components/session-file-panel-v2.tsx +149 -0
  250. package/src/v2/components/session-progress-indicator-v2.css +5 -0
  251. package/src/v2/components/session-progress-indicator-v2.stories.tsx +86 -0
  252. package/src/v2/components/session-progress-indicator-v2.tsx +16 -0
  253. package/src/v2/components/session-review-empty-changes-v2.tsx +17 -0
  254. package/src/v2/components/session-review-empty-no-git-v2.tsx +28 -0
  255. package/src/v2/components/session-review-file-preview-v2-virtualize.ts +5 -0
  256. package/src/v2/components/session-review-file-preview-v2.tsx +266 -0
  257. package/src/v2/components/session-review-v2.css +653 -0
  258. package/src/v2/components/session-review-v2.tsx +422 -0
  259. package/src/v2/components/sidebar-presence-machine.ts +69 -0
  260. package/tsconfig.json +20 -0
  261. package/README.md +0 -3
@@ -0,0 +1,1028 @@
1
+ import type {
2
+ ModelRef,
3
+ SessionMessageAssistant,
4
+ SessionMessageIdle,
5
+ SessionMessageInfo,
6
+ SessionMessageShell,
7
+ SessionMessageUser,
8
+ SessionStatus,
9
+ } from "@zyro-sec/client/promise"
10
+ import { Effect, Option, Predicate, Schema } from "effect"
11
+ import { createComputed, createMemo, createSignal, mapArray, untrack, type Accessor } from "solid-js"
12
+ import { turnCommentary } from "../timeline/commentary"
13
+ import { timelineNoticeRequired, type TimelineDetail } from "../timeline/detail"
14
+ import { TimelineRow, type PartGroup, type PartRef } from "../timeline/timeline-row"
15
+ import {
16
+ IDLE_TURN_PHASE,
17
+ isInterruptedError,
18
+ sameTurnPhase,
19
+ transitionTurnPhase,
20
+ viewTurnPhase,
21
+ type TurnPhase,
22
+ type TurnPhaseEvent,
23
+ type TurnThinkingPlacement,
24
+ } from "../timeline/turn-phase-machine"
25
+ import { errorInfo } from "./errors"
26
+ import { launchOf } from "../timeline/facts"
27
+ import {
28
+ hidesActivity,
29
+ placeNotice,
30
+ placer,
31
+ placeScriptChange,
32
+ scriptChangeItems,
33
+ type Place,
34
+ type PlaceFactOf,
35
+ } from "../timeline/place"
36
+ import { placeFacts } from "../timeline/projection"
37
+ import { noticeEvent, workKey, type TimelineEvent } from "./events"
38
+ import { echoesUserShell, liveThinkingShows, movedInPlace, textShows } from "./rules"
39
+
40
+ type Notice = Exclude<SessionMessageInfo, { type: "user" | "assistant" | "shell" | "idle" }>
41
+
42
+ type FailedIdle = SessionMessageIdle & {
43
+ outcome: "failed"
44
+ error: NonNullable<SessionMessageIdle["error"]>
45
+ }
46
+
47
+ type Entry =
48
+ | { type: "assistant"; message: SessionMessageAssistant; run: number }
49
+ | { type: "notice"; message: Notice }
50
+ | { type: "idle"; message: FailedIdle }
51
+ | { type: "diff"; message: SessionMessageIdle; from: string; files: string[] }
52
+
53
+ type Turn = {
54
+ id: string
55
+ time: { created: number }
56
+ user?: SessionMessageUser
57
+ shell?: SessionMessageShell
58
+ entries: Entry[]
59
+ }
60
+
61
+ type Content = SessionMessageAssistant["content"][number]
62
+
63
+ type GroupRow = Extract<TimelineRow.TimelineRow, { _tag: "AssistantPart" }>
64
+
65
+ type PriorGroup = { index: number; row: GroupRow }
66
+
67
+ /** Everything the projection reads to build the New timeline's rows. */
68
+ type Input = {
69
+ messages: SessionMessageInfo[]
70
+ status: SessionStatus
71
+ detail: TimelineDetail
72
+ pendingInputIDs?: ReadonlySet<string>
73
+ queuedCompactionIDs: readonly string[]
74
+ turnDiffs: boolean
75
+ /** Whether a part shows. Text and thoughts are read through signals, so a streamed delta does not rebuild the rows. */
76
+ shows: (content: Content) => boolean
77
+ /** Where a part shows, each call placed once per build. */
78
+ place: (content: Content, commentary?: boolean) => Place
79
+ /** What placing a call reads, through a signal per call. */
80
+ factOf?: PlaceFactOf
81
+ }
82
+
83
+ // A field of the wrong type decodes as absent, so one bad field does not discard its neighbours.
84
+ function lenient<S extends Schema.Top>(schema: S) {
85
+ return Schema.optionalKey(schema.pipe(Schema.catchDecoding(() => Effect.succeedNone)))
86
+ }
87
+
88
+ const decodeLocalAgent = Schema.decodeUnknownOption(Schema.Struct({ agent: Schema.String }))
89
+
90
+ const decodeLocalModel = Schema.decodeUnknownOption(
91
+ Schema.Struct({
92
+ model: Schema.Struct({
93
+ id: lenient(Schema.String),
94
+ modelID: lenient(Schema.String),
95
+ providerID: Schema.String,
96
+ variant: lenient(Schema.String),
97
+ }),
98
+ }),
99
+ )
100
+
101
+ /**
102
+ * The New timeline's rows. It returns the same shape as the current timeline's projection, so the app scrolls, searches
103
+ * and reveals either the same way.
104
+ */
105
+ export function createNextTimelineProjection(input: {
106
+ sessionMessages: Accessor<SessionMessageInfo[]>
107
+ status: Accessor<SessionStatus>
108
+ timelineDetail: Accessor<TimelineDetail>
109
+ pendingInputIDs?: Accessor<ReadonlySet<string>>
110
+ queuedCompactionIDs?: Accessor<readonly string[]>
111
+ /** Summarize each finished turn's changed files after it. */
112
+ turnDiffs?: Accessor<boolean>
113
+ }) {
114
+ const sessionMessageByID = createMemo(
115
+ () => new Map(input.sessionMessages().map((message) => [message.id, message] as const)),
116
+ )
117
+
118
+ const userContextByID = createMemo(() => indexUserContext(input.sessionMessages()))
119
+ const assistantMessagesByParent = createMemo(() => indexAssistantMessages(input.sessionMessages()))
120
+
121
+ // Row structure depends on the empty/non-empty boundary, not each text delta.
122
+ // Keep the original content objects so row renderers still read live text.
123
+ const textParts = mapArray(
124
+ () =>
125
+ input
126
+ .sessionMessages()
127
+ .flatMap((message) =>
128
+ message.type === "assistant" ? message.content.filter((content) => content.type !== "tool") : [],
129
+ ),
130
+ (content) => {
131
+ // A memo here went stale on every streamed delta, which marked the projection below pending; Solid then
132
+ // re-checked each of its thousands of sources to find nothing changed. A signal set from a computation
133
+ // notifies only when visibility actually flips.
134
+ const [visible, setVisible] = createSignal(false)
135
+ createComputed(() => setVisible(textShows(content)))
136
+
137
+ // The signal only says when visibility flips, one computation after the write that flipped it. Rows built from
138
+ // its value in between list a part that no longer shows, so the value comes from the part itself.
139
+ return [content, () => (visible(), untrack(() => textShows(content)))] as const
140
+ },
141
+ )
142
+
143
+ const textVisible = createMemo(() => new Map<Content, Accessor<boolean>>(textParts()))
144
+ const factOf = placeFacts(input.sessionMessages)
145
+
146
+ const projection = createMemo(() => {
147
+ const detail = input.timelineDetail()
148
+ const place = placer(detail, "next", factOf)
149
+
150
+ return constructRows({
151
+ messages: input.sessionMessages(),
152
+ status: input.status(),
153
+ detail,
154
+ pendingInputIDs: input.pendingInputIDs?.(),
155
+ queuedCompactionIDs: input.queuedCompactionIDs?.() ?? [],
156
+ turnDiffs: input.turnDiffs?.() ?? false,
157
+ place,
158
+ factOf,
159
+ shows: (content) =>
160
+ content.type === "tool"
161
+ ? place(content).placement !== "hidden"
162
+ : (content.type === "text" || detail.thinking.placement !== "hidden") && textVisible().get(content)!(),
163
+ })
164
+ })
165
+
166
+ const activeMessageID = createMemo(() => projection().activeMessageID)
167
+
168
+ // Rows read their turn's phase, so a recomputed projection that leaves every phase as it was notifies none of them.
169
+ const turnPhaseByID = createMemo(() => projection().turnPhaseByID, undefined, {
170
+ equals: (previous, next) =>
171
+ previous.size === next.size &&
172
+ [...next].every(([id, phase]) => {
173
+ const prior = previous.get(id)
174
+
175
+ return !!prior && sameTurnPhase(prior, phase)
176
+ }),
177
+ })
178
+
179
+ const rows = createMemo((previous: TimelineRow.TimelineRow[] | undefined) =>
180
+ reuseTimelineRows(previous, projection().rows),
181
+ )
182
+
183
+ const rowByKey = createMemo(() => new Map(rows().map((row) => [TimelineRow.key(row), row] as const)))
184
+
185
+ const messageRowIndex = createMemo(() => {
186
+ const result = new Map<string, number>()
187
+ rows().forEach((row, index) => {
188
+ if (result.has(row.userMessageID)) return
189
+ result.set(row.userMessageID, index)
190
+ })
191
+
192
+ return result
193
+ })
194
+
195
+ const messageLastRowIndex = createMemo(() => {
196
+ const result = new Map<string, number>()
197
+ rows().forEach((row, index) => result.set(row.userMessageID, index))
198
+
199
+ return result
200
+ })
201
+
202
+ const lastAssistantGroupKey = createMemo(() => {
203
+ const result = new Map<string, string>()
204
+ rows().forEach((row) => {
205
+ if (Predicate.isTagged(row, "AssistantPart")) result.set(row.userMessageID, row.group.key)
206
+ })
207
+
208
+ return result
209
+ })
210
+
211
+ return {
212
+ activeMessageID,
213
+ turnPhaseByID,
214
+ assistantMessagesByParent,
215
+ lastAssistantGroupKey,
216
+ messageByID: sessionMessageByID,
217
+ messageRowIndex,
218
+ messageLastRowIndex,
219
+ rowByKey,
220
+ rows,
221
+ sessionMessageByID,
222
+ userContextByID,
223
+ }
224
+ }
225
+
226
+ /**
227
+ * How long a turn the user stopped worked: from its start, the user's message or else the agent's first step, to the end
228
+ * of the step the user stopped. A stopped step may not record its end, so its parts' latest time stands in.
229
+ */
230
+ export function workedDuration(user: SessionMessageUser | undefined, steps: readonly SessionMessageAssistant[]) {
231
+ const start = user?.time.created ?? steps[0]?.time.created
232
+ const stopped = steps.find((step) => isInterruptedError(step.error))
233
+
234
+ if (start === undefined || !stopped) return undefined
235
+
236
+ const end =
237
+ stopped.time.completed ??
238
+ Math.max(
239
+ stopped.time.created,
240
+ ...stopped.content.flatMap((content) =>
241
+ content.type === "text" ? [] : [content.time?.completed ?? content.time?.created ?? stopped.time.created],
242
+ ),
243
+ )
244
+
245
+ return Math.max(0, end - start)
246
+ }
247
+
248
+ /** A part of an assistant message by its ID: a tool's own ID, or `<message>:<text|reasoning>:<n>`. */
249
+ export function resolveContent(message: SessionMessageInfo | undefined, partID: string): Content | undefined {
250
+ if (message?.type !== "assistant") return undefined
251
+
252
+ return contentEntries(message).find((entry) => entry.id === partID)?.content
253
+ }
254
+
255
+ export function contentEntries(message: SessionMessageAssistant) {
256
+ const ordinals = { text: 0, reasoning: 0 }
257
+
258
+ return message.content.map((content) => ({
259
+ id: content.type === "tool" ? content.id : `${message.id}:${content.type}:${ordinals[content.type]++}`,
260
+ content,
261
+ }))
262
+ }
263
+
264
+ function constructRows(input: Input) {
265
+ const { turns, leading, openRun } = constructTurns(input)
266
+
267
+ const activeMessageID =
268
+ turns.findLast(
269
+ (turn) => !input.pendingInputIDs?.has(turn.id) || turn.entries.some((entry) => entry.type === "idle"),
270
+ )?.id ?? turns.at(-1)?.id
271
+
272
+ // The thought the model is writing stands at the end of the turn in place of the status line, wherever thinking
273
+ // shows. Once finished, it settles where the setting puts thoughts.
274
+ const livePlacement = liveThinkingShows(input.detail) ? "separate" : "hidden"
275
+
276
+ const turnPhaseByID = new Map(
277
+ turns.map(
278
+ (turn) => [turn.id, turnPhase(turn.entries, turn.id === activeMessageID, input.status, livePlacement)] as const,
279
+ ),
280
+ )
281
+
282
+ const phaseOf = (turn: Turn) => turnPhaseByID.get(turn.id) ?? IDLE_TURN_PHASE
283
+
284
+ const commentary = new Set(
285
+ input.detail.commentary.placement !== "separate"
286
+ ? turns.flatMap((turn) =>
287
+ turnCommentary(
288
+ turn.entries.filter((entry) => entry.type === "assistant"),
289
+ openRun,
290
+ viewTurnPhase(phaseOf(turn)).settled,
291
+ input.shows,
292
+ ),
293
+ )
294
+ : [],
295
+ )
296
+
297
+ const visible = (content: Content) =>
298
+ !(commentary.has(content) && input.place(content, true).placement === "hidden") && input.shows(content)
299
+
300
+ const noticeShows = (message: Notice) => placeNotice(message, input.detail, "next") !== "hidden"
301
+
302
+ // Your messages and the commands you ran always show; any other turn shows when something in it does.
303
+ const visibleTurns = turns.filter(
304
+ (turn) =>
305
+ turn.user ||
306
+ turn.shell ||
307
+ turn.entries.some((entry) =>
308
+ entry.type === "notice"
309
+ ? noticeShows(entry.message)
310
+ : entry.type === "idle" ||
311
+ entry.type === "diff" ||
312
+ !!entry.message.error ||
313
+ !!entry.message.retry ||
314
+ entry.message.content.some(visible),
315
+ ),
316
+ )
317
+
318
+ const leadingRows = leading
319
+ .filter(noticeShows)
320
+ .map((message) => new TimelineRow.Notice({ userMessageID: turns[0]?.id ?? message.id, messageID: message.id }))
321
+
322
+ // A turn gap holds the gap above its turn. A turn the user started stays a turn when older history loads, so it has
323
+ // its gap unless it is the first row: after leading notices too, which then join the turn that loads above them.
324
+ const gapped = (turn: Turn, index: number) => index > 0 || (leadingRows.length > 0 && !!(turn.user || turn.shell))
325
+
326
+ const rows: TimelineRow.TimelineRow[] = [
327
+ ...leadingRows,
328
+ ...visibleTurns.flatMap((turn, index) => {
329
+ if (turn.shell)
330
+ return [
331
+ ...(gapped(turn, index) ? [new TimelineRow.TurnGap({ userMessageID: turn.id })] : []),
332
+ new TimelineRow.Shell({ userMessageID: turn.id, messageID: turn.shell.id }),
333
+ ...turn.entries.flatMap((entry) =>
334
+ entry.type === "notice" && noticeShows(entry.message)
335
+ ? [new TimelineRow.Notice({ userMessageID: turn.id, messageID: entry.message.id })]
336
+ : [],
337
+ ),
338
+ ]
339
+
340
+ return turnRows(
341
+ turn,
342
+ gapped(turn, index),
343
+ phaseOf(turn),
344
+ input.detail,
345
+ visible,
346
+ commentary,
347
+ input.place,
348
+ input.factOf,
349
+ )
350
+ }),
351
+ ]
352
+
353
+ // Like the TUI, a queued compaction waits after the active turn and ahead of every steer still waiting for delivery.
354
+ // Notices waiting for delivery are already in the active turn, since they report what happened.
355
+ const pendingAt = rows.findIndex((row) => input.pendingInputIDs?.has(row.userMessageID))
356
+
357
+ rows.splice(
358
+ pendingAt < 0 ? rows.length : pendingAt,
359
+ 0,
360
+ // Live status ends the turn, so it stays above the input the user steered in, which waits for the agent to reply.
361
+ ...(input.status.type !== "idle" && activeMessageID && (pendingAt >= 0 || input.queuedCompactionIDs.length > 0)
362
+ ? [new TimelineRow.Activity({ userMessageID: activeMessageID })]
363
+ : []),
364
+ ...input.queuedCompactionIDs.map(
365
+ (inboxID) => new TimelineRow.CompactionQueued({ userMessageID: activeMessageID ?? inboxID, inboxID }),
366
+ ),
367
+ )
368
+
369
+ const messageByID = new Map(input.messages.map((message) => [message.id, message]))
370
+
371
+ return { activeMessageID, turnPhaseByID, rows: groupNotices(rows, input.detail, messageByID) }
372
+ }
373
+
374
+ // Everything since the last idle marker is one turn, including prompts steered in meanwhile. Notices before the first
375
+ // turn have none to join, so they lead.
376
+ function constructTurns(input: Input) {
377
+ const userShellIDs = new Set(input.messages.flatMap((message) => (message.type === "shell" ? [message.shellID] : [])))
378
+ const turns: Turn[] = []
379
+ const leading: Notice[] = []
380
+ const turnByUserID = new Map<string, Turn>()
381
+ let current: Turn | undefined
382
+ let openRun = 0
383
+ let execution: { opener: string; turn: Turn; files: Set<string> } | undefined
384
+
385
+ const appendIdle = (message: SessionMessageIdle) => {
386
+ if (!isFailedIdle(message)) return
387
+ const last = current?.entries.at(-1)
388
+
389
+ if (
390
+ last?.type === "notice" &&
391
+ last.message.type === "compaction" &&
392
+ last.message.status === "failed" &&
393
+ !isInterruptedError(last.message.error)
394
+ )
395
+ return
396
+
397
+ const lastStep = current?.entries.findLast((entry) => entry.type === "assistant" || entry.type === "idle")
398
+
399
+ if (lastStep?.type === "assistant" && lastStep.message.error && !isInterruptedError(lastStep.message.error)) return
400
+
401
+ if (current && !current.shell) {
402
+ current.entries.push({ type: "idle", message })
403
+
404
+ return
405
+ }
406
+
407
+ const turn: Turn = { id: message.id, time: message.time, entries: [{ type: "idle", message }] }
408
+ turns.push(turn)
409
+ current = turn
410
+ }
411
+
412
+ input.messages.forEach((message) => {
413
+ if (echoesUserShell(message, userShellIDs) || movedInPlace(message)) return
414
+
415
+ if (isNotice(message)) {
416
+ // A notice still waiting for delivery, such as a subagent reporting back, already happened, so it joins the
417
+ // working turn above the status line, even when input the user steered in meanwhile waits below it.
418
+ const turn = input.pendingInputIDs?.has(message.id) ? (execution?.turn ?? current) : current
419
+
420
+ if (turn) turn.entries.push({ type: "notice", message })
421
+ else leading.push(message)
422
+
423
+ return
424
+ }
425
+
426
+ if (message.type === "shell") {
427
+ const turn: Turn = { id: message.id, time: message.time, shell: message, entries: [] }
428
+ turns.push(turn)
429
+ current = turn
430
+
431
+ return
432
+ }
433
+
434
+ if (message.type === "user") {
435
+ if (turnByUserID.has(message.id)) return
436
+ const turn: Turn = { id: message.id, time: message.time, user: message, entries: [] }
437
+ turns.push(turn)
438
+ turnByUserID.set(message.id, turn)
439
+ current = turn
440
+
441
+ // Undelivered input has not joined the turn yet.
442
+ if (!input.pendingInputIDs?.has(message.id))
443
+ execution = { opener: execution?.opener ?? message.id, turn, files: execution?.files ?? new Set() }
444
+
445
+ return
446
+ }
447
+
448
+ if (message.type === "idle") {
449
+ appendIdle(message)
450
+ openRun++
451
+
452
+ // The summary follows the turn's last prompt, after any failure the marker reports.
453
+ // Sorted like the diff route's git order, so the list keeps its order when the diffs arrive.
454
+ if (input.turnDiffs && execution?.files.size)
455
+ execution.turn.entries.push({
456
+ type: "diff",
457
+ message,
458
+ from: execution.opener,
459
+ files: [...execution.files].sort(),
460
+ })
461
+ execution = undefined
462
+
463
+ return
464
+ }
465
+
466
+ if (message.type !== "assistant") return
467
+ message.snapshot?.files?.forEach((file) => execution?.files.add(file))
468
+
469
+ if (current && !current.shell) {
470
+ current.entries.push({ type: "assistant", message, run: openRun })
471
+
472
+ return
473
+ }
474
+
475
+ const turn: Turn = { id: message.id, time: message.time, entries: [{ type: "assistant", message, run: openRun }] }
476
+ turns.push(turn)
477
+ current = turn
478
+ })
479
+
480
+ return { turns, leading, openRun }
481
+ }
482
+
483
+ function turnRows(
484
+ turn: Turn,
485
+ previousTurn: boolean,
486
+ phase: TurnPhase,
487
+ detail: TimelineDetail,
488
+ isVisible: (content: Content) => boolean,
489
+ commentary: ReadonlySet<Content>,
490
+ place: Input["place"],
491
+ factOf?: PlaceFactOf,
492
+ ) {
493
+ const rows: TimelineRow.TimelineRow[] = []
494
+ const assistantMessages = turn.entries.flatMap((entry) => (entry.type === "assistant" ? [entry.message] : []))
495
+ const lastAssistant = assistantMessages.at(-1)
496
+ const lastStep = turn.entries.findLast((entry) => entry.type === "assistant" || entry.type === "idle")
497
+ const view = viewTurnPhase(phase)
498
+ const thinking = view.separateThinkingRef
499
+ const lastAssistantEntry = turn.entries.findLastIndex((entry) => entry.type === "assistant")
500
+
501
+ const quietTail = turn.entries
502
+ .slice(lastAssistantEntry + 1)
503
+ .every((entry) => entry.type === "notice" && placeNotice(entry.message, detail, "next") === "hidden")
504
+
505
+ if (previousTurn) rows.push(new TimelineRow.TurnGap({ userMessageID: turn.id }))
506
+
507
+ if (turn.user) rows.push(new TimelineRow.UserMessage({ userMessageID: turn.id }))
508
+
509
+ let assistantGroupIndex = 0
510
+ let previousAssistantTool = false
511
+
512
+ // An assistant message can produce several rows because its content parts are rendered separately. Notices end a
513
+ // segment so none of those rows cross it.
514
+ const appendAssistantSegment = (messages: SessionMessageAssistant[]) => {
515
+ const visibleRefs = messages.flatMap((message, messageIndex) =>
516
+ contentEntries(message).flatMap((entry) => [
517
+ ...(isVisible(entry.content) && !(thinking?.messageID === message.id && thinking.partID === entry.id)
518
+ ? [{ messageID: message.id, messageIndex, partID: entry.id, content: entry.content, script: false }]
519
+ : []),
520
+ // A script's changes follow it, placed by the Edits setting even where the script itself hides.
521
+ ...scriptChangeItems(message.id, messageIndex, entry.content, detail, factOf),
522
+ ]),
523
+ )
524
+
525
+ // While the turn runs, the thoughts it ends on read as Thinking until something else shows, since the model may
526
+ // think again in its next step. A notice after them ends the run.
527
+ const tail = messages.at(-1) === lastAssistant && view.live ? trailingThoughts(visibleRefs) : []
528
+ const live = thinking ?? (quietTail ? tail.at(-1) : undefined)
529
+ const settled = !live ? [] : thinking ? tail : tail.slice(0, -1)
530
+ const refs = live ? visibleRefs.slice(0, visibleRefs.length - tail.length) : visibleRefs
531
+
532
+ const interruptedAt = messages.findIndex((message) => isInterruptedError(message.error))
533
+ const before = interruptedAt < 0 ? refs : refs.filter((ref) => ref.messageIndex <= interruptedAt)
534
+ const after = interruptedAt < 0 ? [] : refs.filter((ref) => ref.messageIndex > interruptedAt)
535
+
536
+ const appendGroups = (items: typeof refs) => {
537
+ let offset = 0
538
+ groupContent(items, place, commentary, detail).forEach((group) => {
539
+ const tool = group.type !== "part" || items[offset]?.content.type !== "text"
540
+ offset += group.type === "part" ? 1 : group.refs.length
541
+ rows.push(
542
+ new TimelineRow.AssistantPart({
543
+ userMessageID: turn.id,
544
+ group,
545
+ previousAssistantPart: assistantGroupIndex > 0,
546
+ spacing: assistantGroupIndex > 0 ? (previousAssistantTool && tool ? "tool" : "content") : undefined,
547
+ }),
548
+ )
549
+ assistantGroupIndex += 1
550
+ previousAssistantTool = tool
551
+ })
552
+ }
553
+
554
+ appendGroups(before)
555
+
556
+ // The user stopped the turn, so the timeline confirms it whatever the setting. Where the setting hides all of the
557
+ // agent's activity, the work stopped first says how long it ran.
558
+ if (interruptedAt >= 0) {
559
+ if (hidesActivity(detail) && !rows.some((row) => Predicate.isTagged(row, "Worked")))
560
+ rows.push(new TimelineRow.Worked({ userMessageID: turn.id }))
561
+ rows.push(new TimelineRow.TurnDivider({ userMessageID: turn.id }))
562
+ appendGroups(after)
563
+ }
564
+
565
+ if (messages.at(-1) !== lastAssistant) return
566
+
567
+ // The live thought closes its own step, so notices that arrive meanwhile follow it.
568
+ if (live)
569
+ rows.push(
570
+ new TimelineRow.Thinking({
571
+ userMessageID: turn.id,
572
+ ref: live,
573
+ before: settled.map((ref) => ({ messageID: ref.messageID, partID: ref.partID })),
574
+ }),
575
+ )
576
+
577
+ if (lastStep?.type !== "assistant") return
578
+
579
+ if (view.retry)
580
+ rows.push(
581
+ new TimelineRow.Retry({
582
+ userMessageID: turn.id,
583
+ attempt: view.retry.attempt,
584
+ message: view.retry.message,
585
+ next: view.retry.next,
586
+ }),
587
+ )
588
+
589
+ if (view.error) rows.push(new TimelineRow.Error({ userMessageID: turn.id, ...view.error }))
590
+ }
591
+
592
+ let assistantSegment: SessionMessageAssistant[] = []
593
+ turn.entries.forEach((entry) => {
594
+ switch (entry.type) {
595
+ case "assistant":
596
+ assistantSegment.push(entry.message)
597
+
598
+ return
599
+ case "idle":
600
+ appendAssistantSegment(assistantSegment)
601
+ assistantSegment = []
602
+
603
+ if (entry === lastStep && view.error)
604
+ rows.push(new TimelineRow.Error({ userMessageID: turn.id, ...view.error }))
605
+
606
+ return
607
+ case "diff":
608
+ appendAssistantSegment(assistantSegment)
609
+ assistantSegment = []
610
+ rows.push(
611
+ new TimelineRow.TurnDiff({
612
+ userMessageID: turn.id,
613
+ messageID: entry.message.id,
614
+ from: entry.from,
615
+ files: entry.files,
616
+ }),
617
+ )
618
+
619
+ return
620
+ case "notice":
621
+ if (placeNotice(entry.message, detail, "next") === "hidden") return
622
+ appendAssistantSegment(assistantSegment)
623
+ assistantSegment = []
624
+ rows.push(new TimelineRow.Notice({ userMessageID: turn.id, messageID: entry.message.id }))
625
+ }
626
+ })
627
+ appendAssistantSegment(assistantSegment)
628
+
629
+ return rows
630
+ }
631
+
632
+ // The thoughts a list of parts ends on, oldest first.
633
+ function trailingThoughts<T extends { content: Content; script: boolean }>(refs: T[]) {
634
+ const start = refs.findLastIndex((ref) => ref.script || ref.content.type !== "reasoning") + 1
635
+
636
+ return refs.slice(start)
637
+ }
638
+
639
+ // Each step replaces the phase the steps before it left, so the turn ends in the phase of its last step.
640
+ function turnPhase(entries: Entry[], active: boolean, status: SessionStatus, placement: TurnThinkingPlacement) {
641
+ return entries.reduce(
642
+ (phase, entry) => {
643
+ if (entry.type === "idle")
644
+ return transitionTurnPhase(phase, { type: "idle.failed", error: errorInfo(entry.message) })
645
+
646
+ if (entry.type !== "assistant") return phase
647
+
648
+ return transitionTurnPhase(phase, stepEvent(entry.message, active, status, placement))
649
+ },
650
+ transitionTurnPhase(IDLE_TURN_PHASE, { type: "started", live: active && status.type !== "idle" }),
651
+ )
652
+ }
653
+
654
+ function stepEvent(
655
+ message: SessionMessageAssistant,
656
+ active: boolean,
657
+ status: SessionStatus,
658
+ placement: TurnThinkingPlacement,
659
+ ): TurnPhaseEvent {
660
+ const completed = message.time.completed !== undefined
661
+ const last = !completed && active ? contentEntries(message).at(-1) : undefined
662
+
663
+ return {
664
+ type: "step",
665
+ active,
666
+ session: status.type,
667
+ completed,
668
+ reasoning:
669
+ last?.content.type === "reasoning" && last.content.time?.completed === undefined
670
+ ? { ref: { messageID: message.id, partID: last.id }, placement }
671
+ : undefined,
672
+ retry: message.retry
673
+ ? { attempt: message.retry.attempt, message: message.retry.error.message, next: message.retry.at }
674
+ : undefined,
675
+ error: !message.error
676
+ ? undefined
677
+ : isInterruptedError(message.error)
678
+ ? { interrupted: true }
679
+ : { interrupted: false, info: errorInfo(message) },
680
+ }
681
+ }
682
+
683
+ function isFailedIdle(message: SessionMessageInfo): message is FailedIdle {
684
+ return message.type === "idle" && message.outcome === "failed" && !!message.error
685
+ }
686
+
687
+ /**
688
+ * Grouped notices join the activity group, shell reports can share an events row, and each subagent report keeps
689
+ * its own place in the timeline.
690
+ */
691
+ function groupNotices(
692
+ rows: TimelineRow.TimelineRow[],
693
+ detail: TimelineDetail,
694
+ messageByID: ReadonlyMap<string, SessionMessageInfo>,
695
+ ) {
696
+ return rows.reduce<TimelineRow.TimelineRow[]>((result, row) => {
697
+ const previous = result.at(-1)
698
+ // Live status renders nothing while other feedback shows, so a group below it spaces from the content above it.
699
+ const above = Predicate.isTagged(previous, "Activity") ? result.at(-2) : previous
700
+ const message = Predicate.isTagged(row, "Notice") ? messageByID.get(row.messageID) : undefined
701
+ const event = message && noticeEvent(message)
702
+
703
+ // Work that reports back right after the activity group that started it, with nothing between, finishes there.
704
+ if (
705
+ message &&
706
+ event?.kind === "shell" &&
707
+ !event.failed &&
708
+ Predicate.isTagged(previous, "AssistantPart") &&
709
+ previous.group.type === "context" &&
710
+ previous.userMessageID === row.userMessageID &&
711
+ launches(previous.group, event, messageByID)
712
+ ) {
713
+ result[result.length - 1] = new TimelineRow.AssistantPart({
714
+ ...previous,
715
+ group: { ...previous.group, refs: [...previous.group.refs, { messageID: message.id, partID: message.id }] },
716
+ })
717
+
718
+ return result
719
+ }
720
+
721
+ const type = message ? noticeGroup(detail, message, event) : undefined
722
+
723
+ const current =
724
+ Predicate.isTagged(row, "Notice") && type
725
+ ? new TimelineRow.AssistantPart({
726
+ userMessageID: row.userMessageID,
727
+ previousAssistantPart: Predicate.isTagged(above, "AssistantPart"),
728
+ spacing:
729
+ Predicate.isTagged(above, "AssistantPart") || Predicate.isTagged(above, "Error") ? "tool" : undefined,
730
+ group: {
731
+ type,
732
+ key: `${type === "context" ? "message" : "events"}:${row.messageID}`,
733
+ refs: [{ messageID: row.messageID, partID: row.messageID }],
734
+ },
735
+ })
736
+ : row
737
+
738
+ if (
739
+ Predicate.isTagged(previous, "AssistantPart") &&
740
+ Predicate.isTagged(current, "AssistantPart") &&
741
+ previous.userMessageID === current.userMessageID &&
742
+ previous.group.type !== "part" &&
743
+ current.group.type !== "part" &&
744
+ joins(previous.group, current.group, messageByID)
745
+ ) {
746
+ result[result.length - 1] = new TimelineRow.AssistantPart({
747
+ ...previous,
748
+ group: { ...previous.group, refs: [...previous.group.refs, ...current.group.refs] },
749
+ })
750
+
751
+ return result
752
+ }
753
+
754
+ result.push(current)
755
+
756
+ return result
757
+ }, [])
758
+ }
759
+
760
+ // Activity groups next to each other read as one, except that notices never join a run of thoughts: the thoughts stay
761
+ // thought rows, and the notices a row of their own. Notices reporting back join each other, never the calls that
762
+ // started the work, which count separately.
763
+ function joins(
764
+ previous: Exclude<PartGroup, { type: "part" }>,
765
+ current: Exclude<PartGroup, { type: "part" }>,
766
+ messageByID: ReadonlyMap<string, SessionMessageInfo>,
767
+ ) {
768
+ const notices = (group: Exclude<PartGroup, { type: "part" }>) =>
769
+ group.refs.every((ref) => ref.messageID === ref.partID)
770
+
771
+ const thoughts = (group: Exclude<PartGroup, { type: "part" }>) =>
772
+ group.refs.every((ref) => resolveContent(messageByID.get(ref.messageID), ref.partID)?.type === "reasoning")
773
+
774
+ if (previous.type === "context" && current.type === "context")
775
+ return !((notices(previous) && thoughts(current)) || (thoughts(previous) && notices(current)))
776
+
777
+ return previous.type === "events" && current.type === "events" && notices(previous) && notices(current)
778
+ }
779
+
780
+ // Whether an activity group started the work an event is about.
781
+ function launches(
782
+ group: Exclude<PartGroup, { type: "part" }>,
783
+ event: TimelineEvent,
784
+ messageByID: ReadonlyMap<string, SessionMessageInfo>,
785
+ ) {
786
+ const key = workKey(event)
787
+
788
+ return (
789
+ key !== undefined &&
790
+ group.refs.some((ref) => {
791
+ const content = resolveContent(messageByID.get(ref.messageID), ref.partID)
792
+
793
+ return content?.type === "tool" && launchOf(content)?.key === key
794
+ })
795
+ )
796
+ }
797
+
798
+ function noticeGroup(detail: TimelineDetail, message: SessionMessageInfo, event?: TimelineEvent) {
799
+ if (event) return event.kind === "subagent" ? ("subagent" as const) : ("events" as const)
800
+
801
+ return placeNotice(message, detail, "next") === "grouped" ? ("context" as const) : undefined
802
+ }
803
+
804
+ export function reuseTimelineRows(previous: TimelineRow.TimelineRow[] | undefined, rows: TimelineRow.TimelineRow[]) {
805
+ if (!previous?.length) return rows
806
+ const byKey = new Map(previous.map((row) => [TimelineRow.key(row), row] as const))
807
+ const groupByPart = new Map<string, PriorGroup>()
808
+ previous.forEach((row, index) => {
809
+ if (!Predicate.isTagged(row, "AssistantPart") || row.group.type === "part") return
810
+ row.group.refs.forEach((ref) => groupByPart.set(groupPartKey(ref), { index, row }))
811
+ })
812
+ const reserved = new Map<string, number>()
813
+ rows.forEach((row, index) => {
814
+ if (!Predicate.isTagged(row, "AssistantPart") || row.group.type === "part") return
815
+ const key = TimelineRow.key(row)
816
+
817
+ if (byKey.has(key) && !reserved.has(key)) reserved.set(key, index)
818
+ })
819
+ const claimed = new Set<string>()
820
+
821
+ const next = rows.map((input, index) => {
822
+ const row = stabilizeGroupKey(groupByPart, reserved, input, index, claimed)
823
+ const existing = byKey.get(TimelineRow.key(row))
824
+
825
+ if (!existing) return row
826
+
827
+ return TimelineRow.equals(existing, row) ? existing : row
828
+ })
829
+
830
+ if (previous.length === next.length && previous.every((row, index) => row === next[index])) return previous
831
+
832
+ return next
833
+ }
834
+
835
+ type UserSelection = { agent: string; model: ModelRef }
836
+
837
+ /** The agent and model a user message's metadata names, when it names them. */
838
+ function localSelection(message: SessionMessageUser): Partial<UserSelection> {
839
+ const localModel = Option.getOrUndefined(decodeLocalModel(message.metadata))?.model
840
+ const localModelID = localModel?.id ?? localModel?.modelID
841
+
842
+ return {
843
+ agent: Option.getOrUndefined(decodeLocalAgent(message.metadata))?.agent,
844
+ model:
845
+ localModel && localModelID
846
+ ? { id: localModelID, providerID: localModel.providerID, variant: localModel.variant }
847
+ : undefined,
848
+ }
849
+ }
850
+
851
+ function indexUserContext(messages: SessionMessageInfo[]) {
852
+ const result = new Map<string, UserSelection>()
853
+ let agent = ""
854
+ let model: ModelRef = { id: "", providerID: "" }
855
+ let userID: string | undefined
856
+
857
+ messages.forEach((message) => {
858
+ if (message.type === "agent-switched") agent = message.agent
859
+
860
+ if (message.type === "model-switched") model = message.model
861
+
862
+ if (message.type === "user") {
863
+ userID = message.id
864
+ const local = localSelection(message)
865
+ result.set(message.id, { agent: local.agent ?? agent, model: local.model ?? model })
866
+ }
867
+
868
+ if (message.type === "shell") userID = undefined
869
+
870
+ if (message.type !== "assistant") return
871
+ agent = message.agent
872
+ model = message.model
873
+
874
+ if (userID) result.set(userID, { agent, model })
875
+ })
876
+
877
+ return result
878
+ }
879
+
880
+ function indexAssistantMessages(messages: SessionMessageInfo[]) {
881
+ const result = new Map<string, SessionMessageAssistant[]>()
882
+ let userID: string | undefined
883
+
884
+ messages.forEach((message) => {
885
+ if (message.type === "user") userID = message.id
886
+
887
+ if (message.type === "shell") userID = undefined
888
+
889
+ if (message.type !== "assistant") return
890
+
891
+ if (!userID) userID = message.id
892
+ const existing = result.get(userID)
893
+
894
+ if (existing) {
895
+ existing.push(message)
896
+
897
+ return
898
+ }
899
+
900
+ result.set(userID, [message])
901
+ })
902
+
903
+ return result
904
+ }
905
+
906
+ function stabilizeGroupKey(
907
+ groupByPart: Map<string, PriorGroup>,
908
+ reserved: Map<string, number>,
909
+ row: TimelineRow.TimelineRow,
910
+ rowIndex: number,
911
+ claimed: Set<string>,
912
+ ) {
913
+ if (!Predicate.isTagged(row, "AssistantPart") || row.group.type === "part") return row
914
+
915
+ const existing = row.group.refs.reduce<PriorGroup | undefined>((result, ref) => {
916
+ const candidate = groupByPart.get(groupPartKey(ref))
917
+
918
+ if (!candidate) return result
919
+ const key = TimelineRow.key(candidate.row)
920
+
921
+ if (claimed.has(key)) return result
922
+ const owner = reserved.get(key)
923
+
924
+ if (owner !== undefined && owner !== rowIndex) return result
925
+
926
+ return !result || candidate.index < result.index ? candidate : result
927
+ }, undefined)
928
+
929
+ if (!existing) return row
930
+ const key = TimelineRow.key(existing.row)
931
+ claimed.add(key)
932
+
933
+ if (row.group.key === existing.row.group.key) return row
934
+
935
+ return new TimelineRow.AssistantPart({
936
+ userMessageID: row.userMessageID,
937
+ previousAssistantPart: row.previousAssistantPart,
938
+ spacing: row.spacing,
939
+ group: { ...row.group, key: existing.row.group.key },
940
+ })
941
+ }
942
+
943
+ // Part refs are globally unique; keying by the turn would break reuse when a
944
+ // page-boundary turn regroups under its real user message after a history prepend.
945
+ function groupPartKey(ref: PartRef) {
946
+ return `${ref.messageID}:${ref.partID}`
947
+ }
948
+
949
+ function groupContent(
950
+ items: { messageID: string; partID: string; content: Content; script?: boolean }[],
951
+ place: Input["place"],
952
+ commentary: ReadonlySet<Content>,
953
+ detail: TimelineDetail,
954
+ ): PartGroup[] {
955
+ const groups: PartGroup[] = []
956
+ let adjacent: { type: "context" | "file" | "read" | "events" | "thought"; refs: PartRef[] } | undefined
957
+
958
+ const flush = () => {
959
+ const current = adjacent
960
+ const first = current?.refs[0]
961
+
962
+ if (!first) return
963
+ adjacent = undefined
964
+
965
+ // A thought alone keeps its own row; thoughts one after another read as one.
966
+ if (current.type === "thought" && current.refs.length === 1) {
967
+ groups.push({ type: "part", key: `part:${first.messageID}:${first.partID}`, ref: first })
968
+
969
+ return
970
+ }
971
+
972
+ groups.push({
973
+ type: current.type,
974
+ key:
975
+ current.type !== "context"
976
+ ? `part:${first.messageID}:${first.partID}`
977
+ : `context:${first.messageID}:${first.partID}`,
978
+ refs: current.refs,
979
+ })
980
+ }
981
+
982
+ const placed = items.map((item) =>
983
+ item.script ? placeScriptChange(detail) : place(item.content, commentary.has(item.content)),
984
+ )
985
+
986
+ items.forEach((item, index) => {
987
+ const group = placed[index]!.group
988
+ const type = group !== "part" ? group : item.content.type === "reasoning" && !item.script ? "thought" : undefined
989
+
990
+ if (type === "subagent") {
991
+ flush()
992
+ groups.push({
993
+ type,
994
+ key: `subagent:${item.messageID}:${item.partID}`,
995
+ refs: [{ messageID: item.messageID, partID: item.partID }],
996
+ })
997
+
998
+ return
999
+ }
1000
+
1001
+ if (type) {
1002
+ if (adjacent?.type !== type) flush()
1003
+ adjacent ??= { type, refs: [] }
1004
+ adjacent.refs.push({ messageID: item.messageID, partID: item.partID })
1005
+
1006
+ return
1007
+ }
1008
+
1009
+ flush()
1010
+ groups.push({
1011
+ type: "part",
1012
+ key: `part:${item.messageID}:${item.partID}`,
1013
+ ref: { messageID: item.messageID, partID: item.partID },
1014
+ })
1015
+ })
1016
+ flush()
1017
+
1018
+ return groups
1019
+ }
1020
+
1021
+ function isNotice(message: SessionMessageInfo): message is Notice {
1022
+ if (message.type === "user" || message.type === "assistant" || message.type === "shell" || message.type === "idle")
1023
+ return false
1024
+
1025
+ if (message.type !== "synthetic") return true
1026
+
1027
+ return message.metadata?.source === "subagent" || !!message.description?.trim() || timelineNoticeRequired(message)
1028
+ }