Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

WorkflowAgentLinks.test.ts

430 lines15.1 KB

1import { EnvironmentId, OrchestratorMcpFailure } from "@t3tools/contracts";
2import { assert, it } from "@effect/vitest";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Schema from "effect/Schema";
7import * as TestClock from "effect/testing/TestClock";
8​
9import * as PeerLinks from "../peer/PeerLinks.ts";
10import * as PeerMcpClient from "../peer/PeerMcpClient.ts";
11import * as WorkflowAgentLinks from "./WorkflowAgentLinks.ts";
12​
13const isFailure = Schema.is(OrchestratorMcpFailure);
14​
15interface Call {
16 readonly environmentId: string;
17 readonly tool: string;
18 readonly arguments: Record<string, unknown>;
19 readonly runtimeMode: string;
21​
22/** The other environment, played by the test: each tool answers from a list, in order. */
23const peer = (answers: Record<string, ReadonlyArray<unknown>>, enabled = true) => {
24 const calls: Array<Call> = [];
25 const left = new Map(Object.entries(answers).map(([tool, list]) => [tool, [...list]]));
26 const layer = Layer.merge(
27 Layer.succeed(
28 PeerMcpClient.PeerMcpClient,
29 PeerMcpClient.PeerMcpClient.of({
30 call: (input) =>
31 Effect.suspend(() => {
32 calls.push({
33 environmentId: input.environmentId,
34 tool: input.tool,
35 arguments: input.arguments,
36 runtimeMode: input.limits.runtimeMode,
37 });
38 const answer = left.get(input.tool)?.shift();
39 return isFailure(answer) ? Effect.fail(answer) : Effect.succeed(answer as never);
40 }),
41 }),
42 ),
43 Layer.mock(PeerLinks.PeerLinks)({ enabled: Effect.succeed(enabled) }),
44 );
45 return { calls, layer };
46};
47​
48const input = {
49 key: "run-1/write/0",
50 origin: { runId: "run-1", workflow: "fix", step: "write" },
51 title: "fix: write",
52 prompt: "Write the fix.",
53 outputSchema: { type: "object" },
54 model: undefined,
55 project: "/work/app",
56 environment: "env-b",
57 thread: undefined,
58};
59const run = (status: string) => ({ recentRuns: [{ runId: "turn-1", status }], items: [] });
60const waited = { threadId: "thread-1", runId: "turn-1", status: "idle" };
61​
62const assistant = (position: number, runId: string, text: string) => ({
63 type: "assistant_message",
64 itemId: `item-${position}`,
65 position,
66 runId,
67 text,
68 textTruncated: false,
69});
70const page = (
71 items: ReadonlyArray<ReturnType<typeof assistant>>,
72 earlierPosition?: number | null,
73 hasMore = false,
74) => ({
75 recentRuns: [],
76 items,
77 earlierPosition,
78 hasMore,
79 nextPosition: items.at(-1)?.position ?? null,
80});
81const readReply = (...pages: ReadonlyArray<unknown>) => {
82 const there = peer({
83 t3_thread_wait: [{ ...waited, timedOut: false }],
84 t3_thread_read: [run("completed"), ...pages],
85 });
86 return Effect.gen(function* () {
87 const result = yield* Effect.provide(
88 Effect.flatMap(WorkflowAgentLinks.make, (links) =>
89 links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b"),
90 ),
91 there.layer,
92 );
93 return { result, reads: there.calls.slice(2).map((call) => call.arguments) };
94 });
95};
96const messageRead = { threadId: "thread-1", view: "messages", limit: 100 };
97​
98it.effect("starts a thread there by the project's folder, with the step's key as the request", () =>
99 Effect.gen(function* () {
100 const there = peer({
101 t3_project_list: [
102 { projects: [{ id: "p-other", workspaceRoot: "/work/other" }], nextCursor: 1 },
103 { projects: [{ id: "p-app", workspaceRoot: "/work/app" }], nextCursor: null },
104 ],
105 t3_thread_launch: [{ threadId: "thread-1", runId: "turn-1" }],
106 });
107 const options = {
108 workspace: { type: "worktree", baseRef: "origin/main", startFromOrigin: true },
109 runtimeMode: "auto-accept-edits",
110 } as const;
111 const [turn, continued] = yield* Effect.provide(
112 Effect.flatMap(WorkflowAgentLinks.make, (links) =>
113 Effect.all([
114 links.start(
115 { ...input, launch: options },
116 "env-b",
117 "workflow:k",
118 EnvironmentId.make("env-a"),
119 ),
120 // A thread keeps how it started.
121 links
122 .start(
123 { ...input, thread: "thread-1", launch: options },
124 "env-b",
125 "workflow:c",
126 EnvironmentId.make("env-a"),
127 )
128 .pipe(Effect.flip),
129 ]),
130 ),
131 there.layer,
132 );
133 assert.deepStrictEqual(turn, { threadId: "thread-1", turnId: "turn-1", environment: "env-b" });
134 assert.include(continued.reason, "A continued `thread` keeps how it started");
135 const launch = there.calls.at(-1);
136 assert.deepStrictEqual(launch?.arguments, {
137 projectId: "p-app",
138 title: "fix: write",
139 runtimeMode: "auto-accept-edits",
140 workspaceStrategy: { type: "worktree", baseRef: "origin/main", startFromOrigin: true },
141 message: "Write the fix.",
142 outputSchema: { type: "object" },
143 clientRequestId: "workflow:k",
144 workflowRun: { environmentId: "env-a", runId: "run-1", workflow: "fix", step: "write" },
145 });
146 // The link's own access is the ceiling, not a mode narrower than it.
147 assert.equal(launch?.runtimeMode, "full-access");
148 }),
149);
150​
151it.effect("registers a folder that is not a project there yet", () =>
152 Effect.gen(function* () {
153 for (const [project, title] of [
154 [input.project, "app"],
155 ["/work/team\\api", "team\\api"],
156 ["C:\\work\\app", "app"],
157 ]) {
158 const there = peer({
159 t3_project_list: [{ projects: [], nextCursor: null }],
160 t3_project_create: [{ id: "p-new", workspaceRoot: project }],
161 t3_thread_launch: [{ threadId: "thread-1", runId: "turn-1" }],
162 });
163 yield* Effect.provide(
164 Effect.flatMap(WorkflowAgentLinks.make, (links) =>
165 links.start({ ...input, project }, "env-b", "workflow:k", EnvironmentId.make("env-a")),
166 ),
167 there.layer,
168 );
169 assert.deepStrictEqual(
170 there.calls.map((call) => [call.tool, call.arguments.projectId ?? call.arguments.title]),
171 [
172 ["t3_project_list", undefined],
173 ["t3_project_create", title],
174 ["t3_thread_launch", "p-new"],
175 ],
176 );
177 }
178 }),
179);
180​
181it.effect("finds a Windows folder there however its separators are written", () =>
182 Effect.gen(function* () {
183 const there = peer({
184 t3_project_list: [
185 { projects: [{ id: "p-app", workspaceRoot: "C:\\work\\app" }], nextCursor: null },
186 ],
187 t3_thread_launch: [{ threadId: "thread-1", runId: "turn-1" }],
188 });
189 yield* Effect.provide(
190 Effect.flatMap(WorkflowAgentLinks.make, (links) =>
191 links.start(
192 { ...input, project: "C:/work/app" },
193 "env-b",
194 "workflow:k",
195 EnvironmentId.make("env-a"),
196 ),
197 ),
198 there.layer,
199 );
200 assert.equal(there.calls.at(-1)?.arguments.projectId, "p-app");
201 }),
202);
203​
204it.effect("does not start anything while linked environments is off", () =>
205 Effect.gen(function* () {
206 const there = peer({}, false);
207 const error = yield* Effect.provide(
208 Effect.flatMap(WorkflowAgentLinks.make, (links) =>
209 links.start(input, "env-b", "workflow:k", EnvironmentId.make("env-a")),
210 ),
211 there.layer,
212 ).pipe(Effect.flip);
213 assert.match(error.reason, /Linked environments is off/);
214 assert.deepStrictEqual(there.calls, []);
215 }),
216);
217​
218it.effect("waits in pieces, rides out a dropped route, and returns the output and reply", () =>
219 Effect.gen(function* () {
220 const there = peer({
221 t3_thread_wait: [
222 { ...waited, timedOut: true },
223 new OrchestratorMcpFailure({ code: "orchestration_error", message: "unreachable" }),
224 { ...waited, timedOut: false, output: { branch: "fix/1" } },
225 ],
226 t3_thread_read: [
227 run("completed"),
228 {
229 recentRuns: [],
230 hasMore: false,
231 nextPosition: null,
232 items: [
233 { type: "assistant_message", runId: "turn-0", text: "earlier", textTruncated: false },
234 {
235 type: "assistant_message",
236 runId: "turn-1",
237 itemId: "item-9",
238 text: "Done, ",
239 textTruncated: true,
240 nextTextOffset: 6,
241 },
242 ],
243 },
244 { recentRuns: [], items: [{ text: "pushed.", textTruncated: false }] },
245 ],
246 });
247 const result = yield* Effect.provide(
248 Effect.flatMap(WorkflowAgentLinks.make, (links) =>
249 links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b"),
250 ),
251 there.layer,
252 ).pipe(Effect.raceFirst(Effect.forever(TestClock.adjust("1 second"))));
253 assert.deepStrictEqual(result, {
254 ending: "completed",
255 detail: "",
256 reply: "Done, pushed.",
257 output: { branch: "fix/1" },
258 });
259 assert.equal(there.calls.filter((call) => call.tool === "t3_thread_wait").length, 3);
260 }),
261);
262​
263it.effect("returns the whole last reply from an older page of a linked thread", () =>
264 Effect.gen(function* () {
265 const later = {
266 ...assistant(4, "turn-1", "Latest "),
267 textTruncated: true,
268 nextTextOffset: 7,
269 };
270 const { result, reads } = yield* readReply(
271 page([assistant(9, "turn-3", "newest turn")], 9),
272 page([assistant(6, "turn-2", "another turn")], 6, true),
273 page([assistant(3, "turn-1", "earlier draft"), later], 3, true),
274 page([{ ...later, text: "complete reply", textTruncated: false }]),
275 );
276 assert.deepStrictEqual(result, {
277 ending: "completed",
278 detail: "",
279 reply: "Latest complete reply",
280 });
281 assert.deepStrictEqual(reads, [
282 messageRead,
283 { ...messageRead, beforePosition: 9 },
284 { ...messageRead, beforePosition: 6 },
285 { threadId: "thread-1", itemId: "item-4", textOffset: 7, maxCharsPerItem: 50_000 },
286 ]);
287 }),
288);
289​
290it.effect("keeps the latest matching reply when paging a legacy peer forward", () =>
291 Effect.gen(function* () {
292 for (const earlierPosition of [undefined, null]) {
293 const { result, reads } = yield* readReply(
294 page([assistant(2, "turn-1", "draft")], earlierPosition, true),
295 page([assistant(4, "turn-1", "final")], earlierPosition, true),
296 page([assistant(6, "turn-2", "other turn")], earlierPosition),
297 );
298 assert.strictEqual(result.reply, "final");
299 assert.deepStrictEqual(reads, [
300 messageRead,
301 { ...messageRead, afterPosition: 2 },
302 { ...messageRead, afterPosition: 4 },
303 ]);
304 }
305 }),
306);
307​
308it.effect("keeps the reply when a legacy peer's forward cursor stops advancing", () =>
309 Effect.gen(function* () {
310 for (const position of [2, 1]) {
311 const { result, reads } = yield* readReply(
312 page([assistant(2, "turn-1", "Done.")], undefined, true),
313 page([assistant(position, "turn-2", "other turn")], undefined, true),
314 );
315 assert.strictEqual(result.reply, "Done.");
316 assert.deepStrictEqual(reads, [messageRead, { ...messageRead, afterPosition: 2 }]);
317 }
318 }),
319);
320​
321it.effect(
322 "returns an empty reply when older pages are exhausted or their cursor stops advancing",
323 () =>
324 Effect.gen(function* () {
325 for (const earlierPosition of [null, 3, 4]) {
326 const { result, reads } = yield* readReply(
327 page([assistant(3, "turn-2", "other turn")], 3),
328 page([assistant(1, "turn-0", "another turn")], earlierPosition, true),
329 );
330 assert.deepStrictEqual(result, { ending: "completed", detail: "", reply: "" });
331 assert.deepStrictEqual(reads, [messageRead, { ...messageRead, beforePosition: 3 }]);
332 }
333 }),
334);
335​
336it.effect("a turn someone stopped there is stopped, and a refused link fails at once", () =>
337 Effect.gen(function* () {
338 const stopped = peer({
339 t3_thread_wait: [{ ...waited, timedOut: false }],
340 t3_thread_read: [run("interrupted")],
341 t3_thread_interrupt: [{ threadId: "thread-1", runId: "turn-1", status: "interrupted" }],
342 });
343 const result = yield* Effect.provide(
344 Effect.flatMap(WorkflowAgentLinks.make, (links) =>
345 links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b"),
346 ),
347 stopped.layer,
348 );
349 assert.deepStrictEqual(result, { ending: "stopped", detail: "interrupted", reply: "" });
350 // Stopping names the step's turn, so a person's turn on that thread keeps going.
351 yield* Effect.provide(
352 Effect.flatMap(WorkflowAgentLinks.make, (links) =>
353 links.interrupt("thread-1", "env-b", "turn-1"),
354 ),
355 stopped.layer,
356 );
357 assert.deepInclude(stopped.calls.at(-1)?.arguments, { threadId: "thread-1", runId: "turn-1" });
358​
359 const revoked = peer({
360 t3_thread_wait: [
361 new OrchestratorMcpFailure({ code: "capability_denied", message: "link revoked" }),
362 ],
363 });
364 const error = yield* Effect.provide(
365 Effect.flatMap(WorkflowAgentLinks.make, (links) =>
366 links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b"),
367 ),
368 revoked.layer,
369 ).pipe(Effect.flip);
370 assert.match(error.reason, /link revoked/);
371 assert.equal(revoked.calls.length, 1);
372 }),
373);
374​
375it.effect("a turn that ended without its result is waited past until a later turn gives it", () =>
376 Effect.gen(function* () {
377 const there = peer({
378 t3_thread_wait: [
379 // The turn ended. The agent is waiting to be woken, and has submitted nothing.
380 { ...waited, timedOut: false },
381 // Quiet for five minutes, in pieces. A turn that woke in between is under way...
382 ...Array.from({ length: 6 }, () => ({ ...waited, timedOut: true })),
383 // ...so the wait starts over, and that turn submits.
384 { ...waited, timedOut: false, output: { head: "abc" } },
385 ],
386 t3_thread_read: [
387 run("completed"),
388 { recentRuns: [{ runId: "turn-2", status: "running" }], items: [] },
389 { recentRuns: [], hasMore: false, nextPosition: null, items: [] },
390 ],
391 });
392 const result = yield* Effect.provide(
393 Effect.flatMap(WorkflowAgentLinks.make, (links) =>
394 links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b", {
395 quiet: Duration.minutes(5),
396 }),
397 ),
398 there.layer,
399 ).pipe(Effect.raceFirst(Effect.forever(TestClock.adjust("1 second"))));
400 assert.deepStrictEqual(result.output, { head: "abc" });
401 const waits = there.calls.filter((call) => call.tool === "t3_thread_wait");
402 assert.isTrue(waits.slice(1).every((call) => call.arguments.untilOutput === true));
403 }),
404);
405​
406it.effect("a thread that stays quiet gives the turn back without a result", () =>
407 Effect.gen(function* () {
408 const there = peer({
409 t3_thread_wait: [
410 { ...waited, timedOut: false },
411 ...Array.from({ length: 6 }, () => ({ ...waited, timedOut: true })),
412 ],
413 t3_thread_read: [
414 run("completed"),
415 // Nothing has run since the turn the step knows.
416 run("completed"),
417 { recentRuns: [], hasMore: false, nextPosition: null, items: [] },
418 ],
419 });
420 const result = yield* Effect.provide(
421 Effect.flatMap(WorkflowAgentLinks.make, (links) =>
422 links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b", {
423 quiet: Duration.minutes(5),
424 }),
425 ),
426 there.layer,
427 ).pipe(Effect.raceFirst(Effect.forever(TestClock.adjust("1 second"))));
428 assert.deepStrictEqual(result, { ending: "completed", detail: "", reply: "" });
429 }),
430);