@golba98/codexa 1.0.1

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 (226) hide show
  1. package/README.md +320 -0
  2. package/bin/codexa.js +445 -0
  3. package/package.json +45 -0
  4. package/scripts/audit-codexa-capabilities.mjs +466 -0
  5. package/scripts/smoke-terminal-bench.mjs +35 -0
  6. package/src/app.tsx +4561 -0
  7. package/src/appRenderStability.test.ts +131 -0
  8. package/src/commands/handler.test.ts +643 -0
  9. package/src/commands/handler.ts +875 -0
  10. package/src/config/launchArgs.test.ts +158 -0
  11. package/src/config/launchArgs.ts +186 -0
  12. package/src/config/layeredConfig.test.ts +143 -0
  13. package/src/config/layeredConfig.ts +836 -0
  14. package/src/config/persistence.test.ts +110 -0
  15. package/src/config/persistence.ts +311 -0
  16. package/src/config/runtimeConfig.test.ts +218 -0
  17. package/src/config/runtimeConfig.ts +554 -0
  18. package/src/config/settings.test.ts +155 -0
  19. package/src/config/settings.ts +401 -0
  20. package/src/config/toml-serialize.ts +98 -0
  21. package/src/config/trustStore.test.ts +29 -0
  22. package/src/config/trustStore.ts +68 -0
  23. package/src/core/attachments.test.ts +155 -0
  24. package/src/core/attachments.ts +71 -0
  25. package/src/core/auth/codexAuth.test.ts +68 -0
  26. package/src/core/auth/codexAuth.ts +359 -0
  27. package/src/core/cleanupFastFail.test.ts +76 -0
  28. package/src/core/cleanupFastFail.ts +67 -0
  29. package/src/core/clipboard.ts +24 -0
  30. package/src/core/codex.ts +124 -0
  31. package/src/core/codexExecArgs.test.ts +195 -0
  32. package/src/core/codexExecArgs.ts +152 -0
  33. package/src/core/codexLaunch.test.ts +205 -0
  34. package/src/core/codexLaunch.ts +162 -0
  35. package/src/core/codexPrompt.test.ts +252 -0
  36. package/src/core/codexPrompt.ts +428 -0
  37. package/src/core/executables/claudeExecutable.ts +63 -0
  38. package/src/core/executables/codexExecutable.test.ts +212 -0
  39. package/src/core/executables/codexExecutable.ts +159 -0
  40. package/src/core/executables/executableResolver.test.ts +129 -0
  41. package/src/core/executables/executableResolver.ts +138 -0
  42. package/src/core/executables/geminiExecutable.test.ts +116 -0
  43. package/src/core/executables/geminiExecutable.ts +78 -0
  44. package/src/core/executables/pathSanityScan.test.ts +47 -0
  45. package/src/core/githubDiagnostics.test.ts +92 -0
  46. package/src/core/githubDiagnostics.ts +222 -0
  47. package/src/core/hollowResponseFormat.test.ts +58 -0
  48. package/src/core/hollowResponseFormat.ts +39 -0
  49. package/src/core/inputDebug.ts +51 -0
  50. package/src/core/launchContext.test.ts +157 -0
  51. package/src/core/launchContext.ts +266 -0
  52. package/src/core/models/codexCapabilities.test.ts +45 -0
  53. package/src/core/models/codexCapabilities.ts +95 -0
  54. package/src/core/models/codexModelCapabilities.test.ts +246 -0
  55. package/src/core/models/codexModelCapabilities.ts +571 -0
  56. package/src/core/models/modelSpecs.test.ts +283 -0
  57. package/src/core/models/modelSpecs.ts +300 -0
  58. package/src/core/perf/profiler.ts +125 -0
  59. package/src/core/perf/renderDebug.test.ts +230 -0
  60. package/src/core/perf/renderDebug.ts +373 -0
  61. package/src/core/planStorage.test.ts +143 -0
  62. package/src/core/planStorage.ts +141 -0
  63. package/src/core/process/CommandRunner.test.ts +105 -0
  64. package/src/core/process/CommandRunner.ts +269 -0
  65. package/src/core/process/processValidation.ts +101 -0
  66. package/src/core/projectInstructions.test.ts +50 -0
  67. package/src/core/projectInstructions.ts +54 -0
  68. package/src/core/providerLauncher/launcher.test.ts +238 -0
  69. package/src/core/providerLauncher/launcher.ts +203 -0
  70. package/src/core/providerLauncher/registry.test.ts +324 -0
  71. package/src/core/providerLauncher/registry.ts +253 -0
  72. package/src/core/providerLauncher/types.ts +84 -0
  73. package/src/core/providerLauncher/workspaceConfig.test.ts +638 -0
  74. package/src/core/providerLauncher/workspaceConfig.ts +407 -0
  75. package/src/core/providerRuntime/anthropic.test.ts +1120 -0
  76. package/src/core/providerRuntime/anthropic.ts +576 -0
  77. package/src/core/providerRuntime/capabilityProfile.test.ts +311 -0
  78. package/src/core/providerRuntime/capabilityProfile.ts +288 -0
  79. package/src/core/providerRuntime/claudeCodeDiscovery.ts +446 -0
  80. package/src/core/providerRuntime/contextMetadata.test.ts +468 -0
  81. package/src/core/providerRuntime/contextMetadata.ts +409 -0
  82. package/src/core/providerRuntime/gemini.test.ts +437 -0
  83. package/src/core/providerRuntime/gemini.ts +784 -0
  84. package/src/core/providerRuntime/lmstudio.test.ts +168 -0
  85. package/src/core/providerRuntime/lmstudio.ts +118 -0
  86. package/src/core/providerRuntime/local.test.ts +787 -0
  87. package/src/core/providerRuntime/local.ts +754 -0
  88. package/src/core/providerRuntime/models.ts +150 -0
  89. package/src/core/providerRuntime/reasoning.ts +17 -0
  90. package/src/core/providerRuntime/registry.test.ts +233 -0
  91. package/src/core/providerRuntime/registry.ts +203 -0
  92. package/src/core/providerRuntime/types.ts +103 -0
  93. package/src/core/providers/codexJsonStream.test.ts +148 -0
  94. package/src/core/providers/codexJsonStream.ts +305 -0
  95. package/src/core/providers/codexSubprocess.test.ts +68 -0
  96. package/src/core/providers/codexSubprocess.ts +372 -0
  97. package/src/core/providers/codexTranscript.test.ts +284 -0
  98. package/src/core/providers/codexTranscript.ts +695 -0
  99. package/src/core/providers/openaiNative.ts +13 -0
  100. package/src/core/providers/registry.ts +21 -0
  101. package/src/core/providers/types.ts +59 -0
  102. package/src/core/terminal/terminalCapabilities.test.ts +93 -0
  103. package/src/core/terminal/terminalCapabilities.ts +100 -0
  104. package/src/core/terminal/terminalControl.test.ts +75 -0
  105. package/src/core/terminal/terminalControl.ts +147 -0
  106. package/src/core/terminal/terminalSanitize.test.ts +22 -0
  107. package/src/core/terminal/terminalSanitize.ts +147 -0
  108. package/src/core/terminal/terminalSelection.test.ts +42 -0
  109. package/src/core/terminal/terminalSelection.ts +66 -0
  110. package/src/core/terminal/terminalTitle.test.ts +328 -0
  111. package/src/core/terminal/terminalTitle.ts +483 -0
  112. package/src/core/workspaceActivity.test.ts +163 -0
  113. package/src/core/workspaceActivity.ts +380 -0
  114. package/src/core/workspaceGuard.test.ts +151 -0
  115. package/src/core/workspaceGuard.ts +288 -0
  116. package/src/core/workspaceRoot.test.ts +23 -0
  117. package/src/core/workspaceRoot.ts +47 -0
  118. package/src/exec.test.ts +13 -0
  119. package/src/exec.ts +72 -0
  120. package/src/headless/execArgs.test.ts +147 -0
  121. package/src/headless/execArgs.ts +294 -0
  122. package/src/headless/execRunner.test.ts +434 -0
  123. package/src/headless/execRunner.ts +304 -0
  124. package/src/index.test.tsx +618 -0
  125. package/src/index.tsx +296 -0
  126. package/src/session/appSession.test.ts +897 -0
  127. package/src/session/appSession.ts +761 -0
  128. package/src/session/chatLifecycle.test.ts +64 -0
  129. package/src/session/chatLifecycle.ts +951 -0
  130. package/src/session/liveRenderScheduler.test.ts +201 -0
  131. package/src/session/liveRenderScheduler.ts +214 -0
  132. package/src/session/planFlow.test.ts +103 -0
  133. package/src/session/planFlow.ts +149 -0
  134. package/src/session/planTranscript.test.ts +65 -0
  135. package/src/session/planTranscript.ts +15 -0
  136. package/src/session/promptRunSchedule.test.ts +36 -0
  137. package/src/session/promptRunSchedule.ts +26 -0
  138. package/src/session/types.ts +228 -0
  139. package/src/test/runtimeTestUtils.ts +14 -0
  140. package/src/types/react-dom.d.ts +3 -0
  141. package/src/ui/ActionRequiredBlock.tsx +38 -0
  142. package/src/ui/ActivityBars.tsx +68 -0
  143. package/src/ui/ActivityIndicator.test.tsx +58 -0
  144. package/src/ui/ActivityIndicator.tsx +58 -0
  145. package/src/ui/AgentBlock.test.ts +6 -0
  146. package/src/ui/AgentBlock.tsx +130 -0
  147. package/src/ui/AnimatedStatusText.test.ts +16 -0
  148. package/src/ui/AnimatedStatusText.tsx +69 -0
  149. package/src/ui/AppShell.test.tsx +1739 -0
  150. package/src/ui/AppShell.tsx +698 -0
  151. package/src/ui/AttachmentImportPanel.test.tsx +204 -0
  152. package/src/ui/AttachmentImportPanel.tsx +98 -0
  153. package/src/ui/AuthPanel.tsx +113 -0
  154. package/src/ui/BackendPicker.tsx +28 -0
  155. package/src/ui/BottomComposer.test.ts +674 -0
  156. package/src/ui/BottomComposer.tsx +1028 -0
  157. package/src/ui/CodexLogo.tsx +55 -0
  158. package/src/ui/DashCard.tsx +82 -0
  159. package/src/ui/Markdown.test.ts +157 -0
  160. package/src/ui/Markdown.tsx +310 -0
  161. package/src/ui/ModePicker.tsx +27 -0
  162. package/src/ui/ModelPicker.tsx +31 -0
  163. package/src/ui/ModelPickerProviderScope.test.tsx +411 -0
  164. package/src/ui/ModelPickerScreen.test.tsx +99 -0
  165. package/src/ui/ModelPickerScreen.tsx +416 -0
  166. package/src/ui/ModelPickerState.test.tsx +151 -0
  167. package/src/ui/ModelReasoningPicker.test.tsx +447 -0
  168. package/src/ui/ModelReasoningPicker.tsx +458 -0
  169. package/src/ui/Panel.tsx +51 -0
  170. package/src/ui/PermissionsPanel.tsx +78 -0
  171. package/src/ui/PlanActionPicker.tsx +119 -0
  172. package/src/ui/PlanReviewPanel.test.tsx +267 -0
  173. package/src/ui/PlanReviewPanel.tsx +212 -0
  174. package/src/ui/PromptCardBorder.test.tsx +161 -0
  175. package/src/ui/ProviderPicker.test.tsx +289 -0
  176. package/src/ui/ProviderPicker.tsx +321 -0
  177. package/src/ui/ProviderShortcut.test.tsx +143 -0
  178. package/src/ui/ReasoningPicker.tsx +46 -0
  179. package/src/ui/RunFooter.tsx +65 -0
  180. package/src/ui/SelectionPanel.tsx +67 -0
  181. package/src/ui/SettingsPanel.test.tsx +233 -0
  182. package/src/ui/SettingsPanel.tsx +156 -0
  183. package/src/ui/Spinner.tsx +25 -0
  184. package/src/ui/StaticIntroItem.tsx +54 -0
  185. package/src/ui/StaticTranscriptItem.tsx +56 -0
  186. package/src/ui/TextEntryPanel.tsx +139 -0
  187. package/src/ui/ThemePicker.tsx +31 -0
  188. package/src/ui/ThinkingBlock.tsx +100 -0
  189. package/src/ui/Timeline.test.ts +2067 -0
  190. package/src/ui/Timeline.tsx +1472 -0
  191. package/src/ui/TimelineNavigation.test.tsx +201 -0
  192. package/src/ui/TopHeader.test.tsx +239 -0
  193. package/src/ui/TopHeader.tsx +257 -0
  194. package/src/ui/TurnGroup.test.tsx +365 -0
  195. package/src/ui/TurnGroup.tsx +657 -0
  196. package/src/ui/busyStatusAnimation.test.ts +30 -0
  197. package/src/ui/busyStatusAnimation.ts +11 -0
  198. package/src/ui/commandNormalize.test.ts +142 -0
  199. package/src/ui/commandNormalize.ts +66 -0
  200. package/src/ui/diffRenderer.test.ts +102 -0
  201. package/src/ui/diffRenderer.ts +116 -0
  202. package/src/ui/focus.ts +61 -0
  203. package/src/ui/focusFlow.test.tsx +1098 -0
  204. package/src/ui/inputBuffer.test.ts +151 -0
  205. package/src/ui/inputBuffer.ts +203 -0
  206. package/src/ui/layout.test.ts +145 -0
  207. package/src/ui/layout.ts +287 -0
  208. package/src/ui/modeDisplay.test.ts +42 -0
  209. package/src/ui/modeDisplay.ts +52 -0
  210. package/src/ui/outputPipeline.ts +64 -0
  211. package/src/ui/progressEntries.ts +156 -0
  212. package/src/ui/runActivityView.test.ts +89 -0
  213. package/src/ui/runActivityView.ts +37 -0
  214. package/src/ui/runLifecycleView.test.tsx +237 -0
  215. package/src/ui/slashCommands.ts +41 -0
  216. package/src/ui/statusRenderIsolation.test.tsx +654 -0
  217. package/src/ui/terminalAnswerFormat.test.ts +19 -0
  218. package/src/ui/terminalAnswerFormat.ts +128 -0
  219. package/src/ui/textLayout.test.ts +18 -0
  220. package/src/ui/textLayout.ts +338 -0
  221. package/src/ui/theme.tsx +395 -0
  222. package/src/ui/themeFlow.test.ts +53 -0
  223. package/src/ui/themeFlow.ts +41 -0
  224. package/src/ui/timelineMeasure.ts +3088 -0
  225. package/src/ui/timelineMeasureCache.test.ts +986 -0
  226. package/src/ui/useThrottledValue.ts +31 -0
