@agentrq/acp-gateway 0.2.17 → 0.2.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,7 +4,7 @@ import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import { EventEmitter } from "node:events";
6
6
  import * as acp from "@agentclientprotocol/sdk";
7
- import { createAcpSessionSwitcher, checkForNextTask, mapMcpServers, TaskQueue, getOrCreateSession, openIdleSession, resetIdleSession, activeSessions, AuthenticationFailed, IDLE_SESSION_KEY, loginCommandFor, authConfig, modelConfig, createSessionWithAuth, isInteractiveTerminal, openAgentConnection, parseGatewayArgs, assertAgentRunnable, helpText, isRunnable, resolveOnPath, spawnTarget, needsShell, escapeCmdCommand, quoteForCmd, spawnArgsFor, terminateAgentProcess, printHelp, resolveAgentCommand, runListAgents, pickHumanApprovalMode, enforceHumanApprovalMode, handleAgentModeChange, runAgentCommand, findActiveSession, handleTaskCancellation, handleSetModel, applyModelSelection, cancelledTaskSeq, markTaskCancelled, isTaskCancelled, nextTaskSeq, supportsCloseSession, closeSession, closeAllSessions, setupSignalHandlers, } from "../index.js";
7
+ import { createAcpSessionSwitcher, checkForNextTask, mapMcpServers, TaskQueue, getOrCreateSession, openIdleSession, resetIdleSession, activeSessions, AuthenticationFailed, IDLE_SESSION_KEY, loginCommandFor, authConfig, modelConfig, createSessionWithAuth, isInteractiveTerminal, openAgentConnection, parseGatewayArgs, assertAgentRunnable, helpText, isRunnable, resolveOnPath, spawnTarget, needsShell, escapeCmdCommand, quoteForCmd, spawnArgsFor, terminateAgentProcess, printHelp, resolveAgentCommand, runListAgents, pickHumanApprovalMode, enforceHumanApprovalMode, handleAgentModeChange, runAgentCommand, findActiveSession, handleTaskCancellation, handleSetModel, handleSetConcurrency, runTurnForTask, resetTaskTurns, registerConcurrencyListeners, reportConcurrency, applyModelSelection, cancelledTaskSeq, markTaskCancelled, isTaskCancelled, nextTaskSeq, supportsCloseSession, closeSession, closeAllSessions, setupSignalHandlers, } from "../index.js";
8
8
  import { sendModelsNotification } from "../acpClient.js";
9
9
  import { AUTH_REQUIRED_CODE } from "../auth.js";
