File size: 25,804 Bytes
4e23b01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
/**
 * Self-tests for `DaemonClient` against a live server at
 * `process.env.KIMI_SERVER_URL ?? http://127.0.0.1:58627`.
 *
 * Every test gates on a `daemonReachable()` check so CI / dev machines
 * without a running server stay green. Run a server (`pnpm dev:server` from
 * repo root) to exercise these locally.
 *
 * Coverage:
 *   1. HTTP envelope unwrap throws on `code !== 0`.
 *   2. WS handshake completes (server_hello + client_hello ack).
 *   3. Subscribe ack succeeds for a real session id.
 *   4. `waitForFrame` times out cleanly (no zombie waiters).
 *   5. Created session is observable via `getSession`.
 */
import { afterEach, describe, expect, it } from 'vitest';

import type { FileMeta } from '@moonshot-ai/agent-core-v2/app/file/fileService';
import type {
  ModelCatalogItem,
  ProviderCatalogItem,
} from '@moonshot-ai/agent-core-v2/llm-adapter/model/catalog';
import { ErrorCode } from '@moonshot-ai/kap-server/protocol/error-codes';
import type { Message } from '@moonshot-ai/kap-server/protocol/message';
import type { SessionStatusResponse } from '@moonshot-ai/kap-server/protocol/rest-session';
import type { Session } from '@moonshot-ai/kap-server/protocol/session';

import { DaemonClient, EnvelopeError } from '../harness/index.js';
import { fetchWithReport } from '../harness/report.js';
import { createCaseLogger, errorForLog } from './log.js';

const BASE_URL = process.env['KIMI_SERVER_URL'] ?? 'http://127.0.0.1:58627';
const PROMPT_TIMEOUT_MS = 120_000;

async function daemonReachable(): Promise<boolean> {
  try {
    const res = await fetchWithReport(`${BASE_URL}/api/v1/meta`, {
      signal: AbortSignal.timeout(500),
    });
    return res.ok;
  } catch {
    return false;
  }
}

const reachable = await daemonReachable();
const describeLive = reachable ? describe : describe.skip;

let created: { client: DaemonClient; sid: string }[] = [];

afterEach(async () => {
  // Best-effort cleanup so reruns don't accumulate phantom sessions.
  for (const { client, sid } of created.splice(0)) {
    try {
      await client.archiveSession(sid);
    } catch {
      // ignore
    }
    try {
      await client.close();
    } catch {
      // ignore
    }
  }
});

