chatccc 0.2.103 → 0.2.107

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,912 +1,442 @@
1
- import { describe, it, expect, vi, beforeEach, afterAll } from "vitest";
2
- import { normalizeSdkMessage, createClaudeAdapter } from "../adapters/claude-adapter.ts";
3
- import type { UnifiedStreamMessage } from "../adapters/adapter-interface.ts";
4
-
5
- // ---------------------------------------------------------------------------
6
- // Mock Claude SDK
7
- // ---------------------------------------------------------------------------
8
-
9
- const mockSend = vi.fn();
10
- const mockClose = vi.fn();
11
- const mockStreamNext = vi.fn();
12
- const mockStreamIterable: AsyncGenerator<any, void> = {
13
- next: mockStreamNext,
14
- [Symbol.asyncIterator]() { return this; },
15
- } as any;
16
-
17
- function mockSession(overrides: Partial<{ send: any; close: any; streamNext: any }> = {}) {
18
- return {
19
- send: overrides.send ?? mockSend,
20
- close: overrides.close ?? mockClose,
21
- stream: () => ({
22
- next: overrides.streamNext ?? mockStreamNext,
23
- [Symbol.asyncIterator]() { return this; },
24
- }),
25
- };
26
- }
27
-
28
- vi.mock("@anthropic-ai/claude-agent-sdk", () => {
29
- // We only mock the full adapter integration tests; normalizeSdkMessage is pure
30
- return {
31
- unstable_v2_createSession: vi.fn(),
32
- unstable_v2_resumeSession: vi.fn(),
33
- getSessionInfo: vi.fn(),
34
- };
35
- });
36
-
37
- // ---------------------------------------------------------------------------
38
- // normalizeSdkMessage — 核心映射逻辑测试(纯函数,不需要 mock SDK)
39
- // ---------------------------------------------------------------------------
40
-
41
- describe("normalizeSdkMessage", () => {
42
- // --- assistant messages ---
43
-
44
- it("normalizes assistant message with text block", () => {
45
- const result = normalizeSdkMessage({
46
- type: "assistant",
47
- message: { content: [{ type: "text", text: "Hello world" }] },
48
- });
49
- expect(result).not.toBeNull();
50
- expect(result!.type).toBe("assistant");
51
- expect(result!.blocks).toEqual([{ type: "text", text: "Hello world" }]);
52
- });
53
-
54
- it("normalizes assistant message with thinking block", () => {
55
- const result = normalizeSdkMessage({
56
- type: "assistant",
57
- message: { content: [{ type: "thinking", thinking: "Let me analyze..." }] },
58
- });
59
- expect(result).not.toBeNull();
60
- expect(result!.blocks).toEqual([{ type: "thinking", thinking: "Let me analyze..." }]);
61
- });
62
-
63
- it("normalizes assistant message with tool_use block", () => {
64
- const result = normalizeSdkMessage({
65
- type: "assistant",
66
- message: {
67
- content: [{ type: "tool_use", name: "Read", input: { file_path: "/tmp/test.txt" } }],
68
- },
69
- });
70
- expect(result).not.toBeNull();
71
- expect(result!.blocks).toEqual([
72
- { type: "tool_use", name: "Read", input: { file_path: "/tmp/test.txt" } },
73
- ]);
74
- });
75
-
76
- it('uses "unknown" for tool_use without name', () => {
77
- const result = normalizeSdkMessage({
78
- type: "assistant",
79
- message: { content: [{ type: "tool_use", input: { x: 1 } }] },
80
- });
81
- expect(result!.blocks[0]).toMatchObject({ type: "tool_use", name: "unknown" });
82
- });
83
-
84
- it("normalizes user message with tool_result block (success)", () => {
85
- const result = normalizeSdkMessage({
86
- type: "user",
87
- message: {
88
- content: [
89
- { type: "tool_result", tool_use_id: "abc123", content: "file content here", is_error: false },
90
- ],
91
- },
92
- });
93
- expect(result).not.toBeNull();
94
- expect(result!.type).toBe("user");
95
- const block = result!.blocks[0] as any;
96
- expect(block.type).toBe("tool_result");
97
- expect(block.tool_use_id).toBe("abc123");
98
- expect(block.content).toBe("file content here");
99
- expect(block.is_error).toBe(false);
100
- });
101
-
102
- it("normalizes user message with tool_result block (error)", () => {
103
- const result = normalizeSdkMessage({
104
- type: "user",
105
- message: {
106
- content: [
107
- { type: "tool_result", tool_use_id: "err456", content: "permission denied", is_error: true },
108
- ],
109
- },
110
- });
111
- expect(result!.blocks[0]).toMatchObject({
112
- type: "tool_result",
113
- tool_use_id: "err456",
114
- is_error: true,
115
- });
116
- });
117
-
118
- it("normalizes tool_result with array content", () => {
119
- const content = [{ type: "text", text: "line 1" }, { type: "text", text: "line 2" }];
120
- const result = normalizeSdkMessage({
121
- type: "user",
122
- message: { content: [{ type: "tool_result", tool_use_id: "arr", content }] },
123
- });
124
- expect(result!.blocks[0]).toMatchObject({
125
- type: "tool_result",
126
- tool_use_id: "arr",
127
- });
128
- expect((result!.blocks[0] as any).content).toEqual(content);
129
- });
130
-
131
- it("normalizes redacted_thinking block", () => {
132
- const result = normalizeSdkMessage({
133
- type: "assistant",
134
- message: { content: [{ type: "redacted_thinking" }] },
135
- });
136
- expect(result!.blocks).toEqual([{ type: "redacted_thinking" }]);
137
- });
138
-
139
- it("normalizes search_result block", () => {
140
- const result = normalizeSdkMessage({
141
- type: "assistant",
142
- message: {
143
- content: [{ type: "search_result", query: "TypeScript best practices" }],
144
- },
145
- });
146
- expect(result!.blocks).toEqual([
147
- { type: "search_result", query: "TypeScript best practices" },
148
- ]);
149
- });
150
-
151
- it("normalizes search_result without query (empty string)", () => {
152
- const result = normalizeSdkMessage({
153
- type: "assistant",
154
- message: { content: [{ type: "search_result" }] },
155
- });
156
- expect(result!.blocks).toEqual([{ type: "search_result", query: "" }]);
157
- });
158
-
159
- // --- system messages ---
160
-
161
- it("normalizes system compact_boundary message", () => {
162
- const result = normalizeSdkMessage({
163
- type: "system",
164
- subtype: "compact_boundary",
165
- compact_metadata: {
166
- trigger: "auto",
167
- pre_tokens: 15000,
168
- post_tokens: 8000,
169
- },
170
- });
171
- expect(result).not.toBeNull();
172
- expect(result!.type).toBe("system");
173
- expect(result!.blocks).toEqual([
174
- { type: "compact_boundary", trigger: "auto", pre_tokens: 15000, post_tokens: 8000 },
175
- ]);
176
- });
177
-
178
- it("normalizes compact_boundary with manual trigger", () => {
179
- const result = normalizeSdkMessage({
180
- type: "system",
181
- subtype: "compact_boundary",
182
- compact_metadata: { trigger: "manual", pre_tokens: 20000 },
183
- });
184
- expect(result!.blocks).toEqual([
185
- { type: "compact_boundary", trigger: "manual", pre_tokens: 20000, post_tokens: undefined },
186
- ]);
187
- });
188
-
189
- it("normalizes compact_boundary without post_tokens", () => {
190
- const result = normalizeSdkMessage({
191
- type: "system",
192
- subtype: "compact_boundary",
193
- compact_metadata: { trigger: "auto", pre_tokens: 10000 },
194
- });
195
- expect(result!.blocks).toEqual([
196
- { type: "compact_boundary", trigger: "auto", pre_tokens: 10000, post_tokens: undefined },
197
- ]);
198
- });
199
-
200
- // --- mixed blocks ---
201
-
202
- it("normalizes message with multiple block types mixed", () => {
203
- const result = normalizeSdkMessage({
204
- type: "assistant",
205
- message: {
206
- content: [
207
- { type: "thinking", thinking: "Hmm..." },
208
- { type: "tool_use", name: "Grep", input: { pattern: "foo" } },
209
- { type: "text", text: "Found it." },
210
- ],
211
- },
212
- });
213
- expect(result).not.toBeNull();
214
- expect(result!.blocks).toHaveLength(3);
215
- expect(result!.blocks[0]).toEqual({ type: "thinking", thinking: "Hmm..." });
216
- expect(result!.blocks[1]).toEqual({ type: "tool_use", name: "Grep", input: { pattern: "foo" } });
217
- expect(result!.blocks[2]).toEqual({ type: "text", text: "Found it." });
218
- });
219
-
220
- // --- edge cases ---
221
-
222
- it("skips unknown block types", () => {
223
- const result = normalizeSdkMessage({
224
- type: "assistant",
225
- message: {
226
- content: [
227
- { type: "unknown_type", data: "whatever" },
228
- { type: "text", text: "still here" },
229
- ],
230
- },
231
- });
232
- expect(result!.blocks).toHaveLength(1);
233
- expect(result!.blocks[0]).toEqual({ type: "text", text: "still here" });
234
- });
235
-
236
- it("returns null for non-assistant/non-user/non-system messages", () => {
237
- expect(
238
- normalizeSdkMessage({ type: "result", subtype: "success" }),
239
- ).toBeNull();
240
- expect(
241
- normalizeSdkMessage({ type: "stream_event" }),
242
- ).toBeNull();
243
- expect(
244
- normalizeSdkMessage({ type: "status" }),
245
- ).toBeNull();
246
- });
247
-
248
- it("returns null for system message without compact_boundary subtype", () => {
249
- expect(
250
- normalizeSdkMessage({ type: "system", subtype: "init" }),
251
- ).toBeNull();
252
- expect(
253
- normalizeSdkMessage({ type: "system", subtype: "notification" }),
254
- ).toBeNull();
255
- });
256
-
257
- it("returns message with empty blocks for content=[ ]", () => {
258
- const result = normalizeSdkMessage({
259
- type: "assistant",
260
- message: { content: [] },
261
- });
262
- expect(result).not.toBeNull();
263
- expect(result!.blocks).toEqual([]);
264
- });
265
-
266
- it("returns null for message without content", () => {
267
- const result = normalizeSdkMessage({
268
- type: "assistant",
269
- message: {},
270
- });
271
- expect(result).toBeNull();
272
- });
273
-
274
- it("returns null for message with null content array", () => {
275
- const result = normalizeSdkMessage({
276
- type: "assistant",
277
- message: { content: undefined as any },
278
- });
279
- expect(result).toBeNull();
280
- });
281
-
282
- it("returns null for compact_boundary without metadata", () => {
283
- const result = normalizeSdkMessage({
284
- type: "system",
285
- subtype: "compact_boundary",
286
- });
287
- expect(result).toBeNull();
288
- });
289
-
290
- it("skips thinking block with empty thinking string", () => {
291
- const result = normalizeSdkMessage({
292
- type: "assistant",
293
- message: { content: [{ type: "thinking", thinking: "" }] },
294
- });
295
- // empty thinking string → falsy check (block.thinking → "") → skipped
296
- expect(result!.blocks).toEqual([]);
297
- });
298
-
299
- it("skips text block with empty text string", () => {
300
- const result = normalizeSdkMessage({
301
- type: "assistant",
302
- message: { content: [{ type: "text", text: "" }] },
303
- });
304
- // empty text string → falsy check → skipped
305
- expect(result!.blocks).toEqual([]);
306
- });
307
-
308
- it("handles message with undefined type gracefully", () => {
309
- const result = normalizeSdkMessage({
310
- message: { content: [{ type: "text", text: "orphan" }] },
311
- });
312
- expect(result).toBeNull();
313
- });
314
- });
315
-
316
- // ---------------------------------------------------------------------------
317
- // createClaudeAdapter — 集成测试(mock SDK)
318
- // ---------------------------------------------------------------------------
319
-
320
- describe("createClaudeAdapter", () => {
321
- let sdk: any;
322
-
323
- beforeEach(async () => {
324
- vi.clearAllMocks();
325
- sdk = await import("@anthropic-ai/claude-agent-sdk");
326
- });
327
-
328
- it("returns adapter with correct displayName and sessionDescPrefix", () => {
329
- const adapter = createClaudeAdapter({
330
- model: "claude-sonnet-4-6",
331
- effort: "high",
332
- isEmpty: (v) => v.trim() === "",
333
- });
334
- expect(adapter.displayName).toBe("Claude Code");
335
- expect(adapter.sessionDescPrefix).toBe("Claude Code Session:");
336
- });
337
-
338
- it("createSession returns sessionId from init event", async () => {
339
- const mockSessionObj = mockSession({
340
- streamNext: vi
341
- .fn()
342
- .mockResolvedValueOnce({
343
- done: false,
344
- value: { session_id: "test-sid-001", type: "system", subtype: "init" },
345
- })
346
- .mockResolvedValueOnce({ done: true, value: undefined }),
347
- });
348
- sdk.unstable_v2_createSession.mockReturnValue(mockSessionObj);
349
-
350
- const adapter = createClaudeAdapter({
351
- model: "claude-sonnet-4-6",
352
- effort: "high",
353
- isEmpty: () => false,
354
- });
355
-
356
- const result = await adapter.createSession("/tmp");
357
- expect(result.sessionId).toBe("test-sid-001");
358
- expect(sdk.unstable_v2_createSession).toHaveBeenCalledTimes(1);
359
- });
360
-
361
- it("createSession throws when first event has no session_id", async () => {
362
- const mockSessionObj = mockSession({
363
- streamNext: vi
364
- .fn()
365
- .mockResolvedValueOnce({
366
- done: false,
367
- value: { type: "other", no_session_id: true },
368
- }),
369
- });
370
- sdk.unstable_v2_createSession.mockReturnValue(mockSessionObj);
371
-
372
- const adapter = createClaudeAdapter({
373
- model: "claude-sonnet-4-6",
374
- effort: "high",
375
- isEmpty: () => false,
376
- });
377
-
378
- await expect(adapter.createSession("/tmp")).rejects.toThrow(
379
- "No session ID",
380
- );
381
- });
382
-
383
- it("createSession sends 'ok' to the session", async () => {
384
- const sendSpy = vi.fn();
385
- const mockSessionObj = mockSession({
386
- send: sendSpy,
387
- streamNext: vi
388
- .fn()
389
- .mockResolvedValueOnce({
390
- done: false,
391
- value: { session_id: "sid", type: "system", subtype: "init" },
392
- })
393
- .mockResolvedValueOnce({ done: true, value: undefined }),
394
- });
395
- sdk.unstable_v2_createSession.mockReturnValue(mockSessionObj);
396
-
397
- const adapter = createClaudeAdapter({
398
- model: "claude-sonnet-4-6",
399
- effort: "high",
400
- isEmpty: () => false,
401
- });
402
-
403
- await adapter.createSession("/tmp");
404
- expect(sendSpy).toHaveBeenCalledWith("ok");
405
- });
406
-
407
- it("prompt yields normalized messages", async () => {
408
- const mockSessionObj = mockSession({
409
- streamNext: (() => {
410
- let callCount = 0;
411
- return vi.fn(async () => {
412
- callCount++;
413
- if (callCount === 1) {
414
- return {
415
- done: false,
416
- value: {
417
- type: "assistant",
418
- message: { content: [{ type: "text", text: "Hello!" }] },
419
- },
420
- };
421
- }
422
- return { done: true, value: undefined };
423
- });
424
- })(),
425
- });
426
- sdk.unstable_v2_resumeSession.mockReturnValue(mockSessionObj);
427
-
428
- const adapter = createClaudeAdapter({
429
- model: "claude-sonnet-4-6",
430
- effort: "high",
431
- isEmpty: () => false,
432
- });
433
-
434
- const messages: UnifiedStreamMessage[] = [];
435
- for await (const msg of adapter.prompt("sid", "hi", "/tmp")) {
436
- messages.push(msg);
437
- }
438
-
439
- expect(messages).toHaveLength(1);
440
- expect(messages[0].type).toBe("assistant");
441
- expect(messages[0].blocks).toEqual([{ type: "text", text: "Hello!" }]);
442
- expect(sdk.unstable_v2_resumeSession).toHaveBeenCalledTimes(1);
443
- });
444
-
445
- it("prompt handles AbortSignal", async () => {
446
- const mockSessionObj = mockSession({
447
- streamNext: vi
448
- .fn()
449
- .mockResolvedValueOnce({
450
- done: false,
451
- value: {
452
- type: "assistant",
453
- message: { content: [{ type: "text", text: "msg1" }] },
454
- },
455
- })
456
- .mockResolvedValueOnce({
457
- done: false,
458
- value: {
459
- type: "assistant",
460
- message: { content: [{ type: "text", text: "msg2" }] },
461
- },
462
- })
463
- .mockResolvedValue({ done: true, value: undefined }),
464
- });
465
- sdk.unstable_v2_resumeSession.mockReturnValue(mockSessionObj);
466
-
467
- const controller = new AbortController();
468
- const adapter = createClaudeAdapter({
469
- model: "claude-sonnet-4-6",
470
- effort: "high",
471
- isEmpty: () => false,
472
- });
473
-
474
- const messages: UnifiedStreamMessage[] = [];
475
- for await (const msg of adapter.prompt("sid", "hi", "/tmp", controller.signal)) {
476
- messages.push(msg);
477
- if (messages.length === 1) controller.abort();
478
- }
479
-
480
- // Should only get the first message before abort stops iteration
481
- expect(messages).toHaveLength(1);
482
- });
483
-
484
- it("getSessionInfo returns mapped SessionInfo", async () => {
485
- sdk.getSessionInfo.mockResolvedValue({
486
- sessionId: "sid",
487
- cwd: "/home/user",
488
- summary: "A test session",
489
- lastModified: 1234567890,
490
- });
491
-
492
- const adapter = createClaudeAdapter({
493
- model: "claude-sonnet-4-6",
494
- effort: "high",
495
- isEmpty: () => false,
496
- });
497
-
498
- const info = await adapter.getSessionInfo("sid");
499
- expect(info).toEqual({
500
- sessionId: "sid",
501
- cwd: "/home/user",
502
- summary: "A test session",
503
- lastModified: 1234567890,
504
- });
505
- });
506
-
507
- it("getSessionInfo returns undefined when SDK returns undefined", async () => {
508
- sdk.getSessionInfo.mockResolvedValue(undefined);
509
-
510
- const adapter = createClaudeAdapter({
511
- model: "claude-sonnet-4-6",
512
- effort: "high",
513
- isEmpty: () => false,
514
- });
515
-
516
- const info = await adapter.getSessionInfo("nonexistent");
517
- expect(info).toBeUndefined();
518
- });
519
-
520
- it("closeSession is no-op (does not throw)", async () => {
521
- const adapter = createClaudeAdapter({
522
- model: "claude-sonnet-4-6",
523
- effort: "high",
524
- isEmpty: () => false,
525
- });
526
-
527
- await expect(adapter.closeSession("any-sid")).resolves.toBeUndefined();
528
- });
529
- });
530
-
531
- // ---------------------------------------------------------------------------
532
- // createClaudeAdapter — sessionOpts 形状护栏
533
- // 这一组测试只断言 "调用 SDK 时传了什么"。任何对 buildSessionOptions / env
534
- // 注入逻辑的改动都应该让这组测试继续通过;如有意修改默认行为,请同步更新断言。
535
- // ---------------------------------------------------------------------------
536
-
537
- describe("createClaudeAdapter — sessionOpts 形状", () => {
538
- let sdk: any;
539
-
540
- /** 构造一个完成首次 init 即结束的 mock session,用于让 createSession 走完流程。 */
541
- function setupMockCreateSession(): void {
542
- const mockSessionObj = mockSession({
543
- streamNext: vi
544
- .fn()
545
- .mockResolvedValueOnce({
546
- done: false,
547
- value: { session_id: "sid", type: "system", subtype: "init" },
548
- })
549
- .mockResolvedValueOnce({ done: true, value: undefined }),
550
- });
551
- sdk.unstable_v2_createSession.mockReturnValue(mockSessionObj);
552
- }
553
-
554
- function setupMockResumeSession(): void {
555
- const mockSessionObj = mockSession({
556
- streamNext: vi
557
- .fn()
558
- .mockResolvedValueOnce({ done: true, value: undefined }),
559
- });
560
- sdk.unstable_v2_resumeSession.mockReturnValue(mockSessionObj);
561
- }
562
-
563
- beforeEach(async () => {
564
- vi.clearAllMocks();
565
- sdk = await import("@anthropic-ai/claude-agent-sdk");
566
- });
567
-
568
- it("createSession 把 cwd / 固定权限选项传给 SDK", async () => {
569
- setupMockCreateSession();
570
- const adapter = createClaudeAdapter({
571
- model: "claude-sonnet-4-6",
572
- effort: "high",
573
- isEmpty: () => false,
574
- });
575
-
576
- await adapter.createSession("/work/dir");
577
-
578
- const opts = sdk.unstable_v2_createSession.mock.calls[0][0];
579
- expect(opts).toMatchObject({
580
- cwd: "/work/dir",
581
- permissionMode: "bypassPermissions",
582
- allowDangerouslySkipPermissions: true,
583
- autoCompactEnabled: true,
584
- settingSources: ["user", "project", "local"],
585
- });
586
- });
587
-
588
- it("model / effort 非空时被传给 SDK", async () => {
589
- setupMockCreateSession();
590
- const adapter = createClaudeAdapter({
591
- model: "claude-sonnet-4-6",
592
- effort: "max",
593
- isEmpty: (v) => v.trim() === "",
594
- });
595
-
596
- await adapter.createSession("/cwd");
597
-
598
- const opts = sdk.unstable_v2_createSession.mock.calls[0][0];
599
- expect(opts.model).toBe("claude-sonnet-4-6");
600
- expect(opts.effort).toBe("max");
601
- });
602
-
603
- it("isEmpty(model) 为 true 时不传 model 字段", async () => {
604
- setupMockCreateSession();
605
- const adapter = createClaudeAdapter({
606
- model: "",
607
- effort: "high",
608
- isEmpty: (v) => v.trim() === "",
609
- });
610
-
611
- await adapter.createSession("/cwd");
612
-
613
- const opts = sdk.unstable_v2_createSession.mock.calls[0][0];
614
- expect(opts).not.toHaveProperty("model");
615
- expect(opts.effort).toBe("high");
616
- });
617
-
618
- it("isEmpty(effort) 为 true 时不传 effort 字段", async () => {
619
- setupMockCreateSession();
620
- const adapter = createClaudeAdapter({
621
- model: "claude-sonnet-4-6",
622
- effort: "",
623
- isEmpty: (v) => v.trim() === "",
624
- });
625
-
626
- await adapter.createSession("/cwd");
627
-
628
- const opts = sdk.unstable_v2_createSession.mock.calls[0][0];
629
- expect(opts.model).toBe("claude-sonnet-4-6");
630
- expect(opts).not.toHaveProperty("effort");
631
- });
632
-
633
- it("prompt() 也按相同规则构造 sessionOpts(resume 路径)", async () => {
634
- setupMockResumeSession();
635
- const adapter = createClaudeAdapter({
636
- model: "claude-sonnet-4-6",
637
- effort: "max",
638
- isEmpty: (v) => v.trim() === "",
639
- });
640
-
641
- const it_ = adapter.prompt("sid", "hi", "/resume/cwd");
642
- for await (const _ of it_) { /* drain */ }
643
-
644
- const opts = sdk.unstable_v2_resumeSession.mock.calls[0][1];
645
- expect(opts).toMatchObject({
646
- cwd: "/resume/cwd",
647
- permissionMode: "bypassPermissions",
648
- autoCompactEnabled: true,
649
- model: "claude-sonnet-4-6",
650
- effort: "max",
651
- });
652
- });
653
- });
654
-
655
- // ---------------------------------------------------------------------------
656
- // createClaudeAdapter — env 注入(apiKey / baseUrl 通过 SDK env 传递)
657
- // 行为契约:
658
- // - apiKey 或 baseUrl 任一非空(trim 后)→ 传 env,且 env 是 process.env
659
- // 的副本,并按需覆盖 ANTHROPIC_API_KEY / ANTHROPIC_BASE_URL;
660
- // 其余 process.env 字段保持不变。
661
- // - 两者都为空 → 完全不传 env 字段,让 SDK 走默认行为(即 process.env)。
662
- // - 主进程的 process.env 永不被修改(避免污染其他依赖于 env 的代码)。
663
- // ---------------------------------------------------------------------------
664
-
665
- describe("createClaudeAdapter — env 注入", () => {
666
- let sdk: any;
667
- const ORIGINAL_ENV = { ...process.env };
668
-
669
- function setupMockCreateSession(): void {
670
- const mockSessionObj = mockSession({
671
- streamNext: vi
672
- .fn()
673
- .mockResolvedValueOnce({
674
- done: false,
675
- value: { session_id: "sid", type: "system", subtype: "init" },
676
- })
677
- .mockResolvedValueOnce({ done: true, value: undefined }),
678
- });
679
- sdk.unstable_v2_createSession.mockReturnValue(mockSessionObj);
680
- }
681
-
682
- beforeEach(async () => {
683
- vi.clearAllMocks();
684
- sdk = await import("@anthropic-ai/claude-agent-sdk");
685
- // 确保每个用例从干净的 process.env 起步
686
- delete process.env.ANTHROPIC_API_KEY;
687
- delete process.env.ANTHROPIC_BASE_URL;
688
- delete process.env.ANTHROPIC_AUTH_TOKEN;
689
- delete process.env.CLAUDE_CODE_OAUTH_TOKEN;
690
- delete process.env.ANTHROPIC_MODEL;
691
- delete process.env.ANTHROPIC_DEFAULT_OPUS_MODEL;
692
- delete process.env.ANTHROPIC_DEFAULT_SONNET_MODEL;
693
- delete process.env.ANTHROPIC_DEFAULT_HAIKU_MODEL;
694
- delete process.env.CLAUDE_CODE_SUBAGENT_MODEL;
695
- delete process.env.CLAUDE_CODE_EFFORT_LEVEL;
696
- });
697
-
698
- // 用例之间清掉我们写入的 env,避免互相污染
699
- // (afterEach 等价物:vitest 在 beforeEach 里 reset 即可)
700
- afterAll(() => {
701
- process.env = { ...ORIGINAL_ENV };
702
- });
703
-
704
- it("apiKey / baseUrl 都为空时,不向 SDK 传 env 字段", async () => {
705
- setupMockCreateSession();
706
- const adapter = createClaudeAdapter({
707
- model: "claude-sonnet-4-6",
708
- effort: "high",
709
- isEmpty: (v) => v.trim() === "",
710
- apiKey: "",
711
- baseUrl: "",
712
- });
713
-
714
- await adapter.createSession("/cwd");
715
-
716
- const opts = sdk.unstable_v2_createSession.mock.calls[0][0];
717
- expect(opts).not.toHaveProperty("env");
718
- });
719
-
720
- it("apiKey / baseUrl 全空白同样视为空", async () => {
721
- setupMockCreateSession();
722
- const adapter = createClaudeAdapter({
723
- model: "claude-sonnet-4-6",
724
- effort: "high",
725
- isEmpty: (v) => v.trim() === "",
726
- apiKey: " ",
727
- baseUrl: "\t\n",
728
- });
729
-
730
- await adapter.createSession("/cwd");
731
-
732
- const opts = sdk.unstable_v2_createSession.mock.calls[0][0];
733
- expect(opts).not.toHaveProperty("env");
734
- });
735
-
736
- it("apiKey 非空 → 传 env 且覆盖 ANTHROPIC_API_KEY", async () => {
737
- setupMockCreateSession();
738
- process.env.SOME_OTHER = "keep-me";
739
- const adapter = createClaudeAdapter({
740
- model: "",
741
- effort: "",
742
- isEmpty: (v) => v.trim() === "",
743
- apiKey: "sk-test-key",
744
- baseUrl: "",
745
- });
746
-
747
- await adapter.createSession("/cwd");
748
-
749
- const opts = sdk.unstable_v2_createSession.mock.calls[0][0];
750
- expect(opts.env).toBeDefined();
751
- expect(opts.env.ANTHROPIC_API_KEY).toBe("sk-test-key");
752
- expect(opts.env.SOME_OTHER).toBe("keep-me");
753
-
754
- delete process.env.SOME_OTHER;
755
- });
756
-
757
- it("baseUrl 非空 → 传 env 且覆盖 ANTHROPIC_BASE_URL", async () => {
758
- setupMockCreateSession();
759
- const adapter = createClaudeAdapter({
760
- model: "",
761
- effort: "",
762
- isEmpty: (v) => v.trim() === "",
763
- apiKey: "",
764
- baseUrl: "https://api.deepseek.com/anthropic",
765
- });
766
-
767
- await adapter.createSession("/cwd");
768
-
769
- const opts = sdk.unstable_v2_createSession.mock.calls[0][0];
770
- expect(opts.env).toBeDefined();
771
- expect(opts.env.ANTHROPIC_BASE_URL).toBe("https://api.deepseek.com/anthropic");
772
- });
773
-
774
- it("apiKey + baseUrl 都设置 → 同时覆盖", async () => {
775
- setupMockCreateSession();
776
- const adapter = createClaudeAdapter({
777
- model: "",
778
- effort: "",
779
- isEmpty: (v) => v.trim() === "",
780
- apiKey: "sk-x",
781
- baseUrl: "https://gateway.example/anthropic",
782
- });
783
-
784
- await adapter.createSession("/cwd");
785
-
786
- const opts = sdk.unstable_v2_createSession.mock.calls[0][0];
787
- expect(opts.env.ANTHROPIC_API_KEY).toBe("sk-x");
788
- expect(opts.env.ANTHROPIC_BASE_URL).toBe("https://gateway.example/anthropic");
789
- });
790
-
791
- it("官方 API 模式下 subagentModel 不注入 env,也不覆盖 Claude 登录环境", async () => {
792
- setupMockCreateSession();
793
- process.env.CLAUDE_CODE_OAUTH_TOKEN = "oauth-from-login";
794
- const adapter = createClaudeAdapter({
795
- model: "claude-sonnet-4-6",
796
- subagentModel: "claude-haiku-4-5-20251001",
797
- effort: "",
798
- isEmpty: (v) => v.trim() === "",
799
- apiKey: "",
800
- baseUrl: "",
801
- });
802
-
803
- await adapter.createSession("/cwd");
804
-
805
- const opts = sdk.unstable_v2_createSession.mock.calls[0][0];
806
- expect(opts).not.toHaveProperty("env");
807
- });
808
-
809
- it("第三方 API 模式下 subagentModel 通过 CLAUDE_CODE_SUBAGENT_MODEL 覆盖 Haiku", async () => {
810
- setupMockCreateSession();
811
- process.env.CLAUDE_CODE_OAUTH_TOKEN = "oauth-from-login";
812
- const adapter = createClaudeAdapter({
813
- model: "claude-sonnet-4-6",
814
- subagentModel: "claude-haiku-4-5-20251001",
815
- effort: "",
816
- isEmpty: (v) => v.trim() === "",
817
- apiKey: "sk-thirdparty",
818
- baseUrl: "https://gateway.example/anthropic",
819
- });
820
-
821
- await adapter.createSession("/cwd");
822
-
823
- const opts = sdk.unstable_v2_createSession.mock.calls[0][0];
824
- expect(opts.model).toBe("claude-sonnet-4-6");
825
- expect(opts.env.ANTHROPIC_API_KEY).toBe("sk-thirdparty");
826
- expect(opts.env.CLAUDE_CODE_SUBAGENT_MODEL).toBe("claude-haiku-4-5-20251001");
827
- expect(opts.env.CLAUDE_CODE_OAUTH_TOKEN).toBeUndefined();
828
- });
829
-
830
- it("ChatCCC API config is isolated from Claude settings auth/model env", async () => {
831
- setupMockCreateSession();
832
- process.env.ANTHROPIC_AUTH_TOKEN = "token-from-claude-settings";
833
- process.env.CLAUDE_CODE_OAUTH_TOKEN = "oauth-from-claude-settings";
834
- process.env.ANTHROPIC_MODEL = "model-from-claude-settings";
835
- process.env.ANTHROPIC_DEFAULT_SONNET_MODEL = "sonnet-from-claude-settings";
836
- process.env.CLAUDE_CODE_SUBAGENT_MODEL = "subagent-from-claude-settings";
837
- process.env.CLAUDE_CODE_EFFORT_LEVEL = "max";
838
- const adapter = createClaudeAdapter({
839
- model: "chatccc-model",
840
- effort: "high",
841
- isEmpty: (v) => v.trim() === "",
842
- apiKey: "sk-chatccc",
843
- baseUrl: "https://chatccc-gateway.example/anthropic",
844
- });
845
-
846
- await adapter.createSession("/cwd");
847
-
848
- const opts = sdk.unstable_v2_createSession.mock.calls[0][0];
849
- expect(opts.env.ANTHROPIC_API_KEY).toBe("sk-chatccc");
850
- expect(opts.env.ANTHROPIC_BASE_URL).toBe("https://chatccc-gateway.example/anthropic");
851
- expect(opts.env.ANTHROPIC_AUTH_TOKEN).toBeUndefined();
852
- expect(opts.env.CLAUDE_CODE_OAUTH_TOKEN).toBeUndefined();
853
- expect(opts.env.ANTHROPIC_MODEL).toBeUndefined();
854
- expect(opts.env.ANTHROPIC_DEFAULT_SONNET_MODEL).toBeUndefined();
855
- expect(opts.env.CLAUDE_CODE_SUBAGENT_MODEL).toBeUndefined();
856
- expect(opts.env.CLAUDE_CODE_EFFORT_LEVEL).toBeUndefined();
857
- });
858
-
859
- it("第三方 API 配置时仍然加载 CLAUDE.md(settingSources 包含 user+project+local)", async () => {
860
- setupMockCreateSession();
861
- const adapter = createClaudeAdapter({
862
- model: "",
863
- effort: "",
864
- isEmpty: (v) => v.trim() === "",
865
- apiKey: "sk-chatccc",
866
- baseUrl: "https://chatccc-gateway.example/anthropic",
867
- });
868
-
869
- await adapter.createSession("/cwd");
870
-
871
- const opts = sdk.unstable_v2_createSession.mock.calls[0][0];
872
- expect(opts.settingSources).toEqual(["user", "project", "local"]);
873
- });
874
-
875
- it("不修改主进程 process.env(永不污染)", async () => {
876
- setupMockCreateSession();
877
- const before = { ...process.env };
878
-
879
- const adapter = createClaudeAdapter({
880
- model: "",
881
- effort: "",
882
- isEmpty: (v) => v.trim() === "",
883
- apiKey: "sk-should-not-leak",
884
- baseUrl: "https://should-not-leak/anthropic",
885
- });
886
-
887
- await adapter.createSession("/cwd");
888
-
889
- // 调用结束后 process.env 与调用前应保持一致
890
- expect(process.env.ANTHROPIC_API_KEY).toBe(before.ANTHROPIC_API_KEY);
891
- expect(process.env.ANTHROPIC_BASE_URL).toBe(before.ANTHROPIC_BASE_URL);
892
- });
893
-
894
- it("apiKey 留空但 process.env 已有 ANTHROPIC_API_KEY → 不覆盖、不抹掉", async () => {
895
- setupMockCreateSession();
896
- process.env.ANTHROPIC_API_KEY = "from-system-env";
897
- const adapter = createClaudeAdapter({
898
- model: "",
899
- effort: "",
900
- isEmpty: (v) => v.trim() === "",
901
- apiKey: "",
902
- baseUrl: "https://override.example/anthropic",
903
- });
904
-
905
- await adapter.createSession("/cwd");
906
-
907
- const opts = sdk.unstable_v2_createSession.mock.calls[0][0];
908
- // baseUrl 触发了 env 注入;apiKey 为空 → 沿用系统 env
909
- expect(opts.env.ANTHROPIC_API_KEY).toBe("from-system-env");
910
- expect(opts.env.ANTHROPIC_BASE_URL).toBe("https://override.example/anthropic");
911
- });
912
- });
1
+ import { describe, it, expect } from "vitest";
2
+ import { normalizeSdkMessage, createClaudeAdapter } from "../adapters/claude-adapter.ts";
3
+ import type { UnifiedStreamMessage } from "../adapters/adapter-interface.ts";
4
+ import type {
5
+ ClaudeSessionMeta,
6
+ ClaudeSessionMetaStore,
7
+ } from "../adapters/claude-session-meta-store.ts";
8
+
9
+ // ---------------------------------------------------------------------------
10
+ // 进程内内存版 meta store(测试用,避开磁盘 IO)
11
+ // ---------------------------------------------------------------------------
12
+
13
+ function createInMemoryMetaStore(
14
+ initial: Record<string, ClaudeSessionMeta> = {},
15
+ ): ClaudeSessionMetaStore & { snapshot(): Record<string, ClaudeSessionMeta> } {
16
+ const map = new Map<string, ClaudeSessionMeta>(Object.entries(initial));
17
+ return {
18
+ async get(sid) {
19
+ return map.get(sid);
20
+ },
21
+ async set(sid, partial) {
22
+ const existing = map.get(sid);
23
+ const merged: { cwd?: string; model?: string } = { ...existing };
24
+ if (typeof partial.cwd === "string" && partial.cwd.length > 0) merged.cwd = partial.cwd;
25
+ if (typeof partial.model === "string" && partial.model.length > 0) merged.model = partial.model;
26
+ if (!merged.cwd) return;
27
+ map.set(sid, merged.model ? { cwd: merged.cwd, model: merged.model } : { cwd: merged.cwd });
28
+ },
29
+ snapshot() {
30
+ return Object.fromEntries(map);
31
+ },
32
+ };
33
+ }
34
+
35
+ // ---------------------------------------------------------------------------
36
+ // normalizeSdkMessage — 核心映射逻辑测试(纯函数,CLI 与 SDK 格式相同)
37
+ // ---------------------------------------------------------------------------
38
+
39
+ describe("normalizeSdkMessage", () => {
40
+ // --- assistant messages ---
41
+
42
+ it("normalizes assistant message with text block", () => {
43
+ const result = normalizeSdkMessage({
44
+ type: "assistant",
45
+ message: { content: [{ type: "text", text: "Hello world" }] },
46
+ });
47
+ expect(result).not.toBeNull();
48
+ expect(result!.type).toBe("assistant");
49
+ expect(result!.blocks).toEqual([{ type: "text", text: "Hello world" }]);
50
+ });
51
+
52
+ it("normalizes assistant message with thinking block", () => {
53
+ const result = normalizeSdkMessage({
54
+ type: "assistant",
55
+ message: { content: [{ type: "thinking", thinking: "Let me analyze..." }] },
56
+ });
57
+ expect(result).not.toBeNull();
58
+ expect(result!.blocks).toEqual([{ type: "thinking", thinking: "Let me analyze..." }]);
59
+ });
60
+
61
+ it("normalizes assistant message with tool_use block", () => {
62
+ const result = normalizeSdkMessage({
63
+ type: "assistant",
64
+ message: {
65
+ content: [{ type: "tool_use", name: "Read", input: { file_path: "/tmp/test.txt" } }],
66
+ },
67
+ });
68
+ expect(result).not.toBeNull();
69
+ expect(result!.blocks).toEqual([
70
+ { type: "tool_use", name: "Read", input: { file_path: "/tmp/test.txt" } },
71
+ ]);
72
+ });
73
+
74
+ it('uses "unknown" for tool_use without name', () => {
75
+ const result = normalizeSdkMessage({
76
+ type: "assistant",
77
+ message: { content: [{ type: "tool_use", input: { x: 1 } }] },
78
+ });
79
+ expect(result!.blocks[0]).toMatchObject({ type: "tool_use", name: "unknown" });
80
+ });
81
+
82
+ it("normalizes user message with tool_result block (success)", () => {
83
+ const result = normalizeSdkMessage({
84
+ type: "user",
85
+ message: {
86
+ content: [
87
+ { type: "tool_result", tool_use_id: "abc123", content: "file content here", is_error: false },
88
+ ],
89
+ },
90
+ });
91
+ expect(result).not.toBeNull();
92
+ expect(result!.type).toBe("user");
93
+ const block = result!.blocks[0] as any;
94
+ expect(block.type).toBe("tool_result");
95
+ expect(block.tool_use_id).toBe("abc123");
96
+ expect(block.content).toBe("file content here");
97
+ expect(block.is_error).toBe(false);
98
+ });
99
+
100
+ it("normalizes user message with tool_result block (error)", () => {
101
+ const result = normalizeSdkMessage({
102
+ type: "user",
103
+ message: {
104
+ content: [
105
+ { type: "tool_result", tool_use_id: "err456", content: "permission denied", is_error: true },
106
+ ],
107
+ },
108
+ });
109
+ expect(result!.blocks[0]).toMatchObject({
110
+ type: "tool_result",
111
+ tool_use_id: "err456",
112
+ is_error: true,
113
+ });
114
+ });
115
+
116
+ it("normalizes tool_result with array content", () => {
117
+ const content = [{ type: "text", text: "line 1" }, { type: "text", text: "line 2" }];
118
+ const result = normalizeSdkMessage({
119
+ type: "user",
120
+ message: { content: [{ type: "tool_result", tool_use_id: "arr", content }] },
121
+ });
122
+ expect(result!.blocks[0]).toMatchObject({
123
+ type: "tool_result",
124
+ tool_use_id: "arr",
125
+ });
126
+ expect((result!.blocks[0] as any).content).toEqual(content);
127
+ });
128
+
129
+ it("skips text blocks in user messages (replayed input from --replay-user-messages)", () => {
130
+ // user 消息中的 text block 来自 --replay-user-messages 重放的用户输入
131
+ // (含内嵌的 IM skill prompt),不应出现在最终回复中
132
+ const result = normalizeSdkMessage({
133
+ type: "user",
134
+ message: {
135
+ content: [
136
+ { type: "text", text: "[ChatCCC IM skill: feishu-skill]\n...[/ChatCCC IM skill: feishu-skill]" },
137
+ { type: "tool_result", tool_use_id: "abc", content: "result" },
138
+ ],
139
+ },
140
+ });
141
+ expect(result).not.toBeNull();
142
+ expect(result!.type).toBe("user");
143
+ // text block 应被跳过,只保留 tool_result
144
+ expect(result!.blocks).toHaveLength(1);
145
+ expect(result!.blocks[0]).toMatchObject({ type: "tool_result", tool_use_id: "abc" });
146
+ });
147
+
148
+ it("returns null for user message with only text blocks (all skipped)", () => {
149
+ // 纯 user text 消息(无 tool_result)→ 全部跳过,不产生有效 blocks
150
+ const result = normalizeSdkMessage({
151
+ type: "user",
152
+ message: {
153
+ content: [{ type: "text", text: "some replayed user input" }],
154
+ },
155
+ });
156
+ // 此时 blocks 为空,但消息本身仍有 type,返回非 null 以保持流完整性
157
+ // 调用方 accumulateBlockContent 对空 blocks 是 no-op
158
+ expect(result).not.toBeNull();
159
+ expect(result!.blocks).toEqual([]);
160
+ });
161
+
162
+ it("normalizes redacted_thinking block", () => {
163
+ const result = normalizeSdkMessage({
164
+ type: "assistant",
165
+ message: { content: [{ type: "redacted_thinking" }] },
166
+ });
167
+ expect(result!.blocks).toEqual([{ type: "redacted_thinking" }]);
168
+ });
169
+
170
+ it("normalizes search_result block", () => {
171
+ const result = normalizeSdkMessage({
172
+ type: "assistant",
173
+ message: {
174
+ content: [{ type: "search_result", query: "TypeScript best practices" }],
175
+ },
176
+ });
177
+ expect(result!.blocks).toEqual([
178
+ { type: "search_result", query: "TypeScript best practices" },
179
+ ]);
180
+ });
181
+
182
+ it("normalizes search_result without query (empty string)", () => {
183
+ const result = normalizeSdkMessage({
184
+ type: "assistant",
185
+ message: { content: [{ type: "search_result" }] },
186
+ });
187
+ expect(result!.blocks).toEqual([{ type: "search_result", query: "" }]);
188
+ });
189
+
190
+ // --- system messages ---
191
+
192
+ it("normalizes system compact_boundary message", () => {
193
+ const result = normalizeSdkMessage({
194
+ type: "system",
195
+ subtype: "compact_boundary",
196
+ compact_metadata: {
197
+ trigger: "auto",
198
+ pre_tokens: 15000,
199
+ post_tokens: 8000,
200
+ },
201
+ });
202
+ expect(result).not.toBeNull();
203
+ expect(result!.type).toBe("system");
204
+ expect(result!.blocks).toEqual([
205
+ { type: "compact_boundary", trigger: "auto", pre_tokens: 15000, post_tokens: 8000 },
206
+ ]);
207
+ });
208
+
209
+ it("normalizes compact_boundary with manual trigger", () => {
210
+ const result = normalizeSdkMessage({
211
+ type: "system",
212
+ subtype: "compact_boundary",
213
+ compact_metadata: { trigger: "manual", pre_tokens: 20000 },
214
+ });
215
+ expect(result!.blocks).toEqual([
216
+ { type: "compact_boundary", trigger: "manual", pre_tokens: 20000, post_tokens: undefined },
217
+ ]);
218
+ });
219
+
220
+ it("normalizes compact_boundary without post_tokens", () => {
221
+ const result = normalizeSdkMessage({
222
+ type: "system",
223
+ subtype: "compact_boundary",
224
+ compact_metadata: { trigger: "auto", pre_tokens: 10000 },
225
+ });
226
+ expect(result!.blocks).toEqual([
227
+ { type: "compact_boundary", trigger: "auto", pre_tokens: 10000, post_tokens: undefined },
228
+ ]);
229
+ });
230
+
231
+ // --- mixed blocks ---
232
+
233
+ it("normalizes message with multiple block types mixed", () => {
234
+ const result = normalizeSdkMessage({
235
+ type: "assistant",
236
+ message: {
237
+ content: [
238
+ { type: "thinking", thinking: "Hmm..." },
239
+ { type: "tool_use", name: "Grep", input: { pattern: "foo" } },
240
+ { type: "text", text: "Found it." },
241
+ ],
242
+ },
243
+ });
244
+ expect(result).not.toBeNull();
245
+ expect(result!.blocks).toHaveLength(3);
246
+ expect(result!.blocks[0]).toEqual({ type: "thinking", thinking: "Hmm..." });
247
+ expect(result!.blocks[1]).toEqual({ type: "tool_use", name: "Grep", input: { pattern: "foo" } });
248
+ expect(result!.blocks[2]).toEqual({ type: "text", text: "Found it." });
249
+ });
250
+
251
+ // --- edge cases ---
252
+
253
+ it("skips unknown block types", () => {
254
+ const result = normalizeSdkMessage({
255
+ type: "assistant",
256
+ message: {
257
+ content: [
258
+ { type: "unknown_type", data: "whatever" },
259
+ { type: "text", text: "still here" },
260
+ ],
261
+ },
262
+ });
263
+ expect(result!.blocks).toHaveLength(1);
264
+ expect(result!.blocks[0]).toEqual({ type: "text", text: "still here" });
265
+ });
266
+
267
+ it("returns null for non-assistant/non-user/non-system messages", () => {
268
+ expect(
269
+ normalizeSdkMessage({ type: "result", subtype: "success" }),
270
+ ).toBeNull();
271
+ expect(
272
+ normalizeSdkMessage({ type: "stream_event" }),
273
+ ).toBeNull();
274
+ expect(
275
+ normalizeSdkMessage({ type: "status" }),
276
+ ).toBeNull();
277
+ });
278
+
279
+ it("returns null for system message without compact_boundary subtype", () => {
280
+ expect(
281
+ normalizeSdkMessage({ type: "system", subtype: "init" }),
282
+ ).toBeNull();
283
+ expect(
284
+ normalizeSdkMessage({ type: "system", subtype: "notification" }),
285
+ ).toBeNull();
286
+ });
287
+
288
+ it("returns message with empty blocks for content=[ ]", () => {
289
+ const result = normalizeSdkMessage({
290
+ type: "assistant",
291
+ message: { content: [] },
292
+ });
293
+ expect(result).not.toBeNull();
294
+ expect(result!.blocks).toEqual([]);
295
+ });
296
+
297
+ it("returns null for message without content", () => {
298
+ const result = normalizeSdkMessage({
299
+ type: "assistant",
300
+ message: {},
301
+ });
302
+ expect(result).toBeNull();
303
+ });
304
+
305
+ it("returns null for message with null content array", () => {
306
+ const result = normalizeSdkMessage({
307
+ type: "assistant",
308
+ message: { content: undefined as any },
309
+ });
310
+ expect(result).toBeNull();
311
+ });
312
+
313
+ it("returns null for compact_boundary without metadata", () => {
314
+ const result = normalizeSdkMessage({
315
+ type: "system",
316
+ subtype: "compact_boundary",
317
+ });
318
+ expect(result).toBeNull();
319
+ });
320
+
321
+ it("skips thinking block with empty thinking string", () => {
322
+ const result = normalizeSdkMessage({
323
+ type: "assistant",
324
+ message: { content: [{ type: "thinking", thinking: "" }] },
325
+ });
326
+ expect(result!.blocks).toEqual([]);
327
+ });
328
+
329
+ it("skips text block with empty text string", () => {
330
+ const result = normalizeSdkMessage({
331
+ type: "assistant",
332
+ message: { content: [{ type: "text", text: "" }] },
333
+ });
334
+ expect(result!.blocks).toEqual([]);
335
+ });
336
+
337
+ it("handles message with undefined type gracefully", () => {
338
+ const result = normalizeSdkMessage({
339
+ message: { content: [{ type: "text", text: "orphan" }] },
340
+ });
341
+ expect(result).toBeNull();
342
+ });
343
+ });
344
+
345
+ // ---------------------------------------------------------------------------
346
+ // createClaudeAdapter 工厂函数 + getSessionInfo / closeSession 测试
347
+ // ---------------------------------------------------------------------------
348
+
349
+ describe("createClaudeAdapter", () => {
350
+ it("returns adapter with correct displayName and sessionDescPrefix", () => {
351
+ const adapter = createClaudeAdapter({
352
+ model: "claude-sonnet-4-6",
353
+ effort: "high",
354
+ isEmpty: (v) => v.trim() === "",
355
+ });
356
+ expect(adapter.displayName).toBe("Claude Code");
357
+ expect(adapter.sessionDescPrefix).toBe("Claude Code Session:");
358
+ });
359
+
360
+ it("closeSession does not throw", async () => {
361
+ const adapter = createClaudeAdapter({
362
+ model: "claude-sonnet-4-6",
363
+ effort: "high",
364
+ isEmpty: () => false,
365
+ });
366
+ await expect(adapter.closeSession("any-sid")).resolves.toBeUndefined();
367
+ });
368
+
369
+ // -------------------------------------------------------------------------
370
+ // getSessionInfo 行为契约
371
+ // - cwd 决定 /git 是否可用
372
+ // - model 用于 /status、/sessions 显示
373
+ // -------------------------------------------------------------------------
374
+
375
+ it("getSessionInfo: store 中无该 sessionId 时只返回 sessionId", async () => {
376
+ const store = createInMemoryMetaStore();
377
+ const adapter = createClaudeAdapter({
378
+ model: "",
379
+ effort: "",
380
+ isEmpty: () => false,
381
+ metaStore: store,
382
+ });
383
+ const info = await adapter.getSessionInfo("unknown-sid");
384
+ expect(info).toEqual({ sessionId: "unknown-sid" });
385
+ expect(info?.cwd).toBeUndefined();
386
+ expect(info?.model).toBeUndefined();
387
+ });
388
+
389
+ it("getSessionInfo: store 仅有 cwd 时返回 cwd,model 仍为 undefined", async () => {
390
+ const store = createInMemoryMetaStore({ "sid-known": { cwd: "F:/proj/Foo" } });
391
+ const adapter = createClaudeAdapter({
392
+ model: "",
393
+ effort: "",
394
+ isEmpty: () => false,
395
+ metaStore: store,
396
+ });
397
+ const info = await adapter.getSessionInfo("sid-known");
398
+ expect(info).toEqual({ sessionId: "sid-known", cwd: "F:/proj/Foo" });
399
+ expect(info?.model).toBeUndefined();
400
+ });
401
+
402
+ it("getSessionInfo: store 同时有 cwd + model 时一并返回", async () => {
403
+ const store = createInMemoryMetaStore({
404
+ "sid-known": { cwd: "F:/proj/Foo", model: "claude-sonnet-4-6" },
405
+ });
406
+ const adapter = createClaudeAdapter({
407
+ model: "",
408
+ effort: "",
409
+ isEmpty: () => false,
410
+ metaStore: store,
411
+ });
412
+ const info = await adapter.getSessionInfo("sid-known");
413
+ expect(info).toEqual({
414
+ sessionId: "sid-known",
415
+ cwd: "F:/proj/Foo",
416
+ model: "claude-sonnet-4-6",
417
+ });
418
+ });
419
+
420
+ it("getSessionInfo: 不同 sessionId 互不影响", async () => {
421
+ const store = createInMemoryMetaStore({
422
+ "sid-A": { cwd: "/a", model: "mA" },
423
+ "sid-B": { cwd: "/b" },
424
+ });
425
+ const adapter = createClaudeAdapter({
426
+ model: "",
427
+ effort: "",
428
+ isEmpty: () => false,
429
+ metaStore: store,
430
+ });
431
+ expect(await adapter.getSessionInfo("sid-A")).toEqual({
432
+ sessionId: "sid-A",
433
+ cwd: "/a",
434
+ model: "mA",
435
+ });
436
+ expect(await adapter.getSessionInfo("sid-B")).toEqual({
437
+ sessionId: "sid-B",
438
+ cwd: "/b",
439
+ });
440
+ expect(await adapter.getSessionInfo("sid-C")).toEqual({ sessionId: "sid-C" });
441
+ });
442
+ });