@agentrq/acp-gateway 0.3.1 → 0.4.1
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.
- package/README.md +59 -169
- package/dist/__tests__/agentInfo.test.js +2 -31
- package/dist/__tests__/agentInfo.test.js.map +1 -1
- package/dist/__tests__/concurrency.test.js +1 -74
- package/dist/__tests__/concurrency.test.js.map +1 -1
- package/dist/__tests__/index.test.js +190 -2672
- package/dist/__tests__/index.test.js.map +1 -1
- package/dist/__tests__/localClient.test.js +100 -0
- package/dist/__tests__/localClient.test.js.map +1 -0
- package/dist/__tests__/log.test.js +1 -42
- package/dist/__tests__/log.test.js.map +1 -1
- package/dist/__tests__/mcpServers.test.js +62 -0
- package/dist/__tests__/mcpServers.test.js.map +1 -0
- package/dist/__tests__/models.test.js +2 -18
- package/dist/__tests__/models.test.js.map +1 -1
- package/dist/__tests__/native.test.js +294 -29
- package/dist/__tests__/native.test.js.map +1 -1
- package/dist/__tests__/nativeFrames.test.js +132 -4
- package/dist/__tests__/nativeFrames.test.js.map +1 -1
- package/dist/__tests__/nativeHeaders.test.js +34 -0
- package/dist/__tests__/nativeHeaders.test.js.map +1 -1
- package/dist/agentInfo.js +0 -31
- package/dist/agentInfo.js.map +1 -1
- package/dist/concurrency.js +6 -64
- package/dist/concurrency.js.map +1 -1
- package/dist/index.js +114 -1729
- package/dist/index.js.map +1 -1
- package/dist/localClient.js +91 -0
- package/dist/localClient.js.map +1 -0
- package/dist/log.js +0 -22
- package/dist/log.js.map +1 -1
- package/dist/mcpServers.js +60 -0
- package/dist/mcpServers.js.map +1 -0
- package/dist/models.js +0 -10
- package/dist/models.js.map +1 -1
- package/dist/native.js +243 -30
- package/dist/native.js.map +1 -1
- package/dist/nativeFrames.js +114 -12
- package/dist/nativeFrames.js.map +1 -1
- package/package.json +6 -8
- package/dist/__tests__/acpClient.test.js +0 -2346
- package/dist/__tests__/acpClient.test.js.map +0 -1
- package/dist/__tests__/collections.test.js +0 -116
- package/dist/__tests__/collections.test.js.map +0 -1
- package/dist/__tests__/commands.test.js +0 -92
- package/dist/__tests__/commands.test.js.map +0 -1
- package/dist/__tests__/mcpClient.test.js +0 -558
- package/dist/__tests__/mcpClient.test.js.map +0 -1
- package/dist/__tests__/taskIdentity.test.js +0 -63
- package/dist/__tests__/taskIdentity.test.js.map +0 -1
- package/dist/__tests__/telemetry.test.js +0 -151
- package/dist/__tests__/telemetry.test.js.map +0 -1
- package/dist/acpClient.js +0 -1112
- package/dist/acpClient.js.map +0 -1
- package/dist/collections.js +0 -105
- package/dist/collections.js.map +0 -1
- package/dist/commands.js +0 -60
- package/dist/commands.js.map +0 -1
- package/dist/mcpClient.js +0 -361
- package/dist/mcpClient.js.map +0 -1
- package/dist/taskIdentity.js +0 -41
- package/dist/taskIdentity.js.map +0 -1
- package/dist/telemetry.js +0 -106
- package/dist/telemetry.js.map +0 -1
|
@@ -5,8 +5,7 @@ import { tmpdir } from "node:os";
|
|
|
5
5
|
import { join } from "node:path";
|
|
6
6
|
import { EventEmitter } from "node:events";
|
|
7
7
|
import * as acp from "@agentclientprotocol/sdk";
|
|
8
|
-
import {
|
|
9
|
-
import { AgentRQACPClient, sendModelsNotification } from "../acpClient.js";
|
|
8
|
+
import { AuthenticationFailed, createSessionWithAuth, isInteractiveTerminal, openAgentConnection, agentExitFailed, showAgentStderr, shouldPrintBanner, parseGatewayArgs, assertAgentRunnable, helpText, isRunnable, resolveOnPath, spawnTarget, needsShell, escapeCmdCommand, quoteForCmd, spawnArgsFor, terminateAgentProcess, printHelp, resolveAgentCommand, runListAgents, runAgentCommand, loadWorkspace, makeIsolatedDir, WORKSPACE_OPTIONAL_COMMANDS, supportsCloseSession, closeSession, nativeOptionsFor, startNativeMode, runGateway, } from "../index.js";
|
|
10
9
|
import { AUTH_REQUIRED_CODE } from "../auth.js";
|
|
11
10
|
/**
|
|
12
11
|
* A stand-in for the workspace bridge.
|
|
@@ -64,1869 +63,11 @@ vi.mock("@agentclientprotocol/sdk", async () => {
|
|
|
64
63
|
});
|
|
65
64
|
describe("index", () => {
|
|
66
65
|
afterEach(() => setVerbose(false));
|
|
67
|
-
describe("mapMcpServers", () => {
|
|
68
|
-
it("should correctly map HTTP servers with headers and env", () => {
|
|
69
|
-
const configs = [{
|
|
70
|
-
type: "http",
|
|
71
|
-
name: "test-http",
|
|
72
|
-
url: "http://localhost:8000",
|
|
73
|
-
env: { "Authorization": "Bearer env-token", "Other": "Val" },
|
|
74
|
-
headers: { "Authorization": "Bearer header-token", "Custom": "Header" }
|
|
75
|
-
}];
|
|
76
|
-
const result = mapMcpServers(configs);
|
|
77
|
-
expect(result).toEqual([{
|
|
78
|
-
type: "http",
|
|
79
|
-
name: "test-http",
|
|
80
|
-
url: "http://localhost:8000",
|
|
81
|
-
headers: [
|
|
82
|
-
{ name: "Authorization", value: "Bearer header-token" },
|
|
83
|
-
{ name: "Custom", value: "Header" }
|
|
84
|
-
]
|
|
85
|
-
}]);
|
|
86
|
-
});
|
|
87
|
-
it("should default headers to empty object for HTTP servers", () => {
|
|
88
|
-
const configs = [{
|
|
89
|
-
type: "http",
|
|
90
|
-
name: "test-http",
|
|
91
|
-
url: "http://localhost:8000"
|
|
92
|
-
}];
|
|
93
|
-
const result = mapMcpServers(configs);
|
|
94
|
-
expect(result).toEqual([{
|
|
95
|
-
type: "http",
|
|
96
|
-
name: "test-http",
|
|
97
|
-
url: "http://localhost:8000",
|
|
98
|
-
headers: []
|
|
99
|
-
}]);
|
|
100
|
-
});
|
|
101
|
-
it("should map an sse server as its own transport", () => {
|
|
102
|
-
const configs = [{
|
|
103
|
-
type: "sse",
|
|
104
|
-
name: "events",
|
|
105
|
-
url: "http://localhost:8000/sse",
|
|
106
|
-
}];
|
|
107
|
-
expect(mapMcpServers(configs, { mcpCapabilities: { sse: true } })).toEqual([{
|
|
108
|
-
type: "sse",
|
|
109
|
-
name: "events",
|
|
110
|
-
url: "http://localhost:8000/sse",
|
|
111
|
-
headers: [],
|
|
112
|
-
}]);
|
|
113
|
-
});
|
|
114
|
-
it("should leave out a transport the agent says it does not support", () => {
|
|
115
|
-
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
|
|
116
|
-
const configs = [
|
|
117
|
-
{ type: "http", name: "remote", url: "http://localhost:8000" },
|
|
118
|
-
{ type: "stdio", name: "local", command: "npx" },
|
|
119
|
-
];
|
|
120
|
-
// An agent may refuse the whole session/new rather than skip one entry.
|
|
121
|
-
const result = mapMcpServers(configs, {
|
|
122
|
-
mcpCapabilities: { http: false, sse: false },
|
|
123
|
-
});
|
|
124
|
-
expect(result.map((s) => s.name)).toEqual(["local"]);
|
|
125
|
-
expect(errorSpy.mock.calls.flat().join("\n")).toContain('Not passing MCP server "remote"');
|
|
126
|
-
errorSpy.mockRestore();
|
|
127
|
-
});
|
|
128
|
-
it("should still hand over a transport the agent never mentions", () => {
|
|
129
|
-
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
|
|
130
|
-
const configs = [
|
|
131
|
-
{ type: "http", name: "remote", url: "http://localhost:8000" },
|
|
132
|
-
];
|
|
133
|
-
// A terse agent is likelier than one that genuinely cannot reach HTTP,
|
|
134
|
-
// and dropping this would take the workspace's own server away from it.
|
|
135
|
-
expect(mapMcpServers(configs, {}).map((s) => s.name)).toEqual(["remote"]);
|
|
136
|
-
expect(mapMcpServers(configs).map((s) => s.name)).toEqual(["remote"]);
|
|
137
|
-
errorSpy.mockRestore();
|
|
138
|
-
});
|
|
139
|
-
it("should correctly map stdio servers", () => {
|
|
140
|
-
const configs = [{
|
|
141
|
-
type: "stdio",
|
|
142
|
-
name: "test-stdio",
|
|
143
|
-
command: "npx",
|
|
144
|
-
args: ["-y", "some-pkg"],
|
|
145
|
-
env: {
|
|
146
|
-
API_KEY: "secret",
|
|
147
|
-
MODE: "test"
|
|
148
|
-
}
|
|
149
|
-
}];
|
|
150
|
-
const result = mapMcpServers(configs);
|
|
151
|
-
expect(result).toEqual([{
|
|
152
|
-
name: "test-stdio",
|
|
153
|
-
command: "npx",
|
|
154
|
-
args: ["-y", "some-pkg"],
|
|
155
|
-
env: [
|
|
156
|
-
{ name: "API_KEY", value: "secret" },
|
|
157
|
-
{ name: "MODE", value: "test" }
|
|
158
|
-
]
|
|
159
|
-
}]);
|
|
160
|
-
});
|
|
161
|
-
it("should default args to empty array and env to empty object for stdio servers", () => {
|
|
162
|
-
const configs = [{
|
|
163
|
-
type: "stdio",
|
|
164
|
-
name: "minimal-stdio",
|
|
165
|
-
command: "echo"
|
|
166
|
-
}];
|
|
167
|
-
const result = mapMcpServers(configs);
|
|
168
|
-
expect(result).toEqual([{
|
|
169
|
-
name: "minimal-stdio",
|
|
170
|
-
command: "echo",
|
|
171
|
-
args: [],
|
|
172
|
-
env: []
|
|
173
|
-
}]);
|
|
174
|
-
});
|
|
175
|
-
});
|
|
176
|
-
describe("createAcpSessionSwitcher", () => {
|
|
177
|
-
let mockConnection;
|
|
178
|
-
let params;
|
|
179
|
-
beforeEach(() => {
|
|
180
|
-
mockConnection = {
|
|
181
|
-
newSession: vi.fn().mockResolvedValue({ sessionId: "new-session-id" }),
|
|
182
|
-
};
|
|
183
|
-
params = { cwd: "/test", mcpServers: [{ name: "s1", url: "http://s1", headers: [] }] };
|
|
184
|
-
});
|
|
185
|
-
it("should return initial session ID", () => {
|
|
186
|
-
const switcher = createAcpSessionSwitcher(mockConnection, params, "initial-id");
|
|
187
|
-
expect(switcher.getSessionId()).toBe("initial-id");
|
|
188
|
-
});
|
|
189
|
-
it("should return current session ID if taskId is undefined", async () => {
|
|
190
|
-
const switcher = createAcpSessionSwitcher(mockConnection, params, "initial-id");
|
|
191
|
-
const id = await switcher.ensureForTask(undefined);
|
|
192
|
-
expect(id).toBe("initial-id");
|
|
193
|
-
expect(mockConnection.newSession).not.toHaveBeenCalled();
|
|
194
|
-
});
|
|
195
|
-
it("should create a new session on first call with taskId", async () => {
|
|
196
|
-
const switcher = createAcpSessionSwitcher(mockConnection, params, "initial-id");
|
|
197
|
-
const id = await switcher.ensureForTask("task-1");
|
|
198
|
-
expect(id).toBe("new-session-id");
|
|
199
|
-
expect(mockConnection.newSession).toHaveBeenCalled();
|
|
200
|
-
// Second call with same taskId should still return same ID
|
|
201
|
-
const id2 = await switcher.ensureForTask("task-1");
|
|
202
|
-
expect(id2).toBe("new-session-id");
|
|
203
|
-
expect(mockConnection.newSession).toHaveBeenCalledTimes(1);
|
|
204
|
-
});
|
|
205
|
-
it("should create a new session when taskId changes", async () => {
|
|
206
|
-
params = { cwd: "/test", mcpServers: [{ name: "s1", url: "http://s1", headers: [] }] };
|
|
207
|
-
const switcher = createAcpSessionSwitcher(mockConnection, params, "initial-id");
|
|
208
|
-
// Set initial task
|
|
209
|
-
await switcher.ensureForTask("task-1");
|
|
210
|
-
// Change task
|
|
211
|
-
const id = await switcher.ensureForTask("task-2");
|
|
212
|
-
expect(id).toBe("new-session-id");
|
|
213
|
-
expect(mockConnection.newSession).toHaveBeenCalledTimes(2);
|
|
214
|
-
expect(switcher.getSessionId()).toBe("new-session-id");
|
|
215
|
-
});
|
|
216
|
-
it("should return existing session when a previously seen task returns", async () => {
|
|
217
|
-
mockConnection.newSession
|
|
218
|
-
.mockResolvedValueOnce({ sessionId: "session-for-task-1" })
|
|
219
|
-
.mockResolvedValueOnce({ sessionId: "session-for-task-2" });
|
|
220
|
-
const switcher = createAcpSessionSwitcher(mockConnection, params, "initial-id");
|
|
221
|
-
const id1 = await switcher.ensureForTask("task-1");
|
|
222
|
-
expect(id1).toBe("session-for-task-1");
|
|
223
|
-
const id2 = await switcher.ensureForTask("task-2");
|
|
224
|
-
expect(id2).toBe("session-for-task-2");
|
|
225
|
-
// task-1 returns — must reuse session-for-task-1, not create a third session
|
|
226
|
-
const id3 = await switcher.ensureForTask("task-1");
|
|
227
|
-
expect(id3).toBe("session-for-task-1");
|
|
228
|
-
expect(mockConnection.newSession).toHaveBeenCalledTimes(2);
|
|
229
|
-
});
|
|
230
|
-
});
|
|
231
|
-
describe("createAcpSessionSwitcher – getTaskIdForSession", () => {
|
|
232
|
-
let mockConnection;
|
|
233
|
-
let params;
|
|
234
|
-
beforeEach(() => {
|
|
235
|
-
mockConnection = {
|
|
236
|
-
newSession: vi.fn()
|
|
237
|
-
.mockResolvedValueOnce({ sessionId: "session-for-task-1" })
|
|
238
|
-
.mockResolvedValueOnce({ sessionId: "session-for-task-2" }),
|
|
239
|
-
};
|
|
240
|
-
params = { cwd: "/test", mcpServers: [] };
|
|
241
|
-
});
|
|
242
|
-
it("should return taskId for a known session", async () => {
|
|
243
|
-
const switcher = createAcpSessionSwitcher(mockConnection, params, "initial-id");
|
|
244
|
-
await switcher.ensureForTask("task-1");
|
|
245
|
-
expect(switcher.getTaskIdForSession("session-for-task-1")).toBe("task-1");
|
|
246
|
-
});
|
|
247
|
-
it("should return undefined for an unknown session", async () => {
|
|
248
|
-
const switcher = createAcpSessionSwitcher(mockConnection, params, "initial-id");
|
|
249
|
-
expect(switcher.getTaskIdForSession("unknown-session")).toBeUndefined();
|
|
250
|
-
});
|
|
251
|
-
it("should track multiple sessions independently", async () => {
|
|
252
|
-
const switcher = createAcpSessionSwitcher(mockConnection, params, "initial-id");
|
|
253
|
-
await switcher.ensureForTask("task-1");
|
|
254
|
-
await switcher.ensureForTask("task-2");
|
|
255
|
-
expect(switcher.getTaskIdForSession("session-for-task-1")).toBe("task-1");
|
|
256
|
-
expect(switcher.getTaskIdForSession("session-for-task-2")).toBe("task-2");
|
|
257
|
-
});
|
|
258
|
-
});
|
|
259
|
-
describe("running a task the workspace handed over", () => {
|
|
260
|
-
let mockMcpBridge;
|
|
261
|
-
let mockConnection;
|
|
262
|
-
let mockSessionSwitcher;
|
|
263
|
-
let mockAcpClient;
|
|
264
|
-
/** What the gateway's fetch-and-run path needs, with a session already open. */
|
|
265
|
-
const deps = (taskQueue) => ({
|
|
266
|
-
acpCmdArgsOrConnection: mockConnection,
|
|
267
|
-
configsOrSessionSwitcher: mockSessionSwitcher,
|
|
268
|
-
agentrqConfigOrAcpClient: mockAcpClient,
|
|
269
|
-
taskQueue,
|
|
270
|
-
});
|
|
271
|
-
beforeEach(() => {
|
|
272
|
-
vi.clearAllMocks();
|
|
273
|
-
resetPendingTaskDrain();
|
|
274
|
-
mockMcpBridge = {
|
|
275
|
-
callTool: vi.fn(),
|
|
276
|
-
};
|
|
277
|
-
mockConnection = {
|
|
278
|
-
prompt: vi.fn().mockResolvedValue({ stopReason: "complete" }),
|
|
279
|
-
};
|
|
280
|
-
mockSessionSwitcher = {
|
|
281
|
-
getSessionId: vi.fn().mockReturnValue("current-session"),
|
|
282
|
-
ensureForTask: vi.fn().mockResolvedValue("current-session"),
|
|
283
|
-
};
|
|
284
|
-
mockAcpClient = {
|
|
285
|
-
flushReply: vi.fn().mockResolvedValue(undefined),
|
|
286
|
-
reportStopReason: vi.fn().mockResolvedValue(undefined),
|
|
287
|
-
};
|
|
288
|
-
// Mock console.error to avoid cluttering test output
|
|
289
|
-
vi.spyOn(console, "error").mockImplementation(() => { });
|
|
290
|
-
vi.spyOn(console, "log").mockImplementation(() => { });
|
|
291
|
-
});
|
|
292
|
-
afterEach(() => {
|
|
293
|
-
vi.restoreAllMocks();
|
|
294
|
-
});
|
|
295
|
-
it("prompts the agent in the session that belongs to the task", async () => {
|
|
296
|
-
const queue = new TaskQueue(1);
|
|
297
|
-
mockMcpBridge.callTool.mockResolvedValue({
|
|
298
|
-
isError: false,
|
|
299
|
-
content: [{ type: "text", text: "Task ID: T1\ndo something" }],
|
|
300
|
-
});
|
|
301
|
-
await drainPendingTasks(mockMcpBridge, queue, deps(queue));
|
|
302
|
-
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
303
|
-
expect(mockSessionSwitcher.ensureForTask).toHaveBeenCalledWith("T1");
|
|
304
|
-
expect(mockConnection.prompt).toHaveBeenCalledWith({
|
|
305
|
-
sessionId: "current-session",
|
|
306
|
-
prompt: [{ type: "text", text: "Task ID: T1\ndo something" }],
|
|
307
|
-
});
|
|
308
|
-
expect(mockAcpClient.flushReply).toHaveBeenCalledWith("current-session");
|
|
309
|
-
});
|
|
310
|
-
it("runs a queued task through the queue, and behind any turn it already has", async () => {
|
|
311
|
-
// The queue is how a concurrency limit is enforced at all, and the turn
|
|
312
|
-
// guard is what keeps a second delivery of this task off a session that
|
|
313
|
-
// is already mid-prompt.
|
|
314
|
-
resetTaskTurns();
|
|
315
|
-
mockMcpBridge.callTool.mockResolvedValue({
|
|
316
|
-
isError: false,
|
|
317
|
-
content: [{ type: "text", text: "Task ID: T-Queued\nwork please" }],
|
|
318
|
-
});
|
|
319
|
-
const queue = new TaskQueue(2);
|
|
320
|
-
let releaseEarlier;
|
|
321
|
-
const earlier = new Promise((resolve) => { releaseEarlier = resolve; });
|
|
322
|
-
const earlierTurn = runTurnForTask("T-Queued", () => earlier);
|
|
323
|
-
const draining = drainPendingTasks(mockMcpBridge, queue, deps(queue));
|
|
324
|
-
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
325
|
-
expect(mockConnection.prompt).not.toHaveBeenCalled();
|
|
326
|
-
releaseEarlier();
|
|
327
|
-
await Promise.all([earlierTurn, draining]);
|
|
328
|
-
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
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 draining = drainPendingTasks(mockMcpBridge, queue, deps(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, draining, unrelated]);
|
|
360
|
-
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
361
|
-
expect(mockConnection.prompt).toHaveBeenCalledTimes(1);
|
|
362
|
-
expect(queue.getActiveCount()).toBe(0);
|
|
363
|
-
});
|
|
364
|
-
it("forwards a slash command to the agent unmodified", async () => {
|
|
365
|
-
// ACP runs a command as ordinary prompt text and the agent matches the
|
|
366
|
-
// prefix at the *start* of it, so anything prepended here — a wrapper, a
|
|
367
|
-
// task header, a courtesy sentence — stops it being a command at all.
|
|
368
|
-
// agentrq relies on this passthrough to deliver what the human typed.
|
|
369
|
-
const queue = new TaskQueue(1);
|
|
370
|
-
mockMcpBridge.callTool.mockResolvedValue({
|
|
371
|
-
isError: false,
|
|
372
|
-
content: [{ type: "text", text: "/compact keep the API discussion" }],
|
|
373
|
-
});
|
|
374
|
-
await drainPendingTasks(mockMcpBridge, queue, deps(queue));
|
|
375
|
-
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
376
|
-
expect(mockConnection.prompt).toHaveBeenCalledWith({
|
|
377
|
-
sessionId: "current-session",
|
|
378
|
-
prompt: [{ type: "text", text: "/compact keep the API discussion" }],
|
|
379
|
-
});
|
|
380
|
-
});
|
|
381
|
-
});
|
|
382
|
-
describe("fetchNextTask", () => {
|
|
383
|
-
let bridge;
|
|
384
|
-
beforeEach(() => {
|
|
385
|
-
vi.spyOn(console, "error").mockImplementation(() => { });
|
|
386
|
-
vi.spyOn(console, "log").mockImplementation(() => { });
|
|
387
|
-
bridge = { callTool: vi.fn() };
|
|
388
|
-
});
|
|
389
|
-
afterEach(() => {
|
|
390
|
-
vi.restoreAllMocks();
|
|
391
|
-
});
|
|
392
|
-
it("hands back the task the workspace dequeued", async () => {
|
|
393
|
-
bridge.callTool.mockResolvedValue({
|
|
394
|
-
isError: false,
|
|
395
|
-
content: [{ type: "text", text: "Task ID: T-Fetch\nplease do it" }],
|
|
396
|
-
});
|
|
397
|
-
const outcome = await fetchNextTask(bridge);
|
|
398
|
-
expect(bridge.callTool).toHaveBeenCalledWith("getTask");
|
|
399
|
-
expect(outcome.status).toBe("task");
|
|
400
|
-
const task = outcome.task;
|
|
401
|
-
expect(task.text).toBe("Task ID: T-Fetch\nplease do it");
|
|
402
|
-
expect(task.taskId).toBe("T-Fetch");
|
|
403
|
-
// Stamped at the fetch, so a cancel landing during session setup still bites.
|
|
404
|
-
expect(task.queuedSeq).toBeGreaterThan(0);
|
|
405
|
-
});
|
|
406
|
-
it("tells an empty workspace apart from one it could not ask", async () => {
|
|
407
|
-
// A caller filling slots treats these differently: an empty workspace is
|
|
408
|
-
// the end of the drain, while a workspace that could not be reached is
|
|
409
|
-
// the bridge's problem to reconnect rather than this loop's to retry.
|
|
410
|
-
bridge.callTool.mockResolvedValueOnce({
|
|
411
|
-
isError: false,
|
|
412
|
-
content: [{ type: "text", text: "no pending tasks exist" }],
|
|
413
|
-
});
|
|
414
|
-
expect(await fetchNextTask(bridge)).toEqual({ status: "empty" });
|
|
415
|
-
bridge.callTool.mockResolvedValueOnce({ isError: false, content: [] });
|
|
416
|
-
expect(await fetchNextTask(bridge)).toEqual({ status: "empty" });
|
|
417
|
-
bridge.callTool.mockResolvedValueOnce({
|
|
418
|
-
isError: false,
|
|
419
|
-
content: [{ type: "text", text: "" }],
|
|
420
|
-
});
|
|
421
|
-
expect(await fetchNextTask(bridge)).toEqual({ status: "empty" });
|
|
422
|
-
bridge.callTool.mockResolvedValueOnce({ isError: true, content: "nope" });
|
|
423
|
-
expect(await fetchNextTask(bridge)).toEqual({ status: "failed" });
|
|
424
|
-
bridge.callTool.mockRejectedValueOnce(new Error("network error"));
|
|
425
|
-
expect(await fetchNextTask(bridge)).toEqual({ status: "failed" });
|
|
426
|
-
expect(console.error).toHaveBeenCalledWith(expect.stringContaining("Failed to check for next task"), expect.any(Error));
|
|
427
|
-
});
|
|
428
|
-
it("says a repeat was skipped, not that the workspace is empty", async () => {
|
|
429
|
-
// The difference matters: a repeat has been dequeued and dropped, so the
|
|
430
|
-
// slot it was meant to fill is still free and something else may fill it.
|
|
431
|
-
bridge.callTool.mockResolvedValue({
|
|
432
|
-
isError: false,
|
|
433
|
-
content: [{ type: "text", text: "Task ID: T-Twice\nsame words" }],
|
|
434
|
-
});
|
|
435
|
-
expect((await fetchNextTask(bridge)).status).toBe("task");
|
|
436
|
-
expect(await fetchNextTask(bridge)).toEqual({ status: "skipped" });
|
|
437
|
-
});
|
|
438
|
-
it("takes an unnamed task, since not every delivery carries an id", async () => {
|
|
439
|
-
bridge.callTool.mockResolvedValue({
|
|
440
|
-
isError: false,
|
|
441
|
-
content: [{ type: "text", text: "/compact keep the API discussion" }],
|
|
442
|
-
});
|
|
443
|
-
const outcome = await fetchNextTask(bridge);
|
|
444
|
-
expect(outcome.status).toBe("task");
|
|
445
|
-
const task = outcome.task;
|
|
446
|
-
expect(task.taskId).toBeUndefined();
|
|
447
|
-
expect(task.text).toBe("/compact keep the API discussion");
|
|
448
|
-
});
|
|
449
|
-
});
|
|
450
|
-
describe("startPendingTask", () => {
|
|
451
|
-
afterEach(() => {
|
|
452
|
-
activeSessions.clear();
|
|
453
|
-
resetIdleSession();
|
|
454
|
-
resetTaskTurns();
|
|
455
|
-
vi.restoreAllMocks();
|
|
456
|
-
});
|
|
457
|
-
it("opens a session from the agent command when it was given one", async () => {
|
|
458
|
-
// The gateway's own path passes a command rather than an open
|
|
459
|
-
// connection, and that is the shape `main` uses — so it is the shape
|
|
460
|
-
// that has to work when the workspace hands over a task.
|
|
461
|
-
vi.spyOn(console, "error").mockImplementation(() => { });
|
|
462
|
-
const prompt = vi.fn().mockResolvedValue({ stopReason: "end_turn" });
|
|
463
|
-
const acpClient = {
|
|
464
|
-
flushReply: vi.fn().mockResolvedValue(undefined),
|
|
465
|
-
reportStopReason: vi.fn().mockResolvedValue(undefined),
|
|
466
|
-
};
|
|
467
|
-
activeSessions.set("T-Cmd", {
|
|
468
|
-
process: {},
|
|
469
|
-
connection: { prompt },
|
|
470
|
-
acpClient: acpClient,
|
|
471
|
-
sessionId: "S-Cmd",
|
|
472
|
-
initResult: {},
|
|
473
|
-
adopt: vi.fn(),
|
|
474
|
-
});
|
|
475
|
-
await startPendingTask({ text: "Task ID: T-Cmd\nwork", taskId: "T-Cmd", queuedSeq: 1 }, { callTool: vi.fn() }, {
|
|
476
|
-
acpCmdArgsOrConnection: ["fake-agent"],
|
|
477
|
-
configsOrSessionSwitcher: [],
|
|
478
|
-
agentrqConfigOrAcpClient: { name: "agentrq", type: "http" },
|
|
479
|
-
});
|
|
480
|
-
expect(prompt).toHaveBeenCalledWith({
|
|
481
|
-
sessionId: "S-Cmd",
|
|
482
|
-
prompt: [{ type: "text", text: "Task ID: T-Cmd\nwork" }],
|
|
483
|
-
});
|
|
484
|
-
expect(acpClient.reportStopReason).toHaveBeenCalledWith("S-Cmd", "end_turn");
|
|
485
|
-
});
|
|
486
|
-
it("uses the session it was handed when there is no switcher to ask", async () => {
|
|
487
|
-
// --list-models and friends open a session that belongs to no task and
|
|
488
|
-
// hand it straight over; there is nothing to switch between.
|
|
489
|
-
vi.spyOn(console, "error").mockImplementation(() => { });
|
|
490
|
-
const prompt = vi.fn().mockResolvedValue({ stopReason: "end_turn" });
|
|
491
|
-
const acpClient = {
|
|
492
|
-
flushReply: vi.fn().mockResolvedValue(undefined),
|
|
493
|
-
reportStopReason: vi.fn().mockResolvedValue(undefined),
|
|
494
|
-
};
|
|
495
|
-
await startPendingTask({ text: "just do it", queuedSeq: 1 }, { callTool: vi.fn() }, {
|
|
496
|
-
acpCmdArgsOrConnection: { prompt },
|
|
497
|
-
configsOrSessionSwitcher: undefined,
|
|
498
|
-
agentrqConfigOrAcpClient: acpClient,
|
|
499
|
-
});
|
|
500
|
-
expect(prompt).toHaveBeenCalledWith({
|
|
501
|
-
sessionId: undefined,
|
|
502
|
-
prompt: [{ type: "text", text: "just do it" }],
|
|
503
|
-
});
|
|
504
|
-
});
|
|
505
|
-
it("cancels the session when the cancel lands while it is being opened", async () => {
|
|
506
|
-
// Opening a session takes seconds, and a cancel that arrives inside that
|
|
507
|
-
// window has no turn to stop yet — so the task must not be handed to the
|
|
508
|
-
// agent once the session finally exists.
|
|
509
|
-
vi.spyOn(console, "error").mockImplementation(() => { });
|
|
510
|
-
cancelledTaskSeq.clear();
|
|
511
|
-
const prompt = vi.fn().mockResolvedValue({ stopReason: "end_turn" });
|
|
512
|
-
const acpClient = {
|
|
513
|
-
flushReply: vi.fn().mockResolvedValue(undefined),
|
|
514
|
-
reportStopReason: vi.fn().mockResolvedValue(undefined),
|
|
515
|
-
cancelTurn: vi.fn().mockResolvedValue(undefined),
|
|
516
|
-
};
|
|
517
|
-
const switcher = {
|
|
518
|
-
getSessionId: vi.fn().mockReturnValue("S-Late"),
|
|
519
|
-
ensureForTask: vi.fn(async (id) => {
|
|
520
|
-
markTaskCancelled(id);
|
|
521
|
-
return `S-${id}`;
|
|
522
|
-
}),
|
|
523
|
-
};
|
|
524
|
-
await startPendingTask({ text: "Task ID: T-Late\nnever mind", taskId: "T-Late", queuedSeq: 1 }, { callTool: vi.fn() }, {
|
|
525
|
-
acpCmdArgsOrConnection: { prompt },
|
|
526
|
-
configsOrSessionSwitcher: switcher,
|
|
527
|
-
agentrqConfigOrAcpClient: acpClient,
|
|
528
|
-
});
|
|
529
|
-
expect(acpClient.cancelTurn).toHaveBeenCalledWith("S-T-Late");
|
|
530
|
-
expect(prompt).not.toHaveBeenCalled();
|
|
531
|
-
cancelledTaskSeq.clear();
|
|
532
|
-
});
|
|
533
|
-
});
|
|
534
|
-
describe("createSelfFillingTaskQueue", () => {
|
|
535
|
-
it("fetches work whenever the queue has room, at startup and after", async () => {
|
|
536
|
-
// The whole of "a gateway allowed three tasks runs three tasks": the
|
|
537
|
-
// queue says it has room, and something goes and fills it.
|
|
538
|
-
vi.spyOn(console, "error").mockImplementation(() => { });
|
|
539
|
-
vi.spyOn(console, "log").mockImplementation(() => { });
|
|
540
|
-
resetPendingTaskDrain();
|
|
541
|
-
resetTaskTurns();
|
|
542
|
-
resetConcurrencyReports();
|
|
543
|
-
const bridge = {
|
|
544
|
-
callTool: vi.fn(),
|
|
545
|
-
sendNotification: vi.fn().mockResolvedValue(undefined),
|
|
546
|
-
};
|
|
547
|
-
const connection = {
|
|
548
|
-
prompt: vi.fn().mockResolvedValue({ stopReason: "end_turn" }),
|
|
549
|
-
};
|
|
550
|
-
const acpClient = {
|
|
551
|
-
flushReply: vi.fn().mockResolvedValue(undefined),
|
|
552
|
-
reportStopReason: vi.fn().mockResolvedValue(undefined),
|
|
553
|
-
};
|
|
554
|
-
const switcher = {
|
|
555
|
-
getSessionId: vi.fn().mockReturnValue("S"),
|
|
556
|
-
ensureForTask: vi.fn(async (id) => `S-${id}`),
|
|
557
|
-
};
|
|
558
|
-
bridge.callTool
|
|
559
|
-
.mockResolvedValueOnce({
|
|
560
|
-
isError: false,
|
|
561
|
-
content: [{ type: "text", text: "Task ID: W1\nfirst" }],
|
|
562
|
-
})
|
|
563
|
-
.mockResolvedValue({
|
|
564
|
-
isError: false,
|
|
565
|
-
content: [{ type: "text", text: "no pending tasks exist" }],
|
|
566
|
-
});
|
|
567
|
-
const queue = createSelfFillingTaskQueue(1, bridge, {
|
|
568
|
-
acpCmdArgsOrConnection: connection,
|
|
569
|
-
configsOrSessionSwitcher: switcher,
|
|
570
|
-
agentrqConfigOrAcpClient: acpClient,
|
|
571
|
-
});
|
|
572
|
-
await drainPendingTasks(bridge, queue, {
|
|
573
|
-
acpCmdArgsOrConnection: connection,
|
|
574
|
-
configsOrSessionSwitcher: switcher,
|
|
575
|
-
agentrqConfigOrAcpClient: acpClient,
|
|
576
|
-
taskQueue: queue,
|
|
577
|
-
});
|
|
578
|
-
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
579
|
-
expect(connection.prompt).toHaveBeenCalledTimes(1);
|
|
580
|
-
// The task finished and freed its slot, so the queue went back for more
|
|
581
|
-
// on its own rather than sitting idle until something pushed it.
|
|
582
|
-
expect(bridge.callTool.mock.calls.length).toBeGreaterThanOrEqual(2);
|
|
583
|
-
// And it still reports itself to the workspace, as before.
|
|
584
|
-
expect(bridge.sendNotification).toHaveBeenCalled();
|
|
585
|
-
resetConcurrencyReports();
|
|
586
|
-
vi.restoreAllMocks();
|
|
587
|
-
});
|
|
588
|
-
it("keeps checking for work on an interval while idle, so a workspace with nothing at startup is not idle forever", async () => {
|
|
589
|
-
// Nothing ever runs in this test, so nothing frees a slot and the
|
|
590
|
-
// event-driven check (a task finishing) never fires. A fetch here can
|
|
591
|
-
// only be the idle timer.
|
|
592
|
-
vi.spyOn(console, "error").mockImplementation(() => { });
|
|
593
|
-
vi.spyOn(console, "log").mockImplementation(() => { });
|
|
594
|
-
resetPendingTaskDrain();
|
|
595
|
-
resetTaskTurns();
|
|
596
|
-
resetConcurrencyReports();
|
|
597
|
-
vi.useFakeTimers();
|
|
598
|
-
const bridge = {
|
|
599
|
-
callTool: vi.fn().mockResolvedValue({
|
|
600
|
-
isError: false,
|
|
601
|
-
content: [{ type: "text", text: "no pending tasks exist" }],
|
|
602
|
-
}),
|
|
603
|
-
sendNotification: vi.fn().mockResolvedValue(undefined),
|
|
604
|
-
};
|
|
605
|
-
createSelfFillingTaskQueue(1, bridge, {
|
|
606
|
-
acpCmdArgsOrConnection: [],
|
|
607
|
-
configsOrSessionSwitcher: [],
|
|
608
|
-
agentrqConfigOrAcpClient: {},
|
|
609
|
-
});
|
|
610
|
-
expect(bridge.callTool).not.toHaveBeenCalled();
|
|
611
|
-
await vi.advanceTimersByTimeAsync(IDLE_TASK_POLL_INTERVAL_MS);
|
|
612
|
-
expect(bridge.callTool).toHaveBeenCalledTimes(1);
|
|
613
|
-
await vi.advanceTimersByTimeAsync(IDLE_TASK_POLL_INTERVAL_MS);
|
|
614
|
-
expect(bridge.callTool).toHaveBeenCalledTimes(2);
|
|
615
|
-
vi.useRealTimers();
|
|
616
|
-
resetConcurrencyReports();
|
|
617
|
-
vi.restoreAllMocks();
|
|
618
|
-
});
|
|
619
|
-
it("skips the idle check while a task is still running", async () => {
|
|
620
|
-
// A running task will free its own slot and trigger the event-driven
|
|
621
|
-
// check when it finishes, so the idle timer firing in the meantime has
|
|
622
|
-
// nothing to do here.
|
|
623
|
-
vi.spyOn(console, "error").mockImplementation(() => { });
|
|
624
|
-
vi.spyOn(console, "log").mockImplementation(() => { });
|
|
625
|
-
resetPendingTaskDrain();
|
|
626
|
-
resetTaskTurns();
|
|
627
|
-
resetConcurrencyReports();
|
|
628
|
-
vi.useFakeTimers();
|
|
629
|
-
const bridge = {
|
|
630
|
-
callTool: vi.fn().mockResolvedValue({
|
|
631
|
-
isError: false,
|
|
632
|
-
content: [{ type: "text", text: "no pending tasks exist" }],
|
|
633
|
-
}),
|
|
634
|
-
sendNotification: vi.fn().mockResolvedValue(undefined),
|
|
635
|
-
};
|
|
636
|
-
const queue = createSelfFillingTaskQueue(1, bridge, {
|
|
637
|
-
acpCmdArgsOrConnection: [],
|
|
638
|
-
configsOrSessionSwitcher: [],
|
|
639
|
-
agentrqConfigOrAcpClient: {},
|
|
640
|
-
});
|
|
641
|
-
let release;
|
|
642
|
-
const held = new Promise((resolve) => {
|
|
643
|
-
release = resolve;
|
|
644
|
-
});
|
|
645
|
-
void queue.run(() => held);
|
|
646
|
-
await vi.advanceTimersByTimeAsync(IDLE_TASK_POLL_INTERVAL_MS);
|
|
647
|
-
expect(bridge.callTool).not.toHaveBeenCalled();
|
|
648
|
-
release();
|
|
649
|
-
await vi.advanceTimersByTimeAsync(0);
|
|
650
|
-
vi.useRealTimers();
|
|
651
|
-
resetConcurrencyReports();
|
|
652
|
-
vi.restoreAllMocks();
|
|
653
|
-
});
|
|
654
|
-
});
|
|
655
|
-
describe("freeSlots", () => {
|
|
656
|
-
it("counts the room left, with what is waiting already spoken for", () => {
|
|
657
|
-
const queue = new TaskQueue(3);
|
|
658
|
-
expect(freeSlots(queue)).toBe(3);
|
|
659
|
-
});
|
|
660
|
-
it("never goes negative when the limit was lowered under running work", () => {
|
|
661
|
-
// Lowering never interrupts, so the queue can legitimately hold more than
|
|
662
|
-
// the limit allows — and a negative number of slots would read as room.
|
|
663
|
-
const queue = new TaskQueue(3);
|
|
664
|
-
let release;
|
|
665
|
-
const held = new Promise((resolve) => { release = resolve; });
|
|
666
|
-
const running = [queue.run(() => held), queue.run(() => held), queue.run(() => held)];
|
|
667
|
-
queue.setMaxConcurrency(1);
|
|
668
|
-
expect(freeSlots(queue)).toBe(0);
|
|
669
|
-
release();
|
|
670
|
-
return Promise.all(running);
|
|
671
|
-
});
|
|
672
|
-
});
|
|
673
|
-
describe("drainPendingTasks", () => {
|
|
674
|
-
let bridge;
|
|
675
|
-
let connection;
|
|
676
|
-
let switcher;
|
|
677
|
-
let acpClient;
|
|
678
|
-
/** A workspace answer holding one task. */
|
|
679
|
-
const task = (id) => ({
|
|
680
|
-
isError: false,
|
|
681
|
-
content: [{ type: "text", text: `Task ID: ${id}\nwork on ${id}` }],
|
|
682
|
-
});
|
|
683
|
-
/** The workspace answer meaning there is nothing left. */
|
|
684
|
-
const nothing = () => ({
|
|
685
|
-
isError: false,
|
|
686
|
-
content: [{ type: "text", text: "no pending tasks exist" }],
|
|
687
|
-
});
|
|
688
|
-
const deps = () => ({
|
|
689
|
-
acpCmdArgsOrConnection: connection,
|
|
690
|
-
configsOrSessionSwitcher: switcher,
|
|
691
|
-
agentrqConfigOrAcpClient: acpClient,
|
|
692
|
-
});
|
|
693
|
-
beforeEach(() => {
|
|
694
|
-
vi.spyOn(console, "error").mockImplementation(() => { });
|
|
695
|
-
vi.spyOn(console, "log").mockImplementation(() => { });
|
|
696
|
-
resetPendingTaskDrain();
|
|
697
|
-
resetTaskTurns();
|
|
698
|
-
bridge = { callTool: vi.fn() };
|
|
699
|
-
connection = { prompt: vi.fn().mockResolvedValue({ stopReason: "end_turn" }) };
|
|
700
|
-
switcher = {
|
|
701
|
-
getSessionId: vi.fn().mockReturnValue("S"),
|
|
702
|
-
ensureForTask: vi.fn(async (id) => `S-${id}`),
|
|
703
|
-
};
|
|
704
|
-
acpClient = {
|
|
705
|
-
flushReply: vi.fn().mockResolvedValue(undefined),
|
|
706
|
-
reportStopReason: vi.fn().mockResolvedValue(undefined),
|
|
707
|
-
};
|
|
708
|
-
});
|
|
709
|
-
afterEach(() => {
|
|
710
|
-
vi.restoreAllMocks();
|
|
711
|
-
});
|
|
712
|
-
it("fills every free slot instead of taking a single task", async () => {
|
|
713
|
-
// The bug this exists for: three tasks waiting, three slots, and the
|
|
714
|
-
// gateway running one of them because it only ever asked once.
|
|
715
|
-
const queue = new TaskQueue(3);
|
|
716
|
-
let release;
|
|
717
|
-
const held = new Promise((resolve) => { release = resolve; });
|
|
718
|
-
connection.prompt.mockReturnValue(held.then(() => ({ stopReason: "end_turn" })));
|
|
719
|
-
bridge.callTool
|
|
720
|
-
.mockResolvedValueOnce(task("D1"))
|
|
721
|
-
.mockResolvedValueOnce(task("D2"))
|
|
722
|
-
.mockResolvedValueOnce(task("D3"))
|
|
723
|
-
.mockResolvedValue(nothing());
|
|
724
|
-
await drainPendingTasks(bridge, queue, deps());
|
|
725
|
-
expect(queue.getActiveCount()).toBe(3);
|
|
726
|
-
// Three fetches and no fourth: it stops at the limit rather than
|
|
727
|
-
// emptying the workspace into a queue nobody asked it to hold.
|
|
728
|
-
expect(bridge.callTool).toHaveBeenCalledTimes(3);
|
|
729
|
-
release();
|
|
730
|
-
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
731
|
-
expect(connection.prompt).toHaveBeenCalledTimes(3);
|
|
732
|
-
});
|
|
733
|
-
it("keeps working after a drain that found no room at all", async () => {
|
|
734
|
-
// The drain that does nothing never waits for anything, so it finishes
|
|
735
|
-
// before the promise it will be remembered by even exists. Remembering
|
|
736
|
-
// it anyway left a settled promise in the one-drain-at-a-time slot, and
|
|
737
|
-
// every later drain joined it and fetched nothing — the whole feature
|
|
738
|
-
// switching itself off after one harmless call.
|
|
739
|
-
const queue = new TaskQueue(1);
|
|
740
|
-
let release;
|
|
741
|
-
const held = new Promise((resolve) => { release = resolve; });
|
|
742
|
-
const running = queue.run(() => held);
|
|
743
|
-
await drainPendingTasks(bridge, queue, deps());
|
|
744
|
-
expect(bridge.callTool).not.toHaveBeenCalled();
|
|
745
|
-
release();
|
|
746
|
-
await running;
|
|
747
|
-
bridge.callTool.mockResolvedValueOnce(task("A1")).mockResolvedValue(nothing());
|
|
748
|
-
await drainPendingTasks(bridge, queue, deps());
|
|
749
|
-
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
750
|
-
expect(connection.prompt).toHaveBeenCalledTimes(1);
|
|
751
|
-
});
|
|
752
|
-
it("counts a task parked behind an earlier turn against the room it has", async () => {
|
|
753
|
-
// A second message on one chat waits for the first and takes no slot, so
|
|
754
|
-
// the queue still reads as having room. Fetching against that same room
|
|
755
|
-
// again and again would empty the workspace into this process, where
|
|
756
|
-
// nobody else can pick the work up.
|
|
757
|
-
resetTaskTurns();
|
|
758
|
-
const queue = new TaskQueue(2);
|
|
759
|
-
let releaseEarlier;
|
|
760
|
-
const earlier = new Promise((resolve) => { releaseEarlier = resolve; });
|
|
761
|
-
const earlierTurn = runTurnForTask("P1", () => earlier);
|
|
762
|
-
let release;
|
|
763
|
-
const held = new Promise((resolve) => { release = resolve; });
|
|
764
|
-
connection.prompt.mockReturnValue(held.then(() => ({ stopReason: "end_turn" })));
|
|
765
|
-
bridge.callTool
|
|
766
|
-
.mockResolvedValueOnce(task("P1"))
|
|
767
|
-
.mockResolvedValueOnce(task("P2"))
|
|
768
|
-
.mockResolvedValue(nothing());
|
|
769
|
-
await drainPendingTasks(bridge, queue, deps());
|
|
770
|
-
// Two slots, two tasks taken: the parked one counts, so there is no
|
|
771
|
-
// third fetch against the slot it is going to want.
|
|
772
|
-
expect(bridge.callTool).toHaveBeenCalledTimes(2);
|
|
773
|
-
releaseEarlier();
|
|
774
|
-
release();
|
|
775
|
-
await earlierTurn;
|
|
776
|
-
});
|
|
777
|
-
it("moves past a repeat instead of abandoning the slot it was meant to fill", async () => {
|
|
778
|
-
// A repeat has already been dequeued and dropped. Treating that as "the
|
|
779
|
-
// workspace is empty" left every slot idle behind it, and with nothing
|
|
780
|
-
// running there is no completion coming to start another drain.
|
|
781
|
-
const queue = new TaskQueue(2);
|
|
782
|
-
bridge.callTool
|
|
783
|
-
.mockResolvedValueOnce(task("S1"))
|
|
784
|
-
.mockResolvedValueOnce(task("S1"))
|
|
785
|
-
.mockResolvedValueOnce(task("S2"))
|
|
786
|
-
.mockResolvedValue(nothing());
|
|
787
|
-
// The first S1 is taken and run; the second is the repeat.
|
|
788
|
-
await drainPendingTasks(bridge, queue, deps());
|
|
789
|
-
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
790
|
-
expect(connection.prompt).toHaveBeenCalledTimes(2);
|
|
791
|
-
expect(connection.prompt).toHaveBeenLastCalledWith({
|
|
792
|
-
sessionId: "S-S2",
|
|
793
|
-
prompt: [{ type: "text", text: "Task ID: S2\nwork on S2" }],
|
|
794
|
-
});
|
|
795
|
-
});
|
|
796
|
-
it("gives up on a workspace that hands back nothing but repeats", async () => {
|
|
797
|
-
const queue = new TaskQueue(4);
|
|
798
|
-
bridge.callTool.mockResolvedValueOnce(task("K1")).mockResolvedValue(task("K1"));
|
|
799
|
-
await drainPendingTasks(bridge, queue, deps());
|
|
800
|
-
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
801
|
-
// The task itself, then the repeats it is willing to sit through.
|
|
802
|
-
expect(bridge.callTool).toHaveBeenCalledTimes(1 + MAX_SKIPPED_FETCHES);
|
|
803
|
-
});
|
|
804
|
-
it("leaves a workspace it could not reach to its own reconnection", async () => {
|
|
805
|
-
// Retrying a failing call in a tight loop is how a gateway turns a blip
|
|
806
|
-
// into an outage of its own.
|
|
807
|
-
const queue = new TaskQueue(3);
|
|
808
|
-
bridge.callTool.mockRejectedValue(new Error("network error"));
|
|
809
|
-
await drainPendingTasks(bridge, queue, deps());
|
|
810
|
-
expect(bridge.callTool).toHaveBeenCalledTimes(1);
|
|
811
|
-
});
|
|
812
|
-
it("asks once and stops when the workspace has nothing waiting", async () => {
|
|
813
|
-
const queue = new TaskQueue(3);
|
|
814
|
-
bridge.callTool.mockResolvedValue(nothing());
|
|
815
|
-
await drainPendingTasks(bridge, queue, deps());
|
|
816
|
-
expect(bridge.callTool).toHaveBeenCalledTimes(1);
|
|
817
|
-
expect(connection.prompt).not.toHaveBeenCalled();
|
|
818
|
-
});
|
|
819
|
-
it("does not ask at all while the queue is full", async () => {
|
|
820
|
-
const queue = new TaskQueue(1);
|
|
821
|
-
let release;
|
|
822
|
-
const held = new Promise((resolve) => { release = resolve; });
|
|
823
|
-
const running = queue.run(() => held);
|
|
824
|
-
await drainPendingTasks(bridge, queue, deps());
|
|
825
|
-
expect(bridge.callTool).not.toHaveBeenCalled();
|
|
826
|
-
release();
|
|
827
|
-
await running;
|
|
828
|
-
});
|
|
829
|
-
it("counts a task waiting in the queue as a slot already spoken for", async () => {
|
|
830
|
-
// Queued work is work this gateway has promised to run; fetching more
|
|
831
|
-
// against it would pull the whole workspace in and hold it here.
|
|
832
|
-
const queue = new TaskQueue(1);
|
|
833
|
-
let release;
|
|
834
|
-
const held = new Promise((resolve) => { release = resolve; });
|
|
835
|
-
const running = queue.run(() => held);
|
|
836
|
-
const waiting = queue.run(async () => { });
|
|
837
|
-
await drainPendingTasks(bridge, queue, deps());
|
|
838
|
-
expect(bridge.callTool).not.toHaveBeenCalled();
|
|
839
|
-
release();
|
|
840
|
-
await Promise.all([running, waiting]);
|
|
841
|
-
});
|
|
842
|
-
it("joins a drain already running, and answers the wake-up that joining collapsed", async () => {
|
|
843
|
-
// Every trigger — a task finishing, a limit rising — can land while a
|
|
844
|
-
// drain is waiting on getTask. A second drain started there would be
|
|
845
|
-
// asking for the task the first one is about to be handed; but simply
|
|
846
|
-
// swallowing the news would leave the slot that just came free empty,
|
|
847
|
-
// because the drain that swallowed it may already have been told the
|
|
848
|
-
// workspace is empty.
|
|
849
|
-
let queue;
|
|
850
|
-
const rejoined = [];
|
|
851
|
-
queue = new TaskQueue(2, undefined, () => {
|
|
852
|
-
rejoined.push(drainPendingTasks(bridge, queue, { ...deps(), taskQueue: queue }));
|
|
853
|
-
});
|
|
854
|
-
let release;
|
|
855
|
-
const held = new Promise((resolve) => { release = resolve; });
|
|
856
|
-
const running = queue.run(() => held);
|
|
857
|
-
const answerFetch = [];
|
|
858
|
-
bridge.callTool.mockImplementation(() => new Promise((resolve) => { answerFetch.push(resolve); }));
|
|
859
|
-
const draining = drainPendingTasks(bridge, queue, { ...deps(), taskQueue: queue });
|
|
860
|
-
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
861
|
-
expect(answerFetch.length).toBe(1);
|
|
862
|
-
// The slot comes free while that fetch is still in the air.
|
|
863
|
-
release();
|
|
864
|
-
await running;
|
|
865
|
-
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
866
|
-
expect(rejoined).toHaveLength(1);
|
|
867
|
-
expect(rejoined[0]).toBe(draining);
|
|
868
|
-
// The drain that collapsed it is told there is nothing — and goes back
|
|
869
|
-
// anyway, because the slot it heard about came free after it had asked.
|
|
870
|
-
answerFetch[0](nothing());
|
|
871
|
-
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
872
|
-
expect(answerFetch.length).toBe(2);
|
|
873
|
-
answerFetch[1](nothing());
|
|
874
|
-
await draining;
|
|
875
|
-
expect(connection.prompt).not.toHaveBeenCalled();
|
|
876
|
-
});
|
|
877
|
-
it("goes back for more when a finished task frees a slot", async () => {
|
|
878
|
-
let queue;
|
|
879
|
-
queue = new TaskQueue(1, undefined, () => {
|
|
880
|
-
void drainPendingTasks(bridge, queue, { ...deps(), taskQueue: queue });
|
|
881
|
-
});
|
|
882
|
-
bridge.callTool.mockResolvedValueOnce(task("L1")).mockResolvedValue(nothing());
|
|
883
|
-
await drainPendingTasks(bridge, queue, { ...deps(), taskQueue: queue });
|
|
884
|
-
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
885
|
-
expect(connection.prompt).toHaveBeenCalledTimes(1);
|
|
886
|
-
// Asked again once the slot came back, and was told there was nothing.
|
|
887
|
-
expect(bridge.callTool.mock.calls.length).toBeGreaterThanOrEqual(2);
|
|
888
|
-
});
|
|
889
|
-
it("keeps filling slots when one of the tasks fails", async () => {
|
|
890
|
-
// One task that cannot run is not a reason to leave the other slots empty.
|
|
891
|
-
const queue = new TaskQueue(2);
|
|
892
|
-
let release;
|
|
893
|
-
const held = new Promise((resolve) => { release = resolve; });
|
|
894
|
-
connection.prompt
|
|
895
|
-
.mockRejectedValueOnce(new Error("agent said no"))
|
|
896
|
-
.mockReturnValue(held.then(() => ({ stopReason: "end_turn" })));
|
|
897
|
-
bridge.callTool
|
|
898
|
-
.mockResolvedValueOnce(task("F1"))
|
|
899
|
-
.mockResolvedValueOnce(task("F2"))
|
|
900
|
-
.mockResolvedValue(nothing());
|
|
901
|
-
await drainPendingTasks(bridge, queue, deps());
|
|
902
|
-
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
903
|
-
expect(connection.prompt).toHaveBeenCalledTimes(2);
|
|
904
|
-
expect(console.error).toHaveBeenCalledWith(expect.stringContaining("Error running task F1"), expect.any(Error));
|
|
905
|
-
release();
|
|
906
|
-
});
|
|
907
|
-
it("names an unnamed task in the log rather than saying nothing went wrong", async () => {
|
|
908
|
-
const queue = new TaskQueue(1);
|
|
909
|
-
connection.prompt.mockRejectedValue(new Error("agent said no"));
|
|
910
|
-
bridge.callTool
|
|
911
|
-
.mockResolvedValueOnce({
|
|
912
|
-
isError: false,
|
|
913
|
-
content: [{ type: "text", text: "/compact and then some" }],
|
|
914
|
-
})
|
|
915
|
-
.mockResolvedValue(nothing());
|
|
916
|
-
await drainPendingTasks(bridge, queue, deps());
|
|
917
|
-
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
918
|
-
expect(console.error).toHaveBeenCalledWith(expect.stringContaining("Error running task (unnamed)"), expect.any(Error));
|
|
919
|
-
});
|
|
920
|
-
it("fills the slots a raised limit just opened", async () => {
|
|
921
|
-
// Raising the limit with nothing waiting internally used to start
|
|
922
|
-
// nothing at all: the tasks it could now run were in the workspace,
|
|
923
|
-
// and nothing went to ask for them.
|
|
924
|
-
let queue;
|
|
925
|
-
queue = new TaskQueue(1, undefined, () => {
|
|
926
|
-
void drainPendingTasks(bridge, queue, { ...deps(), taskQueue: queue });
|
|
927
|
-
});
|
|
928
|
-
let release;
|
|
929
|
-
const held = new Promise((resolve) => { release = resolve; });
|
|
930
|
-
connection.prompt.mockReturnValue(held.then(() => ({ stopReason: "end_turn" })));
|
|
931
|
-
bridge.callTool
|
|
932
|
-
.mockResolvedValueOnce(task("U1"))
|
|
933
|
-
.mockResolvedValueOnce(task("U2"))
|
|
934
|
-
.mockResolvedValueOnce(task("U3"))
|
|
935
|
-
.mockResolvedValue(nothing());
|
|
936
|
-
await drainPendingTasks(bridge, queue, { ...deps(), taskQueue: queue });
|
|
937
|
-
expect(queue.getActiveCount()).toBe(1);
|
|
938
|
-
queue.setMaxConcurrency(3);
|
|
939
|
-
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
940
|
-
expect(queue.getActiveCount()).toBe(3);
|
|
941
|
-
release();
|
|
942
|
-
});
|
|
943
|
-
});
|
|
944
|
-
describe("TaskQueue", () => {
|
|
945
|
-
it("should run tasks up to maxConcurrency immediately", async () => {
|
|
946
|
-
const queue = new TaskQueue(2);
|
|
947
|
-
let running = 0;
|
|
948
|
-
const tasks = Array.from({ length: 3 }, async (_, i) => {
|
|
949
|
-
return queue.run(async () => {
|
|
950
|
-
running++;
|
|
951
|
-
expect(running).toBeLessThanOrEqual(2);
|
|
952
|
-
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
953
|
-
running--;
|
|
954
|
-
});
|
|
955
|
-
});
|
|
956
|
-
await Promise.all(tasks);
|
|
957
|
-
});
|
|
958
|
-
it("should queue subsequent tasks and execute them when previous ones finish", async () => {
|
|
959
|
-
const queue = new TaskQueue(1);
|
|
960
|
-
const executionOrder = [];
|
|
961
|
-
const t1 = queue.run(async () => {
|
|
962
|
-
executionOrder.push(1);
|
|
963
|
-
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
964
|
-
});
|
|
965
|
-
const t2 = queue.run(async () => {
|
|
966
|
-
executionOrder.push(2);
|
|
967
|
-
});
|
|
968
|
-
await Promise.all([t1, t2]);
|
|
969
|
-
expect(executionOrder).toEqual([1, 2]);
|
|
970
|
-
});
|
|
971
|
-
it("should handle error in immediate task and decrement activeCount", async () => {
|
|
972
|
-
const queue = new TaskQueue(1);
|
|
973
|
-
await expect(queue.run(async () => {
|
|
974
|
-
throw new Error("immediate error");
|
|
975
|
-
})).rejects.toThrow("immediate error");
|
|
976
|
-
expect(queue.getActiveCount()).toBe(0);
|
|
977
|
-
});
|
|
978
|
-
it("should handle error in queued task, reject, and trigger next task", async () => {
|
|
979
|
-
const queue = new TaskQueue(1);
|
|
980
|
-
const logSpy = vi.spyOn(console, "log").mockImplementation(() => { });
|
|
981
|
-
let resolveFirst;
|
|
982
|
-
const firstPromise = new Promise((resolve) => { resolveFirst = resolve; });
|
|
983
|
-
const t1 = queue.run(async () => {
|
|
984
|
-
await firstPromise;
|
|
985
|
-
});
|
|
986
|
-
const t2 = queue.run(async () => {
|
|
987
|
-
throw new Error("queued error");
|
|
988
|
-
});
|
|
989
|
-
let ranThird = false;
|
|
990
|
-
const t3 = queue.run(async () => {
|
|
991
|
-
ranThird = true;
|
|
992
|
-
});
|
|
993
|
-
expect(queue.getQueueLength()).toBe(2);
|
|
994
|
-
resolveFirst();
|
|
995
|
-
await t1;
|
|
996
|
-
await expect(t2).rejects.toThrow("queued error");
|
|
997
|
-
await t3;
|
|
998
|
-
// Allow catch microtasks to run
|
|
999
|
-
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
1000
|
-
expect(ranThird).toBe(true);
|
|
1001
|
-
expect(queue.getActiveCount()).toBe(0);
|
|
1002
|
-
expect(logSpy).toHaveBeenCalledWith("[queue] Error executing queued task:", expect.any(Error));
|
|
1003
|
-
logSpy.mockRestore();
|
|
1004
|
-
});
|
|
1005
|
-
it("reports the limit it was built with", () => {
|
|
1006
|
-
expect(new TaskQueue(3).getMaxConcurrency()).toBe(3);
|
|
1007
|
-
});
|
|
1008
|
-
it("starts every task a raised limit has room for, not one at a time", async () => {
|
|
1009
|
-
const queue = new TaskQueue(1);
|
|
1010
|
-
let release;
|
|
1011
|
-
const held = new Promise((resolve) => { release = resolve; });
|
|
1012
|
-
const started = [];
|
|
1013
|
-
const runs = [
|
|
1014
|
-
queue.run(async () => { started.push(0); await held; }),
|
|
1015
|
-
queue.run(async () => { started.push(1); }),
|
|
1016
|
-
queue.run(async () => { started.push(2); }),
|
|
1017
|
-
queue.run(async () => { started.push(3); }),
|
|
1018
|
-
];
|
|
1019
|
-
// Only the first is running; the other three are waiting on a limit of 1.
|
|
1020
|
-
expect(queue.getActiveCount()).toBe(1);
|
|
1021
|
-
expect(queue.getQueueLength()).toBe(3);
|
|
1022
|
-
queue.setMaxConcurrency(4);
|
|
1023
|
-
// All three waiting tasks start at once, without the running one
|
|
1024
|
-
// finishing first — a raise that took effect one task per completion
|
|
1025
|
-
// would leave two of them still queued here.
|
|
1026
|
-
expect(started).toEqual([0, 1, 2, 3]);
|
|
1027
|
-
expect(queue.getMaxConcurrency()).toBe(4);
|
|
1028
|
-
release();
|
|
1029
|
-
await Promise.all(runs);
|
|
1030
|
-
});
|
|
1031
|
-
it("starts only as many as the new limit allows, and leaves the rest queued", async () => {
|
|
1032
|
-
const queue = new TaskQueue(1);
|
|
1033
|
-
let release;
|
|
1034
|
-
const held = new Promise((resolve) => { release = resolve; });
|
|
1035
|
-
const runs = [
|
|
1036
|
-
queue.run(async () => { await held; }),
|
|
1037
|
-
queue.run(async () => { await held; }),
|
|
1038
|
-
queue.run(async () => { await held; }),
|
|
1039
|
-
queue.run(async () => { await held; }),
|
|
1040
|
-
];
|
|
1041
|
-
queue.setMaxConcurrency(2);
|
|
1042
|
-
expect(queue.getActiveCount()).toBe(2);
|
|
1043
|
-
expect(queue.getQueueLength()).toBe(2);
|
|
1044
|
-
release();
|
|
1045
|
-
await Promise.all(runs);
|
|
1046
|
-
});
|
|
1047
|
-
it("never interrupts work already in flight when the limit is lowered", async () => {
|
|
1048
|
-
const queue = new TaskQueue(3);
|
|
1049
|
-
let release;
|
|
1050
|
-
const held = new Promise((resolve) => { release = resolve; });
|
|
1051
|
-
const finished = [];
|
|
1052
|
-
const runs = [
|
|
1053
|
-
queue.run(async () => { await held; finished.push(0); }),
|
|
1054
|
-
queue.run(async () => { await held; finished.push(1); }),
|
|
1055
|
-
queue.run(async () => { await held; finished.push(2); }),
|
|
1056
|
-
];
|
|
1057
|
-
const queued = queue.run(async () => { finished.push(3); });
|
|
1058
|
-
expect(queue.getActiveCount()).toBe(3);
|
|
1059
|
-
queue.setMaxConcurrency(1);
|
|
1060
|
-
// The three that already have the agent's attention keep it — a lowered
|
|
1061
|
-
// limit is honoured going forward, not retroactively.
|
|
1062
|
-
expect(queue.getActiveCount()).toBe(3);
|
|
1063
|
-
expect(queue.getQueueLength()).toBe(1);
|
|
1064
|
-
release();
|
|
1065
|
-
await Promise.all([...runs, queued]);
|
|
1066
|
-
expect(finished).toEqual([0, 1, 2, 3]);
|
|
1067
|
-
expect(queue.getActiveCount()).toBe(0);
|
|
1068
|
-
});
|
|
1069
|
-
it("holds the queue until the active count falls under a lowered limit", async () => {
|
|
1070
|
-
const queue = new TaskQueue(2);
|
|
1071
|
-
const releases = [];
|
|
1072
|
-
const hold = () => new Promise((resolve) => { releases.push(resolve); });
|
|
1073
|
-
const first = queue.run(hold);
|
|
1074
|
-
const second = queue.run(hold);
|
|
1075
|
-
const third = queue.run(async () => { });
|
|
1076
|
-
queue.setMaxConcurrency(1);
|
|
1077
|
-
expect(queue.getQueueLength()).toBe(1);
|
|
1078
|
-
// One finishing still leaves one running, which is already the whole of
|
|
1079
|
-
// the new limit, so the waiting task must not start yet.
|
|
1080
|
-
releases[0]();
|
|
1081
|
-
await first;
|
|
1082
|
-
expect(queue.getQueueLength()).toBe(1);
|
|
1083
|
-
expect(queue.getActiveCount()).toBe(1);
|
|
1084
|
-
releases[1]();
|
|
1085
|
-
await second;
|
|
1086
|
-
await third;
|
|
1087
|
-
expect(queue.getActiveCount()).toBe(0);
|
|
1088
|
-
});
|
|
1089
|
-
it("does nothing, and says nothing, when the limit has not actually changed", () => {
|
|
1090
|
-
const queue = new TaskQueue(4);
|
|
1091
|
-
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
|
|
1092
|
-
errorSpy.mockClear();
|
|
1093
|
-
queue.setMaxConcurrency(4);
|
|
1094
|
-
expect(queue.getMaxConcurrency()).toBe(4);
|
|
1095
|
-
expect(errorSpy).not.toHaveBeenCalled();
|
|
1096
|
-
errorSpy.mockRestore();
|
|
1097
|
-
});
|
|
1098
|
-
describe("saying when its numbers move", () => {
|
|
1099
|
-
/** Records what the queue looked like at each announcement. */
|
|
1100
|
-
const watch = (queue) => {
|
|
1101
|
-
const seen = [];
|
|
1102
|
-
return {
|
|
1103
|
-
seen,
|
|
1104
|
-
onChange: () => seen.push({
|
|
1105
|
-
active: queue().getActiveCount(),
|
|
1106
|
-
queued: queue().getQueueLength(),
|
|
1107
|
-
}),
|
|
1108
|
-
};
|
|
1109
|
-
};
|
|
1110
|
-
it("says so when a task starts, and again when it finishes", async () => {
|
|
1111
|
-
// Without this the workspace hears the count once, while the gateway is
|
|
1112
|
-
// idle, and then shows 0 running for the rest of its life.
|
|
1113
|
-
let queue;
|
|
1114
|
-
const { seen, onChange } = watch(() => queue);
|
|
1115
|
-
queue = new TaskQueue(2, onChange);
|
|
1116
|
-
let release;
|
|
1117
|
-
const held = new Promise((resolve) => { release = resolve; });
|
|
1118
|
-
const running = queue.run(() => held);
|
|
1119
|
-
expect(seen).toEqual([{ active: 1, queued: 0 }]);
|
|
1120
|
-
release();
|
|
1121
|
-
await running;
|
|
1122
|
-
expect(seen).toEqual([
|
|
1123
|
-
{ active: 1, queued: 0 },
|
|
1124
|
-
{ active: 0, queued: 0 },
|
|
1125
|
-
]);
|
|
1126
|
-
});
|
|
1127
|
-
it("says so when a task is made to wait, with nothing newly running", async () => {
|
|
1128
|
-
let queue;
|
|
1129
|
-
const { seen, onChange } = watch(() => queue);
|
|
1130
|
-
queue = new TaskQueue(1, onChange);
|
|
1131
|
-
let release;
|
|
1132
|
-
const held = new Promise((resolve) => { release = resolve; });
|
|
1133
|
-
const first = queue.run(() => held);
|
|
1134
|
-
const second = queue.run(async () => { });
|
|
1135
|
-
// The second changed what is waiting, not what is running.
|
|
1136
|
-
expect(seen).toEqual([
|
|
1137
|
-
{ active: 1, queued: 0 },
|
|
1138
|
-
{ active: 1, queued: 1 },
|
|
1139
|
-
]);
|
|
1140
|
-
release();
|
|
1141
|
-
await Promise.all([first, second]);
|
|
1142
|
-
// A slot came free, then the waiting task took it, then it finished.
|
|
1143
|
-
expect(seen.slice(2)).toEqual([
|
|
1144
|
-
{ active: 0, queued: 1 },
|
|
1145
|
-
{ active: 1, queued: 0 },
|
|
1146
|
-
{ active: 0, queued: 0 },
|
|
1147
|
-
]);
|
|
1148
|
-
});
|
|
1149
|
-
it("runs tasks normally when nobody is listening", async () => {
|
|
1150
|
-
// The queue is built without a listener throughout these tests and in
|
|
1151
|
-
// --list-models; an optional callback must stay optional.
|
|
1152
|
-
const queue = new TaskQueue(1);
|
|
1153
|
-
let ran = false;
|
|
1154
|
-
await expect(queue.run(async () => { ran = true; })).resolves.toBeUndefined();
|
|
1155
|
-
expect(ran).toBe(true);
|
|
1156
|
-
expect(queue.getActiveCount()).toBe(0);
|
|
1157
|
-
});
|
|
1158
|
-
it("tells the workspace, end to end, when a task starts and finishes", async () => {
|
|
1159
|
-
const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
|
|
1160
|
-
// The callback is only worth anything if it reaches the wire, so this
|
|
1161
|
-
// asserts on the notification rather than on the callback firing.
|
|
1162
|
-
const bridge = { sendNotification: vi.fn().mockResolvedValue(undefined) };
|
|
1163
|
-
const queue = createTaskQueue(2, bridge);
|
|
1164
|
-
let release;
|
|
1165
|
-
const held = new Promise((resolve) => { release = resolve; });
|
|
1166
|
-
const running = queue.run(() => held);
|
|
1167
|
-
await flush();
|
|
1168
|
-
expect(bridge.sendNotification).toHaveBeenCalledWith("notifications/claude/channel/concurrency", expect.objectContaining({ maxConcurrency: 2, active: 1, queued: 0 }));
|
|
1169
|
-
release();
|
|
1170
|
-
await running;
|
|
1171
|
-
await flush();
|
|
1172
|
-
expect(bridge.sendNotification).toHaveBeenLastCalledWith("notifications/claude/channel/concurrency", expect.objectContaining({ maxConcurrency: 2, active: 0, queued: 0 }));
|
|
1173
|
-
});
|
|
1174
|
-
it("keeps running tasks when the listener throws", async () => {
|
|
1175
|
-
// Announcing happens inside execute, including in its finally — a
|
|
1176
|
-
// listener that threw there would replace the task's own error with its
|
|
1177
|
-
// own. Running tasks is the job; telling an interface is a courtesy.
|
|
1178
|
-
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
|
|
1179
|
-
const queue = new TaskQueue(1, () => {
|
|
1180
|
-
throw new Error("the workspace is on fire");
|
|
1181
|
-
});
|
|
1182
|
-
let ran = false;
|
|
1183
|
-
await expect(queue.run(async () => { ran = true; })).resolves.toBeUndefined();
|
|
1184
|
-
expect(ran).toBe(true);
|
|
1185
|
-
// And a task's own failure still reaches its caller unchanged.
|
|
1186
|
-
await expect(queue.run(async () => { throw new Error("the task itself failed"); })).rejects.toThrow("the task itself failed");
|
|
1187
|
-
expect(errorSpy).toHaveBeenCalledWith("[queue] Error reporting the queue's state:", expect.any(Error));
|
|
1188
|
-
errorSpy.mockRestore();
|
|
1189
|
-
});
|
|
1190
|
-
});
|
|
1191
|
-
});
|
|
1192
|
-
describe("offering its free capacity", () => {
|
|
1193
|
-
it("says so when a task finishes, but not when one starts", async () => {
|
|
1194
|
-
// Two different questions: the numbers moved (a start moves them too),
|
|
1195
|
-
// and there may be room now. Only the second is a reason to go and ask
|
|
1196
|
-
// the workspace for more work.
|
|
1197
|
-
let queue;
|
|
1198
|
-
const offers = [];
|
|
1199
|
-
queue = new TaskQueue(1, undefined, () => offers.push(queue.getActiveCount()));
|
|
1200
|
-
let release;
|
|
1201
|
-
const held = new Promise((resolve) => { release = resolve; });
|
|
1202
|
-
const running = queue.run(() => held);
|
|
1203
|
-
expect(offers).toEqual([]);
|
|
1204
|
-
release();
|
|
1205
|
-
await running;
|
|
1206
|
-
expect(offers).toEqual([0]);
|
|
1207
|
-
});
|
|
1208
|
-
it("says so when the limit is raised, even with nothing waiting here", async () => {
|
|
1209
|
-
// The tasks a raise makes room for are usually still in the workspace,
|
|
1210
|
-
// so a raise that told nobody would run nothing at all.
|
|
1211
|
-
let offered = 0;
|
|
1212
|
-
const queue = new TaskQueue(1, undefined, () => { offered++; });
|
|
1213
|
-
queue.setMaxConcurrency(3);
|
|
1214
|
-
expect(offered).toBe(1);
|
|
1215
|
-
// Not a change, so nothing to offer.
|
|
1216
|
-
queue.setMaxConcurrency(3);
|
|
1217
|
-
expect(offered).toBe(1);
|
|
1218
|
-
});
|
|
1219
|
-
it("says nothing when what was queued here takes the slot straight back", async () => {
|
|
1220
|
-
// Otherwise the gateway hears "room!" and fetches a task to sit beside
|
|
1221
|
-
// work it had already promised to run.
|
|
1222
|
-
let queue;
|
|
1223
|
-
const roomSeen = [];
|
|
1224
|
-
queue = new TaskQueue(1, undefined, () => roomSeen.push(freeSlots(queue)));
|
|
1225
|
-
let release;
|
|
1226
|
-
const held = new Promise((resolve) => { release = resolve; });
|
|
1227
|
-
const first = queue.run(() => held);
|
|
1228
|
-
let releaseSecond;
|
|
1229
|
-
const second = queue.run(() => new Promise((resolve) => { releaseSecond = resolve; }));
|
|
1230
|
-
release();
|
|
1231
|
-
await first;
|
|
1232
|
-
expect(roomSeen).toEqual([]);
|
|
1233
|
-
releaseSecond();
|
|
1234
|
-
await second;
|
|
1235
|
-
// Only now, with nothing left waiting, is there room worth mentioning.
|
|
1236
|
-
expect(roomSeen).toEqual([1]);
|
|
1237
|
-
});
|
|
1238
|
-
it("says nothing when the limit is lowered under work already running", async () => {
|
|
1239
|
-
// Lowering never interrupts, so a lowered limit leaves less room, not
|
|
1240
|
-
// more — and asking the workspace for another task would be absurd.
|
|
1241
|
-
let offered = 0;
|
|
1242
|
-
const queue = new TaskQueue(3, undefined, () => { offered++; });
|
|
1243
|
-
let release;
|
|
1244
|
-
const held = new Promise((resolve) => { release = resolve; });
|
|
1245
|
-
const running = [queue.run(() => held), queue.run(() => held), queue.run(() => held)];
|
|
1246
|
-
queue.setMaxConcurrency(1);
|
|
1247
|
-
expect(offered).toBe(0);
|
|
1248
|
-
release();
|
|
1249
|
-
await Promise.all(running);
|
|
1250
|
-
});
|
|
1251
|
-
it("survives a listener that throws, so a finished task still finishes", async () => {
|
|
1252
|
-
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
|
|
1253
|
-
const queue = new TaskQueue(1, undefined, () => {
|
|
1254
|
-
throw new Error("nobody to tell");
|
|
1255
|
-
});
|
|
1256
|
-
await expect(queue.run(async () => { })).resolves.toBeUndefined();
|
|
1257
|
-
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("Error offering the queue's free capacity"), expect.any(Error));
|
|
1258
|
-
errorSpy.mockRestore();
|
|
1259
|
-
});
|
|
1260
|
-
it("is wired through createTaskQueue, which is how the gateway gets it", () => {
|
|
1261
|
-
const bridge = { sendNotification: vi.fn().mockResolvedValue(undefined) };
|
|
1262
|
-
let offered = 0;
|
|
1263
|
-
const queue = createTaskQueue(2, bridge, () => { offered++; });
|
|
1264
|
-
queue.setMaxConcurrency(3);
|
|
1265
|
-
expect(offered).toBe(1);
|
|
1266
|
-
resetConcurrencyReports();
|
|
1267
|
-
});
|
|
1268
|
-
});
|
|
1269
|
-
describe("handleSetConcurrency", () => {
|
|
1270
|
-
let errorSpy;
|
|
1271
|
-
beforeEach(() => {
|
|
1272
|
-
errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
|
|
1273
|
-
});
|
|
1274
|
-
afterEach(() => {
|
|
1275
|
-
errorSpy.mockRestore();
|
|
1276
|
-
});
|
|
1277
|
-
const fakeConcurrencyBridge = () => ({
|
|
1278
|
-
sendNotification: vi.fn().mockResolvedValue(undefined),
|
|
1279
|
-
});
|
|
1280
|
-
it("applies the limit the workspace asked for and reports it back", async () => {
|
|
1281
|
-
const queue = new TaskQueue(1);
|
|
1282
|
-
const bridge = fakeConcurrencyBridge();
|
|
1283
|
-
await handleSetConcurrency({ maxConcurrency: 5 }, queue, bridge);
|
|
1284
|
-
expect(queue.getMaxConcurrency()).toBe(5);
|
|
1285
|
-
expect(bridge.sendNotification).toHaveBeenCalledWith("notifications/claude/channel/concurrency", expect.objectContaining({ maxConcurrency: 5, active: 0, queued: 0 }));
|
|
1286
|
-
});
|
|
1287
|
-
it("reports the clamped limit, so the interface shows what took effect", async () => {
|
|
1288
|
-
const queue = new TaskQueue(1);
|
|
1289
|
-
const bridge = fakeConcurrencyBridge();
|
|
1290
|
-
await handleSetConcurrency({ maxConcurrency: 100_000 }, queue, bridge);
|
|
1291
|
-
expect(queue.getMaxConcurrency()).toBe(64);
|
|
1292
|
-
expect(bridge.sendNotification).toHaveBeenCalledWith("notifications/claude/channel/concurrency", expect.objectContaining({ maxConcurrency: 64 }));
|
|
1293
|
-
});
|
|
1294
|
-
it("keeps the current limit when asked for something that is not a number", async () => {
|
|
1295
|
-
const queue = new TaskQueue(3);
|
|
1296
|
-
const bridge = fakeConcurrencyBridge();
|
|
1297
|
-
await handleSetConcurrency({ maxConcurrency: "lots" }, queue, bridge);
|
|
1298
|
-
expect(queue.getMaxConcurrency()).toBe(3);
|
|
1299
|
-
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('asking for "lots"'));
|
|
1300
|
-
});
|
|
1301
|
-
it("still answers a rejected value, rather than leaving the control hanging", async () => {
|
|
1302
|
-
const queue = new TaskQueue(3);
|
|
1303
|
-
const bridge = fakeConcurrencyBridge();
|
|
1304
|
-
await handleSetConcurrency({}, queue, bridge);
|
|
1305
|
-
// The interface moved a control and is waiting to see where it landed;
|
|
1306
|
-
// silence would leave it showing a limit this gateway never adopted.
|
|
1307
|
-
expect(bridge.sendNotification).toHaveBeenCalledWith("notifications/claude/channel/concurrency", expect.objectContaining({ maxConcurrency: 3 }));
|
|
1308
|
-
});
|
|
1309
|
-
it("reports what the queue is doing under the new limit", async () => {
|
|
1310
|
-
const queue = new TaskQueue(1);
|
|
1311
|
-
const bridge = fakeConcurrencyBridge();
|
|
1312
|
-
let release;
|
|
1313
|
-
const held = new Promise((resolve) => { release = resolve; });
|
|
1314
|
-
const runs = [
|
|
1315
|
-
queue.run(async () => { await held; }),
|
|
1316
|
-
queue.run(async () => { await held; }),
|
|
1317
|
-
queue.run(async () => { await held; }),
|
|
1318
|
-
];
|
|
1319
|
-
await handleSetConcurrency({ maxConcurrency: 2 }, queue, bridge);
|
|
1320
|
-
expect(bridge.sendNotification).toHaveBeenCalledWith("notifications/claude/channel/concurrency", expect.objectContaining({ maxConcurrency: 2, active: 2, queued: 1 }));
|
|
1321
|
-
release();
|
|
1322
|
-
await Promise.all(runs);
|
|
1323
|
-
});
|
|
1324
|
-
it("answers even when applying the change throws", async () => {
|
|
1325
|
-
// "Always answered" is the design; it must not depend on the change
|
|
1326
|
-
// itself going well, or the interface is left showing a limit nothing
|
|
1327
|
-
// adopted precisely when something has gone wrong.
|
|
1328
|
-
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
|
|
1329
|
-
const queue = new TaskQueue(3);
|
|
1330
|
-
const bridge = fakeConcurrencyBridge();
|
|
1331
|
-
vi.spyOn(queue, "setMaxConcurrency").mockImplementation(() => {
|
|
1332
|
-
throw new Error("queue is wedged");
|
|
1333
|
-
});
|
|
1334
|
-
await expect(handleSetConcurrency({ maxConcurrency: 5 }, queue, bridge)).rejects.toThrow("queue is wedged");
|
|
1335
|
-
expect(bridge.sendNotification).toHaveBeenCalledWith("notifications/claude/channel/concurrency", expect.objectContaining({ maxConcurrency: 3 }));
|
|
1336
|
-
errorSpy.mockRestore();
|
|
1337
|
-
});
|
|
1338
|
-
it("applies the limit even with no bridge to report it to", async () => {
|
|
1339
|
-
const queue = new TaskQueue(1);
|
|
1340
|
-
await handleSetConcurrency({ maxConcurrency: 6 }, queue);
|
|
1341
|
-
expect(queue.getMaxConcurrency()).toBe(6);
|
|
1342
|
-
});
|
|
1343
|
-
});
|
|
1344
|
-
describe("runTurnForTask", () => {
|
|
1345
|
-
beforeEach(() => {
|
|
1346
|
-
resetTaskTurns();
|
|
1347
|
-
});
|
|
1348
|
-
it("holds a second message on a chat until the first turn has finished", async () => {
|
|
1349
|
-
// A session takes one turn at a time, and agentrq reuses a chat's id as
|
|
1350
|
-
// the task id — so two messages to one chat are two deliveries of one
|
|
1351
|
-
// task, and running them at once puts two prompts on one session.
|
|
1352
|
-
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
|
|
1353
|
-
const events = [];
|
|
1354
|
-
let releaseFirst;
|
|
1355
|
-
const firstHeld = new Promise((resolve) => { releaseFirst = resolve; });
|
|
1356
|
-
const first = runTurnForTask("T-Chat", async () => {
|
|
1357
|
-
events.push("first:start");
|
|
1358
|
-
await firstHeld;
|
|
1359
|
-
events.push("first:end");
|
|
1360
|
-
});
|
|
1361
|
-
const second = runTurnForTask("T-Chat", async () => {
|
|
1362
|
-
events.push("second:start");
|
|
1363
|
-
});
|
|
1364
|
-
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
1365
|
-
expect(events).toEqual(["first:start"]);
|
|
1366
|
-
releaseFirst();
|
|
1367
|
-
await Promise.all([first, second]);
|
|
1368
|
-
expect(events).toEqual(["first:start", "first:end", "second:start"]);
|
|
1369
|
-
errorSpy.mockRestore();
|
|
1370
|
-
});
|
|
1371
|
-
it("lets a second message through after the first turn failed", async () => {
|
|
1372
|
-
// Losing it would lose what someone typed, and the first message erroring
|
|
1373
|
-
// is no reason the agent should never hear the second.
|
|
1374
|
-
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
|
|
1375
|
-
const ran = [];
|
|
1376
|
-
const first = runTurnForTask("T-Fail", async () => {
|
|
1377
|
-
ran.push("first");
|
|
1378
|
-
throw new Error("agent blew up");
|
|
1379
|
-
});
|
|
1380
|
-
const second = runTurnForTask("T-Fail", async () => {
|
|
1381
|
-
ran.push("second");
|
|
1382
|
-
});
|
|
1383
|
-
await expect(first).rejects.toThrow("agent blew up");
|
|
1384
|
-
await second;
|
|
1385
|
-
expect(ran).toEqual(["first", "second"]);
|
|
1386
|
-
errorSpy.mockRestore();
|
|
1387
|
-
});
|
|
1388
|
-
it("keeps a queue of messages in the order they were sent", async () => {
|
|
1389
|
-
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
|
|
1390
|
-
const ran = [];
|
|
1391
|
-
const turns = [0, 1, 2, 3].map((n) => runTurnForTask("T-Order", async () => {
|
|
1392
|
-
await new Promise((resolve) => setTimeout(resolve, 5 - n));
|
|
1393
|
-
ran.push(n);
|
|
1394
|
-
}));
|
|
1395
|
-
await Promise.all(turns);
|
|
1396
|
-
expect(ran).toEqual([0, 1, 2, 3]);
|
|
1397
|
-
errorSpy.mockRestore();
|
|
1398
|
-
});
|
|
1399
|
-
it("never makes one chat wait on another", async () => {
|
|
1400
|
-
// Serialising per task, not globally — a shared lock would undo the whole
|
|
1401
|
-
// point of a concurrency limit above 1.
|
|
1402
|
-
const started = [];
|
|
1403
|
-
let release;
|
|
1404
|
-
const held = new Promise((resolve) => { release = resolve; });
|
|
1405
|
-
const a = runTurnForTask("T-One", async () => { started.push("a"); await held; });
|
|
1406
|
-
const b = runTurnForTask("T-Two", async () => { started.push("b"); await held; });
|
|
1407
|
-
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
1408
|
-
expect(started.sort()).toEqual(["a", "b"]);
|
|
1409
|
-
release();
|
|
1410
|
-
await Promise.all([a, b]);
|
|
1411
|
-
});
|
|
1412
|
-
it("runs a delivery with no task id straight away", async () => {
|
|
1413
|
-
let ran = false;
|
|
1414
|
-
await runTurnForTask(undefined, async () => { ran = true; });
|
|
1415
|
-
expect(ran).toBe(true);
|
|
1416
|
-
});
|
|
1417
|
-
it("forgets a task once its last turn is done, rather than growing forever", async () => {
|
|
1418
|
-
await runTurnForTask("T-Clean", async () => { });
|
|
1419
|
-
const ran = [];
|
|
1420
|
-
// A stale chain tail would make this wait on an already-settled promise
|
|
1421
|
-
// instead of starting at once; a leaked one would never be collected.
|
|
1422
|
-
await runTurnForTask("T-Clean", async () => { ran.push("second"); });
|
|
1423
|
-
expect(ran).toEqual(["second"]);
|
|
1424
|
-
});
|
|
1425
|
-
});
|
|
1426
|
-
describe("registerConcurrencyListeners", () => {
|
|
1427
|
-
let errorSpy;
|
|
1428
|
-
beforeEach(() => {
|
|
1429
|
-
errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
|
|
1430
|
-
});
|
|
1431
|
-
afterEach(() => {
|
|
1432
|
-
errorSpy.mockRestore();
|
|
1433
|
-
});
|
|
1434
|
-
const listeningBridge = () => {
|
|
1435
|
-
const bridge = new EventEmitter();
|
|
1436
|
-
bridge.sendNotification = vi.fn().mockResolvedValue(undefined);
|
|
1437
|
-
return bridge;
|
|
1438
|
-
};
|
|
1439
|
-
const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
|
|
1440
|
-
it("applies a limit the workspace pushes while the gateway is running", async () => {
|
|
1441
|
-
const bridge = listeningBridge();
|
|
1442
|
-
const queue = new TaskQueue(1);
|
|
1443
|
-
registerConcurrencyListeners(bridge, queue);
|
|
1444
|
-
bridge.emit("setConcurrency", { maxConcurrency: 5 });
|
|
1445
|
-
await settle();
|
|
1446
|
-
expect(queue.getMaxConcurrency()).toBe(5);
|
|
1447
|
-
expect(bridge.sendNotification).toHaveBeenCalledWith("notifications/claude/channel/concurrency", expect.objectContaining({ maxConcurrency: 5 }));
|
|
1448
|
-
});
|
|
1449
|
-
it("re-reports the limit on reconnect, which the workspace has just forgotten", async () => {
|
|
1450
|
-
const bridge = listeningBridge();
|
|
1451
|
-
const queue = new TaskQueue(1);
|
|
1452
|
-
registerConcurrencyListeners(bridge, queue);
|
|
1453
|
-
bridge.emit("setConcurrency", { maxConcurrency: 7 });
|
|
1454
|
-
await settle();
|
|
1455
|
-
bridge.sendNotification.mockClear();
|
|
1456
|
-
bridge.emit("reconnected");
|
|
1457
|
-
await settle();
|
|
1458
|
-
// The limit in force, not the one the gateway booted with.
|
|
1459
|
-
expect(bridge.sendNotification).toHaveBeenCalledWith("notifications/claude/channel/concurrency", expect.objectContaining({ maxConcurrency: 7 }));
|
|
1460
|
-
});
|
|
1461
|
-
it("logs rather than throws when applying the change goes wrong", async () => {
|
|
1462
|
-
const bridge = listeningBridge();
|
|
1463
|
-
const queue = new TaskQueue(1);
|
|
1464
|
-
vi.spyOn(queue, "setMaxConcurrency").mockImplementation(() => {
|
|
1465
|
-
throw new Error("queue is wedged");
|
|
1466
|
-
});
|
|
1467
|
-
registerConcurrencyListeners(bridge, queue);
|
|
1468
|
-
// An unhandled rejection here would be logged and swallowed by the
|
|
1469
|
-
// process-level net in production, which is a worse place to find out.
|
|
1470
|
-
bridge.emit("setConcurrency", { maxConcurrency: 2 });
|
|
1471
|
-
await settle();
|
|
1472
|
-
expect(errorSpy).toHaveBeenCalledWith("[bridge] Error handling concurrency change:", expect.any(Error));
|
|
1473
|
-
});
|
|
1474
|
-
});
|
|
1475
|
-
describe("reportConcurrency", () => {
|
|
1476
|
-
beforeEach(() => resetConcurrencyReports());
|
|
1477
|
-
afterEach(() => resetConcurrencyReports());
|
|
1478
|
-
/** A bridge whose sends finish only when the test says so. */
|
|
1479
|
-
const heldBridge = () => {
|
|
1480
|
-
const releases = [];
|
|
1481
|
-
const sendNotification = vi.fn(() => new Promise((resolve) => { releases.push(resolve); }));
|
|
1482
|
-
return { bridge: { sendNotification }, sendNotification, releases };
|
|
1483
|
-
};
|
|
1484
|
-
it("never puts two reports on the wire at once", async () => {
|
|
1485
|
-
// Each report is its own POST and nothing sequences them, so two in
|
|
1486
|
-
// flight can be processed in either order — and the workspace would then
|
|
1487
|
-
// show whichever landed last rather than whichever is true.
|
|
1488
|
-
const { bridge, sendNotification, releases } = heldBridge();
|
|
1489
|
-
const queue = new TaskQueue(4);
|
|
1490
|
-
void reportConcurrency(bridge, queue);
|
|
1491
|
-
void reportConcurrency(bridge, queue);
|
|
1492
|
-
void reportConcurrency(bridge, queue);
|
|
1493
|
-
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
1494
|
-
// The second and third waited for the first rather than racing it.
|
|
1495
|
-
expect(sendNotification).toHaveBeenCalledTimes(1);
|
|
1496
|
-
releases[0]();
|
|
1497
|
-
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
1498
|
-
expect(sendNotification).toHaveBeenCalledTimes(2);
|
|
1499
|
-
releases[1]();
|
|
1500
|
-
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
1501
|
-
// Three asks, two reports: the ones that piled up became one.
|
|
1502
|
-
expect(sendNotification).toHaveBeenCalledTimes(2);
|
|
1503
|
-
});
|
|
1504
|
-
it("makes the report that follows a burst describe the queue now", async () => {
|
|
1505
|
-
// A collapsed report is worth sending only because it is current; one
|
|
1506
|
-
// carrying the state at the moment it was asked for would be a stale
|
|
1507
|
-
// number arriving late, which is the thing being fixed.
|
|
1508
|
-
const { bridge, sendNotification, releases } = heldBridge();
|
|
1509
|
-
// Wired to the bridge, so a task starting is what asks for the report.
|
|
1510
|
-
const queue = createTaskQueue(4, bridge);
|
|
1511
|
-
void reportConcurrency(bridge, queue);
|
|
1512
|
-
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
1513
|
-
expect(sendNotification).toHaveBeenLastCalledWith("notifications/claude/channel/concurrency", expect.objectContaining({ active: 0, queued: 0 }));
|
|
1514
|
-
// The numbers move while the first report is still flying.
|
|
1515
|
-
let release;
|
|
1516
|
-
const held = new Promise((resolve) => { release = resolve; });
|
|
1517
|
-
const running = queue.run(() => held);
|
|
1518
|
-
releases[0]();
|
|
1519
|
-
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
1520
|
-
expect(sendNotification).toHaveBeenLastCalledWith("notifications/claude/channel/concurrency", expect.objectContaining({ active: 1, queued: 0 }));
|
|
1521
|
-
release();
|
|
1522
|
-
releases.slice(1).forEach((r) => r());
|
|
1523
|
-
await running;
|
|
1524
|
-
});
|
|
1525
|
-
it("resolves only once the workspace has been told", async () => {
|
|
1526
|
-
// handleSetConcurrency awaits this to make "always answered" true, so it
|
|
1527
|
-
// must not resolve on the strength of somebody else's report.
|
|
1528
|
-
const { bridge, sendNotification, releases } = heldBridge();
|
|
1529
|
-
const queue = new TaskQueue(4);
|
|
1530
|
-
void reportConcurrency(bridge, queue);
|
|
1531
|
-
let answered = false;
|
|
1532
|
-
void reportConcurrency(bridge, queue).then(() => { answered = true; });
|
|
1533
|
-
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
1534
|
-
// The first report has not even landed yet.
|
|
1535
|
-
expect(answered).toBe(false);
|
|
1536
|
-
releases[0]();
|
|
1537
|
-
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
1538
|
-
// Nor on the first one landing — the second is what it is owed.
|
|
1539
|
-
expect(answered).toBe(false);
|
|
1540
|
-
releases[1]();
|
|
1541
|
-
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
1542
|
-
expect(answered).toBe(true);
|
|
1543
|
-
expect(sendNotification).toHaveBeenCalledTimes(2);
|
|
1544
|
-
});
|
|
1545
|
-
it("describes the queue as it stands", async () => {
|
|
1546
|
-
const bridge = { sendNotification: vi.fn().mockResolvedValue(undefined) };
|
|
1547
|
-
const queue = new TaskQueue(2);
|
|
1548
|
-
let release;
|
|
1549
|
-
const held = new Promise((resolve) => { release = resolve; });
|
|
1550
|
-
const runs = [
|
|
1551
|
-
queue.run(async () => { await held; }),
|
|
1552
|
-
queue.run(async () => { await held; }),
|
|
1553
|
-
queue.run(async () => { await held; }),
|
|
1554
|
-
];
|
|
1555
|
-
await reportConcurrency(bridge, queue);
|
|
1556
|
-
expect(bridge.sendNotification).toHaveBeenCalledWith("notifications/claude/channel/concurrency", expect.objectContaining({ maxConcurrency: 2, active: 2, queued: 1 }));
|
|
1557
|
-
release();
|
|
1558
|
-
await Promise.all(runs);
|
|
1559
|
-
});
|
|
1560
|
-
});
|
|
1561
|
-
describe("getOrCreateSession", () => {
|
|
1562
|
-
beforeEach(() => {
|
|
1563
|
-
activeSessions.clear();
|
|
1564
|
-
resetIdleSession();
|
|
1565
|
-
newSessionError.value = null;
|
|
1566
|
-
newSessionHangs.value = false;
|
|
1567
|
-
});
|
|
1568
|
-
it("should spawn a new session when not cached", async () => {
|
|
1569
|
-
const mockBridge = fakeBridge();
|
|
1570
|
-
const configs = [];
|
|
1571
|
-
const agentrqConfig = { env: {} };
|
|
1572
|
-
const session = await getOrCreateSession("T-New", ["node", "agent.js"], configs, agentrqConfig, mockBridge);
|
|
1573
|
-
expect(session).toBeDefined();
|
|
1574
|
-
expect(session.sessionId).toBe("test-sess-123");
|
|
1575
|
-
expect(activeSessions.has("T-New")).toBe(true);
|
|
1576
|
-
});
|
|
1577
|
-
it("files a session opened with no task under the idle key", async () => {
|
|
1578
|
-
// This is the session the gateway opens at startup so a workspace can say
|
|
1579
|
-
// what its agent offers before any work arrives.
|
|
1580
|
-
const mockBridge = fakeBridge();
|
|
1581
|
-
const session = await getOrCreateSession(undefined, ["node", "agent.js"], [], { env: {} }, mockBridge);
|
|
1582
|
-
expect(session).toBeDefined();
|
|
1583
|
-
expect(activeSessions.has(IDLE_SESSION_KEY)).toBe(true);
|
|
1584
|
-
});
|
|
1585
|
-
it("gives two deliveries of one task a single agent, not one each", async () => {
|
|
1586
|
-
// activeSessions only learns about a session once the agent has spawned,
|
|
1587
|
-
// handshaken and opened it. Two deliveries inside that window both missed
|
|
1588
|
-
// the cache and both spawned — two processes on one task, and only the
|
|
1589
|
-
// second reachable afterwards, so the first could never be closed.
|
|
1590
|
-
const mockBridge = fakeBridge();
|
|
1591
|
-
spawnedAgents.length = 0;
|
|
1592
|
-
const [first, second] = await Promise.all([
|
|
1593
|
-
getOrCreateSession("T-Dup", ["node", "agent.js"], [], { env: {} }, mockBridge),
|
|
1594
|
-
getOrCreateSession("T-Dup", ["node", "agent.js"], [], { env: {} }, mockBridge),
|
|
1595
|
-
]);
|
|
1596
|
-
expect(spawnedAgents.length).toBe(1);
|
|
1597
|
-
expect(second).toBe(first);
|
|
1598
|
-
expect(activeSessions.size).toBe(1);
|
|
1599
|
-
});
|
|
1600
|
-
it("holds a crowd of simultaneous deliveries to one agent", async () => {
|
|
1601
|
-
const mockBridge = fakeBridge();
|
|
1602
|
-
spawnedAgents.length = 0;
|
|
1603
|
-
const sessions = await Promise.all(Array.from({ length: 8 }, () => getOrCreateSession("T-Crowd", ["node", "agent.js"], [], { env: {} }, mockBridge)));
|
|
1604
|
-
expect(spawnedAgents.length).toBe(1);
|
|
1605
|
-
expect(new Set(sessions).size).toBe(1);
|
|
1606
|
-
});
|
|
1607
|
-
it("still opens separate agents for separate tasks at the same time", async () => {
|
|
1608
|
-
// The guard is per task, not a lock on opening sessions at all — a raised
|
|
1609
|
-
// concurrency limit would be worth nothing if it serialised every spawn.
|
|
1610
|
-
const mockBridge = fakeBridge();
|
|
1611
|
-
spawnedAgents.length = 0;
|
|
1612
|
-
const [a, b, c] = await Promise.all([
|
|
1613
|
-
getOrCreateSession("T-A", ["node", "agent.js"], [], { env: {} }, mockBridge),
|
|
1614
|
-
getOrCreateSession("T-B", ["node", "agent.js"], [], { env: {} }, mockBridge),
|
|
1615
|
-
getOrCreateSession("T-C", ["node", "agent.js"], [], { env: {} }, mockBridge),
|
|
1616
|
-
]);
|
|
1617
|
-
expect(spawnedAgents.length).toBe(3);
|
|
1618
|
-
expect(new Set([a, b, c]).size).toBe(3);
|
|
1619
|
-
expect(activeSessions.size).toBe(3);
|
|
1620
|
-
});
|
|
1621
|
-
it("serves a later delivery from the cache, not from a spent attempt", async () => {
|
|
1622
|
-
const mockBridge = fakeBridge();
|
|
1623
|
-
spawnedAgents.length = 0;
|
|
1624
|
-
const first = await getOrCreateSession("T-Later", ["node", "agent.js"], [], { env: {} }, mockBridge);
|
|
1625
|
-
const second = await getOrCreateSession("T-Later", ["node", "agent.js"], [], { env: {} }, mockBridge);
|
|
1626
|
-
expect(second).toBe(first);
|
|
1627
|
-
expect(spawnedAgents.length).toBe(1);
|
|
1628
|
-
});
|
|
1629
|
-
it("lets a task try again after the attempt it waited on failed", async () => {
|
|
1630
|
-
// A failed attempt must not leave the key wedged, or one bad spawn would
|
|
1631
|
-
// cost the task every later delivery too.
|
|
1632
|
-
const mockBridge = fakeBridge();
|
|
1633
|
-
newSessionError.value = new Error("agent said no");
|
|
1634
|
-
await expect(getOrCreateSession("T-Retry", ["node", "agent.js"], [], { env: {} }, mockBridge)).rejects.toThrow("agent said no");
|
|
1635
|
-
newSessionError.value = null;
|
|
1636
|
-
const recovered = await getOrCreateSession("T-Retry", ["node", "agent.js"], [], { env: {} }, mockBridge);
|
|
1637
|
-
expect(recovered).toBeDefined();
|
|
1638
|
-
expect(activeSessions.has("T-Retry")).toBe(true);
|
|
1639
|
-
});
|
|
1640
|
-
it("fails both waiters together rather than spawning a second agent to retry", async () => {
|
|
1641
|
-
const mockBridge = fakeBridge();
|
|
1642
|
-
newSessionError.value = new Error("agent said no");
|
|
1643
|
-
spawnedAgents.length = 0;
|
|
1644
|
-
const results = await Promise.allSettled([
|
|
1645
|
-
getOrCreateSession("T-BothFail", ["node", "agent.js"], [], { env: {} }, mockBridge),
|
|
1646
|
-
getOrCreateSession("T-BothFail", ["node", "agent.js"], [], { env: {} }, mockBridge),
|
|
1647
|
-
]);
|
|
1648
|
-
expect(results.every((r) => r.status === "rejected")).toBe(true);
|
|
1649
|
-
expect(spawnedAgents.length).toBe(1);
|
|
1650
|
-
newSessionError.value = null;
|
|
1651
|
-
});
|
|
1652
|
-
it("hands the startup session to the first task rather than opening a second", async () => {
|
|
1653
|
-
// Sessions are keyed by task, so without this the first real task would
|
|
1654
|
-
// spawn a second agent alongside the one already running.
|
|
1655
|
-
const mockBridge = fakeBridge();
|
|
1656
|
-
const idle = await getOrCreateSession(undefined, ["node", "agent.js"], [], { env: {} }, mockBridge);
|
|
1657
|
-
const forTask = await getOrCreateSession("T-First", ["node", "agent.js"], [], { env: {} }, mockBridge);
|
|
1658
|
-
expect(forTask).toBe(idle);
|
|
1659
|
-
expect(activeSessions.has("T-First")).toBe(true);
|
|
1660
|
-
expect(activeSessions.has(IDLE_SESSION_KEY)).toBe(false);
|
|
1661
|
-
expect(activeSessions.size).toBe(1);
|
|
1662
|
-
});
|
|
1663
|
-
it("attributes what an adopted session reports to the task that took it", async () => {
|
|
1664
|
-
// Everything the session says afterwards — models, commands, replies —
|
|
1665
|
-
// belongs to that task, so the task id has to follow the adoption.
|
|
1666
|
-
const mockBridge = fakeBridge();
|
|
1667
|
-
const idle = await getOrCreateSession(undefined, ["node", "agent.js"], [], { env: {} }, mockBridge);
|
|
1668
|
-
mockBridge.sendNotification.mockClear();
|
|
1669
|
-
await getOrCreateSession("T-Owner", ["node", "agent.js"], [], { env: {} }, mockBridge);
|
|
1670
|
-
await idle.acpClient.sendCommandsToWorkspace(idle.sessionId, [{ name: "init", description: "d" }]);
|
|
1671
|
-
expect(mockBridge.sendNotification).toHaveBeenCalledWith("notifications/claude/channel/commands", expect.objectContaining({ task_id: "T-Owner" }));
|
|
1672
|
-
});
|
|
1673
|
-
it("re-advertises known models with the adopted task id when taken over", async () => {
|
|
1674
|
-
const mockBridge = fakeBridge();
|
|
1675
|
-
const idle = await getOrCreateSession(undefined, ["node", "agent.js"], [], { env: {} }, mockBridge);
|
|
1676
|
-
await idle.acpClient.sendModelsToWorkspace(idle.sessionId, {
|
|
1677
|
-
configId: "model",
|
|
1678
|
-
currentModelId: "m1",
|
|
1679
|
-
models: [{ id: "m1", name: "Model 1", current: true }],
|
|
1680
|
-
});
|
|
1681
|
-
mockBridge.sendNotification.mockClear();
|
|
1682
|
-
await getOrCreateSession("T-Adopt", ["node", "agent.js"], [], { env: {} }, mockBridge);
|
|
1683
|
-
expect(mockBridge.sendNotification).toHaveBeenCalledWith("notifications/claude/channel/models", expect.objectContaining({
|
|
1684
|
-
task_id: "T-Adopt",
|
|
1685
|
-
session_id: idle.sessionId,
|
|
1686
|
-
current_model: "m1",
|
|
1687
|
-
}));
|
|
1688
|
-
});
|
|
1689
|
-
it("gives a second task its own session, having only one to hand over", async () => {
|
|
1690
|
-
const mockBridge = fakeBridge();
|
|
1691
|
-
await getOrCreateSession(undefined, ["node", "agent.js"], [], { env: {} }, mockBridge);
|
|
1692
|
-
const first = await getOrCreateSession("T-A", ["node", "agent.js"], [], { env: {} }, mockBridge);
|
|
1693
|
-
const second = await getOrCreateSession("T-B", ["node", "agent.js"], [], { env: {} }, mockBridge);
|
|
1694
|
-
expect(second).not.toBe(first);
|
|
1695
|
-
expect(activeSessions.has("T-A")).toBe(true);
|
|
1696
|
-
expect(activeSessions.has("T-B")).toBe(true);
|
|
1697
|
-
});
|
|
1698
|
-
it("opens the idle session at startup", async () => {
|
|
1699
|
-
const mockBridge = fakeBridge();
|
|
1700
|
-
await openIdleSession(["node", "agent.js"], [], { env: {} }, mockBridge);
|
|
1701
|
-
expect(activeSessions.has(IDLE_SESSION_KEY)).toBe(true);
|
|
1702
|
-
});
|
|
1703
|
-
it("never fails when the agent cannot be started", async () => {
|
|
1704
|
-
// The safety property of the whole change: a broken agent used to fail
|
|
1705
|
-
// when the first task arrived, and it still must. Failing at startup
|
|
1706
|
-
// would turn it into a gateway that will not run at all.
|
|
1707
|
-
const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => { });
|
|
1708
|
-
const mockBridge = fakeBridge();
|
|
1709
|
-
newSessionError.value = new Error("agent will not start");
|
|
1710
|
-
// Survivable: it says the gateway can carry on, and the first task retries.
|
|
1711
|
-
await expect(openIdleSession(["node", "agent.js"], [], { env: {} }, mockBridge)).resolves.toBe("unknown");
|
|
1712
|
-
expect(activeSessions.has(IDLE_SESSION_KEY)).toBe(false);
|
|
1713
|
-
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("the first task will start one"), expect.anything());
|
|
1714
|
-
consoleSpy.mockRestore();
|
|
1715
|
-
});
|
|
1716
|
-
it("reports that the gateway cannot continue when the agent is unauthenticated", async () => {
|
|
1717
|
-
// Carrying on would leave the workspace showing a live agent that fails
|
|
1718
|
-
// every task it is given, which is worse than not running at all.
|
|
1719
|
-
const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => { });
|
|
1720
|
-
const mockBridge = fakeBridge();
|
|
1721
|
-
newSessionError.value = { code: -32000, data: { authRequired: true }, message: "auth_required" };
|
|
1722
|
-
const outcome = await openIdleSession(["node", "agent.js"], [], { env: {} }, mockBridge);
|
|
1723
|
-
expect(outcome).toBe("unauthenticated");
|
|
1724
|
-
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("until it is authenticated"));
|
|
1725
|
-
expect(activeSessions.has(IDLE_SESSION_KEY)).toBe(false);
|
|
1726
|
-
// Nothing was claimed about an agent that never started.
|
|
1727
|
-
expect(mockBridge.sendNotification).not.toHaveBeenCalledWith("notifications/claude/channel/models", expect.anything());
|
|
1728
|
-
consoleSpy.mockRestore();
|
|
1729
|
-
});
|
|
1730
|
-
it("shuts down when the login itself went wrong", async () => {
|
|
1731
|
-
// A terminal login the human abandoned, a login subcommand exiting
|
|
1732
|
-
// non-zero, no usable method on a headless run: all of them come back as
|
|
1733
|
-
// AuthenticationFailed, so none of them has to be recognised by its
|
|
1734
|
-
// message. The conclusion is the same — an agent that cannot authenticate
|
|
1735
|
-
// cannot work.
|
|
1736
|
-
const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => { });
|
|
1737
|
-
const mockBridge = fakeBridge();
|
|
1738
|
-
newSessionError.value = new AuthenticationFailed(new Error('Terminal login "oauth" failed (code=1, signal=null).'));
|
|
1739
|
-
const outcome = await openIdleSession(["node", "agent.js"], [], { env: {} }, mockBridge);
|
|
1740
|
-
expect(outcome).toBe("unauthenticated");
|
|
1741
|
-
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("npx @agentrq/acp-gateway@latest --login"));
|
|
1742
|
-
consoleSpy.mockRestore();
|
|
1743
|
-
});
|
|
1744
|
-
it("tells the owner of an API-key agent to set the key, not to log in", async () => {
|
|
1745
|
-
// Plenty of agents never ask anyone to log in — they read a key from the
|
|
1746
|
-
// environment. When one of those refuses, sending its owner looking for a
|
|
1747
|
-
// login prompt that does not exist is worse than saying nothing.
|
|
1748
|
-
const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => { });
|
|
1749
|
-
const mockBridge = fakeBridge();
|
|
1750
|
-
newSessionError.value = new AuthenticationFailed(new Error("auth_required"), false);
|
|
1751
|
-
const outcome = await openIdleSession(["node", "agent.js"], [], { env: {} }, mockBridge);
|
|
1752
|
-
expect(outcome).toBe("unauthenticated");
|
|
1753
|
-
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("expecting a credential of its own"));
|
|
1754
|
-
expect(consoleSpy).not.toHaveBeenCalledWith(expect.stringContaining("--login"));
|
|
1755
|
-
consoleSpy.mockRestore();
|
|
1756
|
-
});
|
|
1757
|
-
it("gives up waiting on an agent that never opens a session", async () => {
|
|
1758
|
-
// Nothing reaches the workspace until this settles, so an agent that
|
|
1759
|
-
// spawns and then goes quiet would otherwise take the whole gateway with
|
|
1760
|
-
// it — a worse failure than the one the startup session fixes.
|
|
1761
|
-
const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => { });
|
|
1762
|
-
const mockBridge = fakeBridge();
|
|
1763
|
-
newSessionHangs.value = true;
|
|
1764
|
-
const outcome = await openIdleSession(["node", "agent.js"], [], { env: {} }, mockBridge, loginCommandFor("some-agent"), 20);
|
|
1765
|
-
expect(outcome).toBe("unknown");
|
|
1766
|
-
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("has not opened a session"));
|
|
1767
|
-
consoleSpy.mockRestore();
|
|
1768
|
-
});
|
|
1769
|
-
it("keeps running when the agent merely failed to start", async () => {
|
|
1770
|
-
// Not the same thing at all: that may have been a race, it used to fail
|
|
1771
|
-
// when the first task arrived, and it still should.
|
|
1772
|
-
const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => { });
|
|
1773
|
-
const mockBridge = fakeBridge();
|
|
1774
|
-
newSessionError.value = new Error("spawn ENOENT");
|
|
1775
|
-
const outcome = await openIdleSession(["node", "agent.js"], [], { env: {} }, mockBridge);
|
|
1776
|
-
// Survivable, so the gateway keeps running.
|
|
1777
|
-
expect(outcome).toBe("unknown");
|
|
1778
|
-
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("the first task will start one"), expect.anything());
|
|
1779
|
-
consoleSpy.mockRestore();
|
|
1780
|
-
});
|
|
1781
|
-
it("makes a task wait for a startup session still coming up, rather than starting a second agent", async () => {
|
|
1782
|
-
// Opening one can take a long time when an agent wants a human to log in,
|
|
1783
|
-
// and a task arriving in that window used to find nothing cached.
|
|
1784
|
-
const mockBridge = fakeBridge();
|
|
1785
|
-
const startup = openIdleSession(["node", "agent.js"], [], { env: {} }, mockBridge);
|
|
1786
|
-
const forTask = getOrCreateSession("T-Racer", ["node", "agent.js"], [], { env: {} }, mockBridge);
|
|
1787
|
-
await startup;
|
|
1788
|
-
const session = await forTask;
|
|
1789
|
-
expect(activeSessions.size).toBe(1);
|
|
1790
|
-
expect(activeSessions.get("T-Racer")).toBe(session);
|
|
1791
|
-
});
|
|
1792
|
-
it("should return cached session when already created", async () => {
|
|
1793
|
-
const mockBridge = fakeBridge();
|
|
1794
|
-
const configs = [];
|
|
1795
|
-
const agentrqConfig = { env: {} };
|
|
1796
|
-
const session1 = await getOrCreateSession("T-Cache", ["node", "agent.js"], configs, agentrqConfig, mockBridge);
|
|
1797
|
-
const session2 = await getOrCreateSession("T-Cache", ["node", "agent.js"], configs, agentrqConfig, mockBridge);
|
|
1798
|
-
expect(session1).toBe(session2);
|
|
1799
|
-
});
|
|
1800
|
-
it("should pass clientInfo with package name and version when initializing the ACP connection", async () => {
|
|
1801
|
-
const mockBridge = fakeBridge();
|
|
1802
|
-
const configs = [];
|
|
1803
|
-
const agentrqConfig = { env: {} };
|
|
1804
|
-
const session = await getOrCreateSession("T-ClientInfo", ["node", "agent.js"], configs, agentrqConfig, mockBridge);
|
|
1805
|
-
expect(session.connection.initialize).toHaveBeenCalledWith(expect.objectContaining({
|
|
1806
|
-
clientInfo: expect.objectContaining({
|
|
1807
|
-
name: "@agentrq/acp-gateway",
|
|
1808
|
-
version: expect.any(String),
|
|
1809
|
-
}),
|
|
1810
|
-
}));
|
|
1811
|
-
});
|
|
1812
|
-
it("should declare plan capability when initializing the ACP connection", async () => {
|
|
1813
|
-
const mockBridge = fakeBridge();
|
|
1814
|
-
const configs = [];
|
|
1815
|
-
const agentrqConfig = { env: {} };
|
|
1816
|
-
const session = await getOrCreateSession("T-Plan", ["node", "agent.js"], configs, agentrqConfig, mockBridge);
|
|
1817
|
-
expect(session.connection.initialize).toHaveBeenCalledWith(expect.objectContaining({
|
|
1818
|
-
clientCapabilities: expect.objectContaining({
|
|
1819
|
-
plan: {},
|
|
1820
|
-
}),
|
|
1821
|
-
}));
|
|
1822
|
-
});
|
|
1823
|
-
it("should declare elicitation support when initializing the ACP connection", async () => {
|
|
1824
|
-
const mockBridge = fakeBridge();
|
|
1825
|
-
const configs = [];
|
|
1826
|
-
const agentrqConfig = { env: {} };
|
|
1827
|
-
const session = await getOrCreateSession("T-Elicit", ["node", "agent.js"], configs, agentrqConfig, mockBridge);
|
|
1828
|
-
expect(session.connection.initialize).toHaveBeenCalledWith(expect.objectContaining({
|
|
1829
|
-
clientCapabilities: expect.objectContaining({
|
|
1830
|
-
elicitation: { form: {}, url: {} },
|
|
1831
|
-
}),
|
|
1832
|
-
}));
|
|
1833
|
-
});
|
|
1834
|
-
it("should declare whether it can host a terminal login", async () => {
|
|
1835
|
-
const mockBridge = fakeBridge();
|
|
1836
|
-
const session = await getOrCreateSession("T-Auth-Cap", ["node", "agent.js"], [], { env: {} }, mockBridge);
|
|
1837
|
-
expect(session.connection.initialize).toHaveBeenCalledWith(expect.objectContaining({
|
|
1838
|
-
clientCapabilities: expect.objectContaining({
|
|
1839
|
-
auth: { terminal: isInteractiveTerminal() },
|
|
1840
|
-
}),
|
|
1841
|
-
}));
|
|
1842
|
-
});
|
|
1843
|
-
it("should log in and retry when the agent refuses the session", async () => {
|
|
1844
|
-
const authenticate = vi.fn().mockResolvedValue({});
|
|
1845
|
-
const newSession = vi
|
|
1846
|
-
.fn()
|
|
1847
|
-
.mockRejectedValueOnce(Object.assign(new Error("Authentication required"), { code: AUTH_REQUIRED_CODE }))
|
|
1848
|
-
.mockResolvedValue({ sessionId: "authed-sess" });
|
|
1849
|
-
vi.mocked(acp.ClientSideConnection).mockImplementationOnce(function () {
|
|
1850
|
-
return {
|
|
1851
|
-
initialize: vi.fn().mockResolvedValue({
|
|
1852
|
-
protocolVersion: "0.1.0",
|
|
1853
|
-
authMethods: [{ id: "agent-login", name: "Agent login" }],
|
|
1854
|
-
}),
|
|
1855
|
-
newSession,
|
|
1856
|
-
authenticate,
|
|
1857
|
-
prompt: vi.fn(),
|
|
1858
|
-
};
|
|
1859
|
-
});
|
|
1860
|
-
const session = await getOrCreateSession("T-Login", ["node", "agent.js"], [], { env: {} }, fakeBridge());
|
|
1861
|
-
expect(authenticate).toHaveBeenCalledWith({ methodId: "agent-login" });
|
|
1862
|
-
expect(newSession).toHaveBeenCalledTimes(2);
|
|
1863
|
-
expect(session.sessionId).toBe("authed-sess");
|
|
1864
|
-
});
|
|
1865
|
-
it("should forward models to workspace on session creation and set model if configured", async () => {
|
|
1866
|
-
const mockBridge = fakeBridge();
|
|
1867
|
-
const setSessionConfigOption = vi.fn().mockResolvedValue({
|
|
1868
|
-
configOptions: [
|
|
1869
|
-
{
|
|
1870
|
-
id: "model",
|
|
1871
|
-
name: "Model",
|
|
1872
|
-
type: "select",
|
|
1873
|
-
currentValue: "gpt-4o",
|
|
1874
|
-
options: [
|
|
1875
|
-
{ value: "gpt-4", name: "GPT-4" },
|
|
1876
|
-
{ value: "gpt-4o", name: "GPT-4o" },
|
|
1877
|
-
],
|
|
1878
|
-
},
|
|
1879
|
-
],
|
|
1880
|
-
});
|
|
1881
|
-
vi.mocked(acp.ClientSideConnection).mockImplementationOnce(function () {
|
|
1882
|
-
return {
|
|
1883
|
-
initialize: vi.fn().mockResolvedValue({ protocolVersion: "0.1.0" }),
|
|
1884
|
-
newSession: vi.fn().mockResolvedValue({
|
|
1885
|
-
sessionId: "model-sess",
|
|
1886
|
-
configOptions: [
|
|
1887
|
-
{
|
|
1888
|
-
id: "model",
|
|
1889
|
-
name: "Model",
|
|
1890
|
-
type: "select",
|
|
1891
|
-
currentValue: "gpt-4",
|
|
1892
|
-
options: [
|
|
1893
|
-
{ value: "gpt-4", name: "GPT-4" },
|
|
1894
|
-
{ value: "gpt-4o", name: "GPT-4o" },
|
|
1895
|
-
],
|
|
1896
|
-
},
|
|
1897
|
-
],
|
|
1898
|
-
}),
|
|
1899
|
-
setSessionConfigOption,
|
|
1900
|
-
prompt: vi.fn(),
|
|
1901
|
-
};
|
|
1902
|
-
});
|
|
1903
|
-
modelConfig.modelId = "gpt-4o";
|
|
1904
|
-
const session = await getOrCreateSession("T-Model", ["node", "agent.js"], [], { env: {} }, mockBridge);
|
|
1905
|
-
expect(setSessionConfigOption).toHaveBeenCalledWith({
|
|
1906
|
-
sessionId: "model-sess",
|
|
1907
|
-
configId: "model",
|
|
1908
|
-
value: "gpt-4o",
|
|
1909
|
-
});
|
|
1910
|
-
expect(mockBridge.sendNotification).toHaveBeenCalledWith("notifications/claude/channel/models", expect.objectContaining({
|
|
1911
|
-
task_id: "T-Model",
|
|
1912
|
-
session_id: "model-sess",
|
|
1913
|
-
current_model: "gpt-4o",
|
|
1914
|
-
}));
|
|
1915
|
-
modelConfig.modelId = undefined;
|
|
1916
|
-
});
|
|
1917
|
-
it("should drop the cached session when the agent process dies", async () => {
|
|
1918
|
-
const mockBridge = fakeBridge();
|
|
1919
|
-
await getOrCreateSession("T-Exit", ["node", "agent.js"], [], { env: {} }, mockBridge);
|
|
1920
|
-
expect(activeSessions.has("T-Exit")).toBe(true);
|
|
1921
|
-
spawnedAgents[spawnedAgents.length - 1].emit("exit", 1, null);
|
|
1922
|
-
expect(activeSessions.has("T-Exit")).toBe(false);
|
|
1923
|
-
});
|
|
1924
|
-
});
|
|
1925
66
|
describe("openAgentConnection", () => {
|
|
1926
67
|
beforeEach(() => {
|
|
1927
68
|
spawnedAgents.length = 0;
|
|
1928
69
|
});
|
|
1929
|
-
it("should pass clientInfo and
|
|
70
|
+
it("should pass clientInfo and the url elicitation capability in initialize handshake", async () => {
|
|
1930
71
|
const initSpy = vi.fn().mockResolvedValue({
|
|
1931
72
|
protocolVersion: "0.1.0",
|
|
1932
73
|
});
|
|
@@ -1937,7 +78,6 @@ describe("index", () => {
|
|
|
1937
78
|
});
|
|
1938
79
|
await openAgentConnection({
|
|
1939
80
|
acpCmdArgs: ["node", "agent.js"],
|
|
1940
|
-
mcpBridge: fakeBridge(),
|
|
1941
81
|
label: "init-test",
|
|
1942
82
|
});
|
|
1943
83
|
expect(initSpy).toHaveBeenCalledWith(expect.objectContaining({
|
|
@@ -1946,7 +86,7 @@ describe("index", () => {
|
|
|
1946
86
|
version: expect.any(String),
|
|
1947
87
|
}),
|
|
1948
88
|
clientCapabilities: expect.objectContaining({
|
|
1949
|
-
|
|
89
|
+
elicitation: { url: {} },
|
|
1950
90
|
}),
|
|
1951
91
|
}));
|
|
1952
92
|
});
|
|
@@ -1954,7 +94,6 @@ describe("index", () => {
|
|
|
1954
94
|
const { spawn } = await import("node:child_process");
|
|
1955
95
|
await openAgentConnection({
|
|
1956
96
|
acpCmdArgs: ["node", "agent.js"],
|
|
1957
|
-
mcpBridge: fakeBridge(),
|
|
1958
97
|
label: "spawn-plain",
|
|
1959
98
|
});
|
|
1960
99
|
expect(vi.mocked(spawn)).toHaveBeenLastCalledWith("node", ["agent.js"], expect.objectContaining({ shell: false }));
|
|
@@ -1972,7 +111,6 @@ describe("index", () => {
|
|
|
1972
111
|
try {
|
|
1973
112
|
await openAgentConnection({
|
|
1974
113
|
acpCmdArgs: ["npx", "-y", "@zed-industries/codex-acp"],
|
|
1975
|
-
mcpBridge: fakeBridge(),
|
|
1976
114
|
label: "spawn-windows",
|
|
1977
115
|
});
|
|
1978
116
|
}
|
|
@@ -1993,18 +131,16 @@ describe("index", () => {
|
|
|
1993
131
|
}),
|
|
1994
132
|
};
|
|
1995
133
|
});
|
|
1996
|
-
const onExit = vi.fn();
|
|
1997
134
|
const agent = await openAgentConnection({
|
|
1998
135
|
acpCmdArgs: ["node", "agent.js"],
|
|
1999
|
-
mcpBridge: fakeBridge(),
|
|
2000
136
|
label: "login",
|
|
2001
|
-
onExit,
|
|
2002
137
|
});
|
|
138
|
+
const dispose = vi.spyOn(agent.acpClient, "dispose");
|
|
2003
139
|
expect(agent.initResult.authMethods).toHaveLength(1);
|
|
2004
140
|
expect(errorSpy.mock.calls.flat().join("\n")).toContain("Agent login (agent-login)");
|
|
2005
141
|
agent.process.emit("error", new Error("spawn failed"));
|
|
2006
142
|
agent.process.stdin.emit("error", new Error("EPIPE"));
|
|
2007
|
-
expect(
|
|
143
|
+
expect(dispose).toHaveBeenCalledTimes(1);
|
|
2008
144
|
errorSpy.mockRestore();
|
|
2009
145
|
});
|
|
2010
146
|
});
|
|
@@ -2022,7 +158,6 @@ describe("index", () => {
|
|
|
2022
158
|
mockInit();
|
|
2023
159
|
const agent = await openAgentConnection({
|
|
2024
160
|
acpCmdArgs: ["node", "agent.js"],
|
|
2025
|
-
mcpBridge: fakeBridge(),
|
|
2026
161
|
label: "list-models",
|
|
2027
162
|
});
|
|
2028
163
|
agent.process.stderr.write("I1002 Starting AGY ACP Server...\n");
|
|
@@ -2038,7 +173,6 @@ describe("index", () => {
|
|
|
2038
173
|
mockInit();
|
|
2039
174
|
const agent = await openAgentConnection({
|
|
2040
175
|
acpCmdArgs: ["node", "agent.js"],
|
|
2041
|
-
mcpBridge: fakeBridge(),
|
|
2042
176
|
label: "task t1",
|
|
2043
177
|
});
|
|
2044
178
|
agent.process.stderr.write("E1002 credentials missing\n");
|
|
@@ -2056,7 +190,6 @@ describe("index", () => {
|
|
|
2056
190
|
mockInit();
|
|
2057
191
|
const agent = await openAgentConnection({
|
|
2058
192
|
acpCmdArgs: ["node", "agent.js"],
|
|
2059
|
-
mcpBridge: fakeBridge(),
|
|
2060
193
|
label: "task t1",
|
|
2061
194
|
});
|
|
2062
195
|
agent.process.stderr.write("I1002 hello\n");
|
|
@@ -2080,7 +213,7 @@ describe("index", () => {
|
|
|
2080
213
|
}),
|
|
2081
214
|
};
|
|
2082
215
|
});
|
|
2083
|
-
await expect(openAgentConnection({ acpCmdArgs: ["node", "agent.js"],
|
|
216
|
+
await expect(openAgentConnection({ acpCmdArgs: ["node", "agent.js"], label: "list-models" })).rejects.toThrow("ACP connection closed");
|
|
2084
217
|
expect(errorSpy).toHaveBeenCalledWith("[acp] The agent's last output:\nE1002 fatal: no credentials");
|
|
2085
218
|
// Already shown, so a later failed exit does not repeat it.
|
|
2086
219
|
errorSpy.mockClear();
|
|
@@ -2142,6 +275,45 @@ describe("index", () => {
|
|
|
2142
275
|
await expect(createSessionWithAuth(connection, {}, auth)).rejects.toThrow("cwd does not exist");
|
|
2143
276
|
expect(connection.authenticate).not.toHaveBeenCalled();
|
|
2144
277
|
});
|
|
278
|
+
const authRequired = () => Object.assign(new Error("Authentication required"), { code: AUTH_REQUIRED_CODE });
|
|
279
|
+
it("should log in and retry when the agent refuses without a login", async () => {
|
|
280
|
+
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
|
|
281
|
+
const connection = {
|
|
282
|
+
newSession: vi.fn().mockRejectedValueOnce(authRequired()).mockResolvedValue({ sessionId: "s2" }),
|
|
283
|
+
authenticate: vi.fn().mockResolvedValue({}),
|
|
284
|
+
};
|
|
285
|
+
const result = await createSessionWithAuth(connection, {}, auth);
|
|
286
|
+
expect(result.sessionId).toBe("s2");
|
|
287
|
+
expect(connection.authenticate).toHaveBeenCalledWith({ methodId: "agent-login" });
|
|
288
|
+
expect(errorSpy).toHaveBeenCalledWith("[auth] Agent requires authentication before a session can start.");
|
|
289
|
+
errorSpy.mockRestore();
|
|
290
|
+
});
|
|
291
|
+
it("should report a login that does not help as an authentication failure", async () => {
|
|
292
|
+
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
|
|
293
|
+
const connection = {
|
|
294
|
+
newSession: vi.fn().mockRejectedValue(authRequired()),
|
|
295
|
+
authenticate: vi.fn().mockResolvedValue({}),
|
|
296
|
+
};
|
|
297
|
+
const failure = await createSessionWithAuth(connection, {}, auth).catch((e) => e);
|
|
298
|
+
expect(failure).toBeInstanceOf(AuthenticationFailed);
|
|
299
|
+
expect(failure).toMatchObject({ name: "AuthenticationFailed", hasLogin: true });
|
|
300
|
+
expect(failure.message).toBe("Authentication required");
|
|
301
|
+
errorSpy.mockRestore();
|
|
302
|
+
});
|
|
303
|
+
it("should say when the agent offers no login at all", async () => {
|
|
304
|
+
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
|
|
305
|
+
const connection = {
|
|
306
|
+
newSession: vi.fn().mockRejectedValue(authRequired()),
|
|
307
|
+
authenticate: vi.fn(),
|
|
308
|
+
};
|
|
309
|
+
const failure = await createSessionWithAuth(connection, {}, { ...auth, methods: [] }).catch((e) => e);
|
|
310
|
+
expect(failure).toBeInstanceOf(AuthenticationFailed);
|
|
311
|
+
expect(failure.hasLogin).toBe(false);
|
|
312
|
+
errorSpy.mockRestore();
|
|
313
|
+
});
|
|
314
|
+
it("should describe a failure that is not an Error", () => {
|
|
315
|
+
expect(new AuthenticationFailed("no").message).toBe("no");
|
|
316
|
+
});
|
|
2145
317
|
});
|
|
2146
318
|
describe("parseGatewayArgs", () => {
|
|
2147
319
|
it("should default to bridging tasks with a concurrency of 1", () => {
|
|
@@ -2307,21 +479,19 @@ describe("index", () => {
|
|
|
2307
479
|
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("--mcp-json provided without a path"));
|
|
2308
480
|
errorSpy.mockRestore();
|
|
2309
481
|
});
|
|
2310
|
-
it("leaves
|
|
2311
|
-
|
|
2312
|
-
expect(options.acpVersion).toBeUndefined();
|
|
2313
|
-
expect(options.acpUrl).toBeUndefined();
|
|
482
|
+
it("leaves --acp-url unset unless it is given", () => {
|
|
483
|
+
expect(parseGatewayArgs(["--agent", "gemini"]).acpUrl).toBeUndefined();
|
|
2314
484
|
});
|
|
2315
|
-
it
|
|
2316
|
-
expect(parseGatewayArgs(["--acp-version",
|
|
485
|
+
it("still accepts --acp-version 1, from launch scripts written before v1 was the only mode", () => {
|
|
486
|
+
expect(parseGatewayArgs(["--acp-version", "1", "--acp-url", "wss://x/api/acp/v1", "gemini"])).toMatchObject({ command: "run", acpUrl: "wss://x/api/acp/v1", rest: ["gemini"] });
|
|
2317
487
|
});
|
|
2318
|
-
it.each([["3"], ["v1"], [undefined]])("refuses --acp-version %s", (value) => {
|
|
488
|
+
it.each([["2"], ["3"], ["v1"], [undefined]])("refuses --acp-version %s", (value) => {
|
|
2319
489
|
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
|
|
2320
490
|
const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {
|
|
2321
491
|
throw new Error("exit");
|
|
2322
492
|
}));
|
|
2323
493
|
expect(() => parseGatewayArgs(value ? ["--acp-version", value] : ["--acp-version"])).toThrow("exit");
|
|
2324
|
-
expect(errorSpy).toHaveBeenCalledWith("[acp-gateway] --acp-version must be 1
|
|
494
|
+
expect(errorSpy).toHaveBeenCalledWith("[acp-gateway] --acp-version must be 1, the only version supported");
|
|
2325
495
|
expect(exitSpy).toHaveBeenCalledWith(1);
|
|
2326
496
|
errorSpy.mockRestore();
|
|
2327
497
|
exitSpy.mockRestore();
|
|
@@ -2733,35 +903,6 @@ describe("index", () => {
|
|
|
2733
903
|
expect(resolved.command.slice(1)).toEqual(["-y", "@google/gemini-cli@0.58.0", "--acp"]);
|
|
2734
904
|
expect(resolved.env).toEqual({ K: "v" });
|
|
2735
905
|
});
|
|
2736
|
-
it("reports who the registry says the agent is, before it has been started", async () => {
|
|
2737
|
-
// This is the only name available while the gateway is idle: the agent
|
|
2738
|
-
// itself does not speak until a task starts it, and until then a
|
|
2739
|
-
// workspace can only see the gateway.
|
|
2740
|
-
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
|
|
2741
|
-
const fetchImpl = vi.fn().mockResolvedValue({
|
|
2742
|
-
ok: true,
|
|
2743
|
-
json: async () => ({
|
|
2744
|
-
version: "1.0.0",
|
|
2745
|
-
agents: [
|
|
2746
|
-
{
|
|
2747
|
-
id: "antigravity-acp",
|
|
2748
|
-
name: "Google Antigravity",
|
|
2749
|
-
version: "1.1.1",
|
|
2750
|
-
description: "…",
|
|
2751
|
-
distribution: { npx: { package: "antigravity-acp@1.1.1", args: [] } },
|
|
2752
|
-
},
|
|
2753
|
-
],
|
|
2754
|
-
}),
|
|
2755
|
-
});
|
|
2756
|
-
const resolved = await resolveAgentCommand(options({ agentId: "antigravity-acp" }), [], fetchImpl);
|
|
2757
|
-
errorSpy.mockRestore();
|
|
2758
|
-
expect(resolved.identity).toEqual({ name: "Google Antigravity", version: "1.1.1" });
|
|
2759
|
-
});
|
|
2760
|
-
it("has no identity to report for a command given after --", async () => {
|
|
2761
|
-
// Nothing named it, so there is nothing to say until the agent does.
|
|
2762
|
-
const resolved = await resolveAgentCommand(options(), ["gemini", "--acp"], vi.fn());
|
|
2763
|
-
expect(resolved.identity).toBeUndefined();
|
|
2764
|
-
});
|
|
2765
906
|
it("should surface a registry id that does not exist", async () => {
|
|
2766
907
|
const fetchImpl = vi.fn().mockResolvedValue({
|
|
2767
908
|
ok: true,
|
|
@@ -2795,41 +936,33 @@ describe("index", () => {
|
|
|
2795
936
|
});
|
|
2796
937
|
it.each(["list-models", "agent-info", "list-auth-methods", "login", "logout"])("should let --%s run without a .mcp.json", (command) => {
|
|
2797
938
|
const workspace = loadWorkspace(command, undefined, emptyWorkspaceDir());
|
|
2798
|
-
expect(workspace
|
|
2799
|
-
expect(workspace.agentrqConfig.env).toEqual({});
|
|
2800
|
-
expect(workspace.mcpBridge.getSessionId()).toBeUndefined();
|
|
939
|
+
expect(workspace).toEqual({ configs: [], agentrqConfig: { name: "none", type: "http", env: {} } });
|
|
2801
940
|
});
|
|
2802
941
|
it("should not read a .mcp.json that is there, when the command does not need it", () => {
|
|
2803
942
|
const dir = emptyWorkspaceDir();
|
|
2804
943
|
// Broken on purpose: had it been read, this would throw.
|
|
2805
944
|
writeFileSync(join(dir, ".mcp.json"), "{ not json");
|
|
2806
|
-
expect(loadWorkspace("list-models", undefined, dir).
|
|
2807
|
-
});
|
|
2808
|
-
it.each(["agent-info", "list-auth-methods", "login", "logout"])("should still use a config named with --mcp-json for --%s", (command) => {
|
|
2809
|
-
const file = writeMcpJson(emptyWorkspaceDir(), "servers.json");
|
|
2810
|
-
const workspace = loadWorkspace(command, file, emptyWorkspaceDir());
|
|
2811
|
-
expect(workspace.agentrqConfig.name).toBe("agentrq-ws");
|
|
2812
|
-
expect(workspace.mcpBridge.getServerName()).toBe("agentrq-ws");
|
|
2813
|
-
});
|
|
2814
|
-
it("should never connect --list-models to the workspace, even one named with --mcp-json", async () => {
|
|
2815
|
-
const file = writeMcpJson(emptyWorkspaceDir(), "servers.json");
|
|
2816
|
-
const workspace = loadWorkspace("list-models", file, emptyWorkspaceDir());
|
|
2817
|
-
expect(workspace.agentrqConfig.name).toBe("agentrq-ws");
|
|
2818
|
-
expect(workspace.mcpBridge.getServerName()).toBeUndefined();
|
|
2819
|
-
await expect(workspace.mcpBridge.callTool("elicit", {})).rejects.toThrow("No agentrq workspace is configured");
|
|
945
|
+
expect(loadWorkspace("list-models", undefined, dir).agentrqConfig.name).toBe("none");
|
|
2820
946
|
});
|
|
2821
|
-
it("should
|
|
2822
|
-
expect(
|
|
947
|
+
it("should not read a config named with --mcp-json for a one-shot command either", () => {
|
|
948
|
+
expect(loadWorkspace("login", "/nowhere/servers.json", emptyWorkspaceDir()).agentrqConfig.name).toBe("none");
|
|
2823
949
|
});
|
|
2824
|
-
it("should still require a .mcp.json to run
|
|
950
|
+
it("should still require a .mcp.json to run the bridge", () => {
|
|
2825
951
|
expect(() => loadWorkspace("run", undefined, emptyWorkspaceDir())).toThrow("Could not find .mcp.json");
|
|
2826
952
|
});
|
|
2827
|
-
it("should
|
|
953
|
+
it("should report a --mcp-json path that is wrong", () => {
|
|
954
|
+
expect(() => loadWorkspace("run", "/nowhere/servers.json", emptyWorkspaceDir())).toThrow();
|
|
955
|
+
});
|
|
956
|
+
it("should pick the AgentRQ server from the workspace it finds", () => {
|
|
2828
957
|
const dir = emptyWorkspaceDir();
|
|
2829
958
|
writeMcpJson(dir);
|
|
2830
959
|
const workspace = loadWorkspace("run", undefined, dir);
|
|
960
|
+
expect(workspace.agentrqConfig.name).toBe("agentrq-ws");
|
|
2831
961
|
expect(workspace.configs.map((c) => c.name)).toEqual(["agentrq-ws"]);
|
|
2832
|
-
|
|
962
|
+
});
|
|
963
|
+
it("should read a config named with --mcp-json", () => {
|
|
964
|
+
const file = writeMcpJson(emptyWorkspaceDir(), "servers.json");
|
|
965
|
+
expect(loadWorkspace("run", file, emptyWorkspaceDir()).agentrqConfig.url).toBe("http://localhost:1/mcp");
|
|
2833
966
|
});
|
|
2834
967
|
});
|
|
2835
968
|
describe("makeIsolatedDir", () => {
|
|
@@ -2843,30 +976,6 @@ describe("index", () => {
|
|
|
2843
976
|
expect(() => isolated.remove()).not.toThrow();
|
|
2844
977
|
});
|
|
2845
978
|
});
|
|
2846
|
-
describe("createDetachedBridge", () => {
|
|
2847
|
-
it("should fail tool calls, drop notifications, and close quietly", async () => {
|
|
2848
|
-
const bridge = createDetachedBridge();
|
|
2849
|
-
await expect(bridge.callTool("elicit", {})).rejects.toThrow("No agentrq workspace is configured");
|
|
2850
|
-
await expect(bridge.sendNotification("notifications/x", {})).resolves.toBeUndefined();
|
|
2851
|
-
expect(bridge.getSessionId()).toBeUndefined();
|
|
2852
|
-
expect(bridge.getServerName()).toBeUndefined();
|
|
2853
|
-
expect(bridge.getAdvertisedTools()).toBeUndefined();
|
|
2854
|
-
await expect(bridge.close()).resolves.toBeUndefined();
|
|
2855
|
-
});
|
|
2856
|
-
it("should not print an error when the agent shares its slash commands", async () => {
|
|
2857
|
-
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
|
|
2858
|
-
const client = new AgentRQACPClient(createDetachedBridge());
|
|
2859
|
-
await client.sessionUpdate({
|
|
2860
|
-
sessionId: "s1",
|
|
2861
|
-
update: {
|
|
2862
|
-
sessionUpdate: "available_commands_update",
|
|
2863
|
-
availableCommands: [{ name: "init", description: "d" }],
|
|
2864
|
-
},
|
|
2865
|
-
});
|
|
2866
|
-
expect(errorSpy).not.toHaveBeenCalled();
|
|
2867
|
-
errorSpy.mockRestore();
|
|
2868
|
-
});
|
|
2869
|
-
});
|
|
2870
979
|
describe("runAgentCommand", () => {
|
|
2871
980
|
const agentrqConfig = { env: {} };
|
|
2872
981
|
let logSpy;
|
|
@@ -2891,7 +1000,7 @@ describe("index", () => {
|
|
|
2891
1000
|
authMethods: [{ id: "agent-login", name: "Agent login" }],
|
|
2892
1001
|
agentCapabilities: { auth: { logout: {} } },
|
|
2893
1002
|
});
|
|
2894
|
-
await runAgentCommand("list-auth-methods", ["gemini", "--acp"], agentrqConfig
|
|
1003
|
+
await runAgentCommand("list-auth-methods", ["gemini", "--acp"], agentrqConfig.env);
|
|
2895
1004
|
const printed = logSpy.mock.calls.flat().join("\n");
|
|
2896
1005
|
expect(printed).toContain("Agent login (agent-login)");
|
|
2897
1006
|
expect(printed).toContain("--logout");
|
|
@@ -2904,7 +1013,7 @@ describe("index", () => {
|
|
|
2904
1013
|
const { spawn } = await import("node:child_process");
|
|
2905
1014
|
const newSession = vi.fn().mockResolvedValue({ sessionId: "m-sess", configOptions: [] });
|
|
2906
1015
|
mockConnection({ newSession });
|
|
2907
|
-
await runAgentCommand("list-models", ["gemini", "--acp"], agentrqConfig
|
|
1016
|
+
await runAgentCommand("list-models", ["gemini", "--acp"], agentrqConfig.env);
|
|
2908
1017
|
const sessionCwd = newSession.mock.calls[0][0].cwd;
|
|
2909
1018
|
expect(sessionCwd).not.toBe(process.cwd());
|
|
2910
1019
|
expect(sessionCwd.startsWith(tmpdir())).toBe(true);
|
|
@@ -2915,7 +1024,7 @@ describe("index", () => {
|
|
|
2915
1024
|
it("should remove the --list-models directory when the agent fails to start", async () => {
|
|
2916
1025
|
const { spawn } = await import("node:child_process");
|
|
2917
1026
|
mockConnection({ initialize: vi.fn().mockRejectedValue(new Error("boom")) });
|
|
2918
|
-
await expect(runAgentCommand("list-models", ["gemini", "--acp"], agentrqConfig
|
|
1027
|
+
await expect(runAgentCommand("list-models", ["gemini", "--acp"], agentrqConfig.env)).rejects.toThrow();
|
|
2919
1028
|
const cwd = vi.mocked(spawn).mock.calls.at(-1)[2].cwd;
|
|
2920
1029
|
expect(cwd.startsWith(tmpdir())).toBe(true);
|
|
2921
1030
|
expect(existsSync(cwd)).toBe(false);
|
|
@@ -2923,7 +1032,7 @@ describe("index", () => {
|
|
|
2923
1032
|
it("should leave the other commands running where the gateway runs", async () => {
|
|
2924
1033
|
const { spawn } = await import("node:child_process");
|
|
2925
1034
|
mockConnection({});
|
|
2926
|
-
await runAgentCommand("agent-info", ["gemini", "--acp"], agentrqConfig
|
|
1035
|
+
await runAgentCommand("agent-info", ["gemini", "--acp"], agentrqConfig.env);
|
|
2927
1036
|
expect(vi.mocked(spawn).mock.calls.at(-1)[2]).not.toHaveProperty("cwd");
|
|
2928
1037
|
});
|
|
2929
1038
|
it("should list models from configOptions and cleanly close session", async () => {
|
|
@@ -2944,7 +1053,7 @@ describe("index", () => {
|
|
|
2944
1053
|
],
|
|
2945
1054
|
}),
|
|
2946
1055
|
});
|
|
2947
|
-
await runAgentCommand("list-models", ["gemini", "--acp"], agentrqConfig
|
|
1056
|
+
await runAgentCommand("list-models", ["gemini", "--acp"], agentrqConfig.env);
|
|
2948
1057
|
const printed = logSpy.mock.calls.flat().join("\n");
|
|
2949
1058
|
expect(printed).toContain("Models supported by \"gemini --acp\":");
|
|
2950
1059
|
expect(printed).toContain("claude-3-7-sonnet");
|
|
@@ -2966,7 +1075,7 @@ describe("index", () => {
|
|
|
2966
1075
|
],
|
|
2967
1076
|
}),
|
|
2968
1077
|
});
|
|
2969
|
-
await runAgentCommand("list-models", ["gemini", "--acp"], {
|
|
1078
|
+
await runAgentCommand("list-models", ["gemini", "--acp"], {});
|
|
2970
1079
|
expect(logSpy.mock.calls.flat().join("\n")).toContain("gemini-pro");
|
|
2971
1080
|
expect(spawnedAgents[0].kill).toHaveBeenCalled();
|
|
2972
1081
|
});
|
|
@@ -2992,7 +1101,7 @@ describe("index", () => {
|
|
|
2992
1101
|
],
|
|
2993
1102
|
}),
|
|
2994
1103
|
});
|
|
2995
|
-
await runAgentCommand("list-models", ["gemini", "--acp"], agentrqConfig,
|
|
1104
|
+
await runAgentCommand("list-models", ["gemini", "--acp"], agentrqConfig.env, undefined, true);
|
|
2996
1105
|
// The most recent call, not the only one: logSpy is shared across this
|
|
2997
1106
|
// describe's tests (recreated on the same already-mocked console.log,
|
|
2998
1107
|
// which vitest hands back rather than a fresh spy each time), so
|
|
@@ -3017,7 +1126,7 @@ describe("index", () => {
|
|
|
3017
1126
|
mockConnection({
|
|
3018
1127
|
newSession: vi.fn().mockResolvedValue({ sessionId: "m-sess", configOptions: [] }),
|
|
3019
1128
|
});
|
|
3020
|
-
await runAgentCommand("list-models", ["gemini", "--acp"], agentrqConfig,
|
|
1129
|
+
await runAgentCommand("list-models", ["gemini", "--acp"], agentrqConfig.env, undefined, true);
|
|
3021
1130
|
const lastLog = logSpy.mock.calls.at(-1)?.[0];
|
|
3022
1131
|
expect(JSON.parse(lastLog)).toEqual({ agent: "gemini --acp", models: [] });
|
|
3023
1132
|
});
|
|
@@ -3035,7 +1144,7 @@ describe("index", () => {
|
|
|
3035
1144
|
}, {
|
|
3036
1145
|
agentCapabilities: { providers: true },
|
|
3037
1146
|
});
|
|
3038
|
-
await runAgentCommand("list-models", ["gemini", "--acp"], agentrqConfig
|
|
1147
|
+
await runAgentCommand("list-models", ["gemini", "--acp"], agentrqConfig.env);
|
|
3039
1148
|
const printed = logSpy.mock.calls.flat().join("\n");
|
|
3040
1149
|
expect(printed).toContain("Configurable providers for \"gemini --acp\":");
|
|
3041
1150
|
expect(printed).toContain("claude-sonnet");
|
|
@@ -3045,7 +1154,7 @@ describe("index", () => {
|
|
|
3045
1154
|
mockConnection({
|
|
3046
1155
|
newSession: vi.fn().mockResolvedValue({ sessionId: "m-sess", configOptions: [] }),
|
|
3047
1156
|
});
|
|
3048
|
-
await runAgentCommand("list-models", ["gemini", "--acp"], agentrqConfig
|
|
1157
|
+
await runAgentCommand("list-models", ["gemini", "--acp"], agentrqConfig.env);
|
|
3049
1158
|
const printed = logSpy.mock.calls.flat().join("\n");
|
|
3050
1159
|
expect(printed).toContain("No configurable models advertised by \"gemini --acp\".");
|
|
3051
1160
|
expect(spawnedAgents[0].kill).toHaveBeenCalled();
|
|
@@ -3059,7 +1168,7 @@ describe("index", () => {
|
|
|
3059
1168
|
mcpCapabilities: { http: true },
|
|
3060
1169
|
},
|
|
3061
1170
|
});
|
|
3062
|
-
await runAgentCommand("agent-info", ["gemini", "--acp"], agentrqConfig
|
|
1171
|
+
await runAgentCommand("agent-info", ["gemini", "--acp"], agentrqConfig.env);
|
|
3063
1172
|
const printed = String(logSpy.mock.calls.at(-1)[0]);
|
|
3064
1173
|
expect(printed).toContain("gemini --acp");
|
|
3065
1174
|
expect(printed).toContain("ACP protocol version 1");
|
|
@@ -3070,14 +1179,14 @@ describe("index", () => {
|
|
|
3070
1179
|
});
|
|
3071
1180
|
it("should report agents that advertise no login", async () => {
|
|
3072
1181
|
mockConnection({});
|
|
3073
|
-
await runAgentCommand("list-auth-methods", ["gemini", "--acp"], agentrqConfig
|
|
1182
|
+
await runAgentCommand("list-auth-methods", ["gemini", "--acp"], agentrqConfig.env);
|
|
3074
1183
|
expect(logSpy.mock.calls.flat().join("\n")).toContain("no authentication methods");
|
|
3075
1184
|
});
|
|
3076
1185
|
it("should log out", async () => {
|
|
3077
1186
|
const connection = mockConnection({ logout: vi.fn().mockResolvedValue({}) }, {
|
|
3078
1187
|
agentCapabilities: { auth: { logout: {} } },
|
|
3079
1188
|
});
|
|
3080
|
-
await runAgentCommand("logout", ["gemini", "--acp"], agentrqConfig
|
|
1189
|
+
await runAgentCommand("logout", ["gemini", "--acp"], agentrqConfig.env);
|
|
3081
1190
|
expect(connection.logout).toHaveBeenCalledWith({});
|
|
3082
1191
|
});
|
|
3083
1192
|
it("should log in with the method the user named", async () => {
|
|
@@ -3087,18 +1196,19 @@ describe("index", () => {
|
|
|
3087
1196
|
{ id: "oauth", name: "OAuth" },
|
|
3088
1197
|
],
|
|
3089
1198
|
});
|
|
3090
|
-
await runAgentCommand("login", ["gemini", "--acp"], agentrqConfig,
|
|
1199
|
+
await runAgentCommand("login", ["gemini", "--acp"], agentrqConfig.env, "oauth");
|
|
3091
1200
|
expect(connection.authenticate).toHaveBeenCalledWith({ methodId: "oauth" });
|
|
3092
1201
|
});
|
|
3093
1202
|
it("should still shut the agent down when the login fails", async () => {
|
|
3094
1203
|
mockConnection({ authenticate: vi.fn() }, {
|
|
3095
1204
|
authMethods: [{ id: "agent-login", name: "Agent login" }],
|
|
3096
1205
|
});
|
|
3097
|
-
await expect(runAgentCommand("login", ["gemini", "--acp"], agentrqConfig,
|
|
1206
|
+
await expect(runAgentCommand("login", ["gemini", "--acp"], agentrqConfig.env, "missing")).rejects.toThrow(/Unknown authentication method/);
|
|
3098
1207
|
expect(spawnedAgents[0].kill).toHaveBeenCalled();
|
|
3099
1208
|
});
|
|
3100
1209
|
});
|
|
3101
1210
|
describe("nativeOptionsFor", () => {
|
|
1211
|
+
const ws = (agentrqConfig) => ({ configs: [agentrqConfig], agentrqConfig });
|
|
3102
1212
|
const agentrq = {
|
|
3103
1213
|
name: "agentrq",
|
|
3104
1214
|
type: "http",
|
|
@@ -3110,8 +1220,7 @@ describe("index", () => {
|
|
|
3110
1220
|
"--acp-version", "1", "--agent", "codex-acp", "--model", "m", "--effort", "high", "--max-concurrency", "4",
|
|
3111
1221
|
"--permission-timeout", "5", "--auth-method", "chatgpt",
|
|
3112
1222
|
]);
|
|
3113
|
-
expect(nativeOptionsFor(options, ["npx", "codex-acp"], agentrq, "/work")).toEqual({
|
|
3114
|
-
version: 1,
|
|
1223
|
+
expect(nativeOptionsFor(options, ["npx", "codex-acp"], ws(agentrq), "/work")).toEqual({
|
|
3115
1224
|
acpCmdArgs: ["npx", "codex-acp"],
|
|
3116
1225
|
env: { A: "1" },
|
|
3117
1226
|
endpoint: "wss://4hro0x9eslxd.mcp.agentrq.com/api/acp/v1",
|
|
@@ -3123,6 +1232,7 @@ describe("index", () => {
|
|
|
3123
1232
|
permissionTimeoutMinutes: 5,
|
|
3124
1233
|
authMethodId: "chatgpt",
|
|
3125
1234
|
cwd: "/work",
|
|
1235
|
+
mcpServers: [agentrq],
|
|
3126
1236
|
});
|
|
3127
1237
|
});
|
|
3128
1238
|
it("parses --effort and warns when missing a value", () => {
|
|
@@ -3135,26 +1245,30 @@ describe("index", () => {
|
|
|
3135
1245
|
consoleSpy.mockRestore();
|
|
3136
1246
|
});
|
|
3137
1247
|
it("names a command-line agent by its basename and honours --acp-url", () => {
|
|
3138
|
-
const options = parseGatewayArgs(["--acp-
|
|
3139
|
-
const native = nativeOptionsFor(options, ["/opt/bin/gemini", "--acp"], agentrq);
|
|
3140
|
-
expect(native).toMatchObject({
|
|
1248
|
+
const options = parseGatewayArgs(["--acp-url", "ws://other/x"]);
|
|
1249
|
+
const native = nativeOptionsFor(options, ["/opt/bin/gemini", "--acp"], ws(agentrq));
|
|
1250
|
+
expect(native).toMatchObject({ agentId: "gemini", endpoint: "ws://other/x", cwd: process.cwd() });
|
|
3141
1251
|
});
|
|
3142
1252
|
it("needs the workspace token", () => {
|
|
3143
1253
|
const options = parseGatewayArgs(["--acp-version", "1"]);
|
|
3144
|
-
expect(nativeOptionsFor(options, ["a"], { ...agentrq, url: "https://h/" })).toBe("
|
|
1254
|
+
expect(nativeOptionsFor(options, ["a"], ws({ ...agentrq, url: "https://h/" }))).toBe("acp-gateway needs the workspace token from .mcp.json");
|
|
1255
|
+
});
|
|
1256
|
+
it("needs no URL in .mcp.json when --acp-url names the endpoint", () => {
|
|
1257
|
+
const options = parseGatewayArgs(["--acp-url", "wss://x/acp"]);
|
|
1258
|
+
expect(nativeOptionsFor(options, ["a"], ws({ name: "x", type: "http", headers: { Authorization: "Bearer t" } }))).toMatchObject({ endpoint: "wss://x/acp", token: "t" });
|
|
3145
1259
|
});
|
|
3146
1260
|
it("needs a URL, from .mcp.json or --acp-url", () => {
|
|
3147
1261
|
const options = parseGatewayArgs(["--acp-version", "1"]);
|
|
3148
|
-
expect(nativeOptionsFor(options, ["a"], { name: "x", type: "http", headers: { Authorization: "Bearer t" } })).toMatch(/needs the AgentRQ URL/);
|
|
1262
|
+
expect(nativeOptionsFor(options, ["a"], ws({ name: "x", type: "http", headers: { Authorization: "Bearer t" } }))).toMatch(/needs the AgentRQ URL/);
|
|
3149
1263
|
});
|
|
3150
1264
|
it("explains a URL it cannot read", () => {
|
|
3151
1265
|
const options = parseGatewayArgs(["--acp-version", "1"]);
|
|
3152
|
-
expect(nativeOptionsFor(options, ["a"], { name: "x", type: "http", url: "not a url", headers: { Authorization: "Bearer t" } })).toMatch(/cannot work out the AgentRQ endpoint from "not a url"; pass --acp-url/);
|
|
1266
|
+
expect(nativeOptionsFor(options, ["a"], ws({ name: "x", type: "http", url: "not a url", headers: { Authorization: "Bearer t" } }))).toMatch(/cannot work out the AgentRQ endpoint from "not a url"; pass --acp-url/);
|
|
3153
1267
|
});
|
|
3154
1268
|
it("starts native mode with those options", async () => {
|
|
3155
1269
|
const run = vi.fn(async () => { });
|
|
3156
1270
|
const exit = vi.fn();
|
|
3157
|
-
await startNativeMode(parseGatewayArgs(["--acp-version", "1"]), ["a"], agentrq, run, exit);
|
|
1271
|
+
await startNativeMode(parseGatewayArgs(["--acp-version", "1"]), ["a"], ws(agentrq), run, exit);
|
|
3158
1272
|
expect(run).toHaveBeenCalledWith(expect.objectContaining({ endpoint: "wss://4hro0x9eslxd.mcp.agentrq.com/api/acp/v1", token: "t" }));
|
|
3159
1273
|
expect(exit).not.toHaveBeenCalled();
|
|
3160
1274
|
});
|
|
@@ -3162,15 +1276,106 @@ describe("index", () => {
|
|
|
3162
1276
|
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
|
|
3163
1277
|
const run = vi.fn(async () => { });
|
|
3164
1278
|
const exit = vi.fn();
|
|
3165
|
-
await startNativeMode(parseGatewayArgs(["--acp-version", "1"]), ["a"], { name: "x", type: "http", url: "https://h/" }, run, exit);
|
|
3166
|
-
expect(errorSpy).toHaveBeenCalledWith("[acp-gateway]
|
|
1279
|
+
await startNativeMode(parseGatewayArgs(["--acp-version", "1"]), ["a"], ws({ name: "x", type: "http", url: "https://h/" }), run, exit);
|
|
1280
|
+
expect(errorSpy).toHaveBeenCalledWith("[acp-gateway] acp-gateway needs the workspace token from .mcp.json");
|
|
3167
1281
|
expect(exit).toHaveBeenCalledWith(1);
|
|
3168
1282
|
expect(run).not.toHaveBeenCalled();
|
|
3169
1283
|
errorSpy.mockRestore();
|
|
3170
1284
|
});
|
|
3171
|
-
it("
|
|
1285
|
+
it("logs the agent in at this terminal only when there is one", async () => {
|
|
1286
|
+
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
|
|
1287
|
+
const options = parseGatewayArgs(["--auth-method", "oauth"]);
|
|
1288
|
+
expect(nativeOptionsFor(options, ["gemini"], ws(agentrq), "/w", false).login).toBeUndefined();
|
|
1289
|
+
const native = nativeOptionsFor(options, [process.execPath, "agent.js"], ws(agentrq), "/w", true);
|
|
1290
|
+
// The mocked agent offers no login methods, so the login has nothing to do.
|
|
1291
|
+
await expect(native.login()).resolves.toBeUndefined();
|
|
1292
|
+
expect(errorSpy.mock.calls.flat().join("\n")).toContain("advertises no authentication methods");
|
|
1293
|
+
errorSpy.mockRestore();
|
|
1294
|
+
});
|
|
1295
|
+
it("always connects to the ACP v1 endpoint", () => {
|
|
1296
|
+
const options = parseGatewayArgs([]);
|
|
1297
|
+
expect(nativeOptionsFor(options, [], ws(agentrq))).toMatchObject({
|
|
1298
|
+
endpoint: "wss://4hro0x9eslxd.mcp.agentrq.com/api/acp/v1",
|
|
1299
|
+
agentId: "",
|
|
1300
|
+
});
|
|
1301
|
+
});
|
|
1302
|
+
});
|
|
1303
|
+
describe("runGateway", () => {
|
|
1304
|
+
let errorSpy;
|
|
1305
|
+
beforeEach(() => {
|
|
1306
|
+
errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
|
|
1307
|
+
});
|
|
1308
|
+
afterEach(() => {
|
|
1309
|
+
errorSpy.mockRestore();
|
|
1310
|
+
});
|
|
1311
|
+
/** A workspace directory whose .mcp.json names an AgentRQ server. */
|
|
1312
|
+
function workspaceDir() {
|
|
1313
|
+
const dir = join(mkdtempSync(join(tmpdir(), "acp-gw-run-")), "a", "b", "c", "d");
|
|
1314
|
+
mkdirSync(dir, { recursive: true });
|
|
1315
|
+
writeFileSync(join(dir, ".mcp.json"), JSON.stringify({
|
|
1316
|
+
mcpServers: { agentrq: { type: "http", url: "https://h.mcp.agentrq.com/?token=t", env: { A: "1" } } },
|
|
1317
|
+
}));
|
|
1318
|
+
return dir;
|
|
1319
|
+
}
|
|
1320
|
+
function deps(over = {}) {
|
|
1321
|
+
return {
|
|
1322
|
+
resolve: vi.fn(async () => ({ command: [process.execPath, "agent.js"] })),
|
|
1323
|
+
agentCommand: vi.fn(async () => { }),
|
|
1324
|
+
bridge: vi.fn(async () => { }),
|
|
1325
|
+
exit: vi.fn(),
|
|
1326
|
+
startDir: workspaceDir(),
|
|
1327
|
+
...over,
|
|
1328
|
+
};
|
|
1329
|
+
}
|
|
1330
|
+
it("bridges the agent to the workspace's ACP endpoint for run", async () => {
|
|
1331
|
+
const d = deps();
|
|
3172
1332
|
const options = parseGatewayArgs([]);
|
|
3173
|
-
|
|
1333
|
+
await runGateway(options, ["agent"], d);
|
|
1334
|
+
expect(d.resolve).toHaveBeenCalledWith(options, ["agent"]);
|
|
1335
|
+
expect(d.bridge).toHaveBeenCalledWith(options, [process.execPath, "agent.js"], {
|
|
1336
|
+
agentrqConfig: expect.objectContaining({ name: "agentrq", env: { A: "1" } }),
|
|
1337
|
+
configs: [expect.objectContaining({ name: "agentrq" })],
|
|
1338
|
+
});
|
|
1339
|
+
expect(d.agentCommand).not.toHaveBeenCalled();
|
|
1340
|
+
expect(d.exit).not.toHaveBeenCalled();
|
|
1341
|
+
});
|
|
1342
|
+
it("adds the registry entry's env to the agent's", async () => {
|
|
1343
|
+
const d = deps({
|
|
1344
|
+
resolve: vi.fn(async () => ({ command: [process.execPath], env: { B: "2" } })),
|
|
1345
|
+
});
|
|
1346
|
+
await runGateway(parseGatewayArgs(["--agent", "x"]), [], d);
|
|
1347
|
+
expect(d.bridge.mock.calls[0][2].agentrqConfig.env).toEqual({ A: "1", B: "2" });
|
|
1348
|
+
});
|
|
1349
|
+
it("runs a one-shot command without a workspace and exits 0", async () => {
|
|
1350
|
+
const d = deps({ startDir: tmpdir() });
|
|
1351
|
+
await runGateway(parseGatewayArgs(["--login", "oauth", "--json"]), ["agent"], d);
|
|
1352
|
+
expect(d.agentCommand).toHaveBeenCalledWith("login", [process.execPath, "agent.js"], {}, "oauth", true);
|
|
1353
|
+
expect(d.bridge).not.toHaveBeenCalled();
|
|
1354
|
+
expect(d.exit).toHaveBeenCalledWith(0);
|
|
1355
|
+
});
|
|
1356
|
+
it("says why it cannot run, without a stack trace, and exits 1", async () => {
|
|
1357
|
+
const root = mkdtempSync(join(tmpdir(), "acp-gw-noworkspace-"));
|
|
1358
|
+
const dir = join(root, "a", "b", "c", "d");
|
|
1359
|
+
mkdirSync(dir, { recursive: true });
|
|
1360
|
+
const d = deps({ startDir: dir });
|
|
1361
|
+
await runGateway(parseGatewayArgs([]), ["agent"], d);
|
|
1362
|
+
expect(errorSpy.mock.calls[0][0]).toMatch(/^\[acp-gateway\] Could not find \.mcp\.json/);
|
|
1363
|
+
expect(d.exit).toHaveBeenCalledWith(1);
|
|
1364
|
+
expect(d.bridge).not.toHaveBeenCalled();
|
|
1365
|
+
});
|
|
1366
|
+
it("refuses an agent command that is not installed", async () => {
|
|
1367
|
+
const d = deps({
|
|
1368
|
+
resolve: vi.fn(async () => ({ command: ["definitely-not-an-agent-xyz"] })),
|
|
1369
|
+
});
|
|
1370
|
+
await runGateway(parseGatewayArgs([]), ["definitely-not-an-agent-xyz"], d);
|
|
1371
|
+
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('Agent command "definitely-not-an-agent-xyz" was not found'));
|
|
1372
|
+
expect(d.exit).toHaveBeenCalledWith(1);
|
|
1373
|
+
});
|
|
1374
|
+
it("reports a failure that is not an Error as it is", async () => {
|
|
1375
|
+
const d = deps({ resolve: vi.fn(async () => Promise.reject("registry down")) });
|
|
1376
|
+
await runGateway(parseGatewayArgs([]), [], d);
|
|
1377
|
+
expect(errorSpy).toHaveBeenCalledWith("[acp-gateway] registry down");
|
|
1378
|
+
expect(d.exit).toHaveBeenCalledWith(1);
|
|
3174
1379
|
});
|
|
3175
1380
|
});
|
|
3176
1381
|
describe("helpText", () => {
|
|
@@ -3196,7 +1401,6 @@ describe("index", () => {
|
|
|
3196
1401
|
"--max-concurrency",
|
|
3197
1402
|
"--permission-timeout",
|
|
3198
1403
|
"--mcp-json",
|
|
3199
|
-
"--acp-version",
|
|
3200
1404
|
"--acp-url",
|
|
3201
1405
|
"--verbose",
|
|
3202
1406
|
"--help",
|
|
@@ -3230,11 +1434,6 @@ describe("index", () => {
|
|
|
3230
1434
|
expect(printed).toContain("--list-agents");
|
|
3231
1435
|
});
|
|
3232
1436
|
});
|
|
3233
|
-
describe("authConfig", () => {
|
|
3234
|
-
it("should start out with no preferred login method", () => {
|
|
3235
|
-
expect(authConfig).toEqual({});
|
|
3236
|
-
});
|
|
3237
|
-
});
|
|
3238
1437
|
describe("isInteractiveTerminal", () => {
|
|
3239
1438
|
it("should be true only when both stdin and stderr are a TTY", () => {
|
|
3240
1439
|
const original = { stdin: process.stdin.isTTY, stderr: process.stderr.isTTY };
|
|
@@ -3251,540 +1450,6 @@ describe("index", () => {
|
|
|
3251
1450
|
}
|
|
3252
1451
|
});
|
|
3253
1452
|
});
|
|
3254
|
-
describe("pickHumanApprovalMode", () => {
|
|
3255
|
-
// The real modes codex-acp advertises. Its default is "agent", whose
|
|
3256
|
-
// reviewer is an automated Guardian Review that approves on the human's
|
|
3257
|
-
// behalf — so tool calls never reach agentrq.
|
|
3258
|
-
const codexModes = {
|
|
3259
|
-
currentModeId: "agent",
|
|
3260
|
-
availableModes: [
|
|
3261
|
-
{ id: "read-only", name: "Ask for approval", _meta: { kind: "standard" } },
|
|
3262
|
-
{ id: "agent", name: "Approve for me", _meta: { kind: "auto_review" } },
|
|
3263
|
-
{ id: "agent-full-access", name: "Full access", _meta: { kind: "full_access" } },
|
|
3264
|
-
],
|
|
3265
|
-
};
|
|
3266
|
-
it("should pick the human-approval mode over auto-reviewing and full-access modes", () => {
|
|
3267
|
-
expect(pickHumanApprovalMode(codexModes)).toBe("read-only");
|
|
3268
|
-
});
|
|
3269
|
-
it("should return undefined when the agent advertises no modes", () => {
|
|
3270
|
-
expect(pickHumanApprovalMode(undefined)).toBeUndefined();
|
|
3271
|
-
expect(pickHumanApprovalMode(null)).toBeUndefined();
|
|
3272
|
-
expect(pickHumanApprovalMode({ currentModeId: "x", availableModes: [] })).toBeUndefined();
|
|
3273
|
-
});
|
|
3274
|
-
it("should return undefined when every available mode auto-approves", () => {
|
|
3275
|
-
const modes = {
|
|
3276
|
-
currentModeId: "agent",
|
|
3277
|
-
availableModes: [
|
|
3278
|
-
{ id: "agent", name: "Approve for me", _meta: { kind: "auto_review" } },
|
|
3279
|
-
{ id: "yolo", name: "Never ask", _meta: { kind: "full_access" } },
|
|
3280
|
-
],
|
|
3281
|
-
};
|
|
3282
|
-
expect(pickHumanApprovalMode(modes)).toBeUndefined();
|
|
3283
|
-
});
|
|
3284
|
-
it("should fall back to the first non-auto-approving mode when none names approval", () => {
|
|
3285
|
-
const modes = {
|
|
3286
|
-
currentModeId: "fast",
|
|
3287
|
-
availableModes: [
|
|
3288
|
-
{ id: "fast", name: "Full access", _meta: { kind: "full_access" } },
|
|
3289
|
-
{ id: "careful", name: "Careful" },
|
|
3290
|
-
{ id: "other", name: "Other" },
|
|
3291
|
-
],
|
|
3292
|
-
};
|
|
3293
|
-
expect(pickHumanApprovalMode(modes)).toBe("careful");
|
|
3294
|
-
});
|
|
3295
|
-
it("should tolerate modes without _meta or with a non-string kind", () => {
|
|
3296
|
-
const modes = {
|
|
3297
|
-
currentModeId: "a",
|
|
3298
|
-
availableModes: [
|
|
3299
|
-
{ id: "a", name: "Full access" },
|
|
3300
|
-
{ id: "b", name: "Ask first", _meta: { kind: 42 } },
|
|
3301
|
-
],
|
|
3302
|
-
};
|
|
3303
|
-
expect(pickHumanApprovalMode(modes)).toBe("b");
|
|
3304
|
-
});
|
|
3305
|
-
});
|
|
3306
|
-
describe("enforceHumanApprovalMode", () => {
|
|
3307
|
-
let consoleSpy;
|
|
3308
|
-
beforeEach(() => {
|
|
3309
|
-
consoleSpy = vi.spyOn(console, "error").mockImplementation(() => { });
|
|
3310
|
-
});
|
|
3311
|
-
it("should switch out of an auto-approving default mode", async () => {
|
|
3312
|
-
const connection = { setSessionMode: vi.fn().mockResolvedValue({}) };
|
|
3313
|
-
const sessionResult = {
|
|
3314
|
-
sessionId: "sess-1",
|
|
3315
|
-
modes: {
|
|
3316
|
-
currentModeId: "agent",
|
|
3317
|
-
availableModes: [
|
|
3318
|
-
{ id: "read-only", name: "Ask for approval", _meta: { kind: "standard" } },
|
|
3319
|
-
{ id: "agent", name: "Approve for me", _meta: { kind: "auto_review" } },
|
|
3320
|
-
],
|
|
3321
|
-
},
|
|
3322
|
-
};
|
|
3323
|
-
await enforceHumanApprovalMode(connection, sessionResult);
|
|
3324
|
-
expect(connection.setSessionMode).toHaveBeenCalledWith({
|
|
3325
|
-
sessionId: "sess-1",
|
|
3326
|
-
modeId: "read-only",
|
|
3327
|
-
});
|
|
3328
|
-
});
|
|
3329
|
-
it("should do nothing when the agent advertises no modes", async () => {
|
|
3330
|
-
const connection = { setSessionMode: vi.fn() };
|
|
3331
|
-
await enforceHumanApprovalMode(connection, { sessionId: "sess-1" });
|
|
3332
|
-
await enforceHumanApprovalMode(connection, {
|
|
3333
|
-
sessionId: "sess-1",
|
|
3334
|
-
modes: { currentModeId: "x", availableModes: [] },
|
|
3335
|
-
});
|
|
3336
|
-
expect(connection.setSessionMode).not.toHaveBeenCalled();
|
|
3337
|
-
});
|
|
3338
|
-
it("should not switch when already in a human-approval mode", async () => {
|
|
3339
|
-
const connection = { setSessionMode: vi.fn() };
|
|
3340
|
-
const sessionResult = {
|
|
3341
|
-
sessionId: "sess-1",
|
|
3342
|
-
modes: {
|
|
3343
|
-
currentModeId: "read-only",
|
|
3344
|
-
availableModes: [
|
|
3345
|
-
{ id: "read-only", name: "Ask for approval", _meta: { kind: "standard" } },
|
|
3346
|
-
{ id: "agent", name: "Approve for me", _meta: { kind: "auto_review" } },
|
|
3347
|
-
],
|
|
3348
|
-
},
|
|
3349
|
-
};
|
|
3350
|
-
await enforceHumanApprovalMode(connection, sessionResult);
|
|
3351
|
-
expect(connection.setSessionMode).not.toHaveBeenCalled();
|
|
3352
|
-
});
|
|
3353
|
-
it("should warn and not switch when every mode auto-approves", async () => {
|
|
3354
|
-
const connection = { setSessionMode: vi.fn() };
|
|
3355
|
-
const sessionResult = {
|
|
3356
|
-
sessionId: "sess-1",
|
|
3357
|
-
modes: {
|
|
3358
|
-
currentModeId: "agent",
|
|
3359
|
-
availableModes: [
|
|
3360
|
-
{ id: "agent", name: "Approve for me", _meta: { kind: "auto_review" } },
|
|
3361
|
-
{ id: "full", name: "Full access", _meta: { kind: "full_access" } },
|
|
3362
|
-
],
|
|
3363
|
-
},
|
|
3364
|
-
};
|
|
3365
|
-
await enforceHumanApprovalMode(connection, sessionResult);
|
|
3366
|
-
expect(connection.setSessionMode).not.toHaveBeenCalled();
|
|
3367
|
-
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("no mode that defers approvals to the human"));
|
|
3368
|
-
});
|
|
3369
|
-
it("should log and not throw when setSessionMode fails", async () => {
|
|
3370
|
-
const connection = {
|
|
3371
|
-
setSessionMode: vi.fn().mockRejectedValue(new Error("unsupported")),
|
|
3372
|
-
};
|
|
3373
|
-
const sessionResult = {
|
|
3374
|
-
sessionId: "sess-1",
|
|
3375
|
-
modes: {
|
|
3376
|
-
currentModeId: "agent",
|
|
3377
|
-
availableModes: [
|
|
3378
|
-
{ id: "read-only", name: "Ask for approval", _meta: { kind: "standard" } },
|
|
3379
|
-
{ id: "agent", name: "Approve for me", _meta: { kind: "auto_review" } },
|
|
3380
|
-
],
|
|
3381
|
-
},
|
|
3382
|
-
};
|
|
3383
|
-
await expect(enforceHumanApprovalMode(connection, sessionResult)).resolves.toBeUndefined();
|
|
3384
|
-
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("Failed to set session mode"), expect.any(Error));
|
|
3385
|
-
});
|
|
3386
|
-
});
|
|
3387
|
-
describe("task cancellation handling", () => {
|
|
3388
|
-
let errorSpy;
|
|
3389
|
-
beforeEach(() => {
|
|
3390
|
-
activeSessions.clear();
|
|
3391
|
-
errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
|
|
3392
|
-
});
|
|
3393
|
-
afterEach(() => {
|
|
3394
|
-
activeSessions.clear();
|
|
3395
|
-
errorSpy.mockRestore();
|
|
3396
|
-
});
|
|
3397
|
-
describe("findActiveSession", () => {
|
|
3398
|
-
it("should find session by direct task key", () => {
|
|
3399
|
-
const mockSession = { sessionId: "sess-1", acpClient: { cancelTurn: vi.fn() } };
|
|
3400
|
-
activeSessions.set("task-1", mockSession);
|
|
3401
|
-
expect(findActiveSession("task-1")).toBe(mockSession);
|
|
3402
|
-
});
|
|
3403
|
-
it("should find session by sessionId match", () => {
|
|
3404
|
-
const mockSession = { sessionId: "sess-custom", acpClient: { cancelTurn: vi.fn() } };
|
|
3405
|
-
activeSessions.set("key-other", mockSession);
|
|
3406
|
-
expect(findActiveSession("sess-custom")).toBe(mockSession);
|
|
3407
|
-
});
|
|
3408
|
-
it("should return the single session if no taskId is provided", () => {
|
|
3409
|
-
const mockSession = { sessionId: "sess-only", acpClient: { cancelTurn: vi.fn() } };
|
|
3410
|
-
activeSessions.set("default", mockSession);
|
|
3411
|
-
expect(findActiveSession(undefined)).toBe(mockSession);
|
|
3412
|
-
});
|
|
3413
|
-
it("should fallback to default keyed session when taskId is given but only 1 session exists", () => {
|
|
3414
|
-
const mockSession = { sessionId: "s1", acpClient: { cancelTurn: vi.fn() } };
|
|
3415
|
-
activeSessions.set("default", mockSession);
|
|
3416
|
-
expect(findActiveSession("task-new-id")).toBe(mockSession);
|
|
3417
|
-
});
|
|
3418
|
-
it("should not fall back to a session that belongs to a different task", () => {
|
|
3419
|
-
// Task A is running; a cancel for queued task B must not abort it.
|
|
3420
|
-
const sessionA = { sessionId: "sess-a", acpClient: { cancelTurn: vi.fn() } };
|
|
3421
|
-
activeSessions.set("task-a", sessionA);
|
|
3422
|
-
expect(findActiveSession("task-b")).toBeUndefined();
|
|
3423
|
-
});
|
|
3424
|
-
it("should return undefined if taskId is not found when multiple sessions exist", () => {
|
|
3425
|
-
activeSessions.set("task-1", { sessionId: "s1" });
|
|
3426
|
-
activeSessions.set("task-2", { sessionId: "s2" });
|
|
3427
|
-
expect(findActiveSession("task-nonexistent")).toBeUndefined();
|
|
3428
|
-
expect(findActiveSession(undefined)).toBeUndefined();
|
|
3429
|
-
});
|
|
3430
|
-
});
|
|
3431
|
-
describe("handleTaskCancellation", () => {
|
|
3432
|
-
it("should cancel turn on the matched active session", async () => {
|
|
3433
|
-
const cancelTurn = vi.fn().mockResolvedValue(undefined);
|
|
3434
|
-
const mockSession = {
|
|
3435
|
-
sessionId: "sess-100",
|
|
3436
|
-
acpClient: { cancelTurn },
|
|
3437
|
-
};
|
|
3438
|
-
activeSessions.set("task-100", mockSession);
|
|
3439
|
-
await handleTaskCancellation("task-100", "cancelled by user");
|
|
3440
|
-
expect(cancelTurn).toHaveBeenCalledWith("sess-100");
|
|
3441
|
-
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("Cancelling session sess-100 for task task-100 (cancelled by user)"));
|
|
3442
|
-
});
|
|
3443
|
-
it("should skip a task cancelled while it was still being fetched", async () => {
|
|
3444
|
-
cancelledTaskSeq.clear();
|
|
3445
|
-
const promptMock = vi.fn();
|
|
3446
|
-
const switcher = { ensureForTask: vi.fn().mockResolvedValue("s-q1") };
|
|
3447
|
-
const acpClient = { flushReply: vi.fn(), reportStopReason: vi.fn() };
|
|
3448
|
-
const connection = { prompt: promptMock };
|
|
3449
|
-
const bridge = {
|
|
3450
|
-
// The cancel lands while the poll is in flight — the task has no
|
|
3451
|
-
// session yet, so nothing but this flag can stop it.
|
|
3452
|
-
callTool: vi.fn().mockImplementation(async () => {
|
|
3453
|
-
await handleTaskCancellation("task-queued-1");
|
|
3454
|
-
return { content: [{ type: "text", text: "task task-queued-1: do work" }] };
|
|
3455
|
-
}),
|
|
3456
|
-
};
|
|
3457
|
-
resetPendingTaskDrain();
|
|
3458
|
-
await drainPendingTasks(bridge, new TaskQueue(1), {
|
|
3459
|
-
acpCmdArgsOrConnection: connection,
|
|
3460
|
-
configsOrSessionSwitcher: switcher,
|
|
3461
|
-
agentrqConfigOrAcpClient: acpClient,
|
|
3462
|
-
});
|
|
3463
|
-
expect(promptMock).not.toHaveBeenCalled();
|
|
3464
|
-
});
|
|
3465
|
-
it("should not swallow work queued after the cancellation", async () => {
|
|
3466
|
-
// agentrq reuses a chat's id as the task id, so the id cancelled a
|
|
3467
|
-
// moment ago is the same id the user's next message arrives under.
|
|
3468
|
-
cancelledTaskSeq.clear();
|
|
3469
|
-
await handleTaskCancellation("task-queued-2");
|
|
3470
|
-
const promptMock = vi.fn().mockResolvedValue({ stopReason: "end_turn" });
|
|
3471
|
-
const switcher = { ensureForTask: vi.fn().mockResolvedValue("s-q2") };
|
|
3472
|
-
const acpClient = { flushReply: vi.fn(), reportStopReason: vi.fn() };
|
|
3473
|
-
const connection = { prompt: promptMock };
|
|
3474
|
-
const bridge = {
|
|
3475
|
-
callTool: vi.fn().mockResolvedValue({
|
|
3476
|
-
content: [{ type: "text", text: "task task-queued-2: fresh work" }],
|
|
3477
|
-
}),
|
|
3478
|
-
};
|
|
3479
|
-
resetPendingTaskDrain();
|
|
3480
|
-
await drainPendingTasks(bridge, new TaskQueue(1), {
|
|
3481
|
-
acpCmdArgsOrConnection: connection,
|
|
3482
|
-
configsOrSessionSwitcher: switcher,
|
|
3483
|
-
agentrqConfigOrAcpClient: acpClient,
|
|
3484
|
-
});
|
|
3485
|
-
expect(promptMock).toHaveBeenCalled();
|
|
3486
|
-
});
|
|
3487
|
-
it("should forget the oldest cancellations rather than grow forever", async () => {
|
|
3488
|
-
cancelledTaskSeq.clear();
|
|
3489
|
-
for (let i = 0; i < 250; i++)
|
|
3490
|
-
markTaskCancelled(`task-${i}`);
|
|
3491
|
-
expect(cancelledTaskSeq.size).toBe(200);
|
|
3492
|
-
expect(cancelledTaskSeq.has("task-0")).toBe(false);
|
|
3493
|
-
expect(cancelledTaskSeq.has("task-249")).toBe(true);
|
|
3494
|
-
});
|
|
3495
|
-
it("should only stop the notification that was queued before the cancel", async () => {
|
|
3496
|
-
cancelledTaskSeq.clear();
|
|
3497
|
-
const older = nextTaskSeq();
|
|
3498
|
-
await handleTaskCancellation("task-two-turns");
|
|
3499
|
-
const newer = nextTaskSeq();
|
|
3500
|
-
expect(isTaskCancelled("task-two-turns", older)).toBe(true);
|
|
3501
|
-
expect(isTaskCancelled("task-two-turns", newer)).toBe(false);
|
|
3502
|
-
});
|
|
3503
|
-
it("should log when task to cancel is not found", async () => {
|
|
3504
|
-
await handleTaskCancellation("task-missing");
|
|
3505
|
-
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("Received cancellation for task task-missing, but no active session found"));
|
|
3506
|
-
});
|
|
3507
|
-
it("should cancel the single session when taskId is omitted and only 1 session exists", async () => {
|
|
3508
|
-
const cancel1 = vi.fn().mockResolvedValue(undefined);
|
|
3509
|
-
activeSessions.set("t1", { sessionId: "s1", acpClient: { cancelTurn: cancel1 } });
|
|
3510
|
-
await handleTaskCancellation(undefined, "single shutdown");
|
|
3511
|
-
expect(cancel1).toHaveBeenCalledWith("s1");
|
|
3512
|
-
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("Received cancellation with no taskId (single shutdown). Cancelling active session s1..."));
|
|
3513
|
-
});
|
|
3514
|
-
it("should fail closed and not cancel anything when taskId is omitted and multiple sessions exist", async () => {
|
|
3515
|
-
const cancel1 = vi.fn().mockResolvedValue(undefined);
|
|
3516
|
-
const cancel2 = vi.fn().mockResolvedValue(undefined);
|
|
3517
|
-
activeSessions.set("t1", { sessionId: "s1", acpClient: { cancelTurn: cancel1 } });
|
|
3518
|
-
activeSessions.set("t2", { sessionId: "s2", acpClient: { cancelTurn: cancel2 } });
|
|
3519
|
-
await handleTaskCancellation(undefined, "multiple active");
|
|
3520
|
-
expect(cancel1).not.toHaveBeenCalled();
|
|
3521
|
-
expect(cancel2).not.toHaveBeenCalled();
|
|
3522
|
-
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("but 2 sessions are active (skipping to avoid aborting unrelated tasks)"));
|
|
3523
|
-
});
|
|
3524
|
-
});
|
|
3525
|
-
});
|
|
3526
|
-
describe("choosing a model at runtime", () => {
|
|
3527
|
-
// Everything here rests on one contract: the interface marks a chosen model
|
|
3528
|
-
// pending and only a models notification releases it. So every path has to
|
|
3529
|
-
// end in a report — including the ones that fail — or the picker is left
|
|
3530
|
-
// claiming a model the agent never adopted, with nothing to correct it.
|
|
3531
|
-
beforeEach(() => {
|
|
3532
|
-
activeSessions.clear();
|
|
3533
|
-
});
|
|
3534
|
-
afterEach(() => {
|
|
3535
|
-
activeSessions.clear();
|
|
3536
|
-
});
|
|
3537
|
-
const known = {
|
|
3538
|
-
configId: "model",
|
|
3539
|
-
currentModelId: "a",
|
|
3540
|
-
models: [
|
|
3541
|
-
{ id: "a", name: "Model A", current: true },
|
|
3542
|
-
{ id: "b", name: "Model B", current: false },
|
|
3543
|
-
],
|
|
3544
|
-
};
|
|
3545
|
-
/** A session whose ACP set succeeds, reporting the new list back. */
|
|
3546
|
-
const sessionThatSwitches = () => {
|
|
3547
|
-
const sendModelsToWorkspace = vi.fn();
|
|
3548
|
-
const setSessionConfigOption = vi.fn().mockResolvedValue({
|
|
3549
|
-
configOptions: [
|
|
3550
|
-
{
|
|
3551
|
-
id: "model",
|
|
3552
|
-
type: "select",
|
|
3553
|
-
category: "model",
|
|
3554
|
-
currentValue: "b",
|
|
3555
|
-
options: [
|
|
3556
|
-
{ value: "a", name: "Model A" },
|
|
3557
|
-
{ value: "b", name: "Model B" },
|
|
3558
|
-
],
|
|
3559
|
-
},
|
|
3560
|
-
],
|
|
3561
|
-
});
|
|
3562
|
-
const session = {
|
|
3563
|
-
sessionId: "sess-1",
|
|
3564
|
-
connection: { setSessionConfigOption },
|
|
3565
|
-
acpClient: { sendModelsToWorkspace, lastModelsFor: () => known },
|
|
3566
|
-
};
|
|
3567
|
-
return { session, sendModelsToWorkspace, setSessionConfigOption };
|
|
3568
|
-
};
|
|
3569
|
-
it("switches the named session and reports what the agent ended up on", async () => {
|
|
3570
|
-
const { session, sendModelsToWorkspace, setSessionConfigOption } = sessionThatSwitches();
|
|
3571
|
-
activeSessions.set("task-1", session);
|
|
3572
|
-
await handleSetModel({ sessionId: "sess-1", configId: "model", modelId: "b" });
|
|
3573
|
-
expect(setSessionConfigOption).toHaveBeenCalledWith({
|
|
3574
|
-
sessionId: "sess-1",
|
|
3575
|
-
configId: "model",
|
|
3576
|
-
value: "b",
|
|
3577
|
-
});
|
|
3578
|
-
// The agent's own answer, not the id that was asked for.
|
|
3579
|
-
expect(sendModelsToWorkspace).toHaveBeenCalledWith("sess-1", expect.objectContaining({ currentModelId: "b" }));
|
|
3580
|
-
});
|
|
3581
|
-
it("puts back what was true when the agent refuses the switch", async () => {
|
|
3582
|
-
const sendModelsToWorkspace = vi.fn();
|
|
3583
|
-
const session = {
|
|
3584
|
-
sessionId: "sess-1",
|
|
3585
|
-
connection: {
|
|
3586
|
-
setSessionConfigOption: vi.fn().mockRejectedValue(new Error("nope")),
|
|
3587
|
-
},
|
|
3588
|
-
acpClient: { sendModelsToWorkspace, lastModelsFor: () => known },
|
|
3589
|
-
};
|
|
3590
|
-
activeSessions.set("task-1", session);
|
|
3591
|
-
await handleSetModel({ sessionId: "sess-1", configId: "model", modelId: "b" });
|
|
3592
|
-
// Still on "a": the picker reverts instead of hanging on "b" forever.
|
|
3593
|
-
expect(sendModelsToWorkspace).toHaveBeenCalledWith("sess-1", expect.objectContaining({ currentModelId: "a" }));
|
|
3594
|
-
});
|
|
3595
|
-
it("does not throw when no session matches", async () => {
|
|
3596
|
-
// The session went away between the human clicking and this arriving.
|
|
3597
|
-
await expect(handleSetModel({ sessionId: "sess-gone", configId: "model", modelId: "b" })).resolves.toBeUndefined();
|
|
3598
|
-
});
|
|
3599
|
-
it("answers for a session that has already ended", async () => {
|
|
3600
|
-
// The agent exited, taking its client with it, so there is nothing left to
|
|
3601
|
-
// set. The picker is still holding a pending model, so what was last true
|
|
3602
|
-
// for that session goes out over the bridge to release it.
|
|
3603
|
-
const sendNotification = vi.fn().mockResolvedValue(undefined);
|
|
3604
|
-
await sendModelsNotification({ sendNotification }, "sess-ended", known);
|
|
3605
|
-
sendNotification.mockClear();
|
|
3606
|
-
await handleSetModel({ sessionId: "sess-ended", configId: "model", modelId: "b" }, { sendNotification });
|
|
3607
|
-
expect(sendNotification).toHaveBeenCalledWith("notifications/claude/channel/models", expect.objectContaining({ session_id: "sess-ended", current_model: "a" }));
|
|
3608
|
-
});
|
|
3609
|
-
it("stays quiet about a set that names no session and matches none", async () => {
|
|
3610
|
-
// With no id and nothing running there is nothing to identify, let alone
|
|
3611
|
-
// report on.
|
|
3612
|
-
const sendNotification = vi.fn().mockResolvedValue(undefined);
|
|
3613
|
-
await handleSetModel({ configId: "model", modelId: "b" }, { sendNotification });
|
|
3614
|
-
expect(sendNotification).not.toHaveBeenCalled();
|
|
3615
|
-
});
|
|
3616
|
-
it("stays quiet about a session it has never heard of", async () => {
|
|
3617
|
-
// Nothing was ever reported for it, so there is no truth to put back and
|
|
3618
|
-
// inventing one would be worse than the silence.
|
|
3619
|
-
const sendNotification = vi.fn().mockResolvedValue(undefined);
|
|
3620
|
-
await handleSetModel({ sessionId: "sess-never-seen", configId: "model", modelId: "b" }, { sendNotification });
|
|
3621
|
-
expect(sendNotification).not.toHaveBeenCalled();
|
|
3622
|
-
});
|
|
3623
|
-
it("answers a notification naming no model instead of ignoring it", async () => {
|
|
3624
|
-
const { session, sendModelsToWorkspace, setSessionConfigOption } = sessionThatSwitches();
|
|
3625
|
-
activeSessions.set("task-1", session);
|
|
3626
|
-
await handleSetModel({ sessionId: "sess-1", configId: "model" });
|
|
3627
|
-
expect(setSessionConfigOption).not.toHaveBeenCalled();
|
|
3628
|
-
// A malformed notification is still a pending picker on the other end.
|
|
3629
|
-
expect(sendModelsToWorkspace).toHaveBeenCalledWith("sess-1", known);
|
|
3630
|
-
});
|
|
3631
|
-
it("refuses a model the session never advertised, and says what it has", async () => {
|
|
3632
|
-
const { session, sendModelsToWorkspace, setSessionConfigOption } = sessionThatSwitches();
|
|
3633
|
-
activeSessions.set("task-1", session);
|
|
3634
|
-
await handleSetModel({ sessionId: "sess-1", configId: "model", modelId: "not-a-model" });
|
|
3635
|
-
expect(setSessionConfigOption).not.toHaveBeenCalled();
|
|
3636
|
-
expect(sendModelsToWorkspace).toHaveBeenCalledWith("sess-1", known);
|
|
3637
|
-
});
|
|
3638
|
-
it("reports without asking the agent when the model is already current", async () => {
|
|
3639
|
-
const { session, sendModelsToWorkspace, setSessionConfigOption } = sessionThatSwitches();
|
|
3640
|
-
activeSessions.set("task-1", session);
|
|
3641
|
-
await handleSetModel({ sessionId: "sess-1", configId: "model", modelId: "a" });
|
|
3642
|
-
expect(setSessionConfigOption).not.toHaveBeenCalled();
|
|
3643
|
-
expect(sendModelsToWorkspace).toHaveBeenCalledWith("sess-1", known);
|
|
3644
|
-
});
|
|
3645
|
-
it("resolves a model by display name, for a --model typed by a human", async () => {
|
|
3646
|
-
const { session, setSessionConfigOption } = sessionThatSwitches();
|
|
3647
|
-
await applyModelSelection({
|
|
3648
|
-
connection: session.connection,
|
|
3649
|
-
acpClient: session.acpClient,
|
|
3650
|
-
sessionId: "sess-1",
|
|
3651
|
-
known,
|
|
3652
|
-
requested: "Model B",
|
|
3653
|
-
});
|
|
3654
|
-
expect(setSessionConfigOption).toHaveBeenCalledWith({
|
|
3655
|
-
sessionId: "sess-1",
|
|
3656
|
-
configId: "model",
|
|
3657
|
-
value: "b",
|
|
3658
|
-
});
|
|
3659
|
-
});
|
|
3660
|
-
it("marks the chosen model current when the agent answers without its config", async () => {
|
|
3661
|
-
// Some agents acknowledge the write without repeating their options. The
|
|
3662
|
-
// interface still has to end up with something selected.
|
|
3663
|
-
const sendModelsToWorkspace = vi.fn();
|
|
3664
|
-
const acpClient = { sendModelsToWorkspace, lastModelsFor: () => known };
|
|
3665
|
-
await applyModelSelection({
|
|
3666
|
-
connection: { setSessionConfigOption: vi.fn().mockResolvedValue({}) },
|
|
3667
|
-
acpClient,
|
|
3668
|
-
sessionId: "sess-1",
|
|
3669
|
-
known,
|
|
3670
|
-
requested: "b",
|
|
3671
|
-
});
|
|
3672
|
-
expect(sendModelsToWorkspace).toHaveBeenCalledWith("sess-1", expect.objectContaining({
|
|
3673
|
-
currentModelId: "b",
|
|
3674
|
-
models: [
|
|
3675
|
-
expect.objectContaining({ id: "a", current: false }),
|
|
3676
|
-
expect.objectContaining({ id: "b", current: true }),
|
|
3677
|
-
],
|
|
3678
|
-
}));
|
|
3679
|
-
});
|
|
3680
|
-
it("puts back the newest report, not the snapshot taken before the set", async () => {
|
|
3681
|
-
// The agent moved to "c" on its own while the set was in flight, and then
|
|
3682
|
-
// refused the set. Reverting to the pre-set snapshot would claim the
|
|
3683
|
-
// session is on "a" — a model it has already left — and, since every
|
|
3684
|
-
// report is recorded, would write that stale list back over the newer one.
|
|
3685
|
-
const fresher = {
|
|
3686
|
-
configId: "model",
|
|
3687
|
-
currentModelId: "c",
|
|
3688
|
-
models: [{ id: "c", name: "Model C", current: true }],
|
|
3689
|
-
};
|
|
3690
|
-
const sendModelsToWorkspace = vi.fn();
|
|
3691
|
-
await applyModelSelection({
|
|
3692
|
-
connection: {
|
|
3693
|
-
setSessionConfigOption: vi.fn().mockRejectedValue(new Error("nope")),
|
|
3694
|
-
},
|
|
3695
|
-
acpClient: { sendModelsToWorkspace, lastModelsFor: () => fresher },
|
|
3696
|
-
sessionId: "sess-1",
|
|
3697
|
-
known,
|
|
3698
|
-
requested: "b",
|
|
3699
|
-
});
|
|
3700
|
-
expect(sendModelsToWorkspace).toHaveBeenCalledWith("sess-1", fresher);
|
|
3701
|
-
});
|
|
3702
|
-
it("falls back to the caller's snapshot when nothing has been reported yet", async () => {
|
|
3703
|
-
// The startup path: --model runs against a session that has not sent a
|
|
3704
|
-
// models notification, so the list from session/new is all there is.
|
|
3705
|
-
const sendModelsToWorkspace = vi.fn();
|
|
3706
|
-
await applyModelSelection({
|
|
3707
|
-
connection: {
|
|
3708
|
-
setSessionConfigOption: vi.fn().mockRejectedValue(new Error("nope")),
|
|
3709
|
-
},
|
|
3710
|
-
acpClient: { sendModelsToWorkspace, lastModelsFor: () => undefined },
|
|
3711
|
-
sessionId: "sess-1",
|
|
3712
|
-
known,
|
|
3713
|
-
requested: "b",
|
|
3714
|
-
});
|
|
3715
|
-
expect(sendModelsToWorkspace).toHaveBeenCalledWith("sess-1", known);
|
|
3716
|
-
});
|
|
3717
|
-
it("says so rather than guessing when there is no config option to write to", async () => {
|
|
3718
|
-
const sendModelsToWorkspace = vi.fn();
|
|
3719
|
-
const setSessionConfigOption = vi.fn();
|
|
3720
|
-
await applyModelSelection({
|
|
3721
|
-
connection: { setSessionConfigOption },
|
|
3722
|
-
acpClient: { sendModelsToWorkspace, lastModelsFor: () => undefined },
|
|
3723
|
-
sessionId: "sess-1",
|
|
3724
|
-
requested: "b",
|
|
3725
|
-
});
|
|
3726
|
-
expect(setSessionConfigOption).not.toHaveBeenCalled();
|
|
3727
|
-
});
|
|
3728
|
-
});
|
|
3729
|
-
describe("handleAgentModeChange", () => {
|
|
3730
|
-
const modes = {
|
|
3731
|
-
currentModeId: "ask",
|
|
3732
|
-
availableModes: [
|
|
3733
|
-
{ id: "ask", name: "Ask first" },
|
|
3734
|
-
{ id: "auto", name: "Auto approve" },
|
|
3735
|
-
],
|
|
3736
|
-
};
|
|
3737
|
-
let errorSpy;
|
|
3738
|
-
beforeEach(() => {
|
|
3739
|
-
errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
|
|
3740
|
-
});
|
|
3741
|
-
afterEach(() => errorSpy.mockRestore());
|
|
3742
|
-
it("should leave a mode that still asks the human alone", async () => {
|
|
3743
|
-
const connection = { setSessionMode: vi.fn() };
|
|
3744
|
-
await handleAgentModeChange(connection, "sess-ok", "ask", modes);
|
|
3745
|
-
expect(connection.setSessionMode).not.toHaveBeenCalled();
|
|
3746
|
-
});
|
|
3747
|
-
it("should put the session back when the agent starts approving for us", async () => {
|
|
3748
|
-
const connection = { setSessionMode: vi.fn().mockResolvedValue({}) };
|
|
3749
|
-
await handleAgentModeChange(connection, "sess-drift", "auto", modes);
|
|
3750
|
-
expect(connection.setSessionMode).toHaveBeenCalledWith({
|
|
3751
|
-
sessionId: "sess-drift",
|
|
3752
|
-
modeId: "ask",
|
|
3753
|
-
});
|
|
3754
|
-
});
|
|
3755
|
-
it("should treat a mode the agent never advertised as untrusted", async () => {
|
|
3756
|
-
const connection = { setSessionMode: vi.fn().mockResolvedValue({}) };
|
|
3757
|
-
await handleAgentModeChange(connection, "sess-unknown", "something-new", modes);
|
|
3758
|
-
expect(connection.setSessionMode).toHaveBeenCalledWith({
|
|
3759
|
-
sessionId: "sess-unknown",
|
|
3760
|
-
modeId: "ask",
|
|
3761
|
-
});
|
|
3762
|
-
});
|
|
3763
|
-
it("should stop fighting an agent that keeps switching back", async () => {
|
|
3764
|
-
const connection = { setSessionMode: vi.fn().mockResolvedValue({}) };
|
|
3765
|
-
for (let i = 0; i < 5; i++) {
|
|
3766
|
-
await handleAgentModeChange(connection, "sess-stubborn", "auto", modes);
|
|
3767
|
-
}
|
|
3768
|
-
// An unbounded fight would be an endless stream of setSessionMode calls.
|
|
3769
|
-
expect(connection.setSessionMode).toHaveBeenCalledTimes(3);
|
|
3770
|
-
expect(errorSpy.mock.calls.flat().join("\n")).toContain("Giving up after 3 attempts");
|
|
3771
|
-
});
|
|
3772
|
-
it("should start counting again once the session is back in a safe mode", async () => {
|
|
3773
|
-
const connection = { setSessionMode: vi.fn().mockResolvedValue({}) };
|
|
3774
|
-
await handleAgentModeChange(connection, "sess-recovered", "auto", modes);
|
|
3775
|
-
await handleAgentModeChange(connection, "sess-recovered", "ask", modes);
|
|
3776
|
-
for (let i = 0; i < 4; i++) {
|
|
3777
|
-
await handleAgentModeChange(connection, "sess-recovered", "auto", modes);
|
|
3778
|
-
}
|
|
3779
|
-
expect(connection.setSessionMode).toHaveBeenCalledTimes(4);
|
|
3780
|
-
});
|
|
3781
|
-
it("should do nothing for an agent that offers no modes at all", async () => {
|
|
3782
|
-
const connection = { setSessionMode: vi.fn() };
|
|
3783
|
-
await handleAgentModeChange(connection, "sess-modeless", "whatever", undefined);
|
|
3784
|
-
await handleAgentModeChange(connection, "sess-modeless", "whatever", { availableModes: [] });
|
|
3785
|
-
expect(connection.setSessionMode).not.toHaveBeenCalled();
|
|
3786
|
-
});
|
|
3787
|
-
});
|
|
3788
1453
|
describe("session lifecycle and clean close", () => {
|
|
3789
1454
|
describe("supportsCloseSession", () => {
|
|
3790
1455
|
it("returns true when close is an object {}", () => {
|
|
@@ -3824,7 +1489,7 @@ describe("index", () => {
|
|
|
3824
1489
|
afterEach(() => {
|
|
3825
1490
|
errorSpy.mockRestore();
|
|
3826
1491
|
});
|
|
3827
|
-
it("
|
|
1492
|
+
it("sends closeSession if supported, and kills process", async () => {
|
|
3828
1493
|
const cancelTurn = vi.fn().mockResolvedValue(undefined);
|
|
3829
1494
|
const closeSessionRpc = vi.fn().mockResolvedValue({});
|
|
3830
1495
|
const kill = vi.fn();
|
|
@@ -3836,7 +1501,6 @@ describe("index", () => {
|
|
|
3836
1501
|
process: { kill },
|
|
3837
1502
|
};
|
|
3838
1503
|
await closeSession(session);
|
|
3839
|
-
expect(cancelTurn).toHaveBeenCalledWith("sess-1");
|
|
3840
1504
|
expect(closeSessionRpc).toHaveBeenCalledWith({ sessionId: "sess-1" });
|
|
3841
1505
|
expect(kill).toHaveBeenCalled();
|
|
3842
1506
|
});
|
|
@@ -3852,25 +1516,9 @@ describe("index", () => {
|
|
|
3852
1516
|
process: { kill },
|
|
3853
1517
|
};
|
|
3854
1518
|
await closeSession(session);
|
|
3855
|
-
expect(cancelTurn).toHaveBeenCalledWith("sess-no-close");
|
|
3856
1519
|
expect(closeSessionRpc).not.toHaveBeenCalled();
|
|
3857
1520
|
expect(kill).toHaveBeenCalled();
|
|
3858
1521
|
});
|
|
3859
|
-
it("handles error during cancelTurn gracefully", async () => {
|
|
3860
|
-
const cancelTurn = vi.fn().mockRejectedValue(new Error("cancel failed"));
|
|
3861
|
-
const kill = vi.fn();
|
|
3862
|
-
const session = {
|
|
3863
|
-
sessionId: "sess-err",
|
|
3864
|
-
acpClient: { cancelTurn },
|
|
3865
|
-
connection: {},
|
|
3866
|
-
initResult: {},
|
|
3867
|
-
process: { kill },
|
|
3868
|
-
};
|
|
3869
|
-
await closeSession(session);
|
|
3870
|
-
expect(cancelTurn).toHaveBeenCalledWith("sess-err");
|
|
3871
|
-
expect(kill).toHaveBeenCalled();
|
|
3872
|
-
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("Error cancelling turn while closing session sess-err"), expect.any(Error));
|
|
3873
|
-
});
|
|
3874
1522
|
it("handles error during closeSession RPC gracefully", async () => {
|
|
3875
1523
|
const cancelTurn = vi.fn().mockResolvedValue(undefined);
|
|
3876
1524
|
const closeSessionRpc = vi.fn().mockRejectedValue(new Error("close RPC failed"));
|
|
@@ -3918,136 +1566,6 @@ describe("index", () => {
|
|
|
3918
1566
|
await expect(closeSession(session)).resolves.not.toThrow();
|
|
3919
1567
|
});
|
|
3920
1568
|
});
|
|
3921
|
-
describe("closeAllSessions", () => {
|
|
3922
|
-
let errorSpy;
|
|
3923
|
-
beforeEach(() => {
|
|
3924
|
-
activeSessions.clear();
|
|
3925
|
-
// Also clears the record of agents spawned by earlier tests, which this
|
|
3926
|
-
// one now reaps.
|
|
3927
|
-
resetIdleSession();
|
|
3928
|
-
errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
|
|
3929
|
-
});
|
|
3930
|
-
afterEach(() => {
|
|
3931
|
-
activeSessions.clear();
|
|
3932
|
-
resetIdleSession();
|
|
3933
|
-
errorSpy.mockRestore();
|
|
3934
|
-
});
|
|
3935
|
-
it("does nothing when activeSessions is empty", async () => {
|
|
3936
|
-
await closeAllSessions();
|
|
3937
|
-
expect(activeSessions.size).toBe(0);
|
|
3938
|
-
});
|
|
3939
|
-
it("ends an agent that spawned but never opened a session", async () => {
|
|
3940
|
-
setVerbose(true);
|
|
3941
|
-
// activeSessions only holds agents that got as far as an open session,
|
|
3942
|
-
// so shutting down on it alone left behind the agent still handshaking
|
|
3943
|
-
// — and the one stopped waiting for a login, which is the case most
|
|
3944
|
-
// likely to be interrupted, since it can sit there indefinitely. One
|
|
3945
|
-
// that quits when its stdin closes got away with it; one with an event
|
|
3946
|
-
// loop of its own did not.
|
|
3947
|
-
newSessionHangs.value = true;
|
|
3948
|
-
spawnedAgents.length = 0;
|
|
3949
|
-
const opening = getOrCreateSession("T-Interrupted", ["node", "agent.js"], [], { env: {} }, fakeBridge());
|
|
3950
|
-
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
3951
|
-
// Spawned, and tracked by nothing that shutdown used to look at.
|
|
3952
|
-
expect(spawnedAgents.length).toBe(1);
|
|
3953
|
-
expect(activeSessions.size).toBe(0);
|
|
3954
|
-
await closeAllSessions(10);
|
|
3955
|
-
expect(spawnedAgents[0].kill).toHaveBeenCalled();
|
|
3956
|
-
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("never opened a session"));
|
|
3957
|
-
newSessionHangs.value = false;
|
|
3958
|
-
void opening.catch(() => { });
|
|
3959
|
-
});
|
|
3960
|
-
it("keeps ending the rest when one refuses to die", async () => {
|
|
3961
|
-
// Shutdown is the last thing that runs; one process that will not go
|
|
3962
|
-
// must not take the others' only chance to go with it.
|
|
3963
|
-
newSessionHangs.value = true;
|
|
3964
|
-
spawnedAgents.length = 0;
|
|
3965
|
-
const opening = [
|
|
3966
|
-
getOrCreateSession("T-Stuck-A", ["node", "agent.js"], [], { env: {} }, fakeBridge()),
|
|
3967
|
-
getOrCreateSession("T-Stuck-B", ["node", "agent.js"], [], { env: {} }, fakeBridge()),
|
|
3968
|
-
];
|
|
3969
|
-
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
3970
|
-
expect(spawnedAgents.length).toBe(2);
|
|
3971
|
-
spawnedAgents[0].kill.mockImplementation(() => {
|
|
3972
|
-
throw new Error("no such process");
|
|
3973
|
-
});
|
|
3974
|
-
await closeAllSessions(10);
|
|
3975
|
-
expect(spawnedAgents[1].kill).toHaveBeenCalled();
|
|
3976
|
-
expect(errorSpy).toHaveBeenCalledWith("[acp] Error ending an agent process:", expect.any(Error));
|
|
3977
|
-
newSessionHangs.value = false;
|
|
3978
|
-
for (const p of opening)
|
|
3979
|
-
void p.catch(() => { });
|
|
3980
|
-
});
|
|
3981
|
-
it("does not report a cleanly closed session as one left behind", async () => {
|
|
3982
|
-
// Its process is ended by closeSession; counting it again would report
|
|
3983
|
-
// a leak that is not there.
|
|
3984
|
-
newSessionHangs.value = false;
|
|
3985
|
-
spawnedAgents.length = 0;
|
|
3986
|
-
await getOrCreateSession("T-Clean-Exit", ["node", "agent.js"], [], { env: {} }, fakeBridge());
|
|
3987
|
-
expect(activeSessions.size).toBe(1);
|
|
3988
|
-
await closeAllSessions(10);
|
|
3989
|
-
expect(spawnedAgents[0].kill).toHaveBeenCalled();
|
|
3990
|
-
expect(errorSpy).not.toHaveBeenCalledWith(expect.stringContaining("never opened a session"));
|
|
3991
|
-
});
|
|
3992
|
-
it("closes all unique active sessions in parallel and clears map", async () => {
|
|
3993
|
-
setVerbose(true);
|
|
3994
|
-
const cancel1 = vi.fn().mockResolvedValue(undefined);
|
|
3995
|
-
const cancel2 = vi.fn().mockResolvedValue(undefined);
|
|
3996
|
-
const kill1 = vi.fn();
|
|
3997
|
-
const kill2 = vi.fn();
|
|
3998
|
-
const session1 = {
|
|
3999
|
-
sessionId: "s1",
|
|
4000
|
-
acpClient: { cancelTurn: cancel1 },
|
|
4001
|
-
connection: {},
|
|
4002
|
-
initResult: {},
|
|
4003
|
-
process: { kill: kill1 },
|
|
4004
|
-
};
|
|
4005
|
-
const session2 = {
|
|
4006
|
-
sessionId: "s2",
|
|
4007
|
-
acpClient: { cancelTurn: cancel2 },
|
|
4008
|
-
connection: {},
|
|
4009
|
-
initResult: {},
|
|
4010
|
-
process: { kill: kill2 },
|
|
4011
|
-
};
|
|
4012
|
-
activeSessions.set("task-1", session1);
|
|
4013
|
-
activeSessions.set("task-2", session2);
|
|
4014
|
-
activeSessions.set("duplicate-task-1", session1);
|
|
4015
|
-
await closeAllSessions();
|
|
4016
|
-
expect(activeSessions.size).toBe(0);
|
|
4017
|
-
expect(cancel1).toHaveBeenCalledTimes(1);
|
|
4018
|
-
expect(cancel2).toHaveBeenCalledTimes(1);
|
|
4019
|
-
expect(kill1).toHaveBeenCalledTimes(1);
|
|
4020
|
-
expect(kill2).toHaveBeenCalledTimes(1);
|
|
4021
|
-
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("Cleanly closing 2 active session(s)..."));
|
|
4022
|
-
});
|
|
4023
|
-
});
|
|
4024
|
-
describe("setupSignalHandlers", () => {
|
|
4025
|
-
it("registers and cleans up SIGINT and SIGTERM handlers", async () => {
|
|
4026
|
-
const signalHandler = vi.fn().mockResolvedValue(undefined);
|
|
4027
|
-
const cleanup = setupSignalHandlers(signalHandler);
|
|
4028
|
-
expect(process.listenerCount("SIGINT")).toBeGreaterThan(0);
|
|
4029
|
-
expect(process.listenerCount("SIGTERM")).toBeGreaterThan(0);
|
|
4030
|
-
// Emit SIGINT
|
|
4031
|
-
process.emit("SIGINT");
|
|
4032
|
-
expect(signalHandler).toHaveBeenCalledWith("SIGINT");
|
|
4033
|
-
// Emit SIGTERM
|
|
4034
|
-
process.emit("SIGTERM");
|
|
4035
|
-
expect(signalHandler).toHaveBeenCalledWith("SIGTERM");
|
|
4036
|
-
// Cleanup
|
|
4037
|
-
cleanup();
|
|
4038
|
-
});
|
|
4039
|
-
});
|
|
4040
|
-
});
|
|
4041
|
-
});
|
|
4042
|
-
describe("loginCommandFor", () => {
|
|
4043
|
-
it("names the agent, so nobody has to work the command out", () => {
|
|
4044
|
-
expect(loginCommandFor("antigravity-acp")).toBe("npx @agentrq/acp-gateway@latest --login --agent antigravity-acp");
|
|
4045
|
-
});
|
|
4046
|
-
it("repeats the command after -- when no registry id named the agent", () => {
|
|
4047
|
-
expect(loginCommandFor(undefined, ["node", "my-agent.js"])).toBe("npx @agentrq/acp-gateway@latest --login -- node my-agent.js");
|
|
4048
|
-
});
|
|
4049
|
-
it("falls back to the bare command when nothing identifies the agent", () => {
|
|
4050
|
-
expect(loginCommandFor()).toBe("npx @agentrq/acp-gateway@latest --login");
|
|
4051
1569
|
});
|
|
4052
1570
|
});
|
|
4053
1571
|
//# sourceMappingURL=index.test.js.map
|