describeLive('DaemonClient (live server required)', () => {
  it('throws EnvelopeError on code !== 0', async () => {
    const log = createCaseLogger('client: missing session envelope');
    const client = new DaemonClient({ baseUrl: BASE_URL });
    const sid = 'sess_does_not_exist_xxxxxxxx';
    log('request', { method: 'GET', path: `/api/v1/sessions/${sid}` });

    let caughtError: unknown;
    try {
      await client.getSession(sid);
    } catch (error) {
      caughtError = error;
    }
    if (caughtError === undefined) {
      throw new Error('expected getSession to reject for a missing session');
    }
    log('error response', errorForLog(caughtError));
    expect(caughtError).toBeInstanceOf(EnvelopeError);
  });

  it('completes handshake (server_hello + client_hello ack)', async () => {
    const log = createCaseLogger('client: ws handshake');
    const client = new DaemonClient({ baseUrl: BASE_URL });
    log('connect request', { url: `${BASE_URL.replace(/^http/, 'ws')}/api/v1/ws` });
    const hello = await client.connect();
    log('server hello', hello);
    // heartbeat_ms is optional — kap-server omits it (no server heartbeat).
    expect(hello.heartbeat_ms === undefined || hello.heartbeat_ms > 0).toBe(true);
    expect(typeof hello.ws_connection_id).toBe('string');
    await client.close();
    log('closed');
  });

  it('subscribes to a real session id', async () => {
    const log = createCaseLogger('client: subscribe real session');
    const client = new DaemonClient({ baseUrl: BASE_URL });
    const session = await client.createSession({ metadata: { cwd: process.cwd() } });
    created.push({ client, sid: session.id });
    log('created session', session);
    await client.connect();
    log('subscribe request', { type: 'subscribe', session_ids: [session.id] });
    await expect(client.subscribe(session.id)).resolves.toBeUndefined();
    log('subscribe accepted', { session_id: session.id });
  });

  it('waitForFrame times out cleanly', async () => {
    const log = createCaseLogger('client: waitForFrame timeout');
    const client = new DaemonClient({ baseUrl: BASE_URL });
    await client.connect();
    log('wait request', { frame_type: 'event.does.not.exist', timeout_ms: 100 });
    let caughtError: unknown;
    try {
      await client.waitForFrame((f) => f.type === 'event.does.not.exist', { timeoutMs: 100 });
    } catch (error) {
      caughtError = error;
    }
    if (caughtError === undefined) {
      throw new Error('expected waitForFrame to time out');
    }
    log('timeout error', errorForLog(caughtError));
    expect(caughtError).toBeInstanceOf(Error);
    expect((caughtError as Error).message).toMatch(/waitForFrame timed out/);
    await client.close();
    log('closed');
  });

  it('created session is readable via getSession', async () => {
    const log = createCaseLogger('client: getSession round trip');
    const client = new DaemonClient({ baseUrl: BASE_URL });
    const session = await client.createSession({ metadata: { cwd: process.cwd() } });
    created.push({ client, sid: session.id });
    log('created session', session);
    const fetched = await client.getSession(session.id);
    log('fetched session', fetched);
    expect(fetched.id).toBe(session.id);
    expect(fetched.metadata.cwd).toBe(process.cwd());
  });

  it('forks a session through the action-suffix route', async () => {
    const log = createCaseLogger('client: fork action');
    const client = new DaemonClient({ baseUrl: BASE_URL });
    const source = await client.createSession({
      title: 'Source session',
      metadata: { cwd: process.cwd(), source: true },
    });
    created.push({ client, sid: source.id });
    log('source session', source);

    const forkRequest = {
      metadata: { child: true },
    };
    log('request', {
      method: 'POST',
      path: `/api/v1/sessions/${source.id}:fork`,
      body: forkRequest,
    });

    const fork = await client.forkSession(source.id, forkRequest);
    created.push({ client, sid: fork.id });
    log('response', fork);

    expect(fork.id).not.toBe(source.id);
    expect(fork.title).toBe('Fork: Source session');
    expect(fork.metadata).toMatchObject({
      cwd: process.cwd(),
      source: true,
      child: true,
    });

    const fetched = await client.getSession(fork.id);
    log('fetched fork session', fetched);
    expect(fetched.id).toBe(fork.id);
  });

  it(
    'compactSession prints empty-history errors and compacted history content',
    async () => {
      const log = createCaseLogger('client: compact empty history');
      const client = new DaemonClient({ baseUrl: BASE_URL });
      const session = await client.createSession({ metadata: { cwd: process.cwd() } });
      created.push({ client, sid: session.id });
      log('source session', session);

      const compactRequest = { instruction: '  focus on decisions  ' };
      log('request', {
        method: 'POST',
        path: `/api/v1/sessions/${session.id}:compact`,
        body: compactRequest,
      });

      let compactError: unknown;
      try {
        const result = await client.compactSession(session.id, compactRequest);
        log('response', result);
      } catch (error) {
        compactError = error;
      }
      if (compactError === undefined) {
        throw new Error('expected compactSession to reject for an empty-history session');
      }
      log('error response', errorForLog(compactError));

      expect(compactError).toMatchObject({
        code: ErrorCode.COMPACTION_UNABLE,
        reason: 'compaction.unable',
        data: null,
      });

      const successLog = createCaseLogger('client: compact populated history');
      const populated = await client.createSession({ metadata: { cwd: process.cwd() } });
      created.push({ client, sid: populated.id });
      successLog('source session', populated);

      await client.connect();
      await client.subscribe(populated.id);
      successLog('subscribe accepted', { session_id: populated.id });

      const promptResult = await client.submitAndWait(
        populated.id,
        {
          content: [
            {
              type: 'text',
              text: 'Remember this compact-test fact: the code word is BLUE. Reply with "OK".',
            },
          ],
        },
        { waitFor: 'prompt.completed', timeoutMs: PROMPT_TIMEOUT_MS },
      );
      successLog('seed prompt completed', {
        prompt_id: promptResult.prompt_id,
        user_message_id: promptResult.user_message_id,
        final_frame: frameForLog(promptResult.finalFrame),
      });

      const beforeCompact = await client.listMessages(populated.id, { page_size: 100 });
      successLog('messages before compact', beforeCompact);
      expect(beforeCompact.items.some((m) => m.role === 'user')).toBe(true);
      expect(beforeCompact.items.some((m) => m.role === 'assistant')).toBe(true);

      const populatedCompactRequest = {
        instruction: 'Preserve the compact-test code word and the fact that the assistant replied OK.',
      };
      successLog('request', {
        method: 'POST',
        path: `/api/v1/sessions/${populated.id}:compact`,
        body: populatedCompactRequest,
      });

      const completedPromise = client.waitForFrame(
        (f) => f.type === 'compaction.completed' && f.session_id === populated.id,
        { timeoutMs: PROMPT_TIMEOUT_MS },
      );
      const compactResponse = await client.compactSession(populated.id, populatedCompactRequest);
      successLog('rest response', compactResponse);
      const completedFrame = await completedPromise;
      successLog('compaction completed frame', frameForLog(completedFrame));

      const afterCompact = await client.listMessages(populated.id, { page_size: 100 });
      successLog('messages after compact', afterCompact);

      const compactedText = afterCompact.items
        .flatMap((m) => m.content)
        .filter((part) => part.type === 'text')
        .map((part) => part.text)
        .join('\n');
      successLog('compacted text content', { text: compactedText });

      expect(afterCompact.items.length).toBeGreaterThan(0);
      expect(compactedText.length).toBeGreaterThan(0);
    },
    PROMPT_TIMEOUT_MS + 30_000,
  );

  it(
    'undoSession removes the latest prompt and returns refreshed messages plus status',
    async () => {
      const log = createCaseLogger('client: undo action');
      const client = new DaemonClient({ baseUrl: BASE_URL });
      const session = await client.createSession({ metadata: { cwd: process.cwd() } });
      created.push({ client, sid: session.id });
      log('source session', session);

      await client.connect();
      await client.subscribe(session.id);
      log('subscribe accepted', { session_id: session.id });

      const keepPrompt = await client.submitAndWait(
        session.id,
        { content: [{ type: 'text', text: 'Remember KEEP. Reply with "OK".' }] },
        { waitFor: 'prompt.completed', timeoutMs: PROMPT_TIMEOUT_MS },
      );
      log('keep prompt completed', {
        prompt_id: keepPrompt.prompt_id,
        user_message_id: keepPrompt.user_message_id,
        final_frame: frameForLog(keepPrompt.finalFrame),
      });

      const undoPrompt = await client.submitAndWait(
        session.id,
        { content: [{ type: 'text', text: 'Remember UNDO-ME. Reply with "OK".' }] },
        { waitFor: 'prompt.completed', timeoutMs: PROMPT_TIMEOUT_MS },
      );
      log('undo prompt completed', {
        prompt_id: undoPrompt.prompt_id,
        user_message_id: undoPrompt.user_message_id,
        final_frame: frameForLog(undoPrompt.finalFrame),
      });

      const beforeUndo = await client.listMessages(session.id, { page_size: 100 });
      log('messages before undo', beforeUndo);
      expect(textFromMessages(beforeUndo.items)).toContain('UNDO-ME');

      const result = await client.undoSession(session.id, { count: 1, page_size: 100 });
      log('undo response', result);

      const afterText = textFromMessages(result.messages.items);
      expect(afterText).toContain('KEEP');
      expect(afterText).not.toContain('UNDO-ME');
      expect(result.messages.has_more).toBe(false);
      expect(result.status.context_tokens).toBeGreaterThanOrEqual(0);
    },
    PROMPT_TIMEOUT_MS * 2 + 30_000,
  );
});

