@qjp88995/agent-chat-web 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 (41) hide show
  1. package/dist/display/block-layout.d.ts +90 -0
  2. package/dist/display/block-layout.d.ts.map +1 -0
  3. package/dist/display/block-layout.js +133 -0
  4. package/dist/display/block-layout.js.map +1 -0
  5. package/dist/display/config.d.ts +52 -0
  6. package/dist/display/config.d.ts.map +1 -0
  7. package/dist/display/config.js +16 -0
  8. package/dist/display/config.js.map +1 -0
  9. package/dist/display/display-names.d.ts +27 -0
  10. package/dist/display/display-names.d.ts.map +1 -0
  11. package/dist/display/display-names.js +34 -0
  12. package/dist/display/display-names.js.map +1 -0
  13. package/dist/display/index.d.ts +20 -0
  14. package/dist/display/index.d.ts.map +1 -0
  15. package/dist/display/index.js +14 -0
  16. package/dist/display/index.js.map +1 -0
  17. package/dist/display/process-line.d.ts +102 -0
  18. package/dist/display/process-line.d.ts.map +1 -0
  19. package/dist/display/process-line.js +216 -0
  20. package/dist/display/process-line.js.map +1 -0
  21. package/dist/display/reasoning-status.d.ts +28 -0
  22. package/dist/display/reasoning-status.d.ts.map +1 -0
  23. package/dist/display/reasoning-status.js +53 -0
  24. package/dist/display/reasoning-status.js.map +1 -0
  25. package/dist/display/spawn-display.d.ts +32 -0
  26. package/dist/display/spawn-display.d.ts.map +1 -0
  27. package/dist/display/spawn-display.js +39 -0
  28. package/dist/display/spawn-display.js.map +1 -0
  29. package/dist/display/tool-display.d.ts +36 -0
  30. package/dist/display/tool-display.d.ts.map +1 -0
  31. package/dist/display/tool-display.js +61 -0
  32. package/dist/display/tool-display.js.map +1 -0
  33. package/package.json +7 -2
  34. package/src/display/block-layout.ts +195 -0
  35. package/src/display/config.ts +72 -0
  36. package/src/display/display-names.ts +46 -0
  37. package/src/display/index.ts +67 -0
  38. package/src/display/process-line.ts +313 -0
  39. package/src/display/reasoning-status.ts +51 -0
  40. package/src/display/spawn-display.ts +72 -0
  41. package/src/display/tool-display.ts +68 -0
