chatccc 0.2.231 → 0.2.232

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 (127) hide show
  1. package/.agents/skills/create-chatccc-feishu-app/SKILL.md +85 -85
  2. package/.claude/skills/create-chatccc-feishu-app/SKILL.md +85 -85
  3. package/.cursor/skills/create-chatccc-feishu-app/SKILL.md +85 -85
  4. package/README.md +90 -90
  5. package/agent-prompts/claude_specific.md +45 -45
  6. package/agent-prompts/codex_specific.md +2 -2
  7. package/agent-prompts/cursor_specific.md +13 -13
  8. package/bin/cccagent.mjs +17 -17
  9. package/im-skills/feishu-skill/receive-send-file.md +63 -63
  10. package/im-skills/feishu-skill/receive-send-image.md +24 -24
  11. package/im-skills/feishu-skill/skill.md +3 -3
  12. package/im-skills/wechat-file-skill/receive-send-file.md +38 -38
  13. package/im-skills/wechat-file-skill/send-file.mjs +83 -83
  14. package/im-skills/wechat-file-skill/skill.md +10 -10
  15. package/im-skills/wechat-image-skill/skill.md +10 -10
  16. package/im-skills/wechat-video-skill/receive-send-video.md +38 -38
  17. package/im-skills/wechat-video-skill/send-video.mjs +79 -79
  18. package/im-skills/wechat-video-skill/skill.md +10 -10
  19. package/package.json +1 -1
  20. package/scripts/postinstall-sharp-check.mjs +58 -58
  21. package/src/__tests__/agent-activity.test.ts +86 -86
  22. package/src/__tests__/agent-delegate-task-rpc.test.ts +165 -165
  23. package/src/__tests__/agent-reload-config-rpc.test.ts +99 -99
  24. package/src/__tests__/builtin-chat-session.test.ts +449 -393
  25. package/src/__tests__/builtin-cli-json.test.ts +39 -39
  26. package/src/__tests__/builtin-config.test.ts +26 -26
  27. package/src/__tests__/builtin-context.test.ts +319 -202
  28. package/src/__tests__/builtin-file-tools.test.ts +240 -240
  29. package/src/__tests__/builtin-permissions.test.ts +211 -211
  30. package/src/__tests__/builtin-session-search.test.ts +228 -0
  31. package/src/__tests__/builtin-session-select.test.ts +116 -116
  32. package/src/__tests__/builtin-sigint.test.ts +56 -56
  33. package/src/__tests__/builtin-skills.test.ts +284 -284
  34. package/src/__tests__/builtin-web-tools.test.ts +220 -220
  35. package/src/__tests__/card-action-routing.test.ts +18 -18
  36. package/src/__tests__/cardkit.test.ts +60 -60
  37. package/src/__tests__/ccc-adapter.test.ts +170 -170
  38. package/src/__tests__/chatgpt-subscription-rpc.test.ts +89 -89
  39. package/src/__tests__/chatgpt-subscription.test.ts +135 -135
  40. package/src/__tests__/chrome-devtools-guard.test.ts +165 -165
  41. package/src/__tests__/claude-adapter.test.ts +614 -614
  42. package/src/__tests__/claude-raw-stream-log.test.ts +87 -87
  43. package/src/__tests__/codex-adapter.test.ts +58 -58
  44. package/src/__tests__/codex-raw-stream-log.test.ts +170 -170
  45. package/src/__tests__/codex-reset-actions.test.ts +146 -146
  46. package/src/__tests__/cursor-adapter.test.ts +268 -268
  47. package/src/__tests__/feishu-api.test.ts +60 -60
  48. package/src/__tests__/feishu-avatar.test.ts +164 -164
  49. package/src/__tests__/feishu-message-ingress.test.ts +138 -138
  50. package/src/__tests__/feishu-platform.test.ts +22 -22
  51. package/src/__tests__/format-message.test.ts +47 -47
  52. package/src/__tests__/jsonl-stream.test.ts +79 -79
  53. package/src/__tests__/package-files.test.ts +24 -24
  54. package/src/__tests__/privacy.test.ts +198 -198
  55. package/src/__tests__/progress-reducer.test.ts +121 -121
  56. package/src/__tests__/raw-stream-log.test.ts +106 -106
  57. package/src/__tests__/response-stall.test.ts +49 -49
  58. package/src/__tests__/restart.test.ts +132 -132
  59. package/src/__tests__/session.test.ts +199 -199
  60. package/src/__tests__/shared-prefix.test.ts +36 -36
  61. package/src/__tests__/sim-platform.test.ts +16 -16
  62. package/src/__tests__/startup-lifecycle.test.ts +231 -231
  63. package/src/__tests__/stop-session.test.ts +34 -34
  64. package/src/__tests__/stream-state.test.ts +42 -42
  65. package/src/__tests__/terminal-error.test.ts +54 -54
  66. package/src/__tests__/terminal-renderer.test.ts +247 -247
  67. package/src/__tests__/update-command-guard.test.ts +144 -144
  68. package/src/__tests__/web-ui.test.ts +326 -326
  69. package/src/adapters/adapter-interface.ts +33 -33
  70. package/src/adapters/ccc-adapter.ts +141 -141
  71. package/src/adapters/claude-adapter.ts +620 -620
  72. package/src/adapters/claude-session-meta-store.ts +120 -120
  73. package/src/adapters/codex-adapter.ts +426 -426
  74. package/src/adapters/cursor-adapter.ts +681 -681
  75. package/src/adapters/jsonl-stream.ts +157 -157
  76. package/src/adapters/raw-stream-log.ts +124 -124
  77. package/src/adapters/resource-monitor.ts +140 -140
  78. package/src/agent-activity.ts +175 -175
  79. package/src/agent-delegate-task-rpc.ts +153 -153
  80. package/src/agent-delegate-task.ts +91 -91
  81. package/src/agent-reload-config-rpc.ts +34 -34
  82. package/src/agent-stop-stuck.ts +129 -129
  83. package/src/builtin/cli.ts +6 -0
  84. package/src/builtin/config.ts +84 -84
  85. package/src/builtin/context.ts +465 -391
  86. package/src/builtin/file-log.ts +38 -38
  87. package/src/builtin/file-tools.ts +34 -0
  88. package/src/builtin/index.ts +24 -23
  89. package/src/builtin/proc-tree-kill.ts +61 -61
  90. package/src/builtin/progress/cards-helpers.ts +76 -76
  91. package/src/builtin/progress/reducer.ts +113 -113
  92. package/src/builtin/progress/terminal-renderer.ts +294 -294
  93. package/src/builtin/progress/view.ts +77 -77
  94. package/src/builtin/raw-stream-log.ts +124 -124
  95. package/src/builtin/session-search.ts +363 -0
  96. package/src/builtin/session-select.ts +48 -48
  97. package/src/builtin/sigint.ts +50 -50
  98. package/src/builtin/skills.ts +205 -205
  99. package/src/builtin/web-tools.ts +313 -313
  100. package/src/card-action-routing.ts +14 -14
  101. package/src/chatgpt-subscription-rpc.ts +27 -27
  102. package/src/chatgpt-subscription.ts +299 -299
  103. package/src/chrome-devtools-guard.ts +318 -318
  104. package/src/codex-reset-actions.ts +184 -184
  105. package/src/feishu-api.ts +193 -193
  106. package/src/feishu-message-ingress.ts +195 -195
  107. package/src/feishu-platform.ts +20 -20
  108. package/src/format-message.ts +293 -293
  109. package/src/litellm-proxy.ts +374 -374
  110. package/src/orchestrator.ts +2494 -2494
  111. package/src/platform-adapter.ts +6 -6
  112. package/src/privacy.ts +118 -118
  113. package/src/progress/reducer.ts +113 -113
  114. package/src/progress/terminal-renderer.ts +294 -294
  115. package/src/progress/view.ts +77 -77
  116. package/src/response-stall.ts +28 -28
  117. package/src/runtime-reload.ts +34 -34
  118. package/src/session-chat-binding.ts +82 -82
  119. package/src/session-name.ts +8 -8
  120. package/src/session.ts +201 -201
  121. package/src/shared-prefix.ts +29 -29
  122. package/src/sim-platform.ts +20 -20
  123. package/src/startup-lifecycle.ts +250 -250
  124. package/src/stream-state.ts +21 -21
  125. package/src/terminal-error.ts +129 -129
  126. package/src/turn-cards.ts +117 -117
  127. package/src/update-command-guard.ts +165 -165
