chatccc 0.2.226 → 0.2.227

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 (64) 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/package.json +1 -1
  6. package/src/__tests__/agent-activity.test.ts +76 -76
  7. package/src/__tests__/builtin-chat-session.test.ts +350 -350
  8. package/src/__tests__/builtin-config.test.ts +26 -26
  9. package/src/__tests__/builtin-context.test.ts +163 -163
  10. package/src/__tests__/builtin-file-tools.test.ts +275 -275
  11. package/src/__tests__/builtin-permissions.test.ts +211 -211
  12. package/src/__tests__/builtin-session-select.test.ts +116 -116
  13. package/src/__tests__/builtin-skills.test.ts +185 -74
  14. package/src/__tests__/card-action-routing.test.ts +18 -18
  15. package/src/__tests__/ccc-adapter.test.ts +136 -136
  16. package/src/__tests__/claude-adapter.test.ts +614 -614
  17. package/src/__tests__/codex-adapter.test.ts +58 -58
  18. package/src/__tests__/codex-raw-stream-log.test.ts +170 -170
  19. package/src/__tests__/cursor-adapter.test.ts +268 -268
  20. package/src/__tests__/feishu-avatar.test.ts +164 -164
  21. package/src/__tests__/feishu-message-ingress.test.ts +138 -138
  22. package/src/__tests__/package-files.test.ts +24 -24
  23. package/src/__tests__/progress-reducer.test.ts +110 -110
  24. package/src/__tests__/response-stall.test.ts +49 -49
  25. package/src/__tests__/sim-platform.test.ts +16 -16
  26. package/src/__tests__/startup-lifecycle.test.ts +231 -231
  27. package/src/__tests__/stop-session.test.ts +34 -34
  28. package/src/__tests__/terminal-renderer.test.ts +247 -247
  29. package/src/__tests__/update-command-guard.test.ts +144 -144
  30. package/src/__tests__/web-ui.test.ts +326 -326
  31. package/src/adapters/adapter-interface.ts +18 -18
  32. package/src/adapters/ccc-adapter.ts +131 -131
  33. package/src/adapters/claude-adapter.ts +620 -620
  34. package/src/adapters/codex-adapter.ts +426 -426
  35. package/src/adapters/cursor-adapter.ts +681 -681
  36. package/src/agent-activity.ts +170 -170
  37. package/src/agent-delegate-task.ts +91 -91
  38. package/src/builtin/cli.ts +61 -2
  39. package/src/builtin/config.ts +84 -84
  40. package/src/builtin/context.ts +323 -323
  41. package/src/builtin/file-log.ts +38 -38
  42. package/src/builtin/index.ts +44 -24
  43. package/src/builtin/proc-tree-kill.ts +61 -61
  44. package/src/builtin/progress/cards-helpers.ts +76 -76
  45. package/src/builtin/progress/reducer.ts +108 -108
  46. package/src/builtin/progress/terminal-renderer.ts +294 -294
  47. package/src/builtin/progress/view.ts +77 -77
  48. package/src/builtin/raw-stream-log.ts +124 -124
  49. package/src/builtin/session-select.ts +48 -48
  50. package/src/builtin/skills.ts +126 -44
  51. package/src/card-action-routing.ts +14 -14
  52. package/src/feishu-api.ts +193 -193
  53. package/src/feishu-message-ingress.ts +195 -195
  54. package/src/index.ts +306 -306
  55. package/src/orchestrator.ts +2388 -2388
  56. package/src/platform-adapter.ts +6 -6
  57. package/src/progress/reducer.ts +108 -108
  58. package/src/progress/terminal-renderer.ts +294 -294
  59. package/src/progress/view.ts +77 -77
  60. package/src/response-stall.ts +28 -28
  61. package/src/session-chat-binding.ts +82 -82
  62. package/src/startup-lifecycle.ts +250 -250
  63. package/src/stream-state.ts +18 -18
  64. package/src/update-command-guard.ts +165 -165
@@ -1,9 +1,9 @@
1
- import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
1
+ import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
2
2
  import { tmpdir } from "node:os";
3
3
  import { join } from "node:path";
4
4
 
