@autopilot-agent/cli 0.2.0 → 0.3.0

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 (73) hide show
  1. package/README.md +10 -5
  2. package/dist/activity-animation.d.ts +4 -0
  3. package/dist/activity-animation.js +11 -17
  4. package/dist/composition-root.d.ts +31 -1
  5. package/dist/composition-root.js +112 -3
  6. package/dist/context-report.d.ts +8 -3
  7. package/dist/context-report.js +14 -2
  8. package/dist/controller.d.ts +34 -4
  9. package/dist/controller.js +434 -90
  10. package/dist/error-diagnostics.d.ts +2 -0
  11. package/dist/error-diagnostics.js +3 -1
  12. package/dist/event-projector.d.ts +16 -2
  13. package/dist/event-projector.js +74 -5
  14. package/dist/index.d.ts +1 -1
  15. package/dist/main.js +142 -7
  16. package/dist/parser.js +498 -0
  17. package/dist/renderer.js +3 -1
  18. package/dist/session-summary.d.ts +7 -0
  19. package/dist/session-summary.js +25 -0
  20. package/dist/session-title.d.ts +5 -0
  21. package/dist/session-title.js +10 -0
  22. package/dist/thread-commands.d.ts +37 -0
  23. package/dist/thread-commands.js +233 -0
  24. package/dist/thread-host.d.ts +31 -0
  25. package/dist/thread-host.js +76 -0
  26. package/dist/timeline-lines.js +36 -28
  27. package/dist/tui/app.d.ts +22 -0
  28. package/dist/tui/app.js +112 -40
  29. package/dist/tui/approval.d.ts +4 -0
  30. package/dist/tui/approval.js +13 -4
  31. package/dist/tui/constants.d.ts +1 -1
  32. package/dist/tui/constants.js +1 -1
  33. package/dist/tui/format.d.ts +1 -1
  34. package/dist/tui/format.js +19 -9
  35. package/dist/tui/hooks/use-prompt-input.d.ts +52 -0
  36. package/dist/tui/hooks/use-prompt-input.js +148 -20
  37. package/dist/tui/hooks/use-status-view.d.ts +2 -2
  38. package/dist/tui/hooks/use-status-view.js +38 -11
  39. package/dist/tui/inline-output.d.ts +17 -0
  40. package/dist/tui/inline-output.js +31 -0
  41. package/dist/tui/input/clipboard-image.d.ts +17 -0
  42. package/dist/tui/input/clipboard-image.js +117 -0
  43. package/dist/tui/input-area.d.ts +8 -0
  44. package/dist/tui/input-area.js +18 -3
  45. package/dist/tui/lifecycle.js +2 -5
  46. package/dist/tui/markdown/diff.d.ts +1 -1
  47. package/dist/tui/markdown/diff.js +28 -1
  48. package/dist/tui/performance-diagnostics.js +2 -0
  49. package/dist/tui/prompt-input.d.ts +1 -0
  50. package/dist/tui/prompt-input.js +5 -3
  51. package/dist/tui/render-mode.d.ts +4 -4
  52. package/dist/tui/render-mode.js +5 -11
  53. package/dist/tui/run.js +37 -49
  54. package/dist/tui/session-manager.d.ts +115 -0
  55. package/dist/tui/session-manager.js +383 -0
  56. package/dist/tui/session-workspace.d.ts +9 -0
  57. package/dist/tui/session-workspace.js +383 -0
  58. package/dist/tui/status-line.d.ts +3 -0
  59. package/dist/tui/status-line.js +12 -6
  60. package/dist/tui/store.js +27 -5
  61. package/dist/tui/timeline/live.js +2 -3
  62. package/dist/tui/timeline/progress.js +3 -2
  63. package/dist/tui/timeline/static-timeline.js +1 -2
  64. package/dist/tui/timeline/turn.js +3 -2
  65. package/dist/tui/transcript.d.ts +1 -1
  66. package/dist/tui/transcript.js +19 -1
  67. package/dist/tui/trust-dialog.d.ts +3 -0
  68. package/dist/tui/trust-dialog.js +23 -2
  69. package/dist/tui/types.d.ts +8 -0
  70. package/dist/tui/types.js +4 -1
  71. package/dist/tui/viewport/sources.js +6 -13
  72. package/dist/types.d.ts +152 -2
  73. package/package.json +4 -4