@@ -1,54 +1,54 @@
1
- import { describe, expect, it } from "vitest";
2
-
3
- import { classifyTerminalError, formatTerminalErrorNotice } from "../terminal-error.ts";
4
-
5
- describe("terminal error classification", () => {
6
- it("turns a retried connection timeout into an actionable root-cause summary", () => {
7
- const error = classifyTerminalError(new Error(
8
- "Failed after 3 attempts. Last error: Cannot connect to API: Connect Timeout Error " +
9
- "(attempted addresses: 172.19.67.251:443, 172.19.68.1:443, timeout: 10000ms)",
10
- ), 123);
11
-
12
- expect(error).toEqual({
13
- kind: "network_timeout",
14
- title: "网络连接超时",
15
- message: "连接模型服务失败,已重试 3 次,单次连接等待 10 秒。请检查网络、VPN或模型服务状态后重试。",
16
- occurredAt: 123,
17
- });
18
- expect(JSON.stringify(error)).not.toContain("172.19.67.251");
19
- });
20
-
21
- it("redacts credentials from an otherwise unknown error", () => {
22
- const error = classifyTerminalError(
23
- new Error("custom provider rejected api_key=secret-value Bearer eyJ.private sk-live-secret"),
24
- 456,
25
- );
26
-
27
- expect(error.kind).toBe("unknown");
28
- expect(error.message).toContain("custom provider rejected");
29
- expect(error.message).not.toContain("secret-value");
30
- expect(error.message).not.toContain("eyJ.private");
31
- expect(error.message).not.toContain("sk-live-secret");
32
- });
33
-
34
- it("marks an existing reply as potentially incomplete", () => {
35
- const error = classifyTerminalError(new Error("HTTP 429 rate limit"), 789);
36
- const notice = formatTerminalErrorNotice(error, "partial answer");
37
-
38
- expect(notice).toContain("请求受到限流");
39
- expect(notice).toContain("以下回复可能不完整");
40
- expect(notice).toContain("partial answer");
41
- });
42
-
43
- it.each([
44
- ["HTTP 401 unauthorized", "authentication", "模型服务鉴权失败"],
45
- ["HTTP 429 too many requests", "rate_limit", "请求受到限流"],
46
- ["HTTP 503 service unavailable", "provider", "模型服务暂时不可用"],
47
- ["getaddrinfo ENOTFOUND api.example.test", "network", "无法连接模型服务"],
48
- ] as const)("classifies %s as %s", (message, kind, title) => {
49
- const error = classifyTerminalError(new Error(message), 999);
50
-
51
- expect(error.kind).toBe(kind);
52
- expect(error.title).toBe(title);
53
- });
54
- });
1
+ import { describe, expect, it } from "vitest";
2
+
3
+ import { classifyTerminalError, formatTerminalErrorNotice } from "../terminal-error.ts";
4
+
5
+ describe("terminal error classification", () => {
6
+ it("turns a retried connection timeout into an actionable root-cause summary", () => {
7
+ const error = classifyTerminalError(new Error(
8
+ "Failed after 3 attempts. Last error: Cannot connect to API: Connect Timeout Error " +
9
+ "(attempted addresses: 172.19.67.251:443, 172.19.68.1:443, timeout: 10000ms)",
10
+ ), 123);
11
+
12
+ expect(error).toEqual({
13
+ kind: "network_timeout",
14
+ title: "网络连接超时",
15
+ message: "连接模型服务失败,已重试 3 次,单次连接等待 10 秒。请检查网络、VPN或模型服务状态后重试。",
16
+ occurredAt: 123,
17
+ });
18
+ expect(JSON.stringify(error)).not.toContain("172.19.67.251");
19
+ });
20
+
21
+ it("redacts credentials from an otherwise unknown error", () => {
22
+ const error = classifyTerminalError(
23
+ new Error("custom provider rejected api_key=secret-value Bearer eyJ.private sk-live-secret"),
24
+ 456,
25
+ );
26
+
27
+ expect(error.kind).toBe("unknown");
28
+ expect(error.message).toContain("custom provider rejected");
29
+ expect(error.message).not.toContain("secret-value");
30
+ expect(error.message).not.toContain("eyJ.private");
31
+ expect(error.message).not.toContain("sk-live-secret");
32
+ });
33
+
34
+ it("marks an existing reply as potentially incomplete", () => {
35
+ const error = classifyTerminalError(new Error("HTTP 429 rate limit"), 789);
36
+ const notice = formatTerminalErrorNotice(error, "partial answer");
37
+
38
+ expect(notice).toContain("请求受到限流");
39
+ expect(notice).toContain("以下回复可能不完整");
40
+ expect(notice).toContain("partial answer");
41
+ });
42
+
43
+ it.each([
44
+ ["HTTP 401 unauthorized", "authentication", "模型服务鉴权失败"],
45
+ ["HTTP 429 too many requests", "rate_limit", "请求受到限流"],
46
+ ["HTTP 503 service unavailable", "provider", "模型服务暂时不可用"],
47
+ ["getaddrinfo ENOTFOUND api.example.test", "network", "无法连接模型服务"],
48
+ ] as const)("classifies %s as %s", (message, kind, title) => {
49
+ const error = classifyTerminalError(new Error(message), 999);
50
+
51
+ expect(error.kind).toBe(kind);
52
+ expect(error.title).toBe(title);
53
+ });
54
+ });
@@ -1,247 +1,247 @@
1
- import { afterEach, describe, expect, it, vi } from "vitest";
2
-
3
- import {
4
- buildBlockLines,
5
- charWidth,
6
- clipToWidth,
7
- TerminalProgressRenderer,
8
- } from "../progress/terminal-renderer.ts";
9
- import { progressView } from "../progress/view.ts";
10
-
11
- class FakeOut {
12
- chunks: string[] = [];
13
- columns = 100;
14
- write(s: string): boolean {
15
- this.chunks.push(s);
16
- return true;
17
- }
18
- get output(): string {
19
- return this.chunks.join("");
20
- }
21
- }
22
-
23
- /** 测试桩:仅实现 write 的假输出流,类型上按 WritableStream 对待 */
24
- function asOut(out: FakeOut): NodeJS.WritableStream & { columns?: number } {
25
- return out as unknown as NodeJS.WritableStream & { columns?: number };
26
- }
27
-
28
- afterEach(() => {
29
- vi.useRealTimers();
30
- });
31
-
32
- describe("buildBlockLines", () => {
33
- it("renders generating status line with header title and stop hint", () => {
34
- const lines = buildBlockLines(
35
- progressView({ headerTitle: "正在启动 Agent · 0秒", text: "" }),
36
- 100,
37
- );
38
- expect(lines[0]).toContain("⏳ 正在启动 Agent · 0秒");
39
- expect(lines[0]).toContain("Ctrl+C 停止");
40
- expect(lines[1]).toContain("等待 Agent 输出...");
41
- });
42
-
43
- it("renders done / stopped / error status lines", () => {
44
- const done = buildBlockLines(progressView({ status: "done", text: "ok" }), 100);
45
- expect(done[0]).toContain("✅ 完成");
46
- expect(done[0]).toContain("\x1b[1m"); // 完成状态行加粗,不用浅色
47
- const stopped = buildBlockLines(progressView({ status: "stopped", text: "x" }), 100);
48
- expect(stopped[0]).toContain("⏹ 已停止");
49
- const error = buildBlockLines(progressView({ status: "error", text: "x" }), 100);
50
- expect(error[0]).toContain("❌ 异常结束");
51
- });
52
-
53
- it("renders tool lines with emoji and status mark", () => {
54
- const lines = buildBlockLines(
55
- progressView({
56
- text: "",
57
- tools: [
58
- { id: "t1", name: "edit_file", status: "running", detail: "edit a.ts" },
59
- { id: "t2", name: "run_command", status: "ok", summary: "npm test passed" },
60
- { id: "t3", name: "search_code", status: "error", summary: "regex error" },
61
- ],
62
- }),
63
- 100,
64
- );
65
- expect(lines[1]).toContain("edit_file");
66
- expect(lines[1]).toContain("…");
67
- expect(lines[1]).toContain("edit a.ts");
68
- expect(lines[2]).toContain("✓");
69
- expect(lines[2]).toContain("npm test passed");
70
- expect(lines[3]).toContain("✗");
71
- expect(lines[3]).toContain("regex error");
72
- // 工具行摘要不用浅色字体(回复内容可读性优先)
73
- for (const line of [lines[1], lines[2], lines[3]]) {
74
- expect(line).not.toContain("\x1b[2m");
75
- }
76
- });
77
-
78
- it("truncates long body to maxBodyLines", () => {
79
- const text = Array.from({ length: 50 }, (_, i) => `line ${i}`).join("\n");
80
- const lines = buildBlockLines(progressView({ text }), 100, 5);
81
- expect(lines.filter((l) => l.startsWith("line"))).toHaveLength(5);
82
- expect(lines.join("\n")).toContain("...");
83
- });
84
-
85
- it("clips lines wider than terminal width to avoid wrapping", () => {
86
- const lines = buildBlockLines(
87
- progressView({ text: "x".repeat(200) }),
88
- 30,
89
- );
90
- for (const line of lines) {
91
- expect(line.length).toBeLessThanOrEqual(30);
92
- }
93
- });
94
-
95
- it("charWidth counts CJK/emoji as 2 columns and control/ZWJ as 0", () => {
96
- expect(charWidth("a")).toBe(1);
97
- expect(charWidth("中")).toBe(2);
98
- expect(charWidth("📂")).toBe(2);
99
- expect(charWidth("\u200d")).toBe(0); // ZWJ
100
- });
101
-
102
- it("clipToWidth truncates by display width, not string length", () => {
103
- expect(clipToWidth("中文abc", 4)).toBe("中文");
104
- expect(clipToWidth("中文abc", 5)).toBe("中文a");
105
- expect(clipToWidth("📂 x", 2)).toBe("📂");
106
- expect(clipToWidth("📂 x", 3)).toBe("📂 ");
107
- });
108
-
109
- it("clipToWidth keeps ANSI tokens whole and closes colors at the cut", () => {
110
- const ansi = "\x1b[32m📂\x1b[0m abc";
111
- expect(clipToWidth(ansi, 6)).toBe("\x1b[32m📂\x1b[0m abc");
112
- expect(clipToWidth(ansi, 5)).toBe("\x1b[32m📂\x1b[0m ab");
113
- // 截断发生在未闭合颜色内时自动补 reset,避免颜色泄漏
114
- expect(clipToWidth("\x1b[1m\x1b[32m✅ 完成\x1b[0m", 6)).toBe("\x1b[1m\x1b[32m✅ 完\x1b[0m");
115
- });
116
-
117
- it("emoji tool lines are clipped by display width so the block never wraps", () => {
118
- // 模拟用户示例:emoji + 超长 JSON 工具行,宽 40 的终端必须整行不折行
119
- const lines = buildBlockLines(
120
- progressView({
121
- text: "",
122
- tools: [
123
- { id: "t1", name: "list_dir", status: "ok", summary: `{"path":"C:\\Users\\weizhangjian\\.chatccc","entries":[{"name":"builtin","path":"C:\\Users${'x'.repeat(300)}"}]}` },
124
- ],
125
- }),
126
- 40,
127
- );
128
- const toolLine = lines.find((l) => l.includes("list_dir"))!;
129
- // 显示宽度(剥离 ANSI 后按 charWidth 计算)不超过终端列宽,永不折行
130
- const visible = [...toolLine.replace(/\x1b\[[0-9;]*m/g, "")].reduce((w, ch) => w + charWidth(ch), 0);
131
- expect(visible).toBeLessThanOrEqual(40);
132
- expect(toolLine).toContain("\x1b[0m"); // ANSI 完整闭合
133
- });
134
- });
135
-
136
- describe("TerminalProgressRenderer", () => {
137
- it("begin writes hide-cursor and the first frame", () => {
138
- const out = new FakeOut();
139
- const r = new TerminalProgressRenderer({ out: asOut(out) });
140
- r.begin(progressView({ text: "hello" }));
141
- expect(out.output.startsWith("\x1b[?25l")).toBe(true);
142
- expect(out.output).toContain("hello");
143
- r.dispose();
144
- });
145
-
146
- it("end finalizes the block and restores cursor, keeping block on screen", () => {
147
- const out = new FakeOut();
148
- const r = new TerminalProgressRenderer({ out: asOut(out) });
149
- r.begin(progressView({ text: "a" }));
150
- const before = out.chunks.length;
151
- r.end(progressView({ status: "done", text: "final" }));
152
- const delta = out.output.slice(out.chunks.slice(0, before).join("").length);
153
- expect(delta).toContain("✅ 完成");
154
- expect(delta.endsWith("\x1b[?25h")).toBe(true);
155
- });
156
-
157
- it("render is frame-throttled and flush forces immediate redraw", () => {
158
- vi.useFakeTimers();
159
- const out = new FakeOut();
160
- const r = new TerminalProgressRenderer({ out: asOut(out), frameMs: 100 });
161
-
162
- r.begin(progressView({ text: "" }));
163
- const outputAfterBegin = out.output;
164
-
165
- r.render(progressView({ text: "one" }));
166
- r.render(progressView({ text: "two" }));
167
- r.render(progressView({ text: "three" }));
168
- // 节流窗口内多次 render 不应产生任何输出
169
- expect(out.output).toBe(outputAfterBegin);
170
-
171
- vi.advanceTimersByTime(100);
172
- // 合并后只重绘一次,且展示的是最新视图
173
- expect(out.output).toContain("three");
174
- expect(out.output).not.toContain("two");
175
-
176
- r.flush();
177
- // flush 立即重绘当前视图(输出继续增长且仍是三帧内容)
178
- expect(out.output.length).toBeGreaterThan(outputAfterBegin.length);
179
- expect(out.output).toContain("three");
180
- r.dispose();
181
- });
182
-
183
- it("clears leftover lines when the block shrinks", () => {
184
- const out = new FakeOut();
185
- const r = new TerminalProgressRenderer({ out: asOut(out) });
186
- r.begin(progressView({ text: "a\nb\nc\nd" }));
187
- r.end(progressView({ status: "done", text: "short" }));
188
- expect(out.output).toContain("\x1b[2K\n");
189
- expect(out.output).toContain("\x1b[J");
190
- });
191
-
192
- it("heartbeat animates generating dots so the block never freezes", () => {
193
- vi.useFakeTimers();
194
- const out = new FakeOut();
195
- const r = new TerminalProgressRenderer({ out: asOut(out), animMs: 100 });
196
- r.begin(progressView({ headerTitle: "生成中...", text: "" }));
197
- const frame0 = out.output;
198
- expect(frame0).toContain("·"); // 首帧即带动画点
199
- vi.advanceTimersByTime(100);
200
- const frame1 = out.output;
201
- expect(frame1).not.toBe(frame0); // 无新事件也持续重绘
202
- expect(frame1).toContain("··"); // 第二帧点号增长
203
- r.dispose();
204
- });
205
-
206
- it("stops the heartbeat after end so the final block stays static", () => {
207
- vi.useFakeTimers();
208
- const out = new FakeOut();
209
- const r = new TerminalProgressRenderer({ out: asOut(out), animMs: 100 });
210
- r.begin(progressView({ text: "" }));
211
- r.end(progressView({ status: "done", text: "final" }));
212
- const afterEnd = out.output.length;
213
- vi.advanceTimersByTime(500);
214
- expect(out.output.length).toBe(afterEnd);
215
- });
216
-
217
- it("redraw moves up exactly blockLines-1 rows, never eating history above", () => {
218
- // 回归测试:光标在区块最后一行时,回到第一行只需上移 N-1 行。
219
- // 上移 N 行会每帧多上移 1 行,把上方历史内容逐行吃掉。
220
- const out = new FakeOut();
221
- const r = new TerminalProgressRenderer({ out: asOut(out), animMs: 0 });
222
- // 状态行 1 行 + 正文 4 行 = 5 行区块
223
- r.begin(progressView({ text: "a\nb\nc\nd" }));
224
- const afterBegin = out.output;
225
- r.flush(); // 第二帧强制重绘
226
- const delta = out.output.slice(afterBegin.length);
227
- expect(delta).toContain("\x1b[4A"); // 上移 5-1=4 行
228
- expect(delta).not.toContain("\x1b[5A"); // 绝不出现上移 N 行
229
- r.dispose();
230
- });
231
-
232
- it("multi-frame redraws keep moving up N-1 rows each time (no drift)", () => {
233
- const out = new FakeOut();
234
- const r = new TerminalProgressRenderer({ out: asOut(out), animMs: 0 });
235
- r.begin(progressView({ text: "a\nb\nc\nd" }));
236
- for (let i = 0; i < 3; i++) {
237
- r.flush();
238
- }
239
- // 连续多帧重绘,每帧上移都是 4 行(5 行区块),不是 5/6/7... 逐帧递增
240
- const moves = out.output.match(/\x1b\[(\d+)A/g) ?? [];
241
- expect(moves.length).toBe(3);
242
- for (const move of moves) {
243
- expect(move).toBe("\x1b[4A");
244
- }
245
- r.dispose();
246
- });
247
- });
1
+ import { afterEach, describe, expect, it, vi } from "vitest";
2
+
3
+ import {
4
+ buildBlockLines,
5
+ charWidth,
6
+ clipToWidth,
7
+ TerminalProgressRenderer,
8
+ } from "../progress/terminal-renderer.ts";
9
+ import { progressView } from "../progress/view.ts";
10
+
11
+ class FakeOut {
12
+ chunks: string[] = [];
13
+ columns = 100;
14
+ write(s: string): boolean {
15
+ this.chunks.push(s);
16
+ return true;
17
+ }
18
+ get output(): string {
19
+ return this.chunks.join("");
20
+ }
21
+ }
22
+
23
+ /** 测试桩:仅实现 write 的假输出流,类型上按 WritableStream 对待 */
24
+ function asOut(out: FakeOut): NodeJS.WritableStream & { columns?: number } {
25
+ return out as unknown as NodeJS.WritableStream & { columns?: number };
26
+ }
27
+
28
+ afterEach(() => {
29
+ vi.useRealTimers();
30
+ });
31
+
32
+ describe("buildBlockLines", () => {
33
+ it("renders generating status line with header title and stop hint", () => {
34
+ const lines = buildBlockLines(
35
+ progressView({ headerTitle: "正在启动 Agent · 0秒", text: "" }),
36
+ 100,
37
+ );
38
+ expect(lines[0]).toContain("⏳ 正在启动 Agent · 0秒");
39
+ expect(lines[0]).toContain("Ctrl+C 停止");
40
+ expect(lines[1]).toContain("等待 Agent 输出...");
41
+ });
42
+
43
+ it("renders done / stopped / error status lines", () => {
44
+ const done = buildBlockLines(progressView({ status: "done", text: "ok" }), 100);
45
+ expect(done[0]).toContain("✅ 完成");
46
+ expect(done[0]).toContain("\x1b[1m"); // 完成状态行加粗,不用浅色
47
+ const stopped = buildBlockLines(progressView({ status: "stopped", text: "x" }), 100);
48
+ expect(stopped[0]).toContain("⏹ 已停止");
49
+ const error = buildBlockLines(progressView({ status: "error", text: "x" }), 100);
50
+ expect(error[0]).toContain("❌ 异常结束");
51
+ });
52
+
53
+ it("renders tool lines with emoji and status mark", () => {
54
+ const lines = buildBlockLines(
55
+ progressView({
56
+ text: "",
57
+ tools: [
58
+ { id: "t1", name: "edit_file", status: "running", detail: "edit a.ts" },
59
+ { id: "t2", name: "run_command", status: "ok", summary: "npm test passed" },
60
+ { id: "t3", name: "search_code", status: "error", summary: "regex error" },
61
+ ],
62
+ }),
63
+ 100,
64
+ );
65
+ expect(lines[1]).toContain("edit_file");
66
+ expect(lines[1]).toContain("…");
67
+ expect(lines[1]).toContain("edit a.ts");
68
+ expect(lines[2]).toContain("✓");
69
+ expect(lines[2]).toContain("npm test passed");
70
+ expect(lines[3]).toContain("✗");
71
+ expect(lines[3]).toContain("regex error");
72
+ // 工具行摘要不用浅色字体(回复内容可读性优先)
73
+ for (const line of [lines[1], lines[2], lines[3]]) {
74
+ expect(line).not.toContain("\x1b[2m");
75
+ }
76
+ });
77
+
78
+ it("truncates long body to maxBodyLines", () => {
79
+ const text = Array.from({ length: 50 }, (_, i) => `line ${i}`).join("\n");
80
+ const lines = buildBlockLines(progressView({ text }), 100, 5);
81
+ expect(lines.filter((l) => l.startsWith("line"))).toHaveLength(5);
82
+ expect(lines.join("\n")).toContain("...");
83
+ });
84
+
85
+ it("clips lines wider than terminal width to avoid wrapping", () => {
86
+ const lines = buildBlockLines(
87
+ progressView({ text: "x".repeat(200) }),
88
+ 30,
89
+ );
90
+ for (const line of lines) {
91
+ expect(line.length).toBeLessThanOrEqual(30);
92
+ }
93
+ });
94
+
95
+ it("charWidth counts CJK/emoji as 2 columns and control/ZWJ as 0", () => {
96
+ expect(charWidth("a")).toBe(1);
97
+ expect(charWidth("中")).toBe(2);
98
+ expect(charWidth("📂")).toBe(2);
99
+ expect(charWidth("\u200d")).toBe(0); // ZWJ
100
+ });
101
+
102
+ it("clipToWidth truncates by display width, not string length", () => {
103
+ expect(clipToWidth("中文abc", 4)).toBe("中文");
104
+ expect(clipToWidth("中文abc", 5)).toBe("中文a");
105
+ expect(clipToWidth("📂 x", 2)).toBe("📂");
106
+ expect(clipToWidth("📂 x", 3)).toBe("📂 ");
107
+ });
108
+
109
+ it("clipToWidth keeps ANSI tokens whole and closes colors at the cut", () => {
110
+ const ansi = "\x1b[32m📂\x1b[0m abc";
111
+ expect(clipToWidth(ansi, 6)).toBe("\x1b[32m📂\x1b[0m abc");
112
+ expect(clipToWidth(ansi, 5)).toBe("\x1b[32m📂\x1b[0m ab");
113
+ // 截断发生在未闭合颜色内时自动补 reset,避免颜色泄漏
114
+ expect(clipToWidth("\x1b[1m\x1b[32m✅ 完成\x1b[0m", 6)).toBe("\x1b[1m\x1b[32m✅ 完\x1b[0m");
115
+ });
116
+
117
+ it("emoji tool lines are clipped by display width so the block never wraps", () => {
118
+ // 模拟用户示例:emoji + 超长 JSON 工具行,宽 40 的终端必须整行不折行
119
+ const lines = buildBlockLines(
120
+ progressView({
121
+ text: "",
122
+ tools: [
123
+ { id: "t1", name: "list_dir", status: "ok", summary: `{"path":"C:\\Users\\weizhangjian\\.chatccc","entries":[{"name":"builtin","path":"C:\\Users${'x'.repeat(300)}"}]}` },
124
+ ],
125
+ }),
126
+ 40,
127
+ );
128
+ const toolLine = lines.find((l) => l.includes("list_dir"))!;
129
+ // 显示宽度(剥离 ANSI 后按 charWidth 计算)不超过终端列宽,永不折行
130
+ const visible = [...toolLine.replace(/\x1b\[[0-9;]*m/g, "")].reduce((w, ch) => w + charWidth(ch), 0);
131
+ expect(visible).toBeLessThanOrEqual(40);
132
+ expect(toolLine).toContain("\x1b[0m"); // ANSI 完整闭合
133
+ });
134
+ });
135
+
136
+ describe("TerminalProgressRenderer", () => {
137
+ it("begin writes hide-cursor and the first frame", () => {
138
+ const out = new FakeOut();
139
+ const r = new TerminalProgressRenderer({ out: asOut(out) });
140
+ r.begin(progressView({ text: "hello" }));
141
+ expect(out.output.startsWith("\x1b[?25l")).toBe(true);
142
+ expect(out.output).toContain("hello");
143
+ r.dispose();
144
+ });
145
+
146
+ it("end finalizes the block and restores cursor, keeping block on screen", () => {
147
+ const out = new FakeOut();
148
+ const r = new TerminalProgressRenderer({ out: asOut(out) });
149
+ r.begin(progressView({ text: "a" }));
150
+ const before = out.chunks.length;
151
+ r.end(progressView({ status: "done", text: "final" }));
152
+ const delta = out.output.slice(out.chunks.slice(0, before).join("").length);
153
+ expect(delta).toContain("✅ 完成");
154
+ expect(delta.endsWith("\x1b[?25h")).toBe(true);
155
+ });
156
+
157
+ it("render is frame-throttled and flush forces immediate redraw", () => {
158
+ vi.useFakeTimers();
159
+ const out = new FakeOut();
160
+ const r = new TerminalProgressRenderer({ out: asOut(out), frameMs: 100 });
161
+
162
+ r.begin(progressView({ text: "" }));
163
+ const outputAfterBegin = out.output;
164
+
165
+ r.render(progressView({ text: "one" }));
166
+ r.render(progressView({ text: "two" }));
167
+ r.render(progressView({ text: "three" }));
168
+ // 节流窗口内多次 render 不应产生任何输出
169
+ expect(out.output).toBe(outputAfterBegin);
170
+
171
+ vi.advanceTimersByTime(100);
172
+ // 合并后只重绘一次,且展示的是最新视图
173
+ expect(out.output).toContain("three");
174
+ expect(out.output).not.toContain("two");
175
+
176
+ r.flush();
177
+ // flush 立即重绘当前视图(输出继续增长且仍是三帧内容)
178
+ expect(out.output.length).toBeGreaterThan(outputAfterBegin.length);
179
+ expect(out.output).toContain("three");
180
+ r.dispose();
181
+ });
182
+
183
+ it("clears leftover lines when the block shrinks", () => {
184
+ const out = new FakeOut();
185
+ const r = new TerminalProgressRenderer({ out: asOut(out) });
186
+ r.begin(progressView({ text: "a\nb\nc\nd" }));
187
+ r.end(progressView({ status: "done", text: "short" }));
188
+ expect(out.output).toContain("\x1b[2K\n");
189
+ expect(out.output).toContain("\x1b[J");
190
+ });
191
+
192
+ it("heartbeat animates generating dots so the block never freezes", () => {
193
+ vi.useFakeTimers();
194
+ const out = new FakeOut();
195
+ const r = new TerminalProgressRenderer({ out: asOut(out), animMs: 100 });
196
+ r.begin(progressView({ headerTitle: "生成中...", text: "" }));
197
+ const frame0 = out.output;
198
+ expect(frame0).toContain("·"); // 首帧即带动画点
199
+ vi.advanceTimersByTime(100);
200
+ const frame1 = out.output;
201
+ expect(frame1).not.toBe(frame0); // 无新事件也持续重绘
202
+ expect(frame1).toContain("··"); // 第二帧点号增长
203
+ r.dispose();
204
+ });
205
+
206
+ it("stops the heartbeat after end so the final block stays static", () => {
207
+ vi.useFakeTimers();
208
+ const out = new FakeOut();
209
+ const r = new TerminalProgressRenderer({ out: asOut(out), animMs: 100 });
210
+ r.begin(progressView({ text: "" }));
211
+ r.end(progressView({ status: "done", text: "final" }));
212
+ const afterEnd = out.output.length;
213
+ vi.advanceTimersByTime(500);
214
+ expect(out.output.length).toBe(afterEnd);
215
+ });
216
+
217
+ it("redraw moves up exactly blockLines-1 rows, never eating history above", () => {
218
+ // 回归测试:光标在区块最后一行时,回到第一行只需上移 N-1 行。
219
+ // 上移 N 行会每帧多上移 1 行,把上方历史内容逐行吃掉。
220
+ const out = new FakeOut();
221
+ const r = new TerminalProgressRenderer({ out: asOut(out), animMs: 0 });
222
+ // 状态行 1 行 + 正文 4 行 = 5 行区块
223
+ r.begin(progressView({ text: "a\nb\nc\nd" }));
224
+ const afterBegin = out.output;
225
+ r.flush(); // 第二帧强制重绘
226
+ const delta = out.output.slice(afterBegin.length);
227
+ expect(delta).toContain("\x1b[4A"); // 上移 5-1=4 行
228
+ expect(delta).not.toContain("\x1b[5A"); // 绝不出现上移 N 行
229
+ r.dispose();
230
+ });
231
+
232
+ it("multi-frame redraws keep moving up N-1 rows each time (no drift)", () => {
233
+ const out = new FakeOut();
234
+ const r = new TerminalProgressRenderer({ out: asOut(out), animMs: 0 });
235
+ r.begin(progressView({ text: "a\nb\nc\nd" }));
236
+ for (let i = 0; i < 3; i++) {
237
+ r.flush();
238
+ }
239
+ // 连续多帧重绘,每帧上移都是 4 行(5 行区块),不是 5/6/7... 逐帧递增
240
+ const moves = out.output.match(/\x1b\[(\d+)A/g) ?? [];
241
+ expect(moves.length).toBe(3);
242
+ for (const move of moves) {
243
+ expect(move).toBe("\x1b[4A");
244
+ }
245
+ r.dispose();
246
+ });
247
+ });