-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Expand file tree
/
Copy pathtask-spawn.test.ts
More file actions
234 lines (206 loc) · 7.89 KB
/
Copy pathtask-spawn.test.ts
File metadata and controls
234 lines (206 loc) · 7.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
/**
* Contracts: task tool spawn routing (rework-contracts.md §3).
*
* 1. With an AsyncJobManager wired, `execute` returns immediately (agent id +
* job id) while the job body is still gated; job completion delivers a
* result carrying the irc follow-up / `history://<id>` hint.
* 2. The session-scoped spawn semaphore (task.maxConcurrency) serializes job
* bodies: with concurrency 1 the second body does not start until the
* first releases.
* 3. task.maxConcurrency=0 means unlimited rather than one-at-a-time.
*
* Param validation (missing agent / missing assignment) is covered by
* test/task/task-schema.test.ts.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "bun:test";
import { AsyncJobManager } from "@oh-my-pi/pi-coding-agent/async/job-manager";
import { Settings } from "@oh-my-pi/pi-coding-agent/config/settings";
import { AgentLifecycleManager } from "@oh-my-pi/pi-coding-agent/registry/agent-lifecycle";
import { AgentRegistry } from "@oh-my-pi/pi-coding-agent/registry/agent-registry";
import { TaskTool } from "@oh-my-pi/pi-coding-agent/task";
import * as discoveryModule from "@oh-my-pi/pi-coding-agent/task/discovery";
import * as executorModule from "@oh-my-pi/pi-coding-agent/task/executor";
import type { AgentDefinition, SingleResult, TaskParams } from "@oh-my-pi/pi-coding-agent/task/types";
import type { ToolSession } from "@oh-my-pi/pi-coding-agent/tools";
const taskAgent: AgentDefinition = {
name: "task",
description: "General-purpose task agent",
systemPrompt: "You are a task agent.",
source: "bundled",
};
function createSession(options: { manager?: AsyncJobManager; settings?: Record<string, unknown> }): ToolSession {
return {
cwd: "/tmp",
hasUI: false,
settings: Settings.isolated(options.settings ?? {}),
getSessionFile: () => null,
getSessionSpawns: () => "*",
asyncJobManager: options.manager,
} as unknown as ToolSession;
}
function getFirstText(result: { content: Array<{ type: string; text?: string }> }): string {
const content = result.content.find(part => part.type === "text");
return content?.type === "text" ? (content.text ?? "") : "";
}
function makeResult(id: string, overrides: Partial<SingleResult> = {}): SingleResult {
return {
index: 0,
id,
agent: "task",
agentSource: "bundled",
task: "task prompt",
assignment: "Do the thing.",
exitCode: 0,
output: "All done.",
stderr: "",
truncated: false,
durationMs: 5,
tokens: 0,
requests: 1,
...overrides,
};
}
interface Deferred {
promise: Promise<void>;
resolve: () => void;
}
function deferred(): Deferred {
const { promise, resolve } = Promise.withResolvers<void>();
return { promise, resolve };
}
async function pollUntil(predicate: () => boolean, timeoutMs = 2000): Promise<void> {
const start = Date.now();
while (!predicate()) {
if (Date.now() - start > timeoutMs) throw new Error("pollUntil timed out");
await Bun.sleep(5);
}
}
describe("task spawn routing", () => {
const managers: AsyncJobManager[] = [];
function createManager(): AsyncJobManager {
const manager = new AsyncJobManager({ onJobComplete: () => {} });
managers.push(manager);
return manager;
}
beforeEach(() => {
AgentRegistry.resetGlobalForTests();
AgentLifecycleManager.resetGlobalForTests();
});
afterEach(async () => {
vi.restoreAllMocks();
for (const manager of managers.splice(0)) {
await manager.dispose({ timeoutMs: 1000 });
}
AgentLifecycleManager.resetGlobalForTests();
AgentRegistry.resetGlobalForTests();
});
it("returns immediately on spawn and delivers the follow-up hint when the job completes", async () => {
vi.spyOn(discoveryModule, "discoverAgents").mockResolvedValue({
agents: [taskAgent],
projectAgentsDir: null,
});
const gate = deferred();
const runSpy = vi.spyOn(executorModule, "runSubprocess").mockImplementation(async options => {
await gate.promise;
return makeResult(options.id ?? "?");
});
const manager = createManager();
const tool = await TaskTool.create(createSession({ manager }));
const result = await tool.execute("tc-spawn", {
agent: "task",
id: "Spawnling",
description: "background work",
assignment: "Do the thing.",
} as TaskParams);
// Tool returned while the job body is still gated on the deferred.
const text = getFirstText(result);
expect(text).toContain("Spawned agent `Spawnling`");
const jobId = result.details?.async?.jobId;
expect(jobId).toBeTruthy();
expect(text).toContain(`job \`${jobId}\``);
const job = manager.getJob(jobId!);
expect(job?.status).toBe("running");
expect(job?.resultText).toBeUndefined();
gate.resolve();
await job!.promise;
expect(job!.status).toBe("completed");
expect(job!.resultText).toContain("Spawnling is now idle");
expect(job!.resultText).toContain("message it via `irc` to follow up");
expect(job!.resultText).toContain("history://Spawnling");
expect(runSpy).toHaveBeenCalledTimes(1);
});
it("bounds concurrent job bodies with the session spawn semaphore", async () => {
vi.spyOn(discoveryModule, "discoverAgents").mockResolvedValue({
agents: [taskAgent],
projectAgentsDir: null,
});
const started: string[] = [];
const gates = new Map<string, Deferred>();
vi.spyOn(executorModule, "runSubprocess").mockImplementation(async options => {
const id = options.id ?? "?";
started.push(id);
const gate = deferred();
gates.set(id, gate);
await gate.promise;
return makeResult(id);
});
const manager = createManager();
const tool = await TaskTool.create(createSession({ manager, settings: { "task.maxConcurrency": 1 } }));
const first = await tool.execute("tc-1", { agent: "task", id: "First", assignment: "Work A." } as TaskParams);
const second = await tool.execute("tc-2", { agent: "task", id: "Second", assignment: "Work B." } as TaskParams);
const firstJob = manager.getJob(first.details!.async!.jobId)!;
const secondJob = manager.getJob(second.details!.async!.jobId)!;
// First job body reaches the executor; second stays parked at the
// semaphore — still flagged queued because markRunning never ran.
await pollUntil(() => started.length >= 1);
expect(started).toEqual(["First"]);
expect(secondJob.queued).toBe(true);
// Releasing the first body lets the second one start.
gates.get(started[0]!)!.resolve();
await firstJob.promise;
await pollUntil(() => started.length === 2);
expect(started).toEqual(["First", "Second"]);
gates.get("Second")!.resolve();
await secondJob.promise;
expect(firstJob.status).toBe("completed");
expect(secondJob.status).toBe("completed");
});
it("treats task.maxConcurrency 0 as unlimited for background spawns", async () => {
vi.spyOn(discoveryModule, "discoverAgents").mockResolvedValue({
agents: [taskAgent],
projectAgentsDir: null,
});
const started: string[] = [];
const gates = new Map<string, Deferred>();
vi.spyOn(executorModule, "runSubprocess").mockImplementation(async options => {
const id = options.id ?? "?";
started.push(id);
const gate = deferred();
gates.set(id, gate);
await gate.promise;
return makeResult(id);
});
const manager = createManager();
const tool = await TaskTool.create(createSession({ manager, settings: { "task.maxConcurrency": 0 } }));
const first = await tool.execute("tc-unlimited-1", {
agent: "task",
id: "First",
assignment: "Work A.",
} as TaskParams);
const second = await tool.execute("tc-unlimited-2", {
agent: "task",
id: "Second",
assignment: "Work B.",
} as TaskParams);
const firstJob = manager.getJob(first.details!.async!.jobId)!;
const secondJob = manager.getJob(second.details!.async!.jobId)!;
await pollUntil(() => started.length === 2);
expect(started).toEqual(["First", "Second"]);
expect(secondJob.queued).toBe(false);
gates.get("First")!.resolve();
gates.get("Second")!.resolve();
await Promise.all([firstJob.promise, secondJob.promise]);
expect(firstJob.status).toBe("completed");
expect(secondJob.status).toBe("completed");
});
});