chatccc 0.2.170 → 0.2.171

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "chatccc",
3
- "version": "0.2.170",
3
+ "version": "0.2.171",
4
4
  "description": "Feishu bot bridge for Claude Code",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -0,0 +1,60 @@
1
+ import { afterEach, describe, expect, it, vi } from "vitest";
2
+
3
+ import { sendTextReply } from "../feishu-api.ts";
4
+
5
+ function abortError(): Error {
6
+ const err = new Error("aborted");
7
+ err.name = "AbortError";
8
+ return err;
9
+ }
10
+
11
+ describe("sendTextReply timeout", () => {
12
+ afterEach(() => {
13
+ vi.useRealTimers();
14
+ vi.restoreAllMocks();
15
+ vi.unstubAllGlobals();
16
+ });
17
+
18
+ it("aborts a hung text send request", async () => {
19
+ vi.useFakeTimers();
20
+ vi.spyOn(console, "error").mockImplementation(() => {});
21
+
22
+ const fetchMock = vi.fn((_url: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => (
23
+ new Promise<Response>((_resolve, reject) => {
24
+ init?.signal?.addEventListener("abort", () => reject(abortError()));
25
+ })
26
+ ));
27
+ vi.stubGlobal("fetch", fetchMock);
28
+
29
+ const send = expect(sendTextReply("token", "chat-1", "hello"))
30
+ .resolves.toBe(false);
31
+ await vi.advanceTimersByTimeAsync(15_000);
32
+
33
+ await send;
34
+ expect(fetchMock).toHaveBeenCalledWith(
35
+ expect.stringContaining("/im/v1/messages?receive_id_type=chat_id"),
36
+ expect.objectContaining({ signal: expect.any(AbortSignal) }),
37
+ );
38
+ });
39
+
40
+ it("also aborts when response body reading hangs", async () => {
41
+ vi.useFakeTimers();
42
+ vi.spyOn(console, "error").mockImplementation(() => {});
43
+
44
+ const fetchMock = vi.fn((_url: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => (
45
+ Promise.resolve({
46
+ status: 200,
47
+ text: () => new Promise<string>((_resolve, reject) => {
48
+ init?.signal?.addEventListener("abort", () => reject(abortError()));
49
+ }),
50
+ } as Response)
51
+ ));
52
+ vi.stubGlobal("fetch", fetchMock);
53
+
54
+ const send = expect(sendTextReply("token", "chat-2", "hello"))
55
+ .resolves.toBe(false);
56
+ await vi.advanceTimersByTimeAsync(15_000);
57
+
58
+ await send;
59
+ });
60
+ });
@@ -569,6 +569,58 @@ describe("unified display loop terminal card update", () => {
569
569
  );
570
570
  expect(displayCards.get("chat-terminal")?.sequence).toBe(110);
571
571
  });
572
+
573
+ it("keeps terminal display and retries final text when sending fails", async () => {
574
+ vi.spyOn(console, "error").mockImplementation(() => {});
575
+ const platform = mockPlatform("feishu");
576
+ platform.cardUpdate = vi.fn(async () => {});
577
+ platform.sendText = vi.fn()
578
+ .mockResolvedValueOnce(false)
579
+ .mockResolvedValueOnce(true);
580
+ setSessionPlatform(platform);
581
+
582
+ bindChatToSession("sid-terminal-retry", "chat-terminal-retry");
583
+ recordLastActiveChat("sid-terminal-retry", "chat-terminal-retry");
584
+ sessionInfoMap.set("chat-terminal-retry", {
585
+ sessionId: "sid-terminal-retry",
586
+ turnCount: 1,
587
+ lastContextTokens: 0,
588
+ startTime: 0,
589
+ tool: "claude",
590
+ });
591
+ displayCards.set("chat-terminal-retry", {
592
+ cardId: "card-terminal-retry",
593
+ sequence: 4,
594
+ cardBusy: false,
595
+ cardCreatedAt: Date.now(),
596
+ lastSentContent: "",
597
+ streamErrorNotified: false,
598
+ sessionId: "sid-terminal-retry",
599
+ turnCount: 1,
600
+ dotCount: 0,
601
+ });
602
+ mockStreamStates.set("sid-terminal-retry", {
603
+ accumulatedContent: "work log",
604
+ finalReply: "final answer",
605
+ status: "done",
606
+ turnCount: 1,
607
+ });
608
+
609
+ startUnifiedDisplayLoop();
610
+ await vi.advanceTimersByTimeAsync(3000);
611
+
612
+ expect(platform.cardUpdate).toHaveBeenCalledTimes(1);
613
+ expect(platform.sendText).toHaveBeenCalledTimes(1);
614
+ expect(displayCards.has("chat-terminal-retry")).toBe(true);
615
+ expect(mockStreamStates.get("sid-terminal-retry")?.finalReplySentTurn).toBeUndefined();
616
+
617
+ await vi.advanceTimersByTimeAsync(3000);
618
+
619
+ expect(platform.cardUpdate).toHaveBeenCalledTimes(1);
620
+ expect(platform.sendText).toHaveBeenCalledTimes(2);
621
+ expect(displayCards.has("chat-terminal-retry")).toBe(false);
622
+ expect(mockStreamStates.get("sid-terminal-retry")?.finalReplySentTurn).toBe(1);
623
+ });
572
624
  });
