@agentrq/acp-gateway 0.2.17 → 0.2.19

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, createTaskQueue, resetConcurrencyReports, 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,484 @@ 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
+ describe("saying when its numbers move", () => {
553
+ /** Records what the queue looked like at each announcement. */
554
+ const watch = (queue) => {
555
+ const seen = [];
556
+ return {
557
+ seen,
558
+ onChange: () => seen.push({
559
+ active: queue().getActiveCount(),
560
+ queued: queue().getQueueLength(),
561
+ }),
562
+ };
563
+ };
564
+ it("says so when a task starts, and again when it finishes", async () => {
565
+ // Without this the workspace hears the count once, while the gateway is
566
+ // idle, and then shows 0 running for the rest of its life.
567
+ let queue;
568
+ const { seen, onChange } = watch(() => queue);
569
+ queue = new TaskQueue(2, onChange);
570
+ let release;
571
+ const held = new Promise((resolve) => { release = resolve; });
572
+ const running = queue.run(() => held);
573
+ expect(seen).toEqual([{ active: 1, queued: 0 }]);
574
+ release();
575
+ await running;
576
+ expect(seen).toEqual([
577
+ { active: 1, queued: 0 },
578
+ { active: 0, queued: 0 },
579
+ ]);
580
+ });
581
+ it("says so when a task is made to wait, with nothing newly running", async () => {
582
+ let queue;
583
+ const { seen, onChange } = watch(() => queue);
584
+ queue = new TaskQueue(1, onChange);
585
+ let release;
586
+ const held = new Promise((resolve) => { release = resolve; });
587
+ const first = queue.run(() => held);
588
+ const second = queue.run(async () => { });
589
+ // The second changed what is waiting, not what is running.
590
+ expect(seen).toEqual([
591
+ { active: 1, queued: 0 },
592
+ { active: 1, queued: 1 },
593
+ ]);
594
+ release();
595
+ await Promise.all([first, second]);
596
+ // A slot came free, then the waiting task took it, then it finished.
597
+ expect(seen.slice(2)).toEqual([
598
+ { active: 0, queued: 1 },
599
+ { active: 1, queued: 0 },
600
+ { active: 0, queued: 0 },
601
+ ]);
602
+ });
603
+ it("runs tasks normally when nobody is listening", async () => {
604
+ // The queue is built without a listener throughout these tests and in
605
+ // --list-models; an optional callback must stay optional.
606
+ const queue = new TaskQueue(1);
607
+ let ran = false;
608
+ await expect(queue.run(async () => { ran = true; })).resolves.toBeUndefined();
609
+ expect(ran).toBe(true);
610
+ expect(queue.getActiveCount()).toBe(0);
611
+ });
612
+ it("tells the workspace, end to end, when a task starts and finishes", async () => {
613
+ const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
614
+ // The callback is only worth anything if it reaches the wire, so this
615
+ // asserts on the notification rather than on the callback firing.
616
+ const bridge = { sendNotification: vi.fn().mockResolvedValue(undefined) };
617
+ const queue = createTaskQueue(2, bridge);
618
+ let release;
619
+ const held = new Promise((resolve) => { release = resolve; });
620
+ const running = queue.run(() => held);
621
+ await flush();
622
+ expect(bridge.sendNotification).toHaveBeenCalledWith("notifications/claude/channel/concurrency", expect.objectContaining({ maxConcurrency: 2, active: 1, queued: 0 }));
623
+ release();
624
+ await running;
625
+ await flush();
626
+ expect(bridge.sendNotification).toHaveBeenLastCalledWith("notifications/claude/channel/concurrency", expect.objectContaining({ maxConcurrency: 2, active: 0, queued: 0 }));
627
+ });
628
+ it("keeps running tasks when the listener throws", async () => {
629
+ // Announcing happens inside execute, including in its finally — a
630
+ // listener that threw there would replace the task's own error with its
631
+ // own. Running tasks is the job; telling an interface is a courtesy.
632
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
633
+ const queue = new TaskQueue(1, () => {
634
+ throw new Error("the workspace is on fire");
635
+ });
636
+ let ran = false;
637
+ await expect(queue.run(async () => { ran = true; })).resolves.toBeUndefined();
638
+ expect(ran).toBe(true);
639
+ // And a task's own failure still reaches its caller unchanged.
640
+ await expect(queue.run(async () => { throw new Error("the task itself failed"); })).rejects.toThrow("the task itself failed");
641
+ expect(errorSpy).toHaveBeenCalledWith("[queue] Error reporting the queue's state:", expect.any(Error));
642
+ errorSpy.mockRestore();
643
+ });
644
+ });
645
+ });
646
+ describe("handleSetConcurrency", () => {
647
+ let errorSpy;
648
+ beforeEach(() => {
649
+ errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
650
+ });
651
+ afterEach(() => {
652
+ errorSpy.mockRestore();
653
+ });
654
+ const fakeConcurrencyBridge = () => ({
655
+ sendNotification: vi.fn().mockResolvedValue(undefined),
656
+ });
657
+ it("applies the limit the workspace asked for and reports it back", async () => {
658
+ const queue = new TaskQueue(1);
659
+ const bridge = fakeConcurrencyBridge();
660
+ await handleSetConcurrency({ maxConcurrency: 5 }, queue, bridge);
661
+ expect(queue.getMaxConcurrency()).toBe(5);
662
+ expect(bridge.sendNotification).toHaveBeenCalledWith("notifications/claude/channel/concurrency", expect.objectContaining({ maxConcurrency: 5, active: 0, queued: 0 }));
663
+ });
664
+ it("reports the clamped limit, so the interface shows what took effect", async () => {
665
+ const queue = new TaskQueue(1);
666
+ const bridge = fakeConcurrencyBridge();
667
+ await handleSetConcurrency({ maxConcurrency: 100_000 }, queue, bridge);
668
+ expect(queue.getMaxConcurrency()).toBe(64);
669
+ expect(bridge.sendNotification).toHaveBeenCalledWith("notifications/claude/channel/concurrency", expect.objectContaining({ maxConcurrency: 64 }));
670
+ });
671
+ it("keeps the current limit when asked for something that is not a number", async () => {
672
+ const queue = new TaskQueue(3);
673
+ const bridge = fakeConcurrencyBridge();
674
+ await handleSetConcurrency({ maxConcurrency: "lots" }, queue, bridge);
675
+ expect(queue.getMaxConcurrency()).toBe(3);
676
+ expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('asking for "lots"'));
677
+ });
678
+ it("still answers a rejected value, rather than leaving the control hanging", async () => {
679
+ const queue = new TaskQueue(3);
680
+ const bridge = fakeConcurrencyBridge();
681
+ await handleSetConcurrency({}, queue, bridge);
682
+ // The interface moved a control and is waiting to see where it landed;
683
+ // silence would leave it showing a limit this gateway never adopted.
684
+ expect(bridge.sendNotification).toHaveBeenCalledWith("notifications/claude/channel/concurrency", expect.objectContaining({ maxConcurrency: 3 }));
685
+ });
686
+ it("reports what the queue is doing under the new limit", async () => {
687
+ const queue = new TaskQueue(1);
688
+ const bridge = fakeConcurrencyBridge();
689
+ let release;
690
+ const held = new Promise((resolve) => { release = resolve; });
691
+ const runs = [
692
+ queue.run(async () => { await held; }),
693
+ queue.run(async () => { await held; }),
694
+ queue.run(async () => { await held; }),
695
+ ];
696
+ await handleSetConcurrency({ maxConcurrency: 2 }, queue, bridge);
697
+ expect(bridge.sendNotification).toHaveBeenCalledWith("notifications/claude/channel/concurrency", expect.objectContaining({ maxConcurrency: 2, active: 2, queued: 1 }));
698
+ release();
699
+ await Promise.all(runs);
700
+ });
701
+ it("answers even when applying the change throws", async () => {
702
+ // "Always answered" is the design; it must not depend on the change
703
+ // itself going well, or the interface is left showing a limit nothing
704
+ // adopted precisely when something has gone wrong.
705
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
706
+ const queue = new TaskQueue(3);
707
+ const bridge = fakeConcurrencyBridge();
708
+ vi.spyOn(queue, "setMaxConcurrency").mockImplementation(() => {
709
+ throw new Error("queue is wedged");
710
+ });
711
+ await expect(handleSetConcurrency({ maxConcurrency: 5 }, queue, bridge)).rejects.toThrow("queue is wedged");
712
+ expect(bridge.sendNotification).toHaveBeenCalledWith("notifications/claude/channel/concurrency", expect.objectContaining({ maxConcurrency: 3 }));
713
+ errorSpy.mockRestore();
714
+ });
715
+ it("applies the limit even with no bridge to report it to", async () => {
716
+ const queue = new TaskQueue(1);
717
+ await handleSetConcurrency({ maxConcurrency: 6 }, queue);
718
+ expect(queue.getMaxConcurrency()).toBe(6);
719
+ });
720
+ });
721
+ describe("runTurnForTask", () => {
722
+ beforeEach(() => {
723
+ resetTaskTurns();
724
+ });
725
+ it("holds a second message on a chat until the first turn has finished", async () => {
726
+ // A session takes one turn at a time, and agentrq reuses a chat's id as
727
+ // the task id — so two messages to one chat are two deliveries of one
728
+ // task, and running them at once puts two prompts on one session.
729
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
730
+ const events = [];
731
+ let releaseFirst;
732
+ const firstHeld = new Promise((resolve) => { releaseFirst = resolve; });
733
+ const first = runTurnForTask("T-Chat", async () => {
734
+ events.push("first:start");
735
+ await firstHeld;
736
+ events.push("first:end");
737
+ });
738
+ const second = runTurnForTask("T-Chat", async () => {
739
+ events.push("second:start");
740
+ });
741
+ await new Promise((resolve) => setTimeout(resolve, 10));
742
+ expect(events).toEqual(["first:start"]);
743
+ releaseFirst();
744
+ await Promise.all([first, second]);
745
+ expect(events).toEqual(["first:start", "first:end", "second:start"]);
746
+ errorSpy.mockRestore();
747
+ });
748
+ it("lets a second message through after the first turn failed", async () => {
749
+ // Losing it would lose what someone typed, and the first message erroring
750
+ // is no reason the agent should never hear the second.
751
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
752
+ const ran = [];
753
+ const first = runTurnForTask("T-Fail", async () => {
754
+ ran.push("first");
755
+ throw new Error("agent blew up");
756
+ });
757
+ const second = runTurnForTask("T-Fail", async () => {
758
+ ran.push("second");
759
+ });
760
+ await expect(first).rejects.toThrow("agent blew up");
761
+ await second;
762
+ expect(ran).toEqual(["first", "second"]);
763
+ errorSpy.mockRestore();
764
+ });
765
+ it("keeps a queue of messages in the order they were sent", async () => {
766
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
767
+ const ran = [];
768
+ const turns = [0, 1, 2, 3].map((n) => runTurnForTask("T-Order", async () => {
769
+ await new Promise((resolve) => setTimeout(resolve, 5 - n));
770
+ ran.push(n);
771
+ }));
772
+ await Promise.all(turns);
773
+ expect(ran).toEqual([0, 1, 2, 3]);
774
+ errorSpy.mockRestore();
775
+ });
776
+ it("never makes one chat wait on another", async () => {
777
+ // Serialising per task, not globally — a shared lock would undo the whole
778
+ // point of a concurrency limit above 1.
779
+ const started = [];
780
+ let release;
781
+ const held = new Promise((resolve) => { release = resolve; });
782
+ const a = runTurnForTask("T-One", async () => { started.push("a"); await held; });
783
+ const b = runTurnForTask("T-Two", async () => { started.push("b"); await held; });
784
+ await new Promise((resolve) => setTimeout(resolve, 10));
785
+ expect(started.sort()).toEqual(["a", "b"]);
786
+ release();
787
+ await Promise.all([a, b]);
788
+ });
789
+ it("runs a delivery with no task id straight away", async () => {
790
+ let ran = false;
791
+ await runTurnForTask(undefined, async () => { ran = true; });
792
+ expect(ran).toBe(true);
793
+ });
794
+ it("forgets a task once its last turn is done, rather than growing forever", async () => {
795
+ await runTurnForTask("T-Clean", async () => { });
796
+ const ran = [];
797
+ // A stale chain tail would make this wait on an already-settled promise
798
+ // instead of starting at once; a leaked one would never be collected.
799
+ await runTurnForTask("T-Clean", async () => { ran.push("second"); });
800
+ expect(ran).toEqual(["second"]);
801
+ });
802
+ });
803
+ describe("registerConcurrencyListeners", () => {
804
+ let errorSpy;
805
+ beforeEach(() => {
806
+ errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
807
+ });
808
+ afterEach(() => {
809
+ errorSpy.mockRestore();
810
+ });
811
+ const listeningBridge = () => {
812
+ const bridge = new EventEmitter();
813
+ bridge.sendNotification = vi.fn().mockResolvedValue(undefined);
814
+ return bridge;
815
+ };
816
+ const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
817
+ it("applies a limit the workspace pushes while the gateway is running", async () => {
818
+ const bridge = listeningBridge();
819
+ const queue = new TaskQueue(1);
820
+ registerConcurrencyListeners(bridge, queue);
821
+ bridge.emit("setConcurrency", { maxConcurrency: 5 });
822
+ await settle();
823
+ expect(queue.getMaxConcurrency()).toBe(5);
824
+ expect(bridge.sendNotification).toHaveBeenCalledWith("notifications/claude/channel/concurrency", expect.objectContaining({ maxConcurrency: 5 }));
825
+ });
826
+ it("re-reports the limit on reconnect, which the workspace has just forgotten", async () => {
827
+ const bridge = listeningBridge();
828
+ const queue = new TaskQueue(1);
829
+ registerConcurrencyListeners(bridge, queue);
830
+ bridge.emit("setConcurrency", { maxConcurrency: 7 });
831
+ await settle();
832
+ bridge.sendNotification.mockClear();
833
+ bridge.emit("reconnected");
834
+ await settle();
835
+ // The limit in force, not the one the gateway booted with.
836
+ expect(bridge.sendNotification).toHaveBeenCalledWith("notifications/claude/channel/concurrency", expect.objectContaining({ maxConcurrency: 7 }));
837
+ });
838
+ it("logs rather than throws when applying the change goes wrong", async () => {
839
+ const bridge = listeningBridge();
840
+ const queue = new TaskQueue(1);
841
+ vi.spyOn(queue, "setMaxConcurrency").mockImplementation(() => {
842
+ throw new Error("queue is wedged");
843
+ });
844
+ registerConcurrencyListeners(bridge, queue);
845
+ // An unhandled rejection here would be logged and swallowed by the
846
+ // process-level net in production, which is a worse place to find out.
847
+ bridge.emit("setConcurrency", { maxConcurrency: 2 });
848
+ await settle();
849
+ expect(errorSpy).toHaveBeenCalledWith("[bridge] Error handling concurrency change:", expect.any(Error));
850
+ });
851
+ });
852
+ describe("reportConcurrency", () => {
853
+ beforeEach(() => resetConcurrencyReports());
854
+ afterEach(() => resetConcurrencyReports());
855
+ /** A bridge whose sends finish only when the test says so. */
856
+ const heldBridge = () => {
857
+ const releases = [];
858
+ const sendNotification = vi.fn(() => new Promise((resolve) => { releases.push(resolve); }));
859
+ return { bridge: { sendNotification }, sendNotification, releases };
860
+ };
861
+ it("never puts two reports on the wire at once", async () => {
862
+ // Each report is its own POST and nothing sequences them, so two in
863
+ // flight can be processed in either order — and the workspace would then
864
+ // show whichever landed last rather than whichever is true.
865
+ const { bridge, sendNotification, releases } = heldBridge();
866
+ const queue = new TaskQueue(4);
867
+ void reportConcurrency(bridge, queue);
868
+ void reportConcurrency(bridge, queue);
869
+ void reportConcurrency(bridge, queue);
870
+ await new Promise((resolve) => setTimeout(resolve, 0));
871
+ // The second and third waited for the first rather than racing it.
872
+ expect(sendNotification).toHaveBeenCalledTimes(1);
873
+ releases[0]();
874
+ await new Promise((resolve) => setTimeout(resolve, 0));
875
+ expect(sendNotification).toHaveBeenCalledTimes(2);
876
+ releases[1]();
877
+ await new Promise((resolve) => setTimeout(resolve, 0));
878
+ // Three asks, two reports: the ones that piled up became one.
879
+ expect(sendNotification).toHaveBeenCalledTimes(2);
880
+ });
881
+ it("makes the report that follows a burst describe the queue now", async () => {
882
+ // A collapsed report is worth sending only because it is current; one
883
+ // carrying the state at the moment it was asked for would be a stale
884
+ // number arriving late, which is the thing being fixed.
885
+ const { bridge, sendNotification, releases } = heldBridge();
886
+ // Wired to the bridge, so a task starting is what asks for the report.
887
+ const queue = createTaskQueue(4, bridge);
888
+ void reportConcurrency(bridge, queue);
889
+ await new Promise((resolve) => setTimeout(resolve, 0));
890
+ expect(sendNotification).toHaveBeenLastCalledWith("notifications/claude/channel/concurrency", expect.objectContaining({ active: 0, queued: 0 }));
891
+ // The numbers move while the first report is still flying.
892
+ let release;
893
+ const held = new Promise((resolve) => { release = resolve; });
894
+ const running = queue.run(() => held);
895
+ releases[0]();
896
+ await new Promise((resolve) => setTimeout(resolve, 0));
897
+ expect(sendNotification).toHaveBeenLastCalledWith("notifications/claude/channel/concurrency", expect.objectContaining({ active: 1, queued: 0 }));
898
+ release();
899
+ releases.slice(1).forEach((r) => r());
900
+ await running;
901
+ });
902
+ it("resolves only once the workspace has been told", async () => {
903
+ // handleSetConcurrency awaits this to make "always answered" true, so it
904
+ // must not resolve on the strength of somebody else's report.
905
+ const { bridge, sendNotification, releases } = heldBridge();
906
+ const queue = new TaskQueue(4);
907
+ void reportConcurrency(bridge, queue);
908
+ let answered = false;
909
+ void reportConcurrency(bridge, queue).then(() => { answered = true; });
910
+ await new Promise((resolve) => setTimeout(resolve, 0));
911
+ // The first report has not even landed yet.
912
+ expect(answered).toBe(false);
913
+ releases[0]();
914
+ await new Promise((resolve) => setTimeout(resolve, 0));
915
+ // Nor on the first one landing — the second is what it is owed.
916
+ expect(answered).toBe(false);
917
+ releases[1]();
918
+ await new Promise((resolve) => setTimeout(resolve, 0));
919
+ expect(answered).toBe(true);
920
+ expect(sendNotification).toHaveBeenCalledTimes(2);
921
+ });
922
+ it("describes the queue as it stands", async () => {
923
+ const bridge = { sendNotification: vi.fn().mockResolvedValue(undefined) };
924
+ const queue = new TaskQueue(2);
925
+ let release;
926
+ const held = new Promise((resolve) => { release = resolve; });
927
+ const runs = [
928
+ queue.run(async () => { await held; }),
929
+ queue.run(async () => { await held; }),
930
+ queue.run(async () => { await held; }),
931
+ ];
932
+ await reportConcurrency(bridge, queue);
933
+ expect(bridge.sendNotification).toHaveBeenCalledWith("notifications/claude/channel/concurrency", expect.objectContaining({ maxConcurrency: 2, active: 2, queued: 1 }));
934
+ release();
935
+ await Promise.all(runs);
936
+ });
407
937
  });