describe('DaemonClient session action helpers', () => {
  it('forkSession posts the action-suffix route and unwraps the returned session', async () => {
    const log = createCaseLogger('client helper: forkSession');
    const calls: FetchCall[] = [];
    const fork = testSession({ id: 'sess_fork', title: 'Fork: Source session' });
    const client = new DaemonClient({
      baseUrl: 'http://server.example.test',
      fetchImpl: recordingFetch(okEnvelope(fork), calls),
    });

    const result = await client.forkSession('sess_source', {
      title: 'Custom fork',
      metadata: { child: true },
    });

    log('fetch calls', calls);
    log('unwrapped result', result);
    expect(result).toEqual(fork);
    expect(calls).toHaveLength(1);
    expect(calls[0]?.url).toBe('http://server.example.test/api/v1/sessions/sess_source:fork');
    expect(calls[0]?.init.method).toBe('POST');
    expect(parseRecordedJsonBody(calls[0])).toEqual({
      title: 'Custom fork',
      metadata: { child: true },
    });
  });

  it('compactSession posts the action-suffix route and preserves error envelope details', async () => {
    const log = createCaseLogger('client helper: compactSession');
    const calls: FetchCall[] = [];
    const client = new DaemonClient({
      baseUrl: 'http://server.example.test',
      fetchImpl: recordingFetch(
        {
          code: ErrorCode.COMPACTION_UNABLE,
          msg: 'No prefix can be compacted.',
          data: null,
          request_id: 'req_test',
        },
        calls,
      ),
    });

    let caughtError: unknown;
    try {
      await client.compactSession('sess_source', { instruction: '  focus on decisions  ' });
    } catch (error) {
      caughtError = error;
    }
    if (caughtError === undefined) {
      throw new Error('expected compactSession to reject for a non-zero envelope');
    }

    log('fetch calls', calls);
    log('error response', errorForLog(caughtError));
    expect(caughtError).toMatchObject({
      code: ErrorCode.COMPACTION_UNABLE,
      reason: 'compaction.unable',
      requestId: 'req_test',
      data: null,
    });

    expect(calls).toHaveLength(1);
    expect(calls[0]?.url).toBe('http://server.example.test/api/v1/sessions/sess_source:compact');
    expect(calls[0]?.init.method).toBe('POST');
    expect(parseRecordedJsonBody(calls[0])).toEqual({
      instruction: '  focus on decisions  ',
    });
  });

  it('undoSession posts the action-suffix route and unwraps messages plus status', async () => {
    const log = createCaseLogger('client helper: undoSession');
    const calls: FetchCall[] = [];
    const message = testMessage({ id: 'msg_kept', session_id: 'sess_source' });
    const undoResponse = {
      messages: { items: [message], has_more: false },
      status: testSessionStatus(),
    };
    const client = new DaemonClient({
      baseUrl: 'http://server.example.test',
      fetchImpl: recordingFetch(okEnvelope(undoResponse), calls),
    });

    const result = await client.undoSession('sess_source', { count: 2, page_size: 25 });

    log('fetch calls', calls);
    log('unwrapped result', result);
    expect(result).toEqual(undoResponse);
    expect(calls).toHaveLength(1);
    expect(calls[0]?.url).toBe('http://server.example.test/api/v1/sessions/sess_source:undo');
    expect(calls[0]?.init.method).toBe('POST');
    expect(parseRecordedJsonBody(calls[0])).toEqual({
      count: 2,
      page_size: 25,
    });
  });

  it('model catalog helpers call the catalog and action-suffix routes', async () => {
    const log = createCaseLogger('client helper: model catalog');
    const calls: FetchCall[] = [];
    const model = testModel({ model: 'kimi-code/kimi-for-coding' });
    const provider = testProvider({ id: 'kimi', models: [model.model] });
    const client = new DaemonClient({
      baseUrl: 'http://server.example.test',
      fetchImpl: recordingFetchSequence(
        [
          okEnvelope({
            models_ready: true,
            providers_count: 1,
            managed_provider: null,
          }),
          okEnvelope({ items: [model] }),
          okEnvelope({ default_model: model.model, model }),
          okEnvelope({ items: [provider] }),
          okEnvelope(provider),
        ],
        calls,
      ),
    });

    await expect(client.getAuth()).resolves.toMatchObject({ models_ready: true });
    await expect(client.listModels()).resolves.toEqual({ items: [model] });
    await expect(client.setDefaultModel(model.model)).resolves.toEqual({
      default_model: model.model,
      model,
    });
    await expect(client.listProviders()).resolves.toEqual({ items: [provider] });
    await expect(client.getProvider('kimi')).resolves.toEqual(provider);

    log('fetch calls', calls);
    expect(calls.map((call) => [call.init.method, call.url])).toEqual([
      ['GET', 'http://server.example.test/api/v1/auth'],
      ['GET', 'http://server.example.test/api/v1/models'],
      ['POST', 'http://server.example.test/api/v1/models/kimi-code%2Fkimi-for-coding:set_default'],
      ['GET', 'http://server.example.test/api/v1/providers'],
      ['GET', 'http://server.example.test/api/v1/providers/kimi'],
    ]);
    expect(parseRecordedJsonBody(calls[2])).toEqual({});
  });

  it('child-session and pending reverse-RPC helpers call recovery routes', async () => {
    const log = createCaseLogger('client helper: children + pending');
    const calls: FetchCall[] = [];
    const child = testSession({ id: 'sess_child', title: 'Child session' });
    const client = new DaemonClient({
      baseUrl: 'http://server.example.test',
      fetchImpl: recordingFetchSequence(
        [
          okEnvelope(child),
          okEnvelope({ items: [child], has_more: false }),
          okEnvelope({ items: [] }),
          okEnvelope({ items: [] }),
          okEnvelope({ dismissed: true, dismissed_at: '2026-06-09T00:00:00.000Z' }),
        ],
        calls,
      ),
    });

    await expect(
      client.createChild('sess_parent', {
        title: 'Child session',
        metadata: { topic: 'side-question' },
      }),
    ).resolves.toEqual(child);
    await expect(
      client.listChildren('sess_parent', { page_size: 5, busy: false }),
    ).resolves.toEqual({ items: [child], has_more: false });
    await expect(client.listPendingApprovals('sess_parent')).resolves.toEqual({ items: [] });
    await expect(client.listPendingQuestions('sess_parent')).resolves.toEqual({ items: [] });
    await expect(client.dismissQuestion('sess_parent', 'question_1')).resolves.toEqual({
      dismissed: true,
      dismissed_at: '2026-06-09T00:00:00.000Z',
    });

    log('fetch calls', calls);
    expect(calls.map((call) => [call.init.method, call.url])).toEqual([
      ['POST', 'http://server.example.test/api/v1/sessions/sess_parent/children'],
      ['GET', 'http://server.example.test/api/v1/sessions/sess_parent/children?page_size=5&busy=false'],
      ['GET', 'http://server.example.test/api/v1/sessions/sess_parent/approvals?status=pending'],
      ['GET', 'http://server.example.test/api/v1/sessions/sess_parent/questions?status=pending'],
      ['POST', 'http://server.example.test/api/v1/sessions/sess_parent/questions/question_1:dismiss'],
    ]);
    expect(parseRecordedJsonBody(calls[0])).toEqual({
      title: 'Child session',
      metadata: { topic: 'side-question' },
    });
    expect(parseRecordedJsonBody(calls[4])).toEqual({});
  });

  it('uploadFile posts multipart form data and deleteFile hits the file route', async () => {
    const log = createCaseLogger('client helper: file upload');
    const calls: FetchCall[] = [];
    const file = testFile({ id: 'file_png', name: 'tiny.png', media_type: 'image/png', size: 3 });
    const client = new DaemonClient({
      baseUrl: 'http://server.example.test',
      fetchImpl: recordingFetchSequence(
        [
          okEnvelope(file),
          okEnvelope({ deleted: true }),
        ],
        calls,
      ),
    });

    await expect(
      client.uploadFile({
        name: 'tiny.png',
        data: new Uint8Array([1, 2, 3]),
        mediaType: 'image/png',
        expiresInSec: 60,
      }),
    ).resolves.toEqual(file);
    await expect(client.deleteFile(file.id)).resolves.toEqual({ deleted: true });

    log('fetch calls', calls);
    expect(calls.map((call) => [call.init.method, call.url])).toEqual([
      ['POST', 'http://server.example.test/api/v1/files'],
      ['DELETE', 'http://server.example.test/api/v1/files/file_png'],
    ]);
    const form = calls[0]?.init.body;
    expect(form).toBeInstanceOf(FormData);
    const upload = form as FormData;
    expect(upload.get('name')).toBe('tiny.png');
    expect(upload.get('expires_in_sec')).toBe('60');
    const filePart = upload.get('file');
    expect(filePart).toBeInstanceOf(Blob);
    expect((filePart as Blob).type).toBe('image/png');
    expect((filePart as Blob).size).toBe(3);
  });
});

