Open History to see the last commit
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;
20}
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 const there = peer({
118 t3_project_list: [{ projects: [], nextCursor: null }],
119 t3_project_create: [{ id: "p-new", workspaceRoot: "/work/app" }],
120 t3_thread_launch: [{ threadId: "thread-1", runId: "turn-1" }],
121 });
122 yield* Effect.provide(
123 Effect.flatMap(WorkflowAgentLinks.make, (links) =>
124 links.start(input, "env-b", "workflow:k", EnvironmentId.make("env-a")),
125 ),
126 there.layer,
127 );
128 assert.deepStrictEqual(
129 there.calls.map((call) => [call.tool, call.arguments.projectId ?? call.arguments.title]),
130 [
131 ["t3_project_list", undefined],
132 ["t3_project_create", "app"],
133 ["t3_thread_launch", "p-new"],
134 ],
135 );
136 }),
137);
138
139it.effect("does not start anything while linked environments is off", () =>
140 Effect.gen(function* () {
141 const there = peer({}, false);
142 const error = yield* Effect.provide(
143 Effect.flatMap(WorkflowAgentLinks.make, (links) =>
144 links.start(input, "env-b", "workflow:k", EnvironmentId.make("env-a")),
145 ),
146 there.layer,
147 ).pipe(Effect.flip);
148 assert.match(error.reason, /Linked environments is off/);
149 assert.deepStrictEqual(there.calls, []);
150 }),
151);
152
153it.effect("waits in pieces, rides out a dropped route, and returns the output and reply", () =>
154 Effect.gen(function* () {
155 const there = peer({
156 t3_thread_wait: [
157 { ...waited, timedOut: true },
158 new OrchestratorMcpFailure({ code: "orchestration_error", message: "unreachable" }),
159 { ...waited, timedOut: false, output: { branch: "fix/1" } },
160 ],
161 t3_thread_read: [
162 run("completed"),
163 {
164 recentRuns: [],
165 hasMore: false,
166 nextPosition: null,
167 items: [
168 { type: "assistant_message", runId: "turn-0", text: "earlier", textTruncated: false },
169 {
170 type: "assistant_message",
171 runId: "turn-1",
172 itemId: "item-9",
173 text: "Done, ",
174 textTruncated: true,
175 nextTextOffset: 6,
176 },
177 ],
178 },
179 { recentRuns: [], items: [{ text: "pushed.", textTruncated: false }] },
180 ],
181 });
182 const result = yield* Effect.provide(
183 Effect.flatMap(WorkflowAgentLinks.make, (links) =>
184 links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b"),
185 ),
186 there.layer,
187 ).pipe(Effect.raceFirst(Effect.forever(TestClock.adjust("1 second"))));
188 assert.deepStrictEqual(result, {
189 ending: "completed",
190 detail: "",
191 reply: "Done, pushed.",
192 output: { branch: "fix/1" },
193 });
194 assert.equal(there.calls.filter((call) => call.tool === "t3_thread_wait").length, 3);
195 }),
196);
197
198it.effect("a turn someone stopped there is stopped, and a refused link fails at once", () =>
199 Effect.gen(function* () {
200 const stopped = peer({
201 t3_thread_wait: [{ ...waited, timedOut: false }],
202 t3_thread_read: [run("interrupted")],
203 t3_thread_interrupt: [{ threadId: "thread-1", runId: "turn-1", status: "interrupted" }],
204 });
205 const result = yield* Effect.provide(
206 Effect.flatMap(WorkflowAgentLinks.make, (links) =>
207 links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b"),
208 ),
209 stopped.layer,
210 );
211 assert.deepStrictEqual(result, { ending: "stopped", detail: "interrupted", reply: "" });
212 // Stopping names the step's turn, so a person's turn on that thread keeps going.
213 yield* Effect.provide(
214 Effect.flatMap(WorkflowAgentLinks.make, (links) =>
215 links.interrupt("thread-1", "env-b", "turn-1"),
216 ),
217 stopped.layer,
218 );
219 assert.deepInclude(stopped.calls.at(-1)?.arguments, { threadId: "thread-1", runId: "turn-1" });
220
221 const revoked = peer({
222 t3_thread_wait: [
223 new OrchestratorMcpFailure({ code: "capability_denied", message: "link revoked" }),
224 ],
225 });
226 const error = yield* Effect.provide(
227 Effect.flatMap(WorkflowAgentLinks.make, (links) =>
228 links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b"),
229 ),
230 revoked.layer,
231 ).pipe(Effect.flip);
232 assert.match(error.reason, /link revoked/);
233 assert.equal(revoked.calls.length, 1);
234 }),
235);
236
237it.effect("a turn that ended without its result is waited past until a later turn gives it", () =>
238 Effect.gen(function* () {
239 const there = peer({
240 t3_thread_wait: [
241 // The turn ended. The agent is waiting to be woken, and has submitted nothing.
242 { ...waited, timedOut: false },
243 // Quiet for five minutes, in pieces. A turn that woke in between is under way...
244 ...Array.from({ length: 6 }, () => ({ ...waited, timedOut: true })),
245 // ...so the wait starts over, and that turn submits.
246 { ...waited, timedOut: false, output: { head: "abc" } },
247 ],
248 t3_thread_read: [
249 run("completed"),
250 { recentRuns: [{ runId: "turn-2", status: "running" }], items: [] },
251 { recentRuns: [], hasMore: false, nextPosition: null, items: [] },
252 ],
253 });
254 const result = yield* Effect.provide(
255 Effect.flatMap(WorkflowAgentLinks.make, (links) =>
256 links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b", {
257 quiet: Duration.minutes(5),
258 }),
259 ),
260 there.layer,
261 ).pipe(Effect.raceFirst(Effect.forever(TestClock.adjust("1 second"))));
262 assert.deepStrictEqual(result.output, { head: "abc" });
263 const waits = there.calls.filter((call) => call.tool === "t3_thread_wait");
264 assert.isTrue(waits.slice(1).every((call) => call.arguments.untilOutput === true));
265 }),
266);
267
268it.effect("a thread that stays quiet gives the turn back without a result", () =>
269 Effect.gen(function* () {
270 const there = peer({
271 t3_thread_wait: [
272 { ...waited, timedOut: false },
273 ...Array.from({ length: 6 }, () => ({ ...waited, timedOut: true })),
274 ],
275 t3_thread_read: [
276 run("completed"),
277 // Nothing has run since the turn the step knows.
278 run("completed"),
279 { recentRuns: [], hasMore: false, nextPosition: null, items: [] },
280 ],
281 });
282 const result = yield* Effect.provide(
283 Effect.flatMap(WorkflowAgentLinks.make, (links) =>
284 links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b", {
285 quiet: Duration.minutes(5),
286 }),
287 ),
288 there.layer,
289 ).pipe(Effect.raceFirst(Effect.forever(TestClock.adjust("1 second"))));
290 assert.deepStrictEqual(result, { ending: "completed", detail: "", reply: "" });
291 }),
292);