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

WorkflowAgentLinks.test.ts

321 lines11.5 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​
62it.effect("starts a thread there by the project's folder, with the step's key as the request", () =>
63 Effect.gen(function* () {
64 const there = peer({
65 t3_project_list: [
66 { projects: [{ id: "p-other", workspaceRoot: "/work/other" }], nextCursor: 1 },
67 { projects: [{ id: "p-app", workspaceRoot: "/work/app" }], nextCursor: null },
68 ],
69 t3_thread_launch: [{ threadId: "thread-1", runId: "turn-1" }],
70 });
71 const options = {
72 workspace: { type: "worktree", baseRef: "origin/main", startFromOrigin: true },
73 runtimeMode: "auto-accept-edits",
74 } as const;
75 const [turn, continued] = yield* Effect.provide(
76 Effect.flatMap(WorkflowAgentLinks.make, (links) =>
77 Effect.all([
78 links.start(
79 { ...input, launch: options },
80 "env-b",
81 "workflow:k",
82 EnvironmentId.make("env-a"),
83 ),
84 // A thread keeps how it started.
85 links
86 .start(
87 { ...input, thread: "thread-1", launch: options },
88 "env-b",
89 "workflow:c",
90 EnvironmentId.make("env-a"),
91 )
92 .pipe(Effect.flip),
93 ]),
94 ),
95 there.layer,
96 );
97 assert.deepStrictEqual(turn, { threadId: "thread-1", turnId: "turn-1", environment: "env-b" });
98 assert.include(continued.reason, "A continued `thread` keeps how it started");
99 const launch = there.calls.at(-1);
100 assert.deepStrictEqual(launch?.arguments, {
101 projectId: "p-app",
102 title: "fix: write",
103 runtimeMode: "auto-accept-edits",
104 workspaceStrategy: { type: "worktree", baseRef: "origin/main", startFromOrigin: true },
105 message: "Write the fix.",
106 outputSchema: { type: "object" },
107 clientRequestId: "workflow:k",
108 workflowRun: { environmentId: "env-a", runId: "run-1", workflow: "fix", step: "write" },
109 });
110 // The link's own access is the ceiling, not a mode narrower than it.
111 assert.equal(launch?.runtimeMode, "full-access");
112 }),
113);
114​
115it.effect("registers a folder that is not a project there yet", () =>
116 Effect.gen(function* () {
117 for (const [project, title] of [
118 [input.project, "app"],
119 ["/work/team\\api", "team\\api"],
120 ["C:\\work\\app", "app"],
121 ]) {
122 const there = peer({
123 t3_project_list: [{ projects: [], nextCursor: null }],
124 t3_project_create: [{ id: "p-new", workspaceRoot: project }],
125 t3_thread_launch: [{ threadId: "thread-1", runId: "turn-1" }],
126 });
127 yield* Effect.provide(
128 Effect.flatMap(WorkflowAgentLinks.make, (links) =>
129 links.start({ ...input, project }, "env-b", "workflow:k", EnvironmentId.make("env-a")),
130 ),
131 there.layer,
132 );
133 assert.deepStrictEqual(
134 there.calls.map((call) => [call.tool, call.arguments.projectId ?? call.arguments.title]),
135 [
136 ["t3_project_list", undefined],
137 ["t3_project_create", title],
138 ["t3_thread_launch", "p-new"],
139 ],
140 );
141 }
142 }),
143);
144​
145it.effect("finds a Windows folder there however its separators are written", () =>
146 Effect.gen(function* () {
147 const there = peer({
148 t3_project_list: [
149 { projects: [{ id: "p-app", workspaceRoot: "C:\\work\\app" }], nextCursor: null },
150 ],
151 t3_thread_launch: [{ threadId: "thread-1", runId: "turn-1" }],
152 });
153 yield* Effect.provide(
154 Effect.flatMap(WorkflowAgentLinks.make, (links) =>
155 links.start(
156 { ...input, project: "C:/work/app" },
157 "env-b",
158 "workflow:k",
159 EnvironmentId.make("env-a"),
160 ),
161 ),
162 there.layer,
163 );
164 assert.equal(there.calls.at(-1)?.arguments.projectId, "p-app");
165 }),
166);
167​
168it.effect("does not start anything while linked environments is off", () =>
169 Effect.gen(function* () {
170 const there = peer({}, false);
171 const error = yield* Effect.provide(
172 Effect.flatMap(WorkflowAgentLinks.make, (links) =>
173 links.start(input, "env-b", "workflow:k", EnvironmentId.make("env-a")),
174 ),
175 there.layer,
176 ).pipe(Effect.flip);
177 assert.match(error.reason, /Linked environments is off/);
178 assert.deepStrictEqual(there.calls, []);
179 }),
180);
181​
182it.effect("waits in pieces, rides out a dropped route, and returns the output and reply", () =>
183 Effect.gen(function* () {
184 const there = peer({
185 t3_thread_wait: [
186 { ...waited, timedOut: true },
187 new OrchestratorMcpFailure({ code: "orchestration_error", message: "unreachable" }),
188 { ...waited, timedOut: false, output: { branch: "fix/1" } },
189 ],
190 t3_thread_read: [
191 run("completed"),
192 {
193 recentRuns: [],
194 hasMore: false,
195 nextPosition: null,
196 items: [
197 { type: "assistant_message", runId: "turn-0", text: "earlier", textTruncated: false },
198 {
199 type: "assistant_message",
200 runId: "turn-1",
201 itemId: "item-9",
202 text: "Done, ",
203 textTruncated: true,
204 nextTextOffset: 6,
205 },
206 ],
207 },
208 { recentRuns: [], items: [{ text: "pushed.", textTruncated: false }] },
209 ],
210 });
211 const result = yield* Effect.provide(
212 Effect.flatMap(WorkflowAgentLinks.make, (links) =>
213 links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b"),
214 ),
215 there.layer,
216 ).pipe(Effect.raceFirst(Effect.forever(TestClock.adjust("1 second"))));
217 assert.deepStrictEqual(result, {
218 ending: "completed",
219 detail: "",
220 reply: "Done, pushed.",
221 output: { branch: "fix/1" },
222 });
223 assert.equal(there.calls.filter((call) => call.tool === "t3_thread_wait").length, 3);
224 }),
225);
226​
227it.effect("a turn someone stopped there is stopped, and a refused link fails at once", () =>
228 Effect.gen(function* () {
229 const stopped = peer({
230 t3_thread_wait: [{ ...waited, timedOut: false }],
231 t3_thread_read: [run("interrupted")],
232 t3_thread_interrupt: [{ threadId: "thread-1", runId: "turn-1", status: "interrupted" }],
233 });
234 const result = yield* Effect.provide(
235 Effect.flatMap(WorkflowAgentLinks.make, (links) =>
236 links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b"),
237 ),
238 stopped.layer,
239 );
240 assert.deepStrictEqual(result, { ending: "stopped", detail: "interrupted", reply: "" });
241 // Stopping names the step's turn, so a person's turn on that thread keeps going.
242 yield* Effect.provide(
243 Effect.flatMap(WorkflowAgentLinks.make, (links) =>
244 links.interrupt("thread-1", "env-b", "turn-1"),
245 ),
246 stopped.layer,
247 );
248 assert.deepInclude(stopped.calls.at(-1)?.arguments, { threadId: "thread-1", runId: "turn-1" });
249​
250 const revoked = peer({
251 t3_thread_wait: [
252 new OrchestratorMcpFailure({ code: "capability_denied", message: "link revoked" }),
253 ],
254 });
255 const error = yield* Effect.provide(
256 Effect.flatMap(WorkflowAgentLinks.make, (links) =>
257 links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b"),
258 ),
259 revoked.layer,
260 ).pipe(Effect.flip);
261 assert.match(error.reason, /link revoked/);
262 assert.equal(revoked.calls.length, 1);
263 }),
264);
265​
266it.effect("a turn that ended without its result is waited past until a later turn gives it", () =>
267 Effect.gen(function* () {
268 const there = peer({
269 t3_thread_wait: [
270 // The turn ended. The agent is waiting to be woken, and has submitted nothing.
271 { ...waited, timedOut: false },
272 // Quiet for five minutes, in pieces. A turn that woke in between is under way...
273 ...Array.from({ length: 6 }, () => ({ ...waited, timedOut: true })),
274 // ...so the wait starts over, and that turn submits.
275 { ...waited, timedOut: false, output: { head: "abc" } },
276 ],
277 t3_thread_read: [
278 run("completed"),
279 { recentRuns: [{ runId: "turn-2", status: "running" }], items: [] },
280 { recentRuns: [], hasMore: false, nextPosition: null, items: [] },
281 ],
282 });
283 const result = yield* Effect.provide(
284 Effect.flatMap(WorkflowAgentLinks.make, (links) =>
285 links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b", {
286 quiet: Duration.minutes(5),
287 }),
288 ),
289 there.layer,
290 ).pipe(Effect.raceFirst(Effect.forever(TestClock.adjust("1 second"))));
291 assert.deepStrictEqual(result.output, { head: "abc" });
292 const waits = there.calls.filter((call) => call.tool === "t3_thread_wait");
293 assert.isTrue(waits.slice(1).every((call) => call.arguments.untilOutput === true));
294 }),
295);
296​
297it.effect("a thread that stays quiet gives the turn back without a result", () =>
298 Effect.gen(function* () {
299 const there = peer({
300 t3_thread_wait: [
301 { ...waited, timedOut: false },
302 ...Array.from({ length: 6 }, () => ({ ...waited, timedOut: true })),
303 ],
304 t3_thread_read: [
305 run("completed"),
306 // Nothing has run since the turn the step knows.
307 run("completed"),
308 { recentRuns: [], hasMore: false, nextPosition: null, items: [] },
309 ],
310 });
311 const result = yield* Effect.provide(
312 Effect.flatMap(WorkflowAgentLinks.make, (links) =>
313 links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b", {
314 quiet: Duration.minutes(5),
315 }),
316 ),
317 there.layer,
318 ).pipe(Effect.raceFirst(Effect.forever(TestClock.adjust("1 second"))));
319 assert.deepStrictEqual(result, { ending: "completed", detail: "", reply: "" });
320 }),
321);