File size: 28,190 Bytes
6a2bc3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
/**
 * Scenario: the VS Code host owns one Kimi harness and routes Webviews to shared SDK sessions.
 * Responsibilities: create/resume/switch, per-session settings, multi-view ownership, detach, and disposal.
 * Wiring: KimiRuntime and SessionRuntime are real; in-memory Session/KimiHarness fakes form the public SDK boundary.
 * Run: pnpm exec vitest run --config apps/vscode/vitest.config.ts test/kimi-runtime.test.ts
 */

import type {
  ApprovalHandler,
  CreateSessionOptions,
  Event,
  JsonObject,
  KimiHarness,
  PermissionMode,
  PromptInput,
  QuestionHandler,
  ResumeSessionInput,
  Session,
  SessionStatus,
  SessionSummary,
  ThinkingEffort,
} from "@moonshot-ai/kimi-code-sdk";
import { describe, expect, it, vi } from "vitest";

import { Events } from "../shared/bridge";
import { KimiRuntime, type OpenSessionOptions } from "../src/runtime/kimi-runtime";

const sdkFactories = vi.hoisted(() => {
  const harness = { homeDir: "/tmp/kimi-runtime-home", close: vi.fn(async () => undefined) };
  return {
    harness,
    createKimiHarness: vi.fn(() => harness),
  };
});

vi.mock("@moonshot-ai/kimi-code-sdk", async (importOriginal) => {
  const original = await importOriginal<typeof import("@moonshot-ai/kimi-code-sdk")>();
  return {
    ...original,
    createKimiHarness: sdkFactories.createKimiHarness,
  };
});

interface FakeSessionBoundary {
  readonly session: Session;
  readonly setModels: string[];
  readonly setThinkingEfforts: ThinkingEffort[];
  readonly setPermissions: PermissionMode[];
  readonly metadataUpdates: JsonObject[];
  readonly handlerInstallations: { approval: number; question: number };
  readonly subscriptionCount: () => number;
  readonly closeCount: () => number;
  readonly emit: (event: Event) => void;
  readonly setPromptImpl: (impl: (input: string | PromptInput) => Promise<void>) => void;
}

function createFakeSession(
  id: string,
  workDir: string,
  initial: Partial<SessionStatus> = {},
  metadata?: JsonObject,
): FakeSessionBoundary {
  const listeners = new Set<(event: Event) => void>();
  const setModels: string[] = [];
  const setThinkingEfforts: ThinkingEffort[] = [];
  const setPermissions: PermissionMode[] = [];
  const metadataUpdates: JsonObject[] = [];
  const handlerInstallations = { approval: 0, question: 0 };
  let subscriptions = 0;
  let closes = 0;
  let promptImpl: (input: string | PromptInput) => Promise<void> = async () => {};
  let status: SessionStatus = {
    model: initial.model ?? "kimi-test",
    thinkingEffort: initial.thinkingEffort ?? "off",
    permission: initial.permission ?? "manual",
    planMode: initial.planMode ?? false,
    contextTokens: 0,
    maxContextTokens: 128_000,
    contextUsage: 0,
  };
  let summary: SessionSummary = {
    id,
    workDir,
    sessionDir: `/home/sessions/${id}`,
    createdAt: 1,
    updatedAt: 2,
    metadata,
  };

  const session = {
    id,
    workDir,
    get summary() {
      return summary;
    },
    set summary(value: SessionSummary | undefined) {
      if (value !== undefined) summary = value;
    },
    setApprovalHandler(handler: ApprovalHandler | undefined) {
      if (handler !== undefined) handlerInstallations.approval += 1;
    },
    setQuestionHandler(handler: QuestionHandler | undefined) {
      if (handler !== undefined) handlerInstallations.question += 1;
    },
    onEvent(listener: (event: Event) => void) {
      subscriptions += 1;
      listeners.add(listener);
      return () => listeners.delete(listener);
    },
    async prompt(input: string | PromptInput) {
      await promptImpl(input);
    },
    async steer(_input: string | PromptInput) {},
    async cancel() {},
    async getStatus() {
      return status;
    },
    async setModel(model: string) {
      setModels.push(model);
      status = { ...status, model };
    },
    async setThinking(effort: ThinkingEffort) {
      setThinkingEfforts.push(effort);
      status = { ...status, thinkingEffort: effort };
    },
    async setPermission(permission: PermissionMode) {
      setPermissions.push(permission);
      status = { ...status, permission };
    },
    async updateMetadata(patch: JsonObject) {
      metadataUpdates.push(patch);
      summary = { ...summary, metadata: { ...summary.metadata, ...patch } };
    },
    async close() {
      closes += 1;
    },
  } as unknown as Session;

  return {
    session,
    setModels,
    setThinkingEfforts,
    setPermissions,
    metadataUpdates,
    handlerInstallations,
    subscriptionCount: () => subscriptions,
    closeCount: () => closes,
    emit: (event: Event) => {
      for (const listener of [...listeners]) listener(event);
    },
    setPromptImpl: (impl) => {
      promptImpl = impl;
    },
  };
}