interface FetchCall {
  url: string;
  init: RequestInit;
}

function recordingFetch(responseBody: unknown, calls: FetchCall[]): typeof fetch {
  return (async (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {
    calls.push({ url: fetchInputUrl(input), init: init ?? {} });
    return new Response(JSON.stringify(responseBody), {
      status: 200,
      headers: { 'content-type': 'application/json' },
    });
  }) as typeof fetch;
}

function recordingFetchSequence(responseBodies: unknown[], calls: FetchCall[]): typeof fetch {
  let index = 0;
  return (async (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {
    calls.push({ url: fetchInputUrl(input), init: init ?? {} });
    const responseBody = responseBodies[Math.min(index, responseBodies.length - 1)];
    index++;
    return new Response(JSON.stringify(responseBody), {
      status: 200,
      headers: { 'content-type': 'application/json' },
    });
  }) as typeof fetch;
}

function fetchInputUrl(input: Parameters<typeof fetch>[0]): string {
  if (typeof input === 'string') return input;
  if (input instanceof URL) return input.toString();
  return input.url;
}

function parseRecordedJsonBody(call: FetchCall | undefined): unknown {
  const body = call?.init.body;
  if (typeof body !== 'string') {
    throw new TypeError('expected recorded fetch body to be a JSON string');
  }
  return JSON.parse(body) as unknown;
}

function okEnvelope<T>(data: T): { code: 0; msg: string; data: T; request_id: string } {
  return { code: 0, msg: 'success', data, request_id: 'req_test' };
}

function frameForLog(frame: {
  type: string;
  seq?: number;
  session_id?: string;
  id?: string;
  code?: number;
  msg?: string;
  payload?: unknown;
}): Record<string, unknown> {
  return {
    type: frame.type,
    seq: frame.seq,
    session_id: frame.session_id,
    id: frame.id,
    code: frame.code,
    msg: frame.msg,
    payload: frame.payload,
  };
}

function testSession(overrides: Partial<Session> = {}): Session {
  const base: Session = {
    id: 'sess_example',
    workspace_id: 'wd_example_0123456789ab',
    title: 'Example session',
    created_at: '2026-06-09T00:00:00.000Z',
    updated_at: '2026-06-09T00:00:00.000Z',
    busy: false,
    metadata: { cwd: '/tmp/example-server-e2e' },
    agent_config: { model: '' },
    usage: {
      input_tokens: 0,
      output_tokens: 0,
      cache_read_tokens: 0,
      cache_creation_tokens: 0,
      total_cost_usd: 0,
      context_tokens: 0,
      context_limit: 0,
      turn_count: 0,
    },
    permission_rules: [],
    message_count: 0,
    last_seq: 0,
  };
  return {
    ...base,
    ...overrides,
    metadata: { ...base.metadata, ...overrides.metadata },
  };
}

function testModel(overrides: Partial<ModelCatalogItem> = {}): ModelCatalogItem {
  return {
    provider: 'kimi',
    model: 'k2',
    display_name: 'Kimi K2',
    max_context_size: 131_072,
    ...overrides,
  };
}

function testProvider(overrides: Partial<ProviderCatalogItem> = {}): ProviderCatalogItem {
  return {
    id: 'kimi',
    type: 'kimi',
    base_url: 'https://api.example.test/v1',
    default_model: 'k2',
    has_api_key: true,
    status: 'connected',
    models: ['k2'],
    ...overrides,
  };
}

function testFile(overrides: Partial<FileMeta> = {}): FileMeta {
  return {
    id: 'file_example',
    name: 'example.txt',
    media_type: 'text/plain',
    size: 0,
    created_at: '2026-06-09T00:00:00.000Z',
    ...overrides,
  };
}

function testMessage(overrides: Partial<Message> = {}): Message {
  return {
    id: 'msg_example',
    session_id: 'sess_example',
    role: 'user',
    content: [{ type: 'text', text: 'kept' }],
    created_at: '2026-06-09T00:00:00.000Z',
    ...overrides,
  };
}

function testSessionStatus(): SessionStatusResponse {
  return {
    busy: false,
    model: 'kimi-code/kimi-for-coding',
    thinking_level: 'off',
    permission: 'manual',
    plan_mode: false,
    swarm_mode: false,
    context_tokens: 0,
    max_context_tokens: 100,
    context_usage: 0,
  };
}

function textFromMessages(messages: Array<{ content: Array<{ type: string; text?: string }> }>): string {
  return messages
    .flatMap((message) => message.content)
    .filter((part) => part.type === 'text')
    .map((part) => part.text ?? '')
    .join('\n');
}