@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,1261 @@
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 { currentContentDefaultOpen, currentToolHasLoadedFiles } from "../message/current-tool-state"
13
+ import { turnCommentary } from "./commentary"
14
+ import { TimelineRow, type PartGroup, type PartRef, type TimelineRowMap } from "./timeline-row"
15
+ import { timelineNoticeRequired, type TimelineDetail } from "./detail"
16
+ import { placeFactOf, type PlaceFact } from "./facts"
17
+ import {
18
+ placeContent,
19
+ placeNotice,
20
+ placer,
21
+ placeScriptChange,
22
+ scriptChangeItems,
23
+ type Place,
24
+ type PlaceFactOf,
25
+ } from "./place"
26
+ import {
27
+ IDLE_TURN_PHASE,
28
+ isInterruptedError,
29
+ sameTurnPhase,
30
+ transitionTurnPhase,
31
+ viewTurnPhase,
32
+ type TurnErrorInfo,
33
+ type TurnPhase,
34
+ type TurnPhaseEvent,
35
+ type TurnThinkingPlacement,
36
+ } from "./turn-phase-machine"
37
+
38
+ export { TimelineRow, type PartGroup, type PartRef, type TimelineRowMap, type TurnPhase }
39
+
40
+ export type ReasoningMode = "hidden" | "compact" | "full"
41
+
42
+ type Notice = Exclude<SessionMessageInfo, { type: "user" | "assistant" | "shell" | "idle" }>
43
+
44
+ type FailedIdle = SessionMessageIdle & {
45
+ outcome: "failed"
46
+ error: NonNullable<SessionMessageIdle["error"]>
47
+ }
48
+
49
+ type Entry =
50
+ | { type: "assistant"; message: SessionMessageAssistant; run: number }
51
+ | { type: "notice"; message: Notice }
52
+ | { type: "idle"; message: FailedIdle }
53
+ | { type: "diff"; message: SessionMessageIdle; from: string; files: string[] }
54
+
55
+ type Content = SessionMessageAssistant["content"][number]
56
+
57
+ type Tool = Extract<Content, { type: "tool" }>
58
+
59
+ type GroupRow = Extract<TimelineRow.TimelineRow, { _tag: "AssistantPart" }>
60
+
61
+ type PriorGroup = { index: number; row: GroupRow }
62
+
63
+ const decodeJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown))
64
+
65
+ const decodeString = Schema.decodeUnknownOption(Schema.String)
66
+
67
+ // A field of the wrong type decodes as absent, so one bad field does not discard its neighbours.
68
+ function lenient<S extends Schema.Top>(schema: S) {
69
+ return Schema.optionalKey(schema.pipe(Schema.catchDecoding(() => Effect.succeedNone)))
70
+ }
71
+
72
+ const decodeLocalAgent = Schema.decodeUnknownOption(Schema.Struct({ agent: Schema.String }))
73
+
74
+ const decodeLocalModel = Schema.decodeUnknownOption(
75
+ Schema.Struct({
76
+ model: Schema.Struct({
77
+ id: lenient(Schema.String),
78
+ modelID: lenient(Schema.String),
79
+ providerID: Schema.String,
80
+ variant: lenient(Schema.String),
81
+ }),
82
+ }),
83
+ )
84
+
85
+ const decodeErrorEnvelope = Schema.decodeUnknownOption(
86
+ Schema.Struct({ error: Schema.optionalKey(Schema.Unknown), message: lenient(Schema.String) }),
87
+ )
88
+
89
+ const decodeErrorDetails = Schema.decodeUnknownOption(
90
+ Schema.Struct({ type: lenient(Schema.String), message: lenient(Schema.String), code: lenient(Schema.String) }),
91
+ )
92
+
93
+ export type TimelineProjectionInput = {
94
+ sessionMessages: SessionMessageInfo[]
95
+ status: SessionStatus
96
+ reasoningMode: ReasoningMode
97
+ shellToolDefaultOpen?: boolean
98
+ editToolDefaultOpen?: boolean
99
+ timelineDetail?: TimelineDetail
100
+ pendingInputIDs?: ReadonlySet<string>
101
+ queuedCompactionIDs?: readonly string[]
102
+ turnDiffs?: boolean
103
+ previousRows?: TimelineRow.TimelineRow[]
104
+ }
105
+
106
+ export function createTimelineProjection(input: TimelineProjectionInput) {
107
+ const sessionMessageByID = new Map(input.sessionMessages.map((message) => [message.id, message] as const))
108
+
109
+ const projection = Timeline.constructSessionMessageRows(
110
+ input.sessionMessages,
111
+ input.reasoningMode !== "hidden",
112
+ input.status,
113
+ input.pendingInputIDs,
114
+ input.shellToolDefaultOpen ?? false,
115
+ input.editToolDefaultOpen ?? false,
116
+ undefined,
117
+ input.timelineDetail,
118
+ input.queuedCompactionIDs,
119
+ input.turnDiffs,
120
+ )
121
+
122
+ const rows = reuseTimelineRows(input.previousRows, projection.rows)
123
+ const rowByKey = new Map(rows.map((row) => [TimelineRow.key(row), row] as const))
124
+ const messageRowIndex = new Map<string, number>()
125
+ const messageLastRowIndex = new Map<string, number>()
126
+ const lastAssistantGroupKey = new Map<string, string>()
127
+
128
+ rows.forEach((row, index) => {
129
+ if (!messageRowIndex.has(row.userMessageID)) messageRowIndex.set(row.userMessageID, index)
130
+ messageLastRowIndex.set(row.userMessageID, index)
131
+
132
+ if (Predicate.isTagged(row, "AssistantPart")) lastAssistantGroupKey.set(row.userMessageID, row.group.key)
133
+ })
134
+
135
+ return {
136
+ activeMessageID: projection.activeMessageID,
137
+ turnPhaseByID: projection.turnPhaseByID,
138
+ assistantMessagesByParent: indexAssistantMessages(input.sessionMessages),
139
+ lastAssistantGroupKey,
140
+ messageByID: sessionMessageByID,
141
+ messageRowIndex,
142
+ messageLastRowIndex,
143
+ rowByKey,
144
+ rows,
145
+ sessionMessageByID,
146
+ userContextByID: indexUserContext(input.sessionMessages),
147
+ }
148
+ }
149
+
150
+ export function createReactiveTimelineProjection(input: {
151
+ sessionMessages: Accessor<SessionMessageInfo[]>
152
+ status: Accessor<SessionStatus>
153
+ reasoningMode: Accessor<ReasoningMode>
154
+ shellToolDefaultOpen?: Accessor<boolean>
155
+ editToolDefaultOpen?: Accessor<boolean>
156
+ timelineDetail?: Accessor<TimelineDetail>
157
+ pendingInputIDs?: Accessor<ReadonlySet<string>>
158
+ queuedCompactionIDs?: Accessor<readonly string[]>
159
+ /** Summarize each finished turn's changed files after it. */
160
+ turnDiffs?: Accessor<boolean>
161
+ }) {
162
+ const sessionMessageByID = createMemo(
163
+ () => new Map(input.sessionMessages().map((message) => [message.id, message] as const)),
164
+ )
165
+
166
+ const userContextByID = createMemo(() => indexUserContext(input.sessionMessages()))
167
+ const assistantMessagesByParent = createMemo(() => indexAssistantMessages(input.sessionMessages()))
168
+
169
+ // Row structure depends on the empty/non-empty boundary, not each text delta.
170
+ // Keep the original content objects so row renderers still read live text.
171
+ const textParts = mapArray(
172
+ messageParts(input.sessionMessages, (message) =>
173
+ message.type === "assistant" ? message.content.filter((content) => content.type !== "tool") : [],
174
+ ),
175
+ (content) => {
176
+ // A memo here went stale on every streamed delta, which marked the projection below pending; Solid then
177
+ // re-checked each of its thousands of sources to find nothing changed. A signal set from a computation
178
+ // notifies only when visibility actually flips.
179
+ const [visible, setVisible] = createSignal(false)
180
+ createComputed(() => setVisible(!!content.text.trim()))
181
+
182
+ return [content, visible] as const
183
+ },
184
+ )
185
+
186
+ const textVisible = createMemo(() => new Map<Content, Accessor<boolean>>(textParts()))
187
+ const factOf = placeFacts(input.sessionMessages)
188
+
189
+ const projection = createMemo(() =>
190
+ Timeline.constructSessionMessageRows(
191
+ input.sessionMessages(),
192
+ input.reasoningMode() !== "hidden",
193
+ input.status(),
194
+ input.pendingInputIDs?.(),
195
+ input.shellToolDefaultOpen?.() ?? false,
196
+ input.editToolDefaultOpen?.() ?? false,
197
+ (content, showReasoning, detail, placeOf) =>
198
+ content.type === "tool"
199
+ ? renderable(content, showReasoning, detail, placeOf)
200
+ : (content.type === "text" || (detail ? detail.thinking.placement !== "hidden" : showReasoning)) &&
201
+ textVisible().get(content)!(),
202
+ input.timelineDetail?.(),
203
+ input.queuedCompactionIDs?.(),
204
+ input.turnDiffs?.(),
205
+ factOf,
206
+ ),
207
+ )
208
+
209
+ const activeMessageID = createMemo(() => projection().activeMessageID)
210
+
211
+ // Rows read their turn's phase, so a recomputed projection that leaves every phase as it was notifies none of them.
212
+ const turnPhaseByID = createMemo(() => projection().turnPhaseByID, undefined, {
213
+ equals: (previous, next) =>
214
+ previous.size === next.size &&
215
+ [...next].every(([id, phase]) => {
216
+ const prior = previous.get(id)
217
+
218
+ return !!prior && sameTurnPhase(prior, phase)
219
+ }),
220
+ })
221
+
222
+ const rows = createMemo((previous: TimelineRow.TimelineRow[] | undefined) =>
223
+ reuseTimelineRows(previous, projection().rows),
224
+ )
225
+
226
+ const rowByKey = createMemo(() => new Map(rows().map((row) => [TimelineRow.key(row), row] as const)))
227
+
228
+ const messageRowIndex = createMemo(() => {
229
+ const result = new Map<string, number>()
230
+ rows().forEach((row, index) => {
231
+ if (result.has(row.userMessageID)) return
232
+ result.set(row.userMessageID, index)
233
+ })
234
+
235
+ return result
236
+ })
237
+
238
+ const messageLastRowIndex = createMemo(() => {
239
+ const result = new Map<string, number>()
240
+ rows().forEach((row, index) => result.set(row.userMessageID, index))
241
+
242
+ return result
243
+ })
244
+
245
+ const lastAssistantGroupKey = createMemo(() => {
246
+ const result = new Map<string, string>()
247
+ rows().forEach((row) => {
248
+ if (Predicate.isTagged(row, "AssistantPart")) result.set(row.userMessageID, row.group.key)
249
+ })
250
+
251
+ return result
252
+ })
253
+
254
+ return {
255
+ activeMessageID,
256
+ turnPhaseByID,
257
+ assistantMessagesByParent,
258
+ lastAssistantGroupKey,
259
+ messageByID: sessionMessageByID,
260
+ messageRowIndex,
261
+ messageLastRowIndex,
262
+ rowByKey,
263
+ rows,
264
+ sessionMessageByID,
265
+ userContextByID,
266
+ }
267
+ }
268
+
269
+ export namespace Timeline {
270
+ export function constructSessionMessageRows(
271
+ messages: SessionMessageInfo[],
272
+ showReasoning: boolean,
273
+ status: SessionStatus,
274
+ pendingInputIDs?: ReadonlySet<string>,
275
+ shellToolDefaultOpen = false,
276
+ editToolDefaultOpen = false,
277
+ isRenderable = renderable,
278
+ detail?: TimelineDetail,
279
+ queuedCompactionIDs: readonly string[] = [],
280
+ turnDiffs = false,
281
+ factOf?: PlaceFactOf,
282
+ ) {
283
+ const placeOf = detail ? placer(detail, "current", factOf) : undefined
284
+
285
+ const shows = (content: Content, showReasoning: boolean, detail?: TimelineDetail) =>
286
+ isRenderable(content, showReasoning, detail, placeOf)
287
+
288
+ type Turn = {
289
+ id: string
290
+ time: { created: number }
291
+ user?: SessionMessageUser
292
+ shell?: SessionMessageShell
293
+ entries: Entry[]
294
+ }
295
+
296
+ const turns: Turn[] = []
297
+ const turnByUserID = new Map<string, Turn>()
298
+ const leading: Notice[] = []
299
+ let current: Turn | undefined
300
+ let openRun = 0
301
+ // Everything since the last idle marker is one turn, including prompts steered in meanwhile.
302
+ let execution: { opener: string; turn: Turn; files: Set<string> } | undefined
303
+
304
+ messages.forEach((message) => {
305
+ if (isNotice(message)) {
306
+ if (current) current.entries.push({ type: "notice", message })
307
+
308
+ if (!current) leading.push(message)
309
+
310
+ return
311
+ }
312
+
313
+ if (message.type === "shell") {
314
+ const turn: Turn = { id: message.id, time: message.time, shell: message, entries: [] }
315
+ turns.push(turn)
316
+ current = turn
317
+
318
+ return
319
+ }
320
+
321
+ if (message.type === "user") {
322
+ if (turnByUserID.has(message.id)) return
323
+ const turn: Turn = { id: message.id, time: message.time, user: message, entries: [] }
324
+ turns.push(turn)
325
+ turnByUserID.set(message.id, turn)
326
+ current = turn
327
+
328
+ // Undelivered input has not joined the turn yet.
329
+ if (!pendingInputIDs?.has(message.id))
330
+ execution = { opener: execution?.opener ?? message.id, turn, files: execution?.files ?? new Set() }
331
+
332
+ return
333
+ }
334
+
335
+ if (message.type === "idle") {
336
+ appendIdle(message)
337
+ openRun++
338
+
339
+ // The summary follows the turn's last prompt, after any failure the marker reports.
340
+ // Sorted like the diff route's git order, so the list keeps its order when the diffs arrive.
341
+ if (turnDiffs && execution?.files.size)
342
+ execution.turn.entries.push({
343
+ type: "diff",
344
+ message,
345
+ from: execution.opener,
346
+ files: [...execution.files].sort(),
347
+ })
348
+ execution = undefined
349
+
350
+ return
351
+ }
352
+
353
+ if (message.type !== "assistant") return
354
+ message.snapshot?.files?.forEach((file) => execution?.files.add(file))
355
+ const existing = current?.user ? current : undefined
356
+
357
+ if (existing?.user) {
358
+ existing.entries.push({ type: "assistant", message, run: openRun })
359
+ current = existing
360
+
361
+ return
362
+ }
363
+
364
+ if (current && !current.user && !current.shell) {
365
+ current.entries.push({ type: "assistant", message, run: openRun })
366
+
367
+ return
368
+ }
369
+
370
+ const turn: Turn = { id: message.id, time: message.time, entries: [{ type: "assistant", message, run: openRun }] }
371
+ turns.push(turn)
372
+ current = turn
373
+ })
374
+
375
+ function appendIdle(message: SessionMessageIdle) {
376
+ if (!isFailedIdle(message)) return
377
+ const last = current?.entries.at(-1)
378
+
379
+ if (
380
+ last?.type === "notice" &&
381
+ last.message.type === "compaction" &&
382
+ last.message.status === "failed" &&
383
+ !isInterruptedError(last.message.error)
384
+ )
385
+ return
386
+
387
+ const lastStep = current?.entries.findLast((entry) => entry.type === "assistant" || entry.type === "idle")
388
+
389
+ if (lastStep?.type === "assistant" && lastStep.message.error && !isInterruptedError(lastStep.message.error))
390
+ return
391
+
392
+ if (current && !current.shell) {
393
+ current.entries.push({ type: "idle", message })
394
+
395
+ return
396
+ }
397
+
398
+ const turn: Turn = { id: message.id, time: message.time, entries: [{ type: "idle", message }] }
399
+ turns.push(turn)
400
+ current = turn
401
+ }
402
+
403
+ const activeMessageID =
404
+ turns.findLast((turn) => !pendingInputIDs?.has(turn.id) || turn.entries.some((entry) => entry.type === "idle"))
405
+ ?.id ?? turns.at(-1)?.id
406
+
407
+ const placement = detail ? detail.thinking.placement : showReasoning ? "separate" : "hidden"
408
+
409
+ const turnPhaseByID = new Map(
410
+ turns.map((turn) => [turn.id, turnPhase(turn.entries, turn.id === activeMessageID, status, placement)] as const),
411
+ )
412
+
413
+ const phaseOf = (turn: Turn) => turnPhaseByID.get(turn.id) ?? IDLE_TURN_PHASE
414
+
415
+ const commentary = new Set(
416
+ detail && detail.commentary.placement !== "separate"
417
+ ? turns.flatMap((turn) =>
418
+ turnCommentary(
419
+ turn.entries.filter((entry) => entry.type === "assistant"),
420
+ openRun,
421
+ viewTurnPhase(phaseOf(turn)).settled,
422
+ (content) => shows(content, showReasoning, detail),
423
+ ),
424
+ )
425
+ : [],
426
+ )
427
+
428
+ const visible = (content: Content, showReasoning: boolean, detail?: TimelineDetail) =>
429
+ !(placeOf && commentary.has(content) && placeOf(content, true).placement === "hidden") &&
430
+ shows(content, showReasoning, detail)
431
+
432
+ const visibleNotice = (message: Notice) => !detail || placeNotice(message, detail, "current") !== "hidden"
433
+
434
+ const visibleTurns = detail
435
+ ? turns.filter((turn) => {
436
+ if (turn.user) return true
437
+
438
+ if (turn.shell && (detail.shell.placement !== "hidden" || shellFailed(turn.shell))) return true
439
+
440
+ return turn.entries.some((entry) =>
441
+ entry.type === "notice"
442
+ ? visibleNotice(entry.message)
443
+ : entry.type === "idle" ||
444
+ entry.type === "diff" ||
445
+ !!entry.message.error ||
446
+ !!entry.message.retry ||
447
+ entry.message.content.some((content) => visible(content, showReasoning, detail)),
448
+ )
449
+ })
450
+ : turns
451
+
452
+ const rows: TimelineRow.TimelineRow[] = [
453
+ ...leading.flatMap((message) =>
454
+ visibleNotice(message)
455
+ ? [new TimelineRow.Notice({ userMessageID: turns[0]?.id ?? message.id, messageID: message.id })]
456
+ : [],
457
+ ),
458
+ ...visibleTurns.flatMap((turn, index) => {
459
+ if (turn.shell)
460
+ return [
461
+ ...(index > 0 ? [new TimelineRow.TurnGap({ userMessageID: turn.id })] : []),
462
+ ...(!detail || detail.shell.placement !== "hidden" || shellFailed(turn.shell)
463
+ ? [new TimelineRow.Shell({ userMessageID: turn.id, messageID: turn.shell.id })]
464
+ : []),
465
+ ...turn.entries.flatMap((entry) =>
466
+ entry.type === "notice" && visibleNotice(entry.message)
467
+ ? [new TimelineRow.Notice({ userMessageID: turn.id, messageID: entry.message.id })]
468
+ : [],
469
+ ),
470
+ ]
471
+
472
+ return constructMessageRows(
473
+ turn.user,
474
+ turn.id,
475
+ turn.entries,
476
+ index,
477
+ showReasoning,
478
+ phaseOf(turn),
479
+ shellToolDefaultOpen,
480
+ editToolDefaultOpen,
481
+ visible,
482
+ detail,
483
+ commentary,
484
+ placeOf,
485
+ factOf,
486
+ )
487
+ }),
488
+ ]
489
+
490
+ // Like the TUI, a queued compaction waits after the active turn and ahead of every undelivered input:
491
+ // steers, which own turns, and synthetic notices, which ride at the end of the active one.
492
+ const pendingAt = rows.findIndex(
493
+ (row) =>
494
+ pendingInputIDs?.has(row.userMessageID) ||
495
+ (Predicate.isTagged(row, "Notice") && pendingInputIDs?.has(row.messageID)),
496
+ )
497
+
498
+ rows.splice(
499
+ pendingAt < 0 ? rows.length : pendingAt,
500
+ 0,
501
+ // Live status ends the work the model has seen, so it stays above everything still waiting for delivery.
502
+ ...(status.type !== "idle" && activeMessageID && (pendingAt >= 0 || queuedCompactionIDs.length > 0)
503
+ ? [new TimelineRow.Activity({ userMessageID: activeMessageID })]
504
+ : []),
505
+ ...queuedCompactionIDs.map(
506
+ (inboxID) => new TimelineRow.CompactionQueued({ userMessageID: activeMessageID ?? inboxID, inboxID }),
507
+ ),
508
+ )
509
+
510
+ return {
511
+ activeMessageID,
512
+ turnPhaseByID,
513
+ rows: detail
514
+ ? groupMessages(
515
+ rows,
516
+ detail,
517
+ new Set(
518
+ messages.flatMap((message) =>
519
+ message.type === "compaction" ||
520
+ message.type === "model-switched" ||
521
+ message.type === "location-switched" ||
522
+ (message.type === "synthetic" && placeNotice(message, detail, "current") === "separate")
523
+ ? [message.id]
524
+ : [],
525
+ ),
526
+ ),
527
+ )
528
+ : rows,
529
+ }
530
+ }
531
+
532
+ export function constructMessageRows(
533
+ userMessage: SessionMessageUser | undefined,
534
+ turnID: string,
535
+ entries: Entry[],
536
+ index: number,
537
+ showReasoning: boolean,
538
+ phase: TurnPhase,
539
+ shellToolDefaultOpen = false,
540
+ editToolDefaultOpen = false,
541
+ isRenderable = renderable,
542
+ detail?: TimelineDetail,
543
+ commentary: ReadonlySet<Content> = new Set(),
544
+ placeOf = detail ? placer(detail, "current") : undefined,
545
+ factOf?: PlaceFactOf,
546
+ ) {
547
+ const rows: TimelineRow.TimelineRow[] = []
548
+ const assistantMessages = entries.flatMap((entry) => (entry.type === "assistant" ? [entry.message] : []))
549
+ const lastAssistant = assistantMessages.at(-1)
550
+ const lastStep = entries.findLast((entry) => entry.type === "assistant" || entry.type === "idle")
551
+ const previousUserMessage = index > 0
552
+ const compaction = entries.some((entry) => entry.type === "notice" && entry.message.type === "compaction")
553
+ const view = viewTurnPhase(phase)
554
+ const thinking = view.separateThinkingRef
555
+
556
+ if (previousUserMessage) rows.push(new TimelineRow.TurnGap({ userMessageID: turnID }))
557
+
558
+ if (userMessage) rows.push(new TimelineRow.UserMessage({ userMessageID: turnID }))
559
+
560
+ let assistantGroupIndex = 0
561
+ let previousAssistantTool = false
562
+
563
+ // An assistant message can produce several rows because its content parts are
564
+ // rendered separately. Notices end a segment so none of those rows cross it.
565
+ const appendAssistantSegment = (messages: SessionMessageAssistant[]) => {
566
+ const refs = messages.flatMap((message, messageIndex) =>
567
+ contentEntries(message).flatMap((entry) => [
568
+ ...(isRenderable(entry.content, showReasoning, detail) &&
569
+ !(thinking?.messageID === message.id && thinking.partID === entry.id)
570
+ ? [{ messageID: message.id, messageIndex, partID: entry.id, content: entry.content, script: false }]
571
+ : []),
572
+ // A script's changes follow it, placed by the Edits setting even where the script itself hides.
573
+ ...scriptChangeItems(message.id, messageIndex, entry.content, detail, factOf),
574
+ ]),
575
+ )
576
+
577
+ const interruptedAt = messages.findIndex((message) => isInterruptedError(message.error))
578
+ const before = interruptedAt < 0 ? refs : refs.filter((ref) => ref.messageIndex <= interruptedAt)
579
+ const after = interruptedAt < 0 ? [] : refs.filter((ref) => ref.messageIndex > interruptedAt)
580
+
581
+ const appendGroups = (items: typeof refs) => {
582
+ let offset = 0
583
+ groupContent(items, shellToolDefaultOpen, editToolDefaultOpen, commentary, detail, placeOf).forEach((group) => {
584
+ const tool = group.type !== "part" || items[offset]?.content.type !== "text"
585
+ offset += group.type === "part" ? 1 : group.refs.length
586
+ rows.push(
587
+ new TimelineRow.AssistantPart({
588
+ userMessageID: turnID,
589
+ group,
590
+ previousAssistantPart: assistantGroupIndex > 0,
591
+ spacing: assistantGroupIndex > 0 ? (previousAssistantTool && tool ? "tool" : "content") : undefined,
592
+ }),
593
+ )
594
+ assistantGroupIndex += 1
595
+ previousAssistantTool = tool
596
+ })
597
+ }
598
+
599
+ appendGroups(before)
600
+
601
+ if (interruptedAt >= 0) {
602
+ if (!compaction && detail?.notices.placement !== "hidden")
603
+ rows.push(new TimelineRow.TurnDivider({ userMessageID: turnID }))
604
+ appendGroups(after)
605
+ }
606
+
607
+ if (messages.at(-1) !== lastAssistant) return
608
+
609
+ // The live reasoning row closes its own step, so notices that arrive meanwhile follow it.
610
+ if (thinking) rows.push(new TimelineRow.Thinking({ userMessageID: turnID, ref: thinking }))
611
+
612
+ if (lastStep?.type !== "assistant") return
613
+
614
+ if (view.retry)
615
+ rows.push(
616
+ new TimelineRow.Retry({
617
+ userMessageID: turnID,
618
+ attempt: view.retry.attempt,
619
+ message: view.retry.message,
620
+ next: view.retry.next,
621
+ }),
622
+ )
623
+
624
+ if (view.error) rows.push(new TimelineRow.Error({ userMessageID: turnID, ...view.error }))
625
+ }
626
+
627
+ let assistantSegment: SessionMessageAssistant[] = []
628
+ entries.forEach((entry) => {
629
+ switch (entry.type) {
630
+ case "assistant":
631
+ assistantSegment.push(entry.message)
632
+
633
+ return
634
+ case "idle":
635
+ appendAssistantSegment(assistantSegment)
636
+ assistantSegment = []
637
+
638
+ if (entry === lastStep && view.error)
639
+ rows.push(new TimelineRow.Error({ userMessageID: turnID, ...view.error }))
640
+
641
+ return
642
+ case "diff":
643
+ appendAssistantSegment(assistantSegment)
644
+ assistantSegment = []
645
+ rows.push(
646
+ new TimelineRow.TurnDiff({
647
+ userMessageID: turnID,
648
+ messageID: entry.message.id,
649
+ from: entry.from,
650
+ files: entry.files,
651
+ }),
652
+ )
653
+
654
+ return
655
+ case "notice":
656
+ if (detail && placeNotice(entry.message, detail, "current") === "hidden") return
657
+ appendAssistantSegment(assistantSegment)
658
+ assistantSegment = []
659
+ rows.push(new TimelineRow.Notice({ userMessageID: turnID, messageID: entry.message.id }))
660
+ }
661
+ })
662
+ appendAssistantSegment(assistantSegment)
663
+
664
+ return rows
665
+ }
666
+
667
+ export function resolveContent(message: SessionMessageInfo | undefined, partID: string): Content | undefined {
668
+ if (message?.type !== "assistant") return undefined
669
+ const ordinals = { text: 0, reasoning: 0 }
670
+
671
+ for (const content of message.content) {
672
+ const id = content.type === "tool" ? content.id : `${message.id}:${content.type}:${ordinals[content.type]++}`
673
+
674
+ if (id === partID) return content
675
+ }
676
+ }
677
+
678
+ export function contentEntries(message: SessionMessageAssistant) {
679
+ const ordinals = { text: 0, reasoning: 0 }
680
+
681
+ return message.content.map((content) => ({
682
+ id: content.type === "tool" ? content.id : `${message.id}:${content.type}:${ordinals[content.type]++}`,
683
+ content,
684
+ }))
685
+ }
686
+ }
687
+
688
+ const MAX_RETRY_AFTER_MS = 45 * 86_400_000
689
+
690
+ function usageLimit(
691
+ message: Pick<SessionMessageAssistant, "error"> & { time: { created: number; completed?: number } },
692
+ ) {
693
+ const type = message.error?.type
694
+
695
+ if (type !== "provider.free-limit" && type !== "provider.go-limit") return {}
696
+
697
+ const kind = type === "provider.go-limit" ? ("go-limit" as const) : ("free-limit" as const)
698
+ const delay = message.error?.retryAfterMs
699
+ const base = message.time.completed ?? message.time.created
700
+
701
+ if (
702
+ delay === undefined ||
703
+ !Number.isFinite(delay) ||
704
+ delay < 0 ||
705
+ delay > MAX_RETRY_AFTER_MS ||
706
+ !Number.isFinite(base) ||
707
+ Number.isNaN(new Date(base + delay).getTime())
708
+ )
709
+ return { kind }
710
+
711
+ return { kind, resetAt: base + delay }
712
+ }
713
+
714
+ // OpenCode Console says when the budget resets in its refusal's metadata, which every protocol's envelope names `resetsAt`.
715
+ function budgetLimit(message: Pick<SessionMessageAssistant, "error">) {
716
+ const type = message.error?.type
717
+
718
+ if (type !== "provider.budget-limit" && type !== "provider.model-budget-limit") return {}
719
+ const kind = type === "provider.budget-limit" ? ("budget-limit" as const) : ("model-budget-limit" as const)
720
+ const at = Date.parse(/"resetsAt"\s*:\s*"([^"]+)"/.exec(message.error?.response?.body ?? "")?.[1] ?? "")
721
+
722
+ if (Number.isNaN(at)) return { kind }
723
+
724
+ return { kind, resetAt: at }
725
+ }
726
+
727
+ // Each step replaces the phase the steps before it left, so the turn ends in the phase of its last step.
728
+ function turnPhase(entries: Entry[], active: boolean, status: SessionStatus, placement: TurnThinkingPlacement) {
729
+ return entries.reduce(
730
+ (phase, entry) => {
731
+ if (entry.type === "idle")
732
+ return transitionTurnPhase(phase, { type: "idle.failed", error: errorInfo(entry.message) })
733
+
734
+ if (entry.type !== "assistant") return phase
735
+
736
+ return transitionTurnPhase(phase, stepEvent(entry.message, active, status, placement))
737
+ },
738
+ transitionTurnPhase(IDLE_TURN_PHASE, { type: "started", live: active && status.type !== "idle" }),
739
+ )
740
+ }
741
+
742
+ function stepEvent(
743
+ message: SessionMessageAssistant,
744
+ active: boolean,
745
+ status: SessionStatus,
746
+ placement: TurnThinkingPlacement,
747
+ ): TurnPhaseEvent {
748
+ const completed = message.time.completed !== undefined
749
+ const last = !completed && active ? Timeline.contentEntries(message).at(-1) : undefined
750
+
751
+ return {
752
+ type: "step",
753
+ active,
754
+ session: status.type,
755
+ completed,
756
+ reasoning:
757
+ last?.content.type === "reasoning" && last.content.time?.completed === undefined
758
+ ? { ref: { messageID: message.id, partID: last.id }, placement }
759
+ : undefined,
760
+ retry: message.retry
761
+ ? { attempt: message.retry.attempt, message: message.retry.error.message, next: message.retry.at }
762
+ : undefined,
763
+ error: !message.error
764
+ ? undefined
765
+ : isInterruptedError(message.error)
766
+ ? { interrupted: true }
767
+ : { interrupted: false, info: errorInfo(message) },
768
+ }
769
+ }
770
+
771
+ function errorInfo(message: Parameters<typeof usageLimit>[0]): TurnErrorInfo {
772
+ return {
773
+ text: unwrapErrorMessage(message.error?.message ?? ""),
774
+ ...usageLimit(message),
775
+ ...budgetLimit(message),
776
+ }
777
+ }
778
+
779
+ function isFailedIdle(message: SessionMessageInfo): message is FailedIdle {
780
+ return message.type === "idle" && message.outcome === "failed" && !!message.error
781
+ }
782
+
783
+ function shellFailed(message: SessionMessageShell) {
784
+ return (
785
+ message.status === "timeout" || (message.status === "exited" && message.exit !== undefined && message.exit !== 0)
786
+ )
787
+ }
788
+
789
+ function groupMessages(rows: TimelineRow.TimelineRow[], detail: TimelineDetail, separate: ReadonlySet<string>) {
790
+ return rows.reduce<TimelineRow.TimelineRow[]>((result, row) => {
791
+ const previous = result.at(-1)
792
+ // Live status renders nothing while other feedback shows, so a group below it spaces from the content above it.
793
+ const above = Predicate.isTagged(previous, "Activity") ? result.at(-2) : previous
794
+
795
+ const current =
796
+ ((Predicate.isTagged(row, "Notice") && detail.notices.placement === "grouped") ||
797
+ (Predicate.isTagged(row, "Shell") && detail.shell.placement === "grouped")) &&
798
+ !separate.has(row.messageID)
799
+ ? new TimelineRow.AssistantPart({
800
+ userMessageID: row.userMessageID,
801
+ previousAssistantPart: Predicate.isTagged(above, "AssistantPart"),
802
+ spacing:
803
+ Predicate.isTagged(above, "AssistantPart") || Predicate.isTagged(above, "Error") ? "tool" : undefined,
804
+ group: {
805
+ type: "context",
806
+ key: `message:${row.messageID}`,
807
+ refs: [{ messageID: row.messageID, partID: row.messageID }],
808
+ },
809
+ })
810
+ : row
811
+
812
+ if (
813
+ Predicate.isTagged(previous, "AssistantPart") &&
814
+ previous.group.type === "context" &&
815
+ Predicate.isTagged(current, "AssistantPart") &&
816
+ current.group.type === "context" &&
817
+ previous.userMessageID === current.userMessageID
818
+ ) {
819
+ result[result.length - 1] = new TimelineRow.AssistantPart({
820
+ ...previous,
821
+ group: { ...previous.group, refs: [...previous.group.refs, ...current.group.refs] },
822
+ })
823
+
824
+ return result
825
+ }
826
+
827
+ result.push(current)
828
+
829
+ return result
830
+ }, [])
831
+ }
832
+
833
+ export function reuseTimelineRows(previous: TimelineRow.TimelineRow[] | undefined, rows: TimelineRow.TimelineRow[]) {
834
+ if (!previous?.length) return rows
835
+ const byKey = new Map(previous.map((row) => [TimelineRow.key(row), row] as const))
836
+ const groupByPart = new Map<string, PriorGroup>()
837
+ previous.forEach((row, index) => {
838
+ if (!Predicate.isTagged(row, "AssistantPart") || row.group.type === "part") return
839
+ row.group.refs.forEach((ref) => groupByPart.set(groupPartKey(ref), { index, row }))
840
+ })
841
+ const reserved = new Map<string, number>()
842
+ rows.forEach((row, index) => {
843
+ if (!Predicate.isTagged(row, "AssistantPart") || row.group.type === "part") return
844
+ const key = TimelineRow.key(row)
845
+
846
+ if (byKey.has(key) && !reserved.has(key)) reserved.set(key, index)
847
+ })
848
+ const claimed = new Set<string>()
849
+
850
+ const next = rows.map((input, index) => {
851
+ const row = stabilizeGroupKey(groupByPart, reserved, input, index, claimed)
852
+ const existing = byKey.get(TimelineRow.key(row))
853
+
854
+ if (!existing) return row
855
+
856
+ return TimelineRow.equals(existing, row) ? existing : row
857
+ })
858
+
859
+ if (previous.length === next.length && previous.every((row, index) => row === next[index])) return previous
860
+
861
+ return next
862
+ }
863
+
864
+ type UserSelection = { agent: string; model: ModelRef }
865
+
866
+ /** The agent and model a user message's metadata names, when it names them. */
867
+ function localSelection(message: SessionMessageUser): Partial<UserSelection> {
868
+ const localModel = Option.getOrUndefined(decodeLocalModel(message.metadata))?.model
869
+ const localModelID = localModel?.id ?? localModel?.modelID
870
+
871
+ return {
872
+ agent: Option.getOrUndefined(decodeLocalAgent(message.metadata))?.agent,
873
+ model:
874
+ localModel && localModelID
875
+ ? { id: localModelID, providerID: localModel.providerID, variant: localModel.variant }
876
+ : undefined,
877
+ }
878
+ }
879
+
880
+ function indexUserContext(messages: SessionMessageInfo[]) {
881
+ const result = new Map<string, UserSelection>()
882
+ let agent = ""
883
+ let model: ModelRef = { id: "", providerID: "" }
884
+ let userID: string | undefined
885
+
886
+ messages.forEach((message) => {
887
+ if (message.type === "agent-switched") agent = message.agent
888
+
889
+ if (message.type === "model-switched") model = message.model
890
+
891
+ if (message.type === "user") {
892
+ userID = message.id
893
+ const local = localSelection(message)
894
+ result.set(message.id, { agent: local.agent ?? agent, model: local.model ?? model })
895
+ }
896
+
897
+ if (message.type === "shell") userID = undefined
898
+
899
+ if (message.type !== "assistant") return
900
+ agent = message.agent
901
+ model = message.model
902
+
903
+ if (userID) result.set(userID, { agent, model })
904
+ })
905
+
906
+ return result
907
+ }
908
+
909
+ function indexAssistantMessages(messages: SessionMessageInfo[]) {
910
+ const result = new Map<string, SessionMessageAssistant[]>()
911
+ let userID: string | undefined
912
+
913
+ messages.forEach((message) => {
914
+ if (message.type === "user") userID = message.id
915
+
916
+ if (message.type === "shell") userID = undefined
917
+
918
+ if (message.type !== "assistant") return
919
+
920
+ if (!userID) userID = message.id
921
+ const existing = result.get(userID)
922
+
923
+ if (existing) {
924
+ existing.push(message)
925
+
926
+ return
927
+ }
928
+
929
+ result.set(userID, [message])
930
+ })
931
+
932
+ return result
933
+ }
934
+
935
+ function stabilizeGroupKey(
936
+ groupByPart: Map<string, PriorGroup>,
937
+ reserved: Map<string, number>,
938
+ row: TimelineRow.TimelineRow,
939
+ rowIndex: number,
940
+ claimed: Set<string>,
941
+ ) {
942
+ if (!Predicate.isTagged(row, "AssistantPart") || row.group.type === "part") return row
943
+
944
+ const existing = row.group.refs.reduce<PriorGroup | undefined>((result, ref) => {
945
+ const candidate = groupByPart.get(groupPartKey(ref))
946
+
947
+ if (!candidate) return result
948
+ const key = TimelineRow.key(candidate.row)
949
+
950
+ if (claimed.has(key)) return result
951
+ const owner = reserved.get(key)
952
+
953
+ if (owner !== undefined && owner !== rowIndex) return result
954
+
955
+ return !result || candidate.index < result.index ? candidate : result
956
+ }, undefined)
957
+
958
+ if (!existing) return row
959
+ const key = TimelineRow.key(existing.row)
960
+ claimed.add(key)
961
+
962
+ if (row.group.key === existing.row.group.key) return row
963
+
964
+ return new TimelineRow.AssistantPart({
965
+ userMessageID: row.userMessageID,
966
+ previousAssistantPart: row.previousAssistantPart,
967
+ spacing: row.spacing,
968
+ group: { ...row.group, key: existing.row.group.key },
969
+ })
970
+ }
971
+
972
+ // Part refs are globally unique; keying by the turn would break reuse when a
973
+ // page-boundary turn regroups under its real user message after a history prepend.
974
+ function groupPartKey(ref: PartRef) {
975
+ return `${ref.messageID}:${ref.partID}`
976
+ }
977
+
978
+ function renderable(
979
+ content: Content,
980
+ showReasoning: boolean,
981
+ detail?: TimelineDetail,
982
+ placeOf?: (content: Content) => Place,
983
+ ) {
984
+ if (content.type === "text") return !!content.text.trim()
985
+
986
+ if (content.type === "reasoning")
987
+ return (detail ? detail.thinking.placement !== "hidden" : showReasoning) && !!content.text.trim()
988
+
989
+ if (detail) return (placeOf?.(content) ?? placeContent(content, detail, "current")).placement !== "hidden"
990
+
991
+ if (content.name === "todowrite") return false
992
+
993
+ if (content.name === "question") return content.state.status !== "streaming" && content.state.status !== "running"
994
+
995
+ return true
996
+ }
997
+
998
+ function groupContent(
999
+ items: { messageID: string; partID: string; content: Content; script?: boolean }[],
1000
+ shellToolDefaultOpen: boolean,
1001
+ editToolDefaultOpen: boolean,
1002
+ commentary: ReadonlySet<Content>,
1003
+ detail?: TimelineDetail,
1004
+ placeOf?: (content: Content, commentary?: boolean) => Place,
1005
+ ): PartGroup[] {
1006
+ const groups: PartGroup[] = []
1007
+ let adjacent: { type: "context" | "file" | "read"; refs: PartRef[]; tools: boolean } | undefined
1008
+
1009
+ const flush = () => {
1010
+ const current = adjacent
1011
+ const first = current?.refs[0]
1012
+
1013
+ if (!first) return
1014
+
1015
+ if (!current.tools && !detail) {
1016
+ groups.push(
1017
+ ...current.refs.map((ref) => ({ type: "part" as const, key: `part:${ref.messageID}:${ref.partID}`, ref })),
1018
+ )
1019
+ adjacent = undefined
1020
+
1021
+ return
1022
+ }
1023
+
1024
+ groups.push({
1025
+ type: current.type,
1026
+ key:
1027
+ current.type !== "context"
1028
+ ? `part:${first.messageID}:${first.partID}`
1029
+ : `context:${first.messageID}:${first.partID}`,
1030
+ refs: current.refs,
1031
+ })
1032
+ adjacent = undefined
1033
+ }
1034
+
1035
+ const placed =
1036
+ placeOf && detail
1037
+ ? items.map((item) =>
1038
+ item.script ? placeScriptChange(detail) : placeOf(item.content, commentary.has(item.content)),
1039
+ )
1040
+ : undefined
1041
+
1042
+ items.forEach((item, index) => {
1043
+ const group = placed?.[index]?.group
1044
+
1045
+ const type = placed
1046
+ ? group === "context" || group === "read" || group === "file"
1047
+ ? group
1048
+ : undefined
1049
+ : contentGroupType(
1050
+ item.content,
1051
+ shellToolDefaultOpen,
1052
+ editToolDefaultOpen,
1053
+ adjacent?.type === "context" && adjacent.tools,
1054
+ commentary,
1055
+ )
1056
+
1057
+ if (type) {
1058
+ if (adjacent?.type !== type) flush()
1059
+ adjacent ??= { type, refs: [], tools: false }
1060
+ adjacent.tools ||= item.content.type === "tool"
1061
+ adjacent.refs.push({ messageID: item.messageID, partID: item.partID })
1062
+
1063
+ return
1064
+ }
1065
+
1066
+ flush()
1067
+ groups.push({
1068
+ type: "part",
1069
+ key: `part:${item.messageID}:${item.partID}`,
1070
+ ref: { messageID: item.messageID, partID: item.partID },
1071
+ })
1072
+ })
1073
+ flush()
1074
+
1075
+ return groups
1076
+ }
1077
+
1078
+ // Without a detail setting, as in stories and embeds, groups follow the older shell and edit toggles.
1079
+ function contentGroupType(
1080
+ content: Content,
1081
+ shellExpanded: boolean,
1082
+ editExpanded: boolean,
1083
+ hasContextGroup: boolean,
1084
+ commentary: ReadonlySet<Content>,
1085
+ ) {
1086
+ if (content.type === "tool") return toolGroupType(content, shellExpanded, editExpanded, hasContextGroup)
1087
+
1088
+ if (content.type === "text") return commentary.has(content) ? "context" : undefined
1089
+
1090
+ return "context"
1091
+ }
1092
+
1093
+ function toolGroupType(
1094
+ content: Extract<Content, { type: "tool" }>,
1095
+ shellExpanded: boolean,
1096
+ editExpanded: boolean,
1097
+ hasContextGroup: boolean,
1098
+ ) {
1099
+ if (content.name === "question" || currentToolHasLoadedFiles(content)) return undefined
1100
+
1101
+ if (content.state.status === "error") {
1102
+ if ((content.name === "shell" || content.name === "execute") && shellExpanded) return undefined
1103
+
1104
+ if ((content.name === "edit" || content.name === "write" || content.name === "patch") && editExpanded)
1105
+ return undefined
1106
+
1107
+ return "context"
1108
+ }
1109
+
1110
+ if (
1111
+ !hasContextGroup &&
1112
+ (content.state.status !== "completed" ||
1113
+ ("metadata" in content.state && content.state.metadata?.status === "running")) &&
1114
+ (content.name === "shell" || content.name === "execute" || content.name === "subagent")
1115
+ )
1116
+ return undefined
1117
+
1118
+ if (currentContentDefaultOpen(content, shellExpanded, editExpanded) !== true) return "context"
1119
+
1120
+ if (content.name === "patch" || content.name === "edit" || content.name === "write") return "file"
1121
+
1122
+ return undefined
1123
+ }
1124
+
1125
+ export function reasoningHeading(text: string): string | undefined {
1126
+ const markdown = text.replace(/\r\n?/g, "\n")
1127
+ const html = lastHeading(markdown, /<h[1-6][^>]*>([\s\S]*?)<\/h[1-6]>/gi, (value) => value.replace(/<[^>]+>/g, " "))
1128
+ const atx = lastHeading(markdown, /^\s{0,3}#{1,6}[ \t]+(.+?)(?:[ \t]+#+[ \t]*)?$/gm)
1129
+ const setext = lastHeading(markdown, /^([^\n]+)\n(?:=+|-+)\s*$/gm)
1130
+ const strong = lastHeading(markdown, /^\s*(?:\*\*((?:(?!\*\*).)+)\*\*|__((?:(?!__).)+)__)\s*$/gm)
1131
+
1132
+ const latest = [html, atx, strong].reduce<HeadingMatch | undefined>(
1133
+ (best, current) => (!best || (current && current.index >= best.index) ? current : best),
1134
+ undefined,
1135
+ )
1136
+
1137
+ return (latest ?? setext)?.value
1138
+ }
1139
+
1140
+ type HeadingMatch = { index: number; value: string }
1141
+
1142
+ function lastHeading(
1143
+ markdown: string,
1144
+ pattern: RegExp,
1145
+ transform?: (value: string) => string,
1146
+ ): HeadingMatch | undefined {
1147
+ return Array.from(markdown.matchAll(pattern)).reduce<HeadingMatch | undefined>((best, match) => {
1148
+ const raw = match[1] ?? match[2] ?? ""
1149
+ const value = cleanHeading(transform ? transform(raw) : raw)
1150
+
1151
+ return value ? { index: match.index, value } : best
1152
+ }, undefined)
1153
+ }
1154
+
1155
+ function cleanHeading(value: string) {
1156
+ return value
1157
+ .replace(/`([^`]+)`/g, "$1")
1158
+ .replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")
1159
+ .replace(/[*_~]+/g, "")
1160
+ .trim()
1161
+ }
1162
+
1163
+ export function unwrapErrorMessage(message: string) {
1164
+ const text = message.replace(/^Error:\s*/, "").trim()
1165
+ const parse = (value: string) => Option.getOrUndefined(decodeJson(value))
1166
+
1167
+ // A JSON string that itself holds JSON is unwrapped once.
1168
+ const read = (value: string) => {
1169
+ const first = parse(value)
1170
+
1171
+ return Option.match(decodeString(first), { onNone: () => first, onSome: (inner) => parse(inner.trim()) })
1172
+ }
1173
+
1174
+ const whole = read(text)
1175
+ const start = text.indexOf("{")
1176
+ const end = text.lastIndexOf("}")
1177
+ const json = whole === undefined && start !== -1 && end > start ? read(text.slice(start, end + 1)) : whole
1178
+ const envelope = Option.getOrUndefined(decodeErrorEnvelope(json))
1179
+
1180
+ if (!envelope) return message
1181
+ const error = Option.getOrUndefined(decodeErrorDetails(envelope.error))
1182
+
1183
+ if (error?.type && error.message) return `${error.type}: ${error.message}`
1184
+
1185
+ if (error?.message) return error.message
1186
+
1187
+ if (error?.type) return error.type
1188
+
1189
+ if (error?.code) return error.code
1190
+
1191
+ if (envelope.message) return envelope.message
1192
+
1193
+ return Option.getOrUndefined(decodeString(envelope.error)) || message
1194
+ }
1195
+
1196
+ function isNotice(message: SessionMessageInfo): message is Notice {
1197
+ if (message.type === "user" || message.type === "assistant" || message.type === "shell" || message.type === "idle")
1198
+ return false
1199
+
1200
+ if (message.type !== "synthetic") return true
1201
+
1202
+ return !!message.description?.trim() || timelineNoticeRequired(message)
1203
+ }
1204
+
1205
+ /**
1206
+ * The picked parts of every message, in order. A message is read again only when it changes, so a history page that
1207
+ * lands reads its own messages and not the loaded transcript.
1208
+ */
1209
+ function messageParts<Part>(
1210
+ messages: Accessor<SessionMessageInfo[]>,
1211
+ pick: (message: SessionMessageInfo) => Part[],
1212
+ ): Accessor<Part[]> {
1213
+ const each = mapArray(messages, (message) => createMemo(() => pick(message)))
1214
+
1215
+ return createMemo(() => each().flatMap((parts) => parts()))
1216
+ }
1217
+
1218
+ /**
1219
+ * Reads what placing each call needs through a signal per call. Streamed input and progress reports change a call many
1220
+ * times a second without moving it, and a signal notifies the rows only when what they read of it changes.
1221
+ */
1222
+ export function placeFacts(messages: Accessor<SessionMessageInfo[]>): PlaceFactOf {
1223
+ const parts = mapArray(
1224
+ messageParts(messages, (message) =>
1225
+ message.type === "assistant" ? message.content.filter((content): content is Tool => content.type === "tool") : [],
1226
+ ),
1227
+ (tool) => {
1228
+ const [fact, setFact] = createSignal(
1229
+ untrack(() => placeFactOf(tool)),
1230
+ { equals: samePlaceFact },
1231
+ )
1232
+
1233
+ createComputed(() => setFact(placeFactOf(tool)))
1234
+
1235
+ // The signal only says when the fact changes, one computation after the write that changed it, so the value
1236
+ // comes from the part itself.
1237
+ return [tool, () => (fact(), untrack(() => placeFactOf(tool)))] as const
1238
+ },
1239
+ )
1240
+
1241
+ const byTool = createMemo(() => new Map<Tool, Accessor<PlaceFact>>(parts()))
1242
+
1243
+ return (tool) => byTool().get(tool)?.() ?? placeFactOf(tool)
1244
+ }
1245
+
1246
+ const placeFactKeys = [
1247
+ "name",
1248
+ "tool",
1249
+ "mode",
1250
+ "status",
1251
+ "failed",
1252
+ "stopped",
1253
+ "called",
1254
+ "groupedRead",
1255
+ "background",
1256
+ "changes",
1257
+ ] as const
1258
+
1259
+ function samePlaceFact(previous: PlaceFact, next: PlaceFact) {
1260
+ return placeFactKeys.every((key) => previous[key] === next[key])
1261
+ }