File size: 27,115 Bytes
76289e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
/** Tests ACP server startup readiness, Gateway bootstrap, and shutdown wiring. */
import { ReadableStream as NodeReadableStream } from "node:stream/web";
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import type { resolveGatewayClientBootstrap } from "../gateway/client-bootstrap.js";

type GatewayClientCallbacks = {
  onEvent?: (evt: { event: string; payload?: unknown }) => void;
  onHelloOk?: () => void;
  onConnectError?: (err: Error) => void;
  onClose?: (code: number, reason: string) => void;
};

type GatewayClientAuth = {
  token?: string;
  password?: string;
};
type ResolveGatewayClientBootstrap = typeof resolveGatewayClientBootstrap;
type GatewayClientOptions = GatewayClientCallbacks &
  GatewayClientAuth & {
    caps?: string[];
    tlsFingerprint?: string;
    url?: string;
  };
type MockAcpStream = {
  writable: WritableStream<unknown>;
  readable: ReadableStream<unknown>;
};

const mockState = vi.hoisted(() => ({
  acpProtocolVersion: 1,
  acpInputMessages: [] as unknown[],
  rawInputChunks: [] as Uint8Array[],
  gateways: [] as MockGatewayClient[],
  gatewayAuth: [] as GatewayClientAuth[],
  gatewayOptions: [] as GatewayClientOptions[],
  sqliteEventLedgers: [] as unknown[],
  agentOptions: [] as unknown[],
  agentSideConnectionCtor: vi.fn(),
  closeAgentSideConnection: null as (() => void) | null,
  closeAcpInput: null as (() => void) | null,
  agentHandleGatewayEvent: vi.fn(async (_evt: unknown) => {}),
  agentStart: vi.fn(),
  agentShutdown: vi.fn(),
  routeLogsToStderr: vi.fn(),
  startProxy: vi.fn(async (_configForTest: unknown) => null as unknown),
  stopProxy: vi.fn(async (_handle: unknown) => {}),
  closeOpenClawStateDatabaseAsync: vi.fn<() => Promise<void>>(async () => {}),
  gatewayStopDeferred: null as {
    resolve: () => void;
    promise: Promise<void>;
  } | null,
  resolveGatewayClientBootstrap: vi.fn<ResolveGatewayClientBootstrap>(),
}));

vi.mock("node:stream", async (importOriginal) => {
  const actual = await importOriginal<typeof import("node:stream")>();
  vi.spyOn(actual.Readable, "toWeb").mockImplementation(
    () =>
      new NodeReadableStream<Uint8Array>({
        start(controller) {
          for (const chunk of mockState.rawInputChunks) {
            controller.enqueue(chunk);
          }
        },
      }),
  );
  vi.spyOn(actual.Writable, "toWeb").mockImplementation(() => new WritableStream());
  return actual;
});

class MockGatewayClient {
  private callbacks: GatewayClientCallbacks;

  constructor(opts: GatewayClientOptions) {
    this.callbacks = opts;
    mockState.gatewayOptions.push(opts);
    mockState.gatewayAuth.push({ token: opts.token, password: opts.password });
    mockState.gateways.push(this);
  }

  start(): void {}

  stop(): void {
    this.callbacks.onClose?.(1000, "gateway stopped");
  }

  async stopAndWait(): Promise<void> {
    if (mockState.gatewayStopDeferred) {
      await mockState.gatewayStopDeferred.promise;
    }
    this.stop();
  }

  emitHello(): void {
    this.callbacks.onHelloOk?.();
  }

  emitConnectError(message: string): void {
    this.callbacks.onConnectError?.(new Error(message));
  }
  emitEvent(event: { event: string; payload?: unknown }): void {
    this.callbacks.onEvent?.(event);
  }
}