interface FakeHarnessBoundary {
  readonly harness: KimiHarness;
  readonly createInputs: CreateSessionOptions[];
  readonly resumeInputs: ResumeSessionInput[];
  readonly closeSessionIds: string[];
  readonly deleteSessionIds: string[];
  readonly closeCount: () => number;
  readonly sessions: Map<string, FakeSessionBoundary>;
  addSession(
    id: string,
    workDir: string,
    initial?: Partial<SessionStatus>,
    metadata?: JsonObject,
  ): FakeSessionBoundary;
}

function createFakeHarness(
  normalizeCreatedWorkDir: (workDir: string) => string = (workDir) => workDir,
): FakeHarnessBoundary {
  const sessions = new Map<string, FakeSessionBoundary>();
  const createInputs: CreateSessionOptions[] = [];
  const resumeInputs: ResumeSessionInput[] = [];
  const closeSessionIds: string[] = [];
  const deleteSessionIds: string[] = [];
  let creates = 0;
  let closes = 0;

  const addSession = (
    id: string,
    workDir: string,
    initial?: Partial<SessionStatus>,
    metadata?: JsonObject,
  ) => {
    const boundary = createFakeSession(id, workDir, initial, metadata);
    sessions.set(id, boundary);
    return boundary;
  };

  const harness = {
    async createSession(options: CreateSessionOptions) {
      createInputs.push(options);
      creates += 1;
      return addSession(
        `created-${creates}`,
        normalizeCreatedWorkDir(options.workDir),
        {
          model: options.model,
          thinkingEffort: options.thinking,
          permission: options.permission,
        },
        options.metadata,
      ).session;
    },
    async resumeSession(input: ResumeSessionInput) {
      resumeInputs.push(input);
      const boundary = sessions.get(input.id);
      if (boundary === undefined) throw new Error(`Unknown session: ${input.id}`);
      return boundary.session;
    },
    async closeSession(id: string) {
      closeSessionIds.push(id);
    },
    async deleteSession(id: string) {
      deleteSessionIds.push(id);
    },
    async close() {
      closes += 1;
    },
  } as unknown as KimiHarness;

  return {
    harness,
    createInputs,
    resumeInputs,
    closeSessionIds,
    deleteSessionIds,
    closeCount: () => closes,
    sessions,
    addSession,
  };
}

function openOptions(overrides: Partial<OpenSessionOptions> = {}): OpenSessionOptions {
  return {
    webviewId: "view-1",
    workDir: "/workspace",
    model: "kimi-test",
    effort: "off",
    yoloMode: false,
    ...overrides,
  };
}

function createRuntime(
  normalizeCreatedWorkDir?: (workDir: string) => string,
) {
  const sdk = createFakeHarness(normalizeCreatedWorkDir);
  const runtime = new KimiRuntime({
    version: "0.6.0",
    harness: sdk.harness,
    broadcast: () => undefined,
    captureBaseline: () => undefined,
    log: () => undefined,
  });
  return { runtime, sdk };
}

