chatccc 0.2.223 → 0.2.224

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.
@@ -1,16 +1,16 @@
1
1
  import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
2
  import { mkdtemp, rm } from "node:fs/promises";
3
- import { homedir, tmpdir } from "node:os";
3
+ import { homedir, tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
5
 
6
6
  import type { PlatformAdapter } from "../platform-adapter.ts";
7
7
  import type { SessionInfo, ToolAdapter } from "../adapters/adapter-interface.ts";
8
8
 
9
9
  const mockStreamStates = new Map<string, { status: "running" | "done" | "stopped"; finalReply: string }>();
10
- const mockGetCodexUsageSummary = vi.hoisted(() => vi.fn());
11
- const mockGetCursorUsageSummary = vi.hoisted(() => vi.fn());
12
- const mockGetChatGptSubscriptionStatus = vi.hoisted(() => vi.fn());
13
- const mockReloadRuntimeConfig = vi.hoisted(() => vi.fn());
10
+ const mockGetCodexUsageSummary = vi.hoisted(() => vi.fn());
11
+ const mockGetCursorUsageSummary = vi.hoisted(() => vi.fn());
12
+ const mockGetChatGptSubscriptionStatus = vi.hoisted(() => vi.fn());
13
+ const mockReloadRuntimeConfig = vi.hoisted(() => vi.fn());
14
14
 
15
15
  vi.mock("../im-skills.ts", () => ({
16
16
  buildImSkillsPrompt: async () => "",
@@ -66,15 +66,15 @@ vi.mock("../cursor-usage.ts", () => ({
66
66
  getCursorUsageSummary: mockGetCursorUsageSummary,
67
67
  }));
68
68
 
69
- vi.mock("../chatgpt-subscription.ts", () => ({
70
- getChatGptSubscriptionStatus: mockGetChatGptSubscriptionStatus,
71
- }));
72
-
73
- vi.mock("../runtime-reload.ts", () => ({
74
- reloadRuntimeConfig: mockReloadRuntimeConfig,
75
- }));
76
-
77
- import { handleCommand } from "../orchestrator.ts";
69
+ vi.mock("../chatgpt-subscription.ts", () => ({
70
+ getChatGptSubscriptionStatus: mockGetChatGptSubscriptionStatus,
71
+ }));
72
+
73
+ vi.mock("../runtime-reload.ts", () => ({
74
+ reloadRuntimeConfig: mockReloadRuntimeConfig,
75
+ }));
76
+
77
+ import { handleCommand } from "../orchestrator.ts";
78
78
  import {
79
79
  _clearAdapterCacheForTest,
80
80
  _resetSessionRegistryFileForTest,
@@ -82,20 +82,21 @@ import {
82
82
  _setAdapterForToolForTest,
83
83
  _setSessionRegistryFileForTest,
84
84
  _setSessionToolsFileForTest,
85
- loadSessionRegistryForBinding,
86
- recordSessionRegistry,
87
- resetState,
88
- sessionInfoMap,
89
- getEffectiveFastModeForTool,
90
- } from "../session.ts";
91
- import {
92
- activePrompts,
93
- dequeueMessage,
94
- getChatsForSession,
95
- resetBindingState,
96
- } from "../session-chat-binding.ts";
97
- import { ABD_APPEND_PROMPT } from "../shared-prefix.ts";
98
- import { config } from "../config.ts";
85
+ loadSessionRegistryForBinding,
86
+ recordSessionRegistry,
87
+ resetState,
88
+ sessionInfoMap,
89
+ getEffectiveEffortForTool,
90
+ getEffectiveFastModeForTool,
91
+ } from "../session.ts";
92
+ import {
93
+ activePrompts,
94
+ dequeueMessage,
95
+ getChatsForSession,
96
+ resetBindingState,
97
+ } from "../session-chat-binding.ts";
98
+ import { ABD_APPEND_PROMPT } from "../shared-prefix.ts";
99
+ import { config } from "../config.ts";
99
100
 
100
101
  function mockPlatform(kind: "wechat" | "feishu" = "wechat"): PlatformAdapter {
101
102
  return {
@@ -142,23 +143,23 @@ describe("handleCommand WeChat processing ack", () => {
142
143
  tempDir = await mkdtemp(join(tmpdir(), "chatccc-orchestrator-"));
143
144
  _setSessionRegistryFileForTest(join(tempDir, "session-registry.json"));
144
145
  _setSessionToolsFileForTest(join(tempDir, "sessions.json"));
145
- resetState();
146
- resetBindingState();
147
- config.claude.defaultAgent = true;
148
- config.cursor.defaultAgent = false;
149
- config.codex.defaultAgent = false;
150
- config.codex.fastMode = false;
151
- config.ccc.enabled = true;
152
- config.ccc.defaultAgent = false;
153
- config.ccc.DEEPSEEK_API_KEY = "sk-test-ccc";
154
- config.ccc.DEEPSEEK_BASE_URL = "https://api.deepseek.com/v1";
155
- config.ccc.model = "deepseek-v4-pro";
156
- config.ccc.alternativeModel = "deepseek-v4-flash";
157
- mockStreamStates.clear();
158
- mockGetCodexUsageSummary.mockReset();
159
- mockGetCursorUsageSummary.mockReset();
160
- mockGetChatGptSubscriptionStatus.mockReset();
161
- mockReloadRuntimeConfig.mockReset();
146
+ resetState();
147
+ resetBindingState();
148
+ config.claude.defaultAgent = true;
149
+ config.cursor.defaultAgent = false;
150
+ config.codex.defaultAgent = false;
151
+ config.codex.fastMode = false;
152
+ config.ccc.enabled = true;
153
+ config.ccc.defaultAgent = false;
154
+ config.ccc.DEEPSEEK_API_KEY = "sk-test-ccc";
155
+ config.ccc.DEEPSEEK_BASE_URL = "https://api.deepseek.com/v1";
156
+ config.ccc.model = "deepseek-v4-pro";
157
+ config.ccc.alternativeModel = "deepseek-v4-flash";
158
+ mockStreamStates.clear();
159
+ mockGetCodexUsageSummary.mockReset();
160
+ mockGetCursorUsageSummary.mockReset();
161
+ mockGetChatGptSubscriptionStatus.mockReset();
162
+ mockReloadRuntimeConfig.mockReset();
162
163
  mockGetCodexUsageSummary.mockResolvedValue({
163
164
  fiveHour: { usedPercent: 0, remainingPercent: 100, resetAtEpochSeconds: null, resetAfterSeconds: null },
164
165
  weekly: { usedPercent: 0, remainingPercent: 100, resetAtEpochSeconds: null, resetAfterSeconds: null },
@@ -190,19 +191,19 @@ describe("handleCommand WeChat processing ack", () => {
190
191
  displayMessage: "You've hit your usage limit",
191
192
  autoBucketModels: ["default"],
192
193
  });
193
- mockGetChatGptSubscriptionStatus.mockResolvedValue({
194
- ok: false,
195
- code: "chrome_cdp_disabled",
196
- reason: "Chrome CDP guard is disabled in ChatCCC config.",
197
- chromeCdp: { enabled: false, port: 15166, status: "skipped" },
198
- });
199
- mockReloadRuntimeConfig.mockResolvedValue({
200
- configPath: "C:\\Users\\me\\.chatccc\\config.json",
201
- defaultAgent: "codex",
202
- reloadedAt: "2026-07-02T05:00:00.000Z",
203
- });
204
- _setAdapterForToolForTest("claude", mockAdapter());
205
- });
194
+ mockGetChatGptSubscriptionStatus.mockResolvedValue({
195
+ ok: false,
196
+ code: "chrome_cdp_disabled",
197
+ reason: "Chrome CDP guard is disabled in ChatCCC config.",
198
+ chromeCdp: { enabled: false, port: 15166, status: "skipped" },
199
+ });
200
+ mockReloadRuntimeConfig.mockResolvedValue({
201
+ configPath: "C:\\Users\\me\\.chatccc\\config.json",
202
+ defaultAgent: "codex",
203
+ reloadedAt: "2026-07-02T05:00:00.000Z",
204
+ });
205
+ _setAdapterForToolForTest("claude", mockAdapter());
206
+ });
206
207
 
207
208
  afterEach(async () => {
208
209
  resetState();
@@ -210,8 +211,8 @@ describe("handleCommand WeChat processing ack", () => {
210
211
  _clearAdapterCacheForTest();
211
212
  _resetSessionRegistryFileForTest();
212
213
  _resetSessionToolsFileForTest();
213
- vi.useRealTimers();
214
- vi.unstubAllGlobals();
214
+ vi.useRealTimers();
215
+ vi.unstubAllGlobals();
215
216
  await rm(tempDir, { recursive: true, force: true });
216
217
  });
217
218
 
@@ -268,12 +269,12 @@ describe("handleCommand WeChat processing ack", () => {
268
269
  _setAdapterForToolForTest("claude", {
269
270
  displayName: "Claude",
270
271
  sessionDescPrefix: "Claude Session:",
271
- createSession: vi.fn(async () => ({ sessionId: "sid-wechat" })),
272
- prompt,
273
- getSessionInfo: async (sessionId: string): Promise<SessionInfo> => ({
274
- sessionId,
275
- cwd: "F:\\repo",
276
- }),
272
+ createSession: vi.fn(async () => ({ sessionId: "sid-wechat" })),
273
+ prompt,
274
+ getSessionInfo: async (sessionId: string): Promise<SessionInfo> => ({
275
+ sessionId,
276
+ cwd: "F:\\repo",
277
+ }),
277
278
  closeSession: async () => {},
278
279
  });
279
280
  await recordSessionRegistry({
@@ -312,9 +313,233 @@ describe("handleCommand WeChat processing ack", () => {
312
313
  expect(platform.sendText).not.toHaveBeenCalledWith("wx-chat", "会话已停止。");
313
314
  });
314
315
 
315
- it("resumes the Feishu p2p session in place instead of creating a group", async () => {
316
- const platform = mockPlatform("feishu");
317
- const prompt = vi.fn(async function* (_sessionId: string, userText: string) {
316
+ it("resumes the Feishu p2p session in place instead of creating a group", async () => {
317
+ const platform = mockPlatform("feishu");
318
+ const prompt = vi.fn(async function* (_sessionId: string, userText: string) {
319
+ yield {
320
+ type: "assistant" as const,
321
+ blocks: [{ type: "text" as const, text: `收到: ${userText}` }],
322
+ };
323
+ });
324
+ _setAdapterForToolForTest("claude", {
325
+ displayName: "Claude",
326
+ sessionDescPrefix: "Claude Session:",
327
+ createSession: vi.fn(async () => ({ sessionId: "sid-feishu-new" })),
328
+ prompt,
329
+ getSessionInfo: async (sessionId: string): Promise<SessionInfo> => ({
330
+ sessionId,
331
+ cwd: homedir(),
332
+ }),
333
+ closeSession: async () => {},
334
+ });
335
+ await recordSessionRegistry({
336
+ chatId: "feishu-p2p",
337
+ sessionId: "sid-feishu-private",
338
+ tool: "claude",
339
+ chatType: "p2p",
340
+ chatName: "飞书私聊",
341
+ running: false,
342
+ });
343
+
344
+ await handleCommand(platform, "帮我看一下日志", "feishu-p2p", "ou-user", Date.now(), "p2p");
345
+
346
+ expect(platform.createGroup).not.toHaveBeenCalled();
347
+ expect(platform.updateChatInfo).not.toHaveBeenCalled();
348
+ expect(prompt).toHaveBeenCalledWith(
349
+ "sid-feishu-private",
350
+ expect.stringContaining("帮我看一下日志"),
351
+ homedir(),
352
+ expect.any(AbortSignal),
353
+ expect.any(Object),
354
+ );
355
+
356
+ const registry = await loadSessionRegistryForBinding();
357
+ expect(registry["feishu-p2p"]?.sessionId).toBe("sid-feishu-private");
358
+ });
359
+
360
+ it("sends the normal session state card in an established Feishu p2p chat", async () => {
361
+ const platform = mockPlatform("feishu");
362
+ _setAdapterForToolForTest("claude", mockAdapter("sid-feishu-state"));
363
+ await recordSessionRegistry({
364
+ chatId: "feishu-p2p-state",
365
+ sessionId: "sid-feishu-state",
366
+ tool: "claude",
367
+ chatType: "p2p",
368
+ chatName: "飞书私聊",
369
+ turnCount: 2,
370
+ running: false,
371
+ });
372
+
373
+ await handleCommand(platform, "/state", "feishu-p2p-state", "ou-user", Date.now(), "p2p");
374
+
375
+ expect(platform.getChatInfo).not.toHaveBeenCalled();
376
+ expect(platform.sendRawCard).toHaveBeenCalledTimes(1);
377
+ const cardText = vi.mocked(platform.sendRawCard).mock.calls[0][1];
378
+ expect(cardText).toContain("sid-feishu-state");
379
+ expect(cardText).toContain("Claude Code");
380
+ expect(cardText).toContain("2");
381
+ });
382
+
383
+ it("shows an explicit state card without creating an Agent when a Feishu p2p chat is not bound yet", async () => {
384
+ const platform = mockPlatform("feishu");
385
+ const adapter = mockAdapter("should-not-be-created");
386
+ _setAdapterForToolForTest("claude", adapter);
387
+
388
+ await handleCommand(platform, "/state", "feishu-p2p-empty", "ou-user", Date.now(), "p2p");
389
+
390
+ expect(adapter.createSession).not.toHaveBeenCalled();
391
+ expect(platform.sendRawCard).toHaveBeenCalledTimes(1);
392
+ const cardText = vi.mocked(platform.sendRawCard).mock.calls[0][1];
393
+ expect(cardText).toContain("未建立会话");
394
+ expect(cardText).toContain("Claude Code");
395
+ });
396
+
397
+ it("switches an idle Feishu p2p chat to a fresh session when the default Agent changes", async () => {
398
+ const platform = mockPlatform("feishu");
399
+ const oldPrompt = vi.fn(async function* () {
400
+ yield { type: "assistant" as const, blocks: [{ type: "text" as const, text: "old" }] };
401
+ });
402
+ _setAdapterForToolForTest("claude", {
403
+ ...mockAdapter("sid-old-claude"),
404
+ prompt: oldPrompt,
405
+ });
406
+
407
+ const createCursorSession = vi.fn(async () => ({ sessionId: "sid-new-cursor" }));
408
+ const cursorPrompt = vi.fn(async function* () {
409
+ yield { type: "assistant" as const, blocks: [{ type: "text" as const, text: "new" }] };
410
+ });
411
+ _setAdapterForToolForTest("cursor", {
412
+ ...mockAdapter("sid-new-cursor"),
413
+ displayName: "Cursor",
414
+ sessionDescPrefix: "Cursor Session:",
415
+ createSession: createCursorSession,
416
+ prompt: cursorPrompt,
417
+ getSessionInfo: async (sessionId: string): Promise<SessionInfo> => ({ sessionId, cwd: homedir() }),
418
+ });
419
+ await recordSessionRegistry({
420
+ chatId: "feishu-p2p",
421
+ sessionId: "sid-old-claude",
422
+ tool: "claude",
423
+ chatType: "p2p",
424
+ chatName: "飞书私聊",
425
+ running: false,
426
+ });
427
+
428
+ const originalCursorEnabled = config.cursor.enabled;
429
+ try {
430
+ config.cursor.enabled = true;
431
+ config.claude.defaultAgent = false;
432
+ config.cursor.defaultAgent = true;
433
+
434
+ await handleCommand(platform, "/state", "feishu-p2p", "ou-user", Date.now(), "p2p");
435
+ expect(createCursorSession).not.toHaveBeenCalled();
436
+ expect((await loadSessionRegistryForBinding())["feishu-p2p"]?.sessionId).toBe("sid-old-claude");
437
+
438
+ await handleCommand(platform, "使用新的默认 Agent", "feishu-p2p", "ou-user", Date.now(), "p2p");
439
+
440
+ expect(createCursorSession).toHaveBeenCalledWith(homedir(), expect.any(AbortSignal));
441
+ expect(oldPrompt).not.toHaveBeenCalled();
442
+ expect(cursorPrompt).toHaveBeenCalledWith(
443
+ "sid-new-cursor",
444
+ expect.stringContaining("使用新的默认 Agent"),
445
+ homedir(),
446
+ expect.any(AbortSignal),
447
+ expect.any(Object),
448
+ );
449
+ expect(platform.updateChatInfo).not.toHaveBeenCalled();
450
+ expect(platform.sendCard).toHaveBeenCalledWith(
451
+ "feishu-p2p",
452
+ "默认 Agent 已切换",
453
+ expect.stringContaining("Claude Code → Cursor"),
454
+ "green",
455
+ );
456
+
457
+ const registry = await loadSessionRegistryForBinding();
458
+ expect(registry["feishu-p2p"]).toMatchObject({
459
+ sessionId: "sid-new-cursor",
460
+ tool: "cursor",
461
+ chatType: "p2p",
462
+ turnCount: 1,
463
+ });
464
+ } finally {
465
+ config.cursor.enabled = originalCursorEnabled;
466
+ }
467
+ });
468
+
469
+ it("waits for a running Feishu p2p Agent before switching the queued message to the new default", async () => {
470
+ const platform = mockPlatform("feishu");
471
+ const createCursorSession = vi.fn(async () => ({ sessionId: "sid-cursor-after-wait" }));
472
+ const cursorPrompt = vi.fn(async function* () {
473
+ yield { type: "assistant" as const, blocks: [{ type: "text" as const, text: "new" }] };
474
+ });
475
+ _setAdapterForToolForTest("cursor", {
476
+ ...mockAdapter("sid-cursor-after-wait"),
477
+ displayName: "Cursor",
478
+ sessionDescPrefix: "Cursor Session:",
479
+ createSession: createCursorSession,
480
+ prompt: cursorPrompt,
481
+ getSessionInfo: async (sessionId: string): Promise<SessionInfo> => ({ sessionId, cwd: homedir() }),
482
+ });
483
+ await recordSessionRegistry({
484
+ chatId: "feishu-p2p-wait",
485
+ sessionId: "sid-running-claude",
486
+ tool: "claude",
487
+ chatType: "p2p",
488
+ chatName: "飞书私聊",
489
+ running: true,
490
+ });
491
+ activePrompts.set("sid-running-claude", {
492
+ controller: new AbortController(),
493
+ stopped: false,
494
+ startTime: Date.now(),
495
+ });
496
+
497
+ const originalCursorEnabled = config.cursor.enabled;
498
+ try {
499
+ config.cursor.enabled = true;
500
+ config.claude.defaultAgent = false;
501
+ config.cursor.defaultAgent = true;
502
+
503
+ await handleCommand(platform, "等当前回复完成后处理", "feishu-p2p-wait", "ou-user", Date.now(), "p2p");
504
+
505
+ expect(createCursorSession).not.toHaveBeenCalled();
506
+ const queued = dequeueMessage("sid-running-claude");
507
+ expect(queued?.text).toContain("等当前回复完成后处理");
508
+ expect(platform.sendCard).toHaveBeenCalledWith(
509
+ "feishu-p2p-wait",
510
+ "Agent 切换等待中",
511
+ expect.stringContaining("完成后会切换到 Cursor"),
512
+ "blue",
513
+ );
514
+
515
+ activePrompts.delete("sid-running-claude");
516
+ await handleCommand(
517
+ platform,
518
+ queued!.text,
519
+ queued!.chatId,
520
+ queued!.openId,
521
+ queued!.msgTimestamp,
522
+ queued!.chatType,
523
+ queued!.traceId,
524
+ );
525
+
526
+ expect(createCursorSession).toHaveBeenCalledTimes(1);
527
+ expect(cursorPrompt).toHaveBeenCalledWith(
528
+ "sid-cursor-after-wait",
529
+ expect.stringContaining("等当前回复完成后处理"),
530
+ homedir(),
531
+ expect.any(AbortSignal),
532
+ expect.any(Object),
533
+ );
534
+ } finally {
535
+ config.cursor.enabled = originalCursorEnabled;
536
+ }
537
+ });
538
+
539
+ it("creates the first Feishu p2p session in the OS user directory and sends the first prompt in place", async () => {
540
+ const platform = mockPlatform("feishu");
541
+ const createSession = vi.fn(async () => ({ sessionId: "sid-feishu-private" }));
542
+ const prompt = vi.fn(async function* (_sessionId: string, userText: string) {
318
543
  yield {
319
544
  type: "assistant" as const,
320
545
  blocks: [{ type: "text" as const, text: `收到: ${userText}` }],
@@ -323,595 +548,403 @@ describe("handleCommand WeChat processing ack", () => {
323
548
  _setAdapterForToolForTest("claude", {
324
549
  displayName: "Claude",
325
550
  sessionDescPrefix: "Claude Session:",
326
- createSession: vi.fn(async () => ({ sessionId: "sid-feishu-new" })),
327
- prompt,
328
- getSessionInfo: async (sessionId: string): Promise<SessionInfo> => ({
329
- sessionId,
330
- cwd: homedir(),
331
- }),
551
+ createSession,
552
+ prompt,
553
+ getSessionInfo: async (sessionId: string): Promise<SessionInfo> => ({
554
+ sessionId,
555
+ cwd: homedir(),
556
+ }),
332
557
  closeSession: async () => {},
333
558
  });
334
- await recordSessionRegistry({
335
- chatId: "feishu-p2p",
336
- sessionId: "sid-feishu-private",
337
- tool: "claude",
338
- chatType: "p2p",
339
- chatName: "飞书私聊",
340
- running: false,
341
- });
342
-
343
- await handleCommand(platform, "帮我看一下日志", "feishu-p2p", "ou-user", Date.now(), "p2p");
344
-
345
- expect(platform.createGroup).not.toHaveBeenCalled();
346
- expect(platform.updateChatInfo).not.toHaveBeenCalled();
347
- expect(prompt).toHaveBeenCalledWith(
348
- "sid-feishu-private",
349
- expect.stringContaining("帮我看一下日志"),
350
- homedir(),
351
- expect.any(AbortSignal),
559
+
560
+ await handleCommand(platform, "帮我看一下日志", "feishu-p2p", "ou-user", Date.now(), "p2p");
561
+
562
+ expect(createSession).toHaveBeenCalledWith(homedir(), expect.any(AbortSignal));
563
+ expect(platform.createGroup).not.toHaveBeenCalled();
564
+ expect(platform.updateChatInfo).not.toHaveBeenCalled();
565
+ expect(prompt).toHaveBeenCalledWith(
566
+ "sid-feishu-private",
567
+ expect.stringContaining("帮我看一下日志"),
568
+ homedir(),
569
+ expect.any(AbortSignal),
570
+ expect.any(Object),
571
+ );
572
+
573
+ const registry = await loadSessionRegistryForBinding();
574
+ expect(registry["feishu-p2p"]?.sessionId).toBe("sid-feishu-private");
575
+ expect(registry["feishu-p2p"]?.tool).toBe("claude");
576
+ expect(registry["feishu-p2p"]?.chatType).toBe("p2p");
577
+ });
578
+
579
+ it("replaces an unmarked legacy Feishu p2p binding with a home-directory session", async () => {
580
+ const platform = mockPlatform("feishu");
581
+ const createSession = vi.fn(async () => ({ sessionId: "sid-feishu-migrated" }));
582
+ const prompt = vi.fn(async function* () {
583
+ yield {
584
+ type: "assistant" as const,
585
+ blocks: [{ type: "text" as const, text: "done" }],
586
+ };
587
+ });
588
+ _setAdapterForToolForTest("claude", {
589
+ displayName: "Claude",
590
+ sessionDescPrefix: "Claude Session:",
591
+ createSession,
592
+ prompt,
593
+ getSessionInfo: async (sessionId: string): Promise<SessionInfo> => ({
594
+ sessionId,
595
+ cwd: homedir(),
596
+ }),
597
+ closeSession: async () => {},
598
+ });
599
+ await recordSessionRegistry({
600
+ chatId: "feishu-p2p",
601
+ sessionId: "sid-feishu-legacy",
602
+ tool: "claude",
603
+ chatName: "旧私聊绑定",
604
+ running: false,
605
+ });
606
+
607
+ await handleCommand(platform, "继续", "feishu-p2p", "ou-user", Date.now(), "p2p");
608
+
609
+ expect(createSession).toHaveBeenCalledWith(homedir(), expect.any(AbortSignal));
610
+ expect(prompt).toHaveBeenCalledWith(
611
+ "sid-feishu-migrated",
612
+ expect.stringContaining("继续"),
613
+ homedir(),
614
+ expect.any(AbortSignal),
352
615
  expect.any(Object),
353
616
  );
354
-
355
- const registry = await loadSessionRegistryForBinding();
356
- expect(registry["feishu-p2p"]?.sessionId).toBe("sid-feishu-private");
357
- });
358
-
359
- it("sends the normal session state card in an established Feishu p2p chat", async () => {
360
- const platform = mockPlatform("feishu");
361
- _setAdapterForToolForTest("claude", mockAdapter("sid-feishu-state"));
362
- await recordSessionRegistry({
363
- chatId: "feishu-p2p-state",
364
- sessionId: "sid-feishu-state",
365
- tool: "claude",
366
- chatType: "p2p",
367
- chatName: "飞书私聊",
368
- turnCount: 2,
369
- running: false,
370
- });
371
-
372
- await handleCommand(platform, "/state", "feishu-p2p-state", "ou-user", Date.now(), "p2p");
373
-
374
- expect(platform.getChatInfo).not.toHaveBeenCalled();
375
- expect(platform.sendRawCard).toHaveBeenCalledTimes(1);
376
- const cardText = vi.mocked(platform.sendRawCard).mock.calls[0][1];
377
- expect(cardText).toContain("sid-feishu-state");
378
- expect(cardText).toContain("Claude Code");
379
- expect(cardText).toContain("2");
380
- });
381
-
382
- it("shows an explicit state card without creating an Agent when a Feishu p2p chat is not bound yet", async () => {
383
- const platform = mockPlatform("feishu");
384
- const adapter = mockAdapter("should-not-be-created");
385
- _setAdapterForToolForTest("claude", adapter);
386
-
387
- await handleCommand(platform, "/state", "feishu-p2p-empty", "ou-user", Date.now(), "p2p");
388
-
389
- expect(adapter.createSession).not.toHaveBeenCalled();
390
- expect(platform.sendRawCard).toHaveBeenCalledTimes(1);
391
- const cardText = vi.mocked(platform.sendRawCard).mock.calls[0][1];
392
- expect(cardText).toContain("未建立会话");
393
- expect(cardText).toContain("Claude Code");
394
- });
395
-
396
- it("switches an idle Feishu p2p chat to a fresh session when the default Agent changes", async () => {
397
- const platform = mockPlatform("feishu");
398
- const oldPrompt = vi.fn(async function* () {
399
- yield { type: "assistant" as const, blocks: [{ type: "text" as const, text: "old" }] };
400
- });
401
- _setAdapterForToolForTest("claude", {
402
- ...mockAdapter("sid-old-claude"),
403
- prompt: oldPrompt,
404
- });
405
-
406
- const createCursorSession = vi.fn(async () => ({ sessionId: "sid-new-cursor" }));
407
- const cursorPrompt = vi.fn(async function* () {
408
- yield { type: "assistant" as const, blocks: [{ type: "text" as const, text: "new" }] };
409
- });
410
- _setAdapterForToolForTest("cursor", {
411
- ...mockAdapter("sid-new-cursor"),
412
- displayName: "Cursor",
413
- sessionDescPrefix: "Cursor Session:",
414
- createSession: createCursorSession,
415
- prompt: cursorPrompt,
416
- getSessionInfo: async (sessionId: string): Promise<SessionInfo> => ({ sessionId, cwd: homedir() }),
417
- });
418
- await recordSessionRegistry({
419
- chatId: "feishu-p2p",
420
- sessionId: "sid-old-claude",
421
- tool: "claude",
422
- chatType: "p2p",
423
- chatName: "飞书私聊",
424
- running: false,
425
- });
426
-
427
- const originalCursorEnabled = config.cursor.enabled;
428
- try {
429
- config.cursor.enabled = true;
430
- config.claude.defaultAgent = false;
431
- config.cursor.defaultAgent = true;
432
-
433
- await handleCommand(platform, "/state", "feishu-p2p", "ou-user", Date.now(), "p2p");
434
- expect(createCursorSession).not.toHaveBeenCalled();
435
- expect((await loadSessionRegistryForBinding())["feishu-p2p"]?.sessionId).toBe("sid-old-claude");
436
-
437
- await handleCommand(platform, "使用新的默认 Agent", "feishu-p2p", "ou-user", Date.now(), "p2p");
438
-
439
- expect(createCursorSession).toHaveBeenCalledWith(homedir(), expect.any(AbortSignal));
440
- expect(oldPrompt).not.toHaveBeenCalled();
441
- expect(cursorPrompt).toHaveBeenCalledWith(
442
- "sid-new-cursor",
443
- expect.stringContaining("使用新的默认 Agent"),
444
- homedir(),
445
- expect.any(AbortSignal),
446
- expect.any(Object),
447
- );
448
- expect(platform.updateChatInfo).not.toHaveBeenCalled();
449
- expect(platform.sendCard).toHaveBeenCalledWith(
450
- "feishu-p2p",
451
- "默认 Agent 已切换",
452
- expect.stringContaining("Claude Code → Cursor"),
453
- "green",
454
- );
455
-
456
- const registry = await loadSessionRegistryForBinding();
457
- expect(registry["feishu-p2p"]).toMatchObject({
458
- sessionId: "sid-new-cursor",
459
- tool: "cursor",
460
- chatType: "p2p",
461
- turnCount: 1,
462
- });
463
- } finally {
464
- config.cursor.enabled = originalCursorEnabled;
465
- }
466
- });
467
-
468
- it("waits for a running Feishu p2p Agent before switching the queued message to the new default", async () => {
469
- const platform = mockPlatform("feishu");
470
- const createCursorSession = vi.fn(async () => ({ sessionId: "sid-cursor-after-wait" }));
471
- const cursorPrompt = vi.fn(async function* () {
472
- yield { type: "assistant" as const, blocks: [{ type: "text" as const, text: "new" }] };
473
- });
474
- _setAdapterForToolForTest("cursor", {
475
- ...mockAdapter("sid-cursor-after-wait"),
476
- displayName: "Cursor",
477
- sessionDescPrefix: "Cursor Session:",
478
- createSession: createCursorSession,
479
- prompt: cursorPrompt,
480
- getSessionInfo: async (sessionId: string): Promise<SessionInfo> => ({ sessionId, cwd: homedir() }),
481
- });
482
- await recordSessionRegistry({
483
- chatId: "feishu-p2p-wait",
484
- sessionId: "sid-running-claude",
485
- tool: "claude",
486
- chatType: "p2p",
487
- chatName: "飞书私聊",
488
- running: true,
489
- });
490
- activePrompts.set("sid-running-claude", {
491
- controller: new AbortController(),
492
- stopped: false,
493
- startTime: Date.now(),
494
- });
495
-
496
- const originalCursorEnabled = config.cursor.enabled;
497
- try {
498
- config.cursor.enabled = true;
499
- config.claude.defaultAgent = false;
500
- config.cursor.defaultAgent = true;
501
-
502
- await handleCommand(platform, "等当前回复完成后处理", "feishu-p2p-wait", "ou-user", Date.now(), "p2p");
503
-
504
- expect(createCursorSession).not.toHaveBeenCalled();
505
- const queued = dequeueMessage("sid-running-claude");
506
- expect(queued?.text).toContain("等当前回复完成后处理");
507
- expect(platform.sendCard).toHaveBeenCalledWith(
508
- "feishu-p2p-wait",
509
- "Agent 切换等待中",
510
- expect.stringContaining("完成后会切换到 Cursor"),
511
- "blue",
512
- );
513
-
514
- activePrompts.delete("sid-running-claude");
515
- await handleCommand(
516
- platform,
517
- queued!.text,
518
- queued!.chatId,
519
- queued!.openId,
520
- queued!.msgTimestamp,
521
- queued!.chatType,
522
- queued!.traceId,
523
- );
524
-
525
- expect(createCursorSession).toHaveBeenCalledTimes(1);
526
- expect(cursorPrompt).toHaveBeenCalledWith(
527
- "sid-cursor-after-wait",
528
- expect.stringContaining("等当前回复完成后处理"),
529
- homedir(),
530
- expect.any(AbortSignal),
531
- expect.any(Object),
532
- );
533
- } finally {
534
- config.cursor.enabled = originalCursorEnabled;
535
- }
536
- });
537
-
538
- it("creates the first Feishu p2p session in the OS user directory and sends the first prompt in place", async () => {
539
- const platform = mockPlatform("feishu");
540
- const createSession = vi.fn(async () => ({ sessionId: "sid-feishu-private" }));
541
- const prompt = vi.fn(async function* (_sessionId: string, userText: string) {
542
- yield {
543
- type: "assistant" as const,
544
- blocks: [{ type: "text" as const, text: `收到: ${userText}` }],
545
- };
546
- });
547
- _setAdapterForToolForTest("claude", {
548
- displayName: "Claude",
549
- sessionDescPrefix: "Claude Session:",
550
- createSession,
551
- prompt,
552
- getSessionInfo: async (sessionId: string): Promise<SessionInfo> => ({
553
- sessionId,
554
- cwd: homedir(),
555
- }),
556
- closeSession: async () => {},
557
- });
558
-
559
- await handleCommand(platform, "帮我看一下日志", "feishu-p2p", "ou-user", Date.now(), "p2p");
560
-
561
- expect(createSession).toHaveBeenCalledWith(homedir(), expect.any(AbortSignal));
562
- expect(platform.createGroup).not.toHaveBeenCalled();
563
- expect(platform.updateChatInfo).not.toHaveBeenCalled();
564
- expect(prompt).toHaveBeenCalledWith(
565
- "sid-feishu-private",
566
- expect.stringContaining("帮我看一下日志"),
567
- homedir(),
568
- expect.any(AbortSignal),
569
- expect.any(Object),
570
- );
571
-
572
- const registry = await loadSessionRegistryForBinding();
573
- expect(registry["feishu-p2p"]?.sessionId).toBe("sid-feishu-private");
574
- expect(registry["feishu-p2p"]?.tool).toBe("claude");
575
- expect(registry["feishu-p2p"]?.chatType).toBe("p2p");
576
- });
577
-
578
- it("replaces an unmarked legacy Feishu p2p binding with a home-directory session", async () => {
579
- const platform = mockPlatform("feishu");
580
- const createSession = vi.fn(async () => ({ sessionId: "sid-feishu-migrated" }));
581
- const prompt = vi.fn(async function* () {
582
- yield {
583
- type: "assistant" as const,
584
- blocks: [{ type: "text" as const, text: "done" }],
585
- };
586
- });
587
- _setAdapterForToolForTest("claude", {
588
- displayName: "Claude",
589
- sessionDescPrefix: "Claude Session:",
590
- createSession,
591
- prompt,
592
- getSessionInfo: async (sessionId: string): Promise<SessionInfo> => ({
593
- sessionId,
594
- cwd: homedir(),
595
- }),
596
- closeSession: async () => {},
597
- });
598
- await recordSessionRegistry({
599
- chatId: "feishu-p2p",
600
- sessionId: "sid-feishu-legacy",
601
- tool: "claude",
602
- chatName: "旧私聊绑定",
603
- running: false,
604
- });
605
-
606
- await handleCommand(platform, "继续", "feishu-p2p", "ou-user", Date.now(), "p2p");
607
-
608
- expect(createSession).toHaveBeenCalledWith(homedir(), expect.any(AbortSignal));
609
- expect(prompt).toHaveBeenCalledWith(
610
- "sid-feishu-migrated",
611
- expect.stringContaining("继续"),
612
- homedir(),
613
- expect.any(AbortSignal),
614
- expect.any(Object),
615
- );
616
- expect(platform.createGroup).not.toHaveBeenCalled();
617
- const registry = await loadSessionRegistryForBinding();
618
- expect(registry["feishu-p2p"]?.sessionId).toBe("sid-feishu-migrated");
619
- expect(registry["feishu-p2p"]?.chatType).toBe("p2p");
620
- });
621
-
622
- it("creates a Feishu p2p session for /abd and sends the transformed prompt without creating a group", async () => {
623
- const platform = mockPlatform("feishu");
624
- const createSession = vi.fn(async () => ({ sessionId: "sid-feishu-abd" }));
625
- const prompt = vi.fn(async function* (_sessionId: string, userText: string) {
617
+ expect(platform.createGroup).not.toHaveBeenCalled();
618
+ const registry = await loadSessionRegistryForBinding();
619
+ expect(registry["feishu-p2p"]?.sessionId).toBe("sid-feishu-migrated");
620
+ expect(registry["feishu-p2p"]?.chatType).toBe("p2p");
621
+ });
622
+
623
+ it("creates a Feishu p2p session for /abd and sends the transformed prompt without creating a group", async () => {
624
+ const platform = mockPlatform("feishu");
625
+ const createSession = vi.fn(async () => ({ sessionId: "sid-feishu-abd" }));
626
+ const prompt = vi.fn(async function* (_sessionId: string, userText: string) {
626
627
  yield {
627
628
  type: "assistant" as const,
628
629
  blocks: [{ type: "text" as const, text: "done" }],
629
630
  };
630
631
  });
631
632
  _setAdapterForToolForTest("claude", {
632
- displayName: "Claude",
633
- sessionDescPrefix: "Claude Session:",
634
- createSession,
633
+ displayName: "Claude",
634
+ sessionDescPrefix: "Claude Session:",
635
+ createSession,
635
636
  prompt,
636
637
  getSessionInfo: async (sessionId: string): Promise<SessionInfo> => ({
637
638
  sessionId,
638
- cwd: homedir(),
639
+ cwd: homedir(),
639
640
  }),
640
641
  closeSession: async () => {},
641
642
  });
642
-
643
- await handleCommand(platform, "/abd帮我看一下日志", "feishu-p2p", "ou-user", Date.now(), "p2p");
644
-
645
- expect(createSession).toHaveBeenCalledWith(homedir(), expect.any(AbortSignal));
646
- expect(platform.createGroup).not.toHaveBeenCalled();
647
- expect(platform.updateChatInfo).not.toHaveBeenCalled();
648
- const userText = prompt.mock.calls[0][1];
649
- expect(userText).toContain(`[User message]\n帮我看一下日志\n\n---\n${ABD_APPEND_PROMPT}\n[/User message]`);
650
- expect(userText).not.toContain("/abd");
651
- });
652
-
653
- it("keeps the Feishu p2p binding when handling commands", async () => {
654
- const platform = mockPlatform("feishu");
655
- await recordSessionRegistry({
656
- chatId: "feishu-p2p",
657
- sessionId: "sid-feishu-private",
658
- tool: "claude",
659
- chatType: "p2p",
660
- chatName: "飞书私聊",
661
- running: false,
662
- });
663
-
664
- await handleCommand(platform, "/model", "feishu-p2p", "ou-user", Date.now(), "p2p");
665
-
666
- expect(platform.createGroup).not.toHaveBeenCalled();
667
- expect(platform.sendRawCard).toHaveBeenCalled();
668
- const registry = await loadSessionRegistryForBinding();
669
- expect(registry["feishu-p2p"]?.sessionId).toBe("sid-feishu-private");
670
- });
671
-
672
- it("queries and switches Fast mode for the current Codex session", async () => {
673
- const platform = mockPlatform("feishu");
674
- await recordSessionRegistry({
675
- chatId: "feishu-codex",
676
- sessionId: "sid-codex-fast",
677
- tool: "codex",
678
- chatType: "p2p",
679
- chatName: "Codex",
680
- running: false,
681
- });
682
-
683
- await handleCommand(platform, "/fast", "feishu-codex", "ou-user", Date.now(), "p2p");
684
- let card = JSON.parse(
685
- vi.mocked(platform.sendRawCard).mock.calls.at(-1)?.[1] ?? "{}",
686
- ) as { elements?: Array<{ tag: string; text?: { content: string } }> };
687
- expect(card.elements?.find((element) => element.tag === "div")?.text?.content).toContain("OFF");
688
-
689
- await handleCommand(platform, "/fast on", "feishu-codex", "ou-user", Date.now(), "p2p");
690
- expect(getEffectiveFastModeForTool("codex", "sid-codex-fast")).toBe(true);
691
- expect(platform.setChatAvatar).toHaveBeenLastCalledWith(
692
- "feishu-codex",
693
- "codex",
694
- "idle",
695
- { fastMode: true },
696
- );
697
-
698
- await handleCommand(platform, "/fast off", "feishu-codex", "ou-user", Date.now(), "p2p");
699
- expect(getEffectiveFastModeForTool("codex", "sid-codex-fast")).toBe(false);
700
- expect(platform.setChatAvatar).toHaveBeenLastCalledWith(
701
- "feishu-codex",
702
- "codex",
703
- "idle",
704
- { fastMode: false },
705
- );
706
- card = JSON.parse(
707
- vi.mocked(platform.sendRawCard).mock.calls.at(-1)?.[1] ?? "{}",
708
- ) as { elements?: Array<{ tag: string; text?: { content: string } }> };
709
- expect(card.elements?.find((element) => element.tag === "div")?.text?.content).toContain("OFF");
710
- });
711
-
712
- it("uses a text fallback for Fast mode commands on WeChat", async () => {
713
- const platform = mockPlatform("wechat");
714
- await recordSessionRegistry({
715
- chatId: "wechat-codex",
716
- sessionId: "sid-wechat-codex-fast",
717
- tool: "codex",
718
- chatType: "p2p",
719
- chatName: "Codex",
720
- running: false,
721
- });
722
-
723
- await handleCommand(platform, "/fast on", "wechat-codex", "wx-user", Date.now(), "p2p");
724
-
725
- expect(getEffectiveFastModeForTool("codex", "sid-wechat-codex-fast")).toBe(true);
726
- expect(platform.sendText).toHaveBeenCalledWith(
727
- "wechat-codex",
728
- expect.stringContaining("ON (Fast)"),
729
- );
730
- expect(platform.sendRawCard).not.toHaveBeenCalled();
731
- });
732
-
733
- it("keeps the Feishu p2p session bound when /new creates a separate group", async () => {
734
- const platform = mockPlatform("feishu");
735
- const createSession = vi.fn(async () => ({ sessionId: "sid-feishu-group" }));
736
- _setAdapterForToolForTest("claude", {
737
- ...mockAdapter("sid-feishu-group"),
738
- createSession,
739
- });
740
- await recordSessionRegistry({
741
- chatId: "feishu-p2p",
742
- sessionId: "sid-feishu-private",
743
- tool: "claude",
744
- chatType: "p2p",
745
- chatName: "飞书私聊",
746
- running: false,
747
- });
748
-
749
- await handleCommand(platform, "/new", "feishu-p2p", "ou-user", Date.now(), "p2p");
750
-
751
- expect(platform.createGroup).toHaveBeenCalledWith(expect.any(String), ["ou-user"]);
752
- const registry = await loadSessionRegistryForBinding();
753
- expect(registry["feishu-p2p"]?.sessionId).toBe("sid-feishu-private");
754
- expect(registry["feishu-group"]?.sessionId).toBe("sid-feishu-group");
755
- });
756
-
757
- it("resets a Feishu p2p session in place with /newh and forces the OS user directory", async () => {
758
- const platform = mockPlatform("feishu");
759
- const createSession = vi.fn(async () => ({ sessionId: "sid-feishu-private-reset" }));
760
- _setAdapterForToolForTest("claude", {
761
- ...mockAdapter("sid-feishu-private-reset"),
762
- createSession,
763
- getSessionInfo: async (sessionId: string): Promise<SessionInfo> => ({
764
- sessionId,
765
- cwd: "F:\\some-project",
766
- }),
767
- });
768
- await recordSessionRegistry({
769
- chatId: "feishu-p2p",
770
- sessionId: "sid-feishu-private",
771
- tool: "claude",
772
- chatType: "p2p",
773
- chatName: "飞书私聊",
774
- running: false,
775
- });
776
-
777
- await handleCommand(platform, "/newh", "feishu-p2p", "ou-user", Date.now(), "p2p");
778
-
779
- expect(createSession).toHaveBeenCalledWith(homedir(), expect.any(AbortSignal));
780
- expect(platform.createGroup).not.toHaveBeenCalled();
781
- expect(platform.updateChatInfo).not.toHaveBeenCalled();
782
- const registry = await loadSessionRegistryForBinding();
783
- expect(registry["feishu-p2p"]?.sessionId).toBe("sid-feishu-private-reset");
784
- expect(platform.sendCard).toHaveBeenCalledWith(
785
- "feishu-p2p",
786
- "Claude Code Session Reset",
787
- expect.stringContaining(`${homedir()}\`(飞书私聊固定使用系统用户目录)`),
788
- "green",
789
- );
790
- });
791
-
792
- it("does not allow /session to replace the dedicated Feishu p2p session", async () => {
793
- const platform = mockPlatform("feishu");
794
- await recordSessionRegistry({
795
- chatId: "feishu-p2p",
796
- sessionId: "sid-feishu-private",
797
- tool: "claude",
798
- chatType: "p2p",
799
- chatName: "飞书私聊",
800
- running: false,
801
- });
802
-
803
- await handleCommand(platform, "/session 1", "feishu-p2p", "ou-user", Date.now(), "p2p");
804
-
805
- expect(platform.sendCard).toHaveBeenCalledWith(
806
- "feishu-p2p",
807
- "/session",
808
- expect.stringContaining("下一条普通消息时跟随默认 Agent"),
809
- "yellow",
810
- );
811
- expect(platform.updateChatInfo).not.toHaveBeenCalled();
812
- const registry = await loadSessionRegistryForBinding();
813
- expect(registry["feishu-p2p"]?.sessionId).toBe("sid-feishu-private");
814
- });
815
-
816
- it("shows Claude effort switch card in an active Feishu session", async () => {
817
- const platform = mockPlatform("feishu");
818
- vi.mocked(platform.getChatInfo).mockResolvedValue({ name: "claude-session", description: "Claude Session: sid-claude-effort" });
819
- vi.mocked(platform.extractSessionInfo).mockReturnValue({ sessionId: "sid-claude-effort", tool: "claude" });
820
- await recordSessionRegistry({
821
- chatId: "feishu-chat",
822
- sessionId: "sid-claude-effort",
823
- tool: "claude",
824
- chatName: "claude-session",
825
- running: false,
826
- });
827
- sessionInfoMap.set("feishu-chat", {
828
- sessionId: "sid-claude-effort",
829
- tool: "claude",
830
- turnCount: 0,
831
- lastContextTokens: 0,
832
- startTime: Date.now(),
833
- });
834
-
835
- await handleCommand(platform, "/effort", "feishu-chat", "ou-user", Date.now(), "group");
836
-
837
- expect(platform.sendRawCard).toHaveBeenCalled();
838
- const card = JSON.parse(vi.mocked(platform.sendRawCard).mock.calls[0][1]);
839
- const raw = JSON.stringify(card);
840
- expect(raw).toContain("/effort low");
841
- expect(raw).toContain("/effort xhigh");
842
- expect(raw).toContain("/effort max");
843
- });
844
-
845
- it("switches Codex effort for the current session and reflects it in /state", async () => {
846
- const platform = mockPlatform("feishu");
847
- vi.mocked(platform.getChatInfo).mockResolvedValue({ name: "codex-session", description: "Codex Session: sid-codex-effort" });
848
- vi.mocked(platform.extractSessionInfo).mockReturnValue({ sessionId: "sid-codex-effort", tool: "codex" });
849
- _setAdapterForToolForTest("codex", mockAdapter("sid-codex-effort"));
850
- await recordSessionRegistry({
851
- chatId: "codex-chat",
852
- sessionId: "sid-codex-effort",
853
- tool: "codex",
854
- chatName: "codex-session",
855
- running: false,
856
- });
857
- sessionInfoMap.set("codex-chat", {
858
- sessionId: "sid-codex-effort",
859
- tool: "codex",
860
- turnCount: 0,
861
- lastContextTokens: 0,
862
- startTime: Date.now(),
863
- });
864
-
865
- await handleCommand(platform, "/effort xhigh", "codex-chat", "ou-user", Date.now(), "group");
866
- expect(platform.sendCard).toHaveBeenCalledWith(
867
- "codex-chat",
868
- "Effort 切换",
869
- expect.stringContaining("xhigh"),
870
- "green",
871
- );
872
-
873
- vi.mocked(platform.sendCard).mockClear();
874
- vi.mocked(platform.sendRawCard).mockClear();
875
- await handleCommand(platform, "/state", "codex-chat", "ou-user", Date.now() + 1, "group");
876
-
877
- expect(platform.sendRawCard).toHaveBeenCalled();
878
- const card = JSON.parse(vi.mocked(platform.sendRawCard).mock.calls[0][1]);
879
- expect(JSON.stringify(card)).toContain("xhigh");
880
- expect(getChatsForSession("sid-codex-effort")).toContain("codex-chat");
881
- });
882
-
883
- it("rejects /effort in Cursor sessions", async () => {
884
- const platform = mockPlatform("feishu");
885
- vi.mocked(platform.getChatInfo).mockResolvedValue({ name: "cursor-session", description: "Cursor Session: sid-cursor-effort" });
886
- vi.mocked(platform.extractSessionInfo).mockReturnValue({ sessionId: "sid-cursor-effort", tool: "cursor" });
887
- _setAdapterForToolForTest("cursor", mockAdapter("sid-cursor-effort"));
888
- await recordSessionRegistry({
889
- chatId: "cursor-chat",
890
- sessionId: "sid-cursor-effort",
891
- tool: "cursor",
892
- chatName: "cursor-session",
893
- running: false,
894
- });
895
- sessionInfoMap.set("cursor-chat", {
896
- sessionId: "sid-cursor-effort",
897
- tool: "cursor",
898
- turnCount: 0,
899
- lastContextTokens: 0,
900
- startTime: Date.now(),
901
- });
902
-
903
- await handleCommand(platform, "/effort high", "cursor-chat", "ou-user", Date.now(), "group");
904
-
905
- expect(platform.sendCard).toHaveBeenCalledWith(
906
- "cursor-chat",
907
- "Effort 切换",
908
- expect.stringContaining("不支持 effort"),
909
- "red",
910
- );
911
- });
912
-
913
- it("handles /usage without creating a new Feishu group", async () => {
914
- const platform = mockPlatform("feishu");
643
+
644
+ await handleCommand(platform, "/abd帮我看一下日志", "feishu-p2p", "ou-user", Date.now(), "p2p");
645
+
646
+ expect(createSession).toHaveBeenCalledWith(homedir(), expect.any(AbortSignal));
647
+ expect(platform.createGroup).not.toHaveBeenCalled();
648
+ expect(platform.updateChatInfo).not.toHaveBeenCalled();
649
+ const userText = prompt.mock.calls[0][1];
650
+ expect(userText).toContain(`[User message]\n帮我看一下日志\n\n---\n${ABD_APPEND_PROMPT}\n[/User message]`);
651
+ expect(userText).not.toContain("/abd");
652
+ });
653
+
654
+ it("keeps the Feishu p2p binding when handling commands", async () => {
655
+ const platform = mockPlatform("feishu");
656
+ await recordSessionRegistry({
657
+ chatId: "feishu-p2p",
658
+ sessionId: "sid-feishu-private",
659
+ tool: "claude",
660
+ chatType: "p2p",
661
+ chatName: "飞书私聊",
662
+ running: false,
663
+ });
664
+
665
+ await handleCommand(platform, "/model", "feishu-p2p", "ou-user", Date.now(), "p2p");
666
+
667
+ expect(platform.createGroup).not.toHaveBeenCalled();
668
+ expect(platform.sendRawCard).toHaveBeenCalled();
669
+ const registry = await loadSessionRegistryForBinding();
670
+ expect(registry["feishu-p2p"]?.sessionId).toBe("sid-feishu-private");
671
+ });
672
+
673
+ it("queries and switches Fast mode for the current Codex session", async () => {
674
+ const platform = mockPlatform("feishu");
675
+ await recordSessionRegistry({
676
+ chatId: "feishu-codex",
677
+ sessionId: "sid-codex-fast",
678
+ tool: "codex",
679
+ chatType: "p2p",
680
+ chatName: "Codex",
681
+ running: false,
682
+ });
683
+
684
+ await handleCommand(platform, "/fast", "feishu-codex", "ou-user", Date.now(), "p2p");
685
+ let card = JSON.parse(
686
+ vi.mocked(platform.sendRawCard).mock.calls.at(-1)?.[1] ?? "{}",
687
+ ) as { elements?: Array<{ tag: string; text?: { content: string } }> };
688
+ expect(card.elements?.find((element) => element.tag === "div")?.text?.content).toContain("OFF");
689
+
690
+ await handleCommand(platform, "/fast on", "feishu-codex", "ou-user", Date.now(), "p2p");
691
+ expect(getEffectiveFastModeForTool("codex", "sid-codex-fast")).toBe(true);
692
+ expect(platform.setChatAvatar).toHaveBeenLastCalledWith(
693
+ "feishu-codex",
694
+ "codex",
695
+ "idle",
696
+ { fastMode: true },
697
+ );
698
+
699
+ await handleCommand(platform, "/fast off", "feishu-codex", "ou-user", Date.now(), "p2p");
700
+ expect(getEffectiveFastModeForTool("codex", "sid-codex-fast")).toBe(false);
701
+ expect(platform.setChatAvatar).toHaveBeenLastCalledWith(
702
+ "feishu-codex",
703
+ "codex",
704
+ "idle",
705
+ { fastMode: false },
706
+ );
707
+ card = JSON.parse(
708
+ vi.mocked(platform.sendRawCard).mock.calls.at(-1)?.[1] ?? "{}",
709
+ ) as { elements?: Array<{ tag: string; text?: { content: string } }> };
710
+ expect(card.elements?.find((element) => element.tag === "div")?.text?.content).toContain("OFF");
711
+ });
712
+
713
+ it("uses a text fallback for Fast mode commands on WeChat", async () => {
714
+ const platform = mockPlatform("wechat");
715
+ await recordSessionRegistry({
716
+ chatId: "wechat-codex",
717
+ sessionId: "sid-wechat-codex-fast",
718
+ tool: "codex",
719
+ chatType: "p2p",
720
+ chatName: "Codex",
721
+ running: false,
722
+ });
723
+
724
+ await handleCommand(platform, "/fast on", "wechat-codex", "wx-user", Date.now(), "p2p");
725
+
726
+ expect(getEffectiveFastModeForTool("codex", "sid-wechat-codex-fast")).toBe(true);
727
+ expect(platform.sendText).toHaveBeenCalledWith(
728
+ "wechat-codex",
729
+ expect.stringContaining("ON (Fast)"),
730
+ );
731
+ expect(platform.sendRawCard).not.toHaveBeenCalled();
732
+ });
733
+
734
+ it("keeps the Feishu p2p session bound when /new creates a separate group", async () => {
735
+ const platform = mockPlatform("feishu");
736
+ const createSession = vi.fn(async () => ({ sessionId: "sid-feishu-group" }));
737
+ _setAdapterForToolForTest("claude", {
738
+ ...mockAdapter("sid-feishu-group"),
739
+ createSession,
740
+ });
741
+ await recordSessionRegistry({
742
+ chatId: "feishu-p2p",
743
+ sessionId: "sid-feishu-private",
744
+ tool: "claude",
745
+ chatType: "p2p",
746
+ chatName: "飞书私聊",
747
+ running: false,
748
+ });
749
+
750
+ await handleCommand(platform, "/new", "feishu-p2p", "ou-user", Date.now(), "p2p");
751
+
752
+ expect(platform.createGroup).toHaveBeenCalledWith(expect.any(String), ["ou-user"]);
753
+ const registry = await loadSessionRegistryForBinding();
754
+ expect(registry["feishu-p2p"]?.sessionId).toBe("sid-feishu-private");
755
+ expect(registry["feishu-group"]?.sessionId).toBe("sid-feishu-group");
756
+ });
757
+
758
+ it("resets a Feishu p2p session in place with /newh and forces the OS user directory", async () => {
759
+ const platform = mockPlatform("feishu");
760
+ const createSession = vi.fn(async () => ({ sessionId: "sid-feishu-private-reset" }));
761
+ _setAdapterForToolForTest("claude", {
762
+ ...mockAdapter("sid-feishu-private-reset"),
763
+ createSession,
764
+ getSessionInfo: async (sessionId: string): Promise<SessionInfo> => ({
765
+ sessionId,
766
+ cwd: "F:\\some-project",
767
+ }),
768
+ });
769
+ await recordSessionRegistry({
770
+ chatId: "feishu-p2p",
771
+ sessionId: "sid-feishu-private",
772
+ tool: "claude",
773
+ chatType: "p2p",
774
+ chatName: "飞书私聊",
775
+ running: false,
776
+ });
777
+
778
+ await handleCommand(platform, "/newh", "feishu-p2p", "ou-user", Date.now(), "p2p");
779
+
780
+ expect(createSession).toHaveBeenCalledWith(homedir(), expect.any(AbortSignal));
781
+ expect(platform.createGroup).not.toHaveBeenCalled();
782
+ expect(platform.updateChatInfo).not.toHaveBeenCalled();
783
+ const registry = await loadSessionRegistryForBinding();
784
+ expect(registry["feishu-p2p"]?.sessionId).toBe("sid-feishu-private-reset");
785
+ expect(platform.sendCard).toHaveBeenCalledWith(
786
+ "feishu-p2p",
787
+ "Claude Code Session Reset",
788
+ expect.stringContaining(`${homedir()}\`(飞书私聊固定使用系统用户目录)`),
789
+ "green",
790
+ );
791
+ });
792
+
793
+ it("does not allow /session to replace the dedicated Feishu p2p session", async () => {
794
+ const platform = mockPlatform("feishu");
795
+ await recordSessionRegistry({
796
+ chatId: "feishu-p2p",
797
+ sessionId: "sid-feishu-private",
798
+ tool: "claude",
799
+ chatType: "p2p",
800
+ chatName: "飞书私聊",
801
+ running: false,
802
+ });
803
+
804
+ await handleCommand(platform, "/session 1", "feishu-p2p", "ou-user", Date.now(), "p2p");
805
+
806
+ expect(platform.sendCard).toHaveBeenCalledWith(
807
+ "feishu-p2p",
808
+ "/session",
809
+ expect.stringContaining("下一条普通消息时跟随默认 Agent"),
810
+ "yellow",
811
+ );
812
+ expect(platform.updateChatInfo).not.toHaveBeenCalled();
813
+ const registry = await loadSessionRegistryForBinding();
814
+ expect(registry["feishu-p2p"]?.sessionId).toBe("sid-feishu-private");
815
+ });
816
+
817
+ it("shows Claude effort switch card in an active Feishu session", async () => {
818
+ const platform = mockPlatform("feishu");
819
+ vi.mocked(platform.getChatInfo).mockResolvedValue({ name: "claude-session", description: "Claude Session: sid-claude-effort" });
820
+ vi.mocked(platform.extractSessionInfo).mockReturnValue({ sessionId: "sid-claude-effort", tool: "claude" });
821
+ await recordSessionRegistry({
822
+ chatId: "feishu-chat",
823
+ sessionId: "sid-claude-effort",
824
+ tool: "claude",
825
+ chatName: "claude-session",
826
+ running: false,
827
+ });
828
+ sessionInfoMap.set("feishu-chat", {
829
+ sessionId: "sid-claude-effort",
830
+ tool: "claude",
831
+ turnCount: 0,
832
+ lastContextTokens: 0,
833
+ startTime: Date.now(),
834
+ });
835
+
836
+ await handleCommand(platform, "/effort", "feishu-chat", "ou-user", Date.now(), "group");
837
+
838
+ expect(platform.sendRawCard).toHaveBeenCalled();
839
+ const card = JSON.parse(vi.mocked(platform.sendRawCard).mock.calls[0][1]);
840
+ const raw = JSON.stringify(card);
841
+ expect(raw).toContain("/effort low");
842
+ expect(raw).toContain("/effort xhigh");
843
+ expect(raw).toContain("/effort max");
844
+ });
845
+
846
+ it("switches Codex effort for the current session and reflects it in /state", async () => {
847
+ const platform = mockPlatform("feishu");
848
+ vi.mocked(platform.getChatInfo).mockResolvedValue({ name: "codex-session", description: "Codex Session: sid-codex-effort" });
849
+ vi.mocked(platform.extractSessionInfo).mockReturnValue({ sessionId: "sid-codex-effort", tool: "codex" });
850
+ _setAdapterForToolForTest("codex", mockAdapter("sid-codex-effort"));
851
+ await recordSessionRegistry({
852
+ chatId: "codex-chat",
853
+ sessionId: "sid-codex-effort",
854
+ tool: "codex",
855
+ chatName: "codex-session",
856
+ running: false,
857
+ });
858
+ sessionInfoMap.set("codex-chat", {
859
+ sessionId: "sid-codex-effort",
860
+ tool: "codex",
861
+ turnCount: 0,
862
+ lastContextTokens: 0,
863
+ startTime: Date.now(),
864
+ });
865
+
866
+ await handleCommand(platform, "/effort xhigh", "codex-chat", "ou-user", Date.now(), "group");
867
+ expect(platform.sendCard).toHaveBeenCalledWith(
868
+ "codex-chat",
869
+ "Effort 切换",
870
+ expect.stringContaining("xhigh"),
871
+ "green",
872
+ );
873
+
874
+ vi.mocked(platform.sendCard).mockClear();
875
+ vi.mocked(platform.sendRawCard).mockClear();
876
+ await handleCommand(platform, "/state", "codex-chat", "ou-user", Date.now() + 1, "group");
877
+
878
+ expect(platform.sendRawCard).toHaveBeenCalled();
879
+ const card = JSON.parse(vi.mocked(platform.sendRawCard).mock.calls[0][1]);
880
+ expect(JSON.stringify(card)).toContain("xhigh");
881
+ expect(getChatsForSession("sid-codex-effort")).toContain("codex-chat");
882
+ });
883
+
884
+ it("rejects /effort in Cursor sessions", async () => {
885
+ const platform = mockPlatform("feishu");
886
+ vi.mocked(platform.getChatInfo).mockResolvedValue({ name: "cursor-session", description: "Cursor Session: sid-cursor-effort" });
887
+ vi.mocked(platform.extractSessionInfo).mockReturnValue({ sessionId: "sid-cursor-effort", tool: "cursor" });
888
+ _setAdapterForToolForTest("cursor", mockAdapter("sid-cursor-effort"));
889
+ await recordSessionRegistry({
890
+ chatId: "cursor-chat",
891
+ sessionId: "sid-cursor-effort",
892
+ tool: "cursor",
893
+ chatName: "cursor-session",
894
+ running: false,
895
+ });
896
+ sessionInfoMap.set("cursor-chat", {
897
+ sessionId: "sid-cursor-effort",
898
+ tool: "cursor",
899
+ turnCount: 0,
900
+ lastContextTokens: 0,
901
+ startTime: Date.now(),
902
+ });
903
+
904
+ await handleCommand(platform, "/effort high", "cursor-chat", "ou-user", Date.now(), "group");
905
+
906
+ expect(platform.sendCard).toHaveBeenCalledWith(
907
+ "cursor-chat",
908
+ "Effort 切换",
909
+ expect.stringContaining("不支持 effort"),
910
+ "red",
911
+ );
912
+ });
913
+
914
+ it("switches CCC effort for the current session", async () => {
915
+ const platform = mockPlatform("feishu");
916
+ vi.mocked(platform.getChatInfo).mockResolvedValue({ name: "ccc-session", description: "CCC Session: sid-ccc-effort" });
917
+ vi.mocked(platform.extractSessionInfo).mockReturnValue({ sessionId: "sid-ccc-effort", tool: "ccc" });
918
+ _setAdapterForToolForTest("ccc", mockAdapter("sid-ccc-effort"));
919
+ await recordSessionRegistry({
920
+ chatId: "ccc-chat",
921
+ sessionId: "sid-ccc-effort",
922
+ tool: "ccc",
923
+ chatName: "ccc-session",
924
+ running: false,
925
+ });
926
+ sessionInfoMap.set("ccc-chat", {
927
+ sessionId: "sid-ccc-effort",
928
+ tool: "ccc",
929
+ turnCount: 0,
930
+ lastContextTokens: 0,
931
+ startTime: Date.now(),
932
+ });
933
+
934
+ await handleCommand(platform, "/effort max", "ccc-chat", "ou-user", Date.now(), "group");
935
+
936
+ expect(platform.sendCard).toHaveBeenCalledWith(
937
+ "ccc-chat",
938
+ "Effort 切换",
939
+ expect.stringContaining("max"),
940
+ "green",
941
+ );
942
+
943
+ expect(getEffectiveEffortForTool("ccc", "sid-ccc-effort")).toBe("max");
944
+ });
945
+
946
+ it("handles /usage without creating a new Feishu group", async () => {
947
+ const platform = mockPlatform("feishu");
915
948
  const usage = {
916
949
  fiveHour: { usedPercent: 37, remainingPercent: 63, resetAtEpochSeconds: 1781528212, resetAfterSeconds: 10349 },
917
950
  weekly: { usedPercent: 12, remainingPercent: 88, resetAtEpochSeconds: 1781842926, resetAfterSeconds: 325063 },
@@ -937,38 +970,38 @@ describe("handleCommand WeChat processing ack", () => {
937
970
  expect(card.elements[0].text.content).toContain("**5h:** 已用 37%,剩余 63%,重置:");
938
971
  expect(card.elements[0].text.content).toContain("约 2小时52分钟后");
939
972
  expect(card.elements[0].text.content).toContain("[███████░░░░░░░░░░░░░]");
940
- expect(card.elements[0].text.content).toContain("**7天:** 已用 12%,剩余 88%,重置:");
973
+ expect(card.elements[0].text.content).toContain("**7天:** 已用 12%,剩余 88%,重置:");
941
974
  expect(card.elements[0].text.content).toContain("约 3天18小时17分钟后");
942
975
  expect(card.elements[0].text.content).toContain("[██░░░░░░░░░░░░░░░░░░]");
943
976
  expect(card.elements[2].actions[0].text.content).toBe("发起重置");
944
977
  expect(card.elements[2].actions[0].value).toEqual({ action: "codex_reset_request", availableCount: 2 });
945
- expect(platform.setChatAvatar).toHaveBeenCalledWith("feishu-p2p", "codex", "idle", { codexUsage: usage });
946
- });
947
-
948
- it("shows only the 7-day window when the 5h window is absent", async () => {
949
- const platform = mockPlatform("feishu");
950
- const usage = {
951
- fiveHour: null,
952
- weekly: {
953
- usedPercent: 23,
954
- remainingPercent: 77,
955
- resetAtEpochSeconds: 1784510226,
956
- resetAfterSeconds: 500000,
957
- limitWindowSeconds: 604800,
958
- },
959
- rateLimitResetCreditsAvailable: 0,
960
- rateLimitResetCredits: [],
961
- };
962
- mockGetCodexUsageSummary.mockResolvedValue(usage);
963
-
964
- await handleCommand(platform, "/usage", "feishu-p2p", "ou-user", Date.now(), "p2p");
965
-
966
- const card = JSON.parse(vi.mocked(platform.sendRawCard).mock.calls[0][1]);
967
- const content = card.elements[0].text.content as string;
968
- expect(content).not.toContain("**5h:**");
969
- expect(content).toContain("**7天:** 已用 23%,剩余 77%,重置:");
970
- expect(platform.setChatAvatar).toHaveBeenCalledWith("feishu-p2p", "codex", "idle", { codexUsage: usage });
971
- });
978
+ expect(platform.setChatAvatar).toHaveBeenCalledWith("feishu-p2p", "codex", "idle", { codexUsage: usage });
979
+ });
980
+
981
+ it("shows only the 7-day window when the 5h window is absent", async () => {
982
+ const platform = mockPlatform("feishu");
983
+ const usage = {
984
+ fiveHour: null,
985
+ weekly: {
986
+ usedPercent: 23,
987
+ remainingPercent: 77,
988
+ resetAtEpochSeconds: 1784510226,
989
+ resetAfterSeconds: 500000,
990
+ limitWindowSeconds: 604800,
991
+ },
992
+ rateLimitResetCreditsAvailable: 0,
993
+ rateLimitResetCredits: [],
994
+ };
995
+ mockGetCodexUsageSummary.mockResolvedValue(usage);
996
+
997
+ await handleCommand(platform, "/usage", "feishu-p2p", "ou-user", Date.now(), "p2p");
998
+
999
+ const card = JSON.parse(vi.mocked(platform.sendRawCard).mock.calls[0][1]);
1000
+ const content = card.elements[0].text.content as string;
1001
+ expect(content).not.toContain("**5h:**");
1002
+ expect(content).toContain("**7天:** 已用 23%,剩余 77%,重置:");
1003
+ expect(platform.setChatAvatar).toHaveBeenCalledWith("feishu-p2p", "codex", "idle", { codexUsage: usage });
1004
+ });
972
1005
 
973
1006
  it("adds ChatGPT subscription expiry to Codex /usage when CDP lookup succeeds", async () => {
974
1007
  const platform = mockPlatform("feishu");
@@ -1020,7 +1053,7 @@ describe("handleCommand WeChat processing ack", () => {
1020
1053
  expect(card.elements[0].text.content).toContain("ChatGPT browser session has no access token.");
1021
1054
  });
1022
1055
 
1023
- it("handles /usage as Cursor usage in Cursor chats", async () => {
1056
+ it("handles /usage as Cursor usage in Cursor chats", async () => {
1024
1057
  const platform = mockPlatform("feishu");
1025
1058
  await recordSessionRegistry({
1026
1059
  chatId: "cursor-chat",
@@ -1080,28 +1113,28 @@ describe("handleCommand WeChat processing ack", () => {
1080
1113
  );
1081
1114
  });
1082
1115
 
1083
- it("advertises /usage in new Codex and Cursor session ready messages", async () => {
1084
- const codexPlatform = mockPlatform("feishu");
1085
- _setAdapterForToolForTest("codex", mockAdapter("sid-codex"));
1116
+ it("advertises /usage in new Codex and Cursor session ready messages", async () => {
1117
+ const codexPlatform = mockPlatform("feishu");
1118
+ _setAdapterForToolForTest("codex", mockAdapter("sid-codex"));
1086
1119
 
1087
1120
  await handleCommand(codexPlatform, "/new codex", "feishu-p2p", "ou-user", Date.now(), "p2p");
1088
1121
 
1089
1122
  expect(codexPlatform.sendCard).toHaveBeenCalledWith(
1090
1123
  "feishu-group",
1091
1124
  "Codex Session Ready",
1092
- expect.stringContaining("发送 **/usage** 查看 Codex 实际存在的 5h/7天用量窗口,以及查询/使用主动重置卡。"),
1125
+ expect.stringContaining("发送 **/usage** 查看 Codex 实际存在的 5h/7天用量窗口,以及查询/使用主动重置卡。"),
1093
1126
  "green",
1094
1127
  );
1095
1128
 
1096
- const codexReadyCall = vi.mocked(codexPlatform.sendCard).mock.calls.find(
1097
- ([chatId, title]) => chatId === "feishu-group" && title === "Codex Session Ready",
1098
- );
1099
- const modelHelpIndex = codexReadyCall?.[2].indexOf("/model") ?? -1;
1100
- const fastHelpIndex = codexReadyCall?.[2].indexOf("/fast") ?? -1;
1101
- expect(modelHelpIndex).toBeGreaterThanOrEqual(0);
1102
- expect(fastHelpIndex).toBeGreaterThan(modelHelpIndex);
1103
-
1104
- const cursorPlatform = mockPlatform("feishu");
1129
+ const codexReadyCall = vi.mocked(codexPlatform.sendCard).mock.calls.find(
1130
+ ([chatId, title]) => chatId === "feishu-group" && title === "Codex Session Ready",
1131
+ );
1132
+ const modelHelpIndex = codexReadyCall?.[2].indexOf("/model") ?? -1;
1133
+ const fastHelpIndex = codexReadyCall?.[2].indexOf("/fast") ?? -1;
1134
+ expect(modelHelpIndex).toBeGreaterThanOrEqual(0);
1135
+ expect(fastHelpIndex).toBeGreaterThan(modelHelpIndex);
1136
+
1137
+ const cursorPlatform = mockPlatform("feishu");
1105
1138
  _setAdapterForToolForTest("cursor", mockAdapter("sid-cursor"));
1106
1139
 
1107
1140
  await handleCommand(cursorPlatform, "/new cursor", "feishu-p2p-cursor", "ou-user", Date.now(), "p2p");
@@ -1114,122 +1147,122 @@ describe("handleCommand WeChat processing ack", () => {
1114
1147
  const claudePlatform = mockPlatform("feishu");
1115
1148
  await handleCommand(claudePlatform, "/new claude", "feishu-p2p-2", "ou-user", Date.now(), "p2p");
1116
1149
 
1117
- const claudeReadyCall = vi.mocked(claudePlatform.sendCard).mock.calls.find(
1118
- ([chatId, title]) => chatId === "feishu-group" && title === "Claude Code Session Ready",
1119
- );
1120
- expect(claudeReadyCall?.[2]).not.toContain("/usage");
1121
- });
1122
-
1123
- it("handles /usage as DeepSeek balance in CCC Agent chats", async () => {
1124
- const platform = mockPlatform("feishu");
1125
- const fetchMock = vi.fn(async () => new Response(JSON.stringify({
1126
- is_available: true,
1127
- balance_infos: [{
1128
- currency: "CNY",
1129
- total_balance: "12.34",
1130
- topped_up_balance: "10.00",
1131
- granted_balance: "2.34",
1132
- }],
1133
- }), { status: 200 }));
1134
- vi.stubGlobal("fetch", fetchMock);
1135
- await recordSessionRegistry({
1136
- chatId: "ccc-chat",
1137
- sessionId: "sid-ccc",
1138
- tool: "ccc",
1139
- chatName: "ccc-session",
1140
- running: false,
1141
- });
1142
-
1143
- await handleCommand(platform, "/usage", "ccc-chat", "ou-user", Date.now(), "group");
1144
-
1145
- expect(fetchMock).toHaveBeenCalledWith(
1146
- "https://api.deepseek.com/user/balance",
1147
- expect.objectContaining({ headers: { Authorization: "Bearer sk-test-ccc" } }),
1148
- );
1149
- expect(platform.sendCard).toHaveBeenCalledWith(
1150
- "ccc-chat",
1151
- "CCC Usage",
1152
- expect.stringContaining("总余额: 12.34"),
1153
- "blue",
1154
- );
1155
- });
1156
-
1157
- it("does not query balance for a non-official CCC API endpoint", async () => {
1158
- const platform = mockPlatform("feishu");
1159
- const fetchMock = vi.fn();
1160
- vi.stubGlobal("fetch", fetchMock);
1161
- config.ccc.DEEPSEEK_BASE_URL = "https://deepseek-proxy.example.com/v1";
1162
- await recordSessionRegistry({
1163
- chatId: "ccc-proxy-chat",
1164
- sessionId: "sid-ccc-proxy",
1165
- tool: "ccc",
1166
- chatName: "ccc-proxy-session",
1167
- running: false,
1168
- });
1169
-
1170
- await handleCommand(platform, "/usage", "ccc-proxy-chat", "ou-user", Date.now(), "group");
1171
-
1172
- expect(fetchMock).not.toHaveBeenCalled();
1173
- expect(platform.sendCard).toHaveBeenCalledWith(
1174
- "ccc-proxy-chat",
1175
- "CCC Usage",
1176
- expect.stringContaining("仅支持官方 DeepSeek API"),
1177
- "blue",
1178
- );
1179
- });
1180
-
1181
- it("reloads runtime config for the exact /reload command", async () => {
1182
- const platform = mockPlatform("feishu");
1183
-
1184
- await handleCommand(platform, "/reload", "feishu-chat", "open-1", Date.now(), "group");
1185
-
1186
- expect(mockReloadRuntimeConfig).toHaveBeenCalledWith("chat-command");
1187
- expect(platform.sendText).toHaveBeenCalledWith(
1188
- "feishu-chat",
1189
- expect.stringContaining("配置已重新加载"),
1190
- );
1191
- expect(platform.sendText).toHaveBeenCalledWith(
1192
- "feishu-chat",
1193
- expect.stringContaining("默认 Agent: Codex"),
1194
- );
1195
- });
1196
-
1197
- it("allows and advertises the /new ccc entry", async () => {
1198
- const platform = mockPlatform("feishu");
1199
- _setAdapterForToolForTest("ccc", mockAdapter("session-20260702-121530-a1b2c3"));
1200
-
1201
- await handleCommand(platform, "/new ccc", "feishu-p2p-ccc", "ou-user", Date.now(), "p2p");
1202
-
1203
- expect(platform.updateChatInfo).toHaveBeenCalledWith(
1204
- "feishu-group",
1205
- expect.any(String),
1206
- "CCC Session: session-20260702-121530-a1b2c3",
1207
- );
1208
- expect(platform.sendCard).toHaveBeenCalledWith(
1209
- "feishu-group",
1210
- "CCC Agent Session Ready",
1211
- expect.stringContaining("CCC Agent"),
1212
- "green",
1213
- );
1214
-
1215
- const helpPlatform = mockPlatform("feishu");
1216
- await handleCommand(helpPlatform, "hello", "feishu-group-help", "ou-user", Date.now(), "group");
1217
- const helpCard = vi.mocked(helpPlatform.sendRawCard).mock.calls.at(-1)?.[1] as string;
1218
- expect(helpCard).toContain("/new ccc");
1219
- expect(helpCard).toContain("CCC Agent");
1220
- });
1221
-
1222
- it("shows the CCC model list when CCC Agent is the unbound default", async () => {
1223
- const platform = mockPlatform("feishu");
1224
- config.claude.defaultAgent = false;
1225
- config.cursor.defaultAgent = false;
1226
- config.codex.defaultAgent = false;
1227
- config.ccc.defaultAgent = true;
1228
-
1229
- await handleCommand(platform, "/model", "feishu-p2p-ccc-model", "ou-user", Date.now(), "p2p");
1230
-
1231
- const card = vi.mocked(platform.sendRawCard).mock.calls.at(-1)?.[1] as string;
1232
- expect(card).toContain("deepseek-v4-pro");
1233
- expect(card).toContain("deepseek-v4-flash");
1234
- });
1235
- });
1150
+ const claudeReadyCall = vi.mocked(claudePlatform.sendCard).mock.calls.find(
1151
+ ([chatId, title]) => chatId === "feishu-group" && title === "Claude Code Session Ready",
1152
+ );
1153
+ expect(claudeReadyCall?.[2]).not.toContain("/usage");
1154
+ });
1155
+
1156
+ it("handles /usage as DeepSeek balance in CCC Agent chats", async () => {
1157
+ const platform = mockPlatform("feishu");
1158
+ const fetchMock = vi.fn(async () => new Response(JSON.stringify({
1159
+ is_available: true,
1160
+ balance_infos: [{
1161
+ currency: "CNY",
1162
+ total_balance: "12.34",
1163
+ topped_up_balance: "10.00",
1164
+ granted_balance: "2.34",
1165
+ }],
1166
+ }), { status: 200 }));
1167
+ vi.stubGlobal("fetch", fetchMock);
1168
+ await recordSessionRegistry({
1169
+ chatId: "ccc-chat",
1170
+ sessionId: "sid-ccc",
1171
+ tool: "ccc",
1172
+ chatName: "ccc-session",
1173
+ running: false,
1174
+ });
1175
+
1176
+ await handleCommand(platform, "/usage", "ccc-chat", "ou-user", Date.now(), "group");
1177
+
1178
+ expect(fetchMock).toHaveBeenCalledWith(
1179
+ "https://api.deepseek.com/user/balance",
1180
+ expect.objectContaining({ headers: { Authorization: "Bearer sk-test-ccc" } }),
1181
+ );
1182
+ expect(platform.sendCard).toHaveBeenCalledWith(
1183
+ "ccc-chat",
1184
+ "CCC Usage",
1185
+ expect.stringContaining("总余额: 12.34"),
1186
+ "blue",
1187
+ );
1188
+ });
1189
+
1190
+ it("does not query balance for a non-official CCC API endpoint", async () => {
1191
+ const platform = mockPlatform("feishu");
1192
+ const fetchMock = vi.fn();
1193
+ vi.stubGlobal("fetch", fetchMock);
1194
+ config.ccc.DEEPSEEK_BASE_URL = "https://deepseek-proxy.example.com/v1";
1195
+ await recordSessionRegistry({
1196
+ chatId: "ccc-proxy-chat",
1197
+ sessionId: "sid-ccc-proxy",
1198
+ tool: "ccc",
1199
+ chatName: "ccc-proxy-session",
1200
+ running: false,
1201
+ });
1202
+
1203
+ await handleCommand(platform, "/usage", "ccc-proxy-chat", "ou-user", Date.now(), "group");
1204
+
1205
+ expect(fetchMock).not.toHaveBeenCalled();
1206
+ expect(platform.sendCard).toHaveBeenCalledWith(
1207
+ "ccc-proxy-chat",
1208
+ "CCC Usage",
1209
+ expect.stringContaining("仅支持官方 DeepSeek API"),
1210
+ "blue",
1211
+ );
1212
+ });
1213
+
1214
+ it("reloads runtime config for the exact /reload command", async () => {
1215
+ const platform = mockPlatform("feishu");
1216
+
1217
+ await handleCommand(platform, "/reload", "feishu-chat", "open-1", Date.now(), "group");
1218
+
1219
+ expect(mockReloadRuntimeConfig).toHaveBeenCalledWith("chat-command");
1220
+ expect(platform.sendText).toHaveBeenCalledWith(
1221
+ "feishu-chat",
1222
+ expect.stringContaining("配置已重新加载"),
1223
+ );
1224
+ expect(platform.sendText).toHaveBeenCalledWith(
1225
+ "feishu-chat",
1226
+ expect.stringContaining("默认 Agent: Codex"),
1227
+ );
1228
+ });
1229
+
1230
+ it("allows and advertises the /new ccc entry", async () => {
1231
+ const platform = mockPlatform("feishu");
1232
+ _setAdapterForToolForTest("ccc", mockAdapter("session-20260702-121530-a1b2c3"));
1233
+
1234
+ await handleCommand(platform, "/new ccc", "feishu-p2p-ccc", "ou-user", Date.now(), "p2p");
1235
+
1236
+ expect(platform.updateChatInfo).toHaveBeenCalledWith(
1237
+ "feishu-group",
1238
+ expect.any(String),
1239
+ "CCC Session: session-20260702-121530-a1b2c3",
1240
+ );
1241
+ expect(platform.sendCard).toHaveBeenCalledWith(
1242
+ "feishu-group",
1243
+ "CCC Agent Session Ready",
1244
+ expect.stringContaining("CCC Agent"),
1245
+ "green",
1246
+ );
1247
+
1248
+ const helpPlatform = mockPlatform("feishu");
1249
+ await handleCommand(helpPlatform, "hello", "feishu-group-help", "ou-user", Date.now(), "group");
1250
+ const helpCard = vi.mocked(helpPlatform.sendRawCard).mock.calls.at(-1)?.[1] as string;
1251
+ expect(helpCard).toContain("/new ccc");
1252
+ expect(helpCard).toContain("CCC Agent");
1253
+ });
1254
+
1255
+ it("shows the CCC model list when CCC Agent is the unbound default", async () => {
1256
+ const platform = mockPlatform("feishu");
1257
+ config.claude.defaultAgent = false;
1258
+ config.cursor.defaultAgent = false;
1259
+ config.codex.defaultAgent = false;
1260
+ config.ccc.defaultAgent = true;
1261
+
1262
+ await handleCommand(platform, "/model", "feishu-p2p-ccc-model", "ou-user", Date.now(), "p2p");
1263
+
1264
+ const card = vi.mocked(platform.sendRawCard).mock.calls.at(-1)?.[1] as string;
1265
+ expect(card).toContain("deepseek-v4-pro");
1266
+ expect(card).toContain("deepseek-v4-flash");
1267
+ });
1268
+ });