vi.mock("@agentclientprotocol/sdk", () => ({
  AGENT_METHODS: {
    initialize: "initialize",
  },
  AgentSideConnection: function AgentSideConnection(
    factory: (conn: unknown) => unknown,
    stream: unknown,
  ) {
    mockState.agentSideConnectionCtor(factory, stream);
    factory({});
    return {
      closed: new Promise<void>((resolve) => {
        mockState.closeAgentSideConnection = resolve;
      }),
    };
  },
  PROTOCOL_VERSION: mockState.acpProtocolVersion,
  ndJsonStream: vi.fn(() => ({
    writable: new WritableStream(),
    readable: new ReadableStream({
      start(controller) {
        for (const message of mockState.acpInputMessages) {
          controller.enqueue(message);
        }
        mockState.closeAcpInput = () => controller.close();
      },
    }),
  })),
}));

vi.mock("../config/config.js", () => {
  const loadConfig = () => ({
    gateway: {
      mode: "local",
    },
  });
  return {
    getRuntimeConfig: loadConfig,
    loadConfig,
    resolveGatewayPort: vi.fn(() => 18_789),
  };
});

vi.mock("../gateway/call.js", () => ({
  callGateway: vi.fn(),
  buildGatewayConnectionDetails: ({ url }: { url?: string }) => {
    if (typeof url === "string" && url.trim().length > 0) {
      return {
        url: url.trim(),
        urlSource: "cli --url",
        message: `Gateway target: ${url.trim()}`,
      };
    }
    return {
      url: "ws://127.0.0.1:18789",
      urlSource: "local loopback",
      message: "Gateway target: ws://127.0.0.1:18789",
    };
  },
}));

vi.mock("../gateway/client-bootstrap.js", () => ({
  resolveGatewayClientBootstrap: mockState.resolveGatewayClientBootstrap,
}));

vi.mock("../gateway/client.js", () => ({
  GatewayClient: MockGatewayClient,
}));

vi.mock("../../packages/gateway-client/src/readiness.js", () => ({
  startGatewayClientWhenEventLoopReady: vi.fn(async (client: MockGatewayClient) => {
    client.start();
    return {
      ready: true,
      elapsedMs: 0,
      maxDriftMs: 0,
      checks: 2,
      aborted: false,
    };
  }),
}));

vi.mock("../infra/is-main.js", () => ({
  isMainModule: () => false,
}));

vi.mock("../logging/console.js", async (importOriginal) => {
  const actual = await importOriginal<typeof import("../logging/console.js")>();
  return {
    ...actual,
    routeLogsToStderr: () => mockState.routeLogsToStderr(),
  };
});

vi.mock("../state/openclaw-state-db.js", () => ({
  closeOpenClawStateDatabaseAsync: () => mockState.closeOpenClawStateDatabaseAsync(),
}));

vi.mock("./event-ledger.js", () => ({
  createSqliteAcpEventLedger: vi.fn(() => {
    const ledger = { kind: "sqlite-acp-event-ledger" };
    mockState.sqliteEventLedgers.push(ledger);
    return ledger;
  }),
}));

vi.mock("../infra/net/proxy/proxy-lifecycle.js", () => ({
  startProxy: (config: unknown) => mockState.startProxy(config),
  stopProxy: (handle: unknown) => mockState.stopProxy(handle),
}));

vi.mock("./translator.js", () => ({
  AcpGatewayAgent: class {
    constructor(_connection: unknown, _gateway: unknown, opts: unknown) {
      mockState.agentOptions.push(opts);
    }

    start(): void {
      mockState.agentStart();
    }

    shutdown(): void {
      mockState.agentShutdown();
    }

    handleGatewayReconnect(): void {}

    handleGatewayDisconnect(): void {}

    async handleGatewayEvent(event: unknown): Promise<void> {
      await mockState.agentHandleGatewayEvent(event);
    }
  },
}));

