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,106 +1,106 @@
1
- import { gunzipSync } from "node:zlib";
2
- import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
3
- import { join } from "node:path";
4
- import { tmpdir } from "node:os";
5
-
6
- import { describe, expect, it } from "vitest";
7
-
8
- import {
9
- createRawStreamLog,
10
- sanitizeLogPathSegment,
11
- } from "../adapters/raw-stream-log.ts";
12
-
13
- describe("raw stream log", () => {
14
- it("does nothing when disabled", async () => {
15
- const root = await mkdtemp(join(tmpdir(), "chatccc-raw-log-"));
16
- try {
17
- const log = await createRawStreamLog({
18
- enabled: false,
19
- rootDir: root,
20
- tool: "cursor",
21
- sessionId: "sid",
22
- label: "turn",
23
- maxBytesPerTurn: 1024,
24
- retentionDays: 7,
25
- });
26
- expect(log).toBeNull();
27
- } finally {
28
- await rm(root, { recursive: true, force: true });
29
- }
30
- });
31
-
32
- it("writes gzipped JSONL and can keep the file", async () => {
33
- const root = await mkdtemp(join(tmpdir(), "chatccc-raw-log-"));
34
- try {
35
- const log = await createRawStreamLog({
36
- enabled: true,
37
- rootDir: root,
38
- tool: "cursor",
39
- sessionId: "sid/unsafe",
40
- label: "turn:1",
41
- maxBytesPerTurn: 1024,
42
- retentionDays: 7,
43
- });
44
- expect(log).not.toBeNull();
45
- log!.writeLine('{"type":"assistant","text":"hello"}');
46
- await log!.close({ keep: true });
47
-
48
- const raw = gunzipSync(await readFile(log!.filePath)).toString("utf-8");
49
- expect(raw).toBe('{"type":"assistant","text":"hello"}\n');
50
- expect(await stat(log!.filePath)).toBeTruthy();
51
- } finally {
52
- await rm(root, { recursive: true, force: true });
53
- }
54
- });
55
-
56
- it("writes a truncation marker once maxBytesPerTurn is exceeded", async () => {
57
- const root = await mkdtemp(join(tmpdir(), "chatccc-raw-log-"));
58
- try {
59
- const log = await createRawStreamLog({
60
- enabled: true,
61
- rootDir: root,
62
- tool: "cursor",
63
- sessionId: "sid",
64
- label: "turn",
65
- maxBytesPerTurn: 12,
66
- retentionDays: 7,
67
- });
68
- log!.writeLine('{"a":1}');
69
- log!.writeLine('{"too":"large"}');
70
- log!.writeLine('{"ignored":true}');
71
- await log!.close({ keep: true });
72
-
73
- const raw = gunzipSync(await readFile(log!.filePath)).toString("utf-8");
74
- expect(raw).toContain('{"a":1}');
75
- expect(raw).toContain("chatccc_raw_stream_log_truncated");
76
- expect(raw).not.toContain("ignored");
77
- } finally {
78
- await rm(root, { recursive: true, force: true });
79
- }
80
- });
81
-
82
- it("removes the file when keep is false", async () => {
83
- const root = await mkdtemp(join(tmpdir(), "chatccc-raw-log-"));
84
- try {
85
- const log = await createRawStreamLog({
86
- enabled: true,
87
- rootDir: root,
88
- tool: "cursor",
89
- sessionId: "sid",
90
- label: "turn",
91
- maxBytesPerTurn: 1024,
92
- retentionDays: 7,
93
- });
94
- log!.writeLine('{"type":"result"}');
95
- await log!.close({ keep: false });
96
- await expect(stat(log!.filePath)).rejects.toThrow();
97
- } finally {
98
- await rm(root, { recursive: true, force: true });
99
- }
100
- });
101
-
102
- it("sanitizes path segments", () => {
103
- expect(sanitizeLogPathSegment("../sid:1/2")).toBe("sid_1_2");
104
- expect(sanitizeLogPathSegment("")).toBe("unknown");
105
- });
106
- });
1
+ import { gunzipSync } from "node:zlib";
2
+ import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { tmpdir } from "node:os";
5
+
6
+ import { describe, expect, it } from "vitest";
7
+
8
+ import {
9
+ createRawStreamLog,
10
+ sanitizeLogPathSegment,
11
+ } from "../adapters/raw-stream-log.ts";
12
+
13
+ describe("raw stream log", () => {
14
+ it("does nothing when disabled", async () => {
15
+ const root = await mkdtemp(join(tmpdir(), "chatccc-raw-log-"));
16
+ try {
17
+ const log = await createRawStreamLog({
18
+ enabled: false,
19
+ rootDir: root,
20
+ tool: "cursor",
21
+ sessionId: "sid",
22
+ label: "turn",
23
+ maxBytesPerTurn: 1024,
24
+ retentionDays: 7,
25
+ });
26
+ expect(log).toBeNull();
27
+ } finally {
28
+ await rm(root, { recursive: true, force: true });
29
+ }
30
+ });
31
+
32
+ it("writes gzipped JSONL and can keep the file", async () => {
33
+ const root = await mkdtemp(join(tmpdir(), "chatccc-raw-log-"));
34
+ try {
35
+ const log = await createRawStreamLog({
36
+ enabled: true,
37
+ rootDir: root,
38
+ tool: "cursor",
39
+ sessionId: "sid/unsafe",
40
+ label: "turn:1",
41
+ maxBytesPerTurn: 1024,
42
+ retentionDays: 7,
43
+ });
44
+ expect(log).not.toBeNull();
45
+ log!.writeLine('{"type":"assistant","text":"hello"}');
46
+ await log!.close({ keep: true });
47
+
48
+ const raw = gunzipSync(await readFile(log!.filePath)).toString("utf-8");
49
+ expect(raw).toBe('{"type":"assistant","text":"hello"}\n');
50
+ expect(await stat(log!.filePath)).toBeTruthy();
51
+ } finally {
52
+ await rm(root, { recursive: true, force: true });
53
+ }
54
+ });
55
+
56
+ it("writes a truncation marker once maxBytesPerTurn is exceeded", async () => {
57
+ const root = await mkdtemp(join(tmpdir(), "chatccc-raw-log-"));
58
+ try {
59
+ const log = await createRawStreamLog({
60
+ enabled: true,
61
+ rootDir: root,
62
+ tool: "cursor",
63
+ sessionId: "sid",
64
+ label: "turn",
65
+ maxBytesPerTurn: 12,
66
+ retentionDays: 7,
67
+ });
68
+ log!.writeLine('{"a":1}');
69
+ log!.writeLine('{"too":"large"}');
70
+ log!.writeLine('{"ignored":true}');
71
+ await log!.close({ keep: true });
72
+
73
+ const raw = gunzipSync(await readFile(log!.filePath)).toString("utf-8");
74
+ expect(raw).toContain('{"a":1}');
75
+ expect(raw).toContain("chatccc_raw_stream_log_truncated");
76
+ expect(raw).not.toContain("ignored");
77
+ } finally {
78
+ await rm(root, { recursive: true, force: true });
79
+ }
80
+ });
81
+
82
+ it("removes the file when keep is false", async () => {
83
+ const root = await mkdtemp(join(tmpdir(), "chatccc-raw-log-"));
84
+ try {
85
+ const log = await createRawStreamLog({
86
+ enabled: true,
87
+ rootDir: root,
88
+ tool: "cursor",
89
+ sessionId: "sid",
90
+ label: "turn",
91
+ maxBytesPerTurn: 1024,
92
+ retentionDays: 7,
93
+ });
94
+ log!.writeLine('{"type":"result"}');
95
+ await log!.close({ keep: false });
96
+ await expect(stat(log!.filePath)).rejects.toThrow();
97
+ } finally {
98
+ await rm(root, { recursive: true, force: true });
99
+ }
100
+ });
101
+
102
+ it("sanitizes path segments", () => {
103
+ expect(sanitizeLogPathSegment("../sid:1/2")).toBe("sid_1_2");
104
+ expect(sanitizeLogPathSegment("")).toBe("unknown");
105
+ });
106
+ });
@@ -1,49 +1,49 @@
1
- import { describe, expect, it } from "vitest";
2
-
3
- import {
4
- hasResponseStalled,
5
- observeResponseProgress,
6
- } from "../response-stall.ts";
7
-
8
- describe("response stall detection", () => {
9
- it("starts tracking while responding even when the total character count is zero", () => {
10
- const observation = observeResponseProgress(undefined, true, 0, 1_000);
11
-
12
- expect(observation).toEqual({
13
- totalChars: 0,
14
- unchangedSince: 1_000,
15
- });
16
- });
17
-
18
- it("auto-ends only after the same character count has lasted three minutes", () => {
19
- const first = observeResponseProgress(undefined, true, 12, 1_000);
20
- const unchanged = observeResponseProgress(first, true, 12, 90_000);
21
-
22
- expect(unchanged).toBe(first);
23
- expect(hasResponseStalled(unchanged, 180_999, 180_000)).toBe(false);
24
- expect(hasResponseStalled(unchanged, 181_000, 180_000)).toBe(true);
25
- });
26
-
27
- it("restarts the timer whenever the total character count changes", () => {
28
- const first = observeResponseProgress(undefined, true, 12, 1_000);
29
- const changed = observeResponseProgress(first, true, 13, 150_000);
30
-
31
- expect(changed).toEqual({
32
- totalChars: 13,
33
- unchangedSince: 150_000,
34
- });
35
- expect(hasResponseStalled(changed, 181_000, 180_000)).toBe(false);
36
- });
37
-
38
- it("clears tracking outside responding and starts a fresh window after returning", () => {
39
- const first = observeResponseProgress(undefined, true, 0, 1_000);
40
- const cleared = observeResponseProgress(first, false, 0, 100_000);
41
- const resumed = observeResponseProgress(cleared, true, 0, 200_000);
42
-
43
- expect(cleared).toBeUndefined();
44
- expect(resumed).toEqual({
45
- totalChars: 0,
46
- unchangedSince: 200_000,
47
- });
48
- });
49
- });
1
+ import { describe, expect, it } from "vitest";
2
+
3
+ import {
4
+ hasResponseStalled,
5
+ observeResponseProgress,
6
+ } from "../response-stall.ts";
7
+
8
+ describe("response stall detection", () => {
9
+ it("starts tracking while responding even when the total character count is zero", () => {
10
+ const observation = observeResponseProgress(undefined, true, 0, 1_000);
11
+
12
+ expect(observation).toEqual({
13
+ totalChars: 0,
14
+ unchangedSince: 1_000,
15
+ });
16
+ });
17
+
18
+ it("auto-ends only after the same character count has lasted three minutes", () => {
19
+ const first = observeResponseProgress(undefined, true, 12, 1_000);
20
+ const unchanged = observeResponseProgress(first, true, 12, 90_000);
21
+
22
+ expect(unchanged).toBe(first);
23
+ expect(hasResponseStalled(unchanged, 180_999, 180_000)).toBe(false);
24
+ expect(hasResponseStalled(unchanged, 181_000, 180_000)).toBe(true);
25
+ });
26
+
27
+ it("restarts the timer whenever the total character count changes", () => {
28
+ const first = observeResponseProgress(undefined, true, 12, 1_000);
29
+ const changed = observeResponseProgress(first, true, 13, 150_000);
30
+
31
+ expect(changed).toEqual({
32
+ totalChars: 13,
33
+ unchangedSince: 150_000,
34
+ });
35
+ expect(hasResponseStalled(changed, 181_000, 180_000)).toBe(false);
36
+ });
37
+
38
+ it("clears tracking outside responding and starts a fresh window after returning", () => {
39
+ const first = observeResponseProgress(undefined, true, 0, 1_000);
40
+ const cleared = observeResponseProgress(first, false, 0, 100_000);
41
+ const resumed = observeResponseProgress(cleared, true, 0, 200_000);
42
+
43
+ expect(cleared).toBeUndefined();
44
+ expect(resumed).toEqual({
45
+ totalChars: 0,
46
+ unchangedSince: 200_000,
47
+ });
48
+ });
49
+ });
@@ -1,132 +1,132 @@
1
- import { EventEmitter } from "node:events";
2
- import { join } from "node:path";
3
-
4
- import { describe, expect, it, vi } from "vitest";
5
-
6
- import {
7
- buildRestartSpawnSpec,
8
- decideRestartParentExit,
9
- spawnRestartChild,
10
- RESTART_CHILD_READY_MS,
11
- } from "../orchestrator.ts";
12
- import { INTERNAL_RESTART_ENV_VAR } from "../startup-lifecycle.ts";
13
-
14
- describe("buildRestartSpawnSpec", () => {
15
- it("spawns node directly with the local tsx CLI (never via npx/npm)", () => {
16
- const spec = buildRestartSpawnSpec("F:/proj");
17
- expect(spec.command).toBe(process.execPath);
18
- expect(spec.args[0]).toBe(join("F:/proj", "node_modules", "tsx", "dist", "cli.mjs"));
19
- expect(spec.args[1]).toBe("src/index.ts");
20
- expect([spec.command, ...spec.args].join(" ")).not.toMatch(/npx|npm/i);
21
- });
22
-
23
- it("accepts the default project root", () => {
24
- const spec = buildRestartSpawnSpec();
25
- expect(spec.command).toBe(process.execPath);
26
- expect(spec.args[0]).toContain("tsx");
27
- });
28
- });
29
-
30
- describe("spawnRestartChild", () => {
31
- class FakeChild extends EventEmitter {
32
- pid = 12345;
33
- exitCode: number | null = null;
34
- signalCode: number | string | null = null;
35
- unref = vi.fn();
36
- stderr = new EventEmitter();
37
- }
38
-
39
- it("spawns without a shell, captures stderr, and marks the internal restart env", () => {
40
- const fake = new FakeChild();
41
- const spawnImpl = vi.fn(() => fake as never);
42
- const trace = vi.fn();
43
-
44
- const child = spawnRestartChild({ projectRoot: "F:/proj", spawnImpl, trace });
45
-
46
- expect(child).toBe(fake);
47
- expect(spawnImpl).toHaveBeenCalledWith(
48
- process.execPath,
49
- [join("F:/proj", "node_modules", "tsx", "dist", "cli.mjs"), "src/index.ts"],
50
- expect.objectContaining({
51
- detached: true,
52
- stdio: ["ignore", "ignore", "pipe"],
53
- env: expect.objectContaining({ [INTERNAL_RESTART_ENV_VAR]: "1" }),
54
- // 不使用 shell:避免 npm/npx 的 PATH 注入问题
55
- shell: false,
56
- }),
57
- );
58
- // spawnImpl 收到的 command/args 中不得出现 npx/npm(env 里的 npm_* 变量不算)
59
- const firstCall = spawnImpl.mock.calls[0] as unknown as [string, string[]];
60
- const [cmd, args] = firstCall;
61
- expect([cmd, ...args].join(" ")).not.toMatch(/npx|npm/i);
62
- });
63
-
64
- it("writes captured stderr into the trace on child exit", () => {
65
- const fake = new FakeChild();
66
- const spawnImpl = vi.fn(() => fake as never);
67
- const trace = vi.fn();
68
-
69
- spawnRestartChild({ projectRoot: "F:/proj", spawnImpl, trace });
70
-
71
- fake.stderr.emit("data", Buffer.from("tsx error line 1\n"));
72
- fake.stderr.emit("data", Buffer.from("tsx error line 2\n"));
73
- fake.exitCode = 1;
74
- fake.emit("exit", 1, null);
75
-
76
- const exitCall = trace.mock.calls.find(([name]) => name === "restart: child exit");
77
- expect(exitCall).toBeTruthy();
78
- expect(exitCall![1]).toEqual(expect.objectContaining({
79
- childPid: 12345,
80
- code: 1,
81
- signal: null,
82
- }));
83
- expect(exitCall![1].stderr).toContain("tsx error line 1");
84
- expect(exitCall![1].stderr).toContain("tsx error line 2");
85
- });
86
- });
87
-
88
- describe("decideRestartParentExit", () => {
89
- it("returns false (parent stays alive) when the child dies during the window", async () => {
90
- const child = { exitCode: 1, signalCode: null, pid: 42 } as never;
91
- const trace = vi.fn();
92
-
93
- const shouldExit = await decideRestartParentExit(child, 200, 50, trace);
94
-
95
- expect(shouldExit).toBe(false);
96
- expect(trace).toHaveBeenCalledWith(
97
- "restart: child died during window, keeping parent",
98
- expect.objectContaining({ childPid: 42, exitCode: 1 }),
99
- );
100
- });
101
-
102
- it("returns true (parent exits) when the child stays alive through the window", async () => {
103
- const child = { exitCode: null, signalCode: null, pid: 42 } as never;
104
- const trace = vi.fn();
105
-
106
- const shouldExit = await decideRestartParentExit(child, 150, 30, trace);
107
-
108
- expect(shouldExit).toBe(true);
109
- expect(trace).toHaveBeenCalledWith(
110
- "restart: child alive after window, parent exiting",
111
- expect.objectContaining({ childPid: 42 }),
112
- );
113
- });
114
-
115
- it("surfaces a child that died with a signal", async () => {
116
- const child = { exitCode: null, signalCode: "SIGKILL", pid: 42 } as never;
117
- const trace = vi.fn();
118
-
119
- const shouldExit = await decideRestartParentExit(child, 100, 25, trace);
120
-
121
- expect(shouldExit).toBe(false);
122
- expect(trace).toHaveBeenCalledWith(
123
- "restart: child died during window, keeping parent",
124
- expect.objectContaining({ signalCode: "SIGKILL" }),
125
- );
126
- });
127
-
128
- it("exports a sane default readiness window", () => {
129
- expect(RESTART_CHILD_READY_MS).toBeGreaterThan(0);
130
- expect(RESTART_CHILD_READY_MS).toBeLessThan(60_000);
131
- });
132
- });
1
+ import { EventEmitter } from "node:events";
2
+ import { join } from "node:path";
3
+
4
+ import { describe, expect, it, vi } from "vitest";
5
+
6
+ import {
7
+ buildRestartSpawnSpec,
8
+ decideRestartParentExit,
9
+ spawnRestartChild,
10
+ RESTART_CHILD_READY_MS,
11
+ } from "../orchestrator.ts";
12
+ import { INTERNAL_RESTART_ENV_VAR } from "../startup-lifecycle.ts";
13
+
14
+ describe("buildRestartSpawnSpec", () => {
15
+ it("spawns node directly with the local tsx CLI (never via npx/npm)", () => {
16
+ const spec = buildRestartSpawnSpec("F:/proj");
17
+ expect(spec.command).toBe(process.execPath);
18
+ expect(spec.args[0]).toBe(join("F:/proj", "node_modules", "tsx", "dist", "cli.mjs"));
19
+ expect(spec.args[1]).toBe("src/index.ts");
20
+ expect([spec.command, ...spec.args].join(" ")).not.toMatch(/npx|npm/i);
21
+ });
22
+
23
+ it("accepts the default project root", () => {
24
+ const spec = buildRestartSpawnSpec();
25
+ expect(spec.command).toBe(process.execPath);
26
+ expect(spec.args[0]).toContain("tsx");
27
+ });
28
+ });
29
+
30
+ describe("spawnRestartChild", () => {
31
+ class FakeChild extends EventEmitter {
32
+ pid = 12345;
33
+ exitCode: number | null = null;
34
+ signalCode: number | string | null = null;
35
+ unref = vi.fn();
36
+ stderr = new EventEmitter();
37
+ }
38
+
39
+ it("spawns without a shell, captures stderr, and marks the internal restart env", () => {
40
+ const fake = new FakeChild();
41
+ const spawnImpl = vi.fn(() => fake as never);
42
+ const trace = vi.fn();
43
+
44
+ const child = spawnRestartChild({ projectRoot: "F:/proj", spawnImpl, trace });
45
+
46
+ expect(child).toBe(fake);
47
+ expect(spawnImpl).toHaveBeenCalledWith(
48
+ process.execPath,
49
+ [join("F:/proj", "node_modules", "tsx", "dist", "cli.mjs"), "src/index.ts"],
50
+ expect.objectContaining({
51
+ detached: true,
52
+ stdio: ["ignore", "ignore", "pipe"],
53
+ env: expect.objectContaining({ [INTERNAL_RESTART_ENV_VAR]: "1" }),
54
+ // 不使用 shell:避免 npm/npx 的 PATH 注入问题
55
+ shell: false,
56
+ }),
57
+ );
58
+ // spawnImpl 收到的 command/args 中不得出现 npx/npm(env 里的 npm_* 变量不算)
59
+ const firstCall = spawnImpl.mock.calls[0] as unknown as [string, string[]];
60
+ const [cmd, args] = firstCall;
61
+ expect([cmd, ...args].join(" ")).not.toMatch(/npx|npm/i);
62
+ });
63
+
64
+ it("writes captured stderr into the trace on child exit", () => {
65
+ const fake = new FakeChild();
66
+ const spawnImpl = vi.fn(() => fake as never);
67
+ const trace = vi.fn();
68
+
69
+ spawnRestartChild({ projectRoot: "F:/proj", spawnImpl, trace });
70
+
71
+ fake.stderr.emit("data", Buffer.from("tsx error line 1\n"));
72
+ fake.stderr.emit("data", Buffer.from("tsx error line 2\n"));
73
+ fake.exitCode = 1;
74
+ fake.emit("exit", 1, null);
75
+
76
+ const exitCall = trace.mock.calls.find(([name]) => name === "restart: child exit");
77
+ expect(exitCall).toBeTruthy();
78
+ expect(exitCall![1]).toEqual(expect.objectContaining({
79
+ childPid: 12345,
80
+ code: 1,
81
+ signal: null,
82
+ }));
83
+ expect(exitCall![1].stderr).toContain("tsx error line 1");
84
+ expect(exitCall![1].stderr).toContain("tsx error line 2");
85
+ });
86
+ });
87
+
88
+ describe("decideRestartParentExit", () => {
89
+ it("returns false (parent stays alive) when the child dies during the window", async () => {
90
+ const child = { exitCode: 1, signalCode: null, pid: 42 } as never;
91
+ const trace = vi.fn();
92
+
93
+ const shouldExit = await decideRestartParentExit(child, 200, 50, trace);
94
+
95
+ expect(shouldExit).toBe(false);
96
+ expect(trace).toHaveBeenCalledWith(
97
+ "restart: child died during window, keeping parent",
98
+ expect.objectContaining({ childPid: 42, exitCode: 1 }),
99
+ );
100
+ });
101
+
102
+ it("returns true (parent exits) when the child stays alive through the window", async () => {
103
+ const child = { exitCode: null, signalCode: null, pid: 42 } as never;
104
+ const trace = vi.fn();
105
+
106
+ const shouldExit = await decideRestartParentExit(child, 150, 30, trace);
107
+
108
+ expect(shouldExit).toBe(true);
109
+ expect(trace).toHaveBeenCalledWith(
110
+ "restart: child alive after window, parent exiting",
111
+ expect.objectContaining({ childPid: 42 }),
112
+ );
113
+ });
114
+
115
+ it("surfaces a child that died with a signal", async () => {
116
+ const child = { exitCode: null, signalCode: "SIGKILL", pid: 42 } as never;
117
+ const trace = vi.fn();
118
+
119
+ const shouldExit = await decideRestartParentExit(child, 100, 25, trace);
120
+
121
+ expect(shouldExit).toBe(false);
122
+ expect(trace).toHaveBeenCalledWith(
123
+ "restart: child died during window, keeping parent",
124
+ expect.objectContaining({ signalCode: "SIGKILL" }),
125
+ );
126
+ });
127
+
128
+ it("exports a sane default readiness window", () => {
129
+ expect(RESTART_CHILD_READY_MS).toBeGreaterThan(0);
130
+ expect(RESTART_CHILD_READY_MS).toBeLessThan(60_000);
131
+ });
132
+ });