10
10
  /**
@@ -308,6 +308,58 @@ describe("index", () => {
308
308
  });
309
309
  expect(mockAcpClient.flushReply).toHaveBeenCalledWith("current-session");
310
310
  });
311
+ it("runs a queued task through the queue, and behind any turn it already has", async () => {
312
+ // The queue is how a concurrency limit is enforced at all, and the turn
313
+ // guard is what keeps a second delivery of this task off a session that
314
+ // is already mid-prompt.
315
+ resetTaskTurns();
316
+ mockMcpBridge.callTool.mockResolvedValue({
317
+ isError: false,
318
+ content: [{ type: "text", text: "Task ID: T-Queued\nwork please" }],
319
+ });
320
+ const queue = new TaskQueue(2);
321
+ let releaseEarlier;
322
+ const earlier = new Promise((resolve) => { releaseEarlier = resolve; });
323
+ const earlierTurn = runTurnForTask("T-Queued", () => earlier);
324
+ const checking = checkForNextTask(mockMcpBridge, mockConnection, mockSessionSwitcher, mockAcpClient, queue);
325
+ await new Promise((resolve) => setTimeout(resolve, 10));
326
+ expect(mockConnection.prompt).not.toHaveBeenCalled();
327
+ releaseEarlier();
328
+ await Promise.all([earlierTurn, checking]);
329
+ expect(mockConnection.prompt).toHaveBeenCalledTimes(1);
330
+ expect(queue.getActiveCount()).toBe(0);
331
+ });
332
+ it("waits for the turn ahead of it without holding a concurrency slot", async () => {
333
+ // A second message on one chat arrives as a second delivery of one task
334
+ // and has to wait for the first. Waiting *inside* a queue slot would hold
335
+ // a share of the limit while doing nothing at all — so a chat with a few
336
+ // messages in flight could hold every slot the gateway has and stop it
337
+ // running anything else, which is precisely what raising the limit is
338
+ // supposed to prevent.
339
+ resetTaskTurns();
340
+ mockMcpBridge.callTool.mockResolvedValue({
341
+ isError: false,
342
+ content: [{ type: "text", text: "Task ID: T-Chatty\nand another thing" }],
343
+ });
344
+ const queue = new TaskQueue(1);
345
+ let releaseEarlier;
346
+ const earlier = new Promise((resolve) => { releaseEarlier = resolve; });
347
+ const earlierTurn = runTurnForTask("T-Chatty", () => earlier);
348
+ const checking = checkForNextTask(mockMcpBridge, mockConnection, mockSessionSwitcher, mockAcpClient, queue);
349
+ await new Promise((resolve) => setTimeout(resolve, 10));
350
+ // Behind the turn, but not occupying the gateway's only slot.
351
+ expect(mockConnection.prompt).not.toHaveBeenCalled();
352
+ expect(queue.getActiveCount()).toBe(0);
353
+ // So an unrelated task still runs while the duplicate waits.
354
+ let unrelatedRan = false;
355
+ const unrelated = queue.run(async () => { unrelatedRan = true; });
356
+ await new Promise((resolve) => setTimeout(resolve, 10));
357
+ expect(unrelatedRan).toBe(true);
358
+ releaseEarlier();
359
+ await Promise.all([earlierTurn, checking, unrelated]);
360
+ expect(mockConnection.prompt).toHaveBeenCalledTimes(1);
361
+ expect(queue.getActiveCount()).toBe(0);
362
+ });
311
363
  it("forwards a slash command to the agent unmodified", async () => {
312
364
  // ACP runs a command as ordinary prompt text and the agent matches the
313
365
  // prefix at the *start* of it, so anything prepended here — a wrapper, a
@@ -404,6 +456,322 @@ describe("index", () => {
404
456
  expect(logSpy).toHaveBeenCalledWith("[queue] Error executing queued task:", expect.any(Error));
405
457
  logSpy.mockRestore();
406
458
  });
459
+ it("reports the limit it was built with", () => {
460
+ expect(new TaskQueue(3).getMaxConcurrency()).toBe(3);
461
+ });
462
+ it("starts every task a raised limit has room for, not one at a time", async () => {
463
+ const queue = new TaskQueue(1);
464
+ let release;
465
+ const held = new Promise((resolve) => { release = resolve; });
466
+ const started = [];
467
+ const runs = [
468
+ queue.run(async () => { started.push(0); await held; }),
469
+ queue.run(async () => { started.push(1); }),
470
+ queue.run(async () => { started.push(2); }),
471
+ queue.run(async () => { started.push(3); }),
472
+ ];
473
+ // Only the first is running; the other three are waiting on a limit of 1.
474
+ expect(queue.getActiveCount()).toBe(1);
475
+ expect(queue.getQueueLength()).toBe(3);
476
+ queue.setMaxConcurrency(4);
477
+ // All three waiting tasks start at once, without the running one
478
+ // finishing first — a raise that took effect one task per completion
479
+ // would leave two of them still queued here.
480
+ expect(started).toEqual([0, 1, 2, 3]);
481
+ expect(queue.getMaxConcurrency()).toBe(4);
482
+ release();
483
+ await Promise.all(runs);
484
+ });
485
+ it("starts only as many as the new limit allows, and leaves the rest queued", async () => {
486
+ const queue = new TaskQueue(1);
487
+ let release;
488
+ const held = new Promise((resolve) => { release = resolve; });
489
+ const runs = [
490
+ queue.run(async () => { await held; }),
491
+ queue.run(async () => { await held; }),
492
+ queue.run(async () => { await held; }),
493
+ queue.run(async () => { await held; }),
494
+ ];
495
+ queue.setMaxConcurrency(2);
496
+ expect(queue.getActiveCount()).toBe(2);
497
+ expect(queue.getQueueLength()).toBe(2);
498
+ release();
499
+ await Promise.all(runs);
500
+ });
501
+ it("never interrupts work already in flight when the limit is lowered", async () => {
502
+ const queue = new TaskQueue(3);
503
+ let release;
504
+ const held = new Promise((resolve) => { release = resolve; });
505
+ const finished = [];
506
+ const runs = [
507
+ queue.run(async () => { await held; finished.push(0); }),
508
+ queue.run(async () => { await held; finished.push(1); }),
509
+ queue.run(async () => { await held; finished.push(2); }),
510
+ ];
511
+ const queued = queue.run(async () => { finished.push(3); });
512
+ expect(queue.getActiveCount()).toBe(3);
513
+ queue.setMaxConcurrency(1);
514
+ // The three that already have the agent's attention keep it — a lowered
515
+ // limit is honoured going forward, not retroactively.
516
+ expect(queue.getActiveCount()).toBe(3);
517
+ expect(queue.getQueueLength()).toBe(1);
518
+ release();
519
+ await Promise.all([...runs, queued]);
520
+ expect(finished).toEqual([0, 1, 2, 3]);
521
+ expect(queue.getActiveCount()).toBe(0);
522
+ });
523
+ it("holds the queue until the active count falls under a lowered limit", async () => {
524
+ const queue = new TaskQueue(2);
525
+ const releases = [];
526
+ const hold = () => new Promise((resolve) => { releases.push(resolve); });
527
+ const first = queue.run(hold);
528
+ const second = queue.run(hold);
529
+ const third = queue.run(async () => { });
530
+ queue.setMaxConcurrency(1);
531
+ expect(queue.getQueueLength()).toBe(1);
532
+ // One finishing still leaves one running, which is already the whole of
533
+ // the new limit, so the waiting task must not start yet.
534
+ releases[0]();
535
+ await first;
536
+ expect(queue.getQueueLength()).toBe(1);
537
+ expect(queue.getActiveCount()).toBe(1);
538
+ releases[1]();
539
+ await second;
540
+ await third;
541
+ expect(queue.getActiveCount()).toBe(0);
542
+ });
543
+ it("does nothing, and says nothing, when the limit has not actually changed", () => {
544
+ const queue = new TaskQueue(4);
545
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
546
+ errorSpy.mockClear();
547
+ queue.setMaxConcurrency(4);
548
+ expect(queue.getMaxConcurrency()).toBe(4);
549
+ expect(errorSpy).not.toHaveBeenCalled();
550
+ errorSpy.mockRestore();
551
+ });
552
+ });
553
+ describe("handleSetConcurrency", () => {
554
+ let errorSpy;
555
+ beforeEach(() => {
556
+ errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
557
+ });
558
+ afterEach(() => {
559
+ errorSpy.mockRestore();
560
+ });
561
+ const fakeConcurrencyBridge = () => ({
562
+ sendNotification: vi.fn().mockResolvedValue(undefined),
563
+ });
564
+ it("applies the limit the workspace asked for and reports it back", async () => {
565
+ const queue = new TaskQueue(1);
566
+ const bridge = fakeConcurrencyBridge();
567
+ await handleSetConcurrency({ maxConcurrency: 5 }, queue, bridge);
568
+ expect(queue.getMaxConcurrency()).toBe(5);
569
+ expect(bridge.sendNotification).toHaveBeenCalledWith("notifications/claude/channel/concurrency", expect.objectContaining({ maxConcurrency: 5, active: 0, queued: 0 }));
570
+ });
571
+ it("reports the clamped limit, so the interface shows what took effect", async () => {
572
+ const queue = new TaskQueue(1);
573
+ const bridge = fakeConcurrencyBridge();
574
+ await handleSetConcurrency({ maxConcurrency: 100_000 }, queue, bridge);
575
+ expect(queue.getMaxConcurrency()).toBe(64);
576
+ expect(bridge.sendNotification).toHaveBeenCalledWith("notifications/claude/channel/concurrency", expect.objectContaining({ maxConcurrency: 64 }));
577
+ });
578
+ it("keeps the current limit when asked for something that is not a number", async () => {
579
+ const queue = new TaskQueue(3);
580
+ const bridge = fakeConcurrencyBridge();
581
+ await handleSetConcurrency({ maxConcurrency: "lots" }, queue, bridge);
582
+ expect(queue.getMaxConcurrency()).toBe(3);
583
+ expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('asking for "lots"'));
584
+ });
585
+ it("still answers a rejected value, rather than leaving the control hanging", async () => {
586
+ const queue = new TaskQueue(3);
587
+ const bridge = fakeConcurrencyBridge();
588
+ await handleSetConcurrency({}, queue, bridge);
589
+ // The interface moved a control and is waiting to see where it landed;
590
+ // silence would leave it showing a limit this gateway never adopted.
591
+ expect(bridge.sendNotification).toHaveBeenCalledWith("notifications/claude/channel/concurrency", expect.objectContaining({ maxConcurrency: 3 }));
592
+ });
593
+ it("reports what the queue is doing under the new limit", async () => {
594
+ const queue = new TaskQueue(1);
595
+ const bridge = fakeConcurrencyBridge();
596
+ let release;
597
+ const held = new Promise((resolve) => { release = resolve; });
598
+ const runs = [
599
+ queue.run(async () => { await held; }),
600
+ queue.run(async () => { await held; }),
601
+ queue.run(async () => { await held; }),
602
+ ];
603
+ await handleSetConcurrency({ maxConcurrency: 2 }, queue, bridge);
604
+ expect(bridge.sendNotification).toHaveBeenCalledWith("notifications/claude/channel/concurrency", expect.objectContaining({ maxConcurrency: 2, active: 2, queued: 1 }));
605
+ release();
606
+ await Promise.all(runs);
607
+ });
608
+ it("answers even when applying the change throws", async () => {
609
+ // "Always answered" is the design; it must not depend on the change
610
+ // itself going well, or the interface is left showing a limit nothing
611
+ // adopted precisely when something has gone wrong.
612
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
613
+ const queue = new TaskQueue(3);
614
+ const bridge = fakeConcurrencyBridge();
615
+ vi.spyOn(queue, "setMaxConcurrency").mockImplementation(() => {
616
+ throw new Error("queue is wedged");
617
+ });
618
+ await expect(handleSetConcurrency({ maxConcurrency: 5 }, queue, bridge)).rejects.toThrow("queue is wedged");
619
+ expect(bridge.sendNotification).toHaveBeenCalledWith("notifications/claude/channel/concurrency", expect.objectContaining({ maxConcurrency: 3 }));
620
+ errorSpy.mockRestore();
621
+ });
622
+ it("applies the limit even with no bridge to report it to", async () => {
623
+ const queue = new TaskQueue(1);
624
+ await handleSetConcurrency({ maxConcurrency: 6 }, queue);
625
+ expect(queue.getMaxConcurrency()).toBe(6);
626
+ });
627
+ });
628
+ describe("runTurnForTask", () => {
629
+ beforeEach(() => {
630
+ resetTaskTurns();
631
+ });
632
+ it("holds a second message on a chat until the first turn has finished", async () => {
633
+ // A session takes one turn at a time, and agentrq reuses a chat's id as
634
+ // the task id — so two messages to one chat are two deliveries of one
635
+ // task, and running them at once puts two prompts on one session.
636
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
637
+ const events = [];
638
+ let releaseFirst;
639
+ const firstHeld = new Promise((resolve) => { releaseFirst = resolve; });
640
+ const first = runTurnForTask("T-Chat", async () => {
641
+ events.push("first:start");
642
+ await firstHeld;
643
+ events.push("first:end");
644
+ });
645
+ const second = runTurnForTask("T-Chat", async () => {
646
+ events.push("second:start");
647
+ });
648
+ await new Promise((resolve) => setTimeout(resolve, 10));
649
+ expect(events).toEqual(["first:start"]);
650
+ releaseFirst();
651
+ await Promise.all([first, second]);
652
+ expect(events).toEqual(["first:start", "first:end", "second:start"]);
653
+ errorSpy.mockRestore();
654
+ });
655
+ it("lets a second message through after the first turn failed", async () => {
656
+ // Losing it would lose what someone typed, and the first message erroring
657
+ // is no reason the agent should never hear the second.
658
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
659
+ const ran = [];
660
+ const first = runTurnForTask("T-Fail", async () => {
661
+ ran.push("first");
662
+ throw new Error("agent blew up");
663
+ });
664
+ const second = runTurnForTask("T-Fail", async () => {
665
+ ran.push("second");
666
+ });
667
+ await expect(first).rejects.toThrow("agent blew up");
668
+ await second;
669
+ expect(ran).toEqual(["first", "second"]);
670
+ errorSpy.mockRestore();
671
+ });
672
+ it("keeps a queue of messages in the order they were sent", async () => {
673
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
674
+ const ran = [];
675
+ const turns = [0, 1, 2, 3].map((n) => runTurnForTask("T-Order", async () => {
676
+ await new Promise((resolve) => setTimeout(resolve, 5 - n));
677
+ ran.push(n);
678
+ }));
679
+ await Promise.all(turns);
680
+ expect(ran).toEqual([0, 1, 2, 3]);
681
+ errorSpy.mockRestore();
682
+ });
683
+ it("never makes one chat wait on another", async () => {
684
+ // Serialising per task, not globally — a shared lock would undo the whole
685
+ // point of a concurrency limit above 1.
686
+ const started = [];
687
+ let release;
688
+ const held = new Promise((resolve) => { release = resolve; });
689
+ const a = runTurnForTask("T-One", async () => { started.push("a"); await held; });
690
+ const b = runTurnForTask("T-Two", async () => { started.push("b"); await held; });
691
+ await new Promise((resolve) => setTimeout(resolve, 10));
692
+ expect(started.sort()).toEqual(["a", "b"]);
693
+ release();
694
+ await Promise.all([a, b]);
695
+ });
696
+ it("runs a delivery with no task id straight away", async () => {
697
+ let ran = false;
698
+ await runTurnForTask(undefined, async () => { ran = true; });
699
+ expect(ran).toBe(true);
700
+ });
701
+ it("forgets a task once its last turn is done, rather than growing forever", async () => {
702
+ await runTurnForTask("T-Clean", async () => { });
703
+ const ran = [];
704
+ // A stale chain tail would make this wait on an already-settled promise
705
+ // instead of starting at once; a leaked one would never be collected.
706
+ await runTurnForTask("T-Clean", async () => { ran.push("second"); });
707
+ expect(ran).toEqual(["second"]);
708
+ });
709
+ });
710
+ describe("registerConcurrencyListeners", () => {
711
+ let errorSpy;
712
+ beforeEach(() => {
713
+ errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
714
+ });
715
+ afterEach(() => {
716
+ errorSpy.mockRestore();
717
+ });
718
+ const listeningBridge = () => {
719
+ const bridge = new EventEmitter();
720
+ bridge.sendNotification = vi.fn().mockResolvedValue(undefined);
721
+ return bridge;
722
+ };
723
+ const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
724
+ it("applies a limit the workspace pushes while the gateway is running", async () => {
725
+ const bridge = listeningBridge();
726
+ const queue = new TaskQueue(1);
727
+ registerConcurrencyListeners(bridge, queue);
728
+ bridge.emit("setConcurrency", { maxConcurrency: 5 });
729
+ await settle();
730
+ expect(queue.getMaxConcurrency()).toBe(5);
731
+ expect(bridge.sendNotification).toHaveBeenCalledWith("notifications/claude/channel/concurrency", expect.objectContaining({ maxConcurrency: 5 }));
732
+ });
733
+ it("re-reports the limit on reconnect, which the workspace has just forgotten", async () => {
734
+ const bridge = listeningBridge();
735
+ const queue = new TaskQueue(1);
736
+ registerConcurrencyListeners(bridge, queue);
737
+ bridge.emit("setConcurrency", { maxConcurrency: 7 });
738
+ await settle();
739
+ bridge.sendNotification.mockClear();
740
+ bridge.emit("reconnected");
741
+ await settle();
742
+ // The limit in force, not the one the gateway booted with.
743
+ expect(bridge.sendNotification).toHaveBeenCalledWith("notifications/claude/channel/concurrency", expect.objectContaining({ maxConcurrency: 7 }));
744
+ });
745
+ it("logs rather than throws when applying the change goes wrong", async () => {
746
+ const bridge = listeningBridge();
747
+ const queue = new TaskQueue(1);
748
+ vi.spyOn(queue, "setMaxConcurrency").mockImplementation(() => {
749
+ throw new Error("queue is wedged");
750
+ });
751
+ registerConcurrencyListeners(bridge, queue);
752
+ // An unhandled rejection here would be logged and swallowed by the
753
+ // process-level net in production, which is a worse place to find out.
754
+ bridge.emit("setConcurrency", { maxConcurrency: 2 });
755
+ await settle();
756
+ expect(errorSpy).toHaveBeenCalledWith("[bridge] Error handling concurrency change:", expect.any(Error));
757
+ });
758
+ });
759
+ describe("reportConcurrency", () => {
760
+ it("describes the queue as it stands", async () => {
761
+ const bridge = { sendNotification: vi.fn().mockResolvedValue(undefined) };
762
+ const queue = new TaskQueue(2);
763
+ let release;
764
+ const held = new Promise((resolve) => { release = resolve; });
765
+ const runs = [
766
+ queue.run(async () => { await held; }),
767
+ queue.run(async () => { await held; }),
768
+ queue.run(async () => { await held; }),
769
+ ];
770
+ await reportConcurrency(bridge, queue);
771
+ expect(bridge.sendNotification).toHaveBeenCalledWith("notifications/claude/channel/concurrency", expect.objectContaining({ maxConcurrency: 2, active: 2, queued: 1 }));
772
+ release();
773
+ await Promise.all(runs);
774
+ });
407
775
  });
408
776
  describe("getOrCreateSession", () => {
409
777
  beforeEach(() => {
@@ -429,6 +797,73 @@ describe("index", () => {
429
797
  expect(session).toBeDefined();
430
798
  expect(activeSessions.has(IDLE_SESSION_KEY)).toBe(true);
431
799
  });
800
+ it("gives two deliveries of one task a single agent, not one each", async () => {
801
+ // activeSessions only learns about a session once the agent has spawned,
802
+ // handshaken and opened it. Two deliveries inside that window both missed
803
+ // the cache and both spawned — two processes on one task, and only the
804
+ // second reachable afterwards, so the first could never be closed.
805
+ const mockBridge = fakeBridge();
806
+ spawnedAgents.length = 0;
807
+ const [first, second] = await Promise.all([
808
+ getOrCreateSession("T-Dup", ["node", "agent.js"], [], { env: {} }, mockBridge),
809
+ getOrCreateSession("T-Dup", ["node", "agent.js"], [], { env: {} }, mockBridge),
810
+ ]);
811
+ expect(spawnedAgents.length).toBe(1);
812
+ expect(second).toBe(first);
813
+ expect(activeSessions.size).toBe(1);
814
+ });
815
+ it("holds a crowd of simultaneous deliveries to one agent", async () => {
816
+ const mockBridge = fakeBridge();
817
+ spawnedAgents.length = 0;
818
+ const sessions = await Promise.all(Array.from({ length: 8 }, () => getOrCreateSession("T-Crowd", ["node", "agent.js"], [], { env: {} }, mockBridge)));
819
+ expect(spawnedAgents.length).toBe(1);
820
+ expect(new Set(sessions).size).toBe(1);
821
+ });
822
+ it("still opens separate agents for separate tasks at the same time", async () => {
823
+ // The guard is per task, not a lock on opening sessions at all — a raised
824
+ // concurrency limit would be worth nothing if it serialised every spawn.
825
+ const mockBridge = fakeBridge();
826
+ spawnedAgents.length = 0;
827
+ const [a, b, c] = await Promise.all([
828
+ getOrCreateSession("T-A", ["node", "agent.js"], [], { env: {} }, mockBridge),
829
+ getOrCreateSession("T-B", ["node", "agent.js"], [], { env: {} }, mockBridge),
830
+ getOrCreateSession("T-C", ["node", "agent.js"], [], { env: {} }, mockBridge),
831
+ ]);
832
+ expect(spawnedAgents.length).toBe(3);
833
+ expect(new Set([a, b, c]).size).toBe(3);
834
+ expect(activeSessions.size).toBe(3);
835
+ });
836
+ it("serves a later delivery from the cache, not from a spent attempt", async () => {
837
+ const mockBridge = fakeBridge();
838
+ spawnedAgents.length = 0;
839
+ const first = await getOrCreateSession("T-Later", ["node", "agent.js"], [], { env: {} }, mockBridge);
840
+ const second = await getOrCreateSession("T-Later", ["node", "agent.js"], [], { env: {} }, mockBridge);
841
+ expect(second).toBe(first);
842
+ expect(spawnedAgents.length).toBe(1);
843
+ });
844
+ it("lets a task try again after the attempt it waited on failed", async () => {
845
+ // A failed attempt must not leave the key wedged, or one bad spawn would
846
+ // cost the task every later delivery too.
847
+ const mockBridge = fakeBridge();
848
+ newSessionError.value = new Error("agent said no");
849
+ await expect(getOrCreateSession("T-Retry", ["node", "agent.js"], [], { env: {} }, mockBridge)).rejects.toThrow("agent said no");
850
+ newSessionError.value = null;
851
+ const recovered = await getOrCreateSession("T-Retry", ["node", "agent.js"], [], { env: {} }, mockBridge);
852
+ expect(recovered).toBeDefined();
853
+ expect(activeSessions.has("T-Retry")).toBe(true);
854
+ });
855
+ it("fails both waiters together rather than spawning a second agent to retry", async () => {
856
+ const mockBridge = fakeBridge();
857
+ newSessionError.value = new Error("agent said no");
858
+ spawnedAgents.length = 0;
859
+ const results = await Promise.allSettled([
860
+ getOrCreateSession("T-BothFail", ["node", "agent.js"], [], { env: {} }, mockBridge),
861
+ getOrCreateSession("T-BothFail", ["node", "agent.js"], [], { env: {} }, mockBridge),
862
+ ]);
863
+ expect(results.every((r) => r.status === "rejected")).toBe(true);
864
+ expect(spawnedAgents.length).toBe(1);
865
+ newSessionError.value = null;
866
+ });
432
867
  it("hands the startup session to the first task rather than opening a second", async () => {
433
868
  // Sessions are keyed by task, so without this the first real task would
434
869
  // spawn a second agent alongside the one already running.
@@ -834,6 +1269,73 @@ describe("index", () => {
834
1269
  expect(parseGatewayArgs(["--max-concurrency", "4"]).maxConcurrency).toBe(4);
835
1270
  expect(parseGatewayArgs(["--maxConcurrency", "8"]).maxConcurrency).toBe(8);
836
1271
  });
1272
+ it("should refuse a concurrency of zero, which used to stall the queue forever", () => {
1273
+ // Accepted before, and then every task waited on a limit of 0 that no
1274
+ // completion could ever get under.
1275
+ expect(parseGatewayArgs(["--max-concurrency", "0"]).maxConcurrency).toBe(1);
1276
+ expect(parseGatewayArgs(["--max-concurrency", "-3"]).maxConcurrency).toBe(1);
1277
+ });
1278
+ it("should cap the concurrency flag at the same ceiling the workspace gets", () => {
1279
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
1280
+ expect(parseGatewayArgs(["--max-concurrency", "10000"]).maxConcurrency).toBe(64);
1281
+ errorSpy.mockRestore();
1282
+ });
1283
+ it("should say so when it caps the flag, since nothing reports a flag back", () => {
1284
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
1285
+ errorSpy.mockClear();
1286
+ parseGatewayArgs(["--max-concurrency", "128"]);
1287
+ // An existing --max-concurrency 128 would otherwise quietly boot at 64.
1288
+ expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("--max-concurrency 128 is outside 1-64; using 64."));
1289
+ errorSpy.mockRestore();
1290
+ });
1291
+ it("should not warn about a fraction, which is truncated rather than capped", () => {
1292
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
1293
+ errorSpy.mockClear();
1294
+ expect(parseGatewayArgs(["--max-concurrency", "4.9"]).maxConcurrency).toBe(4);
1295
+ expect(errorSpy).not.toHaveBeenCalled();
1296
+ errorSpy.mockRestore();
1297
+ });
1298
+ it("should leave a non-numeric token alone, since it is the agent command", () => {
1299
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
1300
+ // `--max-concurrency claude` is the number left out, not a mistyped
1301
+ // number. Eating the token would leave the gateway nothing to run.
1302
+ expect(parseGatewayArgs(["--max-concurrency", "claude"])).toMatchObject({
1303
+ maxConcurrency: 1,
1304
+ rest: ["claude"],
1305
+ });
1306
+ errorSpy.mockRestore();
1307
+ });
1308
+ it("should consume a malformed concurrency value instead of leaving it to be run", () => {
1309
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
1310
+ // `rest` is the agent command when no `--` was used, so a value left
1311
+ // behind here sent the gateway looking for an agent called "8x".
1312
+ expect(parseGatewayArgs(["--max-concurrency", "8x", "claude"])).toMatchObject({
1313
+ maxConcurrency: 1,
1314
+ rest: ["claude"],
1315
+ });
1316
+ expect(parseGatewayArgs(["--max-concurrency", "8x", "--", "claude"]).rest).toEqual([
1317
+ "--",
1318
+ "claude",
1319
+ ]);
1320
+ errorSpy.mockRestore();
1321
+ });
1322
+ it("should say why a malformed concurrency value was ignored", () => {
1323
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
1324
+ errorSpy.mockClear();
1325
+ parseGatewayArgs(["--max-concurrency", "8x"]);
1326
+ expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('--max-concurrency "8x" is not a number of tasks'));
1327
+ errorSpy.mockRestore();
1328
+ });
1329
+ it("should stay silent when the flag simply has no value to read", () => {
1330
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
1331
+ errorSpy.mockClear();
1332
+ expect(parseGatewayArgs(["--max-concurrency", "--logout"])).toMatchObject({
1333
+ maxConcurrency: 1,
1334
+ command: "logout",
1335
+ });
1336
+ expect(errorSpy).not.toHaveBeenCalled();
1337
+ errorSpy.mockRestore();
1338
+ });
837
1339
  it("should keep the default when the concurrency value is missing or not a number", () => {
838
1340
  expect(parseGatewayArgs(["--max-concurrency"]).maxConcurrency).toBe(1);
839
1341
  expect(parseGatewayArgs(["--max-concurrency", "many"]).maxConcurrency).toBe(1);
@@ -1370,6 +1872,10 @@ describe("index", () => {
1370
1872
  it("should document the default concurrency of 1", () => {
1371
1873
  expect(helpText()).toContain("Defaults to 1.");
1372
1874
  });
1875
+ it("should document the concurrency range and that agentrq can change it", () => {
1876
+ expect(helpText()).toContain("1 to 64.");
1877
+ expect(helpText()).toContain("agentrq can change it while running.");
1878
+ });
1373
1879
  });
1374
1880
  describe("printHelp", () => {
1375
1881
  it("should print the help text", () => {
@@ -2063,16 +2569,72 @@ describe("index", () => {
2063
2569
  let errorSpy;
2064
2570
  beforeEach(() => {
2065
2571
  activeSessions.clear();
2572
+ // Also clears the record of agents spawned by earlier tests, which this
2573
+ // one now reaps.
2574
+ resetIdleSession();
2066
2575
  errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
2067
2576
  });
2068
2577
  afterEach(() => {
2069
2578
  activeSessions.clear();
2579
+ resetIdleSession();
2070
2580
  errorSpy.mockRestore();
2071
2581
  });
2072
2582
  it("does nothing when activeSessions is empty", async () => {
2073
2583
  await closeAllSessions();
2074
2584
  expect(activeSessions.size).toBe(0);
2075
2585
  });
2586
+ it("ends an agent that spawned but never opened a session", async () => {
2587
+ // activeSessions only holds agents that got as far as an open session,
2588
+ // so shutting down on it alone left behind the agent still handshaking
2589
+ // — and the one stopped waiting for a login, which is the case most
2590
+ // likely to be interrupted, since it can sit there indefinitely. One
2591
+ // that quits when its stdin closes got away with it; one with an event
2592
+ // loop of its own did not.
2593
+ newSessionHangs.value = true;
2594
+ spawnedAgents.length = 0;
2595
+ const opening = getOrCreateSession("T-Interrupted", ["node", "agent.js"], [], { env: {} }, fakeBridge());
2596
+ await new Promise((resolve) => setTimeout(resolve, 10));
2597
+ // Spawned, and tracked by nothing that shutdown used to look at.
2598
+ expect(spawnedAgents.length).toBe(1);
2599
+ expect(activeSessions.size).toBe(0);
2600
+ await closeAllSessions(10);
2601
+ expect(spawnedAgents[0].kill).toHaveBeenCalled();
2602
+ expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("never opened a session"));
2603
+ newSessionHangs.value = false;
2604
+ void opening.catch(() => { });
2605
+ });
2606
+ it("keeps ending the rest when one refuses to die", async () => {
2607
+ // Shutdown is the last thing that runs; one process that will not go
2608
+ // must not take the others' only chance to go with it.
2609
+ newSessionHangs.value = true;
2610
+ spawnedAgents.length = 0;
2611
+ const opening = [
2612
+ getOrCreateSession("T-Stuck-A", ["node", "agent.js"], [], { env: {} }, fakeBridge()),
2613
+ getOrCreateSession("T-Stuck-B", ["node", "agent.js"], [], { env: {} }, fakeBridge()),
2614
+ ];
2615
+ await new Promise((resolve) => setTimeout(resolve, 10));
2616
+ expect(spawnedAgents.length).toBe(2);
2617
+ spawnedAgents[0].kill.mockImplementation(() => {
2618
+ throw new Error("no such process");
2619
+ });
2620
+ await closeAllSessions(10);
2621
+ expect(spawnedAgents[1].kill).toHaveBeenCalled();
2622
+ expect(errorSpy).toHaveBeenCalledWith("[acp] Error ending an agent process:", expect.any(Error));
2623
+ newSessionHangs.value = false;
2624
+ for (const p of opening)
2625
+ void p.catch(() => { });
2626
+ });
2627
+ it("does not report a cleanly closed session as one left behind", async () => {
2628
+ // Its process is ended by closeSession; counting it again would report
2629
+ // a leak that is not there.
2630
+ newSessionHangs.value = false;
2631
+ spawnedAgents.length = 0;
2632
+ await getOrCreateSession("T-Clean-Exit", ["node", "agent.js"], [], { env: {} }, fakeBridge());
2633
+ expect(activeSessions.size).toBe(1);
2634
+ await closeAllSessions(10);
2635
+ expect(spawnedAgents[0].kill).toHaveBeenCalled();
2636
+ expect(errorSpy).not.toHaveBeenCalledWith(expect.stringContaining("never opened a session"));
2637
+ });
2076
2638
  it("closes all unique active sessions in parallel and clears map", async () => {
2077
2639
  const cancel1 = vi.fn().mockResolvedValue(undefined);
2078
2640
  const cancel2 = vi.fn().mockResolvedValue(undefined);