describe("serveAcpGateway startup", () => {
  let serveAcpGateway: typeof import("./server.js").serveAcpGateway;

  function getMockGateway() {
    const gateway = mockState.gateways[0];
    if (!gateway) {
      throw new Error("Expected mocked gateway instance");
    }
    return gateway;
  }

  function getGatewayBootstrapParams(): { env?: unknown; gatewayUrl?: unknown } {
    const firstCall = mockState.resolveGatewayClientBootstrap.mock.calls[0];
    if (!firstCall) {
      throw new Error("Expected gateway bootstrap resolution call");
    }
    const params = firstCall[0];
    if (!params || typeof params !== "object") {
      throw new Error("Expected gateway bootstrap params");
    }
    return params;
  }

  function captureProcessSignalHandlers() {
    const signalHandlers = new Map<NodeJS.Signals, () => void>();
    const onceSpy = vi.spyOn(process, "once").mockImplementation(((
      signal: NodeJS.Signals,
      handler: () => void,
    ) => {
      signalHandlers.set(signal, handler);
      return process;
    }) as typeof process.once);
    return { signalHandlers, onceSpy };
  }

  async function emitHelloAndWaitForAgentSideConnection() {
    await vi.waitFor(() => {
      expect(mockState.gateways).toHaveLength(1);
    });
    const gateway = getMockGateway();
    gateway.emitHello();
    await vi.waitFor(() => {
      expect(mockState.agentSideConnectionCtor).toHaveBeenCalledTimes(1);
    });
  }

  function getCapturedAcpStream(): MockAcpStream {
    const stream = mockState.agentSideConnectionCtor.mock.calls[0]?.[1];
    if (
      !stream ||
      typeof stream !== "object" ||
      !(stream as MockAcpStream).readable ||
      !(stream as MockAcpStream).writable
    ) {
      throw new Error("Expected AgentSideConnection stream");
    }
    return stream as MockAcpStream;
  }

  async function readCapturedAcpMessages(): Promise<unknown[]> {
    const reader = getCapturedAcpStream().readable.getReader();
    const messages: unknown[] = [];
    try {
      while (true) {
        const { done, value } = await reader.read();
        if (done) {
          return messages;
        }
        messages.push(value);
      }
    } finally {
      reader.releaseLock();
    }
  }

  async function captureAcpMessagesAfterStartup(inputMessages: unknown[]): Promise<unknown[]> {
    mockState.acpInputMessages.push(...inputMessages);
    const { signalHandlers, onceSpy } = captureProcessSignalHandlers();
    const servePromise = serveAcpGateway({});

    try {
      await emitHelloAndWaitForAgentSideConnection();
      mockState.closeAcpInput?.();
      return await readCapturedAcpMessages();
    } finally {
      signalHandlers.get("SIGINT")?.();
      await servePromise;
      onceSpy.mockRestore();
    }
  }

  async function stopServeWithSigint(
    signalHandlers: Map<NodeJS.Signals, () => void>,
    servePromise: Promise<void>,
  ) {
    signalHandlers.get("SIGINT")?.();
    await servePromise;
  }

  beforeAll(async () => {
    // Vitest workers have closed stdin; model the open ACP transport used by
    // these startup tests. Closed-stdin behavior has process-level coverage.
    Object.defineProperty(process.stdin, "readableEnded", {
      configurable: true,
      value: false,
    });
    Object.defineProperty(process.stdin, "readableLength", {
      configurable: true,
      value: 1,
    });
    ({ serveAcpGateway } = await import("./server.js"));
  });

  afterAll(() => {
    const testStdin = process.stdin as unknown as {
      readableEnded?: boolean;
      readableLength?: number;
    };
    delete testStdin.readableEnded;
    delete testStdin.readableLength;
  });

  beforeEach(async () => {
    mockState.acpInputMessages.length = 0;
    mockState.rawInputChunks.length = 0;
    mockState.gateways.length = 0;
    mockState.gatewayAuth.length = 0;
    mockState.gatewayOptions.length = 0;
    mockState.sqliteEventLedgers.length = 0;
    mockState.agentOptions.length = 0;
    mockState.agentSideConnectionCtor.mockReset();
    mockState.closeAgentSideConnection = null;
    mockState.closeAcpInput = null;
    mockState.agentHandleGatewayEvent.mockReset();
    mockState.agentStart.mockReset();
    mockState.agentShutdown.mockReset();
    mockState.routeLogsToStderr.mockReset();
    mockState.startProxy.mockReset();
    mockState.stopProxy.mockReset();
    mockState.closeOpenClawStateDatabaseAsync.mockReset();
    mockState.gatewayStopDeferred = null;
    mockState.startProxy.mockResolvedValue(null);
    mockState.stopProxy.mockResolvedValue(undefined);
    mockState.resolveGatewayClientBootstrap.mockReset();
    mockState.resolveGatewayClientBootstrap.mockResolvedValue({
      url: "ws://127.0.0.1:18789",
      urlSource: "local loopback",
      connectionDetails: {
        url: "ws://127.0.0.1:18789",
        urlSource: "local loopback",
        message: "Gateway target: ws://127.0.0.1:18789",
      },
      auth: {
        token: undefined,
        password: undefined,
      },
    });
  });

  it("preserves console exports for a co-sharded subsystem logger", async () => {
    const { createSubsystemLogger } = await import("../logging/subsystem.js");

    expect(() =>
      createSubsystemLogger("test/acp-startup").isEnabled("info", "console"),
    ).not.toThrow();
  });

  it("waits for gateway hello before creating AgentSideConnection", async () => {
    const { signalHandlers, onceSpy } = captureProcessSignalHandlers();

    try {
      const servePromise = serveAcpGateway({});
      await Promise.resolve();

      expect(mockState.agentSideConnectionCtor).not.toHaveBeenCalled();
      await emitHelloAndWaitForAgentSideConnection();
      await stopServeWithSigint(signalHandlers, servePromise);
    } finally {
      onceSpy.mockRestore();
    }
  });

  it("injects the server-owned SQLite event ledger into the ACP agent", async () => {
    const { signalHandlers, onceSpy } = captureProcessSignalHandlers();

    try {
      const servePromise = serveAcpGateway({});
      await emitHelloAndWaitForAgentSideConnection();

      expect(mockState.sqliteEventLedgers).toHaveLength(1);
      expect((mockState.agentOptions[0] as { eventLedger?: unknown }).eventLedger).toBe(
        mockState.sqliteEventLedgers[0],
      );

      await stopServeWithSigint(signalHandlers, servePromise);
    } finally {
      onceSpy.mockRestore();
    }
  });

  it("advertises approval handling and subscribes to run-scoped tool events", async () => {
    const { signalHandlers, onceSpy } = captureProcessSignalHandlers();

    try {
      const servePromise = serveAcpGateway({});
      await emitHelloAndWaitForAgentSideConnection();

      expect(mockState.gatewayOptions[0]?.caps).toEqual(["exec-approvals", "tool-events"]);

      await stopServeWithSigint(signalHandlers, servePromise);
    } finally {
      onceSpy.mockRestore();
    }
  });

  it("passes the resolved TLS fingerprint into the ACP gateway client", async () => {
    mockState.resolveGatewayClientBootstrap.mockResolvedValue({
      url: "wss://127.0.0.1:18789",
      urlSource: "local loopback",
      connectionDetails: {
        url: "wss://127.0.0.1:18789",
        urlSource: "local loopback",
        message: "Gateway target: wss://127.0.0.1:18789",
      },
      tlsFingerprint: "sha256:local",
      auth: {
        token: undefined,
        password: undefined,
      },
    });
    const { signalHandlers, onceSpy } = captureProcessSignalHandlers();

    try {
      const servePromise = serveAcpGateway({});
      await emitHelloAndWaitForAgentSideConnection();

      expect(mockState.gatewayOptions[0]?.tlsFingerprint).toBe("sha256:local");

      await stopServeWithSigint(signalHandlers, servePromise);
    } finally {
      onceSpy.mockRestore();
    }
  });

  it.each([
    {
      name: "default logging",
      opts: {},
      expected: ["openclaw acp: gateway event chat failed\n"],
    },
    {
      name: "verbose logging",
      opts: { verbose: true },
      expected: [
        "openclaw acp: gateway event chat failed\n",
        "openclaw acp: gateway event chat error: handler boom\n",
      ],
    },
  ])("contains rejected gateway event handling with $name", async ({ opts, expected }) => {
    const { signalHandlers, onceSpy } = captureProcessSignalHandlers();
    const writes: string[] = [];
    const writeSpy = vi
      .spyOn(process.stderr, "write")
      .mockImplementation((chunk: string | Uint8Array): boolean => {
        writes.push(String(chunk));
        return true;
      });
    mockState.agentHandleGatewayEvent.mockRejectedValueOnce(new Error("handler boom"));

    try {
      const servePromise = serveAcpGateway(opts);
      await emitHelloAndWaitForAgentSideConnection();

      getMockGateway().emitEvent({ event: "chat" });
      await vi.waitFor(() => {
        expect(writes).toEqual(expected);
      });

      await stopServeWithSigint(signalHandlers, servePromise);
    } finally {
      writeSpy.mockRestore();
      onceSpy.mockRestore();
    }
  });

  it("routes logs to stderr before loading gateway config", async () => {
    const { signalHandlers, onceSpy } = captureProcessSignalHandlers();

    try {
      const servePromise = serveAcpGateway({});
      await Promise.resolve();

      expect(mockState.routeLogsToStderr).toHaveBeenCalledTimes(1);
      expect(mockState.routeLogsToStderr.mock.invocationCallOrder[0]).toBeLessThan(
        mockState.resolveGatewayClientBootstrap.mock.invocationCallOrder[0] ??
          Number.MAX_SAFE_INTEGER,
      );

      await emitHelloAndWaitForAgentSideConnection();
      await stopServeWithSigint(signalHandlers, servePromise);
    } finally {
      onceSpy.mockRestore();
    }
  });

  it("rejects startup when gateway connect fails before hello", async () => {
    const onceSpy = vi
      .spyOn(process, "once")
      .mockImplementation(
        ((_signal: NodeJS.Signals, _handler: () => void) => process) as typeof process.once,
      );

    try {
      const servePromise = serveAcpGateway({});
      await Promise.resolve();

      const gateway = getMockGateway();
      gateway.emitConnectError("connect failed");
      await expect(servePromise).rejects.toThrow("connect failed");
      expect(mockState.agentSideConnectionCtor).not.toHaveBeenCalled();
    } finally {
      onceSpy.mockRestore();
    }
  });

  it("shuts down when buffered pre-hello ACP input exceeds its limit", async () => {
    mockState.rawInputChunks.push(new Uint8Array(1024 * 1024 + 1));
    const onceSpy = vi
      .spyOn(process, "once")
      .mockImplementation(
        ((_signal: NodeJS.Signals, _handler: () => void) => process) as typeof process.once,
      );

    try {
      await serveAcpGateway({});
      expect(mockState.agentSideConnectionCtor).not.toHaveBeenCalled();
      expect(mockState.closeOpenClawStateDatabaseAsync).toHaveBeenCalledOnce();
    } finally {
      onceSpy.mockRestore();
    }
  });

  it("passes resolved SecretInput gateway credentials to the ACP gateway client", async () => {
    mockState.resolveGatewayClientBootstrap.mockResolvedValue({
      url: "ws://127.0.0.1:18789",
      urlSource: "local loopback",
      connectionDetails: {
        url: "ws://127.0.0.1:18789",
        urlSource: "local loopback",
        message: "Gateway target: ws://127.0.0.1:18789",
      },
      auth: {
        token: undefined,
        password: "resolved-secret-password", // pragma: allowlist secret
      },
    });
    const { signalHandlers, onceSpy } = captureProcessSignalHandlers();

    try {
      const servePromise = serveAcpGateway({});
      await Promise.resolve();

      const bootstrapParams = getGatewayBootstrapParams();
      expect(bootstrapParams.env).toBe(process.env);
      expect(mockState.gatewayAuth[0]).toEqual({
        token: undefined,
        password: "resolved-secret-password", // pragma: allowlist secret
      });

      await emitHelloAndWaitForAgentSideConnection();
      await stopServeWithSigint(signalHandlers, servePromise);
    } finally {
      onceSpy.mockRestore();
    }
  });

  it("passes CLI URL override context into shared gateway auth resolution", async () => {
    const { signalHandlers, onceSpy } = captureProcessSignalHandlers();

    try {
      const servePromise = serveAcpGateway({
        gatewayUrl: "wss://override.example/ws",
      });
      await Promise.resolve();

      const bootstrapParams = getGatewayBootstrapParams();
      expect(bootstrapParams.env).toBe(process.env);
      expect(bootstrapParams.gatewayUrl).toBe("wss://override.example/ws");

      await emitHelloAndWaitForAgentSideConnection();
      await stopServeWithSigint(signalHandlers, servePromise);
    } finally {
      onceSpy.mockRestore();
    }
  });

  it("passes the configured Gateway URL into the ACP gateway client", async () => {
    mockState.resolveGatewayClientBootstrap.mockResolvedValue({
      url: "ws://127.0.0.1:19999",
      urlSource: "cli --url",
      connectionDetails: {
        url: "ws://127.0.0.1:19999",
        urlSource: "cli --url",
        message: "Gateway target: ws://127.0.0.1:19999",
      },
      auth: {
        token: undefined,
        password: undefined,
      },
    });
    const { signalHandlers, onceSpy } = captureProcessSignalHandlers();

    try {
      const servePromise = serveAcpGateway({
        gatewayUrl: "ws://127.0.0.1:19999",
      });
      await Promise.resolve();

      expect(mockState.gatewayOptions[0]?.url).toBe("ws://127.0.0.1:19999");

      await emitHelloAndWaitForAgentSideConnection();
      await stopServeWithSigint(signalHandlers, servePromise);
    } finally {
      onceSpy.mockRestore();
    }
  });

  it("does not proxy the standalone ACP control-plane Gateway connection", async () => {
    const { signalHandlers, onceSpy } = captureProcessSignalHandlers();

    try {
      const servePromise = serveAcpGateway({});
      await vi.waitFor(() => {
        expect(mockState.gateways).toHaveLength(1);
      });

      expect(mockState.startProxy).not.toHaveBeenCalled();
      await emitHelloAndWaitForAgentSideConnection();
      await stopServeWithSigint(signalHandlers, servePromise);
      expect(mockState.stopProxy).not.toHaveBeenCalled();
    } finally {
      onceSpy.mockRestore();
    }
  });

  it("closes the shared state database on shutdown", async () => {
    const { signalHandlers, onceSpy } = captureProcessSignalHandlers();
    expect(mockState.closeOpenClawStateDatabaseAsync).not.toHaveBeenCalled();

    try {
      const servePromise = serveAcpGateway({});
      await emitHelloAndWaitForAgentSideConnection();
      await stopServeWithSigint(signalHandlers, servePromise);
      expect(mockState.agentShutdown).toHaveBeenCalledOnce();
      expect(mockState.closeOpenClawStateDatabaseAsync).toHaveBeenCalledOnce();
    } finally {
      onceSpy.mockRestore();
    }
  });

  it("shuts down when the ACP client closes its stdio stream", async () => {
    const { onceSpy } = captureProcessSignalHandlers();

    try {
      const servePromise = serveAcpGateway({});
      await emitHelloAndWaitForAgentSideConnection();
      const closeConnection = mockState.closeAgentSideConnection;
      if (!closeConnection) {
        throw new Error("Expected mocked ACP connection close handler");
      }

      closeConnection();
      await servePromise;

      expect(mockState.agentShutdown).toHaveBeenCalledOnce();
      expect(mockState.closeOpenClawStateDatabaseAsync).toHaveBeenCalledOnce();
    } finally {
      onceSpy.mockRestore();
    }
  });

  it("waits for Gateway transport teardown before closing the shared state database", async () => {
    let resolveStop!: () => void;
    const stopPromise = new Promise<void>((resolve) => {
      resolveStop = resolve;
    });
    mockState.gatewayStopDeferred = { resolve: resolveStop, promise: stopPromise };
    const { signalHandlers, onceSpy } = captureProcessSignalHandlers();

    try {
      const servePromise = serveAcpGateway({});
      await emitHelloAndWaitForAgentSideConnection();
      signalHandlers.get("SIGTERM")?.();
      await vi.waitFor(() => {
        expect(mockState.agentShutdown).toHaveBeenCalledOnce();
      });
      expect(mockState.closeOpenClawStateDatabaseAsync).not.toHaveBeenCalled();

      resolveStop();
      await servePromise;
      expect(mockState.closeOpenClawStateDatabaseAsync).toHaveBeenCalledOnce();
    } finally {
      onceSpy.mockRestore();
    }
  });

  it("closes a real node:sqlite DatabaseSync handle through serveAcpGateway shutdown", async () => {
    // Use the real state-db module to open and verify a DatabaseSync handle —
    // this proves the full serveAcpGateway → shutdown → close path, not just
    // the closeOpenClawStateDatabaseAsync helper in isolation.
    const actualStateDb = await vi.importActual<typeof import("../state/openclaw-state-db.js")>(
      "../state/openclaw-state-db.js",
    );

    const realDb = actualStateDb.openOpenClawStateDatabase();
    expect(realDb.db.isOpen).toBe(true);
    expect(actualStateDb.isOpenClawStateDatabaseOpen()).toBe(true);

    // Wire the test mock so serveAcpGateway's shutdown handler calls the
    // real closeOpenClawStateDatabaseAsync, which closes the handle we opened above.
    mockState.closeOpenClawStateDatabaseAsync.mockImplementation(() =>
      actualStateDb.closeOpenClawStateDatabaseAsync(),
    );

    const { signalHandlers, onceSpy } = captureProcessSignalHandlers();
    try {
      const servePromise = serveAcpGateway({});
      await emitHelloAndWaitForAgentSideConnection();
      await stopServeWithSigint(signalHandlers, servePromise);

      // After serveAcpGateway shutdown completes, the real DatabaseSync
      // handle must be closed — proving the ACP shutdown fix works
      // end-to-end, not just in the helper function.
      expect(realDb.db.isOpen).toBe(false);
      expect(actualStateDb.isOpenClawStateDatabaseOpen()).toBe(false);
    } finally {
      await actualStateDb.closeOpenClawStateDatabaseAsync();
      onceSpy.mockRestore();
    }
  });

  it("replays an ACP frame read before Gateway hello to AgentSideConnection", async () => {
    const initializeRequest = {
      jsonrpc: "2.0",
      id: 1,
      method: "initialize",
      params: {
        protocolVersion: mockState.acpProtocolVersion,
        clientCapabilities: {},
      },
    };

    const [message] = await captureAcpMessagesAfterStartup([initializeRequest]);
    expect(message).toBe(initializeRequest);
  });

  it("coerces MCP date-string initialize protocol versions", async () => {
    const initializeRequest = {
      jsonrpc: "2.0",
      id: 1,
      method: "initialize",
      params: {
        protocolVersion: "2025-11-25",
        clientCapabilities: {},
      },
    };

    await expect(captureAcpMessagesAfterStartup([initializeRequest])).resolves.toEqual([
      {
        ...initializeRequest,
        params: {
          ...initializeRequest.params,
          protocolVersion: mockState.acpProtocolVersion,
        },
      },
    ]);
  });

  it("coerces non-integer numeric initialize protocol versions", async () => {
    const initializeRequest = {
      jsonrpc: "2.0",
      id: 1,
      method: "initialize",
      params: {
        protocolVersion: 1.5,
        clientCapabilities: {},
      },
    };

    await expect(captureAcpMessagesAfterStartup([initializeRequest])).resolves.toEqual([
      {
        ...initializeRequest,
        params: {
          ...initializeRequest.params,
          protocolVersion: mockState.acpProtocolVersion,
        },
      },
    ]);
  });

  it("passes uint16 numeric initialize protocol versions through unchanged", async () => {
    const initializeRequest = {
      jsonrpc: "2.0",
      id: 1,
      method: "initialize",
      params: {
        protocolVersion: 42,
        clientCapabilities: {},
      },
    };

    const [message] = await captureAcpMessagesAfterStartup([initializeRequest]);
    expect(message).toBe(initializeRequest);
  });

  it("passes non-initialize JSON-RPC messages through unchanged", async () => {
    const sessionRequest = {
      jsonrpc: "2.0",
      id: 2,
      method: "session/new",
      params: {
        protocolVersion: "2025-11-25",
        cwd: "/tmp/openclaw",
      },
    };

    const [message] = await captureAcpMessagesAfterStartup([sessionRequest]);
    expect(message).toBe(sessionRequest);
  });
});