573
625
 
574
626
  describe("rebuildBindingsFromRegistry", () => {
package/src/feishu-api.ts CHANGED
@@ -757,6 +757,9 @@ export async function sendTextReply(
757
757
  config: { wide_screen_mode: true },
758
758
  elements: [{ tag: "markdown", content: wrappedText }],
759
759
  });
760
+ const timeoutMs = 15_000;
761
+ const controller = new AbortController();
762
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
760
763
  try {
761
764
  const resp = await fetch(`${BASE_URL}/im/v1/messages?receive_id_type=chat_id`, {
762
765
  method: "POST",
@@ -769,8 +772,16 @@ export async function sendTextReply(
769
772
  msg_type: "interactive",
770
773
  content: card,
771
774
  }),
775
+ signal: controller.signal,
772
776
  });
773
- const data = (await resp.json().catch(() => ({}))) as { code: number; msg?: string; data?: { message_id?: string } };
777
+ const respText = await resp.text();
778
+ let data: { code: number; msg?: string; data?: { message_id?: string } };
779
+ try {
780
+ data = JSON.parse(respText);
781
+ } catch {
782
+ console.error(`[${ts()}] [SEND] text FAIL: chatId=${chatId} invalid JSON status=${resp.status}`);
783
+ return false;
784
+ }
774
785
  if (data.code !== 0) {
775
786
  console.error(`[${ts()}] [SEND] text FAIL: chatId=${chatId} code=${data.code} msg="${data.msg ?? ""}"`);
776
787
  return false;
@@ -778,8 +789,14 @@ export async function sendTextReply(
778
789
  console.log(`[${ts()}] [SEND] text OK: chatId=${chatId} msgId=${data.data?.message_id ?? "N/A"}`);
779
790
  return true;
780
791
  } catch (err) {
792
+ if ((err as Error).name === "AbortError") {
793
+ console.error(`[${ts()}] [SEND] text TIMEOUT after ${timeoutMs}ms: chatId=${chatId}`);
794
+ return false;
795
+ }
781
796
  console.error(`[${ts()}] [SEND] text FAIL: chatId=${chatId} ${(err as Error).message}`);
782
797
  return false;
798
+ } finally {
799
+ clearTimeout(timer);
783
800
  }
784
801
  }
785
802
 
package/src/session.ts CHANGED
@@ -1300,17 +1300,21 @@ const CARD_ROTATE_MS = 9 * 60 * 1000;
1300
1300
  export function startUnifiedDisplayLoop(): void {
1301
1301
  if (unifiedDisplayLoopHandle !== null) return;
1302
1302
 
1303
+ let tickRunning = false;
1303
1304
  const interval = setInterval(() => {
1304
1305
  void (async () => {
1305
- for (const [chatId, display] of displayCards) {
1306
- if (display.cardBusy) continue;
1307
-
1308
- const sessionId = display.sessionId;
1309
- const state = await readStreamState(sessionId);
1310
- if (!state) {
1311
- displayCards.delete(chatId);
1312
- continue;
1313
- }
1306
+ if (tickRunning) return;
1307
+ tickRunning = true;
1308
+ try {
1309
+ for (const [chatId, display] of displayCards) {
1310
+ if (display.cardBusy) continue;
1311
+
1312
+ const sessionId = display.sessionId;
1313
+ const state = await readStreamState(sessionId);
1314
+ if (!state) {
1315
+ displayCards.delete(chatId);
1316
+ continue;
1317
+ }
1314
1318
 
1315
1319
  // 交叉验证:chat 当前绑定的 session 是否仍是 display 记录的 session。
1316
1320
  // 若 chat 已被切换到其他 session(如 /newh),旧 display 必须停推。
@@ -1375,45 +1379,57 @@ export function startUnifiedDisplayLoop(): void {
1375
1379
  ) {
1376
1380
  continue;
1377
1381
  }
1378
- const nextSeq = display.sequence + 1;
1379
- const { title: headerTitle, template: headerTemplate } = formatTerminalHeader(state.status);
1380
- const cardContent = truncateContent(state.accumulatedContent + state.finalReply) || " ";
1381
- const doneCard = buildProgressCard(cardContent, { showStop: false, headerTitle, headerTemplate });
1382
- let terminalCardUpdateAccepted = false;
1383
- await p.cardUpdate(display.cardId, doneCard, nextSeq).then(() => {
1384
- display.sequence = nextSeq;
1385
- terminalCardUpdateAccepted = true;
1386
- }).catch(err => {
1387
- console.error(`[${ts()}] [DISPLAY] terminal cardUpdate failed: ${(err as Error).message}`);
1388
- if (isCardKitSequenceConflict(err)) {
1382
+ const terminalCardAlreadyUpdated =
1383
+ display.lastSentAccLen === state.accumulatedContent.length &&
1384
+ display.lastSentFinalReply === state.finalReply;
1385
+ let terminalCardUpdateAccepted = terminalCardAlreadyUpdated;
1386
+ if (!terminalCardAlreadyUpdated) {
1387
+ const nextSeq = display.sequence + 1;
1388
+ const { title: headerTitle, template: headerTemplate } = formatTerminalHeader(state.status);
1389
+ const cardContent = truncateContent(state.accumulatedContent + state.finalReply) || " ";
1390
+ const doneCard = buildProgressCard(cardContent, { showStop: false, headerTitle, headerTemplate });
1391
+ await p.cardUpdate(display.cardId, doneCard, nextSeq).then(() => {
1389
1392
  display.sequence = nextSeq;
1390
1393
  terminalCardUpdateAccepted = true;
1394
+ }).catch(err => {
1395
+ console.error(`[${ts()}] [DISPLAY] terminal cardUpdate failed: ${(err as Error).message}`);
1396
+ if (isCardKitSequenceConflict(err)) {
1397
+ display.sequence = nextSeq;
1398
+ terminalCardUpdateAccepted = true;
1399
+ }
1400
+ });
1401
+ if (terminalCardUpdateAccepted) {
1402
+ display.lastSentAccLen = state.accumulatedContent.length;
1403
+ display.lastSentFinalReply = state.finalReply;
1391
1404
  }
1392
- });
1405
+ }
1393
1406
 
1394
1407
  // 若 session 仍在 activePrompts 中,说明 runAgentSession 的 finally
1395
1408
  // 还没执行,当前 stream state 可能是 stopSession fire-and-forget
1396
1409
  // 写入的,finalReply 滞后于内存态。卡片已更新为终态外观,但不发送
1397
1410
  // 文本、不删除 display 条目,留给 finally 落盘后的下一次 tick 处理。
1398
1411
  if (promptStillActive) {
1399
- if (terminalCardUpdateAccepted) {
1400
- display.lastSentAccLen = state.accumulatedContent.length;
1401
- display.lastSentFinalReply = state.finalReply;
1402
- }
1403
1412
  continue;
1404
1413
  }
1405
1414
 
1406
- const finalSt = turnFinalStatus(state.status);
1407
- finalizeTurnCards(sessionId, state.turnCount, finalSt).catch(() => {});
1408
- displayCards.delete(chatId);
1415
+ let terminalTextDelivered = true;
1409
1416
  if (state.finalReply) {
1410
1417
  if (!isFinalReplySentForTurn(state)) {
1411
- await sendFinalReplyTextOnce(p, chatId, sessionId, state.turnCount, state.finalReply);
1418
+ terminalTextDelivered = await sendFinalReplyTextOnce(p, chatId, sessionId, state.turnCount, state.finalReply);
1412
1419
  }
1413
1420
  } else if (state.accumulatedContent.trim()) {
1414
1421
  const short = truncateContent(state.accumulatedContent, 30, 4000);
1415
- await p.sendText(chatId, `[生成过程]\n${short}`).catch(() => {});
1422
+ terminalTextDelivered = await p.sendText(chatId, `[生成过程]\n${short}`).then((ok) => ok !== false).catch(() => false);
1416
1423
  }
1424
+
1425
+ if (!terminalTextDelivered) {
1426
+ console.error(`[${ts()}] [DISPLAY] terminal text send failed, keep display for retry: chatId=${chatId} session=${sessionId} turn=${state.turnCount}`);
1427
+ continue;
1428
+ }
1429
+
1430
+ const finalSt = turnFinalStatus(state.status);
1431
+ finalizeTurnCards(sessionId, state.turnCount, finalSt).catch(() => {});
1432
+ displayCards.delete(chatId);
1417
1433
  }
1418
1434
  p.setChatAvatar(chatId, state.tool, "idle").catch(() => {});
1419
1435
  console.log(`[${ts()}] [DISPLAY] unified loop deleted display for ${chatId} (terminal: ${state.status})`);
@@ -1561,9 +1577,12 @@ export function startUnifiedDisplayLoop(): void {
1561
1577
  }
1562
1578
  }
1563
1579
  }
1564
- } catch (err) {
1565
- console.error(`[${ts()}] Display loop error for ${chatId}: ${(err as Error).message}`);
1580
+ } catch (err) {
1581
+ console.error(`[${ts()}] Display loop error for ${chatId}: ${(err as Error).message}`);
1582
+ }
1566
1583
  }
1584
+ } finally {
1585
+ tickRunning = false;
1567
1586
  }
1568
1587
  })().catch((err: unknown) => {
1569
1588
  const e = err instanceof Error ? err : new Error(String(err));