chatccc 0.2.236 → 0.2.238

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "chatccc",
3
- "version": "0.2.236",
3
+ "version": "0.2.238",
4
4
  "description": "Feishu bot bridge for Claude Code",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -210,6 +210,40 @@ describe("searchBuiltinSessions (raw stream logs)", () => {
210
210
  expect(enabled.scannedRawLogFiles).toBe(1);
211
211
  });
212
212
 
213
+ it("skips truncated/corrupt gzip files without crashing (unexpected end of file)", async () => {
214
+ // 护栏:线上事故——截断的 gzip 解压报 "unexpected end of file",若 error 事件
215
+ // 无人监听会升级为 uncaughtException 杀死整个服务。必须跳过并继续。
216
+ const contextDir = await mkdtemp(join(tmpdir(), "deepccc-search-raw-trunc-"));
217
+ const rawLogsDir = await mkdtemp(join(tmpdir(), "deepccc-search-raw-trunc-logs-"));
218
+ await writeContextSession(contextDir, "trunc", {
219
+ messages: [{ role: "user", content: "kw-trunc" }],
220
+ });
221
+
222
+ const sessionDir = join(rawLogsDir, "deepccc", "trunc");
223
+ await mkdir(sessionDir, { recursive: true });
224
+ const good = gzipSync(JSON.stringify({ type: "text-delta", text: "关键词 kw-good" }));
225
+ await writeFile(join(sessionDir, "2026-08-04T00-00-00-000Z-a.jsonl.gz"), good, "utf8");
226
+ // 截断一半:必然触发 zlib unexpected end of file
227
+ const truncated = gzipSync(JSON.stringify({ type: "text-delta", text: "关键词 kw-trunc-in-gzip" }));
228
+ await writeFile(join(sessionDir, "2026-08-04T00-00-00-000Z-b.jsonl.gz"), truncated.subarray(0, Math.floor(truncated.length / 2)), "utf8");
229
+
230
+ let output;
231
+ try {
232
+ output = await searchBuiltinSessions("kw-good", {
233
+ contextDir,
234
+ rawLogsDir,
235
+ includeRawLogs: true,
236
+ });
237
+ } catch (err) {
238
+ // 若损坏 gzip 导致 reject,这里直接断言失败并暴露错误
239
+ expect.fail(`searchBuiltinSessions 不应 reject: ${String(err)}`);
240
+ }
241
+
242
+ // 好文件正常命中;截断文件被跳过但不崩溃
243
+ expect(output!.matches.map((m) => m.snippet).join("\n")).toContain("kw-good");
244
+ expect(output!.scannedRawLogFiles).toBe(2);
245
+ });
246
+
213
247
  it("ignores missing raw log roots", async () => {
214
248
  const contextDir = await mkdtemp(join(tmpdir(), "deepccc-search-raw-missing-"));
215
249
  await writeContextSession(contextDir, "s", {
@@ -1,232 +1,232 @@
1
- import { EventEmitter } from "node:events";
2
- import { mkdtemp, readdir, rm, writeFile } from "node:fs/promises";
3
- import { tmpdir } from "node:os";
4
- import { join } from "node:path";
5
-
6
- import { describe, expect, it, vi, afterEach } from "vitest";
7
-
8
- import {
9
- buildRestartSpawnSpec,
10
- decideRestartParentExit,
11
- spawnRestartChild,
12
- RESTART_CHILD_READY_MS,
13
- } from "../orchestrator.ts";
14
- import { INTERNAL_RESTART_ENV_VAR } from "../startup-lifecycle.ts";
15
-
16
- describe("buildRestartSpawnSpec", () => {
17
- it("spawns node directly with the local tsx CLI (never via npx/npm)", () => {
18
- const spec = buildRestartSpawnSpec("F:/proj");
19
- expect(spec.command).toBe(process.execPath);
20
- expect(spec.args[0]).toBe(join("F:/proj", "node_modules", "tsx", "dist", "cli.mjs"));
21
- expect(spec.args[1]).toBe("src/index.ts");
22
- expect([spec.command, ...spec.args].join(" ")).not.toMatch(/npx|npm/i);
23
- });
24
-
25
- it("accepts the default project root", () => {
26
- const spec = buildRestartSpawnSpec();
27
- expect(spec.command).toBe(process.execPath);
28
- expect(spec.args[0]).toContain("tsx");
29
- });
30
- });
31
-
32
- describe("spawnRestartChild", () => {
33
- class FakeChild extends EventEmitter {
34
- pid = 12345;
35
- exitCode: number | null = null;
36
- signalCode: number | string | null = null;
37
- unref = vi.fn();
38
- stderr = new EventEmitter();
39
- }
40
-
41
- let tmpDirs: string[] = [];
42
- afterEach(async () => {
43
- for (const dir of tmpDirs) await rm(dir, { recursive: true, force: true });
44
- tmpDirs = [];
45
- });
46
-
47
- async function tmpLogDir(): Promise<string> {
48
- const dir = await mkdtemp(join(tmpdir(), "chatccc-restart-"));
49
- tmpDirs.push(dir);
50
- return dir;
51
- }
52
-
53
- it("spawns without a shell, redirects stderr to a restart log file, and marks the internal restart env", async () => {
54
- const logDir = await tmpLogDir();
55
- const fake = new FakeChild();
56
- const spawnImpl = vi.fn(() => fake as never);
57
- const trace = vi.fn();
58
-
59
- const child = spawnRestartChild({ projectRoot: "F:/proj", spawnImpl, trace, restartLogDir: logDir });
60
-
61
- expect(child).toBe(fake);
62
- expect(spawnImpl).toHaveBeenCalledWith(
63
- process.execPath,
64
- [join("F:/proj", "node_modules", "tsx", "dist", "cli.mjs"), "src/index.ts"],
65
- expect.objectContaining({
66
- detached: true,
67
- env: expect.objectContaining({ [INTERNAL_RESTART_ENV_VAR]: "1" }),
68
- // 不使用 shell:避免 npm/npx 的 PATH 注入问题
69
- shell: false,
70
- }),
71
- );
72
- // spawnImpl 收到的 command/args 中不得出现 npx/npm(env 里的 npm_* 变量不算)
73
- const firstCall = spawnImpl.mock.calls[0] as unknown as [string, string[]];
74
- const [cmd, args] = firstCall;
75
- expect([cmd, ...args].join(" ")).not.toMatch(/npx|npm/i);
76
-
77
- // stderr 指向磁盘日志文件(fd),而不是 pipe:pipe 读端随父进程退出关闭后,
78
- // 子进程写 stderr 会 EPIPE 崩溃(飞书 SDK console.warn 崩溃根因)。
79
- const callArgs = spawnImpl.mock.calls[0] as unknown as Array<unknown>;
80
- const stdio = (callArgs[2] as { stdio: unknown[] }).stdio;
81
- expect(stdio[0]).toBe("ignore");
82
- expect(stdio[1]).toBe("ignore");
83
- expect(typeof stdio[2]).toBe("number");
84
- expect(stdio[2] as number).toBeGreaterThan(2);
85
-
86
- const files = await readdir(logDir);
87
- expect(files.some((f) => f.startsWith("restart-") && f.endsWith(".log"))).toBe(true);
88
- });
89
-
90
- it("records child exit code/signal in trace without pipe capture", async () => {
91
- const logDir = await tmpLogDir();
92
- const fake = new FakeChild();
93
- const spawnImpl = vi.fn(() => fake as never);
94
- const trace = vi.fn();
95
-
96
- spawnRestartChild({ projectRoot: "F:/proj", spawnImpl, trace, restartLogDir: logDir });
97
-
98
- fake.exitCode = 1;
99
- fake.emit("exit", 1, null);
100
-
101
- const exitCall = trace.mock.calls.find(([name]) => name === "restart: child exit");
102
- expect(exitCall).toBeTruthy();
103
- expect(exitCall![1]).toEqual(expect.objectContaining({
104
- childPid: 12345,
105
- code: 1,
106
- signal: null,
107
- }));
108
- // 不再用 pipe 收集 stderr,trace 里不再有 stderr 字段
109
- expect(exitCall![1]).not.toHaveProperty("stderr");
110
- });
111
-
112
- it("falls back to pipe capture when the stderr log file cannot be opened", async () => {
113
- const dir = await tmpLogDir();
114
- // 用普通文件顶替目录:mkdir/open 日志文件必然失败
115
- const blocker = join(dir, "blocker");
116
- await writeFile(blocker, "x");
117
- const fake = new FakeChild();
118
- const spawnImpl = vi.fn(() => fake as never);
119
- const trace = vi.fn();
120
-
121
- spawnRestartChild({ projectRoot: "F:/proj", spawnImpl, trace, restartLogDir: blocker });
122
-
123
- const callArgs = spawnImpl.mock.calls[0] as unknown as Array<unknown>;
124
- expect((callArgs[2] as { stdio: unknown[] }).stdio[2]).toBe("pipe");
125
- const failCall = trace.mock.calls.find(
126
- ([name]) => name === "restart: stderr log open failed, falling back to pipe",
127
- );
128
- expect(failCall).toBeTruthy();
129
- expect(typeof (failCall![1] as { error: unknown }).error).toBe("string");
130
- });
131
-
132
- it("inherits the full terminal stdio when launched from a TTY (visible window logs, no EPIPE)", async () => {
133
- const logDir = await tmpLogDir();
134
- const fake = new FakeChild();
135
- const spawnImpl = vi.fn(() => fake as never);
136
- const trace = vi.fn();
137
-
138
- spawnRestartChild({
139
- projectRoot: "F:/proj",
140
- spawnImpl,
141
- trace,
142
- restartLogDir: logDir,
143
- isTty: () => true,
144
- });
145
-
146
- const callArgs = spawnImpl.mock.calls[0] as unknown as Array<unknown>;
147
- const stdio = (callArgs[2] as { stdio: unknown[] }).stdio;
148
- // 全部 inherit(含 stdin):避免 detached + stdin=ignore 在 Windows 上
149
- // 弹新控制台/丢失控制台关联,日志必须留在用户当前窗口
150
- expect(stdio).toEqual(["inherit", "inherit", "inherit"]);
151
- // TTY 场景 stderr 走终端,不再生成 restart-*.log 文件
152
- const files = await readdir(logDir);
153
- expect(files.filter((f) => f.startsWith("restart-") && f.endsWith(".log"))).toHaveLength(0);
154
- // 运行时自检 trace:记录 isTty 判定与最终 stdio
155
- const spawnCall = trace.mock.calls.find(([name]) => name === "restart: spawn child");
156
- expect(spawnCall).toBeTruthy();
157
- expect(spawnCall![1]).toEqual({
158
- isTty: true,
159
- stdio: JSON.stringify(["inherit", "inherit", "inherit"]),
160
- });
161
- });
162
-
163
- it("still redirects stderr to a file when explicitly not a TTY", async () => {
164
- const logDir = await tmpLogDir();
165
- const fake = new FakeChild();
166
- const spawnImpl = vi.fn(() => fake as never);
167
- const trace = vi.fn();
168
-
169
- spawnRestartChild({
170
- projectRoot: "F:/proj",
171
- spawnImpl,
172
- trace,
173
- restartLogDir: logDir,
174
- isTty: () => false,
175
- });
176
-
177
- const callArgs = spawnImpl.mock.calls[0] as unknown as Array<unknown>;
178
- const stdio = (callArgs[2] as { stdio: unknown[] }).stdio;
179
- expect(stdio[0]).toBe("ignore");
180
- expect(stdio[1]).toBe("ignore");
181
- expect(typeof stdio[2]).toBe("number");
182
- expect(stdio[2] as number).toBeGreaterThan(2);
183
- const files = await readdir(logDir);
184
- expect(files.some((f) => f.startsWith("restart-") && f.endsWith(".log"))).toBe(true);
185
- });
186
- });
187
-
188
- describe("decideRestartParentExit", () => {
189
- it("returns false (parent stays alive) when the child dies during the window", async () => {
190
- const child = { exitCode: 1, signalCode: null, pid: 42 } as never;
191
- const trace = vi.fn();
192
-
193
- const shouldExit = await decideRestartParentExit(child, 200, 50, trace);
194
-
195
- expect(shouldExit).toBe(false);
196
- expect(trace).toHaveBeenCalledWith(
197
- "restart: child died during window, keeping parent",
198
- expect.objectContaining({ childPid: 42, exitCode: 1 }),
199
- );
200
- });
201
-
202
- it("returns true (parent exits) when the child stays alive through the window", async () => {
203
- const child = { exitCode: null, signalCode: null, pid: 42 } as never;
204
- const trace = vi.fn();
205
-
206
- const shouldExit = await decideRestartParentExit(child, 150, 30, trace);
207
-
208
- expect(shouldExit).toBe(true);
209
- expect(trace).toHaveBeenCalledWith(
210
- "restart: child alive after window, parent exiting",
211
- expect.objectContaining({ childPid: 42 }),
212
- );
213
- });
214
-
215
- it("surfaces a child that died with a signal", async () => {
216
- const child = { exitCode: null, signalCode: "SIGKILL", pid: 42 } as never;
217
- const trace = vi.fn();
218
-
219
- const shouldExit = await decideRestartParentExit(child, 100, 25, trace);
220
-
221
- expect(shouldExit).toBe(false);
222
- expect(trace).toHaveBeenCalledWith(
223
- "restart: child died during window, keeping parent",
224
- expect.objectContaining({ signalCode: "SIGKILL" }),
225
- );
226
- });
227
-
228
- it("exports a sane default readiness window", () => {
229
- expect(RESTART_CHILD_READY_MS).toBeGreaterThan(0);
230
- expect(RESTART_CHILD_READY_MS).toBeLessThan(60_000);
231
- });
232
- });
1
+ import { EventEmitter } from "node:events";
2
+ import { mkdtemp, readdir, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+
6
+ import { describe, expect, it, vi, afterEach } from "vitest";
7
+
8
+ import {
9
+ buildRestartSpawnSpec,
10
+ decideRestartParentExit,
11
+ spawnRestartChild,
12
+ RESTART_CHILD_READY_MS,
13
+ } from "../orchestrator.ts";
14
+ import { INTERNAL_RESTART_ENV_VAR } from "../startup-lifecycle.ts";
15
+
16
+ describe("buildRestartSpawnSpec", () => {
17
+ it("spawns node directly with the local tsx CLI (never via npx/npm)", () => {
18
+ const spec = buildRestartSpawnSpec("F:/proj");
19
+ expect(spec.command).toBe(process.execPath);
20
+ expect(spec.args[0]).toBe(join("F:/proj", "node_modules", "tsx", "dist", "cli.mjs"));
21
+ expect(spec.args[1]).toBe("src/index.ts");
22
+ expect([spec.command, ...spec.args].join(" ")).not.toMatch(/npx|npm/i);
23
+ });
24
+
25
+ it("accepts the default project root", () => {
26
+ const spec = buildRestartSpawnSpec();
27
+ expect(spec.command).toBe(process.execPath);
28
+ expect(spec.args[0]).toContain("tsx");
29
+ });
30
+ });
31
+
32
+ describe("spawnRestartChild", () => {
33
+ class FakeChild extends EventEmitter {
34
+ pid = 12345;
35
+ exitCode: number | null = null;
36
+ signalCode: number | string | null = null;
37
+ unref = vi.fn();
38
+ stderr = new EventEmitter();
39
+ }
40
+
41
+ let tmpDirs: string[] = [];
42
+ afterEach(async () => {
43
+ for (const dir of tmpDirs) await rm(dir, { recursive: true, force: true });
44
+ tmpDirs = [];
45
+ });
46
+
47
+ async function tmpLogDir(): Promise<string> {
48
+ const dir = await mkdtemp(join(tmpdir(), "chatccc-restart-"));
49
+ tmpDirs.push(dir);
50
+ return dir;
51
+ }
52
+
53
+ it("spawns without a shell, redirects stderr to a restart log file, and marks the internal restart env", async () => {
54
+ const logDir = await tmpLogDir();
55
+ const fake = new FakeChild();
56
+ const spawnImpl = vi.fn(() => fake as never);
57
+ const trace = vi.fn();
58
+
59
+ const child = spawnRestartChild({ projectRoot: "F:/proj", spawnImpl, trace, restartLogDir: logDir });
60
+
61
+ expect(child).toBe(fake);
62
+ expect(spawnImpl).toHaveBeenCalledWith(
63
+ process.execPath,
64
+ [join("F:/proj", "node_modules", "tsx", "dist", "cli.mjs"), "src/index.ts"],
65
+ expect.objectContaining({
66
+ detached: true,
67
+ env: expect.objectContaining({ [INTERNAL_RESTART_ENV_VAR]: "1" }),
68
+ // 不使用 shell:避免 npm/npx 的 PATH 注入问题
69
+ shell: false,
70
+ }),
71
+ );
72
+ // spawnImpl 收到的 command/args 中不得出现 npx/npm(env 里的 npm_* 变量不算)
73
+ const firstCall = spawnImpl.mock.calls[0] as unknown as [string, string[]];
74
+ const [cmd, args] = firstCall;
75
+ expect([cmd, ...args].join(" ")).not.toMatch(/npx|npm/i);
76
+
77
+ // stderr 指向磁盘日志文件(fd),而不是 pipe:pipe 读端随父进程退出关闭后,
78
+ // 子进程写 stderr 会 EPIPE 崩溃(飞书 SDK console.warn 崩溃根因)。
79
+ const callArgs = spawnImpl.mock.calls[0] as unknown as Array<unknown>;
80
+ const stdio = (callArgs[2] as { stdio: unknown[] }).stdio;
81
+ expect(stdio[0]).toBe("ignore");
82
+ expect(stdio[1]).toBe("ignore");
83
+ expect(typeof stdio[2]).toBe("number");
84
+ expect(stdio[2] as number).toBeGreaterThan(2);
85
+
86
+ const files = await readdir(logDir);
87
+ expect(files.some((f) => f.startsWith("restart-") && f.endsWith(".log"))).toBe(true);
88
+ });
89
+
90
+ it("records child exit code/signal in trace without pipe capture", async () => {
91
+ const logDir = await tmpLogDir();
92
+ const fake = new FakeChild();
93
+ const spawnImpl = vi.fn(() => fake as never);
94
+ const trace = vi.fn();
95
+
96
+ spawnRestartChild({ projectRoot: "F:/proj", spawnImpl, trace, restartLogDir: logDir });
97
+
98
+ fake.exitCode = 1;
99
+ fake.emit("exit", 1, null);
100
+
101
+ const exitCall = trace.mock.calls.find(([name]) => name === "restart: child exit");
102
+ expect(exitCall).toBeTruthy();
103
+ expect(exitCall![1]).toEqual(expect.objectContaining({
104
+ childPid: 12345,
105
+ code: 1,
106
+ signal: null,
107
+ }));
108
+ // 不再用 pipe 收集 stderr,trace 里不再有 stderr 字段
109
+ expect(exitCall![1]).not.toHaveProperty("stderr");
110
+ });
111
+
112
+ it("falls back to pipe capture when the stderr log file cannot be opened", async () => {
113
+ const dir = await tmpLogDir();
114
+ // 用普通文件顶替目录:mkdir/open 日志文件必然失败
115
+ const blocker = join(dir, "blocker");
116
+ await writeFile(blocker, "x");
117
+ const fake = new FakeChild();
118
+ const spawnImpl = vi.fn(() => fake as never);
119
+ const trace = vi.fn();
120
+
121
+ spawnRestartChild({ projectRoot: "F:/proj", spawnImpl, trace, restartLogDir: blocker });
122
+
123
+ const callArgs = spawnImpl.mock.calls[0] as unknown as Array<unknown>;
124
+ expect((callArgs[2] as { stdio: unknown[] }).stdio[2]).toBe("pipe");
125
+ const failCall = trace.mock.calls.find(
126
+ ([name]) => name === "restart: stderr log open failed, falling back to pipe",
127
+ );
128
+ expect(failCall).toBeTruthy();
129
+ expect(typeof (failCall![1] as { error: unknown }).error).toBe("string");
130
+ });
131
+
132
+ it("inherits the full terminal stdio when launched from a TTY (visible window logs, no EPIPE)", async () => {
133
+ const logDir = await tmpLogDir();
134
+ const fake = new FakeChild();
135
+ const spawnImpl = vi.fn(() => fake as never);
136
+ const trace = vi.fn();
137
+
138
+ spawnRestartChild({
139
+ projectRoot: "F:/proj",
140
+ spawnImpl,
141
+ trace,
142
+ restartLogDir: logDir,
143
+ isTty: () => true,
144
+ });
145
+
146
+ const callArgs = spawnImpl.mock.calls[0] as unknown as Array<unknown>;
147
+ const stdio = (callArgs[2] as { stdio: unknown[] }).stdio;
148
+ // 全部 inherit(含 stdin):避免 detached + stdin=ignore 在 Windows 上
149
+ // 弹新控制台/丢失控制台关联,日志必须留在用户当前窗口
150
+ expect(stdio).toEqual(["inherit", "inherit", "inherit"]);
151
+ // TTY 场景 stderr 走终端,不再生成 restart-*.log 文件
152
+ const files = await readdir(logDir);
153
+ expect(files.filter((f) => f.startsWith("restart-") && f.endsWith(".log"))).toHaveLength(0);
154
+ // 运行时自检 trace:记录 isTty 判定与最终 stdio
155
+ const spawnCall = trace.mock.calls.find(([name]) => name === "restart: spawn child");
156
+ expect(spawnCall).toBeTruthy();
157
+ expect(spawnCall![1]).toEqual({
158
+ isTty: true,
159
+ stdio: JSON.stringify(["inherit", "inherit", "inherit"]),
160
+ });
161
+ });
162
+
163
+ it("still redirects stderr to a file when explicitly not a TTY", async () => {
164
+ const logDir = await tmpLogDir();
165
+ const fake = new FakeChild();
166
+ const spawnImpl = vi.fn(() => fake as never);
167
+ const trace = vi.fn();
168
+
169
+ spawnRestartChild({
170
+ projectRoot: "F:/proj",
171
+ spawnImpl,
172
+ trace,
173
+ restartLogDir: logDir,
174
+ isTty: () => false,
175
+ });
176
+
177
+ const callArgs = spawnImpl.mock.calls[0] as unknown as Array<unknown>;
178
+ const stdio = (callArgs[2] as { stdio: unknown[] }).stdio;
179
+ expect(stdio[0]).toBe("ignore");
180
+ expect(stdio[1]).toBe("ignore");
181
+ expect(typeof stdio[2]).toBe("number");
182
+ expect(stdio[2] as number).toBeGreaterThan(2);
183
+ const files = await readdir(logDir);
184
+ expect(files.some((f) => f.startsWith("restart-") && f.endsWith(".log"))).toBe(true);
185
+ });
186
+ });
187
+
188
+ describe("decideRestartParentExit", () => {
189
+ it("returns false (parent stays alive) when the child dies during the window", async () => {
190
+ const child = { exitCode: 1, signalCode: null, pid: 42 } as never;
191
+ const trace = vi.fn();
192
+
193
+ const shouldExit = await decideRestartParentExit(child, 200, 50, trace);
194
+
195
+ expect(shouldExit).toBe(false);
196
+ expect(trace).toHaveBeenCalledWith(
197
+ "restart: child died during window, keeping parent",
198
+ expect.objectContaining({ childPid: 42, exitCode: 1 }),
199
+ );
200
+ });
201
+
202
+ it("returns true (parent exits) when the child stays alive through the window", async () => {
203
+ const child = { exitCode: null, signalCode: null, pid: 42 } as never;
204
+ const trace = vi.fn();
205
+
206
+ const shouldExit = await decideRestartParentExit(child, 150, 30, trace);
207
+
208
+ expect(shouldExit).toBe(true);
209
+ expect(trace).toHaveBeenCalledWith(
210
+ "restart: child alive after window, parent exiting",
211
+ expect.objectContaining({ childPid: 42 }),
212
+ );
213
+ });
214
+
215
+ it("surfaces a child that died with a signal", async () => {
216
+ const child = { exitCode: null, signalCode: "SIGKILL", pid: 42 } as never;
217
+ const trace = vi.fn();
218
+
219
+ const shouldExit = await decideRestartParentExit(child, 100, 25, trace);
220
+
221
+ expect(shouldExit).toBe(false);
222
+ expect(trace).toHaveBeenCalledWith(
223
+ "restart: child died during window, keeping parent",
224
+ expect.objectContaining({ signalCode: "SIGKILL" }),
225
+ );
226
+ });
227
+
228
+ it("exports a sane default readiness window", () => {
229
+ expect(RESTART_CHILD_READY_MS).toBeGreaterThan(0);
230
+ expect(RESTART_CHILD_READY_MS).toBeLessThan(60_000);
231
+ });
232
+ });
@@ -131,9 +131,11 @@ import {
131
131
  stopUnifiedDisplayLoop,
132
132
  _setProcessAliveForTest,
133
133
  _resetProcessAliveForTest,
134
- _setProcessMonitorIntervalForTest,
135
- _resetProcessMonitorIntervalForTest,
136
- _setResponseStallTimeoutForTest,
134
+ _setProcessMonitorIntervalForTest,
135
+ _resetProcessMonitorIntervalForTest,
136
+ _setAvatarRefreshIntervalForTest,
137
+ _resetAvatarRefreshIntervalForTest,
138
+ _setResponseStallTimeoutForTest,
137
139
  _resetResponseStallTimeoutForTest,
138
140
  _setResponseStallCheckIntervalForTest,
139
141
  _resetResponseStallCheckIntervalForTest,
@@ -436,7 +438,7 @@ describe("runAgentSession previous final delivery guard", () => {
436
438
  });
437
439
  });
438
440
 
439
- describe("runAgentSession process monitor", () => {
441
+ describe("runAgentSession process monitor", () => {
440
442
  let registryFile = "";
441
443
  let toolsFile = "";
442
444
 
@@ -804,7 +806,99 @@ describe("runAgentSession process monitor", () => {
804
806
  expect(sentTexts[0]).toContain("first prompt");
805
807
  expect(sentTexts[1]).toContain("second prompt");
806
808
  });
807
- });
809
+ });
810
+
811
+ describe("runAgentSession periodic avatar refresh", () => {
812
+ let registryFile = "";
813
+ let toolsFile = "";
814
+
815
+ beforeEach(async () => {
816
+ vi.useFakeTimers();
817
+ resetState();
818
+ resetBindingState();
819
+ mockStreamStates.clear();
820
+ const dir = await mkdtemp(join(tmpdir(), "chatccc-avatar-refresh-"));
821
+ registryFile = join(dir, "session-registry.json");
822
+ toolsFile = join(dir, "session-tools.json");
823
+ _setSessionRegistryFileForTest(registryFile);
824
+ _setSessionToolsFileForTest(toolsFile);
825
+ _setAvatarRefreshIntervalForTest(50);
826
+ });
827
+
828
+ afterEach(async () => {
829
+ _resetSessionRegistryFileForTest();
830
+ _resetSessionToolsFileForTest();
831
+ _resetAvatarRefreshIntervalForTest();
832
+ _clearAdapterCacheForTest();
833
+ resetState();
834
+ resetBindingState();
835
+ vi.useRealTimers();
836
+ if (registryFile) await rm(dirname(registryFile), { recursive: true, force: true });
837
+ });
838
+
839
+ it.each(["codex", "cursor", "claude", "ccc"])(
840
+ "refreshes the busy avatar for %s every interval and stops after completion",
841
+ async (tool) => {
842
+ const sessionId = `sid-avatar-${tool}`;
843
+ const chatId = `chat-avatar-${tool}`;
844
+ const platform = mockPlatform("feishu");
845
+ setSessionPlatform(platform);
846
+ bindChatToSession(sessionId, chatId);
847
+ recordLastActiveChat(sessionId, chatId);
848
+
849
+ let finishPrompt: (() => void) | undefined;
850
+ const adapter: ToolAdapter = {
851
+ displayName: tool,
852
+ sessionDescPrefix: `${tool} Session:`,
853
+ createSession: async () => ({ sessionId }),
854
+ getSessionInfo: async (sid) => ({ sessionId: sid, cwd: "/tmp" }),
855
+ closeSession: async () => {},
856
+ prompt: async function* () {
857
+ yield { type: "assistant", blocks: [{ type: "text", text: "working" }] };
858
+ await new Promise<void>((resolve) => {
859
+ finishPrompt = resolve;
860
+ });
861
+ yield { type: "assistant", blocks: [{ type: "text", text: "done" }] };
862
+ },
863
+ };
864
+ _setAdapterForToolForTest(tool, adapter);
865
+
866
+ const runPromise = runAgentSession(
867
+ sessionId,
868
+ "prompt",
869
+ platform,
870
+ chatId,
871
+ Date.now(),
872
+ tool,
873
+ );
874
+
875
+ await vi.waitFor(() => {
876
+ expect(vi.mocked(platform.setChatAvatar).mock.calls.some(
877
+ ([calledChatId, calledTool, status]) =>
878
+ calledChatId === chatId && calledTool === tool && status === "busy",
879
+ )).toBe(true);
880
+ expect(finishPrompt).toBeTypeOf("function");
881
+ });
882
+ const initialBusyCalls = vi.mocked(platform.setChatAvatar).mock.calls.filter(
883
+ ([calledChatId, calledTool, status]) =>
884
+ calledChatId === chatId && calledTool === tool && status === "busy",
885
+ ).length;
886
+
887
+ await vi.advanceTimersByTimeAsync(51);
888
+ expect(vi.mocked(platform.setChatAvatar).mock.calls.filter(
889
+ ([calledChatId, calledTool, status]) =>
890
+ calledChatId === chatId && calledTool === tool && status === "busy",
891
+ )).toHaveLength(initialBusyCalls + 1);
892
+
893
+ finishPrompt?.();
894
+ await runPromise;
895
+ const callsAfterCompletion = vi.mocked(platform.setChatAvatar).mock.calls.length;
896
+
897
+ await vi.advanceTimersByTimeAsync(100);
898
+ expect(platform.setChatAvatar).toHaveBeenCalledTimes(callsAfterCompletion);
899
+ },
900
+ );
901
+ });
808
902
 
809
903
  describe("runAgentSession response stall watchdog", () => {
810
904
  let tempDir = "";