@@ -0,0 +1,1472 @@
1
+ import React, { memo, useEffect, useMemo, useRef, useState } from "react";
2
+ import { Box, Text, useInput, useStdin } from "ink";
3
+ import {
4
+ getRunPlanText,
5
+ type AssistantEvent,
6
+ type ErrorEvent,
7
+ type RunEvent,
8
+ type ShellEvent,
9
+ type SystemEvent,
10
+ type TimelineEvent,
11
+ type UIState,
12
+ type UserPromptEvent,
13
+ } from "../session/types.js";
14
+ import { APP_VERSION } from "../config/settings.js";
15
+ import type { CodexAuthState } from "../core/auth/codexAuth.js";
16
+ import { getAuthStateLabel } from "../core/auth/codexAuth.js";
17
+ import * as renderDebug from "../core/perf/renderDebug.js";
18
+ import { getShellWidth, type Layout, type StartupHeaderMode } from "./layout.js";
19
+ import type { TimelineRow, TimelineSnapshot, TimelineTone } from "./timelineMeasure.js";
20
+ import { buildStableTimelineSnapshot, buildTimelineSnapshot } from "./timelineMeasure.js";
21
+ import { resolveTurnRunPhase, type TurnOpacity, type TurnRunPhase } from "./TurnGroup.js";
22
+ import { useTheme } from "./theme.js";
23
+
24
+ // ─── Types & constants ────────────────────────────────────────────────────────
25
+
26
+ interface TimelineProps {
27
+ staticEvents: TimelineEvent[];
28
+ activeEvents: TimelineEvent[];
29
+ layout: Layout;
30
+ uiState: UIState;
31
+ viewportRows: number;
32
+ verboseMode?: boolean;
33
+ authState?: CodexAuthState;
34
+ workspaceLabel?: string;
35
+ workspaceRoot?: string | null;
36
+ mouseCapture?: boolean;
37
+ onMouseActivity?: () => void;
38
+ contentSized?: boolean;
39
+ }
40
+
41
+ type StandaloneTimelineEvent = SystemEvent | ErrorEvent | ShellEvent;
42
+
43
+ interface TurnTimelineItem {
44
+ type: "turn";
45
+ turnId: number;
46
+ turnIndex: number;
47
+ user: UserPromptEvent | null;
48
+ run: RunEvent | null;
49
+ assistant: AssistantEvent | null;
50
+ }
51
+
52
+ interface EventTimelineItem {
53
+ type: "event";
54
+ event: StandaloneTimelineEvent;
55
+ }
56
+
57
+ export type TimelineItem = TurnTimelineItem | EventTimelineItem;
58
+
59
+ export interface TurnRenderState {
60
+ opacity: TurnOpacity;
61
+ question: string | null;
62
+ runPhase: TurnRunPhase;
63
+ }
64
+
65
+ interface TurnRenderTimelineItem {
66
+ key: string;
67
+ type: "turn";
68
+ padded: boolean;
69
+ item: TurnTimelineItem;
70
+ renderState: TurnRenderState;
71
+ }
72
+
73
+ interface EventRenderTimelineItem {
74
+ key: string;
75
+ type: "event";
76
+ padded: boolean;
77
+ event: StandaloneTimelineEvent;
78
+ }
79
+
80
+ export interface IntroRenderTimelineItem {
81
+ key: string;
82
+ type: "intro";
83
+ padded: boolean;
84
+ intro: {
85
+ version: string;
86
+ layoutMode: Layout["mode"];
87
+ startupHeaderMode?: StartupHeaderMode;
88
+ authLabel: string;
89
+ workspaceLabel: string;
90
+ };
91
+ }
92
+
93
+ export type RenderTimelineItem = IntroRenderTimelineItem | TurnRenderTimelineItem | EventRenderTimelineItem;
94
+
95
+ const WHEEL_SCROLL_STEP = 3;
96
+ // Re-enter follow-tail mode when the user scrolls within this many rows of the
97
+ // tail, preventing a "stuck just above bottom" state after a near-end wheel scroll.
98
+ const NEAR_BOTTOM_THRESHOLD = 3;
99
+ const PAGE_UP_KEY_INPUTS = new Set(["\u001b[5~", "\u001b[[5~"]);
100
+ const PAGE_DOWN_KEY_INPUTS = new Set(["\u001b[6~", "\u001b[[6~"]);
101
+ const HOME_KEY_INPUTS = new Set(["\u001b[H", "\u001b[1~", "\u001bOH"]);
102
+ const END_KEY_INPUTS = new Set(["\u001b[F", "\u001b[4~", "\u001bOF"]);
103
+ const CTRL_HOME_KEY_INPUTS = new Set(["\u001b[1;5H", "\u001b[H"]);
104
+ const CTRL_END_KEY_INPUTS = new Set(["\u001b[1;5F", "\u001b[F"]);
105
+ const SGR_WHEEL_EVENT_PATTERN = /\u001b\[<(\d+);(\d+);(\d+)([Mm])/g;
106
+ const STABLE_RENDER_ENABLED = process.env.CODEXA_STABLE_RENDER !== "0";
107
+
108
+ type TimelineNavigationAction = "pageUp" | "pageDown" | "home" | "end" | "wheelUp" | "wheelDown";
109
+
110
+ export interface TimelineViewportState {
111
+ anchorRow: number;
112
+ followTail: boolean;
113
+ unseenItems: number;
114
+ unseenRows: number;
115
+ frozenSnapshot: TimelineSnapshot | null;
116
+ }
117
+
118
+ interface FinalizeContinuityOptions {
119
+ previousTotalRows: number;
120
+ viewportRows: number;
121
+ }
122
+
123
+ // ─── Viewport helpers ────────────────────────────────────────────────────────
124
+
125
+ function isStandaloneEvent(event: TimelineEvent): event is StandaloneTimelineEvent {
126
+ return event.type === "system" || event.type === "error" || event.type === "shell";
127
+ }
128
+
129
+ function getActiveTurnId(uiState: UIState): number | null {
130
+ return uiState.kind === "THINKING"
131
+ || uiState.kind === "RESPONDING"
132
+ || uiState.kind === "ANSWER_VISIBLE"
133
+ || uiState.kind === "AWAITING_USER_ACTION"
134
+ || uiState.kind === "ERROR"
135
+ ? uiState.turnId
136
+ : null;
137
+ }
138
+
139
+ function isBusyUiState(uiState: UIState): boolean {
140
+ return uiState.kind === "THINKING"
141
+ || uiState.kind === "RESPONDING"
142
+ || uiState.kind === "ANSWER_VISIBLE"
143
+ || uiState.kind === "SHELL_RUNNING";
144
+ }
145
+
146
+ function getRunningTurnIds(events: TimelineEvent[]): number[] {
147
+ return events
148
+ .filter((event): event is RunEvent => event.type === "run" && event.status === "running")
149
+ .map((event) => event.turnId);
150
+ }
151
+
152
+ function getFinalizedTurnIds(events: TimelineEvent[]): number[] {
153
+ return events
154
+ .filter((event): event is RunEvent => event.type === "run" && event.status !== "running")
155
+ .map((event) => event.turnId);
156
+ }
157
+
158
+ function latestFinalizedRunEndsWithPlan(events: TimelineEvent[]): boolean {
159
+ for (let index = events.length - 1; index >= 0; index -= 1) {
160
+ const event = events[index];
161
+ if (!event || event.type !== "run" || event.status === "running") {
162
+ continue;
163
+ }
164
+
165
+ const lastStreamItem = (event.streamItems ?? [])
166
+ .slice()
167
+ .sort((left, right) => left.streamSeq - right.streamSeq)
168
+ .at(-1);
169
+ return lastStreamItem?.kind === "plan"
170
+ && event.plan?.status === "completed"
171
+ && getRunPlanText(event.plan).trim().length > 0;
172
+ }
173
+
174
+ return false;
175
+ }
176
+
177
+ function hasFinalizeTransition(params: {
178
+ previousRunningTurnIds: number[];
179
+ nextRunningTurnIds: number[];
180
+ nextFinalizedTurnIds: number[];
181
+ previousBusy: boolean;
182
+ nextBusy: boolean;
183
+ }): boolean {
184
+ if (!params.previousBusy || params.nextBusy) return false;
185
+ return params.previousRunningTurnIds.some((turnId) =>
186
+ !params.nextRunningTurnIds.includes(turnId)
187
+ && params.nextFinalizedTurnIds.includes(turnId)
188
+ );
189
+ }
190
+
191
+ function isHomeInput(input: string): boolean {
192
+ return HOME_KEY_INPUTS.has(input);
193
+ }
194
+
195
+ function isEndInput(input: string): boolean {
196
+ return END_KEY_INPUTS.has(input);
197
+ }
198
+
199
+ function rawIncludesAny(raw: string, inputs: ReadonlySet<string>): boolean {
200
+ for (const input of inputs) {
201
+ if (raw.includes(input)) {
202
+ return true;
203
+ }
204
+ }
205
+ return false;
206
+ }
207
+
208
+ function clampAnchorRow(anchorRow: number, totalRows: number): number {
209
+ if (totalRows <= 0) {
210
+ return 0;
211
+ }
212
+
213
+ return Math.max(0, Math.min(anchorRow, totalRows - 1));
214
+ }
215
+
216
+ export function isNearBottom(anchorRow: number, totalRows: number): boolean {
217
+ return totalRows <= 0 || anchorRow >= totalRows - 1 - NEAR_BOTTOM_THRESHOLD;
218
+ }
219
+
220
+ function getFirstPageAnchor(totalRows: number, viewportRows: number): number {
221
+ if (totalRows <= 0) {
222
+ return 0;
223
+ }
224
+ return Math.min(totalRows - 1, Math.max(0, viewportRows - 1));
225
+ }
226
+
227
+ // ─── Timeline item builders ───────────────────────────────────────────────────
228
+
229
+ export function buildTimelineItems(events: TimelineEvent[]): TimelineItem[] {
230
+ const items: TimelineItem[] = [];
231
+ const turns = new Map<number, TurnTimelineItem>();
232
+ let nextTurnIndex = 1;
233
+
234
+ for (const event of events) {
235
+ if (isStandaloneEvent(event)) {
236
+ items.push({ type: "event", event });
237
+ continue;
238
+ }
239
+
240
+ const turnId = event.turnId;
241
+ let turn = turns.get(turnId);
242
+ if (!turn) {
243
+ turn = {
244
+ type: "turn",
245
+ turnId,
246
+ turnIndex: nextTurnIndex++,
247
+ user: null,
248
+ run: null,
249
+ assistant: null,
250
+ };
251
+ turns.set(turnId, turn);
252
+ items.push(turn);
253
+ }
254
+
255
+ if (event.type === "user") {
256
+ turn.user = event;
257
+ } else if (event.type === "run") {
258
+ turn.run = event;
259
+ } else if (event.type === "assistant") {
260
+ turn.assistant = event;
261
+ }
262
+ }
263
+
264
+ return items.filter((item) => item.type === "event" || item.user !== null);
265
+ }
266
+
267
+ export function resolveTurnOpacity(turnIds: number[], turnId: number, activeTurnId: number | null): TurnOpacity {
268
+ if (turnIds.length === 0) return "dim";
269
+
270
+ if (activeTurnId === null) {
271
+ return turnId === turnIds[turnIds.length - 1] ? "recent" : "dim";
272
+ }
273
+
274
+ const activeIndex = turnIds.indexOf(activeTurnId);
275
+ const currentIndex = turnIds.indexOf(turnId);
276
+ if (currentIndex === activeIndex) return "active";
277
+ if (currentIndex === activeIndex - 1) return "recent";
278
+ return "dim";
279
+ }
280
+
281
+ export function createFollowTailViewport(totalRows: number): TimelineViewportState {
282
+ return {
283
+ anchorRow: Math.max(0, totalRows - 1),
284
+ followTail: true,
285
+ unseenItems: 0,
286
+ unseenRows: 0,
287
+ frozenSnapshot: null,
288
+ };
289
+ }
290
+
291
+ function createAnchoredViewport(snapshot: TimelineSnapshot, anchorRow: number): TimelineViewportState {
292
+ return {
293
+ anchorRow: clampAnchorRow(anchorRow, snapshot.totalRows),
294
+ followTail: false,
295
+ unseenItems: 0,
296
+ unseenRows: 0,
297
+ frozenSnapshot: snapshot,
298
+ };
299
+ }
300
+
301
+ function findFinalResponseStartRow(snapshot: TimelineSnapshot, previousTotalRows: number, viewportRows: number): number | null {
302
+ const searchFloor = Math.max(0, previousTotalRows - Math.max(1, viewportRows));
303
+ const responseIndex = snapshot.rows.findIndex((row, index) =>
304
+ index >= searchFloor && row.key.includes("-codex-response-")
305
+ );
306
+ return responseIndex >= 0 ? responseIndex : null;
307
+ }
308
+
309
+ export function createFinalizeContinuityViewport(
310
+ snapshot: TimelineSnapshot,
311
+ options: FinalizeContinuityOptions,
312
+ ): TimelineViewportState {
313
+ if (snapshot.totalRows === 0) {
314
+ return createFollowTailViewport(0);
315
+ }
316
+
317
+ const responseStartRow = findFinalResponseStartRow(
318
+ snapshot,
319
+ options.previousTotalRows,
320
+ options.viewportRows,
321
+ );
322
+ const answerPreviewRows = Math.min(3, Math.max(1, Math.floor(options.viewportRows / 4)));
323
+ const fallbackAnchor = options.previousTotalRows + answerPreviewRows - 1;
324
+ const anchorRow = responseStartRow === null
325
+ ? fallbackAnchor
326
+ : responseStartRow + answerPreviewRows - 1;
327
+
328
+ return createAnchoredViewport(snapshot, Math.min(snapshot.totalRows - 1, Math.max(0, anchorRow)));
329
+ }
330
+
331
+ // ─── Viewport operations ─────────────────────────────────────────────────────
332
+
333
+ function getFrozenSnapshot(
334
+ viewport: TimelineViewportState,
335
+ liveSnapshot: TimelineSnapshot,
336
+ ): TimelineSnapshot {
337
+ return viewport.followTail || viewport.frozenSnapshot === null
338
+ ? liveSnapshot
339
+ : viewport.frozenSnapshot;
340
+ }
341
+
342
+ export function syncTimelineViewport(
343
+ viewport: TimelineViewportState,
344
+ liveSnapshot: TimelineSnapshot,
345
+ options: { finalizeContinuity?: FinalizeContinuityOptions } = {},
346
+ ): TimelineViewportState {
347
+ if (liveSnapshot.totalRows === 0) {
348
+ // Preserve a frozen scroll offset through a transient empty-snapshot moment so
349
+ // the user's reading position is not reset to row 0. Only reset when the
350
+ // viewport is already in follow-tail mode (there is nothing meaningful to preserve).
351
+ return viewport.followTail ? createFollowTailViewport(0) : viewport;
352
+ }
353
+
354
+ if (viewport.followTail) {
355
+ if (options.finalizeContinuity) {
356
+ return createFinalizeContinuityViewport(liveSnapshot, options.finalizeContinuity);
357
+ }
358
+
359
+ const nextAnchor = liveSnapshot.totalRows - 1;
360
+ if (
361
+ viewport.anchorRow === nextAnchor
362
+ && viewport.unseenItems === 0
363
+ && viewport.unseenRows === 0
364
+ && viewport.frozenSnapshot === null
365
+ ) {
366
+ return viewport;
367
+ }
368
+ return createFollowTailViewport(liveSnapshot.totalRows);
369
+ }
370
+
371
+ const frozenSnapshot = viewport.frozenSnapshot ?? liveSnapshot;
372
+ const anchorRow = clampAnchorRow(viewport.anchorRow, frozenSnapshot.totalRows);
373
+ const unseenItems = Math.max(0, liveSnapshot.itemCount - frozenSnapshot.itemCount);
374
+ const unseenRows = Math.max(0, liveSnapshot.totalRows - frozenSnapshot.totalRows);
375
+
376
+ if (
377
+ viewport.anchorRow === anchorRow
378
+ && viewport.unseenItems === unseenItems
379
+ && viewport.unseenRows === unseenRows
380
+ && viewport.frozenSnapshot === frozenSnapshot
381
+ ) {
382
+ return viewport;
383
+ }
384
+
385
+ return {
386
+ anchorRow,
387
+ followTail: false,
388
+ unseenItems,
389
+ unseenRows,
390
+ frozenSnapshot,
391
+ };
392
+ }
393
+
394
+ /**
395
+ * Returns the item index and row-within-item for the given absolute anchorRow
396
+ * inside a snapshot. Used by reflowTimelineViewport to translate a row-based
397
+ * anchor into a layout-independent (item, offset) anchor.
398
+ */
399
+ export function findAnchorItem(
400
+ snapshot: TimelineSnapshot,
401
+ anchorRow: number,
402
+ ): { itemIndex: number; rowWithinItem: number } {
403
+ let rowOffset = 0;
404
+ for (let i = 0; i < snapshot.items.length; i++) {
405
+ const item = snapshot.items[i]!;
406
+ if (rowOffset + item.rowCount > anchorRow) {
407
+ return { itemIndex: i, rowWithinItem: anchorRow - rowOffset };
408
+ }
409
+ rowOffset += item.rowCount;
410
+ }
411
+ // anchorRow is at or beyond the last item – clamp to end
412
+ const lastIdx = Math.max(0, snapshot.items.length - 1);
413
+ const lastItem = snapshot.items[lastIdx];
414
+ return {
415
+ itemIndex: lastIdx,
416
+ rowWithinItem: lastItem ? Math.max(0, lastItem.rowCount - 1) : 0,
417
+ };
418
+ }
419
+
420
+ /**
421
+ * Rebuilds the frozen viewport snapshot after a terminal width change.
422
+ *
423
+ * When the terminal is resized (width changes), all snapshot memos are
424
+ * rebuilt at the new snapshotWidth, so liveSnapshot already contains
425
+ * correctly reflowed rows. However syncTimelineViewport preserves the
426
+ * old frozenSnapshot (with old-width rows), causing visual corruption.
427
+ *
428
+ * This function replaces the stale frozen snapshot with a new one built
429
+ * from the same items as before (liveSnapshot.items[0..frozenItemCount]),
430
+ * now correctly wrapped at the new width. The anchorRow is translated
431
+ * from the old layout via an item-level anchor so the user's reading
432
+ * position is preserved across reflow.
433
+ */
434
+ export function reflowTimelineViewport(
435
+ viewport: TimelineViewportState,
436
+ liveSnapshot: TimelineSnapshot,
437
+ ): TimelineViewportState {
438
+ if (liveSnapshot.totalRows === 0) {
439
+ return createFollowTailViewport(0);
440
+ }
441
+
442
+ if (viewport.followTail) {
443
+ return createFollowTailViewport(liveSnapshot.totalRows);
444
+ }
445
+
446
+ const oldFrozen = viewport.frozenSnapshot ?? liveSnapshot;
447
+
448
+ // Translate anchorRow → stable (item, rowWithinItem) anchor
449
+ const clampedAnchor = clampAnchorRow(viewport.anchorRow, oldFrozen.totalRows);
450
+ const { itemIndex: anchorItemIdx, rowWithinItem: anchorRowWithinItem } =
451
+ findAnchorItem(oldFrozen, clampedAnchor);
452
+
453
+ // Grab the same items from liveSnapshot (already reflowed at new width)
454
+ const frozenItemCount = oldFrozen.itemCount;
455
+ const newFrozenItems = liveSnapshot.items.slice(0, frozenItemCount);
456
+
457
+ if (newFrozenItems.length === 0) {
458
+ return createFollowTailViewport(liveSnapshot.totalRows);
459
+ }
460
+
461
+ // Assemble a new frozen snapshot from the reflowed items
462
+ const newFrozenRows = newFrozenItems.flatMap((item) => item.rows);
463
+ const newFrozenSnapshot: TimelineSnapshot = {
464
+ items: newFrozenItems,
465
+ rows: newFrozenRows,
466
+ totalRows: newFrozenRows.length,
467
+ itemCount: frozenItemCount,
468
+ };
469
+
470
+ // Reconstruct anchorRow in the new layout
471
+ let newAnchorRow = 0;
472
+ for (let i = 0; i < anchorItemIdx; i++) {
473
+ newAnchorRow += newFrozenItems[i]!.rowCount;
474
+ }
475
+ const targetItem = newFrozenItems[anchorItemIdx];
476
+ if (targetItem) {
477
+ newAnchorRow += Math.min(anchorRowWithinItem, targetItem.rowCount - 1);
478
+ } else {
479
+ // Anchor item is beyond the new frozen range (unseen) – clamp to end
480
+ newAnchorRow = Math.max(0, newFrozenSnapshot.totalRows - 1);
481
+ }
482
+ newAnchorRow = clampAnchorRow(newAnchorRow, newFrozenSnapshot.totalRows);
483
+
484
+ const unseenItems = Math.max(0, liveSnapshot.itemCount - frozenItemCount);
485
+ const unseenRows = Math.max(0, liveSnapshot.totalRows - newFrozenSnapshot.totalRows);
486
+
487
+ return {
488
+ anchorRow: newAnchorRow,
489
+ followTail: false,
490
+ unseenItems,
491
+ unseenRows,
492
+ frozenSnapshot: newFrozenSnapshot,
493
+ };
494
+ }
495
+
496
+ export function pageUpTimelineViewport(
497
+ viewport: TimelineViewportState,
498
+ liveSnapshot: TimelineSnapshot,
499
+ viewportRows: number,
500
+ ): TimelineViewportState {
501
+ if (liveSnapshot.totalRows === 0) {
502
+ return createFollowTailViewport(0);
503
+ }
504
+
505
+ const frozenSnapshot = getFrozenSnapshot(viewport, liveSnapshot);
506
+ const tailRow = Math.max(0, frozenSnapshot.totalRows - 1);
507
+ const currentAnchor = viewport.followTail
508
+ ? tailRow
509
+ : clampAnchorRow(viewport.anchorRow, frozenSnapshot.totalRows);
510
+ const nextAnchor = Math.max(getFirstPageAnchor(frozenSnapshot.totalRows, viewportRows), currentAnchor - Math.max(1, viewportRows));
511
+
512
+ return {
513
+ anchorRow: nextAnchor,
514
+ followTail: false,
515
+ unseenItems: Math.max(0, liveSnapshot.itemCount - frozenSnapshot.itemCount),
516
+ unseenRows: Math.max(0, liveSnapshot.totalRows - frozenSnapshot.totalRows),
517
+ frozenSnapshot,
518
+ };
519
+ }
520
+
521
+ export function pageDownTimelineViewport(
522
+ viewport: TimelineViewportState,
523
+ liveSnapshot: TimelineSnapshot,
524
+ viewportRows: number,
525
+ ): TimelineViewportState {
526
+ if (liveSnapshot.totalRows === 0 || viewport.followTail) {
527
+ return viewport;
528
+ }
529
+
530
+ const frozenSnapshot = viewport.frozenSnapshot ?? liveSnapshot;
531
+ const tailRow = Math.max(0, frozenSnapshot.totalRows - 1);
532
+ const currentAnchor = clampAnchorRow(viewport.anchorRow, frozenSnapshot.totalRows);
533
+ if (currentAnchor >= tailRow) {
534
+ return createFollowTailViewport(liveSnapshot.totalRows);
535
+ }
536
+
537
+ const nextAnchor = Math.min(tailRow, currentAnchor + Math.max(1, viewportRows));
538
+ if (nextAnchor >= tailRow) {
539
+ return createFollowTailViewport(liveSnapshot.totalRows);
540
+ }
541
+
542
+ return {
543
+ anchorRow: nextAnchor,
544
+ followTail: false,
545
+ unseenItems: Math.max(0, liveSnapshot.itemCount - frozenSnapshot.itemCount),
546
+ unseenRows: Math.max(0, liveSnapshot.totalRows - frozenSnapshot.totalRows),
547
+ frozenSnapshot,
548
+ };
549
+ }
550
+
551
+ export function stepUpTimelineViewport(
552
+ viewport: TimelineViewportState,
553
+ liveSnapshot: TimelineSnapshot,
554
+ viewportRows: number,
555
+ ): TimelineViewportState {
556
+ if (liveSnapshot.totalRows === 0) {
557
+ return createFollowTailViewport(0);
558
+ }
559
+
560
+ const frozenSnapshot = getFrozenSnapshot(viewport, liveSnapshot);
561
+ const tailRow = Math.max(0, frozenSnapshot.totalRows - 1);
562
+ const currentAnchor = viewport.followTail
563
+ ? tailRow
564
+ : clampAnchorRow(viewport.anchorRow, frozenSnapshot.totalRows);
565
+ const floor = getFirstPageAnchor(frozenSnapshot.totalRows, viewportRows);
566
+
567
+ return {
568
+ anchorRow: Math.max(floor, currentAnchor - 1),
569
+ followTail: false,
570
+ unseenItems: Math.max(0, liveSnapshot.itemCount - frozenSnapshot.itemCount),
571
+ unseenRows: Math.max(0, liveSnapshot.totalRows - frozenSnapshot.totalRows),
572
+ frozenSnapshot,
573
+ };
574
+ }
575
+
576
+ export function stepDownTimelineViewport(
577
+ viewport: TimelineViewportState,
578
+ liveSnapshot: TimelineSnapshot,
579
+ _viewportRows?: number,
580
+ ): TimelineViewportState {
581
+ if (liveSnapshot.totalRows === 0 || viewport.followTail) {
582
+ return viewport;
583
+ }
584
+
585
+ const frozenSnapshot = viewport.frozenSnapshot ?? liveSnapshot;
586
+ const tailRow = Math.max(0, frozenSnapshot.totalRows - 1);
587
+ const currentAnchor = clampAnchorRow(viewport.anchorRow, frozenSnapshot.totalRows);
588
+ if (currentAnchor >= tailRow) {
589
+ return createFollowTailViewport(liveSnapshot.totalRows);
590
+ }
591
+
592
+ const nextAnchor = Math.min(tailRow, currentAnchor + 1);
593
+ if (nextAnchor >= tailRow) {
594
+ return createFollowTailViewport(liveSnapshot.totalRows);
595
+ }
596
+
597
+ return {
598
+ anchorRow: nextAnchor,
599
+ followTail: false,
600
+ unseenItems: Math.max(0, liveSnapshot.itemCount - frozenSnapshot.itemCount),
601
+ unseenRows: Math.max(0, liveSnapshot.totalRows - frozenSnapshot.totalRows),
602
+ frozenSnapshot,
603
+ };
604
+ }
605
+
606
+ export function scrollTimelineViewport(
607
+ viewport: TimelineViewportState,
608
+ liveSnapshot: TimelineSnapshot,
609
+ viewportRows: number,
610
+ deltaRows: number,
611
+ ): TimelineViewportState {
612
+ if (liveSnapshot.totalRows === 0) {
613
+ return createFollowTailViewport(0);
614
+ }
615
+ if (deltaRows === 0) {
616
+ return viewport;
617
+ }
618
+
619
+ const frozenSnapshot = getFrozenSnapshot(viewport, liveSnapshot);
620
+ const tailRow = Math.max(0, frozenSnapshot.totalRows - 1);
621
+
622
+ if (deltaRows > 0 && viewport.followTail) {
623
+ return viewport;
624
+ }
625
+
626
+ const currentAnchor = viewport.followTail
627
+ ? tailRow
628
+ : clampAnchorRow(viewport.anchorRow, frozenSnapshot.totalRows);
629
+
630
+ const floor = getFirstPageAnchor(frozenSnapshot.totalRows, viewportRows);
631
+
632
+ let nextAnchor = currentAnchor + deltaRows;
633
+
634
+ if (nextAnchor >= tailRow) {
635
+ return createFollowTailViewport(liveSnapshot.totalRows);
636
+ }
637
+
638
+ if (nextAnchor < floor) {
639
+ nextAnchor = floor;
640
+ }
641
+
642
+ return {
643
+ anchorRow: nextAnchor,
644
+ followTail: false,
645
+ unseenItems: Math.max(0, liveSnapshot.itemCount - frozenSnapshot.itemCount),
646
+ unseenRows: Math.max(0, liveSnapshot.totalRows - frozenSnapshot.totalRows),
647
+ frozenSnapshot,
648
+ };
649
+ }
650
+
651
+ export function homeTimelineViewport(
652
+ viewport: TimelineViewportState,
653
+ liveSnapshot: TimelineSnapshot,
654
+ viewportRows: number,
655
+ ): TimelineViewportState {
656
+ if (liveSnapshot.totalRows === 0) {
657
+ return createFollowTailViewport(0);
658
+ }
659
+
660
+ const frozenSnapshot = getFrozenSnapshot(viewport, liveSnapshot);
661
+ return {
662
+ anchorRow: getFirstPageAnchor(frozenSnapshot.totalRows, viewportRows),
663
+ followTail: false,
664
+ unseenItems: Math.max(0, liveSnapshot.itemCount - frozenSnapshot.itemCount),
665
+ unseenRows: Math.max(0, liveSnapshot.totalRows - frozenSnapshot.totalRows),
666
+ frozenSnapshot,
667
+ };
668
+ }
669
+
670
+ export function endTimelineViewport(totalRows: number): TimelineViewportState {
671
+ return createFollowTailViewport(totalRows);
672
+ }
673
+
674
+ export function parseWheelScrollDirections(raw: string): Array<"up" | "down"> {
675
+ const directions: Array<"up" | "down"> = [];
676
+
677
+ for (const match of raw.matchAll(SGR_WHEEL_EVENT_PATTERN)) {
678
+ const code = Number.parseInt(match[1] ?? "", 10);
679
+ const terminator = match[4];
680
+ if (terminator !== "M" || Number.isNaN(code) || (code & 64) !== 64) {
681
+ continue;
682
+ }
683
+
684
+ directions.push((code & 1) === 0 ? "up" : "down");
685
+ }
686
+
687
+ return directions;
688
+ }
689
+
690
+ export function parseTimelineNavigationInput(raw: string): TimelineNavigationAction[] {
691
+ const actions: TimelineNavigationAction[] = [];
692
+
693
+ if (rawIncludesAny(raw, PAGE_UP_KEY_INPUTS)) {
694
+ actions.push("pageUp");
695
+ }
696
+
697
+ if (rawIncludesAny(raw, PAGE_DOWN_KEY_INPUTS)) {
698
+ actions.push("pageDown");
699
+ }
700
+
701
+ if (isHomeInput(raw) || rawIncludesAny(raw, CTRL_HOME_KEY_INPUTS)) {
702
+ actions.push("home");
703
+ }
704
+
705
+ if (isEndInput(raw) || rawIncludesAny(raw, CTRL_END_KEY_INPUTS)) {
706
+ actions.push("end");
707
+ }
708
+
709
+ for (const direction of parseWheelScrollDirections(raw)) {
710
+ actions.push(direction === "up" ? "wheelUp" : "wheelDown");
711
+ }
712
+
713
+ return actions;
714
+ }
715
+
716
+ // ─── Row selection & render items ────────────────────────────────────────────
717
+
718
+ export function selectTimelineRows(
719
+ liveSnapshot: TimelineSnapshot,
720
+ viewport: TimelineViewportState,
721
+ viewportRows: number,
722
+ ): {
723
+ sourceSnapshot: TimelineSnapshot;
724
+ visibleRows: TimelineRow[];
725
+ window: {
726
+ startRow: number;
727
+ endRow: number;
728
+ anchorRow: number;
729
+ };
730
+ } {
731
+ const sourceSnapshot = viewport.followTail || viewport.frozenSnapshot === null
732
+ ? liveSnapshot
733
+ : viewport.frozenSnapshot;
734
+ const safeViewportRows = Math.max(1, viewportRows);
735
+
736
+ if (sourceSnapshot.totalRows === 0) {
737
+ return {
738
+ sourceSnapshot,
739
+ visibleRows: [],
740
+ window: { startRow: 0, endRow: 0, anchorRow: 0 },
741
+ };
742
+ }
743
+
744
+ const anchorRow = viewport.followTail
745
+ ? sourceSnapshot.totalRows - 1
746
+ : clampAnchorRow(viewport.anchorRow, sourceSnapshot.totalRows);
747
+ const endRow = Math.max(1, anchorRow + 1);
748
+ const startRow = Math.max(0, endRow - safeViewportRows);
749
+
750
+ const visibleRows = sourceSnapshot.rows.slice(startRow, endRow);
751
+
752
+ // Aggressive fallback: if slicing returned nothing but we have rows,
753
+ // return at least the last row to avoid a blank screen.
754
+ if (visibleRows.length === 0 && sourceSnapshot.totalRows > 0) {
755
+ const fallbackRow = sourceSnapshot.rows[sourceSnapshot.totalRows - 1]!;
756
+ return {
757
+ sourceSnapshot,
758
+ visibleRows: [fallbackRow],
759
+ window: {
760
+ startRow: sourceSnapshot.totalRows - 1,
761
+ endRow: sourceSnapshot.totalRows,
762
+ anchorRow: sourceSnapshot.totalRows - 1,
763
+ },
764
+ };
765
+ }
766
+
767
+ return {
768
+ sourceSnapshot,
769
+ visibleRows,
770
+ window: {
771
+ startRow,
772
+ endRow,
773
+ anchorRow,
774
+ },
775
+ };
776
+ }
777
+
778
+ export function buildStaticRenderItems(
779
+ items: TimelineItem[],
780
+ turnIds: number[],
781
+ activeTurnId: number | null,
782
+ questionTurnId: number | null,
783
+ question: string | null,
784
+ ): RenderTimelineItem[] {
785
+ return items.map((item) => {
786
+ if (item.type === "event") {
787
+ return {
788
+ key: `event-${item.event.id}`,
789
+ type: "event",
790
+ padded: false,
791
+ event: item.event,
792
+ };
793
+ }
794
+
795
+ return {
796
+ key: `turn-${item.turnId}`,
797
+ type: "turn",
798
+ padded: false,
799
+ item,
800
+ renderState: {
801
+ opacity: resolveTurnOpacity(turnIds, item.turnId, activeTurnId),
802
+ question: questionTurnId === item.turnId ? question : null,
803
+ runPhase: resolveTurnRunPhase(item.run, item.assistant, { kind: "IDLE" }, item.turnId),
804
+ },
805
+ };
806
+ });
807
+ }
808
+
809
+ export function buildActiveRenderItems(
810
+ items: TimelineItem[],
811
+ turnIds: number[],
812
+ uiState: UIState,
813
+ ): RenderTimelineItem[] {
814
+ const activeTurnId = getActiveTurnId(uiState);
815
+ const questionTurnId = uiState.kind === "AWAITING_USER_ACTION" ? uiState.turnId : null;
816
+ const question = uiState.kind === "AWAITING_USER_ACTION" ? uiState.question : null;
817
+
818
+ return items.map((item) => {
819
+ if (item.type === "event") {
820
+ return {
821
+ key: `event-${item.event.id}`,
822
+ type: "event",
823
+ padded: true,
824
+ event: item.event,
825
+ };
826
+ }
827
+
828
+ return {
829
+ key: `turn-${item.turnId}`,
830
+ type: "turn",
831
+ padded: false,
832
+ item,
833
+ renderState: {
834
+ opacity: resolveTurnOpacity(turnIds, item.turnId, activeTurnId),
835
+ question: questionTurnId === item.turnId ? question : null,
836
+ runPhase: resolveTurnRunPhase(item.run, item.assistant, uiState, item.turnId),
837
+ },
838
+ };
839
+ });
840
+ }
841
+
842
+ function formatAuthLabel(authState: CodexAuthState): string {
843
+ const raw = getAuthStateLabel(authState);
844
+ return raw.length > 0 ? raw[0]!.toUpperCase() + raw.slice(1) : raw;
845
+ }
846
+
847
+ export function buildIntroRenderItem(params: {
848
+ authState: CodexAuthState;
849
+ workspaceLabel: string;
850
+ layout: Layout;
851
+ startupHeaderMode?: StartupHeaderMode;
852
+ }): IntroRenderTimelineItem {
853
+ return {
854
+ key: "codexa-intro",
855
+ type: "intro",
856
+ padded: true,
857
+ intro: {
858
+ version: APP_VERSION,
859
+ layoutMode: params.layout.mode,
860
+ startupHeaderMode: params.startupHeaderMode,
861
+ authLabel: formatAuthLabel(params.authState),
862
+ workspaceLabel: params.workspaceLabel,
863
+ },
864
+ };
865
+ }
866
+
867
+ // ─── Row rendering ────────────────────────────────────────────────────────────
868
+
869
+ function getToneColor(theme: ReturnType<typeof useTheme>, tone: TimelineTone | undefined): string | undefined {
870
+ switch (tone) {
871
+ case "text": return theme.TEXT;
872
+ case "dim": return theme.DIM;
873
+ case "muted": return theme.MUTED;
874
+ case "accent": return theme.ACCENT;
875
+ case "info": return theme.INFO;
876
+ case "error": return theme.ERROR;
877
+ case "warning": return theme.WARNING;
878
+ case "success": return theme.SUCCESS;
879
+ case "borderSubtle": return theme.BORDER_SUBTLE;
880
+ case "borderActive": return theme.BORDER_ACTIVE;
881
+ case "panel": return theme.PANEL;
882
+ case "star": return theme.STAR;
883
+ default: return undefined;
884
+ }
885
+ }
886
+
887
+ export const TimelineRowView = memo(function TimelineRowView({ row }: { row: TimelineRow }) {
888
+ const isActionRow = row.key.includes("-action-");
889
+ renderDebug.useRenderDebug("TimelineRow", {
890
+ rowKey: row.key,
891
+ row,
892
+ });
893
+ if (isActionRow) {
894
+ renderDebug.traceFlickerEvent("timelineRowRender", {
895
+ rowKey: row.key,
896
+ spanToken: row.spans.map((span) => span.text).join("|"),
897
+ });
898
+ }
899
+
900
+ useEffect(() => {
901
+ if (!isActionRow) return;
902
+ renderDebug.traceFlickerEvent("timelineRowMount", { rowKey: row.key });
903
+ renderDebug.traceLifecycleEvent("ActionRow", "mount", { rowKey: row.key });
904
+ renderDebug.traceLifecycleEvent("ActionBlock", "mount", { rowKey: row.key });
905
+ return () => {
906
+ renderDebug.traceFlickerEvent("timelineRowUnmount", { rowKey: row.key });
907
+ renderDebug.traceLifecycleEvent("ActionRow", "unmount", { rowKey: row.key });
908
+ renderDebug.traceLifecycleEvent("ActionBlock", "unmount", { rowKey: row.key });
909
+ };
910
+ }, [isActionRow, row.key]);
911
+
912
+ const theme = useTheme();
913
+
914
+ return (
915
+ <Box width="100%" overflow="hidden">
916
+ <Text>
917
+ {row.spans.map((span, index) => (
918
+ <Text
919
+ key={index}
920
+ color={getToneColor(theme, span.tone)}
921
+ backgroundColor={getToneColor(theme, span.backgroundTone)}
922
+ bold={span.bold}
923
+ >
924
+ {span.text}
925
+ </Text>
926
+ ))}
927
+ </Text>
928
+ </Box>
929
+ );
930
+ }, (prev, next) => prev.row === next.row);
931
+
932
+ function rowArraysEqual(left: TimelineRow[], right: TimelineRow[]): boolean {
933
+ if (left === right) return true;
934
+ if (left.length !== right.length) return false;
935
+ for (let index = 0; index < left.length; index += 1) {
936
+ if (left[index] !== right[index]) return false;
937
+ }
938
+ return true;
939
+ }
940
+
941
+ const TimelineRowsView = memo(function TimelineRowsView({ rows }: { rows: TimelineRow[] }) {
942
+ return (
943
+ <>
944
+ {rows.map((row) => (
945
+ <TimelineRowView key={row.key} row={row} />
946
+ ))}
947
+ </>
948
+ );
949
+ }, (prev, next) => rowArraysEqual(prev.rows, next.rows));
950
+
951
+ const JumpToBottomBar = memo(function JumpToBottomBar({
952
+ unseenItems,
953
+ mouseCapture,
954
+ }: { unseenItems: number; mouseCapture: boolean }) {
955
+ const theme = useTheme();
956
+ const label = unseenItems > 0
957
+ ? `↑ Scrolled up · ${unseenItems} new item${unseenItems === 1 ? "" : "s"} below`
958
+ : "↑ Scrolled up";
959
+ const hint = mouseCapture ? "wheel↓/End to bottom" : "PgDn/End to bottom";
960
+ return (
961
+ <Box width="100%" paddingX={1}>
962
+ <Text color={theme.INFO}>{label}</Text>
963
+ <Text color={theme.DIM}>{` · ${hint}`}</Text>
964
+ </Box>
965
+ );
966
+ });
967
+
968
+ // ─── Component ────────────────────────────────────────────────────────────────
969
+
970
+ export const Timeline = memo(function Timeline({
971
+ staticEvents,
972
+ activeEvents,
973
+ layout,
974
+ uiState,
975
+ viewportRows,
976
+ verboseMode = false,
977
+ authState = "checking",
978
+ workspaceLabel = "",
979
+ workspaceRoot = null,
980
+ mouseCapture = false,
981
+ onMouseActivity,
982
+ contentSized = false,
983
+ }: TimelineProps) {
984
+ renderDebug.useRenderDebug("Timeline", {
985
+ staticEvents,
986
+ activeEvents,
987
+ staticEventsLength: staticEvents.length,
988
+ activeEventsLength: activeEvents.length,
989
+ cols: layout.cols,
990
+ rows: layout.rows,
991
+ mode: layout.mode,
992
+ uiStateKind: uiState.kind,
993
+ viewportRows,
994
+ verboseMode,
995
+ authState,
996
+ workspaceLabel,
997
+ workspaceRoot,
998
+ });
999
+ renderDebug.useLifecycleDebug("Timeline", {
1000
+ cols: layout.cols,
1001
+ rows: layout.rows,
1002
+ mode: layout.mode,
1003
+ viewportRows,
1004
+ });
1005
+ renderDebug.traceLayoutValidity("Timeline", {
1006
+ cols: layout.cols,
1007
+ rows: layout.rows,
1008
+ viewportRows,
1009
+ });
1010
+ renderDebug.useFlickerDebug("timelineRender", {
1011
+ staticEvents,
1012
+ activeEvents,
1013
+ staticEventsLength: staticEvents.length,
1014
+ activeEventsLength: activeEvents.length,
1015
+ cols: layout.cols,
1016
+ rows: layout.rows,
1017
+ mode: layout.mode,
1018
+ uiStateKind: uiState.kind,
1019
+ viewportRows,
1020
+ verboseMode,
1021
+ authState,
1022
+ workspaceLabel,
1023
+ });
1024
+ renderDebug.useRenderDebug("Transcript", {
1025
+ staticEvents,
1026
+ activeEvents,
1027
+ staticEventsLength: staticEvents.length,
1028
+ activeEventsLength: activeEvents.length,
1029
+ cols: layout.cols,
1030
+ rows: layout.rows,
1031
+ mode: layout.mode,
1032
+ uiStateKind: uiState.kind,
1033
+ viewportRows,
1034
+ verboseMode,
1035
+ workspaceRoot,
1036
+ });
1037
+
1038
+ const staticItems = useMemo(() => buildTimelineItems(staticEvents), [staticEvents]);
1039
+ const activeItems = useMemo(() => buildTimelineItems(activeEvents), [activeEvents]);
1040
+ const activeTurnId = getActiveTurnId(uiState);
1041
+ const runningTurnIds = useMemo(() => getRunningTurnIds(activeEvents), [activeEvents]);
1042
+ const finalizedTurnIds = useMemo(() => getFinalizedTurnIds(staticEvents), [staticEvents]);
1043
+ const finalizedPlanAtTail = useMemo(() => latestFinalizedRunEndsWithPlan(staticEvents), [staticEvents]);
1044
+ const finalizeTransitionRef = useRef<{
1045
+ runningTurnIds: number[];
1046
+ finalizedTurnIds: number[];
1047
+ busy: boolean;
1048
+ }>({
1049
+ runningTurnIds,
1050
+ finalizedTurnIds,
1051
+ busy: isBusyUiState(uiState),
1052
+ });
1053
+ const finalizeTransition = hasFinalizeTransition({
1054
+ previousRunningTurnIds: finalizeTransitionRef.current.runningTurnIds,
1055
+ nextRunningTurnIds: runningTurnIds,
1056
+ nextFinalizedTurnIds: finalizedTurnIds,
1057
+ previousBusy: finalizeTransitionRef.current.busy,
1058
+ nextBusy: isBusyUiState(uiState),
1059
+ });
1060
+ const questionTurnId = uiState.kind === "AWAITING_USER_ACTION" ? uiState.turnId : null;
1061
+ const question = uiState.kind === "AWAITING_USER_ACTION" ? uiState.question : null;
1062
+ const staticTurnIds = useMemo(
1063
+ () => staticItems.filter((item): item is TurnTimelineItem => item.type === "turn").map((item) => item.turnId),
1064
+ [staticItems],
1065
+ );
1066
+ const activeTurnIds = useMemo(
1067
+ () => activeItems.filter((item): item is TurnTimelineItem => item.type === "turn").map((item) => item.turnId),
1068
+ [activeItems],
1069
+ );
1070
+ const allTurnIds = useMemo(
1071
+ () => [...staticTurnIds, ...activeTurnIds],
1072
+ [activeTurnIds, staticTurnIds],
1073
+ );
1074
+ const staticRenderItems = useMemo(
1075
+ () => buildStaticRenderItems(staticItems, allTurnIds, activeTurnId, questionTurnId, question),
1076
+ [activeTurnId, allTurnIds, question, questionTurnId, staticItems],
1077
+ );
1078
+ const activeRenderItems = useMemo(
1079
+ () => buildActiveRenderItems(activeItems, allTurnIds, uiState),
1080
+ [activeItems, allTurnIds, uiState],
1081
+ );
1082
+ // ── Split snapshot building ──────────────────────────────────────────────
1083
+ // During streaming, activeEvents change every frame but staticEvents stay
1084
+ // the same. We further split the active items into "stable" (user prompt,
1085
+ // run header — don't change during streaming) and "streaming" (assistant
1086
+ // content — changes every frame). This gives us three cached tiers so only
1087
+ // the streaming assistant item is rebuilt each frame.
1088
+ const snapshotWidth = getShellWidth(layout.cols);
1089
+ const staticSnapshot = useMemo(
1090
+ () => buildTimelineSnapshot(staticRenderItems, { totalWidth: snapshotWidth, verboseMode, debugLabel: "static", workspaceRoot }),
1091
+ [snapshotWidth, staticRenderItems, verboseMode, workspaceRoot],
1092
+ );
1093
+ // Partition active items: non-assistant items are stable during streaming
1094
+ const isStreaming = uiState.kind === "RESPONDING";
1095
+ const activeStableItems = useMemo(
1096
+ () => isStreaming
1097
+ ? activeRenderItems.filter((item) => !(item.type === "turn" && item.item.assistant))
1098
+ : [],
1099
+ [activeRenderItems, isStreaming],
1100
+ );
1101
+ const activeStreamingItems = useMemo(
1102
+ () => isStreaming
1103
+ ? activeRenderItems.filter((item) => item.type === "turn" && item.item.assistant)
1104
+ : activeRenderItems,
1105
+ [activeRenderItems, isStreaming],
1106
+ );
1107
+ const activeStableSnapshot = useMemo(
1108
+ () => STABLE_RENDER_ENABLED
1109
+ ? { items: [], rows: [], totalRows: 0, itemCount: 0 }
1110
+ : activeStableItems.length > 0
1111
+ ? buildTimelineSnapshot(activeStableItems, { totalWidth: snapshotWidth, verboseMode, debugLabel: "active-stable", workspaceRoot })
1112
+ : { items: [], rows: [], totalRows: 0, itemCount: 0 },
1113
+ [snapshotWidth, activeStableItems, verboseMode, workspaceRoot],
1114
+ );
1115
+ const activeStreamingSnapshot = useMemo(
1116
+ () => STABLE_RENDER_ENABLED
1117
+ ? { items: [], rows: [], totalRows: 0, itemCount: 0 }
1118
+ : buildTimelineSnapshot(activeStreamingItems, { totalWidth: snapshotWidth, verboseMode, debugLabel: "active-streaming", workspaceRoot }),
1119
+ [snapshotWidth, activeStreamingItems, verboseMode, workspaceRoot],
1120
+ );
1121
+ const stableActiveSnapshot = useMemo(
1122
+ () => STABLE_RENDER_ENABLED
1123
+ ? buildStableTimelineSnapshot(activeRenderItems, { totalWidth: snapshotWidth, verboseMode, debugLabel: "active-stable-render", workspaceRoot })
1124
+ : null,
1125
+ [snapshotWidth, activeRenderItems, verboseMode, workspaceRoot],
1126
+ );
1127
+ const liveSnapshot = useMemo(
1128
+ () => {
1129
+ if (stableActiveSnapshot) {
1130
+ return {
1131
+ items: [...staticSnapshot.items, ...stableActiveSnapshot.snapshot.items],
1132
+ rows: [...staticSnapshot.rows, ...stableActiveSnapshot.snapshot.rows],
1133
+ totalRows: staticSnapshot.totalRows + stableActiveSnapshot.snapshot.totalRows,
1134
+ itemCount: staticSnapshot.itemCount + stableActiveSnapshot.snapshot.itemCount,
1135
+ };
1136
+ }
1137
+
1138
+ return {
1139
+ items: [...staticSnapshot.items, ...activeStableSnapshot.items, ...activeStreamingSnapshot.items],
1140
+ rows: [...staticSnapshot.rows, ...activeStableSnapshot.rows, ...activeStreamingSnapshot.rows],
1141
+ totalRows: staticSnapshot.totalRows + activeStableSnapshot.totalRows + activeStreamingSnapshot.totalRows,
1142
+ itemCount: staticSnapshot.itemCount + activeStableSnapshot.itemCount + activeStreamingSnapshot.itemCount,
1143
+ };
1144
+ },
1145
+ [staticSnapshot, stableActiveSnapshot, activeStableSnapshot, activeStreamingSnapshot],
1146
+ );
1147
+
1148
+ const lastNonEmptySnapshotRef = useRef<TimelineSnapshot>(liveSnapshot);
1149
+ if (liveSnapshot.totalRows > 0) {
1150
+ lastNonEmptySnapshotRef.current = liveSnapshot;
1151
+ }
1152
+
1153
+ const isBusy = uiState.kind === "THINKING"
1154
+ || uiState.kind === "RESPONDING"
1155
+ || uiState.kind === "ANSWER_VISIBLE"
1156
+ || uiState.kind === "SHELL_RUNNING";
1157
+
1158
+ const transcriptEventCount = staticEvents.length + activeEvents.length;
1159
+
1160
+ const effectiveSnapshot = useMemo(() => {
1161
+ // If we have events but the live snapshot is empty, fallback to the last
1162
+ // known good snapshot to avoid blanking the screen during transitions.
1163
+ if (liveSnapshot.totalRows === 0 && transcriptEventCount > 0 && lastNonEmptySnapshotRef.current.totalRows > 0) {
1164
+ renderDebug.traceFlickerEvent("snapshotFallback", {
1165
+ reason: "empty-while-busy-with-events",
1166
+ uiStateKind: uiState.kind,
1167
+ previousTotalRows: lastNonEmptySnapshotRef.current.totalRows,
1168
+ transcriptEventCount,
1169
+ });
1170
+ return lastNonEmptySnapshotRef.current;
1171
+ }
1172
+ return liveSnapshot;
1173
+ }, [liveSnapshot, transcriptEventCount, uiState.kind]);
1174
+ const snapshotForViewport = effectiveSnapshot;
1175
+
1176
+ const [viewport, setViewport] = useState<TimelineViewportState>(() => createFollowTailViewport(snapshotForViewport.totalRows));
1177
+ const liveSnapshotRef = useRef(snapshotForViewport);
1178
+ // Tracks the previous snapshotWidth so we can detect width changes inside
1179
+ // the liveSnapshot effect and dispatch reflowTimelineViewport instead of
1180
+ // syncTimelineViewport when the terminal has been resized.
1181
+ const snapshotWidthRef = useRef(snapshotWidth);
1182
+ // Tracks previous totalRows so we can skip setViewport when no new rows
1183
+ // arrived — avoiding a second React render / Ink stdout write per streaming
1184
+ // flush when the viewport already reflects the correct state.
1185
+ const prevTotalRowsRef = useRef(effectiveSnapshot.totalRows);
1186
+ // Stable ref so the raw stdin wheel listener always reads the latest
1187
+ // viewportRows without needing to re-register the listener on resize.
1188
+ const viewportRowsRef = useRef(viewportRows);
1189
+
1190
+ const { stdin } = useStdin();
1191
+
1192
+ useEffect(() => {
1193
+ liveSnapshotRef.current = snapshotForViewport;
1194
+ }, [snapshotForViewport]);
1195
+
1196
+ useEffect(() => {
1197
+ viewportRowsRef.current = viewportRows;
1198
+ }, [viewportRows]);
1199
+
1200
+ // Raw stdin listener for SGR mouse wheel events. Ink's readline layer can
1201
+ // fragment escape sequences before they reach useInput, so we parse the raw
1202
+ // bytes directly — the same approach BottomComposer uses to detect mouse
1203
+ // events. Only wheel button codes (64/65) are acted upon; clicks are ignored.
1204
+ useEffect(() => {
1205
+ if (!mouseCapture || !stdin) return;
1206
+
1207
+ function handleRawWheel(chunk: Buffer | string) {
1208
+ const raw = typeof chunk === "string" ? chunk : chunk.toString("utf8");
1209
+ const directions = parseWheelScrollDirections(raw);
1210
+ if (directions.length === 0) return;
1211
+ const delta = directions.reduce(
1212
+ (acc, dir) => acc + (dir === "up" ? -WHEEL_SCROLL_STEP : WHEEL_SCROLL_STEP),
1213
+ 0,
1214
+ );
1215
+ if (delta === 0) return;
1216
+ setViewport((current) =>
1217
+ scrollTimelineViewport(current, liveSnapshotRef.current, viewportRowsRef.current, delta),
1218
+ );
1219
+ onMouseActivity?.();
1220
+ }
1221
+
1222
+ stdin.on("data", handleRawWheel);
1223
+ return () => { stdin.off("data", handleRawWheel); };
1224
+ }, [mouseCapture, stdin]);
1225
+
1226
+ useEffect(() => {
1227
+ const widthChanged = snapshotWidthRef.current !== snapshotWidth;
1228
+ snapshotWidthRef.current = snapshotWidth;
1229
+
1230
+ const totalRows = snapshotForViewport.totalRows;
1231
+ const previousTotalRows = prevTotalRowsRef.current;
1232
+ const rowGrowth = totalRows - previousTotalRows;
1233
+ const totalRowsGrew = rowGrowth > 0;
1234
+ prevTotalRowsRef.current = totalRows;
1235
+
1236
+ setViewport((current) => {
1237
+ // Width change: always reflow or sync to wrap text at the new width.
1238
+ if (widthChanged) {
1239
+ const next = !current.followTail && current.frozenSnapshot !== null
1240
+ ? reflowTimelineViewport(current, snapshotForViewport)
1241
+ : syncTimelineViewport(current, snapshotForViewport);
1242
+ renderDebug.traceFlickerEvent("viewportSync", {
1243
+ reason: "width-change",
1244
+ result: next === current ? "skipped" : "updated",
1245
+ previousTotalRows,
1246
+ totalRows,
1247
+ rowGrowth,
1248
+ previousAnchorRow: current.anchorRow,
1249
+ anchorRow: next.anchorRow,
1250
+ followTail: next.followTail,
1251
+ viewportRows,
1252
+ });
1253
+ return next;
1254
+ }
1255
+
1256
+ // Frozen (user scrolled up): keep the frozen snapshot fresh when rows
1257
+ // grow or the stream finalizes so the unseen-item counters and
1258
+ // jump-to-bottom affordance stay accurate.
1259
+ if (!current.followTail) {
1260
+ const next = totalRowsGrew || finalizeTransition
1261
+ ? syncTimelineViewport(current, snapshotForViewport)
1262
+ : current;
1263
+ renderDebug.traceFlickerEvent("viewportSync", {
1264
+ reason: finalizeTransition
1265
+ ? (totalRowsGrew ? "detached-finalize-growth" : "detached-finalize")
1266
+ : (totalRowsGrew ? "detached-growth" : "detached-no-growth"),
1267
+ result: next === current ? "skipped" : "updated",
1268
+ previousTotalRows,
1269
+ totalRows,
1270
+ rowGrowth,
1271
+ previousAnchorRow: current.anchorRow,
1272
+ anchorRow: next.anchorRow,
1273
+ followTail: next.followTail,
1274
+ viewportRows,
1275
+ });
1276
+ return next;
1277
+ }
1278
+
1279
+ // Follow-tail: only advance anchorRow when content actually grew.
1280
+ // Streaming is append-only so shrinking rows is rare; if it happens the
1281
+ // anchorRow stays at the old position until the next growth tick.
1282
+ if (!totalRowsGrew) {
1283
+ renderDebug.traceFlickerEvent("viewportSync", {
1284
+ reason: "follow-tail-no-growth",
1285
+ result: "skipped",
1286
+ previousTotalRows,
1287
+ totalRows,
1288
+ rowGrowth,
1289
+ previousAnchorRow: current.anchorRow,
1290
+ anchorRow: current.anchorRow,
1291
+ followTail: current.followTail,
1292
+ viewportRows,
1293
+ });
1294
+ return current;
1295
+ }
1296
+
1297
+ const useFinalizeContinuity = finalizeTransition
1298
+ && !finalizedPlanAtTail
1299
+ && rowGrowth > Math.max(1, Math.floor(viewportRows / 2));
1300
+ const next = syncTimelineViewport(current, snapshotForViewport, {
1301
+ finalizeContinuity: useFinalizeContinuity
1302
+ ? { previousTotalRows, viewportRows }
1303
+ : undefined,
1304
+ });
1305
+ renderDebug.traceFlickerEvent("viewportSync", {
1306
+ reason: useFinalizeContinuity ? "finalize-continuity" : "follow-tail-growth",
1307
+ result: next === current ? "skipped" : "updated",
1308
+ previousTotalRows,
1309
+ totalRows,
1310
+ rowGrowth,
1311
+ previousAnchorRow: current.anchorRow,
1312
+ anchorRow: next.anchorRow,
1313
+ followTail: next.followTail,
1314
+ viewportRows,
1315
+ });
1316
+ return next;
1317
+ });
1318
+ }, [finalizeTransition, finalizedPlanAtTail, snapshotForViewport, snapshotWidth, viewportRows]);
1319
+
1320
+ useEffect(() => {
1321
+ finalizeTransitionRef.current = {
1322
+ runningTurnIds,
1323
+ finalizedTurnIds,
1324
+ busy: isBusyUiState(uiState),
1325
+ };
1326
+ }, [finalizedTurnIds, runningTurnIds, uiState]);
1327
+
1328
+ useInput((input, key) => {
1329
+ const currentSnapshot = liveSnapshotRef.current;
1330
+ if (currentSnapshot.totalRows === 0) return;
1331
+
1332
+ const rawInput = input.includes("\u001b") ? input : `\u001b${input}`;
1333
+ const wheelDelta = parseTimelineNavigationInput(rawInput).reduce((deltaRows, action) => {
1334
+ if (action === "wheelUp") return deltaRows - WHEEL_SCROLL_STEP;
1335
+ if (action === "wheelDown") return deltaRows + WHEEL_SCROLL_STEP;
1336
+ return deltaRows;
1337
+ }, 0);
1338
+
1339
+ if (wheelDelta !== 0) {
1340
+ setViewport((current) => scrollTimelineViewport(current, currentSnapshot, viewportRows, wheelDelta));
1341
+ return;
1342
+ }
1343
+
1344
+ if (key.pageUp) {
1345
+ setViewport((current) => pageUpTimelineViewport(current, currentSnapshot, viewportRows));
1346
+ return;
1347
+ }
1348
+
1349
+ if (key.pageDown) {
1350
+ setViewport((current) => pageDownTimelineViewport(current, currentSnapshot, viewportRows));
1351
+ return;
1352
+ }
1353
+
1354
+ if (key.home || isHomeInput(input)) {
1355
+ setViewport((current) => homeTimelineViewport(current, currentSnapshot, viewportRows));
1356
+ return;
1357
+ }
1358
+
1359
+ if (key.end || isEndInput(input)) {
1360
+ setViewport(endTimelineViewport(currentSnapshot.totalRows));
1361
+ }
1362
+ });
1363
+
1364
+ const { visibleRows } = useMemo(() => {
1365
+ const selection = selectTimelineRows(snapshotForViewport, viewport, viewportRows);
1366
+ renderDebug.traceEvent("viewport", "slice", {
1367
+ providerState: uiState.kind,
1368
+ visibleRows: selection.visibleRows.length,
1369
+ visibleStart: selection.window.startRow,
1370
+ visibleEnd: selection.window.endRow,
1371
+ anchorRow: selection.window.anchorRow,
1372
+ maxScrollOffset: Math.max(0, selection.sourceSnapshot.totalRows - viewportRows),
1373
+ followTail: viewport.followTail,
1374
+ totalItems: selection.sourceSnapshot.itemCount,
1375
+ totalRows: selection.sourceSnapshot.totalRows,
1376
+ availableTimelineRows: viewportRows,
1377
+ sliceEmpty: selection.visibleRows.length === 0 && selection.sourceSnapshot.totalRows > 0,
1378
+ fallbackSnapshot: snapshotForViewport !== liveSnapshot,
1379
+ });
1380
+ renderDebug.traceFlickerEvent("viewportSlice", {
1381
+ visibleRows: selection.visibleRows.length,
1382
+ startRow: selection.window.startRow,
1383
+ endRow: selection.window.endRow,
1384
+ anchorRow: selection.window.anchorRow,
1385
+ followTail: viewport.followTail,
1386
+ totalRows: selection.sourceSnapshot.totalRows,
1387
+ fallbackSnapshot: snapshotForViewport !== liveSnapshot,
1388
+ });
1389
+ return selection;
1390
+ }, [snapshotForViewport, viewport, viewportRows]);
1391
+ const lastNonEmptyVisibleRowsRef = useRef<TimelineRow[]>([]);
1392
+ if (visibleRows.length > 0) {
1393
+ lastNonEmptyVisibleRowsRef.current = visibleRows;
1394
+ }
1395
+ const usingLastGoodFrameFallback = visibleRows.length === 0 && transcriptEventCount > 0;
1396
+ if (usingLastGoodFrameFallback) {
1397
+ renderDebug.traceEvent("viewport", "lastGoodFrameFallback", {
1398
+ providerState: uiState.kind,
1399
+ totalRows: liveSnapshot.totalRows,
1400
+ availableTimelineRows: viewportRows,
1401
+ preservedRows: lastNonEmptyVisibleRowsRef.current.length,
1402
+ });
1403
+ }
1404
+ const preservedVisibleRows = usingLastGoodFrameFallback
1405
+ ? lastNonEmptyVisibleRowsRef.current
1406
+ : visibleRows;
1407
+
1408
+ const showJumpToBottom = !viewport.followTail;
1409
+ const rowsForDisplay = showJumpToBottom
1410
+ ? preservedVisibleRows.slice(0, Math.max(0, viewportRows - 1))
1411
+ : preservedVisibleRows;
1412
+
1413
+ if (visibleRows.length === 0) {
1414
+ renderDebug.traceBlankFrame("Timeline", {
1415
+ reason: transcriptEventCount > 0 ? "visible-rows-zero-with-events" : "visible-rows-zero-no-events",
1416
+ staticEventsLength: staticEvents.length,
1417
+ activeEventsLength: activeEvents.length,
1418
+ transcriptEventCount,
1419
+ totalRows: liveSnapshot.totalRows,
1420
+ viewportRows,
1421
+ preservedRows: preservedVisibleRows.length,
1422
+ uiStateKind: uiState.kind,
1423
+ });
1424
+ }
1425
+
1426
+ if (preservedVisibleRows.length === 0) {
1427
+ renderDebug.traceBlankFrame("Timeline", {
1428
+ reason: "empty-root-layout-return",
1429
+ staticEventsLength: staticEvents.length,
1430
+ activeEventsLength: activeEvents.length,
1431
+ transcriptEventCount,
1432
+ totalRows: liveSnapshot.totalRows,
1433
+ effectiveTotalRows: snapshotForViewport.totalRows,
1434
+ viewportRows,
1435
+ uiStateKind: uiState.kind,
1436
+ });
1437
+ return <Box flexDirection="column" width="100%" height={contentSized ? undefined : Math.max(1, viewportRows)} />;
1438
+ }
1439
+
1440
+ return (
1441
+ <Box
1442
+ flexDirection="column"
1443
+ width="100%"
1444
+ height={contentSized ? undefined : Math.max(1, viewportRows)}
1445
+ overflow="hidden"
1446
+ >
1447
+ <TimelineRowsView rows={rowsForDisplay} />
1448
+ {showJumpToBottom && (
1449
+ <JumpToBottomBar unseenItems={viewport.unseenItems} mouseCapture={mouseCapture} />
1450
+ )}
1451
+ </Box>
1452
+ );
1453
+ }, (prev, next) => {
1454
+ return (
1455
+ prev.staticEvents === next.staticEvents &&
1456
+ prev.activeEvents === next.activeEvents &&
1457
+ prev.layout.cols === next.layout.cols &&
1458
+ prev.layout.rows === next.layout.rows &&
1459
+ prev.layout.mode === next.layout.mode &&
1460
+ prev.uiState === next.uiState &&
1461
+ prev.viewportRows === next.viewportRows &&
1462
+ prev.verboseMode === next.verboseMode &&
1463
+ prev.authState === next.authState &&
1464
+ prev.workspaceLabel === next.workspaceLabel &&
1465
+ prev.workspaceRoot === next.workspaceRoot &&
1466
+ prev.mouseCapture === next.mouseCapture &&
1467
+ prev.onMouseActivity === next.onMouseActivity &&
1468
+ prev.contentSized === next.contentSized
1469
+ );
1470
+ });
1471
+
1472
+ export { Timeline as ActiveTimeline };