describe("Kimi runtime (owns shared SDK sessions for Webviews)", () => {
  it("creates the harness through the SDK factory when none is injected", async () => {
    const runtime = new KimiRuntime({
      version: "0.6.0",
      broadcast: () => undefined,
      captureBaseline: () => undefined,
      log: () => undefined,
    });
    expect(sdkFactories.createKimiHarness).toHaveBeenCalledOnce();
    expect(sdkFactories.createKimiHarness).toHaveBeenCalledWith({
      homeDir: undefined,
      identity: {
        productName: "kimi-code-vscode",
        version: "0.6.0",
        platform: "kimi_code_vscode",
      },
      uiMode: "vscode",
    });
    expect(runtime.harness).toBe(sdkFactories.harness as unknown as KimiHarness);
    await runtime.dispose();
  });

  it("forwards the requested settings when creating an SDK session", async () => {
    const { runtime, sdk } = createRuntime();

    const opened = await runtime.openSession(
      openOptions({ model: "kimi-k2", effort: "high", yoloMode: true }),
    );

    expect(sdk.createInputs).toEqual([
      {
        workDir: "/workspace",
        model: "kimi-k2",
        thinking: "high",
        permission: "yolo",
        metadata: { vscode_legacy_approval: { yolo: true, afk: false } },
      },
    ]);
    expect(opened.subscribers).toEqual(["view-1"]);
  });

  it("accepts the normalized SDK workDir when a Windows session is created", async () => {
    const { runtime } = createRuntime((workDir) => workDir.replaceAll("\\", "/"));

    const opened = await runtime.openSession(openOptions({
      workDir: "C:\\Users\\Example User\\项目",
    }));

    expect(opened.session.workDir).toBe("C:/Users/Example User/项目");
  });

  it("resumes a Windows session when only separators and casing differ", async () => {
    const { runtime, sdk } = createRuntime();
    sdk.addSession("saved-win", "C:/Users/Example User/项目");

    const opened = await runtime.openSession(openOptions({
      sessionId: "saved-win",
      workDir: "c:\\users\\example user\\项目",
    }));

    expect(opened.id).toBe("saved-win");
  });

  it("uses off thinking when a new session receives an empty effort", async () => {
    const { runtime, sdk } = createRuntime();

    await runtime.openSession(openOptions({ effort: "   " }));

    expect(sdk.createInputs[0]?.thinking).toBe("off");
  });

  it("resumes the requested SDK session instead of creating a replacement", async () => {
    const { runtime, sdk } = createRuntime();
    sdk.addSession("saved-1", "/workspace");

    const opened = await runtime.openSession(openOptions({ sessionId: "saved-1" }));

    expect(opened.id).toBe("saved-1");
    expect(sdk.resumeInputs).toEqual([{ id: "saved-1", includeSubagents: true }]);
    expect(sdk.createInputs).toEqual([]);
  });

  it("switches a Webview to the requested session", async () => {
    const { runtime, sdk } = createRuntime();
    await runtime.openSession(openOptions());
    sdk.addSession("saved-2", "/workspace");

    const selected = await runtime.openSession(openOptions({ sessionId: "saved-2" }));

    expect(runtime.getSessionForView("view-1")?.id).toBe("saved-2");
    expect(selected.id).toBe("saved-2");
  });

  it("closes an unshared old session when its Webview switches away", async () => {
    const { runtime, sdk } = createRuntime();
    const old = await runtime.openSession(openOptions());
    const oldBoundary = sdk.sessions.get(old.id)!;
    sdk.addSession("saved-2", "/workspace");

    await runtime.openSession(openOptions({ sessionId: "saved-2" }));

    expect(oldBoundary.closeCount()).toBe(1);
  });

  it("shares one SDK subscription when two Webviews attach to the same session", async () => {
    const { runtime, sdk } = createRuntime();
    const first = await runtime.openSession(openOptions({ webviewId: "view-1" }));
    const boundary = sdk.sessions.get(first.id)!;

    const second = await runtime.openSession(
      openOptions({ webviewId: "view-2", sessionId: first.id }),
    );

    expect(second).toBe(first);
    expect(first.subscribers).toEqual(["view-1", "view-2"]);
    expect(boundary.subscriptionCount()).toBe(1);
    expect(boundary.handlerInstallations).toEqual({ approval: 1, question: 1 });
  });

  it("does not double-wrap the SDK session when two opens race for it", async () => {
    const sdk = createFakeHarness();
    const broadcasts: { event: string; data: unknown; webviewId?: string }[] = [];
    const runtime = new KimiRuntime({
      version: "0.6.0",
      harness: sdk.harness,
      broadcast: (event, data, webviewId) => {
        broadcasts.push({ event, data, webviewId });
      },
      captureBaseline: () => undefined,
      log: () => undefined,
    });
    const boundary = sdk.addSession("saved-1", "/workspace");

    const [first, second] = await Promise.all([
      runtime.openSession(openOptions({ sessionId: "saved-1" })),
      runtime.openSession(openOptions({ sessionId: "saved-1" })),
    ]);

    expect(second).toBe(first);
    expect(boundary.subscriptionCount()).toBe(1);

    boundary.emit({
      type: "assistant.delta",
      sessionId: "saved-1",
      agentId: "main",
      turnId: 1,
      delta: "Hello",
    });

    const parts = broadcasts.filter(
      ({ data }) => (data as { type?: string }).type === "ContentPart",
    );
    expect(parts).toHaveLength(1);
  });

  it("coalesces two concurrent new-session opens for one view onto one session", async () => {
    const { runtime, sdk } = createRuntime();

    const [first, second] = await Promise.all([
      runtime.openSession(openOptions()),
      runtime.openSession(openOptions()),
    ]);

    expect(second).toBe(first);
    expect(sdk.createInputs).toHaveLength(1);
    expect(first.subscribers).toEqual(["view-1"]);
  });

  it("does not double-wrap the SDK session when two attaches race for it", async () => {
    const sdk = createFakeHarness();
    const broadcasts: { event: string; data: unknown; webviewId?: string }[] = [];
    const runtime = new KimiRuntime({
      version: "0.6.0",
      harness: sdk.harness,
      broadcast: (event, data, webviewId) => {
        broadcasts.push({ event, data, webviewId });
      },
      captureBaseline: () => undefined,
      log: () => undefined,
    });
    const boundary = sdk.addSession("saved-1", "/workspace");

    const [first, second] = await Promise.all([
      runtime.attachResumedSession("view-1", boundary.session),
      runtime.attachResumedSession("view-1", boundary.session),
    ]);

    expect(second).toBe(first);
    expect(boundary.subscriptionCount()).toBe(1);

    boundary.emit({
      type: "assistant.delta",
      sessionId: "saved-1",
      agentId: "main",
      turnId: 1,
      delta: "Hello",
    });

    const parts = broadcasts.filter(
      ({ data }) => (data as { type?: string }).type === "ContentPart",
    );
    expect(parts).toHaveLength(1);
  });

  it("preserves the resumed session's model instead of reapplying the configured default", async () => {
    const { runtime, sdk } = createRuntime();
    const session = sdk.addSession("saved-1", "/workspace", { model: "old-model" });

    const opened = await runtime.openSession(openOptions({ sessionId: "saved-1", model: "new-model" }));

    expect(session.setModels).toEqual([]);
    await expect(opened.session.getStatus()).resolves.toMatchObject({ model: "old-model" });
  });

  it("preserves the resumed session's thinking effort instead of reapplying the configured default", async () => {
    const { runtime, sdk } = createRuntime();
    const session = sdk.addSession("saved-1", "/workspace", { thinkingEffort: "max" });

    const opened = await runtime.openSession(openOptions({ sessionId: "saved-1", effort: "medium" }));

    expect(session.setThinkingEfforts).toEqual([]);
    await expect(opened.session.getStatus()).resolves.toMatchObject({ thinkingEffort: "max" });
  });

  it("announces the session's actual status to the attaching view so the display matches it", async () => {
    const sdk = createFakeHarness();
    const broadcasts: { event: string; data: unknown; webviewId?: string }[] = [];
    const runtime = new KimiRuntime({
      version: "0.6.0",
      harness: sdk.harness,
      broadcast: (event, data, webviewId) => {
        broadcasts.push({ event, data, webviewId });
      },
      captureBaseline: () => undefined,
      log: () => undefined,
    });
    sdk.addSession("saved-1", "/workspace", {
      model: "kimi-test",
      thinkingEffort: "max",
      planMode: true,
    });

    await runtime.openSession(openOptions({ sessionId: "saved-1", effort: "medium" }));

    expect(broadcasts).toContainEqual({
      event: Events.StreamEvent,
      data: {
        type: "StatusUpdate",
        payload: {
          model: "kimi-test",
          thinking_effort: "max",
          plan_mode: true,
          context_usage: 0,
        },
        _sessionId: "saved-1",
      },
      webviewId: "view-1",
    });
  });

  it("uses the yolo setting as the initial value for an unmarked resumed session", async () => {
    const { runtime, sdk } = createRuntime();
    const session = sdk.addSession("saved-1", "/workspace", { permission: "manual" });

    await runtime.openSession(openOptions({ sessionId: "saved-1", yoloMode: true }));

    expect(session.metadataUpdates).toEqual([
      { vscode_legacy_approval: { yolo: true, afk: false } },
    ]);
  });

  it("lets the global yolo setting override a persisted off flag on resume", async () => {
    const { runtime, sdk } = createRuntime();
    const session = sdk.addSession(
      "saved-1",
      "/workspace",
      { permission: "manual" },
      { vscode_legacy_approval: { yolo: false, afk: false } },
    );

    const opened = await runtime.openSession(openOptions({ sessionId: "saved-1", yoloMode: true }));

    expect(session.setPermissions).toEqual(["yolo"]);
    expect(session.metadataUpdates).toEqual([
      { vscode_legacy_approval: { yolo: true, afk: false } },
    ]);
    expect(opened.legacyApprovalFlags).toEqual({ yolo: true, afk: false });
  });

  it("lets the global yolo setting disable a persisted session yolo flag on resume", async () => {
    const { runtime, sdk } = createRuntime();
    const session = sdk.addSession(
      "saved-1",
      "/workspace",
      { permission: "yolo" },
      { vscode_legacy_approval: { yolo: true, afk: false } },
    );

    const opened = await runtime.openSession(openOptions({ sessionId: "saved-1", yoloMode: false }));

    expect(session.setPermissions).toEqual(["manual"]);
    expect(session.metadataUpdates).toEqual([
      { vscode_legacy_approval: { yolo: false, afk: false } },
    ]);
    expect(opened.legacyApprovalFlags).toEqual({ yolo: false, afk: false });
  });

  it("keeps the persisted afk flag while applying the global yolo setting on resume", async () => {
    const { runtime, sdk } = createRuntime();
    const session = sdk.addSession(
      "saved-1",
      "/workspace",
      { permission: "manual" },
      { vscode_legacy_approval: { yolo: false, afk: true } },
    );

    const opened = await runtime.openSession(openOptions({ sessionId: "saved-1", yoloMode: true }));

    expect(session.setPermissions).toEqual(["auto"]);
    expect(opened.legacyApprovalFlags).toEqual({ yolo: true, afk: true });
  });

  it("restores persisted afk with core auto permission", async () => {
    const { runtime, sdk } = createRuntime();
    const session = sdk.addSession(
      "saved-1",
      "/workspace",
      { permission: "manual" },
      { vscode_legacy_approval: { yolo: false, afk: true } },
    );

    await runtime.openSession(openOptions({ sessionId: "saved-1", yoloMode: false }));

    expect(session.setPermissions).toEqual(["auto"]);
  });

  it("changes the setting-backed yolo flag without clearing session afk", async () => {
    const { runtime } = createRuntime();
    const opened = await runtime.openSession(openOptions());
    await opened.toggleLegacyApproval("afk");

    await runtime.setYoloModeForActiveSessions(true);

    expect(opened.legacyApprovalFlags).toEqual({ yolo: true, afk: true });
    await expect(opened.session.getStatus()).resolves.toMatchObject({ permission: "auto" });
  });

  it("keeps a shared session open when one of its Webviews detaches", async () => {
    const { runtime, sdk } = createRuntime();
    const opened = await runtime.openSession(openOptions({ webviewId: "view-1" }));
    await runtime.openSession(openOptions({ webviewId: "view-2", sessionId: opened.id }));
    const boundary = sdk.sessions.get(opened.id)!;

    await runtime.detachView("view-1");

    expect(boundary.closeCount()).toBe(0);
    expect(runtime.getSessionForView("view-2")?.id).toBe(opened.id);
  });

  it("closes an SDK session when its last Webview detaches", async () => {
    const { runtime, sdk } = createRuntime();
    const opened = await runtime.openSession(openOptions());
    const boundary = sdk.sessions.get(opened.id)!;

    await runtime.detachView("view-1");

    expect(boundary.closeCount()).toBe(1);
    expect(runtime.getSession(opened.id)).toBeUndefined();
  });

  it("reattaches the same resumed session without replacing its handlers", async () => {
    const { runtime, sdk } = createRuntime();
    const boundary = sdk.addSession("saved-1", "/workspace");
    const first = await runtime.attachResumedSession("view-1", boundary.session);

    const second = await runtime.attachResumedSession("view-1", boundary.session);

    expect(second).toBe(first);
    expect(boundary.subscriptionCount()).toBe(1);
    expect(boundary.handlerInstallations).toEqual({ approval: 1, question: 1 });
    expect(boundary.closeCount()).toBe(0);
  });

  it("removes every Webview mapping when a shared session is closed", async () => {
    const { runtime } = createRuntime();
    const opened = await runtime.openSession(openOptions({ webviewId: "view-1" }));
    await runtime.openSession(openOptions({ webviewId: "view-2", sessionId: opened.id }));

    await runtime.closeSession(opened.id);

    expect(runtime.getSessionForView("view-1")).toBeUndefined();
    expect(runtime.getSessionForView("view-2")).toBeUndefined();
  });

  it("delegates deletion after the active session has been closed", async () => {
    const { runtime, sdk } = createRuntime();
    const opened = await runtime.openSession(openOptions());
    const boundary = sdk.sessions.get(opened.id)!;

    await runtime.deleteSession(opened.id);

    expect(boundary.closeCount()).toBe(1);
    expect(sdk.deleteSessionIds).toEqual([opened.id]);
  });

  it("closes every active SDK session when the host runtime is disposed", async () => {
    const { runtime, sdk } = createRuntime();
    const first = await runtime.openSession(openOptions({ webviewId: "view-1" }));
    const secondBoundary = sdk.addSession("saved-2", "/workspace");
    await runtime.openSession(openOptions({ webviewId: "view-2", sessionId: "saved-2" }));

    await runtime.dispose();

    expect(sdk.sessions.get(first.id)?.closeCount()).toBe(1);
    expect(secondBoundary.closeCount()).toBe(1);
    expect(sdk.closeCount()).toBe(1);
  });

  it("does not retain a resumed session when it belongs to a different working directory", async () => {
    const { runtime, sdk } = createRuntime();
    const foreign = sdk.addSession("foreign-1", "/other-workspace");

    await expect(
      runtime.openSession(openOptions({ sessionId: "foreign-1" })),
    ).rejects.toThrow("The selected session belongs to a different working directory.");

    expect(runtime.getSession("foreign-1")).toBeUndefined();
    expect(foreign.closeCount()).toBe(1);
  });

  function createRecordingRuntime() {
    const sdk = createFakeHarness();
    const broadcasts: Array<{ event: string; data: unknown }> = [];
    const runtime = new KimiRuntime({
      version: "test",
      harness: sdk.harness,
      broadcast: (event, data) => {
        broadcasts.push({ event, data });
      },
      captureBaseline: () => undefined,
      log: () => undefined,
    });
    return { runtime, sdk, broadcasts };
  }

  it("fails a reentrant prompt without disturbing the running turn", async () => {
    const { runtime, sdk, broadcasts } = createRecordingRuntime();
    const opened = await runtime.openSession(openOptions());
    const boundary = sdk.sessions.get(opened.id)!;

    let releaseTurn!: () => void;
    boundary.setPromptImpl(() => new Promise<void>((resolve) => {
      releaseTurn = resolve;
    }));
    const first = opened.prompt("first message");
    boundary.emit({ type: "turn.started", agentId: "main", sessionId: opened.id, turnId: "t1" } as unknown as Event);
    expect(opened.isBusy).toBe(true);

    await expect(opened.prompt("concurrent message")).resolves.toEqual({ status: "failed" });

    // The rejection surfaces as a mid-turn warning; the active turn is untouched.
    expect(opened.isBusy).toBe(true);
    const busyWarning = broadcasts.find(({ data }) => (data as { type?: string }).type === "error");
    expect(busyWarning?.data).toMatchObject({
      type: "error",
      phase: "runtime",
      detail: "A response is already being generated for this session.",
      terminal: false,
    });

    boundary.emit({ type: "turn.ended", agentId: "main", sessionId: opened.id, turnId: "t1", reason: "completed" } as unknown as Event);
    releaseTurn();
    await expect(first).resolves.toEqual({ status: "finished" });
    expect(opened.isBusy).toBe(false);
  });

  it("rejects a prompt during an exclusive operation with a terminal error", async () => {
    const { runtime, broadcasts } = createRecordingRuntime();
    const opened = await runtime.openSession(openOptions());

    let releaseExclusive!: () => void;
    const exclusive = opened.runExclusiveAfterCancelling(
      () => new Promise<void>((resolve) => {
        releaseExclusive = resolve;
      }),
    );
    // No active work means no later stream_complete: the rejection must be
    // terminal so the caller's composer can unlock.
    expect(opened.isBusy).toBe(true);

    await expect(opened.prompt("during fork")).resolves.toEqual({ status: "failed" });
    const rejection = broadcasts.find(({ data }) => (data as { type?: string }).type === "error");
    expect(rejection?.data).toMatchObject({ type: "error", phase: "runtime" });
    expect((rejection?.data as Record<string, unknown>)["terminal"]).toBeUndefined();

    releaseExclusive();
    await exclusive;
    expect(opened.isBusy).toBe(false);
  });

  it("marks a mid-turn core error as non-terminal until the turn ends", async () => {
    const { runtime, sdk, broadcasts } = createRecordingRuntime();
    const opened = await runtime.openSession(openOptions());
    const boundary = sdk.sessions.get(opened.id)!;

    let releaseTurn!: () => void;
    boundary.setPromptImpl(() => new Promise<void>((resolve) => {
      releaseTurn = resolve;
    }));
    const first = opened.prompt("first message");
    boundary.emit({ type: "turn.started", agentId: "main", sessionId: opened.id, turnId: "t1" } as unknown as Event);

    boundary.emit({
      type: "error",
      agentId: "main",
      sessionId: opened.id,
      code: "records.write_failed",
      message: "Failed to write agent records: EACCES",
    } as unknown as Event);

    // The turn is still running: no settlement, no terminal error on the wire.
    expect(opened.isBusy).toBe(true);
    const warning = broadcasts.find(({ data }) => (data as { type?: string }).type === "error");
    expect(warning?.data).toMatchObject({
      type: "error",
      code: "records.write_failed",
      phase: "runtime",
      terminal: false,
    });

    boundary.emit({ type: "turn.ended", agentId: "main", sessionId: opened.id, turnId: "t1", reason: "completed" } as unknown as Event);
    releaseTurn();
    await expect(first).resolves.toEqual({ status: "finished" });
    expect(opened.isBusy).toBe(false);
  });

  it("keeps preflight failures terminal", async () => {
    const { runtime, sdk, broadcasts } = createRecordingRuntime();
    const opened = await runtime.openSession(openOptions());
    const boundary = sdk.sessions.get(opened.id)!;

    boundary.setPromptImpl(() => Promise.reject(new Error("provider down")));

    await expect(opened.prompt("hi")).resolves.toEqual({ status: "failed" });
    const failure = broadcasts.find(({ data }) => (data as { type?: string }).type === "error");
    expect(failure?.data).toMatchObject({ type: "error", phase: "preflight" });
    expect((failure?.data as Record<string, unknown>)["terminal"]).toBeUndefined();
    expect(opened.isBusy).toBe(false);
  });
});