408
938
  describe("getOrCreateSession", () => {
409
939
  beforeEach(() => {
@@ -429,6 +959,73 @@ describe("index", () => {
429
959
  expect(session).toBeDefined();
430
960
  expect(activeSessions.has(IDLE_SESSION_KEY)).toBe(true);
431
961
  });
962
+ it("gives two deliveries of one task a single agent, not one each", async () => {
963
+ // activeSessions only learns about a session once the agent has spawned,
964
+ // handshaken and opened it. Two deliveries inside that window both missed
965
+ // the cache and both spawned — two processes on one task, and only the
966
+ // second reachable afterwards, so the first could never be closed.
967
+ const mockBridge = fakeBridge();
968
+ spawnedAgents.length = 0;
969
+ const [first, second] = await Promise.all([
970
+ getOrCreateSession("T-Dup", ["node", "agent.js"], [], { env: {} }, mockBridge),
971
+ getOrCreateSession("T-Dup", ["node", "agent.js"], [], { env: {} }, mockBridge),
972
+ ]);
973
+ expect(spawnedAgents.length).toBe(1);
974
+ expect(second).toBe(first);
975
+ expect(activeSessions.size).toBe(1);
976
+ });
977
+ it("holds a crowd of simultaneous deliveries to one agent", async () => {
978
+ const mockBridge = fakeBridge();
979
+ spawnedAgents.length = 0;
980
+ const sessions = await Promise.all(Array.from({ length: 8 }, () => getOrCreateSession("T-Crowd", ["node", "agent.js"], [], { env: {} }, mockBridge)));
981
+ expect(spawnedAgents.length).toBe(1);
982
+ expect(new Set(sessions).size).toBe(1);
983
+ });
984
+ it("still opens separate agents for separate tasks at the same time", async () => {
985
+ // The guard is per task, not a lock on opening sessions at all — a raised
986
+ // concurrency limit would be worth nothing if it serialised every spawn.
987
+ const mockBridge = fakeBridge();
988
+ spawnedAgents.length = 0;
989
+ const [a, b, c] = await Promise.all([
990
+ getOrCreateSession("T-A", ["node", "agent.js"], [], { env: {} }, mockBridge),
991
+ getOrCreateSession("T-B", ["node", "agent.js"], [], { env: {} }, mockBridge),
992
+ getOrCreateSession("T-C", ["node", "agent.js"], [], { env: {} }, mockBridge),
993
+ ]);
994
+ expect(spawnedAgents.length).toBe(3);
995
+ expect(new Set([a, b, c]).size).toBe(3);
996
+ expect(activeSessions.size).toBe(3);
997
+ });
998
+ it("serves a later delivery from the cache, not from a spent attempt", async () => {
999
+ const mockBridge = fakeBridge();
1000
+ spawnedAgents.length = 0;
1001
+ const first = await getOrCreateSession("T-Later", ["node", "agent.js"], [], { env: {} }, mockBridge);
1002
+ const second = await getOrCreateSession("T-Later", ["node", "agent.js"], [], { env: {} }, mockBridge);
1003
+ expect(second).toBe(first);
1004
+ expect(spawnedAgents.length).toBe(1);
1005
+ });
1006
+ it("lets a task try again after the attempt it waited on failed", async () => {
1007
+ // A failed attempt must not leave the key wedged, or one bad spawn would
1008
+ // cost the task every later delivery too.
1009
+ const mockBridge = fakeBridge();
1010
+ newSessionError.value = new Error("agent said no");
1011
+ await expect(getOrCreateSession("T-Retry", ["node", "agent.js"], [], { env: {} }, mockBridge)).rejects.toThrow("agent said no");
1012
+ newSessionError.value = null;
1013
+ const recovered = await getOrCreateSession("T-Retry", ["node", "agent.js"], [], { env: {} }, mockBridge);
1014
+ expect(recovered).toBeDefined();
1015
+ expect(activeSessions.has("T-Retry")).toBe(true);
1016
+ });
1017
+ it("fails both waiters together rather than spawning a second agent to retry", async () => {
1018
+ const mockBridge = fakeBridge();
1019
+ newSessionError.value = new Error("agent said no");
1020
+ spawnedAgents.length = 0;
1021
+ const results = await Promise.allSettled([
1022
+ getOrCreateSession("T-BothFail", ["node", "agent.js"], [], { env: {} }, mockBridge),
1023
+ getOrCreateSession("T-BothFail", ["node", "agent.js"], [], { env: {} }, mockBridge),
1024
+ ]);
1025
+ expect(results.every((r) => r.status === "rejected")).toBe(true);
1026
+ expect(spawnedAgents.length).toBe(1);
1027
+ newSessionError.value = null;
1028
+ });
432
1029
  it("hands the startup session to the first task rather than opening a second", async () => {
433
1030
  // Sessions are keyed by task, so without this the first real task would
434
1031
  // spawn a second agent alongside the one already running.
@@ -834,6 +1431,73 @@ describe("index", () => {
834
1431
  expect(parseGatewayArgs(["--max-concurrency", "4"]).maxConcurrency).toBe(4);
835
1432
  expect(parseGatewayArgs(["--maxConcurrency", "8"]).maxConcurrency).toBe(8);
836
1433
  });
1434
+ it("should refuse a concurrency of zero, which used to stall the queue forever", () => {
1435
+ // Accepted before, and then every task waited on a limit of 0 that no
1436
+ // completion could ever get under.
1437
+ expect(parseGatewayArgs(["--max-concurrency", "0"]).maxConcurrency).toBe(1);
1438
+ expect(parseGatewayArgs(["--max-concurrency", "-3"]).maxConcurrency).toBe(1);
1439
+ });
1440
+ it("should cap the concurrency flag at the same ceiling the workspace gets", () => {
1441
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
1442
+ expect(parseGatewayArgs(["--max-concurrency", "10000"]).maxConcurrency).toBe(64);
1443
+ errorSpy.mockRestore();
1444
+ });
1445
+ it("should say so when it caps the flag, since nothing reports a flag back", () => {
1446
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
1447
+ errorSpy.mockClear();
1448
+ parseGatewayArgs(["--max-concurrency", "128"]);
1449
+ // An existing --max-concurrency 128 would otherwise quietly boot at 64.
1450
+ expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("--max-concurrency 128 is outside 1-64; using 64."));
1451
+ errorSpy.mockRestore();
1452
+ });
1453
+ it("should not warn about a fraction, which is truncated rather than capped", () => {
1454
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
1455
+ errorSpy.mockClear();
1456
+ expect(parseGatewayArgs(["--max-concurrency", "4.9"]).maxConcurrency).toBe(4);
1457
+ expect(errorSpy).not.toHaveBeenCalled();
1458
+ errorSpy.mockRestore();
1459
+ });
1460
+ it("should leave a non-numeric token alone, since it is the agent command", () => {
1461
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
1462
+ // `--max-concurrency claude` is the number left out, not a mistyped
1463
+ // number. Eating the token would leave the gateway nothing to run.
1464
+ expect(parseGatewayArgs(["--max-concurrency", "claude"])).toMatchObject({
1465
+ maxConcurrency: 1,
1466
+ rest: ["claude"],
1467
+ });
1468
+ errorSpy.mockRestore();
1469
+ });
1470
+ it("should consume a malformed concurrency value instead of leaving it to be run", () => {
1471
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
1472
+ // `rest` is the agent command when no `--` was used, so a value left
1473
+ // behind here sent the gateway looking for an agent called "8x".
1474
+ expect(parseGatewayArgs(["--max-concurrency", "8x", "claude"])).toMatchObject({
1475
+ maxConcurrency: 1,
1476
+ rest: ["claude"],
1477
+ });
1478
+ expect(parseGatewayArgs(["--max-concurrency", "8x", "--", "claude"]).rest).toEqual([
1479
+ "--",
1480
+ "claude",
1481
+ ]);
1482
+ errorSpy.mockRestore();
1483
+ });
1484
+ it("should say why a malformed concurrency value was ignored", () => {
1485
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
1486
+ errorSpy.mockClear();
1487
+ parseGatewayArgs(["--max-concurrency", "8x"]);
1488
+ expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('--max-concurrency "8x" is not a number of tasks'));
1489
+ errorSpy.mockRestore();
1490
+ });
1491
+ it("should stay silent when the flag simply has no value to read", () => {
1492
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
1493
+ errorSpy.mockClear();
1494
+ expect(parseGatewayArgs(["--max-concurrency", "--logout"])).toMatchObject({
1495
+ maxConcurrency: 1,
1496
+ command: "logout",
1497
+ });
1498
+ expect(errorSpy).not.toHaveBeenCalled();
1499
+ errorSpy.mockRestore();
1500
+ });
837
1501
  it("should keep the default when the concurrency value is missing or not a number", () => {
838
1502
  expect(parseGatewayArgs(["--max-concurrency"]).maxConcurrency).toBe(1);
839
1503
  expect(parseGatewayArgs(["--max-concurrency", "many"]).maxConcurrency).toBe(1);
@@ -1370,6 +2034,10 @@ describe("index", () => {
1370
2034
  it("should document the default concurrency of 1", () => {
1371
2035
  expect(helpText()).toContain("Defaults to 1.");
1372
2036
  });
2037
+ it("should document the concurrency range and that agentrq can change it", () => {
2038
+ expect(helpText()).toContain("1 to 64.");
2039
+ expect(helpText()).toContain("agentrq can change it while running.");
2040
+ });
1373
2041
  });
1374
2042
  describe("printHelp", () => {
1375
2043
  it("should print the help text", () => {
@@ -2063,16 +2731,72 @@ describe("index", () => {
2063
2731
  let errorSpy;
2064
2732
  beforeEach(() => {
2065
2733
  activeSessions.clear();
2734
+ // Also clears the record of agents spawned by earlier tests, which this
2735
+ // one now reaps.
2736
+ resetIdleSession();
2066
2737
  errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
2067
2738
  });
2068
2739
  afterEach(() => {
2069
2740
  activeSessions.clear();
2741
+ resetIdleSession();
2070
2742
  errorSpy.mockRestore();
2071
2743
  });
2072
2744
  it("does nothing when activeSessions is empty", async () => {
2073
2745
  await closeAllSessions();
2074
2746
  expect(activeSessions.size).toBe(0);
2075
2747
  });
2748
+ it("ends an agent that spawned but never opened a session", async () => {
2749
+ // activeSessions only holds agents that got as far as an open session,
2750
+ // so shutting down on it alone left behind the agent still handshaking
2751
+ // — and the one stopped waiting for a login, which is the case most
2752
+ // likely to be interrupted, since it can sit there indefinitely. One
2753
+ // that quits when its stdin closes got away with it; one with an event
2754
+ // loop of its own did not.
2755
+ newSessionHangs.value = true;
2756
+ spawnedAgents.length = 0;
2757
+ const opening = getOrCreateSession("T-Interrupted", ["node", "agent.js"], [], { env: {} }, fakeBridge());
2758
+ await new Promise((resolve) => setTimeout(resolve, 10));
2759
+ // Spawned, and tracked by nothing that shutdown used to look at.
2760
+ expect(spawnedAgents.length).toBe(1);
2761
+ expect(activeSessions.size).toBe(0);
2762
+ await closeAllSessions(10);
2763
+ expect(spawnedAgents[0].kill).toHaveBeenCalled();
2764
+ expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("never opened a session"));
2765
+ newSessionHangs.value = false;
2766
+ void opening.catch(() => { });
2767
+ });
2768
+ it("keeps ending the rest when one refuses to die", async () => {
2769
+ // Shutdown is the last thing that runs; one process that will not go
2770
+ // must not take the others' only chance to go with it.
2771
+ newSessionHangs.value = true;
2772
+ spawnedAgents.length = 0;
2773
+ const opening = [
2774
+ getOrCreateSession("T-Stuck-A", ["node", "agent.js"], [], { env: {} }, fakeBridge()),
2775
+ getOrCreateSession("T-Stuck-B", ["node", "agent.js"], [], { env: {} }, fakeBridge()),
2776
+ ];
2777
+ await new Promise((resolve) => setTimeout(resolve, 10));
2778
+ expect(spawnedAgents.length).toBe(2);
2779
+ spawnedAgents[0].kill.mockImplementation(() => {
2780
+ throw new Error("no such process");
2781
+ });
2782
+ await closeAllSessions(10);
2783
+ expect(spawnedAgents[1].kill).toHaveBeenCalled();
2784
+ expect(errorSpy).toHaveBeenCalledWith("[acp] Error ending an agent process:", expect.any(Error));
2785
+ newSessionHangs.value = false;
2786
+ for (const p of opening)
2787
+ void p.catch(() => { });
2788
+ });
2789
+ it("does not report a cleanly closed session as one left behind", async () => {
2790
+ // Its process is ended by closeSession; counting it again would report
2791
+ // a leak that is not there.
2792
+ newSessionHangs.value = false;
2793
+ spawnedAgents.length = 0;
2794
+ await getOrCreateSession("T-Clean-Exit", ["node", "agent.js"], [], { env: {} }, fakeBridge());
2795
+ expect(activeSessions.size).toBe(1);
2796
+ await closeAllSessions(10);
2797
+ expect(spawnedAgents[0].kill).toHaveBeenCalled();
2798
+ expect(errorSpy).not.toHaveBeenCalledWith(expect.stringContaining("never opened a session"));
2799
+ });
2076
2800
  it("closes all unique active sessions in parallel and clears map", async () => {
2077
2801
  const cancel1 = vi.fn().mockResolvedValue(undefined);
2078
2802
  const cancel2 = vi.fn().mockResolvedValue(undefined);