@@ -0,0 +1,383 @@
1
+ import { jsxs as _jsxs, jsx as _jsx } from "react/jsx-runtime";
2
+ /** inline单窗口会话壳:目录按需分页,仅当前会话挂载正文,输入按原目标隔离。 */
3
+ import { useEffect, useLayoutEffect, useRef, useState } from "react";
4
+ import { Box, Text, useInput, useStdout } from "ink";
5
+ import { TuiApprovalPrompt, createTuiApprovalOptions } from "./approval.js";
6
+ import { readTuiTerminalSize } from "./format.js";
7
+ import { TuiInlineOutputOwner } from "./inline-output.js";
8
+ import { CliTuiApp } from "./app.js";
9
+ import { getCliInteractionLabel } from "./session-manager.js";
10
+ /** 仅已打开/关联目标拥有Store,普通目录项不为展示创建重型对象。 */
11
+ function isLoadedSession(entry) { return "store" in entry; }
12
+ /** 按Session保存草稿引用,仅挂载当前正文;目录选择不执行或取消Turn。 */
13
+ export function CliSessionWorkspace(props) {
14
+ const { stdout } = useStdout();
15
+ const terminalSizeSource = props.terminalSizeSource ?? stdout;
16
+ const initialSessionId = useRef(props.manager.selected().sessionId);
17
+ const [, setVersion] = useState(0);
18
+ const [size, setSize] = useState(function initialSize() { return readTuiTerminalSize(terminalSizeSource); });
19
+ const { columns, rows } = size;
20
+ const [management, setManagement] = useState(false);
21
+ const managementRef = useRef(false);
22
+ const [requestsOnly, setRequestsOnly] = useState(false);
23
+ const requestsOnlyRef = useRef(false);
24
+ /** 同一事件批次内管理目录立即生效,避免 Ctrl+T 后方向键沿旧关联列表路由。 */
25
+ function updateManagement(value) { managementRef.current = value; setManagement(value); }
26
+ const [approval, setApproval] = useState();
27
+ const approvalRef = useRef(approval);
28
+ const [decisionIndex, setDecisionIndex] = useState(0);
29
+ const decisionRef = useRef(0);
30
+ const [detailOffset, setDetailOffset] = useState(0);
31
+ const [details, setDetails] = useState(false);
32
+ const approvalMaximumRef = useRef(0);
33
+ const submittingRef = useRef(false);
34
+ const approvalSubmissions = useRef(new Set());
35
+ const approvalOrder = useRef(new Map());
36
+ const [open, setOpen] = useState((terminalSizeSource.columns ?? 80) >= 110);
37
+ const [listFocused, setListFocused] = useState(false);
38
+ const [index, setIndex] = useState(0);
39
+ const [offset, setOffset] = useState(0);
40
+ const [draftAttachments, setDraftAttachments] = useState({});
41
+ const indexRef = useRef(0);
42
+ const consumedInputRef = useRef(false);
43
+ const forwardingInputRef = useRef(false);
44
+ const directoryLoadingRef = useRef(false);
45
+ const directoryKeysRef = useRef([]);
46
+ const activeInputRef = useRef(undefined);
47
+ const queuedKeysRef = useRef([]);
48
+ const offsetRef = useRef(0);
49
+ const modeRef = useRef({ open: (terminalSizeSource.columns ?? 80) >= 110, focused: false, epoch: 0 });
50
+ const selected = props.manager.selected();
51
+ const selectedState = selected.store.getSnapshot();
52
+ const todo = [...selectedState.liveEvents].reverse().find(function todo(event) { return event.type === "todo_updated"; });
53
+ const stage = todo?.type === "todo_updated" ? todo.todos.find(function active(item) { return item.status === "in_progress"; })?.activeForm : undefined;
54
+ const attachments = [...new Set([...(selected.attachments ?? []), ...(draftAttachments[selected.sessionId] ?? [])])];
55
+ const related = props.manager.related();
56
+ const approvalCards = related.flatMap(function pendingCard(entry) {
57
+ const state = entry.store.getSnapshot();
58
+ if (!state.pendingApproval || !state.liveTurnId || state.status !== "waiting_approval")
59
+ return [];
60
+ const identity = JSON.stringify([entry.sessionId, state.liveTurnId, state.pendingApproval.approvalId]);
61
+ if (!approvalOrder.current.has(identity))
62
+ approvalOrder.current.set(identity, approvalOrder.current.size);
63
+ return [{ entry, identity, sessionId: entry.sessionId, turnId: state.liveTurnId, approvalId: state.pendingApproval.approvalId, pending: state.pendingApproval }];
64
+ }).sort(function arrival(a, b) { return approvalOrder.current.get(a.identity) - approvalOrder.current.get(b.identity); });
65
+ const recoveryCards = related.flatMap(function savedDecision(entry) {
66
+ const view = entry.executionView;
67
+ const event = view?.interaction?.approval?.event;
68
+ if (entry.controller.isExecuting?.() || view?.interaction?.state !== "decided" || event?.type !== "approval_required" || view.interaction.continuation?.failureDiagnostic?.started || (view.interaction.continuation && view.interaction.continuation.state !== "failed") || (view.continuation ?? view.interaction.continuation)?.failureCode === "BOUNDARY_CHANGED")
69
+ return [];
70
+ return [{ entry, sessionId: entry.sessionId, turnId: view.turnId, approvalId: event.result.approval.approvalId, pending: { approvalId: event.result.approval.approvalId, toolName: event.toolName, reason: "审批决定已保存" }, retry: true }];
71
+ });
72
+ const focusableCards = [...approvalCards, ...recoveryCards];
73
+ const refreshingApproval = [selected, ...related].some(function loading(entry) { return entry.summaryStatus === "waiting_approval" && !entry.summaryReady; });
74
+ /** 真实问题请求定位沿用原列表Enter语义,不把普通running目标混成审批。 */
75
+ function requestEntries() {
76
+ return props.manager.related().filter(function actionable(entry) {
77
+ const state = entry.store.getSnapshot();
78
+ const view = entry.executionView;
79
+ const question = state.status === "waiting_user_input" && Boolean(entry.controller.getProjection().questionRequestId)
80
+ && (!view || view.waiting === "user_input" && view.interaction?.state === "pending");
81
+ return question || focusableCards.some(function same(card) { return card.sessionId === entry.sessionId; });
82
+ });
83
+ }
84
+ const listedEntries = management ? props.manager.directory() : requestsOnly ? requestEntries() : related;
85
+ const hasSidebarContent = related.length > 0 || attachments.length > 0 || Boolean(stage);
86
+ const fullscreen = props.renderMode === "alternate-screen" && !props.screenReader;
87
+ const wide = columns >= 110 && fullscreen;
88
+ const bodyRows = Math.max(1, rows - (approval && !approval.retry ? 15 : 5));
89
+ const visibleRows = Math.max(1, bodyRows - 4);
90
+ const sidebarRows = [
91
+ ...listedEntries.flatMap(function session(entry, rowIndex) {
92
+ if (management || !isLoadedSession(entry))
93
+ return [{ text: `${entry.sessionId === selected.sessionId ? "▶ " : " "}${entry.title}`, sessionIndex: rowIndex }];
94
+ const state = entry.store.getSnapshot();
95
+ const todo = [...state.liveEvents].reverse().find(function latest(event) { return event.type === "todo_updated"; });
96
+ const phase = todo?.type === "todo_updated" ? todo.todos.find(function active(item) { return item.status === "in_progress"; })?.activeForm : undefined;
97
+ const label = getCliInteractionLabel(entry.executionView) ?? (state.pendingApproval ? "待审批" : state.status === "waiting_user_input" ? "等待回答" : state.status === "completed" ? "已完成" : state.status === "failed" ? "失败/阻塞" : state.status);
98
+ return [{ text: `${entry.sessionId === selected.sessionId ? "▶ " : " "}${entry.title}`, sessionIndex: rowIndex }, { text: ` ${label}${phase ? ` · ${phase}` : ""}${entry.unread ? " 未读" : ""}`, sessionIndex: rowIndex }];
99
+ }),
100
+ ...(!management && attachments.length ? [{ text: "附件", sessionIndex: -1 }, ...attachments.map(function attachment(name) { return { text: name.replace(/[\x00-\x1f\x7f]/gu, " "), sessionIndex: -1 }; })] : []),
101
+ ...(!management && stage ? [{ text: "当前阶段", sessionIndex: -1 }, { text: stage, sessionIndex: -1 }] : []),
102
+ ];
103
+ const showList = open && (listFocused || (wide && hasSidebarContent));
104
+ const listWidth = wide && showList ? 30 : 0;
105
+ useEffect(function subscribeDirectory() { return props.manager.subscribe(function changed() { setVersion(function next(value) { return value + 1; }); }); }, [props.manager]);
106
+ useEffect(function observeTerminalSize() {
107
+ function resize() { setSize(readTuiTerminalSize(terminalSizeSource)); }
108
+ terminalSizeSource.on?.("resize", resize);
109
+ return function release() { terminalSizeSource.off?.("resize", resize); };
110
+ }, [terminalSizeSource]);
111
+ useLayoutEffect(function commitRootSize() { props.onTerminalSizeChange?.(size); }, [size, props.onTerminalSizeChange]);
112
+ /** 独立侧栏窗口保持有界;增删内容和resize不会把正文滚动位置带入侧栏。 */
113
+ function updateOffset(next) {
114
+ const bounded = Math.max(0, Math.min(Math.max(0, sidebarRows.length - visibleRows), next));
115
+ offsetRef.current = bounded;
116
+ setOffset(bounded);
117
+ }
118
+ /** 连续方向键紧接Enter使用同步索引,不依赖React渲染闭包。 */
119
+ function updateIndex(next) {
120
+ const bounded = Math.max(0, Math.min((managementRef.current ? props.manager.directory() : requestsOnlyRef.current ? requestEntries() : props.manager.related()).length - 1, next));
121
+ indexRef.current = bounded;
122
+ setIndex(bounded);
123
+ const row = bounded * (managementRef.current ? 1 : 2);
124
+ if (row < offsetRef.current)
125
+ updateOffset(row);
126
+ else if (row + 1 >= offsetRef.current + visibleRows)
127
+ updateOffset(row - visibleRows + 2);
128
+ }
129
+ /** 模式与消费代次同步提交,保留原输入隔离机制。 */
130
+ function updateMode(nextOpen, focused) {
131
+ // Ink逐订阅者batchedUpdates可在同一按键分发中commit新闭包;保留事件周期消费标记。
132
+ consumedInputRef.current = true;
133
+ queueMicrotask(function releaseConsumedInput() { consumedInputRef.current = false; });
134
+ modeRef.current = { open: nextOpen, focused, epoch: modeRef.current.epoch + 1 };
135
+ setVersion(function publishMode(value) { return value + 1; });
136
+ setOpen(nextOpen);
137
+ setListFocused(focused);
138
+ if (!focused) {
139
+ updateManagement(false);
140
+ requestsOnlyRef.current = false;
141
+ setRequestsOnly(false);
142
+ }
143
+ }
144
+ /** 按实时open与展示条件判定可见面板,不能把未聚焦的可见侧栏漏给取消入口。 */
145
+ function isPanelVisible() { return modeRef.current.open && (modeRef.current.focused || (wide && hasSidebarContent)); }
146
+ /** 仅显式快捷键移动审批焦点,自动到达的请求保留主输入。 */
147
+ function focusApproval(index) {
148
+ const card = focusableCards[index];
149
+ if (!card)
150
+ return;
151
+ approvalRef.current = card;
152
+ setApproval(card);
153
+ decisionRef.current = 0;
154
+ setDecisionIndex(0);
155
+ setDetails(false);
156
+ setDetailOffset(0);
157
+ updateMode(false, false);
158
+ }
159
+ /** 仅根桥转发允许越过本批次消费标记,其他Ink订阅仍受标记保护。 */
160
+ function forwardInput(value, key) {
161
+ forwardingInputRef.current = true;
162
+ try {
163
+ activeInputRef.current?.handle?.(value, key);
164
+ }
165
+ finally {
166
+ forwardingInputRef.current = false;
167
+ }
168
+ }
169
+ /** 根路由按接收时模式处理一次输入,异步目录只回放同代次列表按键。 */
170
+ function handleSessionList(value, key) {
171
+ if (submittingRef.current) {
172
+ if (key.ctrl && value === "c")
173
+ props.onRequestInterrupt();
174
+ return;
175
+ }
176
+ if (key.ctrl && value === "c" && modeRef.current.focused) {
177
+ props.onRequestInterrupt();
178
+ return;
179
+ }
180
+ if (key.ctrl && value === "t") {
181
+ const approvalFocused = approvalRef.current !== undefined;
182
+ approvalRef.current = undefined;
183
+ setApproval(undefined);
184
+ requestsOnlyRef.current = false;
185
+ setRequestsOnly(false);
186
+ updateManagement(true);
187
+ if (!approvalFocused && modeRef.current.open && modeRef.current.focused)
188
+ updateMode(false, false);
189
+ else {
190
+ updateMode(true, true);
191
+ updateIndex(props.manager.directory().findIndex(function current(entry) { return entry.sessionId === props.manager.selected().sessionId; }));
192
+ const epoch = modeRef.current.epoch;
193
+ directoryLoadingRef.current = true;
194
+ directoryKeysRef.current = [];
195
+ void props.manager.loadDirectory().then(function loaded() {
196
+ if (modeRef.current.epoch !== epoch)
197
+ return;
198
+ directoryLoadingRef.current = false;
199
+ const keys = directoryKeysRef.current;
200
+ directoryKeysRef.current = [];
201
+ for (const item of keys)
202
+ handleSessionList(item.value, item.key);
203
+ }).catch(function failed() { selected.store.addNotice("历史目录暂不可用"); }).finally(function release() { if (modeRef.current.epoch === epoch)
204
+ directoryLoadingRef.current = false; });
205
+ }
206
+ return;
207
+ }
208
+ if (directoryLoadingRef.current && managementRef.current && modeRef.current.focused && !key.ctrl && !key.escape && value !== "\u001b") {
209
+ directoryKeysRef.current.push({ value, key });
210
+ return;
211
+ }
212
+ if (approvalRef.current) {
213
+ consumedInputRef.current = true;
214
+ queueMicrotask(function releaseApprovalInput() { consumedInputRef.current = false; });
215
+ const frozen = approvalRef.current;
216
+ if (key.ctrl && value === "a") {
217
+ focusApproval((focusableCards.findIndex(function same(card) { return card.sessionId === frozen.sessionId && card.turnId === frozen.turnId && card.approvalId === frozen.approvalId; }) + 1) % focusableCards.length);
218
+ return;
219
+ }
220
+ if (key.escape || value === "\u001b") {
221
+ approvalRef.current = undefined;
222
+ setApproval(undefined);
223
+ return;
224
+ }
225
+ if (key.ctrl && value === "c") {
226
+ props.onRequestInterrupt();
227
+ return;
228
+ }
229
+ if (frozen.retry) {
230
+ if (!key.return)
231
+ return;
232
+ const card = recoveryCards.find(function same(card) { return card.sessionId === frozen.sessionId && card.turnId === frozen.turnId && card.approvalId === frozen.approvalId; });
233
+ approvalRef.current = undefined;
234
+ setApproval(undefined);
235
+ if (card)
236
+ void card.entry.controller.resume({ turnId: frozen.turnId, approvalId: frozen.approvalId }).then(function result(result) { props.manager.handleResult(card.entry, result); }).catch(function failed() { card.entry.store.addNotice("审批决定已保存,恢复执行失败,请重试原决定继续"); }).finally(function refresh() { void props.manager.refresh().catch(function failed() { card.entry.store.addNotice("当前恢复状态暂不可用"); }); });
237
+ return;
238
+ }
239
+ if (value === "d") {
240
+ setDetails(function toggle(current) { return !current; });
241
+ setDetailOffset(0);
242
+ return;
243
+ }
244
+ if (key.pageDown)
245
+ setDetailOffset(function down(current) { return Math.min(current + Math.max(1, bodyRows - 5), approvalMaximumRef.current); });
246
+ if (key.pageUp)
247
+ setDetailOffset(function up(current) { return Math.max(0, current - Math.max(1, bodyRows - 5)); });
248
+ const options = createTuiApprovalOptions(frozen.pending);
249
+ if (key.upArrow || key.downArrow) {
250
+ decisionRef.current = Math.max(0, Math.min(options.length - 1, decisionRef.current + (key.downArrow ? 1 : -1)));
251
+ setDecisionIndex(decisionRef.current);
252
+ }
253
+ if (key.return && !submittingRef.current) {
254
+ const target = props.manager.entries().find(function match(entry) { return entry.sessionId === frozen.sessionId; });
255
+ const state = target?.store.getSnapshot();
256
+ if (!target || state?.liveTurnId !== frozen.turnId || state?.pendingApproval?.approvalId !== frozen.approvalId || state.status !== "waiting_approval") {
257
+ selected.store.addNotice("审批请求已失效,正在刷新当前请求");
258
+ approvalRef.current = undefined;
259
+ setApproval(undefined);
260
+ void props.manager.refresh().catch(function failed() { selected.store.addNotice("当前审批暂不可用,请重试"); });
261
+ return;
262
+ }
263
+ const identity = JSON.stringify([frozen.sessionId, frozen.turnId, frozen.approvalId]);
264
+ if (approvalSubmissions.current.has(identity))
265
+ return;
266
+ approvalSubmissions.current.add(identity);
267
+ target.store.recordApprovalSubmission(options[decisionRef.current].decision);
268
+ approvalRef.current = undefined;
269
+ setApproval(undefined);
270
+ updateMode(wide && modeRef.current.open, false);
271
+ void target.controller.dispatch({ type: "approve", expected: { sessionId: frozen.sessionId, turnId: frozen.turnId, approvalId: frozen.approvalId }, decision: options[decisionRef.current].decision }).then(function result(result) { props.manager.handleResult(target, result); }).catch(function failed() { target.store.addNotice("审批提交或恢复失败,请核对当前决定后重试继续"); }).finally(function release() { approvalSubmissions.current.delete(identity); void props.manager.refresh().catch(function failed() { target.store.addNotice("当前审批状态暂不可用"); }); });
272
+ }
273
+ return;
274
+ }
275
+ if (key.ctrl && value === "a") {
276
+ const card = focusableCards[0];
277
+ if (card)
278
+ focusApproval(0);
279
+ else {
280
+ updateManagement(false);
281
+ if (requestEntries().length) {
282
+ requestsOnlyRef.current = true;
283
+ setRequestsOnly(true);
284
+ updateIndex(0);
285
+ updateMode(true, true);
286
+ }
287
+ else {
288
+ updateMode(wide && modeRef.current.open, false);
289
+ selected.store.addNotice("暂无待处理审批/问答或可安全重试的请求;Ctrl+T查看会话");
290
+ }
291
+ }
292
+ return;
293
+ }
294
+ if (key.ctrl && value === "l") {
295
+ consumedInputRef.current = true;
296
+ queueMicrotask(function release() { consumedInputRef.current = false; });
297
+ void props.manager.loadHistory().catch(function failed() { selected.store.addNotice("历史页暂不可用"); });
298
+ return;
299
+ }
300
+ if ((key.escape || value === "\u001b") && isPanelVisible()) {
301
+ updateMode(false, false);
302
+ return;
303
+ }
304
+ if (!modeRef.current.focused) {
305
+ const sessionId = props.manager.selected().sessionId;
306
+ if (activeInputRef.current?.sessionId === sessionId && activeInputRef.current.handle)
307
+ forwardInput(value, key);
308
+ else if (listFocused || approval || activeInputRef.current?.sessionId !== sessionId)
309
+ queuedKeysRef.current.push({ sessionId, value, key });
310
+ return;
311
+ }
312
+ if (key.pageUp)
313
+ updateOffset(offsetRef.current - visibleRows);
314
+ if (key.pageDown) {
315
+ if (managementRef.current && offsetRef.current + visibleRows >= sidebarRows.length)
316
+ void props.manager.loadDirectory().catch(function failed() { selected.store.addNotice("历史目录暂不可用"); });
317
+ updateOffset(offsetRef.current + visibleRows);
318
+ }
319
+ if (key.upArrow)
320
+ updateIndex(indexRef.current - 1);
321
+ if (key.downArrow)
322
+ updateIndex(indexRef.current + 1);
323
+ const target = (managementRef.current ? props.manager.directory() : requestsOnlyRef.current ? requestEntries() : props.manager.related())[indexRef.current];
324
+ if (key.return && target) {
325
+ const state = isLoadedSession(target) ? target.store.getSnapshot() : undefined;
326
+ if (!managementRef.current && state?.pendingApproval && state.liveTurnId && state.status === "waiting_approval") {
327
+ const frozen = { sessionId: target.sessionId, turnId: state.liveTurnId, approvalId: state.pendingApproval.approvalId, pending: state.pendingApproval };
328
+ approvalRef.current = frozen;
329
+ setApproval(frozen);
330
+ decisionRef.current = 0;
331
+ setDecisionIndex(0);
332
+ setDetails(false);
333
+ setDetailOffset(0);
334
+ updateMode(true, true);
335
+ }
336
+ else if (managementRef.current || state?.status === "waiting_user_input") {
337
+ const targetId = target.sessionId;
338
+ submittingRef.current = true;
339
+ updateMode(wide && modeRef.current.open, false);
340
+ void props.manager.select(targetId).catch(function failed() { selected.store.addNotice("会话历史暂不可用"); }).finally(function release() { submittingRef.current = false; });
341
+ }
342
+ else if (!managementRef.current) {
343
+ const saved = recoveryCards.find(function same(card) { return card.sessionId === target.sessionId; });
344
+ if (saved) {
345
+ focusApproval(focusableCards.indexOf(saved));
346
+ return;
347
+ }
348
+ selected.store.addNotice("该会话暂无可处理请求;Ctrl+T可查看会话");
349
+ void props.manager.refresh().catch(function failed() { selected.store.addNotice("当前请求状态暂不可用,请重试"); });
350
+ }
351
+ }
352
+ }
353
+ useInput(handleSessionList);
354
+ useEffect(function bindSidebarMouse() {
355
+ if (!listFocused || !props.mouseInput)
356
+ return;
357
+ props.mouseInput.setHandler(function scroll(event, notches) { if (event.kind === "wheel_up")
358
+ updateOffset(offsetRef.current - 3 * notches); if (event.kind === "wheel_down")
359
+ updateOffset(offsetRef.current + 3 * notches); });
360
+ return function release() { props.mouseInput?.setHandler(undefined); };
361
+ }, [listFocused, props.mouseInput, sidebarRows.length, visibleRows]);
362
+ const activeApproval = approval && props.manager.entries().find(function target(entry) { return entry.sessionId === approval.sessionId; });
363
+ const approvalValid = activeApproval && (approval?.retry ? recoveryCards.some(function same(card) { return card.sessionId === approval.sessionId && card.turnId === approval.turnId && card.approvalId === approval.approvalId; }) : activeApproval.store.getSnapshot().status === "waiting_approval" && activeApproval.store.getSnapshot().liveTurnId === approval?.turnId && activeApproval.store.getSnapshot().pendingApproval?.approvalId === approval?.approvalId);
364
+ useEffect(function dismissStaleApproval() { if (approval && !approvalValid) {
365
+ approvalRef.current = undefined;
366
+ setApproval(undefined);
367
+ } }, [approval, approvalValid]);
368
+ const listOffset = Math.max(0, Math.min(offset, Math.max(0, sidebarRows.length - visibleRows)));
369
+ const list = _jsxs(Box, { flexDirection: "column", width: wide ? 30 : Math.max(1, columns), height: bodyRows, flexShrink: 0, overflow: "hidden", borderStyle: "single", "aria-label": "\u4F1A\u8BDD\u4E0E\u9644\u4EF6\u4FA7\u680F\uFF0C\u65B9\u5411\u952E\u9009\u62E9\uFF0CEnter\u5207\u6362\uFF0CPgUp/PgDn\u6EDA\u52A8\uFF0CEsc\u5173\u95ED", children: [_jsxs(Text, { wrap: "truncate", children: [management ? "会话" : "关联任务", " \u00B7 ", listFocused ? "↑↓/Enter · Esc关闭" : "Ctrl+A审批 · Esc关闭"] }), _jsx(Box, { flexDirection: "column", flexGrow: 1, overflow: "hidden", children: sidebarRows.slice(listOffset, listOffset + visibleRows).map(function row(item, localIndex) { return _jsx(Text, { inverse: listFocused && item.sessionIndex >= 0 && item.sessionIndex === index, wrap: "truncate", children: item.text }, listOffset + localIndex); }) }), _jsxs(Text, { wrap: "truncate", children: [listOffset + 1, "\u2013", Math.min(sidebarRows.length, listOffset + visibleRows), "/", sidebarRows.length, " \u00B7 ", management && props.manager.directoryState().loading ? "加载中" : management && props.manager.directoryState().more ? "PgDn继续加载" : "PgUp/PgDn"] })] });
370
+ return _jsx(TuiInlineOutputOwner, { children: _jsxs(Box, { flexDirection: "column", width: columns, height: fullscreen ? Math.max(1, rows - 1) : undefined, overflow: "hidden", children: [_jsxs(Box, { flexDirection: "row", height: fullscreen ? bodyRows : undefined, flexShrink: 0, overflow: "hidden", children: [!wide && showList && !approval ? list : null, _jsx(Box, { flexDirection: "column", width: Math.max(1, columns - listWidth), height: fullscreen ? bodyRows : undefined, display: !wide && showList && !approval ? "none" : "flex", children: [selected].map(function currentSession(entry) {
371
+ const visible = true;
372
+ return _jsx(Box, { display: visible ? "flex" : "none", flexDirection: "column", children: _jsx(CliTuiApp, { ...props, sessionTitle: entry.title, interactionLabel: getCliInteractionLabel(entry.executionView), inlineOutputKey: entry.sessionId, bindInputHandler: function bindCurrentSessionInput(handle) { activeInputRef.current = { sessionId: entry.sessionId, handle }; if (handle && !modeRef.current.focused && !approvalRef.current) {
373
+ const keys = queuedKeysRef.current;
374
+ queuedKeysRef.current = [];
375
+ for (const item of keys)
376
+ if (item.sessionId === entry.sessionId)
377
+ forwardInput(item.value, item.key);
378
+ } }, viewState: entry.viewState, store: entry.store, controller: entry.controller, initial: entry.sessionId === initialSessionId.current && !entry.viewState.initialStarted ? props.initial : undefined, closeWhenIdle: false, visible: visible, inputActive: visible && !listFocused && !approval, escapeClosesPanel: showList, canReceiveInput: function acceptsCurrentInput(value, key) { const reservedKey = (key?.escape || value === "\u001b") && isPanelVisible() || key?.ctrl && (value === "t" || value === "a" || value === "l"); return !submittingRef.current && !approvalRef.current && (!consumedInputRef.current || forwardingInputRef.current) && !reservedKey && !modeRef.current.focused && props.manager.selected().sessionId === entry.sessionId; }, onDraftAttachmentsChange: function attachmentsChanged(names) { setDraftAttachments(function update(current) { return (current[entry.sessionId] ?? []).join("\0") === names.join("\0") ? current : { ...current, [entry.sessionId]: names }; }); }, onTerminalSizeChange: undefined, availableColumns: Math.max(1, columns - listWidth), availableRows: bodyRows, onResult: function fixedResult(result) { props.manager.handleResult(entry, result); props.onResult(result); } }) }, entry.sessionId);
379
+ }) }), wide && showList && !approval ? list : null] }), approvalCards.filter(function focused(card) { return approval?.sessionId === card.sessionId && approval.approvalId === card.approvalId; }).map(function card(card) {
380
+ const focused = approval?.sessionId === card.sessionId && approval.turnId === card.turnId && approval.approvalId === card.approvalId;
381
+ return _jsxs(Box, { flexDirection: "column", children: [_jsxs(Text, { wrap: "truncate", children: [card.entry.title, " \u00B7 \u5173\u8054\u4EFB\u52A1\u5BA1\u6279 \u00B7 ", focused ? "已聚焦 · d详情 · PgUp/PgDn · Esc返回输入" : "Ctrl+A聚焦,输入草稿保持可用"] }), _jsx(TuiApprovalPrompt, { height: 8, offset: focused ? detailOffset : 0, onMaximumOffset: focused ? function rememberMaximum(maximum) { approvalMaximumRef.current = maximum; } : undefined, pendingApproval: card.pending, selectedIndex: focused ? decisionIndex : 0, useColor: props.useColor, screenReader: props.screenReader, details: focused && details }), focused ? _jsx(Text, { wrap: "truncate", children: approvalValid ? `Enter确认:${createTuiApprovalOptions(card.pending)[decisionIndex]?.label}` : "请求已失效" }) : null] }, card.identity);
382
+ }), recoveryCards.filter(function focused(card) { return approval?.retry && approval.sessionId === card.sessionId; }).map(function retry(card) { return _jsxs(Text, { wrap: "truncate", children: [card.entry.title, " \u00B7 ", getCliInteractionLabel(card.entry.executionView), " \u00B7 ", approval?.retry && approval.sessionId === card.sessionId ? "Enter重试原决定 · Esc返回输入" : "Ctrl+A聚焦重试"] }, JSON.stringify([card.sessionId, card.turnId, card.approvalId])); }), related.some(function pending(entry) { return entry.store.getSnapshot().pendingApproval !== undefined; }) ? _jsx(Text, { wrap: "truncate", children: "\u5173\u8054\u4EFB\u52A1\u7B49\u5F85\u5BA1\u6279 \u00B7 Ctrl+A\u539F\u5730\u5904\u7406" }) : null, refreshingApproval ? _jsx(Text, { wrap: "truncate", children: "\u6B63\u5728\u5237\u65B0\u5F53\u524D\u5BA1\u6279 \u00B7 \u65E7\u8BF7\u6C42\u4E0D\u53EF\u64CD\u4F5C" }) : null, _jsxs(Text, { wrap: "truncate", children: ["Ctrl+A\u5BA1\u6279/\u56DE\u7B54 \u00B7 Ctrl+T\u4F1A\u8BDD \u00B7 Ctrl+L", selected.historyMore ? "加载历史页" : "刷新新增", " \u00B7 /resume\u6062\u590D \u00B7 Ctrl+C\u9000\u51FA"] })] }) });
383
+ }
@@ -5,9 +5,12 @@ import type { CliTuiSnapshot } from "./types.js";
5
5
  export declare const TuiStatusLine: import("react").NamedExoticComponent<{
6
6
  snapshot: CliTuiSnapshot;
7
7
  statusView?: CliStatusView;
8
+ sessionTitle?: string;
9
+ interactionLabel?: string;
8
10
  useColor: boolean;
9
11
  screenReader: boolean;
10
12
  selectionCharacters?: number;
13
+ escapeClosesPanel?: boolean;
11
14
  }>;
