@golba98/codexa 1.0.3 → 1.0.5

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