5
- import { afterEach, describe, expect, it, vi } from "vitest";
6
- import sharp from "sharp";
5
+ import { afterEach, describe, expect, it, vi } from "vitest";
6
+ import sharp from "sharp";
7
7
 
8
8
  const mockConfig = {
9
9
  cursor: {
@@ -69,18 +69,18 @@ function mockAvatarFetch(uploadedNames: string[], usageResponse: Response): void
69
69
  }));
70
70
  }
71
71
 
72
- function mockAvatarUploadOnlyFetch(
73
- uploadedNames: string[],
74
- uploadedImages: Buffer[] = [],
75
- ): ReturnType<typeof vi.fn> {
76
- const fetchMock = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
77
- const urlText = String(url);
78
- if (urlText === "https://open.feishu.test/im/v1/images") {
79
- const form = init?.body as FormData;
80
- const image = form.get("image") as File;
81
- uploadedNames.push(image.name);
82
- uploadedImages.push(Buffer.from(await image.arrayBuffer()));
83
- return new Response(JSON.stringify({ code: 0, data: { image_key: "img_test" } }), { status: 200 });
72
+ function mockAvatarUploadOnlyFetch(
73
+ uploadedNames: string[],
74
+ uploadedImages: Buffer[] = [],
75
+ ): ReturnType<typeof vi.fn> {
76
+ const fetchMock = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
77
+ const urlText = String(url);
78
+ if (urlText === "https://open.feishu.test/im/v1/images") {
79
+ const form = init?.body as FormData;
80
+ const image = form.get("image") as File;
81
+ uploadedNames.push(image.name);
82
+ uploadedImages.push(Buffer.from(await image.arrayBuffer()));
83
+ return new Response(JSON.stringify({ code: 0, data: { image_key: "img_test" } }), { status: 200 });
84
84
  }
85
85
  if (urlText === "https://open.feishu.test/im/v1/chats/chat_1") {
86
86
  return new Response(JSON.stringify({ code: 0 }), { status: 200 });
@@ -88,10 +88,44 @@ function mockAvatarUploadOnlyFetch(
88
88
  throw new Error(`unexpected fetch: ${urlText}`);
89
89
  });
90
90
  vi.stubGlobal("fetch", fetchMock);
91
- return fetchMock;
92
- }
93
-
94
- describe("Plain avatar fallback", () => {
91
+ return fetchMock;
92
+ }
93
+
94
+ describe("Plain avatar fallback", () => {
95
+ afterEach(() => {
96
+ vi.unstubAllGlobals();
97
+ vi.doUnmock("node:os");
98
+ vi.doUnmock("../config.ts");
99
+ vi.doUnmock("../cursor-usage.ts");
100
+ vi.restoreAllMocks();
101
+ getCursorUsageSummaryMock.mockReset();
102
+ mockConfig.cursor.avatarBatteryMode = "apiPercent";
103
+ mockConfig.cursor.onDemandMonthlyBudget = 1000;
104
+ });
105
+
106
+ it("uses a status-only avatar for unknown tools instead of falling back to Claude", async () => {
107
+ const homeDir = await mkdtemp(join(tmpdir(), "chatccc-avatar-home-"));
108
+ const userDataDir = await mkdtemp(join(tmpdir(), "chatccc-avatar-data-"));
109
+ const uploadedNames: string[] = [];
110
+ mockAvatarUploadOnlyFetch(uploadedNames);
111
+
112
+ try {
113
+ const { setChatAvatar } = await loadFeishuApiWithHome(homeDir, userDataDir);
114
+ await setChatAvatar("tenant-token", "chat_1", "ccc", "new");
115
+
116
+ expect(uploadedNames).toEqual(["avatar_plain_new.jpg"]);
117
+ const cacheRaw = await readFile(join(userDataDir, "state", "avatar-image-keys.json"), "utf-8");
118
+ const cache = JSON.parse(cacheRaw) as Record<string, string>;
119
+ expect(cache["plain:new"]).toBe("img_test");
120
+ expect(cache["claude:new"]).toBeUndefined();
121
+ } finally {
122
+ await rm(homeDir, { recursive: true, force: true });
123
+ await rm(userDataDir, { recursive: true, force: true });
124
+ }
125
+ });
126
+ });
127
+
128
+ describe("Codex avatar usage battery", () => {
95
129
  afterEach(() => {
96
130
  vi.unstubAllGlobals();
97
131
  vi.doUnmock("node:os");
@@ -103,106 +137,72 @@ describe("Plain avatar fallback", () => {
103
137
  mockConfig.cursor.onDemandMonthlyBudget = 1000;
104
138
  });
105
139
 
106
- it("uses a status-only avatar for unknown tools instead of falling back to Claude", async () => {
107
- const homeDir = await mkdtemp(join(tmpdir(), "chatccc-avatar-home-"));
108
- const userDataDir = await mkdtemp(join(tmpdir(), "chatccc-avatar-data-"));
109
- const uploadedNames: string[] = [];
110
- mockAvatarUploadOnlyFetch(uploadedNames);
111
-
112
- try {
113
- const { setChatAvatar } = await loadFeishuApiWithHome(homeDir, userDataDir);
114
- await setChatAvatar("tenant-token", "chat_1", "ccc", "new");
115
-
116
- expect(uploadedNames).toEqual(["avatar_plain_new.jpg"]);
117
- const cacheRaw = await readFile(join(userDataDir, "state", "avatar-image-keys.json"), "utf-8");
118
- const cache = JSON.parse(cacheRaw) as Record<string, string>;
119
- expect(cache["plain:new"]).toBe("img_test");
120
- expect(cache["claude:new"]).toBeUndefined();
121
- } finally {
122
- await rm(homeDir, { recursive: true, force: true });
123
- await rm(userDataDir, { recursive: true, force: true });
124
- }
125
- });
126
- });
127
-
128
- describe("Codex avatar usage battery", () => {
129
- afterEach(() => {
130
- vi.unstubAllGlobals();
131
- vi.doUnmock("node:os");
132
- vi.doUnmock("../config.ts");
133
- vi.doUnmock("../cursor-usage.ts");
134
- vi.restoreAllMocks();
135
- getCursorUsageSummaryMock.mockReset();
136
- mockConfig.cursor.avatarBatteryMode = "apiPercent";
137
- mockConfig.cursor.onDemandMonthlyBudget = 1000;
138
- });
139
-
140
- it("adds 7-day battery and 5h ring percentages to Codex avatar uploads when both windows exist", async () => {
140
+ it("adds 7-day battery and 5h ring percentages to Codex avatar uploads when both windows exist", async () => {
141
141
  const homeDir = await mkdtemp(join(tmpdir(), "chatccc-avatar-home-"));
142
142
  const userDataDir = await mkdtemp(join(tmpdir(), "chatccc-avatar-data-"));
143
143
  const uploadedNames: string[] = [];
144
144
  await writeCodexAuth(homeDir);
145
145
  mockAvatarFetch(uploadedNames, new Response(JSON.stringify({
146
- rate_limit: {
147
- primary_window: { used_percent: 37, limit_window_seconds: 18000 },
148
- secondary_window: { used_percent: 12, limit_window_seconds: 604800 },
149
- },
146
+ rate_limit: {
147
+ primary_window: { used_percent: 37, limit_window_seconds: 18000 },
148
+ secondary_window: { used_percent: 12, limit_window_seconds: 604800 },
149
+ },
150
150
  }), { status: 200 }));
151
151
 
152
152
  try {
153
153
  const { setChatAvatar } = await loadFeishuApiWithHome(homeDir, userDataDir);
154
154
  await setChatAvatar("tenant-token", "chat_1", "codex", "busy");
155
155
 
156
- expect(uploadedNames).toEqual(["avatar_codex_busy_7d_88_5h_63.jpg"]);
156
+ expect(uploadedNames).toEqual(["avatar_codex_busy_7d_88_5h_63.jpg"]);
157
157
  } finally {
158
158
  await rm(homeDir, { recursive: true, force: true });
159
159
  await rm(userDataDir, { recursive: true, force: true });
160
160
  }
161
- });
162
-
163
- it("uses a 7-day battery without a 5h ring when the API only returns a 7-day window", async () => {
164
- const homeDir = await mkdtemp(join(tmpdir(), "chatccc-avatar-home-"));
165
- const userDataDir = await mkdtemp(join(tmpdir(), "chatccc-avatar-data-"));
166
- const uploadedNames: string[] = [];
167
- await writeCodexAuth(homeDir);
168
- mockAvatarFetch(uploadedNames, new Response(JSON.stringify({
169
- rate_limit: {
170
- primary_window: {
171
- used_percent: 23,
172
- limit_window_seconds: 604800,
173
- reset_after_seconds: 500000,
174
- reset_at: 1784510226,
175
- },
176
- secondary_window: null,
177
- },
178
- }), { status: 200 }));
179
-
180
- try {
181
- const { getCodexUsageSummary, setChatAvatar } = await loadFeishuApiWithHome(homeDir, userDataDir);
182
-
183
- await expect(getCodexUsageSummary()).resolves.toEqual({
184
- fiveHour: null,
185
- weekly: {
186
- usedPercent: 23,
187
- remainingPercent: 77,
188
- resetAfterSeconds: 500000,
189
- resetAtEpochSeconds: 1784510226,
190
- limitWindowSeconds: 604800,
191
- },
192
- rateLimitResetCreditsAvailable: null,
193
- rateLimitResetCredits: [],
194
- });
195
-
196
- await setChatAvatar("tenant-token", "chat_1", "codex", "busy");
197
-
198
- expect(uploadedNames).toEqual(["avatar_codex_busy_7d_77.jpg"]);
199
- } finally {
200
- await rm(homeDir, { recursive: true, force: true });
201
- await rm(userDataDir, { recursive: true, force: true });
202
- }
203
- });
204
-
205
- it("uses provided Codex usage without fetching usage again", async () => {
161
+ });
162
+
163
+ it("uses a 7-day battery without a 5h ring when the API only returns a 7-day window", async () => {
164
+ const homeDir = await mkdtemp(join(tmpdir(), "chatccc-avatar-home-"));
165
+ const userDataDir = await mkdtemp(join(tmpdir(), "chatccc-avatar-data-"));
166
+ const uploadedNames: string[] = [];
167
+ await writeCodexAuth(homeDir);
168
+ mockAvatarFetch(uploadedNames, new Response(JSON.stringify({
169
+ rate_limit: {
170
+ primary_window: {
171
+ used_percent: 23,
172
+ limit_window_seconds: 604800,
173
+ reset_after_seconds: 500000,
174
+ reset_at: 1784510226,
175
+ },
176
+ secondary_window: null,
177
+ },
178
+ }), { status: 200 }));
179
+
180
+ try {
181
+ const { getCodexUsageSummary, setChatAvatar } = await loadFeishuApiWithHome(homeDir, userDataDir);
182
+
183
+ await expect(getCodexUsageSummary()).resolves.toEqual({
184
+ fiveHour: null,
185
+ weekly: {
186
+ usedPercent: 23,
187
+ remainingPercent: 77,
188
+ resetAfterSeconds: 500000,
189
+ resetAtEpochSeconds: 1784510226,
190
+ limitWindowSeconds: 604800,
191
+ },
192
+ rateLimitResetCreditsAvailable: null,
193
+ rateLimitResetCredits: [],
194
+ });
195
+
196
+ await setChatAvatar("tenant-token", "chat_1", "codex", "busy");
197
+
198
+ expect(uploadedNames).toEqual(["avatar_codex_busy_7d_77.jpg"]);
199
+ } finally {
200
+ await rm(homeDir, { recursive: true, force: true });
201
+ await rm(userDataDir, { recursive: true, force: true });
202
+ }
203
+ });
204
+
205
+ it("uses provided Codex usage without fetching usage again", async () => {
206
206
  const homeDir = await mkdtemp(join(tmpdir(), "chatccc-avatar-home-"));
207
207
  const userDataDir = await mkdtemp(join(tmpdir(), "chatccc-avatar-data-"));
208
208
  const uploadedNames: string[] = [];
@@ -219,71 +219,71 @@ describe("Codex avatar usage battery", () => {
219
219
  },
220
220
  });
221
221
 
222
- expect(uploadedNames).toEqual(["avatar_codex_busy_7d_88_5h_63.jpg"]);
222
+ expect(uploadedNames).toEqual(["avatar_codex_busy_7d_88_5h_63.jpg"]);
223
223
  expect(fetchMock).not.toHaveBeenCalledWith("https://chatgpt.com/backend-api/wham/usage", expect.anything());
224
224
  } finally {
225
225
  await rm(homeDir, { recursive: true, force: true });
226
226
  await rm(userDataDir, { recursive: true, force: true });
227
227
  }
228
- });
229
-
230
- it("isolates Fast and standard Codex avatars in the upload cache", async () => {
231
- const homeDir = await mkdtemp(join(tmpdir(), "chatccc-avatar-home-"));
232
- const userDataDir = await mkdtemp(join(tmpdir(), "chatccc-avatar-data-"));
233
- const uploadedNames: string[] = [];
234
- mockAvatarUploadOnlyFetch(uploadedNames);
235
-
236
- try {
237
- const { setChatAvatar } = await loadFeishuApiWithHome(homeDir, userDataDir);
238
- await setChatAvatar("tenant-token", "chat_1", "codex", "idle", {
239
- codexUsage: null,
240
- fastMode: false,
241
- });
242
- await setChatAvatar("tenant-token", "chat_1", "codex", "idle", {
243
- codexUsage: null,
244
- fastMode: true,
245
- });
246
-
247
- expect(uploadedNames).toEqual([
248
- "avatar_codex_idle.jpg",
249
- "avatar_codex_idle_fast.jpg",
250
- ]);
251
- const cacheRaw = await readFile(join(userDataDir, "state", "avatar-image-keys.json"), "utf-8");
252
- const cache = JSON.parse(cacheRaw) as Record<string, string>;
253
- expect(cache["codex:idle:plain"]).toBe("img_test");
254
- expect(cache["codex:idle:plain:fast-champagne-frame-v2"]).toBe("img_test");
255
- } finally {
256
- await rm(homeDir, { recursive: true, force: true });
257
- await rm(userDataDir, { recursive: true, force: true });
258
- }
259
- });
260
-
261
- it("renders an extra-thick champagne frame above the Codex badge in Fast mode", async () => {
262
- const homeDir = await mkdtemp(join(tmpdir(), "chatccc-avatar-home-"));
263
- const userDataDir = await mkdtemp(join(tmpdir(), "chatccc-avatar-data-"));
264
- const uploadedNames: string[] = [];
265
- const uploadedImages: Buffer[] = [];
266
- mockAvatarUploadOnlyFetch(uploadedNames, uploadedImages);
267
-
268
- try {
269
- const { setChatAvatar } = await loadFeishuApiWithHome(homeDir, userDataDir);
270
- await setChatAvatar("tenant-token", "chat_1", "codex", "idle", {
271
- codexUsage: null,
272
- fastMode: true,
273
- });
274
-
275
- expect(uploadedNames).toEqual(["avatar_codex_idle_fast.jpg"]);
276
- const { data, info } = await sharp(uploadedImages[0]).raw().toBuffer({ resolveWithObject: true });
277
- const pixelOffset = (144 * info.width + 200) * info.channels;
278
- const [red, green, blue] = data.subarray(pixelOffset, pixelOffset + 3);
279
- expect(red).toBeGreaterThan(220);
280
- expect(green).toBeGreaterThan(150);
281
- expect(blue).toBeLessThan(180);
282
- } finally {
283
- await rm(homeDir, { recursive: true, force: true });
284
- await rm(userDataDir, { recursive: true, force: true });
285
- }
286
- });
228
+ });
229
+
230
+ it("isolates Fast and standard Codex avatars in the upload cache", async () => {
231
+ const homeDir = await mkdtemp(join(tmpdir(), "chatccc-avatar-home-"));
232
+ const userDataDir = await mkdtemp(join(tmpdir(), "chatccc-avatar-data-"));
233
+ const uploadedNames: string[] = [];
234
+ mockAvatarUploadOnlyFetch(uploadedNames);
235
+
236
+ try {
237
+ const { setChatAvatar } = await loadFeishuApiWithHome(homeDir, userDataDir);
238
+ await setChatAvatar("tenant-token", "chat_1", "codex", "idle", {
239
+ codexUsage: null,
240
+ fastMode: false,
241
+ });
242
+ await setChatAvatar("tenant-token", "chat_1", "codex", "idle", {
243
+ codexUsage: null,
244
+ fastMode: true,
245
+ });
246
+
247
+ expect(uploadedNames).toEqual([
248
+ "avatar_codex_idle.jpg",
249
+ "avatar_codex_idle_fast.jpg",
250
+ ]);
251
+ const cacheRaw = await readFile(join(userDataDir, "state", "avatar-image-keys.json"), "utf-8");
252
+ const cache = JSON.parse(cacheRaw) as Record<string, string>;
253
+ expect(cache["codex:idle:plain"]).toBe("img_test");
254
+ expect(cache["codex:idle:plain:fast-champagne-frame-v2"]).toBe("img_test");
255
+ } finally {
256
+ await rm(homeDir, { recursive: true, force: true });
257
+ await rm(userDataDir, { recursive: true, force: true });
258
+ }
259
+ });
260
+
261
+ it("renders an extra-thick champagne frame above the Codex badge in Fast mode", async () => {
262
+ const homeDir = await mkdtemp(join(tmpdir(), "chatccc-avatar-home-"));
263
+ const userDataDir = await mkdtemp(join(tmpdir(), "chatccc-avatar-data-"));
264
+ const uploadedNames: string[] = [];
265
+ const uploadedImages: Buffer[] = [];
266
+ mockAvatarUploadOnlyFetch(uploadedNames, uploadedImages);
267
+
268
+ try {
269
+ const { setChatAvatar } = await loadFeishuApiWithHome(homeDir, userDataDir);
270
+ await setChatAvatar("tenant-token", "chat_1", "codex", "idle", {
271
+ codexUsage: null,
272
+ fastMode: true,
273
+ });
274
+
275
+ expect(uploadedNames).toEqual(["avatar_codex_idle_fast.jpg"]);
276
+ const { data, info } = await sharp(uploadedImages[0]).raw().toBuffer({ resolveWithObject: true });
277
+ const pixelOffset = (144 * info.width + 200) * info.channels;
278
+ const [red, green, blue] = data.subarray(pixelOffset, pixelOffset + 3);
279
+ expect(red).toBeGreaterThan(220);
280
+ expect(green).toBeGreaterThan(150);
281
+ expect(blue).toBeLessThan(180);
282
+ } finally {
283
+ await rm(homeDir, { recursive: true, force: true });
284
+ await rm(userDataDir, { recursive: true, force: true });
285
+ }
286
+ });
287
287
 
288
288
  it("returns both usage windows and available reset credit expiries", async () => {
289
289
  const homeDir = await mkdtemp(join(tmpdir(), "chatccc-avatar-home-"));
@@ -1,138 +1,138 @@
1
- import { mkdtemp, rm } from "node:fs/promises";
2
- import { tmpdir } from "node:os";
3
- import { join } from "node:path";
4
-
5
- import { afterEach, describe, expect, it, vi } from "vitest";
6
-
7
- import {
8
- FeishuMessageLedger,
9
- createAckFirstEventHandler,
10
- } from "../feishu-message-ingress.ts";
11
-
12
- const tempDirs: string[] = [];
13
-
14
- async function createLedger(maxEntries = 5): Promise<FeishuMessageLedger> {
15
- const dir = await mkdtemp(join(tmpdir(), "chatccc-feishu-ingress-"));
16
- tempDirs.push(dir);
17
- return new FeishuMessageLedger(join(dir, "messages.json"), maxEntries);
18
- }
19
-
20
- afterEach(async () => {
21
- await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
22
- });
23
-
24
- describe("createAckFirstEventHandler", () => {
25
- it("returns before starting the asynchronous event worker", async () => {
26
- let scheduled: (() => void) | undefined;
27
- const schedule = vi.fn((task: () => void) => {
28
- scheduled = task;
29
- });
30
- const worker = vi.fn(async () => {});
31
- const onError = vi.fn();
32
- const handler = createAckFirstEventHandler(worker, onError, schedule);
33
-
34
- await expect(handler({ message: "test" })).resolves.toBeUndefined();
35
- expect(schedule).toHaveBeenCalledOnce();
36
- expect(worker).not.toHaveBeenCalled();
37
-
38
- scheduled?.();
39
- await vi.waitFor(() => expect(worker).toHaveBeenCalledWith({ message: "test" }));
40
- expect(onError).not.toHaveBeenCalled();
41
- });
42
-
43
- it("reports detached worker failures without rejecting the SDK callback", async () => {
44
- const error = new Error("worker failed");
45
- const onError = vi.fn();
46
- const handler = createAckFirstEventHandler(
47
- async () => {
48
- throw error;
49
- },
50
- onError,
51
- (task) => task(),
52
- );
53
-
54
- await expect(handler({})).resolves.toBeUndefined();
55
- await vi.waitFor(() => expect(onError).toHaveBeenCalledWith(error));
56
- });
57
- });
58
-
59
- describe("FeishuMessageLedger", () => {
60
- it("rejects an already accepted message after a process restart", async () => {
61
- const first = await createLedger();
62
- await first.load();
63
-
64
- expect(await first.accept({
65
- messageId: "om_001",
66
- chatId: "oc_chat",
67
- createTime: 100,
68
- })).toBe("accepted");
69
-
70
- const restarted = new FeishuMessageLedger(first.filePath, 5);
71
- await restarted.load();
72
-
73
- expect(await restarted.accept({
74
- messageId: "om_001",
75
- chatId: "oc_chat",
76
- createTime: 100,
77
- })).toBe("duplicate");
78
- });
79
-
80
- it("rejects a unique old event after restoring the chat high-water mark", async () => {
81
- const first = await createLedger();
82
- await first.load();
83
-
84
- expect(await first.accept({
85
- messageId: "om_new",
86
- chatId: "oc_chat",
87
- createTime: 200,
88
- })).toBe("accepted");
89
-
90
- const restarted = new FeishuMessageLedger(first.filePath, 5);
91
- await restarted.load();
92
-
93
- expect(await restarted.accept({
94
- messageId: "om_old",
95
- chatId: "oc_chat",
96
- createTime: 100,
97
- })).toBe("stale");
98
- });
99
-
100
- it("accepts distinct messages with the same create timestamp", async () => {
101
- const ledger = await createLedger();
102
- await ledger.load();
103
-
104
- expect(await ledger.accept({
105
- messageId: "om_001",
106
- chatId: "oc_chat",
107
- createTime: 100,
108
- })).toBe("accepted");
109
- expect(await ledger.accept({
110
- messageId: "om_002",
111
- chatId: "oc_chat",
112
- createTime: 100,
113
- })).toBe("accepted");
114
- });
115
-
116
- it("keeps only the configured number of recent message IDs", async () => {
117
- const ledger = await createLedger(2);
118
- await ledger.load();
119
-
120
- await ledger.accept({ messageId: "om_001", chatId: "oc_chat", createTime: 100 });
121
- await ledger.accept({ messageId: "om_002", chatId: "oc_chat", createTime: 200 });
122
- await ledger.accept({ messageId: "om_003", chatId: "oc_chat", createTime: 300 });
123
-
124
- const restarted = new FeishuMessageLedger(ledger.filePath, 2);
125
- await restarted.load();
126
-
127
- expect(await restarted.accept({
128
- messageId: "om_001",
129
- chatId: "oc_other",
130
- createTime: 100,
131
- })).toBe("accepted");
132
- expect(await restarted.accept({
133
- messageId: "om_003",
134
- chatId: "oc_chat",
135
- createTime: 300,
136
- })).toBe("duplicate");
137
- });
138
- });
1
+ import { mkdtemp, rm } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+
5
+ import { afterEach, describe, expect, it, vi } from "vitest";
6
+
7
+ import {
8
+ FeishuMessageLedger,
9
+ createAckFirstEventHandler,
10
+ } from "../feishu-message-ingress.ts";
11
+
12
+ const tempDirs: string[] = [];
13
+
14
+ async function createLedger(maxEntries = 5): Promise<FeishuMessageLedger> {
15
+ const dir = await mkdtemp(join(tmpdir(), "chatccc-feishu-ingress-"));
16
+ tempDirs.push(dir);
17
+ return new FeishuMessageLedger(join(dir, "messages.json"), maxEntries);
18
+ }
19
+
20
+ afterEach(async () => {
21
+ await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
22
+ });
23
+
24
+ describe("createAckFirstEventHandler", () => {
25
+ it("returns before starting the asynchronous event worker", async () => {
26
+ let scheduled: (() => void) | undefined;
27
+ const schedule = vi.fn((task: () => void) => {
28
+ scheduled = task;
29
+ });
30
+ const worker = vi.fn(async () => {});
31
+ const onError = vi.fn();
32
+ const handler = createAckFirstEventHandler(worker, onError, schedule);
33
+
34
+ await expect(handler({ message: "test" })).resolves.toBeUndefined();
35
+ expect(schedule).toHaveBeenCalledOnce();
36
+ expect(worker).not.toHaveBeenCalled();
37
+
38
+ scheduled?.();
39
+ await vi.waitFor(() => expect(worker).toHaveBeenCalledWith({ message: "test" }));
40
+ expect(onError).not.toHaveBeenCalled();
41
+ });
42
+
43
+ it("reports detached worker failures without rejecting the SDK callback", async () => {
44
+ const error = new Error("worker failed");
45
+ const onError = vi.fn();
46
+ const handler = createAckFirstEventHandler(
47
+ async () => {
48
+ throw error;
49
+ },
50
+ onError,
51
+ (task) => task(),
52
+ );
53
+
54
+ await expect(handler({})).resolves.toBeUndefined();
55
+ await vi.waitFor(() => expect(onError).toHaveBeenCalledWith(error));
56
+ });
57
+ });
58
+
59
+ describe("FeishuMessageLedger", () => {
60
+ it("rejects an already accepted message after a process restart", async () => {
61
+ const first = await createLedger();
62
+ await first.load();
63
+
64
+ expect(await first.accept({
65
+ messageId: "om_001",
66
+ chatId: "oc_chat",
67
+ createTime: 100,
68
+ })).toBe("accepted");
69
+
70
+ const restarted = new FeishuMessageLedger(first.filePath, 5);
71
+ await restarted.load();
72
+
73
+ expect(await restarted.accept({
74
+ messageId: "om_001",
75
+ chatId: "oc_chat",
76
+ createTime: 100,
77
+ })).toBe("duplicate");
78
+ });
79
+
80
+ it("rejects a unique old event after restoring the chat high-water mark", async () => {
81
+ const first = await createLedger();
82
+ await first.load();
83
+
84
+ expect(await first.accept({
85
+ messageId: "om_new",
86
+ chatId: "oc_chat",
87
+ createTime: 200,
88
+ })).toBe("accepted");
89
+
90
+ const restarted = new FeishuMessageLedger(first.filePath, 5);
91
+ await restarted.load();
92
+
93
+ expect(await restarted.accept({
94
+ messageId: "om_old",
95
+ chatId: "oc_chat",
96
+ createTime: 100,
97
+ })).toBe("stale");
98
+ });
99
+
100
+ it("accepts distinct messages with the same create timestamp", async () => {
101
+ const ledger = await createLedger();
102
+ await ledger.load();
103
+
104
+ expect(await ledger.accept({
105
+ messageId: "om_001",
106
+ chatId: "oc_chat",
107
+ createTime: 100,
108
+ })).toBe("accepted");
109
+ expect(await ledger.accept({
110
+ messageId: "om_002",
111
+ chatId: "oc_chat",
112
+ createTime: 100,
113
+ })).toBe("accepted");
114
+ });
115
+
116
+ it("keeps only the configured number of recent message IDs", async () => {
117
+ const ledger = await createLedger(2);
118
+ await ledger.load();
119
+
120
+ await ledger.accept({ messageId: "om_001", chatId: "oc_chat", createTime: 100 });
121
+ await ledger.accept({ messageId: "om_002", chatId: "oc_chat", createTime: 200 });
122
+ await ledger.accept({ messageId: "om_003", chatId: "oc_chat", createTime: 300 });
123
+
124
+ const restarted = new FeishuMessageLedger(ledger.filePath, 2);
125
+ await restarted.load();
126
+
127
+ expect(await restarted.accept({
128
+ messageId: "om_001",
129
+ chatId: "oc_other",
130
+ createTime: 100,
131
+ })).toBe("accepted");
132
+ expect(await restarted.accept({
133
+ messageId: "om_003",
134
+ chatId: "oc_chat",
135
+ createTime: 300,
136
+ })).toBe("duplicate");
137
+ });
138
+ });