12
15
  /** 将最近的控制台信息固定在输入框上方,避免混入会话时间线或占用回答区域。 */
13
16
  export declare const TuiInfoLines: import("react").NamedExoticComponent<{
@@ -1,15 +1,18 @@
1
1
  import { jsxs as _jsxs, Fragment as _Fragment, jsx as _jsx } from "react/jsx-runtime";
2
2
  /** 状态栏与信息行:消费安全状态视图,渲染状态、模型、权限、context 与 workspace。 */
3
+ import { resolveCliActivityView } from "../activity-animation.js";
3
4
  import { memo } from "react";
4
5
  import { Box, Text } from "ink";
5
- import { formatTuiContextStatus } from "../context-report.js";
6
+ import { formatTuiContextStatus, formatTuiTurnUsageStatus } from "../context-report.js";
6
7
  import { CLI_TUI_COLORS, TUI_ACCENT_COLOR } from "../design-tokens.js";
7
8
  import { getTuiPermissionModeLabel, getTuiStatusLabel } from "./format.js";
8
9
  /** 渲染当前状态栏;配置行只消费安全状态视图,不读取 Runtime 或 checkpoint。 */
9
10
  export const TuiStatusLine = memo(function TuiStatusLine(props) {
10
11
  const suffix = `${props.screenReader ? " · screen reader" : ""}${props.selectionCharacters ? ` · ${props.selectionCharacters} chars selected` : ""}`;
11
- const runningHint = props.snapshot.status === "running" ? " · Esc interrupt · Enter 引导 · /queue <prompt> 排队" : "";
12
- let statusLabel = getTuiStatusLabel(props.snapshot.status);
12
+ const runningHint = props.escapeClosesPanel ? " · Esc关闭侧栏 · Ctrl+T选择会话" : props.snapshot.status === "running" ? " · Esc interrupt · Enter 引导 · /queue <prompt> 排队" : "";
13
+ // 底部状态与活动行消费相同结构化事实,不能在真实等待时仍笼统显示Working。
14
+ const waitingLabel = props.snapshot.status === "running" && props.snapshot.threadWait ? resolveCliActivityView({ activity: props.snapshot.activity, status: props.snapshot.status, now: Date.now(), threadWait: props.snapshot.threadWait })?.label : undefined;
15
+ let statusLabel = props.interactionLabel ?? waitingLabel ?? getTuiStatusLabel(props.snapshot.status);
13
16
  if (props.snapshot.cancellationRequested)
14
17
  statusLabel = "Stopping · press Ctrl+C again to exit";
15
18
  const statusColor = props.snapshot.status === "idle" ? undefined : props.useColor ? TUI_ACCENT_COLOR : undefined;
@@ -17,21 +20,24 @@ export const TuiStatusLine = memo(function TuiStatusLine(props) {
17
20
  const nextPermissionLabel = view?.nextPermissionMode;
18
21
  const permissionLabel = view ? getTuiPermissionModeLabel(view.permissionMode) : undefined;
19
22
  const nextPermissionModeLabel = nextPermissionLabel ? getTuiPermissionModeLabel(nextPermissionLabel) : undefined;
23
+ const sessionLine = props.sessionTitle ? _jsxs(Text, { wrap: props.screenReader ? "wrap" : "truncate", dimColor: props.useColor, children: ["\u4F1A\u8BDD\uFF1A", props.sessionTitle] }) : null;
20
24
  if (!view) {
21
25
  const hint = props.snapshot.status === "idle" ? " · /exit to quit" : runningHint;
22
- return _jsxs(Text, { bold: props.snapshot.status === "waiting_approval", color: statusColor, children: [statusLabel, suffix, hint] });
26
+ return _jsxs(Box, { flexDirection: "column", children: [_jsxs(Text, { wrap: props.screenReader ? "wrap" : "truncate", bold: props.snapshot.status === "waiting_approval", color: statusColor, children: [statusLabel, suffix, hint] }), sessionLine] });
23
27
  }
24
28
  const permissionColor = props.useColor && view.permissionMode === "full_access" ? CLI_TUI_COLORS.permissionFullAccess : undefined;
25
29
  const nextPermissionColor = props.useColor && nextPermissionLabel === "full_access" ? CLI_TUI_COLORS.permissionFullAccess : undefined;
26
30
  // 无数据/无 Session 统一显示 unknown,不猜测窗口或输出伪 0%。
27
31
  const contextLabel = formatTuiContextStatus(view.contextUsage ?? null);
28
- return (_jsxs(Box, { flexDirection: "column", marginTop: 1, children: [_jsxs(Text, { bold: props.snapshot.status === "waiting_approval", color: statusColor, children: [statusLabel, suffix, runningHint] }), _jsxs(Text, { dimColor: props.useColor, children: ["model: ", view.model, " \u00B7 effort: ", view.effort, " \u00B7 ", _jsxs(Text, { color: permissionColor, bold: true, dimColor: false, children: ["permission: ", permissionLabel, " (", view.permissionMode, ")"] }), view.nextModel ? _jsxs(_Fragment, { children: [" \u00B7 next model: ", view.nextModel] }) : null, view.nextEffort ? _jsxs(_Fragment, { children: [" \u00B7 next effort: ", view.nextEffort] }) : null, nextPermissionLabel ? _jsxs(_Fragment, { children: [" \u00B7 next permission: ", _jsxs(Text, { color: nextPermissionColor, bold: true, dimColor: false, children: [nextPermissionModeLabel, " (", nextPermissionLabel, ")"] })] }) : null] }), _jsxs(Text, { dimColor: props.useColor, children: ["context: ", contextLabel] }), _jsxs(Text, { dimColor: props.useColor, children: ["workspace: ", view.workspaceRoot ?? "unavailable"] })] }));
32
+ // 累计用量行与 context 行同节奏刷新;无 checkpoint 时显示 unknown,不伪造 0。
33
+ const turnUsageLabel = formatTuiTurnUsageStatus(view.turnUsage);
34
+ return (_jsxs(Box, { flexDirection: "column", marginTop: 1, children: [_jsxs(Text, { wrap: props.screenReader ? "wrap" : "truncate", bold: props.snapshot.status === "waiting_approval", color: statusColor, children: [statusLabel, suffix, runningHint] }), _jsxs(Text, { wrap: props.screenReader ? "wrap" : "truncate", dimColor: props.useColor, children: ["model: ", view.model, " \u00B7 effort: ", view.effort, " \u00B7 ", _jsxs(Text, { wrap: props.screenReader ? "wrap" : "truncate", color: permissionColor, bold: true, dimColor: false, children: ["permission: ", permissionLabel, " (", view.permissionMode, ")"] }), view.nextModel ? _jsxs(_Fragment, { children: [" \u00B7 next model: ", view.nextModel] }) : null, view.nextEffort ? _jsxs(_Fragment, { children: [" \u00B7 next effort: ", view.nextEffort] }) : null, nextPermissionLabel ? _jsxs(_Fragment, { children: [" \u00B7 next permission: ", _jsxs(Text, { wrap: props.screenReader ? "wrap" : "truncate", color: nextPermissionColor, bold: true, dimColor: false, children: [nextPermissionModeLabel, " (", nextPermissionLabel, ")"] })] }) : null] }), _jsxs(Text, { wrap: props.screenReader ? "wrap" : "truncate", dimColor: props.useColor, children: ["context: ", contextLabel] }), _jsxs(Text, { wrap: props.screenReader ? "wrap" : "truncate", dimColor: props.useColor, children: ["tokens: ", turnUsageLabel] }), _jsxs(Text, { wrap: props.screenReader ? "wrap" : "truncate", dimColor: props.useColor, children: ["workspace: ", view.workspaceRoot ?? "unavailable"] }), sessionLine] }));
29
35
  });
30
36
  /** 将最近的控制台信息固定在输入框上方,避免混入会话时间线或占用回答区域。 */
31
37
  export const TuiInfoLines = memo(function TuiInfoLines(props) {
32
38
  if (props.messages.length === 0)
33
39
  return null;
34
40
  return (_jsx(Box, { flexDirection: "column", marginTop: 1, children: props.messages.map(function renderInfo(message, index) {
35
- return _jsxs(Text, { color: props.useColor ? CLI_TUI_COLORS.copilotMuted : undefined, children: ["info: ", message] }, `${index}:${message}`);
41
+ return _jsxs(Text, { wrap: "truncate", color: props.useColor ? CLI_TUI_COLORS.copilotMuted : undefined, children: ["info: ", message] }, `${index}:${message}`);
36
42
  }) }));
37
43
  });
package/dist/tui/store.js CHANGED
@@ -4,6 +4,7 @@ import { TUI_EVENT_PUBLISH_INTERVAL_MS } from "./constants.js";
4
4
  import { isTerminalStatus } from "./format.js";
5
5
  import { recordTuiPerformanceDiagnostic } from "./performance-diagnostics.js";
6
6
  import { captureTuiInputPosition } from "./timeline/turn-items.js";
7
+ import { getCliTuiExecutionMs } from "./types.js";
7
8
  /** 创建 TUI 初始快照。 */
8
9
  function createInitialTuiSnapshot(now = Date.now()) {
9
10
  return {
@@ -106,10 +107,10 @@ export function createCliTuiStore() {
106
107
  const metrics = metricsByTurn.get(turnId);
107
108
  const thoughtDurationMs = metrics?.firstAnswerAt === undefined
108
109
  ? undefined
109
- : Math.max(0, metrics.firstAnswerAt - metrics.startedAt);
110
+ : metrics.firstAnswerDurationMs ?? 0;
110
111
  const totalDurationMs = metrics?.completedAt === undefined
111
112
  ? undefined
112
- : Math.max(0, metrics.completedAt - metrics.startedAt);
113
+ : getCliTuiExecutionMs(metrics, metrics.completedAt);
113
114
  // 终态先保留当前 live Turn,让这一帧同时接住最后的 answer/status block;
114
115
  // 立即清空会让外层历史区过滤掉同一 Turn,导致最后一段回答不可见。
115
116
  snapshot = {
@@ -237,6 +238,10 @@ export function createCliTuiStore() {
237
238
  });
238
239
  },
239
240
  acceptEvent(event, projection) {
241
+ if (event.type === "thread_wait") {
242
+ publish({ ...snapshot, threadWait: projection.threadWait });
243
+ return;
244
+ }
240
245
  // 用量变化只刷新动态状态栏事实,不进入 transcript 时间线或 scrollback。
241
246
  if (event.type === "context_usage") {
242
247
  if (snapshot.contextUsage === event.usage)
@@ -247,6 +252,9 @@ export function createCliTuiStore() {
247
252
  // Esc 后只等待 Runtime 的终态;取消请求之后已经在途的回答/工具尾部事件不再进入可见时间线。
248
253
  if (snapshot.cancellationRequested && !(event.type === "status" && isTerminalStatus(event.status)))
249
254
  return;
255
+ if (event.type === "turn_started" && finalizedTurns.delete(event.turnId)) {
256
+ snapshot = { ...snapshot, transcript: snapshot.transcript.filter(function previousSegment(item) { return item.kind !== "turn" || item.turnId !== event.turnId; }) };
257
+ }
250
258
  const currentEvents = eventsByTurn.get(event.turnId) ?? [];
251
259
  if (currentEvents.some(function hasSequence(item) { return item.type === event.type && item.seq === event.seq; }))
252
260
  return;
@@ -260,12 +268,17 @@ export function createCliTuiStore() {
260
268
  const eventTime = Date.now();
261
269
  const previousMetrics = metricsByTurn.get(event.turnId);
262
270
  const nextMetrics = {
263
- startedAt: event.type === "turn_started" ? eventTime : previousMetrics?.startedAt ?? eventTime,
271
+ startedAt: previousMetrics?.startedAt ?? eventTime,
272
+ elapsedMs: projection.presentation?.executionByTurn?.[event.turnId]?.elapsedMs ?? previousMetrics?.elapsedMs,
273
+ runningSince: projection.presentation?.executionByTurn?.[event.turnId]?.runningSince,
274
+ firstAnswerDurationMs: previousMetrics?.firstAnswerDurationMs,
264
275
  firstAnswerAt: previousMetrics?.firstAnswerAt,
265
- completedAt: previousMetrics?.completedAt,
276
+ completedAt: event.type === "turn_started" ? undefined : previousMetrics?.completedAt,
266
277
  };
267
- if (event.type === "answer_delta" && nextMetrics.firstAnswerAt === undefined)
278
+ if (event.type === "answer_delta" && nextMetrics.firstAnswerAt === undefined) {
268
279
  nextMetrics.firstAnswerAt = eventTime;
280
+ nextMetrics.firstAnswerDurationMs = getCliTuiExecutionMs(nextMetrics, eventTime);
281
+ }
269
282
  // Core 的 reset/discard 表示当前采样的暂定文字不能展示;下一次真正回答重新计时。
270
283
  if (event.type === "answer_reset")
271
284
  nextMetrics.firstAnswerAt = undefined;
@@ -283,6 +296,7 @@ export function createCliTuiStore() {
283
296
  hasLiveApprovalEvent: isNewTurn ? event.type === "approval_required" : snapshot.hasLiveApprovalEvent || event.type === "approval_required",
284
297
  activity: nextActivity,
285
298
  status: projection.status,
299
+ threadWait: projection.threadWait,
286
300
  recoverable: projection.recoverable,
287
301
  pendingApproval: projection.pendingApproval && !submittedApprovalIds.has(projection.pendingApproval.approvalId)
288
302
  ? { ...projection.pendingApproval }
@@ -322,6 +336,13 @@ export function createCliTuiStore() {
322
336
  }
323
337
  },
324
338
  syncProjection(projection) {
339
+ // Controller已过滤正在提交或已保存的请求,权威pending重现表示保存失败,可重试原请求。
340
+ if (projection.pendingApproval)
341
+ submittedApprovalIds.delete(projection.pendingApproval.approvalId);
342
+ // 身份失效只关闭交互;已打开的旧正文保留为最后观察到的历史,不伪造终态。
343
+ if (snapshot.liveTurnId && projection.turnId !== snapshot.liveTurnId && snapshot.liveEvents.length && !snapshot.transcript.some(function existing(item) { return item.kind === "turn" && item.turnId === snapshot.liveTurnId; })) {
344
+ snapshot = { ...snapshot, transcript: [...snapshot.transcript, { kind: "turn", key: "observed:" + snapshot.liveTurnId, turnId: snapshot.liveTurnId, events: snapshot.liveEvents, presentation: snapshot.livePresentation, status: snapshot.status }] };
345
+ }
325
346
  if (projection.turnId && !eventsByTurn.has(projection.turnId) && projection.events.length > 0)
326
347
  eventsByTurn.set(projection.turnId, projection.events.filter(function belongs(event) { return event.turnId === projection.turnId; }));
327
348
  const turnIsFinalized = projection.turnId ? finalizedTurns.has(projection.turnId) : false;
@@ -350,6 +371,7 @@ export function createCliTuiStore() {
350
371
  hasLiveApprovalEvent: Boolean(keepLiveTurn && !isNewTurn && snapshot.hasLiveApprovalEvent),
351
372
  activity,
352
373
  status: projection.status,
374
+ threadWait: projection.threadWait,
353
375
  recoverable: projection.recoverable,
354
376
  pendingApproval: projection.pendingApproval && !submittedApprovalIds.has(projection.pendingApproval.approvalId)
355
377
  ? { ...projection.pendingApproval }
@@ -4,7 +4,7 @@ import { memo, useRef } from "react";
4
4
  import { Box, Text } from "ink";
5
5
  import { TUI_ACCENT_COLOR } from "../../design-tokens.js";
6
6
  import { TUI_AGENT_LABEL } from "../constants.js";
7
- import { formatTuiDuration, formatTuiInputConsumed, getTuiApprovalDecisionLabel, isTerminalStatus } from "../format.js";
7
+ import { formatTuiInputConsumed, getTuiApprovalDecisionLabel, isTerminalStatus } from "../format.js";
8
8
  import { TuiMarkdown } from "../markdown/markdown.js";
9
9
  import { TuiPromptLine } from "../transcript.js";
10
10
  import { renderTuiToolTreeEvent } from "./tool-tree.js";
@@ -143,9 +143,8 @@ function renderTuiLiveTimelineBlock(block, useColor, renderMarkdown, maximumWidt
143
143
  */
144
144
  export const TuiLiveTimeline = memo(function TuiLiveTimeline(props) {
145
145
  const blocks = useCliTuiTimelineBlocks(props.events);
146
- const firstAnswerKey = blocks.find(function findFirstAnswer(block) { return block.kind === "answer"; })?.key;
147
146
  function renderBlock(block) {
148
- return (_jsxs(Box, { flexDirection: "column", children: [block.key === firstAnswerKey && props.metrics?.firstAnswerAt !== undefined ? _jsxs(Text, { dimColor: props.useColor, children: ["Thought for ", formatTuiDuration(Math.max(0, props.metrics.firstAnswerAt - props.metrics.startedAt))] }) : null, renderTuiLiveTimelineBlock(block, props.useColor, isTerminalStatus(props.status), props.maximumWidth)] }, block.key));
147
+ return (_jsx(Box, { flexDirection: "column", children: renderTuiLiveTimelineBlock(block, props.useColor, isTerminalStatus(props.status), props.maximumWidth) }, block.key));
149
148
  }
150
149
  return (_jsx(_Fragment, { children: blocks.map(function renderDynamicTimelineBlock(block) {
151
150
  return renderBlock(block);
@@ -2,6 +2,7 @@ import { jsxs as _jsxs } from "react/jsx-runtime";
2
2
  /** 当前思考进度汇总;只统计已发出的 tool_started,避免结果重复计数。 */
3
3
  import { useEffect, useState } from "react";
4
4
  import { Text } from "ink";
5
+ import { getCliTuiExecutionMs } from "../types.js";
5
6
  import { formatTuiDuration } from "../format.js";
6
7
  /** 汇总 Claude Code 风格的当前思考进度;只统计已发出的 tool_started,避免结果重复计数。 */
7
8
  export function TuiLiveProgressSummary(props) {
@@ -17,7 +18,7 @@ export function TuiLiveProgressSummary(props) {
17
18
  return null;
18
19
  // Todo 的 activeForm 是模型声明的稳定活动文案,优先于宿主猜测的工具动词短语。
19
20
  if (props.activeTodoForm) {
20
- return _jsxs(Text, { dimColor: props.useColor, children: [props.activeTodoForm, " \u00B7 ", formatTuiDuration(Math.max(0, now - props.metrics.startedAt)), "\u2026"] });
21
+ return _jsxs(Text, { dimColor: props.useColor, children: [props.activeTodoForm, " \u00B7 ", formatTuiDuration(getCliTuiExecutionMs(props.metrics, now)), "\u2026"] });
21
22
  }
22
23
  const counts = new Map();
23
24
  for (const event of props.events) {
@@ -38,6 +39,6 @@ export function TuiLiveProgressSummary(props) {
38
39
  phrase("run_command", "running", "shell command");
39
40
  phrase("write_file", "writing", "file");
40
41
  phrase("edit_file", "editing", "file");
41
- const thinking = `Thinking for ${formatTuiDuration(Math.max(0, now - props.metrics.startedAt))}`;
42
+ const thinking = `Thinking for ${formatTuiDuration(getCliTuiExecutionMs(props.metrics, now))}`;
42
43
  return _jsxs(Text, { dimColor: props.useColor, children: [thinking, phrases.length > 0 ? `, ${phrases.join(", ")}` : "", "\u2026"] });
43
44
  }
@@ -34,8 +34,7 @@ export function renderTimeline(events, useColor, timing, maximumWidth = 80, scre
34
34
  function flushAnswer() {
35
35
  if (!answer)
36
36
  return;
37
- const isFirstAnswer = answerSeq === 0;
38
- nodes.push(_jsxs(Box, { flexDirection: "column", children: [isFirstAnswer && timing?.thoughtDurationMs !== undefined ? _jsxs(Text, { dimColor: useColor, children: ["Thought for ", formatTuiDuration(timing.thoughtDurationMs)] }) : null, _jsxs(Text, { bold: true, color: useColor ? TUI_ACCENT_COLOR : undefined, children: ["\u2022 ", TUI_AGENT_LABEL] }), _jsx(TuiMarkdown, { content: answer, keyPrefix: "answer:" + String(answerSeq), useColor: useColor, maximumWidth: maximumWidth })] }, "answer:" + String(answerSeq++)));
37
+ nodes.push(_jsxs(Box, { flexDirection: "column", children: [_jsxs(Text, { bold: true, color: useColor ? TUI_ACCENT_COLOR : undefined, children: ["\u2022 ", TUI_AGENT_LABEL] }), _jsx(TuiMarkdown, { content: answer, keyPrefix: "answer:" + String(answerSeq), useColor: useColor, maximumWidth: maximumWidth })] }, "answer:" + String(answerSeq++)));
39
38
  lastAnswerNodeIndex = nodes.length - 1;
40
39
  answer = "";
41
40
  }