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

WorkflowAgentLinks.test.ts

488 lines17.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 restarted turn there gives the result of the turn that continued it", () =>
337 Effect.gen(function* () {
338 const there = peer({
339 t3_thread_wait: [
340 { ...waited, runId: "turn-2", status: "completed", timedOut: false, output: { pr: 7 } },
341 ],
342 t3_thread_read: [
343 {
344 recentRuns: [
345 { runId: "turn-2", status: "completed" },
346 { runId: "turn-1", status: "interrupted" },
347 ],
348 items: [],
349 },
350 page([assistant(3, "turn-2", "Done, pushed.")]),
351 ],
352 });
353 const result = yield* Effect.provide(
354 Effect.flatMap(WorkflowAgentLinks.make, (links) =>
355 links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b"),
356 ),
357 there.layer,
358 );
359 assert.deepStrictEqual(result, {
360 ending: "completed",
361 detail: "",
362 reply: "Done, pushed.",
363 output: { pr: 7 },
364 });
365 }),
366);
367​
368it.effect("a turn someone stopped there is stopped, and a refused link fails at once", () =>
369 Effect.gen(function* () {
370 const stopped = peer({
371 t3_thread_wait: [{ ...waited, timedOut: false }],
372 t3_thread_read: [run("interrupted")],
373 t3_thread_interrupt: [{ threadId: "thread-1", runId: "turn-1", status: "interrupted" }],
374 });
375 const result = yield* Effect.provide(
376 Effect.flatMap(WorkflowAgentLinks.make, (links) =>
377 links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b"),
378 ),
379 stopped.layer,
380 );
381 assert.deepStrictEqual(result, { ending: "stopped", detail: "interrupted", reply: "" });
382 // Stopping names the step's turn, so a person's turn on that thread keeps going.
383 yield* Effect.provide(
384 Effect.flatMap(WorkflowAgentLinks.make, (links) =>
385 links.interrupt("thread-1", "env-b", "turn-1"),
386 ),
387 stopped.layer,
388 );
389 assert.deepInclude(stopped.calls.at(-1)?.arguments, { threadId: "thread-1", runId: "turn-1" });
390​
391 const revoked = peer({
392 t3_thread_wait: [
393 new OrchestratorMcpFailure({ code: "capability_denied", message: "link revoked" }),
394 ],
395 });
396 const error = yield* Effect.provide(
397 Effect.flatMap(WorkflowAgentLinks.make, (links) =>
398 links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b"),
399 ),
400 revoked.layer,
401 ).pipe(Effect.flip);
402 assert.match(error.reason, /link revoked/);
403 assert.equal(revoked.calls.length, 1);
404 }),
405);
406​
407it.effect("a turn that ended without its result is waited past until a later turn gives it", () =>
408 Effect.gen(function* () {
409 const there = peer({
410 t3_thread_wait: [
411 // The turn ended. The agent is waiting to be woken, and has submitted nothing.
412 { ...waited, timedOut: false },
413 // Quiet for five minutes, in pieces. A turn that woke in between is under way...
414 ...Array.from({ length: 6 }, () => ({ ...waited, timedOut: true })),
415 // ...so the wait starts over, and that turn submits.
416 { ...waited, timedOut: false, output: { head: "abc" } },
417 ],
418 t3_thread_read: [
419 run("completed"),
420 { recentRuns: [{ runId: "turn-2", status: "running" }], items: [] },
421 { recentRuns: [], hasMore: false, nextPosition: null, items: [] },
422 ],
423 });
424 const result = yield* Effect.provide(
425 Effect.flatMap(WorkflowAgentLinks.make, (links) =>
426 links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b", {
427 quiet: Duration.minutes(5),
428 }),
429 ),
430 there.layer,
431 ).pipe(Effect.raceFirst(Effect.forever(TestClock.adjust("1 second"))));
432 assert.deepStrictEqual(result.output, { head: "abc" });
433 const waits = there.calls.filter((call) => call.tool === "t3_thread_wait");
434 assert.isTrue(waits.slice(1).every((call) => call.arguments.untilOutput === true));
435 }),
436);
437​
438it.effect("a thread that stays quiet gives the turn back without a result", () =>
439 Effect.gen(function* () {
440 const there = peer({
441 t3_thread_wait: [
442 { ...waited, timedOut: false },
443 ...Array.from({ length: 6 }, () => ({ ...waited, timedOut: true })),
444 ],
445 t3_thread_read: [
446 run("completed"),
447 // Nothing has run since the turn the step knows.
448 run("completed"),
449 { recentRuns: [], hasMore: false, nextPosition: null, items: [] },
450 ],
451 });
452 const result = yield* Effect.provide(
453 Effect.flatMap(WorkflowAgentLinks.make, (links) =>
454 links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b", {
455 quiet: Duration.minutes(5),
456 }),
457 ),
458 there.layer,
459 ).pipe(Effect.raceFirst(Effect.forever(TestClock.adjust("1 second"))));
460 assert.deepStrictEqual(result, { ending: "completed", detail: "", reply: "" });
461 }),
462);
463​
464it.effect("a cancellation stop asks once and distinguishes missing turns from link failures", () =>
465 Effect.gen(function* () {
466 const cases = [
467 { code: "thread_not_found", ended: true, final: true },
468 { code: "run_not_found", ended: true, final: true },
469 { code: "capability_denied", ended: false, final: true },
470 { code: "invalid_request", ended: false, final: true },
471 { code: "orchestration_error", ended: false, final: false },
472 ] as const;
473 for (const { code, ended, final } of cases) {
474 const there = peer({
475 t3_thread_interrupt: [new OrchestratorMcpFailure({ code, message: code })],
476 });
477 const stop = Effect.flatMap(WorkflowAgentLinks.make, (links) =>
478 links.interrupt("thread-1", "env-b", "turn-1", { once: true }),
479 ).pipe(Effect.provide(there.layer));
480 if (ended) {
481 assert.strictEqual(yield* stop, "ended");
482 } else {
483 assert.strictEqual((yield* Effect.flip(stop)).final, final);
484 }
485 assert.lengthOf(there.calls, 1);
486 }
487 }),
488);