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

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,1728 @@
1
+ import type {
2
+ SessionMessageAssistant,
3
+ SessionMessageInfo,
4
+ SessionMessageUser,
5
+ SessionStatus,
6
+ } from "@zyro-sec/client/promise"
7
+ import { useI18n } from "@zyro-sec/ui/context/i18n"
8
+ import { SessionTurn } from "@zyro-sec/util/session-turn"
9
+ import { Predicate } from "effect"
10
+ import {
11
+ For,
12
+ Match,
13
+ Show,
14
+ Switch,
15
+ createComputed,
16
+ createEffect,
17
+ createMemo,
18
+ createSignal,
19
+ onCleanup,
20
+ untrack,
21
+ type Accessor,
22
+ type JSX,
23
+ } from "solid-js"
24
+ import { DiffChanges } from "@zyro-sec/ui/diff-changes"
25
+ import { Icon } from "@zyro-sec/ui/icon"
26
+ import { Spring, frameLoop, prefersReducedMotion } from "@zyro-sec/ui/motion"
27
+ import { springStyle } from "@zyro-sec/ui/motion/solid"
28
+ import { Dynamic } from "solid-js/web"
29
+ import type { SessionUserActions, SessionUserAttachmentReference, SessionUserComment } from "../actions"
30
+ import { useData } from "../context"
31
+ import { useSources } from "../context/sources"
32
+ import { turnSources } from "../sources/sources"
33
+ import { SessionReadToolGroup, SessionUserMessage } from "../message/current-message"
34
+ import { FileChangeRuns, fileRuns, runDisclosureKey, ScriptChanges, taskAgentName } from "../tools/tool-renderer"
35
+ import { SessionRetry } from "../components/session-retry"
36
+ import { SessionError } from "../components/session-error"
37
+ import type { TimelineDetail } from "../timeline/detail"
38
+ import { TimelineRow, type PartRef } from "../timeline/timeline-row"
39
+ import { userMessageRuns, userRunSpring } from "../timeline/user-runs"
40
+ import { IDLE_TURN_PHASE, sameRef, viewTurnPhase } from "../timeline/turn-phase-machine"
41
+ import {
42
+ DISPOSED_STEER_ARRIVAL_EVENT,
43
+ INITIAL_STEER_ARRIVAL_STATE,
44
+ shouldGrowUserMessage,
45
+ shouldSnapUserRun,
46
+ transitionSteerArrival,
47
+ } from "../timeline/steer-arrival-machine"
48
+ import { Badge } from "@zyro-sec/ui/badge"
49
+ import { attached } from "../components/message-file"
50
+ import { CompactionMessage, CompactionQueued } from "./compaction"
51
+ import { unwrapErrorMessage } from "./errors"
52
+ import { TimelineEventItem, TimelineEventRow } from "./event-row"
53
+ import { noticeEvent, toolEvent } from "./events"
54
+ import { trackNestedRails } from "./nested-rail"
55
+ import { contentEntries, createNextTimelineProjection, resolveContent, workedDuration } from "./projection"
56
+ import { scriptFileFact, type FileFact } from "../timeline/facts"
57
+ import { diffOpens, placeContent } from "../timeline/place"
58
+ import { goal as goalMessage, movedInPlace, thoughtOpens, toolRule } from "./rules"
59
+ import { Separator } from "./separator"
60
+ import { timelineGaps, type TimelineGap } from "./spacing"
61
+ import { AssistantContent } from "./tools/assistant-content"
62
+ import { ContextGroup, type ActivityGroupPart } from "./tools/context-group"
63
+ import { FileGroup } from "./tools/file-group"
64
+ import { PatchTool } from "./tools/patch"
65
+ import { ShellMessage } from "./tools/shell"
66
+ import { ThoughtRow } from "./tools/thought"
67
+
68
+ const emptyAssistantMessages: SessionMessageAssistant[] = []
69
+
70
+ // Past this many files, the rest of a turn's changes wait behind "Show all".
71
+ const turnDiffFileLimit = 5
72
+
73
+ type Projection = ReturnType<typeof createNextTimelineProjection>
74
+
75
+ type FramedTimelineRow = Exclude<TimelineRow.TimelineRow, TimelineRow.TurnGap>
76
+
77
+ type Outcome = "completed" | "error" | "cancelled"
78
+
79
+ export type SessionUserPresentation = {
80
+ displayText?: string
81
+ comments?: SessionUserComment[]
82
+ references?: SessionUserAttachmentReference[]
83
+ /** A voice call's agent sent it on the user's behalf. */
84
+ voice?: boolean
85
+ }
86
+
87
+ /** Draws the New timeline's rows. */
88
+ export function createNextTimelineRowRenderer(input: {
89
+ sessionID: Accessor<string>
90
+ status: Accessor<SessionStatus>
91
+ projection: Projection
92
+ presentation: (message: SessionMessageUser) => SessionUserPresentation | undefined
93
+ actions?: SessionUserActions
94
+ timelineDetail: Accessor<TimelineDetail>
95
+ foldUserMessages?: Accessor<boolean>
96
+ inlineQuotes?: Accessor<boolean>
97
+ disclosure: {
98
+ value: (key: string) => boolean | undefined
99
+ set: (key: string, open: boolean) => void
100
+ patchGroupKeys?: Map<string, string>
101
+ }
102
+ centered?: Accessor<boolean>
103
+ padding?: Accessor<string>
104
+ anchor?: (messageID: string) => string | undefined
105
+ /** Scrolls to and expands the tool call named by its ID or by the shell ID a backgrounded shell call reports. */
106
+ revealPart?: (target: string) => boolean
107
+ }) {
108
+ const i18n = useI18n()
109
+ const data = useData()
110
+ const sourcesHost = useSources()
111
+ // Cached timelines retain file-change subgroup identities alongside their disclosure choices.
112
+ const patchGroupKeys = input.disclosure.patchGroupKeys ?? new Map<string, string>()
113
+ const patchPartKeys = new WeakMap<SessionMessageAssistant["content"][number], string>()
114
+
115
+ const turns = createMemo(() => {
116
+ const messages = [...input.projection.messageByID().values()]
117
+
118
+ return {
119
+ messages,
120
+ legacy: SessionTurn.legacy(messages),
121
+ indexes: new Map(messages.map((message, index) => [message.id, index])),
122
+ }
123
+ })
124
+
125
+ const patchOwners = createMemo(() => {
126
+ const owners = new Map<string, string>()
127
+ const rows = input.projection.rows()
128
+ // Track status changes before a group is first opened: a failed file change can
129
+ // split an existing group without changing the projection's row identities.
130
+ rows.forEach((row) => {
131
+ if (!Predicate.isTagged(row, "AssistantPart") || row.group.type !== "context") return
132
+ row.group.refs.forEach((ref) => {
133
+ const content = resolveContent(input.projection.messageByID().get(ref.messageID), ref.partID)
134
+
135
+ if (content?.type !== "tool" || toolRule(content).layout !== "file" || content.state.status === "error") return
136
+ const part = `${ref.messageID}:${ref.partID}`
137
+ const key = patchGroupKeys.get(part)
138
+
139
+ if (key && !owners.has(key)) owners.set(key, part)
140
+ })
141
+ })
142
+
143
+ return owners
144
+ })
145
+
146
+ const runs = createMemo(() => {
147
+ const messages = input.projection.messageByID()
148
+ const context = input.projection.userContextByID()
149
+
150
+ const boundaries = [...messages.values()].filter((message) => !movedInPlace(message))
151
+
152
+ return userMessageRuns(input.projection.rows(), boundaries, (id) => {
153
+ const message = messages.get(id)
154
+ const user = context.get(id)
155
+
156
+ if (message?.type !== "user" || !user) return undefined
157
+ const status = input.actions?.pending?.status(id)
158
+ const presentation = input.presentation(message)
159
+
160
+ return {
161
+ kind: status === "steering" || status === "stranded" || status === "sending" ? "pending" : "sent",
162
+ agent: user.agent,
163
+ model: user.model,
164
+ text: !!(presentation?.displayText ?? message.text),
165
+ attachments: (message.files ?? []).some(attached) || !!presentation?.references?.length,
166
+ }
167
+ })
168
+ })
169
+
170
+ // A steer sent while the timeline is open grows in. Messages already there when a session loads, history loaded
171
+ // above them, and rows the virtualizer remounts appear as they are. Every row change syncs here, so the driver reuses
172
+ // its events and skips a sync whose inputs did not change.
173
+ let arrivals = INITIAL_STEER_ARRIVAL_STATE
174
+ const arrivalRendered = { type: "rendered" as const, messageID: "" }
175
+
176
+ const noRows: readonly TimelineRow.TimelineRow[] = []
177
+ const arrivalSync = { type: "sync" as const, sessionID: "", rows: noRows, busy: false }
178
+ const arrivalGrown = { type: "grown" as const, messageID: "" }
179
+
180
+ const syncArrivals = () => {
181
+ const sessionID = input.sessionID()
182
+ const rows = input.projection.rows()
183
+ // The input's pending status lands after its row, so a message sent while the session works counts as a steer.
184
+ const busy = input.status().type !== "idle"
185
+
186
+ if (sessionID === arrivalSync.sessionID && rows === arrivalSync.rows && busy === arrivalSync.busy) return
187
+ arrivalSync.sessionID = sessionID
188
+ arrivalSync.rows = rows
189
+ arrivalSync.busy = busy
190
+ arrivals = transitionSteerArrival(arrivals, arrivalSync)
191
+ }
192
+
193
+ createComputed(syncArrivals)
194
+ onCleanup(() => {
195
+ arrivals = transitionSteerArrival(arrivals, DISPOSED_STEER_ARRIVAL_EVENT)
196
+ })
197
+
198
+ // A row can render before the sync for the rows that hold it, so it syncs first.
199
+ const arriving = (messageID: string) =>
200
+ untrack(() => {
201
+ syncArrivals()
202
+
203
+ if (!shouldGrowUserMessage(arrivals, messageID)) return false
204
+ arrivalRendered.messageID = messageID
205
+ arrivals = transitionSteerArrival(arrivals, arrivalRendered)
206
+
207
+ return true
208
+ })
209
+
210
+ const grown = (messageID: string) => {
211
+ arrivalGrown.messageID = messageID
212
+ arrivals = transitionSteerArrival(arrivals, arrivalGrown)
213
+ }
214
+
215
+ // A run's gaps and meta lines snap while a steer arrives, because the arriving row grows in. Any other change, such
216
+ // as a steer delivered into the run above, springs every gap and meta line together, so the bubbles below hold still.
217
+ // Springs read this on every frame, so it holds for exactly as long as the grow runs.
218
+ const runSnaps = () =>
219
+ untrack(() => {
220
+ syncArrivals()
221
+
222
+ return shouldSnapUserRun(arrivals)
223
+ })
224
+
225
+ // The newest delivered prompt; reverting it undoes the last turn, so its menu calls the action Undo.
226
+ const latestSent = createMemo(
227
+ () =>
228
+ [...input.projection.messageByID().values()].findLast(
229
+ (message) => message.type === "user" && input.actions?.pending?.status(message.id) === undefined,
230
+ )?.id,
231
+ )
232
+
233
+ // Hovering a run's bubbles, or the gaps between them, shows the meta line its last bubble carries. Each bubble's
234
+ // body bridges the gaps to its neighbors, so moving between bubbles never hides the line, and an open menu keeps it
235
+ // while the pointer is on the menu.
236
+ const [hoveredMessage, setHoveredMessage] = createSignal<string>()
237
+ const [menuMessage, setMenuMessage] = createSignal<string>()
238
+
239
+ const runEnds = createMemo(() => {
240
+ const ends = new Map<string, string>()
241
+ const group: string[] = []
242
+ input.projection.rows().forEach((row) => {
243
+ if (!Predicate.isTagged(row, "UserMessage")) return
244
+ group.push(row.userMessageID)
245
+
246
+ if (runs().get(row.userMessageID)?.below) return
247
+ group.splice(0).forEach((id) => ends.set(id, row.userMessageID))
248
+ })
249
+
250
+ return ends
251
+ })
252
+
253
+ const runHovered = (messageID: string) => {
254
+ const ends = runEnds()
255
+
256
+ return [hoveredMessage(), menuMessage()].some((id) => !!id && ends.get(id) === messageID)
257
+ }
258
+
259
+ const bubble = (target: EventTarget | null) =>
260
+ target instanceof Element ? target.closest('[data-slot="user-message-body"]') : null
261
+
262
+ const hoverZone = (messageID: string) => ({
263
+ onPointerOver: (event: PointerEvent) => {
264
+ if (bubble(event.target)) setHoveredMessage(messageID)
265
+ },
266
+ onPointerOut: (event: PointerEvent) => {
267
+ const next = bubble(event.relatedTarget)
268
+
269
+ if (next && event.currentTarget instanceof Element && event.currentTarget.contains(next)) return
270
+ setHoveredMessage((current) => (current === messageID ? undefined : current))
271
+ },
272
+ })
273
+
274
+ const run = (messageID: string) =>
275
+ createMemo(() => runs().get(messageID), undefined, {
276
+ equals: (a, b) => a?.above === b?.above && a?.below === b?.below,
277
+ })
278
+
279
+ const phase = (messageID: string) => viewTurnPhase(input.projection.turnPhaseByID().get(messageID) ?? IDLE_TURN_PHASE)
280
+
281
+ const duration = (messageID: string) => {
282
+ const user = input.projection.messageByID().get(messageID)
283
+
284
+ if (user?.type !== "user") return null
285
+
286
+ const message = input.projection
287
+ .assistantMessagesByParent()
288
+ .get(messageID)
289
+ ?.findLast((message) => message.time.completed !== undefined)
290
+
291
+ if (message?.time.completed === undefined || message.time.completed < user.time.created) return undefined
292
+
293
+ return SessionTurn.duration(turns().messages, message, {
294
+ index: turns().indexes.get(message.id),
295
+ legacy: turns().legacy,
296
+ })
297
+ }
298
+
299
+ const copyContentID = (messageID: string) => {
300
+ if (phase(messageID).hideCopy) return null
301
+
302
+ const message = input.projection
303
+ .assistantMessagesByParent()
304
+ .get(messageID)
305
+ ?.findLast((message) => message.content.some((content) => content.type === "text" && !!content.text.trim()))
306
+
307
+ return message
308
+ ? contentEntries(message).findLast((entry) => entry.content.type === "text" && !!entry.content.text.trim())?.id
309
+ : undefined
310
+ }
311
+
312
+ const latestCopyTurn = createMemo(() =>
313
+ Array.from(input.projection.assistantMessagesByParent().keys()).findLast((id) => !!copyContentID(id)),
314
+ )
315
+
316
+ const padding = () => input.padding?.() ?? "px-4 md:px-6"
317
+
318
+ const indexGroupContents = (refs: PartRef[]) => {
319
+ const result = new Map<string, Map<string, SessionMessageAssistant["content"][number]>>()
320
+ refs.forEach((ref) => {
321
+ if (result.has(ref.messageID)) return
322
+ const contents = new Map<string, SessionMessageAssistant["content"][number]>()
323
+ const message = input.projection.messageByID().get(ref.messageID)
324
+
325
+ if (message?.type === "assistant") {
326
+ contentEntries(message).forEach((entry) => {
327
+ // Match resolveContent's first entry when content IDs repeat.
328
+ if (!contents.has(entry.id)) contents.set(entry.id, entry.content)
329
+ })
330
+ }
331
+
332
+ result.set(ref.messageID, contents)
333
+ })
334
+
335
+ return result
336
+ }
337
+
338
+ const renderAssistant = (row: Accessor<TimelineRow.AssistantPart>, onSizeChange?: () => void) => {
339
+ if (row().group.type === "context") {
340
+ const parts = createMemo(() => {
341
+ const group = row().group
342
+
343
+ if (group.type !== "context") return []
344
+ const contents = indexGroupContents(group.refs)
345
+ const streaming = phase(row().userMessageID).streamingReasoningRef
346
+
347
+ return group.refs.flatMap<ActivityGroupPart>((ref) => {
348
+ const content = contents.get(ref.messageID)?.get(ref.partID)
349
+
350
+ if (content?.type === "tool") {
351
+ patchPartKeys.set(content, `${ref.messageID}:${ref.partID}`)
352
+
353
+ return [content]
354
+ }
355
+
356
+ if (content?.type === "reasoning")
357
+ return [
358
+ {
359
+ ...content,
360
+ id: ref.partID,
361
+ streaming: sameRef(streaming, ref),
362
+ },
363
+ ]
364
+ const message = input.projection.messageByID().get(ref.messageID)
365
+
366
+ if (content?.type === "text" && message?.type === "assistant")
367
+ return [
368
+ {
369
+ type: "text",
370
+ id: ref.partID,
371
+ render: () => <AssistantContent message={message} content={content} contentID={ref.partID} />,
372
+ },
373
+ ]
374
+
375
+ const script =
376
+ message?.type === "assistant" ? scriptFileFact(message.content, ref.messageID, ref.partID) : undefined
377
+
378
+ if (script)
379
+ return [
380
+ {
381
+ type: "file",
382
+ id: ref.partID,
383
+ file: script,
384
+ render: () => (
385
+ <ScriptChanges
386
+ files={[script]}
387
+ render={PatchTool}
388
+ fileOpen={(path) => input.disclosure.value(`patch:${path}`) ?? diffOpens(input.timelineDetail())}
389
+ onFileOpenChange={(path, open) => input.disclosure.set(`patch:${path}`, open)}
390
+ onSizeChange={onSizeChange}
391
+ />
392
+ ),
393
+ },
394
+ ]
395
+
396
+ if (ref.messageID !== ref.partID || !message) return []
397
+ const event = noticeEvent(message)
398
+
399
+ if (event) return [{ type: "event", id: ref.partID, event }]
400
+
401
+ if (message.type !== "assistant" && message.type !== "user")
402
+ return [{ type: "notice", id: ref.partID, render: () => <Notice messageID={ref.messageID} grouped /> }]
403
+
404
+ return []
405
+ })
406
+ })
407
+
408
+ const key = () => `context:${row().group.key}`
409
+
410
+ return (
411
+ <div class="contents" data-notices-only={parts().every((part) => part.type === "notice") ? "" : undefined}>
412
+ <ContextGroup
413
+ parts={parts()}
414
+ patchGroupKey={(tools) => {
415
+ const parts = tools.map((tool) => patchPartKeys.get(tool)!)
416
+
417
+ // After a split, only the subgroup with the earliest surviving member keeps the old anchor.
418
+ const key =
419
+ parts
420
+ .map((part) => patchGroupKeys.get(part))
421
+ .find((key) => key !== undefined && parts.includes(patchOwners().get(key)!)) ?? parts[0]!
422
+
423
+ parts.forEach((part) => patchGroupKeys.set(part, key))
424
+
425
+ return key
426
+ }}
427
+ reasoningDefaultOpen={thoughtOpens(input.timelineDetail(), false)}
428
+ reasoningOpen={(id) => input.disclosure.value(id)}
429
+ onReasoningOpenChange={(id, open) => input.disclosure.set(id, open)}
430
+ toolDefaultOpen={(tool) => placeContent(tool, input.timelineDetail(), "next").opens}
431
+ toolOpen={(id) => input.disclosure.value(`${row().group.key}:tool:${id}`)}
432
+ onToolOpenChange={(id, open) => input.disclosure.set(`${row().group.key}:tool:${id}`, open)}
433
+ fileOpen={(path) => input.disclosure.value(`patch:${path}`) ?? diffOpens(input.timelineDetail())}
434
+ onFileOpenChange={(path, open) => input.disclosure.set(`patch:${path}`, open)}
435
+ open={input.disclosure.value(key()) === true}
436
+ onOpenChange={(open) => input.disclosure.set(key(), open)}
437
+ onSizeChange={onSizeChange}
438
+ onRevealShell={input.revealPart}
439
+ />
440
+ </div>
441
+ )
442
+ }
443
+
444
+ if (row().group.type === "thought") {
445
+ const parts = createMemo(() => {
446
+ const group = row().group
447
+
448
+ if (group.type !== "thought") return []
449
+ const contents = indexGroupContents(group.refs)
450
+
451
+ return group.refs.flatMap((ref) => {
452
+ const content = contents.get(ref.messageID)?.get(ref.partID)
453
+
454
+ return content?.type === "reasoning" ? [{ ...content, id: ref.partID }] : []
455
+ })
456
+ })
457
+
458
+ // Opening the thoughts is remembered by the first one, as it was while they were live.
459
+ const key = () => {
460
+ const group = row().group
461
+
462
+ return group.type === "thought" ? group.refs[0]!.partID : group.key
463
+ }
464
+
465
+ return (
466
+ <ThoughtRow
467
+ parts={parts()}
468
+ streaming={false}
469
+ defaultOpen={thoughtOpens(input.timelineDetail(), false)}
470
+ open={input.disclosure.value(key())}
471
+ onOpenChange={(open) => input.disclosure.set(key(), open)}
472
+ onContentRendered={onSizeChange}
473
+ />
474
+ )
475
+ }
476
+
477
+ if (row().group.type === "events" || row().group.type === "subagent") {
478
+ const events = createMemo(() => {
479
+ const group = row().group
480
+
481
+ if (group.type !== "events" && group.type !== "subagent") return []
482
+ const contents = indexGroupContents(group.refs)
483
+
484
+ // A call starts the work; a notice under its message's own ID reports it back.
485
+ return group.refs.flatMap((ref) => {
486
+ const message = input.projection.messageByID().get(ref.messageID)
487
+ const content = contents.get(ref.messageID)?.get(ref.partID)
488
+
489
+ const event =
490
+ ref.messageID === ref.partID
491
+ ? message && noticeEvent(message)
492
+ : content?.type === "tool"
493
+ ? toolEvent(content)
494
+ : undefined
495
+
496
+ return event ? [event] : []
497
+ })
498
+ })
499
+
500
+ if (row().group.type === "subagent") {
501
+ return (
502
+ <Show when={events()[0]}>
503
+ {(event) => (
504
+ <div data-component="timeline-subagent">
505
+ <TimelineEventItem event={event()} />
506
+ </div>
507
+ )}
508
+ </Show>
509
+ )
510
+ }
511
+
512
+ return (
513
+ <TimelineEventRow
514
+ events={events()}
515
+ open={input.disclosure.value(`events:${row().group.key}`) === true}
516
+ onOpenChange={(open) => {
517
+ input.disclosure.set(`events:${row().group.key}`, open)
518
+ onSizeChange?.()
519
+ }}
520
+ onRevealShell={input.revealPart}
521
+ />
522
+ )
523
+ }
524
+
525
+ if (row().group.type === "read") {
526
+ const tools = createMemo(() => {
527
+ const group = row().group
528
+
529
+ if (group.type !== "read") return []
530
+ const contents = indexGroupContents(group.refs)
531
+
532
+ return group.refs.flatMap((ref) => {
533
+ const content = contents.get(ref.messageID)?.get(ref.partID)
534
+
535
+ return content?.type === "tool" ? [content] : []
536
+ })
537
+ })
538
+
539
+ return (
540
+ <SessionReadToolGroup
541
+ tools={tools()}
542
+ names={2}
543
+ open={input.disclosure.value(row().group.key)}
544
+ onOpenChange={(open) => input.disclosure.set(row().group.key, open)}
545
+ onSizeChange={onSizeChange}
546
+ />
547
+ )
548
+ }
549
+
550
+ if (row().group.type === "file") {
551
+ const tools = createMemo(() => {
552
+ const group = row().group
553
+
554
+ if (group.type !== "file") return []
555
+ const contents = indexGroupContents(group.refs)
556
+
557
+ return group.refs.flatMap((ref) => {
558
+ const content = contents.get(ref.messageID)?.get(ref.partID)
559
+
560
+ return content?.type === "tool" ? [content] : []
561
+ })
562
+ })
563
+
564
+ // Direct changes and a script's changes in the order they happened.
565
+ const runs = createMemo(() => {
566
+ const group = row().group
567
+
568
+ if (group.type !== "file") return []
569
+ const contents = indexGroupContents(group.refs)
570
+
571
+ return fileRuns(
572
+ group.refs.flatMap<Extract<SessionMessageAssistant["content"][number], { type: "tool" }> | FileFact>(
573
+ (ref) => {
574
+ const content = contents.get(ref.messageID)?.get(ref.partID)
575
+
576
+ if (content?.type === "tool") return [content]
577
+ const message = input.projection.messageByID().get(ref.messageID)
578
+
579
+ const file =
580
+ message?.type === "assistant" ? scriptFileFact(message.content, ref.messageID, ref.partID) : undefined
581
+
582
+ return file ? [file] : []
583
+ },
584
+ ),
585
+ )
586
+ })
587
+
588
+ return (
589
+ <Show
590
+ when={runs().some((run) => run.type === "script")}
591
+ fallback={
592
+ <FileGroup
593
+ tools={tools()}
594
+ fileOpen={(path) =>
595
+ input.disclosure.value(`${row().group.key}:file:${path}`) ?? diffOpens(input.timelineDetail())
596
+ }
597
+ onFileOpenChange={(path, open) => input.disclosure.set(`${row().group.key}:file:${path}`, open)}
598
+ onSizeChange={onSizeChange}
599
+ />
600
+ }
601
+ >
602
+ <FileChangeRuns
603
+ runs={runs()}
604
+ render={PatchTool}
605
+ tools={(run) => (
606
+ <FileGroup
607
+ tools={run()}
608
+ fileOpen={(path) =>
609
+ input.disclosure.value(`${runDisclosureKey(row().group.key, run(), tools()[0])}:file:${path}`) ??
610
+ diffOpens(input.timelineDetail())
611
+ }
612
+ onFileOpenChange={(path, open) =>
613
+ input.disclosure.set(`${runDisclosureKey(row().group.key, run(), tools()[0])}:file:${path}`, open)
614
+ }
615
+ onSizeChange={onSizeChange}
616
+ />
617
+ )}
618
+ fileOpen={(path) =>
619
+ input.disclosure.value(`${row().group.key}:file:${path}`) ?? diffOpens(input.timelineDetail())
620
+ }
621
+ onFileOpenChange={(path, open) => input.disclosure.set(`${row().group.key}:file:${path}`, open)}
622
+ onSizeChange={onSizeChange}
623
+ />
624
+ </Show>
625
+ )
626
+ }
627
+
628
+ const ref = createMemo(() => {
629
+ const group = row().group
630
+
631
+ return group.type === "part" ? group.ref : undefined
632
+ })
633
+
634
+ const message = createMemo(() => {
635
+ const current = ref()
636
+ const message = current ? input.projection.messageByID().get(current.messageID) : undefined
637
+
638
+ return message?.type === "assistant" ? message : undefined
639
+ })
640
+
641
+ const content = createMemo(() => {
642
+ const current = ref()
643
+
644
+ return current ? resolveContent(message(), current.partID) : undefined
645
+ })
646
+
647
+ const defaultOpen = createMemo(() => {
648
+ const item = content()
649
+
650
+ return item ? placeContent(item, input.timelineDetail(), "next").opens : undefined
651
+ })
652
+
653
+ // Only the finished turn's footer part derives them, and only while the host shows sources.
654
+ const turnSourcesValue = createMemo(() => {
655
+ const current = ref()
656
+
657
+ if (!sourcesHost?.enabled || !current || copyContentID(row().userMessageID) !== current.partID) return undefined
658
+
659
+ const value = turnSources(
660
+ input.projection.assistantMessagesByParent().get(row().userMessageID) ?? emptyAssistantMessages,
661
+ )
662
+
663
+ return value.steps.length > 0 ? value : undefined
664
+ })
665
+
666
+ const turnTokensPerSecond = createMemo(() => {
667
+ const current = ref()
668
+
669
+ if (!current || copyContentID(row().userMessageID) !== current.partID) return undefined
670
+
671
+ const messages = input.projection.assistantMessagesByParent().get(row().userMessageID) ?? emptyAssistantMessages
672
+
673
+ const last = messages.at(-1)
674
+
675
+ if (!last) return undefined
676
+
677
+ return SessionTurn.tokensPerSecond(turns().messages, last, {
678
+ index: turns().indexes.get(last.id),
679
+ legacy: turns().legacy,
680
+ })
681
+ })
682
+
683
+ const disclosureKey = () => (content()?.type === "reasoning" ? ref()!.partID : row().group.key)
684
+
685
+ return (
686
+ <Show when={message()}>
687
+ {(message) => (
688
+ <Show when={content()}>
689
+ {(content) => (
690
+ <AssistantContent
691
+ message={message()}
692
+ content={content()}
693
+ contentID={ref()!.partID}
694
+ showAssistantCopyPartID={copyContentID(row().userMessageID)}
695
+ keepCopyVisible={latestCopyTurn() === row().userMessageID}
696
+ turnDurationMs={duration(row().userMessageID)}
697
+ turnTokensPerSecond={turnTokensPerSecond()}
698
+ sources={turnSourcesValue()}
699
+ onOpenSources={() => sourcesHost?.open(row().userMessageID)}
700
+ defaultOpen={defaultOpen()}
701
+ toolOpen={input.disclosure.value(disclosureKey()) ?? defaultOpen()}
702
+ onToolOpenChange={(open) => input.disclosure.set(disclosureKey(), open)}
703
+ onContentRendered={onSizeChange}
704
+ />
705
+ )}
706
+ </Show>
707
+ )}
708
+ </Show>
709
+ )
710
+ }
711
+
712
+ const notice = (message: SessionMessageInfo) => {
713
+ if (message.type === "agent-switched" || message.type === "model-switched") return undefined
714
+
715
+ if (message.type === "skill") return { label: i18n.t("ui.tool.skill"), data: message.name }
716
+
717
+ if (message.type === "system") {
718
+ const sources = Array.isArray(message.metadata?.instructionSources)
719
+ ? message.metadata.instructionSources.filter(Predicate.isString)
720
+ : undefined
721
+
722
+ if (message.metadata?.notice === "instructions" && sources?.length)
723
+ return { label: i18n.t("ui.sessionTimeline.notice.instructionsUpdated"), items: sources }
724
+ const prefix = "Instructions updated: "
725
+
726
+ if (message.description?.startsWith(prefix)) {
727
+ const keys = message.description
728
+ .slice(prefix.length)
729
+ .split(",")
730
+ .map((s) => s.trim())
731
+ .filter(Boolean)
732
+
733
+ return {
734
+ label: i18n.t("ui.sessionTimeline.notice.instructionsUpdated"),
735
+ items: keys,
736
+ }
737
+ }
738
+
739
+ return { label: message.description ?? message.text }
740
+ }
741
+
742
+ if (message.type !== "synthetic") return undefined
743
+
744
+ if (message.metadata?.notice === "restart") return { label: i18n.t("ui.sessionTimeline.notice.restart") }
745
+
746
+ if (message.description === "Continuing after restart")
747
+ return { label: i18n.t("ui.sessionTimeline.notice.restart") }
748
+ const source = message.metadata?.source
749
+
750
+ if (source === "subagent" || source === "shell") {
751
+ const agent = message.metadata?.agent
752
+
753
+ const actor =
754
+ source === "shell"
755
+ ? i18n.t("ui.tool.shell")
756
+ : ((Predicate.isString(agent) ? taskAgentName(agent, data.store.agent) : undefined) ??
757
+ i18n.t("ui.tool.agent.default"))
758
+
759
+ const state = message.metadata?.state
760
+ const outcome: Outcome = state === "error" || state === "cancelled" ? state : "completed"
761
+
762
+ return {
763
+ label: i18n.t(outcomeNoticeKey(outcome), { actor }),
764
+ data: message.description,
765
+ outcome,
766
+ icon: outcomeNoticeIcon(outcome),
767
+ }
768
+ }
769
+
770
+ if (source === "codemode") {
771
+ const state = message.metadata?.state
772
+ const outcome: Outcome = state === "error" || state === "cancelled" ? state : "completed"
773
+ const jobID = message.metadata?.jobID
774
+
775
+ return {
776
+ label: i18n.t(outcomeNoticeKey(outcome), { actor: "Script" }),
777
+ data: Predicate.isString(jobID) ? jobID : undefined,
778
+ outcome,
779
+ icon: outcomeNoticeIcon(outcome),
780
+ }
781
+ }
782
+
783
+ return { label: message.description ?? message.text }
784
+ }
785
+
786
+ const gaps = createMemo(() => timelineGaps(input.projection.rows(), input.projection.messageByID()))
787
+
788
+ // Each row's only space is the gap below it, which sets the row below apart. A message joining the user's message
789
+ // above sits its run's 4 px below it instead, which its turn gap springs to.
790
+ const gap = (row: TimelineRow.TimelineRow) => {
791
+ if (Predicate.isTagged(row, "TurnGap") && runs().get(row.userMessageID)?.above) return undefined
792
+
793
+ return gaps().get(TimelineRow.key(row))
794
+ }
795
+
796
+ const Frame = (props: { row: FramedTimelineRow; grow?: boolean; children: JSX.Element }) => (
797
+ <div
798
+ ref={(el) => {
799
+ if (props.grow) growIn(el, () => grown(props.row.userMessageID))
800
+ onCleanup(trackNestedRails(el))
801
+ }}
802
+ id={Predicate.isTagged(props.row, "UserMessage") ? input.anchor?.(props.row.userMessageID) : undefined}
803
+ data-message-id={props.row.userMessageID}
804
+ data-timeline="next"
805
+ data-timeline-row={props.row._tag}
806
+ data-timeline-gap={gap(props.row)}
807
+ classList={{
808
+ "min-w-0 w-full max-w-full": true,
809
+ "md:max-w-session md:mx-auto": input.centered?.(),
810
+ }}
811
+ >
812
+ <div data-component="session-turn" class="min-w-0 w-full relative" style={{ height: "auto" }}>
813
+ {props.children}
814
+ </div>
815
+ </div>
816
+ )
817
+
818
+ function Notice(props: { messageID: string; grouped?: boolean }) {
819
+ const inset = () => (props.grouped ? "" : padding())
820
+ const message = createMemo(() => input.projection.messageByID().get(props.messageID))
821
+
822
+ const compaction = createMemo(() => {
823
+ const value = message()
824
+
825
+ return value?.type === "compaction" ? value : undefined
826
+ })
827
+
828
+ const compactionError = createMemo(() => {
829
+ const value = compaction()
830
+
831
+ if (value?.status !== "failed") return ""
832
+
833
+ return unwrapErrorMessage(value.error.message)
834
+ })
835
+
836
+ const moved = createMemo(() => {
837
+ const value = message()
838
+
839
+ return value?.type === "location-switched" ? value : undefined
840
+ })
841
+
842
+ // Switching the agent or the model changes who answers next, so both draw as the same separator.
843
+ const switched = createMemo(() => {
844
+ const value = message()
845
+
846
+ if (value?.type === "agent-switched")
847
+ return {
848
+ label: i18n.t("ui.timeline.notice.agentSwitched", { agent: capitalizeAgent(value.agent) }),
849
+ providerID: undefined,
850
+ variant: undefined,
851
+ }
852
+
853
+ if (value?.type !== "model-switched") return undefined
854
+ const match = data.store.provider?.all?.get(value.model.providerID)
855
+ const variantOnly = value.previous?.providerID === value.model.providerID && value.previous.id === value.model.id
856
+ const variant = value.model.variant ?? "default"
857
+
858
+ // A model's faster and slower speeds are models of their own ("gpt-5.5-fast"), so moving between them is a
859
+ // change of speed.
860
+ const info = match?.models?.[value.model.id]
861
+ const before = value.previous?.providerID === value.model.providerID && match?.models?.[value.previous.id]
862
+
863
+ if (
864
+ info &&
865
+ before &&
866
+ !variantOnly &&
867
+ (before.speed?.base ?? value.previous?.id) === (info.speed?.base ?? value.model.id)
868
+ )
869
+ return {
870
+ providerID: value.model.providerID,
871
+ variant: undefined,
872
+ label: info.speed
873
+ ? i18n.t("ui.sessionTimeline.notice.speedSwitched", { speed: info.speed.id })
874
+ : i18n.t("ui.sessionTimeline.notice.speedStandard"),
875
+ }
876
+
877
+ return {
878
+ providerID: value.model.providerID,
879
+ variant: variantOnly ? undefined : value.model.variant,
880
+ label: variantOnly
881
+ ? variant === "default"
882
+ ? i18n.t("ui.sessionTimeline.notice.variantDefault")
883
+ : i18n.t("ui.sessionTimeline.notice.variantSwitched", { variant })
884
+ : i18n.t("ui.sessionTimeline.notice.modelSwitched", {
885
+ model: match?.models?.[value.model.id]?.name ?? value.model.id,
886
+ }),
887
+ }
888
+ })
889
+
890
+ // The goal the user set shows as their own message. Core describes it as "Goal: <objective>".
891
+ const goal = createMemo(() => {
892
+ const value = message()
893
+
894
+ if (!goalMessage(value)) return
895
+
896
+ return value.description?.replace(/^Goal: /, "") || undefined
897
+ })
898
+
899
+ const content = createMemo(() => {
900
+ const value = message()
901
+
902
+ return value && !goal() ? notice(value) : undefined
903
+ })
904
+
905
+ const childID = createMemo(() => {
906
+ const value = message()
907
+
908
+ if (value?.type !== "synthetic" || value.metadata?.source !== "subagent") return
909
+ const id = value.metadata.childID
910
+
911
+ if (Predicate.isString(id) && id) return id
912
+ })
913
+
914
+ const href = createMemo(() => {
915
+ const id = childID()
916
+
917
+ if (id) return data.sessionHref?.(id)
918
+ })
919
+
920
+ // A finished background shell jumps to its call, as its activity pill does.
921
+ const shellID = createMemo(() => {
922
+ const value = message()
923
+
924
+ if (!input.revealPart || value?.type !== "synthetic" || value.metadata?.source !== "shell") return
925
+ const id = value.metadata.shellID
926
+
927
+ if (Predicate.isString(id) && id) return id
928
+ })
929
+
930
+ const clickable = createMemo(() => !!shellID() || !!(childID() && (data.navigateToSession || href())))
931
+
932
+ const open = () => {
933
+ const shell = shellID()
934
+
935
+ if (shell) return void input.revealPart?.(shell)
936
+ const id = childID()
937
+
938
+ if (id) data.navigateToSession?.(id)
939
+ }
940
+
941
+ const navigate = (event: MouseEvent) => {
942
+ if (!shellID() && (!childID() || !data.navigateToSession)) return
943
+
944
+ if (event.button !== 0 || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return
945
+ event.preventDefault()
946
+ open()
947
+ }
948
+
949
+ const navigateKey = (event: KeyboardEvent) => {
950
+ if (!clickable() || href()) return
951
+
952
+ if (event.key !== "Enter" && event.key !== " ") return
953
+ event.preventDefault()
954
+ open()
955
+ }
956
+
957
+ return (
958
+ <>
959
+ <Show when={goal()}>
960
+ {(objective) => (
961
+ <div data-slot="session-turn-message-container" class={`w-full ${inset()}`}>
962
+ <div data-component="user-message" data-goal="">
963
+ <div data-slot="user-message-body">
964
+ <div data-slot="user-message-text" dir="auto">
965
+ <Badge data-slot="user-message-goal-badge" dir="ltr">
966
+ /goal
967
+ </Badge>
968
+ <bdi>{objective()}</bdi>
969
+ </div>
970
+ </div>
971
+ </div>
972
+ </div>
973
+ )}
974
+ </Show>
975
+ <Show when={!goal() && compaction()}>
976
+ {(message) => (
977
+ <div data-slot="session-turn-message-container" class={`w-full ${inset()}`}>
978
+ <div data-slot="session-turn-compaction">
979
+ <CompactionMessage message={message()} error={compactionError()} />
980
+ </div>
981
+ </div>
982
+ )}
983
+ </Show>
984
+ <Show
985
+ when={moved()}
986
+ fallback={
987
+ <Show
988
+ when={switched()}
989
+ fallback={
990
+ <Show when={content()}>
991
+ {(content) => (
992
+ <Show
993
+ when={content().items?.length}
994
+ fallback={
995
+ <Dynamic
996
+ component={href() ? "a" : "div"}
997
+ data-slot="session-timeline-notice"
998
+ data-outcome={content().outcome}
999
+ class={`block w-full truncate ${props.grouped ? "py-1" : ""} text-13-regular leading-text-compact text-v2-text-text-faint ${inset()}`}
1000
+ classList={{ "cursor-pointer hover:text-v2-text-text-base": clickable() }}
1001
+ href={href()}
1002
+ role={clickable() && !href() ? (shellID() ? "button" : "link") : undefined}
1003
+ tabIndex={clickable() && !href() ? 0 : undefined}
1004
+ onClick={navigate}
1005
+ onKeyDown={navigateKey}
1006
+ >
1007
+ <Show when={content().icon}>
1008
+ {(icon) => (
1009
+ <Icon
1010
+ name={icon()}
1011
+ size="normal"
1012
+ class={`inline-block align-top me-1.5 ${outcomeNoticeColor(content().outcome)}`}
1013
+ />
1014
+ )}
1015
+ </Show>
1016
+ <bdi dir="auto" class={`font-[530] ${outcomeNoticeColor(content().outcome)}`}>
1017
+ {content().label}
1018
+ </bdi>
1019
+ <Show when={content().data}>
1020
+ {(data) => (
1021
+ <span>
1022
+ {" · "}
1023
+ <bdi dir="auto">{data()}</bdi>
1024
+ </span>
1025
+ )}
1026
+ </Show>
1027
+ </Dynamic>
1028
+ }
1029
+ >
1030
+ <div data-slot="session-timeline-notice" class={`w-full ${inset()}`}>
1031
+ <div class="flex min-h-5 min-w-0 items-center gap-2 overflow-hidden">
1032
+ <bdi
1033
+ dir="auto"
1034
+ class="shrink-0 text-[13px] font-[530] leading-text-compact tracking-[-0.04px] text-v2-text-text-faint"
1035
+ >
1036
+ {content().label}
1037
+ </bdi>
1038
+ <For each={content().items}>
1039
+ {(item) => (
1040
+ <bdi
1041
+ dir="auto"
1042
+ class="min-w-0 truncate text-[13px] font-[440] leading-text-compact tracking-[-0.04px] text-v2-text-text-faint"
1043
+ >
1044
+ {item}
1045
+ </bdi>
1046
+ )}
1047
+ </For>
1048
+ </div>
1049
+ </div>
1050
+ </Show>
1051
+ )}
1052
+ </Show>
1053
+ }
1054
+ >
1055
+ {(switched) => (
1056
+ <div data-slot="session-timeline-notice" data-type={message()?.type} class={`w-full ${inset()}`}>
1057
+ <Separator label={switched().label} providerID={switched().providerID} variant={switched().variant} />
1058
+ </div>
1059
+ )}
1060
+ </Show>
1061
+ }
1062
+ >
1063
+ {(message) => (
1064
+ <div data-slot="session-timeline-notice" data-type="location-switched" class={`w-full ${inset()}`}>
1065
+ <Separator
1066
+ label={i18n.t("ui.sessionTimeline.notice.movedTo")}
1067
+ value={message().location.directory}
1068
+ tooltip={i18n.t("ui.sessionTimeline.notice.movedTooltip")}
1069
+ />
1070
+ </div>
1071
+ )}
1072
+ </Show>
1073
+ </>
1074
+ )
1075
+ }
1076
+
1077
+ function Shell(props: { messageID: string }) {
1078
+ const message = createMemo(() => {
1079
+ const value = input.projection.messageByID().get(props.messageID)
1080
+
1081
+ return value?.type === "shell" ? value : undefined
1082
+ })
1083
+
1084
+ return (
1085
+ <Show when={message()}>
1086
+ {(message) => (
1087
+ <div data-slot="session-turn-message-container" class={`w-full ${padding()}`}>
1088
+ <ShellMessage message={message()} />
1089
+ </div>
1090
+ )}
1091
+ </Show>
1092
+ )
1093
+ }
1094
+
1095
+ function TurnDiff(props: { row: TimelineRow.TurnDiff; onSizeChange?: () => void }) {
1096
+ // Until the diff loads, and if it fails, list the paths the turn's steps recorded, without change counts.
1097
+ const turn = () => ({ sessionID: input.sessionID(), from: props.row.from })
1098
+ const state = createMemo(() => data.turnDiff?.state(turn()))
1099
+
1100
+ const diffs = () => {
1101
+ const current = state()
1102
+
1103
+ return current?.status === "ready" ? current.diffs : undefined
1104
+ }
1105
+
1106
+ const failed = () => state()?.status === "failed"
1107
+ const paths = () => diffs()?.map((diff) => diff.file) ?? props.row.files
1108
+ const showAllKey = () => `turn-diff:${props.row.messageID}`
1109
+ const showAll = () => input.disclosure.value(showAllKey()) === true
1110
+ const limit = <T,>(items: readonly T[]) => (showAll() ? items : items.slice(0, turnDiffFileLimit))
1111
+ const overflow = () => paths().length > turnDiffFileLimit
1112
+ const fileKey = (path: string) => `turn-diff:${props.row.messageID}:file:${path}`
1113
+
1114
+ // Loads once per turn. A failure settles until the row remounts or the reader retries.
1115
+ createEffect(() => data.turnDiff?.load(turn()))
1116
+
1117
+ return (
1118
+ <Show when={data.turnDiff && paths().length > 0}>
1119
+ <div data-slot="session-turn-diffs" class="flex flex-col gap-2">
1120
+ <div class="flex h-6 min-w-0 items-center gap-2">
1121
+ <span class="shrink-0 text-14-medium text-v2-text-text-base tabular-nums">
1122
+ {i18n.plural("ui.sessionTurn.diffs.changed", paths().length)}
1123
+ </span>
1124
+ <DiffChanges changes={[...(diffs() ?? [])]} />
1125
+ <Show when={failed()}>
1126
+ <span
1127
+ data-slot="session-turn-diffs-error"
1128
+ class="min-w-0 truncate text-13-regular leading-text-compact text-v2-text-text-faint"
1129
+ >
1130
+ {i18n.t("ui.sessionTurn.diffs.failed")}
1131
+ </span>
1132
+ </Show>
1133
+ <Show when={failed() || overflow()}>
1134
+ <div class="ms-auto flex shrink-0 items-center gap-3">
1135
+ <Show when={failed()}>
1136
+ <button
1137
+ type="button"
1138
+ data-slot="session-turn-diffs-retry"
1139
+ class="text-14-regular text-v2-text-text-accent"
1140
+ onClick={() => data.turnDiff?.load(turn())}
1141
+ >
1142
+ {i18n.t("ui.sessionTurn.diffs.retry")}
1143
+ </button>
1144
+ </Show>
1145
+ <Show when={overflow()}>
1146
+ <button
1147
+ type="button"
1148
+ class="text-14-regular text-v2-text-text-accent"
1149
+ onClick={() => input.disclosure.set(showAllKey(), !showAll())}
1150
+ >
1151
+ {showAll() ? i18n.t("ui.sessionTurn.diffs.showLess") : i18n.t("ui.sessionTurn.diffs.showAll")}
1152
+ </button>
1153
+ </Show>
1154
+ </div>
1155
+ </Show>
1156
+ </div>
1157
+ <PatchTool
1158
+ tool="patch"
1159
+ input={{}}
1160
+ metadata={{ files: limit(diffs() ?? []) }}
1161
+ pendingFiles={diffs() ? undefined : limit(props.row.files)}
1162
+ status="completed"
1163
+ fileOpen={(path: string) => input.disclosure.value(fileKey(path))}
1164
+ onFileOpenChange={(path: string, open: boolean) => input.disclosure.set(fileKey(path), open)}
1165
+ deferContent
1166
+ virtualizeDiff={false}
1167
+ onContentRendered={props.onSizeChange}
1168
+ />
1169
+ </div>
1170
+ </Show>
1171
+ )
1172
+ }
1173
+
1174
+ // Holds the gap above its turn's first row, so the gap arrives and leaves with the turn and no row beside it
1175
+ // changes. A run's messages sit as close as the iOS app's (4 px) instead; that gap springs as a message joins or
1176
+ // leaves.
1177
+ function TurnGap(props: { messageID: string; gap?: TimelineGap }) {
1178
+ let element: HTMLDivElement | undefined
1179
+ const joined = run(props.messageID)
1180
+ springStyle(
1181
+ () => element,
1182
+ () => ({ height: joined()?.above ? 4 : 0 }),
1183
+ (el, value) => {
1184
+ el.style.height = `${value.height}px`
1185
+ },
1186
+ // Closing up as a message joins is instant; the joining message grows in instead.
1187
+ { ...userRunSpring, snap: () => !!joined()?.above && runSnaps() },
1188
+ )
1189
+
1190
+ return (
1191
+ <div
1192
+ ref={element}
1193
+ data-timeline="next"
1194
+ data-timeline-row="TurnGap"
1195
+ data-timeline-gap={props.gap}
1196
+ aria-hidden="true"
1197
+ style={{ height: untrack(joined)?.above ? "4px" : "0px" }}
1198
+ />
1199
+ )
1200
+ }
1201
+
1202
+ const render = (row: Accessor<TimelineRow.TimelineRow>, onSizeChange?: () => void) => {
1203
+ if (Predicate.isTagged(row(), "TurnGap")) return <TurnGap messageID={row().userMessageID} gap={gap(row())} />
1204
+
1205
+ // The host owns live status and renders this slot itself.
1206
+ if (Predicate.isTagged(row(), "Activity")) return null
1207
+
1208
+ if (Predicate.isTagged(row(), "UserMessage")) {
1209
+ const current = () => {
1210
+ const value = row()
1211
+
1212
+ if (!Predicate.isTagged(value, "UserMessage")) throw new Error("Expected a user-message timeline row")
1213
+
1214
+ return value
1215
+ }
1216
+
1217
+ const message = createMemo(() => {
1218
+ const value = input.projection.messageByID().get(current().userMessageID)
1219
+
1220
+ return value?.type === "user" ? value : undefined
1221
+ })
1222
+
1223
+ const context = createMemo(() => input.projection.userContextByID().get(current().userMessageID))
1224
+ const joined = run(current().userMessageID)
1225
+ const grow = arriving(current().userMessageID)
1226
+
1227
+ return (
1228
+ <Frame row={current()} grow={grow}>
1229
+ <Show when={message()}>
1230
+ {(message) => {
1231
+ const presentation = () => input.presentation(message())
1232
+
1233
+ return (
1234
+ <div
1235
+ data-slot="session-turn-message-container"
1236
+ class={`w-full ${padding()}`}
1237
+ {...hoverZone(message().id)}
1238
+ >
1239
+ <div data-slot="session-turn-message-content" aria-live="off">
1240
+ <SessionUserMessage
1241
+ sessionID={input.sessionID()}
1242
+ message={message()}
1243
+ displayText={presentation()?.displayText}
1244
+ comments={presentation()?.comments}
1245
+ references={presentation()?.references}
1246
+ voice={presentation()?.voice}
1247
+ historicalAgent={context()?.agent ?? ""}
1248
+ historicalModel={context()?.model ?? { id: "", providerID: "" }}
1249
+ actions={input.actions}
1250
+ run={joined()}
1251
+ latest={latestSent() === message().id}
1252
+ runSnaps={runSnaps}
1253
+ runHovered={runHovered(message().id)}
1254
+ onMenuOpenChange={(open) =>
1255
+ setMenuMessage((current) =>
1256
+ open ? message().id : current === message().id ? undefined : current,
1257
+ )
1258
+ }
1259
+ fold={input.foldUserMessages?.()}
1260
+ inlineQuotes={input.inlineQuotes?.()}
1261
+ expanded={input.disclosure.value(`user-expanded:${message().id}`)}
1262
+ onExpandedChange={(open) => input.disclosure.set(`user-expanded:${message().id}`, open)}
1263
+ />
1264
+ </div>
1265
+ </div>
1266
+ )
1267
+ }}
1268
+ </Show>
1269
+ </Frame>
1270
+ )
1271
+ }
1272
+
1273
+ if (Predicate.isTagged(row(), "Shell")) {
1274
+ const current = () => {
1275
+ const value = row()
1276
+
1277
+ if (!Predicate.isTagged(value, "Shell")) throw new Error("Expected a shell timeline row")
1278
+
1279
+ return value
1280
+ }
1281
+
1282
+ return (
1283
+ <Frame row={current()}>
1284
+ <Shell messageID={current().messageID} />
1285
+ </Frame>
1286
+ )
1287
+ }
1288
+
1289
+ if (Predicate.isTagged(row(), "Notice")) {
1290
+ const current = () => {
1291
+ const value = row()
1292
+
1293
+ if (!Predicate.isTagged(value, "Notice")) throw new Error("Expected a notice timeline row")
1294
+
1295
+ return value
1296
+ }
1297
+
1298
+ return (
1299
+ <Frame row={current()}>
1300
+ <Notice messageID={current().messageID} />
1301
+ </Frame>
1302
+ )
1303
+ }
1304
+
1305
+ if (Predicate.isTagged(row(), "TurnDivider")) {
1306
+ const current = () => {
1307
+ const value = row()
1308
+
1309
+ if (!Predicate.isTagged(value, "TurnDivider")) throw new Error("Expected a turn-divider timeline row")
1310
+
1311
+ return value
1312
+ }
1313
+
1314
+ return (
1315
+ <Frame row={current()}>
1316
+ <div data-slot="session-turn-message-container" class={`w-full ${padding()}`}>
1317
+ <div data-slot="session-turn-compaction">
1318
+ <Separator label={i18n.t("ui.message.interrupted")} />
1319
+ </div>
1320
+ </div>
1321
+ </Frame>
1322
+ )
1323
+ }
1324
+
1325
+ if (Predicate.isTagged(row(), "CompactionQueued")) {
1326
+ const current = () => {
1327
+ const value = row()
1328
+
1329
+ if (!Predicate.isTagged(value, "CompactionQueued")) throw new Error("Expected a queued-compaction timeline row")
1330
+
1331
+ return value
1332
+ }
1333
+
1334
+ return (
1335
+ <Frame row={current()}>
1336
+ <div data-slot="session-turn-message-container" class={`w-full ${padding()}`}>
1337
+ <div data-slot="session-turn-compaction">
1338
+ <CompactionQueued />
1339
+ </div>
1340
+ </div>
1341
+ </Frame>
1342
+ )
1343
+ }
1344
+
1345
+ if (Predicate.isTagged(row(), "AssistantPart")) {
1346
+ const current = () => {
1347
+ const value = row()
1348
+
1349
+ if (!Predicate.isTagged(value, "AssistantPart")) throw new Error("Expected an assistant-part timeline row")
1350
+
1351
+ return value
1352
+ }
1353
+
1354
+ // Construct once per row key, not inside JSX that reruns when group refs change.
1355
+ const content = renderAssistant(current, onSizeChange)
1356
+
1357
+ return (
1358
+ <Frame row={current()}>
1359
+ <div data-slot="session-turn-message-container" class={`w-full ${padding()}`}>
1360
+ <div data-slot="session-turn-assistant-content">{content}</div>
1361
+ </div>
1362
+ </Frame>
1363
+ )
1364
+ }
1365
+
1366
+ if (Predicate.isTagged(row(), "Thinking")) {
1367
+ const current = () => {
1368
+ const value = row()
1369
+
1370
+ if (!Predicate.isTagged(value, "Thinking")) throw new Error("Expected a thinking timeline row")
1371
+
1372
+ return value
1373
+ }
1374
+
1375
+ const parts = createMemo(() => {
1376
+ const streaming = phase(current().userMessageID).streamingReasoningRef
1377
+
1378
+ return [...(current().before ?? []), current().ref].flatMap((ref) => {
1379
+ const content = resolveContent(input.projection.messageByID().get(ref.messageID), ref.partID)
1380
+
1381
+ return content?.type === "reasoning"
1382
+ ? [{ ...content, id: ref.partID, streaming: sameRef(streaming, ref) }]
1383
+ : []
1384
+ })
1385
+ })
1386
+
1387
+ const disclosureKey = () => (current().before?.[0] ?? current().ref).partID
1388
+
1389
+ // The live thought stands in for the status line, with the thoughts it follows. It reads as Thinking until
1390
+ // something else shows, and the row it settles into starts closed.
1391
+
1392
+ return (
1393
+ <Frame row={current()}>
1394
+ <div data-slot="session-turn-message-container" class={`w-full ${padding()}`}>
1395
+ <div data-slot="session-turn-thinking-row" data-live-slot="">
1396
+ <Show when={parts().length > 0}>
1397
+ <ThoughtRow
1398
+ parts={parts()}
1399
+ streaming
1400
+ defaultOpen={thoughtOpens(input.timelineDetail(), true)}
1401
+ open={input.disclosure.value(disclosureKey()) ?? thoughtOpens(input.timelineDetail(), true)}
1402
+ onOpenChange={(open) => input.disclosure.set(disclosureKey(), open)}
1403
+ onContentRendered={onSizeChange}
1404
+ />
1405
+ </Show>
1406
+ </div>
1407
+ </div>
1408
+ </Frame>
1409
+ )
1410
+ }
1411
+
1412
+ if (Predicate.isTagged(row(), "Worked")) {
1413
+ const current = () => {
1414
+ const value = row()
1415
+
1416
+ if (!Predicate.isTagged(value, "Worked")) throw new Error("Expected a worked timeline row")
1417
+
1418
+ return value
1419
+ }
1420
+
1421
+ const label = createMemo(() => {
1422
+ const id = current().userMessageID
1423
+ const user = input.projection.messageByID().get(id)
1424
+
1425
+ const ms = workedDuration(
1426
+ user?.type === "user" ? user : undefined,
1427
+ input.projection.assistantMessagesByParent().get(id) ?? emptyAssistantMessages,
1428
+ )
1429
+
1430
+ if (ms === undefined) return i18n.t("ui.timeline.activity.workedUnknown")
1431
+ const total = Math.round(ms / 1000)
1432
+ const numfmt = new Intl.NumberFormat(i18n.locale())
1433
+
1434
+ return i18n.t("ui.timeline.activity.worked", {
1435
+ duration:
1436
+ total < 60
1437
+ ? i18n.t("ui.message.duration.seconds", { count: numfmt.format(total) })
1438
+ : i18n.t("ui.message.duration.minutesSeconds", {
1439
+ minutes: numfmt.format(Math.floor(total / 60)),
1440
+ seconds: numfmt.format(total % 60),
1441
+ }),
1442
+ })
1443
+ })
1444
+
1445
+ return (
1446
+ <Frame row={current()}>
1447
+ <div data-slot="session-turn-message-container" class={`w-full ${padding()}`}>
1448
+ <div class="text-13-regular leading-text-compact text-v2-text-text-muted">{label()}</div>
1449
+ </div>
1450
+ </Frame>
1451
+ )
1452
+ }
1453
+
1454
+ if (Predicate.isTagged(row(), "TurnDiff")) {
1455
+ const current = () => {
1456
+ const value = row()
1457
+
1458
+ if (!Predicate.isTagged(value, "TurnDiff")) throw new Error("Expected a turn-diff timeline row")
1459
+
1460
+ return value
1461
+ }
1462
+
1463
+ return (
1464
+ <Frame row={current()}>
1465
+ <div data-slot="session-turn-message-container" class={`w-full ${padding()}`}>
1466
+ <TurnDiff row={current()} onSizeChange={onSizeChange} />
1467
+ </div>
1468
+ </Frame>
1469
+ )
1470
+ }
1471
+
1472
+ if (Predicate.isTagged(row(), "Retry")) {
1473
+ const current = () => {
1474
+ const value = row()
1475
+
1476
+ if (!Predicate.isTagged(value, "Retry")) throw new Error("Expected a retry timeline row")
1477
+
1478
+ return value
1479
+ }
1480
+
1481
+ return (
1482
+ <Frame row={current()}>
1483
+ <div data-slot="session-turn-message-container" class={`w-full ${padding()}`}>
1484
+ <SessionRetry
1485
+ status={{ type: "retry", attempt: current().attempt, message: current().message, next: current().next }}
1486
+ show={input.projection.activeMessageID() === current().userMessageID}
1487
+ />
1488
+ </div>
1489
+ </Frame>
1490
+ )
1491
+ }
1492
+
1493
+ const current = () => {
1494
+ const value = row()
1495
+
1496
+ if (!Predicate.isTagged(value, "Error")) throw new Error("Expected an error timeline row")
1497
+
1498
+ return value
1499
+ }
1500
+
1501
+ const usageLimit = createMemo(() => {
1502
+ const kind = current().kind
1503
+
1504
+ if (kind !== "free-limit" && kind !== "go-limit") return
1505
+
1506
+ const keys =
1507
+ kind === "go-limit"
1508
+ ? ({ title: "ui.sessionTurn.goLimit.title", lineReset: "ui.sessionTurn.goLimit.lineReset" } as const)
1509
+ : ({ title: "ui.sessionTurn.freeLimit.title", lineReset: "ui.sessionTurn.freeLimit.lineReset" } as const)
1510
+
1511
+ const at = current().resetAt
1512
+
1513
+ if (at === undefined || !Number.isFinite(at) || Number.isNaN(new Date(at).getTime())) return i18n.t(keys.title)
1514
+
1515
+ const now = Date.now()
1516
+ const sameDay = new Date(at).toDateString() === new Date(now).toDateString() && at - now < 86_400_000
1517
+
1518
+ const time = new Intl.DateTimeFormat(
1519
+ i18n.locale(),
1520
+ sameDay ? { timeStyle: "short" } : { dateStyle: "medium", timeStyle: "short" },
1521
+ ).format(at)
1522
+
1523
+ return i18n.t(keys.lineReset, { time })
1524
+ })
1525
+
1526
+ // A budget pauses paid models, or only the ones it covers, until it resets at the start of a month.
1527
+ const budgetLimit = createMemo(() => {
1528
+ const kind = current().kind
1529
+
1530
+ if (kind !== "budget-limit" && kind !== "model-budget-limit") return
1531
+ const at = current().resetAt
1532
+
1533
+ const time =
1534
+ at === undefined
1535
+ ? undefined
1536
+ : new Intl.DateTimeFormat(i18n.locale(), {
1537
+ month: "short",
1538
+ day: "numeric",
1539
+ hour: "numeric",
1540
+ minute: "2-digit",
1541
+ timeZoneName: "shortOffset",
1542
+ }).format(at)
1543
+
1544
+ if (kind === "budget-limit")
1545
+ return {
1546
+ text: time
1547
+ ? i18n.t("ui.sessionTurn.budgetLimit.all", { time })
1548
+ : i18n.t("ui.sessionTurn.budgetLimit.allUntilReset"),
1549
+ action: i18n.t("ui.sessionTurn.budgetLimit.useFreeModel"),
1550
+ }
1551
+
1552
+ return {
1553
+ text: time
1554
+ ? i18n.t("ui.sessionTurn.budgetLimit.models", { time })
1555
+ : i18n.t("ui.sessionTurn.budgetLimit.modelsUntilReset"),
1556
+ action: i18n.t("ui.sessionTurn.budgetLimit.switchModel"),
1557
+ }
1558
+ })
1559
+
1560
+ return (
1561
+ <Frame row={current()}>
1562
+ <div data-slot="session-turn-message-container" class={`w-full ${padding()}`}>
1563
+ <Switch fallback={<SessionError message={current().text} />}>
1564
+ <Match when={budgetLimit()}>
1565
+ {(notice) => (
1566
+ <div
1567
+ role="status"
1568
+ class="text-[13px] font-[440] leading-text-compact tracking-[-0.04px] text-v2-text-text-muted"
1569
+ >
1570
+ {notice().text}
1571
+ <Show when={input.actions?.chooseModel}>
1572
+ {(choose) => (
1573
+ <>
1574
+ <span aria-hidden="true">{" · "}</span>
1575
+ <button
1576
+ type="button"
1577
+ class="font-[530] text-v2-text-text-base hover:underline focus-visible:underline focus-visible:outline-none"
1578
+ onClick={() => choose()()}
1579
+ >
1580
+ {notice().action}
1581
+ </button>
1582
+ </>
1583
+ )}
1584
+ </Show>
1585
+ </div>
1586
+ )}
1587
+ </Match>
1588
+ <Match when={usageLimit()}>
1589
+ {(text) => (
1590
+ <div
1591
+ role="status"
1592
+ class="text-[13px] font-[440] leading-text-compact tracking-[-0.04px] text-v2-text-text-muted"
1593
+ >
1594
+ {text()}
1595
+ </div>
1596
+ )}
1597
+ </Match>
1598
+ </Switch>
1599
+ </div>
1600
+ </Frame>
1601
+ )
1602
+ }
1603
+
1604
+ function Row(props: { row: Accessor<TimelineRow.TimelineRow>; onSizeChange?: () => void }) {
1605
+ return (
1606
+ <Show when={TimelineRow.key(props.row())} keyed>
1607
+ {(_key) => render(props.row, props.onSizeChange)}
1608
+ </Show>
1609
+ )
1610
+ }
1611
+
1612
+ return { Row, gap }
1613
+ }
1614
+
1615
+ function capitalizeAgent(agent: string) {
1616
+ return agent.slice(0, 1).toUpperCase() + agent.slice(1)
1617
+ }
1618
+
1619
+ function outcomeNoticeIcon(outcome: Outcome) {
1620
+ if (outcome === "error") return "warning"
1621
+
1622
+ if (outcome === "cancelled") return "circle-ban-sign"
1623
+ }
1624
+
1625
+ function outcomeNoticeColor(outcome: Outcome | undefined) {
1626
+ if (!outcome) return ""
1627
+
1628
+ if (outcome === "error") return "text-v2-state-fg-danger"
1629
+
1630
+ if (outcome === "cancelled")
1631
+ return "text-[var(--v2-yellow-900)] [[data-color-scheme=dark]_&]:text-v2-state-fg-warning"
1632
+
1633
+ return "text-v2-text-text-code-accent"
1634
+ }
1635
+
1636
+ function outcomeNoticeKey(state: string | undefined) {
1637
+ if (state === "error") return "ui.sessionTimeline.notice.failed"
1638
+
1639
+ if (state === "cancelled") return "ui.sessionTimeline.notice.cancelled"
1640
+
1641
+ return "ui.sessionTimeline.notice.finished"
1642
+ }
1643
+
1644
+ /**
1645
+ * Grows a row from nothing to its natural height while its bubble fades in; rows below follow its edge. A pending
1646
+ * steer's meta line stays in view: a steer that starts a pending run shows its line once the row has settled, and one
1647
+ * that joins a pending run carries the run's line down along the growing edge while the bubble fades into the space.
1648
+ */
1649
+ function growIn(el: HTMLElement, onDone: () => void) {
1650
+ if (prefersReducedMotion()) return onDone()
1651
+ const height = Spring.fromDuration(0, { duration: 0.2, bounce: 0 })
1652
+ const opacity = Spring.fromDuration(0, { duration: 0.3, bounce: 0 }).set(1)
1653
+ const content = el.firstElementChild instanceof HTMLElement ? el.firstElementChild : undefined
1654
+ // The row's children mount after its ref runs, so the whole row starts hidden and hands its fade to the bubble on the
1655
+ // first frame.
1656
+ let faded = content ? [content] : []
1657
+ let meta: HTMLElement | undefined
1658
+ let carried = false
1659
+ let natural = 0
1660
+ let line = 0
1661
+ el.style.height = "0px"
1662
+ el.toggleAttribute("data-timeline-grow", true)
1663
+ faded.forEach((element) => (element.style.opacity = "0"))
1664
+
1665
+ const remove = frameLoop.addMeasured(
1666
+ () => {
1667
+ if (content && !meta) {
1668
+ meta = content.querySelector<HTMLElement>('[data-slot="user-message-copy-wrapper"]') ?? undefined
1669
+
1670
+ const bubbles = [
1671
+ ...content.querySelectorAll<HTMLElement>(
1672
+ '[data-slot="user-message-attachments"], [data-slot="user-message-body"]',
1673
+ ),
1674
+ ]
1675
+
1676
+ if (meta && bubbles.length > 0) {
1677
+ carried = !!content.querySelector('[data-component="user-message"][data-pending][data-run-above]')
1678
+
1679
+ if (!carried) meta.style.visibility = "hidden"
1680
+ content.style.opacity = ""
1681
+ faded = bubbles
1682
+ }
1683
+ }
1684
+
1685
+ natural = content ? content.offsetHeight : 0
1686
+ line = meta ? meta.offsetHeight + parseFloat(getComputedStyle(meta).marginTop) : 0
1687
+ },
1688
+ (dt) => {
1689
+ if (!el.isConnected) return true
1690
+
1691
+ height.set(natural)
1692
+ const value = height.step(dt)
1693
+ const progress = natural > 0 ? value / natural : 1
1694
+ const shown = Math.min(1, Math.max(0, opacity.step(dt)))
1695
+
1696
+ // A carried line passes over the bubble's place, so the bubble shows only as the line clears it.
1697
+ faded.forEach((element) => (element.style.opacity = `${carried ? shown * progress : shown}`))
1698
+
1699
+ // The line starts exactly where the run's line just was, just above this row, and settles below the bubble.
1700
+ if (meta && carried) meta.style.transform = `translateY(${-(natural - line + 8) * (1 - progress)}px)`
1701
+
1702
+ if (!height.resting || !opacity.resting) {
1703
+ el.style.height = height.resting ? "" : `${value}px`
1704
+
1705
+ return true
1706
+ }
1707
+
1708
+ el.style.height = ""
1709
+ faded.forEach((element) => (element.style.opacity = ""))
1710
+
1711
+ if (meta) {
1712
+ meta.style.visibility = ""
1713
+ meta.style.transform = ""
1714
+ }
1715
+
1716
+ el.toggleAttribute("data-timeline-grow", false)
1717
+ onDone()
1718
+
1719
+ return false
1720
+ },
1721
+ )
1722
+
1723
+ // A row that unmounts mid-grow, as the virtualizer recycles it, ends its grow too; a second report is a no-op.
1724
+ onCleanup(() => {
1725
+ remove()
1726
+ onDone()
1727
+ })
1728
+ }