@@ -0,0 +1,195 @@
1
+ import {
2
+ ASK_TOOL_NAME,
3
+ DELEGATE_TOOL_NAME,
4
+ } from '@qjp88995/agent-runtime/schema';
5
+
6
+ import type { MessageBlock, TraceNode } from '../trace/index.js';
7
+ import { displayConfig } from './config.js';
8
+ import { toolDisplay } from './tool-display.js';
9
+
10
+ /**
11
+ * 把一条助手消息的块序列排成**渲染布局**:文字块原样,夹在文字之间的连续
12
+ * 思考/工具块折成一组「过程卡」。
13
+ *
14
+ * 存在的理由是篇幅:一轮里模型动辄十几次读写文件,每次一张卡,正文被推到
15
+ * 屏幕外、用户要滚过一整屏工具卡才看到结论。而这些卡本来就是默认折叠的辅助
16
+ * 信息——用户真要看某一步才点开。折成一组之后,默认只剩一行「N 步 · 思考 ·
17
+ * 读文件 ×3 · 改文件」,点开才铺回原来那几张卡。
18
+ *
19
+ * **什么会打断一组(不进过程组,在那一轮的卡里自己单独一行 / 一节)**:
20
+ * - 文字块——它是结论,本就该独立可见;组的边界就是「两段文字之间」;
21
+ * - `Delegate`——子 Agent 卡是一等公民(有下钻/停止按钮、右栏联动高亮),
22
+ * 收进折叠组里等于把「派了个子 Agent 出去」藏起来;
23
+ * - `Ask`——Agent 停下来问了用户一件事,这一轮就停在这儿;问了什么、
24
+ * 答了什么是这一轮的**结果**而不是过程,收进「N 步」里等于把它藏起来;
25
+ * - 应用登记的单独成行工具(`configureChatDisplay` 的 `standaloneTools`,如 agent-base
26
+ * 分身线的三个确认面板)——「提议了什么、批了什么」同理是这一轮的结果。
27
+ * - 运行级错误节点(`kind:'error'`)——失败必须被看见,不能靠用户点开才发现。
28
+ *
29
+ * 单个工具调用失败(`status:'failed'`)**不打断**:那多半是模型自己能恢复的
30
+ * (`Edit` 没匹配上再来一次),组的状态位会汇总成「失败」提醒用户点开看。
31
+ *
32
+ * **组至少两项**(`ACTIVITY_MIN_ITEMS`):一项的组只是多套了一层壳,什么都没
33
+ * 省。于是流式期间会看到「先是一张思考卡,第二步一来变成一张组卡」——这次重排
34
+ * 是刻意接受的代价,换来的是不必为「只有一项」发明另一种卡。
35
+ *
36
+ * 纯函数、零 UI:两个 app 各自决定组卡长什么样,这里只决定「哪些块归到一起」。
37
+ */
38
+
39
+ export const ACTIVITY_MIN_ITEMS = 2;
40
+
41
+ export type ActivityItem =
42
+ | {
43
+ type: 'reasoning';
44
+ /** 在原块序列里的下标——渲染 key 用它,稳定且不依赖内容。 */
45
+ index: number;
46
+ text: string;
47
+ durationMs?: number;
48
+ /** 这段思考此刻还在产出(它是消息的最后一块、且消息仍在流)。 */
49
+ thinking: boolean;
50
+ }
51
+ | { type: 'trace'; index: number; node: TraceNode };
52
+
53
+ export type LayoutBlock =
54
+ | {
55
+ type: 'text';
56
+ index: number;
57
+ text: string;
58
+ /** 正在流的那一段(最后一块且消息仍在流)。 */
59
+ streaming: boolean;
60
+ }
61
+ | ActivityItem
62
+ | { type: 'activity'; index: number; items: ActivityItem[] };
63
+
64
+ export interface LayoutInput {
65
+ /** `buildTraceTree` 的顶层节点按 key 索引。 */
66
+ nodeByKey: ReadonlyMap<string, TraceNode>;
67
+ /** 主视图要隐藏的子 run 节点(见 `hiddenRunKeys`)。 */
68
+ hidden: ReadonlySet<string>;
69
+ streaming: boolean;
70
+ }
71
+
72
+ /** 这个节点不能收进过程组(在卡里自己单独一行 / 一节)。 */
73
+ export function standsAlone(node: TraceNode): boolean {
74
+ if (node.kind === 'error') return true;
75
+ return (
76
+ node.kind === 'tool' &&
77
+ (node.toolName === DELEGATE_TOOL_NAME ||
78
+ node.toolName === ASK_TOOL_NAME ||
79
+ displayConfig().standaloneTools.has(node.toolName ?? ''))
80
+ );
81
+ }
82
+
83
+ export function layoutBlocks(
84
+ blocks: readonly MessageBlock[],
85
+ { nodeByKey, hidden, streaming }: LayoutInput
86
+ ): LayoutBlock[] {
87
+ const out: LayoutBlock[] = [];
88
+ let run: ActivityItem[] = [];
89
+ const lastIdx = blocks.length - 1;
90
+
91
+ const flush = () => {
92
+ if (run.length === 0) return;
93
+ if (run.length >= ACTIVITY_MIN_ITEMS) {
94
+ out.push({ type: 'activity', index: run[0].index, items: run });
95
+ } else {
96
+ out.push(...run);
97
+ }
98
+ run = [];
99
+ };
100
+
101
+ blocks.forEach((block, index) => {
102
+ const isTail = streaming && index === lastIdx;
103
+ if (block.type === 'text') {
104
+ // 空文字块不占位(流式首帧可能是空 delta);也不打断当前的组——它在
105
+ // 屏幕上什么都不是,不该把两侧的工具卡拆成两组。
106
+ if (block.text === '') return;
107
+ flush();
108
+ out.push({ type: 'text', index, text: block.text, streaming: isTail });
109
+ return;
110
+ }
111
+ if (block.type === 'reasoning') {
112
+ if (block.text === '') return;
113
+ run.push({
114
+ type: 'reasoning',
115
+ index,
116
+ text: block.text,
117
+ ...(block.durationMs != null ? { durationMs: block.durationMs } : {}),
118
+ thinking: isTail,
119
+ });
120
+ return;
121
+ }
122
+ // 子 run 节点隐藏(subagent 由其 Delegate 工具节点代表);查不到节点的
123
+ // key 同样跳过(trace 还没到、或事件流缺了这一条)。
124
+ if (hidden.has(block.key)) return;
125
+ const node = nodeByKey.get(block.key);
126
+ if (!node) return;
127
+ if (standsAlone(node)) {
128
+ flush();
129
+ out.push({ type: 'trace', index, node });
130
+ return;
131
+ }
132
+ run.push({ type: 'trace', index, node });
133
+ });
134
+ flush();
135
+ return out;
136
+ }
137
+
138
+ export interface ActivitySummary {
139
+ /** 组里有几步(思考也算一步)。 */
140
+ count: number;
141
+ /**
142
+ * 按首次出现顺序列出各类步骤,同类合并计数:「思考 · 读文件 ×3 · 改文件」。
143
+ * 工具的中文名来自 `toolDisplay`,与单张工具卡上的 chip 同一份。
144
+ */
145
+ label: string;
146
+ /** 有任何一步还在进行(工具 running、或最后一段思考还在产出)。 */
147
+ running: boolean;
148
+ /** 失败的工具调用数(含后来被补救过的)。 */
149
+ failed: number;
150
+ /**
151
+ * 组里**最后一个**工具调用失败了(其后的思考不算补救——那是在想这次失败)。
152
+ *
153
+ * 组头状态读它,不读 `failed > 0`:模型撞到工具报错后通常会换参数重试,
154
+ * 后面一次成功就算过去了;按「有过失败」判的话,这种组永远挂着红色「失败」,
155
+ * 真正没救回来的那组反而跟它长得一样。
156
+ */
157
+ lastFailed: boolean;
158
+ }
159
+
160
+ /** 组头的状态位:进行中 > 最后一步失败 > 完成。见 `ActivitySummary.lastFailed`。 */
161
+ export function activityStatus(
162
+ summary: ActivitySummary
163
+ ): 'running' | 'failed' | 'done' {
164
+ if (summary.running) return 'running';
165
+ return summary.lastFailed ? 'failed' : 'done';
166
+ }
167
+
168
+ /** 组卡头部要显示的汇总。 */
169
+ export function summarizeActivity(
170
+ items: readonly ActivityItem[]
171
+ ): ActivitySummary {
172
+ const counts = new Map<string, number>();
173
+ let running = false;
174
+ let failed = 0;
175
+ let lastFailed = false;
176
+ for (const item of items) {
177
+ let label: string;
178
+ if (item.type === 'reasoning') {
179
+ label = '思考';
180
+ if (item.thinking) running = true;
181
+ } else {
182
+ const node = item.node;
183
+ label = node.kind === 'error' ? '错误' : toolDisplay(node.toolName).label;
184
+ if (node.status === 'running') running = true;
185
+ const isFailed = node.status === 'failed' || node.kind === 'error';
186
+ if (isFailed) failed += 1;
187
+ lastFailed = isFailed;
188
+ }
189
+ counts.set(label, (counts.get(label) ?? 0) + 1);
190
+ }
191
+ const label = [...counts]
192
+ .map(([name, n]) => (n > 1 ? `${name} ×${n}` : name))
193
+ .join(' · ');
194
+ return { count: items.length, label, running, failed, lastFailed };
195
+ }
@@ -0,0 +1,72 @@
1
+ import type { ChatDisplayRegister } from './index.js';
2
+
3
+ /**
4
+ * 展示配置:工具叫什么、用什么图标、哪些工具在对话里单独成行——这些是应用的事,
5
+ * 由应用在启动时注入一次(`configureChatDisplay`)。包里只有「怎么查」的逻辑。
6
+ *
7
+ * **模块级而不是 context**,理由同 `display-names.ts`:`toolDisplay` 被
8
+ * `processHeadline`、`summarizeActivity` 这类纯函数在任意深处调用,一路传参等于改十几个签名。
9
+ * 应用在模块加载时就配好(早于任何渲染),之后不再变。
10
+ */
11
+
12
+ /**
13
+ * 图标名的类型。默认是 `string`;应用经声明合并收窄成自己的图标名,例如:
14
+ *
15
+ * ```ts
16
+ * declare module '@qjp88995/agent-chat-web/display' {
17
+ * interface ChatDisplayRegister { icon: FluentEmojiName }
18
+ * }
19
+ * ```
20
+ */
21
+ export type ToolIcon = ChatDisplayRegister extends { icon: infer I extends string }
22
+ ? I
23
+ : string;
24
+
25
+ export type ToolTone =
26
+ 'purple' | 'blue' | 'cyan' | 'green' | 'amber' | 'neutral';
27
+
28
+ export interface ToolDisplay {
29
+ /** 图标名(应用自己的图标集,见 `ToolIcon`)。 */
30
+ icon: ToolIcon;
31
+ /** 面向人的中文标签。兜底时 = 原始工具名。 */
32
+ label: string;
33
+ tone: ToolTone;
34
+ }
35
+
36
+ export interface ChatDisplayConfig {
37
+ /** 工具名 → 图标 / 中文标签 / 色调。未登记的工具走兜底(`fallbackIcon` + 原始工具名 + 中性色)。 */
38
+ tools: Readonly<Record<string, ToolDisplay>>;
39
+ /** 未登记工具的图标。 */
40
+ fallbackIcon: ToolIcon;
41
+ /** `Delegate` 那一行的图标:派一个新的 / 让现成的继续做(追加任务)。 */
42
+ spawnIcon: ToolIcon;
43
+ followUpIcon: ToolIcon;
44
+ /**
45
+ * 除 `Delegate`、`Ask`、运行级错误节点之外,还有哪些工具不收进过程组、在对话里单独成行
46
+ * (它们是这一轮的结果,不是过程;见 `block-layout.ts`)。
47
+ */
48
+ standaloneTools: ReadonlySet<string>;
49
+ /**
50
+ * 从一次工具调用的 `ref` 里取落盘后的权威路径(过程行「读文件 初稿.md」里的对象优先用它)。
51
+ * 应用没有这种 ref 就返回 null。
52
+ */
53
+ refPath: (ref: Record<string, unknown> | null | undefined) => string | null;
54
+ }
55
+
56
+ let current: ChatDisplayConfig = {
57
+ tools: {},
58
+ fallbackIcon: '' as ToolIcon,
59
+ spawnIcon: '' as ToolIcon,
60
+ followUpIcon: '' as ToolIcon,
61
+ standaloneTools: new Set(),
62
+ refPath: () => null,
63
+ };
64
+
65
+ export function configureChatDisplay(config: ChatDisplayConfig): void {
66
+ current = config;
67
+ }
68
+
69
+ /** 包内取当前配置。 */
70
+ export function displayConfig(): ChatDisplayConfig {
71
+ return current;
72
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * 界面显示名的登记处(应用后台配的「名字 → 显示名」,agent-base 是 api `GET /display-names`)。
3
+ *
4
+ * **模块级而不是 context**:工具名的叫法出在 `toolDisplay` 里,而它被 `processHeadline`、
5
+ * 运行状态行这类纯函数在任意深处调用,一路传参等于改十几个签名。代价是改了之后
6
+ * 已经算好的东西不会自己重算——所以由应用(agent-base 是 `@ab/chat-ui` 的
7
+ * `DisplayNamesProvider`)在取到数据时写进来,并经 context 让对话件重渲染一次。
8
+ *
9
+ * 没配的一律退回默认:工具用 `tool-display` 里的叫法,子 Agent 用名字本身。
10
+ */
11
+
12
+ /** 每一类一张「名字 → 显示名」,没配的不出现。 */
13
+ export interface DisplayNames {
14
+ tool: Readonly<Record<string, string>>;
15
+ subagent: Readonly<Record<string, string>>;
16
+ /** 内置子 Agent 在代码里登记的默认叫法——不是配置,配的显示名优先。 */
17
+ subagentDefaults: Readonly<Record<string, string>>;
18
+ }
19
+
20
+ let current: DisplayNames = {
21
+ tool: {},
22
+ subagent: {},
23
+ subagentDefaults: {},
24
+ };
25
+
26
+ export function setDisplayNames(names: DisplayNames): void {
27
+ current = names;
28
+ }
29
+
30
+ /** 后台给这个工具配的显示名;没配是 null(调用方用自己的默认)。 */
31
+ export function toolLabelOverride(
32
+ toolName: string | null | undefined
33
+ ): string | null {
34
+ return toolName ? (current.tool[toolName] ?? null) : null;
35
+ }
36
+
37
+ /**
38
+ * 子 Agent 在界面上叫什么:配了显示名用显示名,否则用内置子 Agent 的默认叫法
39
+ * (`subagentDefaults`,代码里登记的中文名),再否则用名字本身;名字都没有是 null
40
+ * (调用方决定兜底词,比如「子 Agent」)。
41
+ */
42
+ export function subagentLabel(name: string | null | undefined): string | null {
43
+ const n = name?.trim();
44
+ if (!n) return null;
45
+ return current.subagent[n] ?? current.subagentDefaults[n] ?? n;
46
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * 展示逻辑:工具叫什么、过程怎么折组、过程行说什么、思考时长怎么写。纯函数、零 UI。
3
+ *
4
+ * 工具的图标 / 中文名、哪些工具单独成行这类应用的事,由应用经 `configureChatDisplay`
5
+ * 注入;图标名的类型经 `ChatDisplayRegister` 声明合并收窄(见 `config.ts` 的 `ToolIcon`)。
6
+ */
7
+
8
+ /**
9
+ * 应用经声明合并登记自己的类型。目前只有 `icon`(图标名),不登记就是 `string`。
10
+ * 必须声明在这个入口文件里:声明合并认的是声明所在的模块,转出的接口合并不进来。
11
+ */
12
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
13
+ export interface ChatDisplayRegister {}
14
+
15
+ export {
16
+ ACTIVITY_MIN_ITEMS,
17
+ type ActivityItem,
18
+ activityStatus,
19
+ type ActivitySummary,
20
+ type LayoutBlock,
21
+ layoutBlocks,
22
+ type LayoutInput,
23
+ standsAlone,
24
+ summarizeActivity,
25
+ } from './block-layout.js';
26
+ export {
27
+ type ChatDisplayConfig,
28
+ configureChatDisplay,
29
+ type ToolDisplay,
30
+ type ToolIcon,
31
+ type ToolTone,
32
+ } from './config.js';
33
+ export {
34
+ type DisplayNames,
35
+ setDisplayNames,
36
+ subagentLabel,
37
+ toolLabelOverride,
38
+ } from './display-names.js';
39
+ export {
40
+ activityKey,
41
+ digestProcess,
42
+ failureText,
43
+ type ProcessDigest,
44
+ type ProcessHeadline,
45
+ processHeadline,
46
+ processTimeline,
47
+ stepObject,
48
+ stepText,
49
+ thinkingNeighbours,
50
+ type TimelineEntry,
51
+ timelineKeys,
52
+ type TimelinePick,
53
+ timelinePicks,
54
+ } from './process-line.js';
55
+ export { formatThinkingDuration, thinkingLabel } from './reasoning-status.js';
56
+ export {
57
+ type DelegateDisplay,
58
+ spawnAgentDisplay,
59
+ type SubagentIdentity,
60
+ traceStepDisplay,
61
+ } from './spawn-display.js';
62
+ export {
63
+ defaultToolLabel,
64
+ FALLBACK_TONE,
65
+ toolDisplay,
66
+ toolInputProgressLabel,
67
+ } from './tool-display.js';
@@ -0,0 +1,313 @@
1
+ import type { TraceNode } from '../trace/index.js';
2
+ import {
3
+ type ActivityItem,
4
+ type LayoutBlock,
5
+ standsAlone,
6
+ } from './block-layout.js';
7
+ import { displayConfig } from './config.js';
8
+ import { formatThinkingDuration, thinkingLabel } from './reasoning-status.js';
9
+ import { toolDisplay } from './tool-display.js';
10
+
11
+ /**
12
+ * 一段过程(两段文字之间的思考与工具)在对话里的那一行小字要说什么
13
+ * (2026-09-26「过程行做减法」可视稿:三层折叠减成一层)。纯函数、零 UI。
14
+ */
15
+
16
+ /**
17
+ * 从入参里挑一个人认得的「对象」:名字、标题、搜索词、文件名……按这个先后取第一个
18
+ * 非空字符串。**不取**命令原文、正文、id 列表——那是日志,不是这一步在干什么。
19
+ */
20
+ const OBJECT_KEYS = [
21
+ 'skill_name',
22
+ 'skillName',
23
+ 'title',
24
+ 'name',
25
+ 'keyword',
26
+ 'query',
27
+ 'q',
28
+ 'pattern',
29
+ 'slug',
30
+ ] as const;
31
+
32
+ /** 取路径的最后一段(文件名 / 目录名)。 */
33
+ function baseName(path: string): string {
34
+ const trimmed = path.replace(/\/+$/, '');
35
+ return trimmed.slice(trimmed.lastIndexOf('/') + 1) || trimmed;
36
+ }
37
+
38
+ /**
39
+ * 这一步的对象:`读文件 草稿-v1.md` 里的「草稿-v1.md」。取不到就是 null,
40
+ * 那一行只写动作。改动摘要(`ref`)里的路径优先——它是落盘后的权威路径。
41
+ */
42
+ export function stepObject(
43
+ node: Pick<TraceNode, 'input' | 'ref'>
44
+ ): string | null {
45
+ const diffPath = displayConfig().refPath(node.ref);
46
+ if (diffPath) return baseName(diffPath);
47
+ const input = node.input;
48
+ if (!input || typeof input !== 'object') return null;
49
+ const rec = input as Record<string, unknown>;
50
+ for (const key of OBJECT_KEYS) {
51
+ const v = rec[key];
52
+ if (typeof v === 'string' && v.trim() !== '') return v.trim();
53
+ }
54
+ for (const key of ['path', 'folder'] as const) {
55
+ const v = rec[key];
56
+ if (typeof v === 'string' && v.trim() !== '') return baseName(v.trim());
57
+ }
58
+ return null;
59
+ }
60
+
61
+ /** 一步的说法:动作 + 对象(「写文件 初稿.md」);没有对象就只有动作。 */
62
+ export function stepText(node: Pick<TraceNode, 'toolName' | 'input' | 'ref'>) {
63
+ const label = toolDisplay(node.toolName).label;
64
+ const obj = stepObject(node);
65
+ return obj ? `${label} ${obj}` : label;
66
+ }
67
+
68
+ /** 写文件 / 改文件,以及工具表里标成琥珀(「写操作」)的那些:它们是这段过程的结果。 */
69
+ function changes(node: TraceNode): boolean {
70
+ return (
71
+ node.toolName === 'Write' ||
72
+ node.toolName === 'Edit' ||
73
+ toolDisplay(node.toolName).tone === 'amber'
74
+ );
75
+ }
76
+
77
+ export interface ProcessDigest {
78
+ /** 工具步(含运行级错误节点),按先后。思考不算步。 */
79
+ steps: TraceNode[];
80
+ /** 有没有思考段。 */
81
+ thought: boolean;
82
+ /** 已结束的思考合计时长;一段都没有时长就是 null。 */
83
+ thinkingMs: number | null;
84
+ /** 收起时代表这段过程的那一步:最后一次改动;没有改动就是第一步。 */
85
+ key: TraceNode | null;
86
+ /** 此刻在做的那一项(思考还在出、或工具在跑);跑完是 null。 */
87
+ current: ActivityItem | null;
88
+ /** 最后一步失败了(其后的思考不算补救),同 `ActivitySummary.lastFailed`。 */
89
+ failed: TraceNode | null;
90
+ }
91
+
92
+ export function digestProcess(items: readonly ActivityItem[]): ProcessDigest {
93
+ const steps: TraceNode[] = [];
94
+ let thought = false;
95
+ let thinkingMs: number | null = null;
96
+ let current: ActivityItem | null = null;
97
+ let failed: TraceNode | null = null;
98
+ for (const item of items) {
99
+ if (item.type === 'reasoning') {
100
+ thought = true;
101
+ if (item.thinking) current = item;
102
+ else if (item.durationMs != null) {
103
+ thinkingMs = (thinkingMs ?? 0) + item.durationMs;
104
+ }
105
+ continue;
106
+ }
107
+ const node = item.node;
108
+ steps.push(node);
109
+ if (node.status === 'running') current = item;
110
+ failed = node.kind === 'error' || node.status === 'failed' ? node : null;
111
+ }
112
+ let lastChange: TraceNode | undefined;
113
+ for (let i = steps.length - 1; i >= 0 && !lastChange; i--) {
114
+ if (changes(steps[i])) lastChange = steps[i];
115
+ }
116
+ return {
117
+ steps,
118
+ thought,
119
+ thinkingMs,
120
+ key: lastChange ?? steps[0] ?? null,
121
+ current,
122
+ failed,
123
+ };
124
+ }
125
+
126
+ /**
127
+ * 过程那一行标记怎么写(对话里的标记与「过程」弹窗的组头共用这一份,口径才一致):
128
+ *
129
+ * - 在跑:正在做的那一步(「正在读文件 草稿-v1.md」「正在思考… 12 秒」);
130
+ * - 最后一步失败:哪一步、为什么;
131
+ * - 其余:思考时长 · 最要紧的一步(最后一次改动,没有就是第一步)+「等 N 步」。
132
+ *
133
+ * `target`:点它打开弹窗时选中哪一项——在跑的那一项 > 失败的那一步 > 最要紧的一步 > 第一项。
134
+ */
135
+ export interface ProcessHeadline {
136
+ text: string;
137
+ tone: 'quiet' | 'running' | 'bad';
138
+ target: string;
139
+ }
140
+
141
+ export function processHeadline(
142
+ items: readonly ActivityItem[]
143
+ ): ProcessHeadline {
144
+ const d = digestProcess(items);
145
+ const target =
146
+ (d.current && activityKey(d.current)) ??
147
+ d.failed?.key ??
148
+ d.key?.key ??
149
+ activityKey(items[0]);
150
+ if (d.current) {
151
+ return {
152
+ tone: 'running',
153
+ target,
154
+ text:
155
+ d.current.type === 'reasoning'
156
+ ? thinkingLabel(true, d.current.durationMs)
157
+ : `正在${stepText(d.current.node)}`,
158
+ };
159
+ }
160
+ if (d.failed) return { tone: 'bad', target, text: failureText(d.failed) };
161
+ const parts: string[] = [];
162
+ if (d.thought) {
163
+ parts.push(
164
+ d.thinkingMs != null
165
+ ? `思考 ${formatThinkingDuration(d.thinkingMs)}`
166
+ : '思考'
167
+ );
168
+ }
169
+ if (d.key) {
170
+ parts.push(
171
+ `${stepText(d.key)}${d.steps.length > 1 ? ` 等 ${d.steps.length} 步` : ''}`
172
+ );
173
+ }
174
+ return { tone: 'quiet', target, text: parts.join(' · ') };
175
+ }
176
+
177
+ /** 失败的那一步:哪一步 + 原因(有就给)。 */
178
+ export function failureText(node: TraceNode): string {
179
+ const what = node.kind === 'error' ? '出错' : `${stepText(node)} 失败`;
180
+ const reason = node.message?.trim();
181
+ return reason ? `${what}:${reason}` : what;
182
+ }
183
+
184
+ /**
185
+ * 「过程」弹窗左栏的一项,**与对话里的结构一一对应**(2026-09-26 用户:「重要的节点要
186
+ * 在对话消息中展示,不重要的隐藏」「内外口径要保持一致」):
187
+ *
188
+ * - `group`:对话里的一行过程标记(组头就是那行标记的原文,下面是它收起的每一步);
189
+ * - `node`:对话里单独成节的重要节点(子 Agent、提问、分身的提议,即
190
+ * `standsAlone` 的那些工具);
191
+ * - `anchor`:两段过程之间那段话的头一句,做路标——只是路标,不可选中,正文本身不进
192
+ * 弹窗。
193
+ *
194
+ * 可选中的是每一步(思考 `r<块下标>`、工具节点 key)与每个重要节点——对话里的标记按
195
+ * 同一个 key 打开弹窗、选中那一步。
196
+ */
197
+ export type TimelineEntry =
198
+ | { kind: 'anchor'; key: string; text: string }
199
+ | { kind: 'group'; key: string; items: ActivityItem[] }
200
+ | { kind: 'node'; key: string; node: TraceNode };
201
+
202
+ /** 路标取这段话的头一句,最多这么多字。 */
203
+ const ANCHOR_MAX = 40;
204
+
205
+ function firstSentence(text: string): string {
206
+ const line =
207
+ text
208
+ .split(/\n/)
209
+ .map(s => s.replace(/^[#>*\-\s]+/, '').trim())
210
+ .find(s => s !== '') ?? '';
211
+ const cut = line.search(/[。!?!?]/);
212
+ const sentence = cut >= 0 ? line.slice(0, cut + 1) : line;
213
+ return sentence.length > ANCHOR_MAX
214
+ ? `${sentence.slice(0, ANCHOR_MAX)}…`
215
+ : sentence;
216
+ }
217
+
218
+ /** 思考 / 工具在弹窗里的 key(与 `TimelineEntry` 里可选中的那些一致)。 */
219
+ export function activityKey(item: ActivityItem): string {
220
+ return item.type === 'reasoning' ? `r${item.index}` : item.node.key;
221
+ }
222
+
223
+ /**
224
+ * 一条回复排成弹窗左栏(结构同对话,见 `TimelineEntry`)。路标只放在后面还有东西的
225
+ * 地方:结尾那句总结夹在最后,什么也指不到。
226
+ */
227
+ export function processTimeline(
228
+ layout: readonly LayoutBlock[]
229
+ ): TimelineEntry[] {
230
+ const out: TimelineEntry[] = [];
231
+ let pendingAnchor: TimelineEntry | null = null;
232
+ const push = (entry: TimelineEntry) => {
233
+ if (pendingAnchor) out.push(pendingAnchor);
234
+ pendingAnchor = null;
235
+ out.push(entry);
236
+ };
237
+ for (const block of layout) {
238
+ if (block.type === 'text') {
239
+ const text = firstSentence(block.text);
240
+ if (text)
241
+ pendingAnchor = { kind: 'anchor', key: `a${block.index}`, text };
242
+ } else if (block.type === 'activity') {
243
+ push({ kind: 'group', key: `g${block.index}`, items: block.items });
244
+ } else if (
245
+ block.type === 'trace' &&
246
+ block.node.kind === 'tool' &&
247
+ standsAlone(block.node)
248
+ ) {
249
+ push({ kind: 'node', key: block.node.key, node: block.node });
250
+ } else {
251
+ // 零散的一步(思考、普通工具、运行级错误):对话里也是一行标记。
252
+ push({ kind: 'group', key: `g${block.index}`, items: [block] });
253
+ }
254
+ }
255
+ return out;
256
+ }
257
+
258
+ /** 左栏里可选中的 key,按先后(↑ ↓ 就在这一列上走)。 */
259
+ export function timelineKeys(entries: readonly TimelineEntry[]): string[] {
260
+ return entries.flatMap(e =>
261
+ e.kind === 'group'
262
+ ? e.items.map(activityKey)
263
+ : e.kind === 'node'
264
+ ? [e.key]
265
+ : []
266
+ );
267
+ }
268
+
269
+ /**
270
+ * 「过程」弹窗左栏里可选中的一项:一段思考、一步工具,或一个重要节点(对话里单独成节
271
+ * 的那些)。按先后排,↑ ↓ 就在这一列上走。
272
+ */
273
+ export type TimelinePick =
274
+ | {
275
+ kind: 'thinking';
276
+ key: string;
277
+ item: Extract<ActivityItem, { type: 'reasoning' }>;
278
+ }
279
+ | { kind: 'step'; key: string; node: TraceNode }
280
+ | { kind: 'node'; key: string; node: TraceNode };
281
+
282
+ export function timelinePicks(
283
+ entries: readonly TimelineEntry[]
284
+ ): TimelinePick[] {
285
+ return entries.flatMap((e): TimelinePick[] =>
286
+ e.kind === 'group'
287
+ ? e.items.map(item =>
288
+ item.type === 'reasoning'
289
+ ? { kind: 'thinking', key: activityKey(item), item }
290
+ : { kind: 'step', key: activityKey(item), node: item.node }
291
+ )
292
+ : e.kind === 'node'
293
+ ? [{ kind: 'node', key: e.key, node: e.node }]
294
+ : []
295
+ );
296
+ }
297
+
298
+ /** 一段思考前后是哪两步的动作名(「在「读文件」之后、「命令」之前」)。 */
299
+ export function thinkingNeighbours(
300
+ picks: readonly TimelinePick[],
301
+ pick: TimelinePick
302
+ ): { before: string | null; after: string | null } {
303
+ const i = picks.indexOf(pick);
304
+ const label = (p: TimelinePick | undefined) =>
305
+ p && p.kind !== 'thinking' ? toolDisplay(p.node.toolName).label : null;
306
+ let before: string | null = null;
307
+ for (let j = i - 1; j >= 0 && before === null; j--) before = label(picks[j]);
308
+ let after: string | null = null;
309
+ for (let j = i + 1; j < picks.length && after === null; j++) {
310
+ after = label(picks[j]);
311
+ }
312
+ return { before, after };
313
+ }