Open History to see the last commit
1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { assert, it } from "@effect/vitest";
4import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
5import * as Context from "effect/Context";
6import * as Deferred from "effect/Deferred";
7import * as Effect from "effect/Effect";
8import * as Exit from "effect/Exit";
9import * as Fiber from "effect/Fiber";
10import * as FileSystem from "effect/FileSystem";
11import * as Layer from "effect/Layer";
12import * as Latch from "effect/Latch";
13import * as Option from "effect/Option";
14import * as Queue from "effect/Queue";
15import * as Path from "effect/Path";
16import * as PlatformError from "effect/PlatformError";
17import * as Stream from "effect/Stream";
18import * as TestClock from "effect/testing/TestClock";
19import { ChildProcess, ChildProcessSpawner } from "effect/process";
20
21import WorkflowsMigration from "../persistence/Migrations/110_Workflows.ts";
22import WorkflowSkippedRunsMigration from "../persistence/Migrations/113_WorkflowSkippedRuns.ts";
23import WorkflowRunTagsMigration from "../persistence/Migrations/115_WorkflowRunTags.ts";
24import WorkflowMailSenderMigration from "../persistence/Migrations/117_WorkflowMailSender.ts";
25import WorkflowPoolsMigration from "../persistence/Migrations/118_WorkflowPools.ts";
26import WorkflowRunSubjectMigration from "../persistence/Migrations/119_WorkflowRunSubject.ts";
27import WorkflowOpenedRunReceiptsMigration from "../persistence/Migrations/122_WorkflowOpenedRunReceipts.ts";
28import WorkflowRunTagIndexMigration from "../persistence/Migrations/123_WorkflowRunTagIndex.ts";
29import { type AgentResult, WorkflowAgentError, WorkflowAgents } from "./WorkflowAgents.ts";
30import * as WorkflowEngine from "./WorkflowEngine.ts";
31import * as WorkflowRuntime from "./WorkflowRuntime.ts";
32import { engineTag, type WorkflowDefinition } from "./workflow.ts";
33import * as Workflows from "./Workflows.ts";
34import * as WorkflowStore from "./WorkflowStore.ts";
35
36/** Waits to be let go. */
37const hold = `T3.workflow("hold", { version: 1, payload: Schema.Struct({}), returns: Schema.String }, () =>
38 Effect.map(T3.wait("go", { returns: Schema.String }), (said) => Option.getOrElse(said, () => "nobody")),
39);
40`;
41const greet = (says: string) => `const { workflow } = T3;
42workflow("greet", { version: 1, payload: Schema.Struct({}), returns: Schema.String }, () =>
43 Effect.succeed(${JSON.stringify(says)}),
44);
45`;
46
47/**
48 * A folder holding `hold.ts`, and the workflow runtime over it on a fresh database. `engine`
49 * stands in for the real one, which needs the clock to run for as long as it is up.
50 */
51const setup = Effect.fn("setup")(function* (
52 wrap: (
53 fileSystem: FileSystem.FileSystem,
54 folder: { readonly path: string; readonly info: FileSystem.File.Info },
55 ) => FileSystem.FileSystem = (fileSystem) => fileSystem,
56 engine?: (definitions: ReadonlyArray<WorkflowDefinition>) => Layer.Layer<Workflows.Workflows>,
57 agents?: WorkflowAgents["Service"],
58 store?: typeof WorkflowStore.layer,
59) {
60 const fileSystem = yield* FileSystem.FileSystem;
61 const path = yield* Path.Path;
62 const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-workflow-defs-" });
63 const directory = path.join(home, "workflows");
64 const at = (name: string) => path.join(directory, name);
65 yield* fileSystem.makeDirectory(directory);
66 yield* fileSystem.writeFileString(at("hold.ts"), hold);
67 const database = NodeSqliteClient.layer({ filename: path.join(home, "state.sqlite") });
68 yield* Effect.provide(
69 Effect.andThen(WorkflowsMigration, WorkflowSkippedRunsMigration).pipe(
70 Effect.andThen(WorkflowRunTagsMigration),
71 Effect.andThen(WorkflowMailSenderMigration),
72 Effect.andThen(WorkflowPoolsMigration),
73 Effect.andThen(WorkflowRunSubjectMigration),
74 Effect.andThen(WorkflowOpenedRunReceiptsMigration),
75 Effect.andThen(WorkflowRunTagIndexMigration),
76 ),
77 database,
78 );
79 const folder = { path: directory, info: yield* fileSystem.stat(directory) };
80 const made = WorkflowRuntime.make(
81 Effect.succeed(
82 (definitions: ReadonlyArray<WorkflowDefinition>) =>
83 engine?.(definitions) ??
84 WorkflowEngine.layer(definitions, store).pipe(
85 Layer.provide(
86 agents === undefined
87 ? Layer.mock(WorkflowAgents)({})
88 : Layer.succeed(WorkflowAgents, agents),
89 ),
90 Layer.provide(database),
91 Layer.provide(NodeCrypto.layer),
92 ),
93 ),
94 directory,
95 Effect.succeed(true),
96 ).pipe(Effect.provideService(FileSystem.FileSystem, wrap(fileSystem, folder)));
97 return { fileSystem, at, directory, made, runtime: Layer.effectContext(made) };
98});
99
100it.effect(
101 "every file in the folder defines workflows, and a saved file is verified before it runs",
102 () =>
103 Effect.gen(function* () {
104 const changed = yield* Queue.unbounded<FileSystem.WatchEvent>();
105 const { fileSystem, at, runtime } = yield* setup((fileSystem) => ({
106 ...fileSystem,
107 watch: () => Stream.fromQueue(changed),
108 }));
109 const writeOutside = (name: string, contents: string) =>
110 fileSystem
111 .writeFileString(at(name), contents)
112 .pipe(Effect.andThen(Queue.offer(changed, { _tag: "Update", path: at(name) })));
113
114 yield* Effect.gen(function* () {
115 const workflows = yield* Workflows.Workflows;
116 const definitions = yield* WorkflowRuntime.WorkflowDefinitions;
117 const held = yield* workflows.start("hold", {}, { idempotencyKey: "h" });
118 yield* workflows.waitFor(held.runId, (run) => run.status === "waiting");
119
120 // A file that does not parse is not written, and says where it breaks.
121 const broken = yield* definitions.save("greet.ts", "T3.workflow(\n 'x',\n];\n");
122 assert.isFalse(broken.changed);
123 assert.deepStrictEqual(
124 broken.problems.map((problem) => [problem.file, problem.line]),
125 [["greet.ts", 3]],
126 );
127 // Nor is one that defines what another file already does, or drops what a run needs.
128 const twice = yield* definitions.save("again.ts", hold);
129 assert.include(
130 twice.problems[0]?.message ?? "",
131 "hold@1 is defined twice, in again.ts and hold.ts",
132 );
133 const dropped = yield* definitions.save("hold.ts", greet("hello"));
134 assert.include(
135 dropped.problems[0]?.message ?? "",
136 "hold@1 is no longer defined, and 1 of its runs",
137 );
138 // Nor one that exports something shaped like a workflow without what the engine walks.
139 const shaped = yield* definitions.save(
140 "shaped.ts",
141 'export default [{ name: "shaped", version: 1, body: () => Effect.void }];\n',
142 );
143 assert.include(shaped.problems[0]?.message ?? "", "is not a workflow");
144 // Nor one with an option nothing reads, or a time a schedule cannot fire at.
145 const misspelt = yield* definitions.save(
146 "misspelt.ts",
147 'T3.workflow("misspelt", { version: 1, payload: Schema.Struct({}), retries: 2 }, () => Effect.void);\n',
148 );
149 assert.include(misspelt.problems[0]?.message ?? "", "does not take `retries`");
150 const late = yield* definitions.save(
151 "late.ts",
152 'T3.workflow("late", { version: 1, payload: T3.Tick, triggers: [T3.daily("9am")] }, () => Effect.void);\n',
153 );
154 assert.include(late.problems[0]?.message ?? "", "24-hour time");
155 const banana = yield* definitions.save(
156 "banana.ts",
157 'T3.workflow("banana", { version: 1, payload: T3.Tick, triggers: [T3.every("banana")] }, () => Effect.void);\n',
158 );
159 assert.include(banana.problems[0]?.message ?? "", 'Write one such as "5 minutes"');
160 const twoHooks = yield* definitions.save(
161 "hooks.ts",
162 'T3.workflow("hooks", { version: 1, payload: T3.WebhookRequest, triggers: [T3.webhook("in"), T3.webhook("in")] }, () => Effect.void);\n',
163 );
164 assert.include(twoHooks.problems[0]?.message ?? "", 'two hooks named "in"');
165 assert.include((yield* definitions.remove("hold.ts")).problems[0]?.message ?? "", "hold@1");
166 assert.deepStrictEqual(
167 (yield* definitions.read).files.map((file) => file.name),
168 ["hold.ts"],
169 );
170 // The same change made outside the app is refused as a whole: the file still reads as the
171 // version that runs, until it is put back.
172 const told = (wanted: boolean) =>
173 Workflows.wholeLists(workflows.watch).pipe(
174 Stream.filter((snapshot) => (snapshot.definition?.problem != null) === wanted),
175 Stream.runHead,
176 );
177 yield* writeOutside("hold.ts", greet("hello"));
178 yield* told(true);
179 assert.deepStrictEqual(
180 (yield* definitions.read).files.map((file) => file.workflows),
181 [["hold@1"]],
182 );
183 // Only that file is held back: another file's change still runs, and the held one says why.
184 const other =
185 'T3.workflow("other", { version: 1, payload: Schema.Struct({}) }, () => Effect.void);\n';
186 // A file the folder's naming leaves out says so, instead of never running without a word.
187 yield* fileSystem.writeFileString(at("my flow.ts"), other);
188 assert.deepStrictEqual(yield* definitions.save("other.ts", other), {
189 changed: true,
190 problems: [],
191 });
192 yield* workflows.start("other", {}, { idempotencyKey: "o" });
193 assert.deepStrictEqual(
194 (yield* definitions.read).files.map((file) => [file.name, file.problems.length]),
195 [
196 ["hold.ts", 1],
197 ["other.ts", 0],
198 ],
199 );
200 assert.deepStrictEqual(
201 (yield* definitions.read).problems.map((problem) => problem.file),
202 ["my flow.ts"],
203 );
204 yield* fileSystem.remove(at("my flow.ts"));
205 assert.deepStrictEqual(yield* definitions.remove("other.ts"), {
206 changed: true,
207 problems: [],
208 });
209 yield* writeOutside("hold.ts", hold);
210 yield* told(false);
211
212 // A new file that passes is there from now on, and what it defines can be started.
213 const saved = { changed: true, problems: [] };
214 assert.deepStrictEqual(yield* definitions.save("greet.ts", greet("hello")), saved);
215 assert.equal(yield* fileSystem.readFileString(at("greet.ts")), greet("hello"));
216 const greeted = yield* workflows.start("greet", {}, { idempotencyKey: "g" });
217 const done = yield* workflows.waitFor(greeted.runId, (run) => run.status === "completed");
218 assert.equal(done.result, "hello");
219 // The run that was waiting came through the reload and can still be let go.
220 yield* workflows.signal({ runId: held.runId, wait: "go" }, "go on", { id: "s1" });
221 const freed = yield* workflows.waitFor(held.runId, (run) => run.status === "completed");
222 assert.equal(freed.result, "go on");
223
224 // Someone breaks a file outside the app: its last good version keeps running, and the
225 // other files go on changing.
226 const problem = (wanted: boolean) =>
227 Workflows.wholeLists(workflows.watch).pipe(
228 Stream.filter((snapshot) => (snapshot.definition?.problem != null) === wanted),
229 Stream.runHead,
230 );
231 yield* writeOutside("greet.ts", "T3.workflow(");
232 yield* problem(true);
233 const read = yield* definitions.read;
234 assert.deepStrictEqual(
235 read.files.map((file) => [file.name, file.problems.length]),
236 [
237 ["greet.ts", 1],
238 ["hold.ts", 0],
239 ],
240 );
241 const still = yield* workflows.start("greet", {}, { idempotencyKey: "g2" });
242 assert.equal(
243 (yield* workflows.waitFor(still.runId, (run) => run.status === "completed")).result,
244 "hello",
245 );
246 // And fixes it, saying something else, this time as the file's one default export.
247 yield* writeOutside(
248 "greet.ts",
249 greet("hi").replace("\nworkflow(", "\nexport default workflow("),
250 );
251 yield* problem(false);
252 const fixed = yield* workflows.start("greet", {}, { idempotencyKey: "g3" });
253 assert.equal(
254 (yield* workflows.waitFor(fixed.runId, (run) => run.status === "completed")).result,
255 "hi",
256 );
257 // A file taken away takes its workflows with it.
258 assert.deepStrictEqual(yield* definitions.remove("greet.ts"), saved);
259 const gone = yield* workflows
260 .start("greet", {}, { idempotencyKey: "g4" })
261 .pipe(Effect.flip);
262 assert.equal(gone._tag, "WorkflowNotRegisteredError");
263 // With no file left, nothing runs, and the runs that ended can still be read.
264 assert.deepStrictEqual(yield* definitions.remove("hold.ts"), saved);
265 assert.equal((yield* workflows.get(held.runId)).run.status, "completed");
266 assert.includeMembers(
267 (yield* workflows.list()).map((run) => run.runId),
268 [held.runId, greeted.runId],
269 );
270 }).pipe(
271 Effect.provide(runtime),
272 Effect.scoped,
273 Effect.raceFirst(Effect.forever(TestClock.adjust("1 second"))),
274 );
275 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
276);
277
278it.effect(
279 "a folder that cannot be listed keeps its workflows and is looked at again, and an engine that cannot start leaves the last one running",
280 () =>
281 Effect.gen(function* () {
282 let refuse = false;
283 // What each engine was built to run. One that registers `broken` does not come up.
284 const builds: Array<ReadonlyArray<string>> = [];
285 // No file events: only the runtime's own retry can pick up what changed.
286 const { at, fileSystem, runtime } = yield* setup(
287 (real) => ({
288 ...real,
289 exists: (target) =>
290 refuse
291 ? Effect.fail(
292 PlatformError.systemError({
293 _tag: "PermissionDenied",
294 module: "FileSystem",
295 method: "exists",
296 pathOrDescriptor: target,
297 }),
298 )
299 : real.exists(target),
300 watch: () => Stream.never,
301 }),
302 (definitions) =>
303 definitions.some((definition) => definition.name === "broken")
304 ? Layer.effect(Workflows.Workflows, Effect.die(new Error("broken took it down")))
305 : Layer.sync(Workflows.Workflows, () => {
306 builds.push(definitions.map(engineTag));
307 return Workflows.disabled;
308 }),
309 );
310
311 yield* Effect.gen(function* () {
312 const workflows = yield* Workflows.Workflows;
313 const definitions = yield* WorkflowRuntime.WorkflowDefinitions;
314 const revision = Effect.map(
315 Stream.runHead(Workflows.wholeLists(workflows.watch)),
316 (snapshot) => Option.getOrThrow(snapshot).definition?.revision ?? 0,
317 );
318 refuse = true;
319 // Written, but the folder could not be listed, so it is not said to run.
320 const unlisted = yield* definitions.save("greet.ts", greet("hi"));
321 assert.isTrue(unlisted.changed);
322 assert.include(unlisted.problems[0]?.message ?? "", "could not be read");
323 // What was loaded stays, and greet is not taken in yet.
324 assert.deepStrictEqual(builds, [["hold@1"]]);
325 const before = yield* revision;
326 refuse = false;
327 yield* TestClock.adjust("30 seconds");
328 yield* Workflows.wholeLists(workflows.watch).pipe(
329 Stream.filter((snapshot) => (snapshot.definition?.revision ?? 0) > before),
330 Stream.runHead,
331 );
332 assert.deepStrictEqual(builds.at(-1), ["greet@1", "hold@1"]);
333
334 // A definition that passes the checks but takes the engine down at start changes nothing.
335 yield* fileSystem.writeFileString(
336 at("broken.ts"),
337 'T3.workflow("broken", { version: 1, payload: Schema.Struct({}) }, () => Effect.void);\n',
338 );
339 const fellBack = yield* definitions.save("greet.ts", greet("hello"));
340 assert.isTrue(fellBack.changed);
341 assert.include(fellBack.problems[0]?.message ?? "", "did not start");
342 assert.deepStrictEqual(builds.slice(1), [
343 ["greet@1", "hold@1"],
344 ["greet@1", "hold@1"],
345 ]);
346 assert.include(
347 (yield* Stream.runHead(Workflows.wholeLists(workflows.watch))).pipe(Option.getOrThrow)
348 .definition?.problem ?? "",
349 "did not start",
350 );
351 }).pipe(Effect.provide(runtime), Effect.scoped);
352 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
353);
354
355it.effect("a file that never finishes loading is given up on, and later files still load", () =>
356 Effect.gen(function* () {
357 const { at, fileSystem } = yield* setup();
358 yield* fileSystem.writeFileString(at("stuck.ts"), "await new Promise(() => {});\n");
359 yield* fileSystem.writeFileString(at("greet.ts"), greet("hi"));
360 const stuck = yield* WorkflowRuntime.loadDefinitions(at("stuck.ts"), 0, 50).pipe(Effect.flip);
361 assert.include(String(stuck.cause), "did not finish loading");
362 const loaded = yield* WorkflowRuntime.loadDefinitions(at("greet.ts"));
363 assert.deepStrictEqual(
364 loaded.map((definition) => definition.name),
365 ["greet"],
366 );
367 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
368);
369
370it.effect("a file loads whatever kinds its asks name, and only a malformed `asks` is refused", () =>
371 Effect.gen(function* () {
372 const { at, fileSystem } = yield* setup();
373 const sorter = (asks: string) => `const { workflow, ask } = T3;
374workflow("sorter", { version: 1, payload: Schema.Struct({})${asks} }, () =>
375 ask("sort", { kind: "feture", title: "Which way?", choices: ["Yes", "No"] }),
376);
377`;
378 // A kind the workflow does not declare, and one on a workflow that declares none.
379 for (const asks of [', asks: { feature: "Feature wanted?" }', ""]) {
380 yield* fileSystem.writeFileString(at("sorter.ts"), sorter(asks));
381 const loaded = yield* WorkflowRuntime.loadDefinitions(at("sorter.ts"), asks.length);
382 assert.deepStrictEqual(
383 loaded.map((definition) => Object.keys(definition.asks)),
384 [asks === "" ? [] : ["feature"]],
385 );
386 }
387 yield* fileSystem.writeFileString(at("sorter.ts"), sorter(', asks: { feature: "" }'));
388 const refused = yield* WorkflowRuntime.loadDefinitions(at("sorter.ts"), 1).pipe(Effect.flip);
389 assert.include(String(refused.cause), 'asks gives the kind "feature" no label');
390 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
391);
392
393it.effect("a file given up on registers nothing into the file that loads after it", () =>
394 Effect.gen(function* () {
395 const { at, fileSystem } = yield* setup();
396 yield* fileSystem.writeFileString(
397 at("slow.ts"),
398 'await new Promise((resolve) => { globalThis.t3TestResume = resolve; });\nT3.workflow("slow", { version: 1, payload: Schema.Struct({}) }, () => Effect.void);\n',
399 );
400 // The second file goes on loading until the first one's top level has run to its end.
401 yield* fileSystem.writeFileString(
402 at("next.ts"),
403 `${greet("hi")}globalThis.t3TestResume();\nawait new Promise((resolve) => setImmediate(resolve));\n`,
404 );
405 yield* WorkflowRuntime.loadDefinitions(at("slow.ts"), 0, 50).pipe(Effect.flip);
406 const loaded = yield* WorkflowRuntime.loadDefinitions(at("next.ts"));
407 assert.deepStrictEqual(
408 loaded.map((definition) => definition.name),
409 ["greet"],
410 );
411 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
412);
413
414// Vitest's module runner loads a file its own way; only Node keeps a CommonJS file by its path.
415it.live("a file without imports or exports loads again after it changes", () =>
416 Effect.gen(function* () {
417 const { at, fileSystem } = yield* setup();
418 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
419 yield* fileSystem.writeFileString(at("greet.ts"), greet("hi"));
420 const twice = `
421 import * as NodeFS from "node:fs";
422 import * as NodeServices from "@effect/platform-node/NodeServices";
423 import * as Context from "effect/Context";
424import * as Effect from "effect/Effect";
425 import { loadDefinitions } from ${JSON.stringify(new URL("./WorkflowRuntime.ts", import.meta.url).href)};
426 const file = process.argv.at(-1);
427 const program = Effect.gen(function* () {
428 const first = yield* loadDefinitions(file, 1);
429 NodeFS.writeFileSync(file, NodeFS.readFileSync(file, "utf8").replace('"hi"', '"hello"'));
430 const second = yield* loadDefinitions(file, 2);
431 return [first.length, second.length];
432 });
433 console.log(JSON.stringify(await Effect.runPromise(Effect.provide(program, NodeServices.layer))));
434 `;
435 const child = yield* spawner.spawn(
436 ChildProcess.make(
437 process.execPath,
438 ["--input-type=module", "--eval", twice, at("greet.ts")],
439 { cwd: import.meta.dirname },
440 ),
441 );
442 const [stdout, stderr] = yield* Effect.all(
443 [
444 child.stdout.pipe(Stream.decodeText(), Stream.mkString),
445 child.stderr.pipe(Stream.decodeText(), Stream.mkString),
446 ],
447 { concurrency: "unbounded" },
448 );
449 assert.equal(stdout.trim(), "[1,1]", stderr);
450 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
451);
452
453// Node keeps an imported module by its address, so a helper the file imports must load again too.
454it.live("a file loads again with the current version of the helpers it imports", () =>
455 Effect.gen(function* () {
456 const { at, fileSystem } = yield* setup();
457 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
458 yield* fileSystem.writeFileString(at("_helpers.ts"), 'export const x = "old";\n');
459 yield* fileSystem.writeFileString(
460 at("demo.ts"),
461 'import { x } from "./_helpers.ts";\nT3.workflow("demo", { version: 1, payload: Schema.Struct({}), returns: Schema.String }, () => Effect.succeed(x));\n',
462 );
463 const twice = `
464 import * as NodeFS from "node:fs";
465 import * as NodePath from "node:path";
466 import * as NodeServices from "@effect/platform-node/NodeServices";
467 import * as Effect from "effect/Effect";
468 import { loadDefinitions } from ${JSON.stringify(new URL("./WorkflowRuntime.ts", import.meta.url).href)};
469 const file = process.argv.at(-1);
470 const helpers = NodePath.join(NodePath.dirname(file), "_helpers.ts");
471 const program = Effect.gen(function* () {
472 const first = yield* loadDefinitions(file, 1);
473 NodeFS.writeFileSync(helpers, 'export const x = "new";\\nexport const y = "added";\\n');
474 NodeFS.writeFileSync(file, NodeFS.readFileSync(file, "utf8").replace("{ x }", "{ x, y }").replace("version: 1", "version: 2"));
475 const second = yield* loadDefinitions(file, 2).pipe(
476 Effect.map((loaded) => loaded.map((definition) => definition.version)),
477 Effect.catchCause((cause) => Effect.succeed(String(cause))),
478 );
479 return [first.map((definition) => definition.version), second];
480 });
481 console.log(JSON.stringify(await Effect.runPromise(Effect.provide(program, NodeServices.layer))));
482 `;
483 const child = yield* spawner.spawn(
484 ChildProcess.make(process.execPath, ["--input-type=module", "--eval", twice, at("demo.ts")], {
485 cwd: import.meta.dirname,
486 }),
487 );
488 const [stdout, stderr] = yield* Effect.all(
489 [
490 child.stdout.pipe(Stream.decodeText(), Stream.mkString),
491 child.stderr.pipe(Stream.decodeText(), Stream.mkString),
492 ],
493 { concurrency: "unbounded" },
494 );
495 assert.equal(stdout.trim(), "[[1],[2]]", stderr);
496 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
497);
498
499it.live("a rescan takes a helper edit when the file that imports it is unchanged", () =>
500 Effect.gen(function* () {
501 const { at, directory, fileSystem } = yield* setup();
502 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
503 yield* fileSystem.remove(at("hold.ts"));
504 yield* fileSystem.writeFileString(at("_helpers.ts"), "export const version = 1;\n");
505 const demo =
506 'import { version } from "./_helpers.ts";\nT3.workflow("demo", { version, payload: Schema.Struct({}), returns: Schema.String }, () => Effect.succeed("x"));\n';
507 yield* fileSystem.writeFileString(at("demo.ts"), demo);
508 const rescan = `
509 import * as NodeFS from "node:fs";
510 import * as NodePath from "node:path";
511 import * as NodeServices from "@effect/platform-node/NodeServices";
512 import * as Context from "effect/Context";
513 import * as Effect from "effect/Effect";
514 import * as Layer from "effect/Layer";
515 import * as WorkflowRuntime from ${JSON.stringify(new URL("./WorkflowRuntime.ts", import.meta.url).href)};
516 import * as Workflows from ${JSON.stringify(new URL("./Workflows.ts", import.meta.url).href)};
517 const directory = process.argv.at(-2);
518 const demo = process.argv.at(-1);
519 const builds = [];
520 const program = Effect.gen(function* () {
521 const context = yield* WorkflowRuntime.make(
522 Effect.succeed((definitions) =>
523 Layer.sync(Workflows.Workflows, () => {
524 builds.push(definitions.map((definition) => definition.version));
525 return Workflows.disabled;
526 }),
527 ),
528 directory,
529 Effect.succeed(true),
530 );
531 NodeFS.writeFileSync(NodePath.join(directory, "_helpers.ts"), "export const version = 2;\\n");
532 const saved = yield* Context.get(context, WorkflowRuntime.WorkflowDefinitions).save("demo.ts", demo);
533 return { problems: saved.problems, builds };
534 });
535 console.log(JSON.stringify(await Effect.runPromise(Effect.scoped(Effect.provide(program, NodeServices.layer)))));
536 process.exit(0);
537 `;
538 const child = yield* spawner.spawn(
539 ChildProcess.make(
540 process.execPath,
541 ["--input-type=module", "--eval", rescan, directory, demo],
542 { cwd: import.meta.dirname },
543 ),
544 );
545 const [stdout, stderr] = yield* Effect.all(
546 [
547 child.stdout.pipe(Stream.decodeText(), Stream.mkString),
548 child.stderr.pipe(Stream.decodeText(), Stream.mkString),
549 ],
550 { concurrency: "unbounded" },
551 );
552 // Logs share stdout, so the result is its last line.
553 const { problems, builds } = JSON.parse(stdout.trim().split("\n").at(-1) || "{}");
554 assert.deepStrictEqual(problems, [], stderr);
555 assert.deepStrictEqual(builds?.at(-1), [2], stderr);
556 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
557);
558
559it.live("the folder watch reloads a workflow when only a helper in a subfolder changes", () =>
560 Effect.gen(function* () {
561 const { at, directory, fileSystem } = yield* setup();
562 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
563 yield* fileSystem.remove(at("hold.ts"));
564 yield* fileSystem.makeDirectory(at("helpers"));
565 yield* fileSystem.writeFileString(at("helpers/version.ts"), "export const version = 1;\n");
566 yield* fileSystem.writeFileString(
567 at("demo.ts"),
568 'import { version } from "./helpers/version.ts";\nT3.workflow("demo", { version, payload: Schema.Struct({}), returns: Schema.String }, () => Effect.succeed("x"));\n',
569 );
570 const watched = `
571 import * as NodeFS from "node:fs";
572 import * as NodePath from "node:path";
573 import * as NodeServices from "@effect/platform-node/NodeServices";
574 import * as Effect from "effect/Effect";
575 import * as Layer from "effect/Layer";
576 import * as WorkflowRuntime from ${JSON.stringify(new URL("./WorkflowRuntime.ts", import.meta.url).href)};
577 import * as Workflows from ${JSON.stringify(new URL("./Workflows.ts", import.meta.url).href)};
578 const directory = process.argv.at(-1);
579 const builds = [];
580 let waiting;
581 const built = (tag) =>
582 new Promise((resolve) => {
583 waiting = { tag, resolve };
584 setTimeout(resolve, 15_000);
585 });
586 const program = Effect.gen(function* () {
587 yield* WorkflowRuntime.make(
588 Effect.succeed((definitions) =>
589 Layer.sync(Workflows.Workflows, () => {
590 const tags = definitions.map((definition) => definition.name + "@" + definition.version);
591 builds.push(tags);
592 if (waiting !== undefined && tags.includes(waiting.tag)) waiting.resolve();
593 return Workflows.disabled;
594 }),
595 ),
596 directory,
597 Effect.succeed(true),
598 );
599 // Only the watch loads a new file, so once it runs the watch is live.
600 const live = built("ready@1");
601 NodeFS.writeFileSync(
602 NodePath.join(directory, "ready.ts"),
603 'T3.workflow("ready", { version: 1, payload: Schema.Struct({}), returns: Schema.String }, () => Effect.succeed("x"));\\n',
604 );
605 yield* Effect.promise(() => live);
606 const reloaded = built("demo@2");
607 NodeFS.writeFileSync(NodePath.join(directory, "helpers", "version.ts"), "export const version = 2;\\n");
608 yield* Effect.promise(() => reloaded);
609 return builds;
610 });
611 console.log(JSON.stringify(await Effect.runPromise(Effect.scoped(Effect.provide(program, NodeServices.layer)))));
612 process.exit(0);
613 `;
614 const child = yield* spawner.spawn(
615 ChildProcess.make(process.execPath, ["--input-type=module", "--eval", watched, directory], {
616 cwd: import.meta.dirname,
617 }),
618 );
619 const [stdout, stderr] = yield* Effect.all(
620 [
621 child.stdout.pipe(Stream.decodeText(), Stream.mkString),
622 child.stderr.pipe(Stream.decodeText(), Stream.mkString),
623 ],
624 { concurrency: "unbounded" },
625 );
626 // Logs share stdout, so the result is its last line.
627 const builds = JSON.parse(stdout.trim().split("\n").at(-1) || "[]");
628 assert.deepStrictEqual(builds.at(-1), ["demo@2", "ready@1"], stderr);
629 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
630);
631
632it.effect("loads a workflow edited on disk after the folder watch recovers", () =>
633 Effect.gen(function* () {
634 const lost = yield* Deferred.make<void>();
635 let attempts = 0;
636 const { fileSystem, at, runtime } = yield* setup(
637 (real, folder) => ({
638 ...real,
639 // The once-a-second probe that reopens the watch must not wait on real I/O: the test
640 // clock moves on without it, and the probe's next tick would never come.
641 stat: (entry) => (entry === folder.path ? Effect.succeed(folder.info) : real.stat(entry)),
642 readLink: (entry) =>
643 entry === folder.path
644 ? Effect.fail(
645 PlatformError.systemError({
646 _tag: "InvalidData",
647 module: "FileSystem",
648 method: "readLink",
649 pathOrDescriptor: entry,
650 }),
651 )
652 : real.readLink(entry),
653 watch: (directory, options) =>
654 Stream.unwrap(
655 Effect.suspend(() => {
656 if (++attempts > 1)
657 return Effect.succeed(
658 Stream.never.pipe(Stream.onStart(Effect.sync(() => options?.onReady?.()))),
659 );
660 return Effect.as(
661 Deferred.succeed(lost, undefined),
662 Stream.fail(
663 PlatformError.systemError({
664 _tag: "NotFound",
665 module: "FileSystem",
666 method: "watch",
667 pathOrDescriptor: directory,
668 }),
669 ),
670 );
671 }),
672 ),
673 }),
674 () => Layer.succeed(Workflows.Workflows, Workflows.disabled),
675 );
676 yield* Effect.gen(function* () {
677 const definitions = yield* WorkflowRuntime.WorkflowDefinitions;
678 const workflows = yield* Workflows.Workflows;
679 const before = (yield* definitions.read).revision;
680 yield* Deferred.await(lost);
681 yield* fileSystem.writeFileString(at("greet.ts"), greet("hello"));
682 // Recovery probes the folder with real I/O between ticks, so one big adjust can end before
683 // the next tick or the reload's debounce is waiting on the clock.
684 yield* Workflows.wholeLists(workflows.watch).pipe(
685 Stream.filter((snapshot) => (snapshot.definition?.revision ?? 0) > before),
686 Stream.runHead,
687 Effect.raceFirst(Effect.forever(TestClock.adjust("1 second"))),
688 );
689 const loaded = (yield* definitions.read).files.find((file) => file.name === "greet.ts");
690 assert.deepStrictEqual(loaded?.workflows, ["greet@1"]);
691 }).pipe(Effect.provide(runtime), Effect.scoped);
692 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
693);
694
695it.effect("a change held back by a run goes in once that run ends, with no further edit", () =>
696 Effect.gen(function* () {
697 // The folder's changes are told by hand, so the test does not hang on a watcher starting.
698 const changed = yield* Queue.unbounded<FileSystem.WatchEvent>();
699 const { fileSystem, at, runtime } = yield* setup((fileSystem) => ({
700 ...fileSystem,
701 watch: () => Stream.fromQueue(changed),
702 }));
703 yield* Effect.gen(function* () {
704 const workflows = yield* Workflows.Workflows;
705 const definitions = yield* WorkflowRuntime.WorkflowDefinitions;
706 const held = yield* workflows.start("hold", {}, { idempotencyKey: "h" });
707 yield* workflows.waitFor(held.runId, (run) => run.status === "waiting");
708 const problem = (wanted: boolean) =>
709 Workflows.wholeLists(workflows.watch).pipe(
710 Stream.filter((snapshot) => (snapshot.definition?.problem != null) === wanted),
711 Stream.runHead,
712 );
713 yield* fileSystem.writeFileString(at("hold.ts"), greet("hello"));
714 yield* Queue.offer(changed, { _tag: "Update", path: at("hold.ts") });
715 yield* problem(true);
716 yield* workflows.signal({ runId: held.runId, wait: "go" }, "go on", { id: "s1" });
717 yield* workflows.waitFor(held.runId, (run) => run.status === "completed");
718 // Nothing is told of the folder now: the held change goes in on its own.
719 yield* problem(false);
720 assert.deepStrictEqual(
721 (yield* definitions.read).files.map((file) => file.workflows),
722 [["greet@1"]],
723 );
724 }).pipe(
725 Effect.provide(runtime),
726 Effect.scoped,
727 Effect.raceFirst(Effect.forever(TestClock.adjust("1 second"))),
728 );
729 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
730);
731
732it.effect(
733 "a reload does not wait for an agent that is still at work, and its step ends with the turn",
734 () =>
735 Effect.gen(function* () {
736 const ended = yield* Deferred.make<AgentResult>();
737 const started = yield* Deferred.make<void>();
738 const { fileSystem, at, runtime } = yield* setup(undefined, undefined, {
739 start: (input) =>
740 Effect.as(Deferred.succeed(started, undefined), {
741 threadId: "thread",
742 turnId: input.key,
743 }),
744 result: () => Deferred.await(ended),
745 interrupt: () => Effect.succeed("stopped" as const),
746 });
747 yield* fileSystem.writeFileString(
748 at("helper.ts"),
749 `T3.workflow("helper", { version: 1, payload: Schema.Struct({}), returns: Schema.String }, () =>
750 Effect.map(T3.agent("work", { brief: "Do it.", project: "p" }), (done) => done.value),
751);
752`,
753 );
754 const ticking = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
755 Effect.raceFirst(effect, Effect.forever(TestClock.adjust("1 second")));
756 yield* Effect.gen(function* () {
757 const workflows = yield* Workflows.Workflows;
758 const definitions = yield* WorkflowRuntime.WorkflowDefinitions;
759 const helped = yield* ticking(
760 Effect.gen(function* () {
761 const run = yield* workflows.start("helper", {}, { idempotencyKey: "a" });
762 yield* Deferred.await(started);
763 yield* workflows.waitFor(run.runId, (row) => row.status === "waiting");
764 return run;
765 }),
766 );
767
768 // The test clock stands still during the save, so an engine that waited for the agent's
769 // step to finish would never stop: the step is not given up on, and the turn does not end.
770 // The swap cannot be interrupted, so a stuck save is unblocked by ending the turn.
771 const saving = yield* Effect.forkChild(definitions.save("greet.ts", greet("hello")));
772 const saved = yield* Fiber.await(saving).pipe(
773 Effect.timeoutOption("10 seconds"),
774 TestClock.withLive,
775 );
776 if (Option.isNone(saved)) {
777 yield* Deferred.succeed(ended, { ending: "completed", detail: "", reply: "late" });
778 yield* ticking(Fiber.await(saving));
779 assert.fail("The reload waited for the agent's turn to end.");
780 }
781 assert.isTrue(Exit.isSuccess(saved.value) && saved.value.value.changed);
782 assert.equal((yield* workflows.get(helped.runId)).run.status, "waiting");
783
784 // The turn ends after the reload, and the new engine carries its result into the run.
785 yield* Deferred.succeed(ended, { ending: "completed", detail: "", reply: "all done" });
786 const done = yield* ticking(
787 workflows.waitFor(helped.runId, (run) => run.status === "completed"),
788 );
789 assert.equal(done.result, "all done");
790 }).pipe(Effect.provide(runtime), Effect.scoped);
791 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
792);
793
794it.effect("cancellation stops linked launches and corrections acknowledged late", () =>
795 Effect.gen(function* () {
796 for (const late of ["work/0", "work/0/correct/0"]) {
797 const started = yield* Deferred.make<void>();
798 const reply = yield* Deferred.make<void>();
799 const recorded = yield* Deferred.make<void>();
800 const stops: Array<Parameters<WorkflowAgents["Service"]["interrupt"]>[0]> = [];
801 const store = Layer.effect(
802 WorkflowStore.WorkflowStore,
803 Effect.map(WorkflowStore.make, (real) =>
804 WorkflowStore.WorkflowStore.of({
805 ...real,
806 stepThread: (...args) =>
807 real
808 .stepThread(...args)
809 .pipe(
810 Effect.tap(() =>
811 args[4].endsWith(`/${late}`)
812 ? Deferred.succeed(recorded, undefined)
813 : Effect.void,
814 ),
815 ),
816 }),
817 ),
818 );
819 const { fileSystem, at, runtime } = yield* setup(
820 undefined,
821 undefined,
822 {
823 start: (input) =>
824 (input.key.endsWith(`/${late}`)
825 ? Deferred.succeed(started, undefined).pipe(Effect.andThen(Deferred.await(reply)))
826 : Effect.void
827 ).pipe(Effect.as({ threadId: "thread", environment: "env-b", turnId: input.key })),
828 result: () => Effect.succeed({ ending: "completed", detail: "", reply: "" }),
829 interrupt: (turn) =>
830 Effect.sync(() => {
831 if (!turn.turnId?.endsWith(`/${late}`)) return "ended" as const;
832 stops.push(turn);
833 return "stopped" as const;
834 }),
835 },
836 store,
837 );
838 yield* fileSystem.writeFileString(
839 at("helper.ts"),
840 `T3.workflow("helper", { version: 1, payload: Schema.Struct({}) }, () =>
841 Effect.asVoid(T3.agent("work", { brief: "Do it.", project: "p", environment: "env-b", returns: Schema.Struct({ head: Schema.String }) })),
842);
843`,
844 );
845 yield* Effect.gen(function* () {
846 const workflows = yield* Workflows.Workflows;
847 const { runId } = yield* workflows.start("helper", {}, { idempotencyKey: late });
848 yield* Deferred.await(started);
849 yield* workflows.cancel(runId);
850 yield* Deferred.succeed(reply, undefined);
851 yield* Deferred.await(recorded);
852 yield* workflows.sweep;
853 assert.deepStrictEqual(stops, [
854 { threadId: "thread", environment: "env-b", turnId: `${runId}/${late}` },
855 ]);
856 }).pipe(
857 Effect.provide(runtime),
858 Effect.scoped,
859 Effect.raceFirst(Effect.forever(TestClock.adjust("1 second"))),
860 );
861 }
862 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
863);
864
865const linkedWorkflow = (cleanup: boolean) => `T3.workflow("linked", {
866 version: 1, payload: Schema.Struct({})${cleanup ? ", onEnd: () => Effect.void" : ""}
867}, () => Effect.asVoid(T3.agent("work", { brief: "Do it.", project: "p", environment: "env-b" })));
868`;
869
870it.effect("a pending stop survives removing the last workflow definition", () =>
871 Effect.gen(function* () {
872 const stopped = yield* Deferred.make<string | undefined>();
873 let online = false;
874 const { fileSystem, at, runtime } = yield* setup(undefined, undefined, {
875 start: (input) =>
876 Effect.succeed({ threadId: "thread", environment: "env-b", turnId: input.key }),
877 result: () => Effect.never,
878 interrupt: (turn) =>
879 Effect.suspend(() =>
880 online
881 ? Deferred.succeed(stopped, turn.turnId).pipe(Effect.as("stopped" as const))
882 : Effect.fail(new WorkflowAgentError({ reason: "the link is down" })),
883 ),
884 });
885 yield* fileSystem.writeFileString(at("linked.ts"), linkedWorkflow(false));
886 yield* Effect.gen(function* () {
887 const workflows = yield* Workflows.Workflows;
888 const definitions = yield* WorkflowRuntime.WorkflowDefinitions;
889 const { runId } = yield* workflows.start("linked", {}, { idempotencyKey: "last-definition" });
890 yield* workflows.waitFor(runId, (run) => run.detail === "agent work");
891 yield* workflows.cancel(runId);
892 assert.isTrue((yield* definitions.remove("hold.ts")).changed);
893 assert.isTrue((yield* definitions.remove("linked.ts")).changed);
894 online = true;
895 assert.equal(yield* Deferred.await(stopped), `${runId}/work/0`);
896 }).pipe(
897 Effect.provide(runtime),
898 Effect.scoped,
899 Effect.raceFirst(Effect.forever(TestClock.adjust("1 second"))),
900 );
901 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
902);
903
904it.effect("cleanup waits for the first recovery stop after cancellation is interrupted", () =>
905 Effect.gen(function* () {
906 const entered = yield* Deferred.make<void>();
907 const recoveryEntered = yield* Deferred.make<void>();
908 const release = yield* Deferred.make<void>();
909 const swept = yield* Deferred.make<void>();
910 const clock = yield* Latch.make(true);
911 let first = true;
912 let checking = false;
913 const store = Layer.effect(
914 WorkflowStore.WorkflowStore,
915 Effect.map(WorkflowStore.make, (real) =>
916 WorkflowStore.WorkflowStore.of({
917 ...real,
918 pruneSkipped: (...args) =>
919 real
920 .pruneSkipped(...args)
921 .pipe(
922 Effect.tap(() => (checking ? Deferred.succeed(swept, undefined) : Effect.void)),
923 ),
924 }),
925 ),
926 );
927 const { fileSystem, at, runtime } = yield* setup(
928 undefined,
929 undefined,
930 {
931 start: (input) =>
932 Effect.succeed({ threadId: "thread", environment: "env-b", turnId: input.key }),
933 result: () => Effect.never,
934 interrupt: () =>
935 Effect.suspend(() => {
936 if (first) {
937 first = false;
938 return Deferred.succeed(entered, undefined).pipe(Effect.andThen(Effect.never));
939 }
940 return Deferred.succeed(recoveryEntered, undefined).pipe(
941 Effect.andThen(Deferred.await(release)),
942 Effect.as("stopped" as const),
943 );
944 }),
945 },
946 store,
947 );
948 yield* fileSystem.writeFileString(at("linked.ts"), linkedWorkflow(true));
949 yield* Effect.gen(function* () {
950 const workflows = yield* Workflows.Workflows;
951 const { runId } = yield* workflows.start("linked", {}, { idempotencyKey: "unfinished-stop" });
952 yield* workflows.waitFor(runId, (run) => run.detail === "agent work");
953 const cancel = yield* Effect.forkChild(workflows.cancel(runId));
954 yield* Deferred.await(entered);
955 yield* clock.close;
956 yield* Fiber.interrupt(cancel);
957
958 checking = true;
959 const sweep = yield* Effect.forkChild(workflows.sweep);
960 yield* Deferred.await(recoveryEntered);
961 yield* Deferred.await(swept);
962 assert.isFalse((yield* workflows.get(runId)).steps.some((step) => step.name === "onEnd"));
963
964 yield* Deferred.succeed(release, undefined);
965 yield* Fiber.join(sweep);
966 yield* workflows.sweep;
967 const cleanup = (yield* workflows.get(runId)).steps.find((step) => step.name === "onEnd");
968 assert.deepStrictEqual([cleanup?.status, cleanup?.attempts], ["completed", 1]);
969 }).pipe(
970 Effect.ensuring(clock.open),
971 Effect.provide(runtime),
972 Effect.scoped,
973 Effect.raceFirst(Effect.forever(Effect.andThen(clock.await, TestClock.adjust("1 second")))),
974 );
975 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
976);
977
978it.effect(
979 "workflows are off until turned on, and a run left waiting when they are turned off goes on once they are on again",
980 () =>
981 Effect.gen(function* () {
982 const { fileSystem, at, directory, made } = yield* setup();
983 // Its top level counts the times it was loaded.
984 yield* fileSystem.writeFileString(
985 at("counted.ts"),
986 "globalThis.t3GatedLoads = (globalThis.t3GatedLoads ?? 0) + 1;\nexport default [];\n",
987 );
988 const loads = () => (globalThis as { t3GatedLoads?: number }).t3GatedLoads ?? 0;
989 yield* Effect.gen(function* () {
990 const { turn, context } = yield* WorkflowRuntime.gate(made, directory);
991 const workflows = Context.get(context, Workflows.Workflows);
992 const definitions = Context.get(context, WorkflowRuntime.WorkflowDefinitions);
993 const start = workflows.start("hold", {}, { idempotencyKey: "h" });
994
995 assert.equal((yield* Effect.flip(start)).message, Workflows.OFF);
996 assert.equal((yield* Effect.flip(workflows.list())).message, Workflows.OFF);
997 assert.deepStrictEqual((yield* definitions.read).files, []);
998 assert.equal(loads(), 0);
999
1000 yield* turn(true);
1001 assert.equal(loads(), 1);
1002 const held = yield* start;
1003 yield* workflows.waitFor(held.runId, (run) => run.status === "waiting");
1004
1005 yield* turn(false);
1006 const signal = workflows.signal({ runId: held.runId, wait: "go" }, "go on", { id: "s1" });
1007 assert.equal((yield* Effect.flip(signal)).message, Workflows.OFF);
1008
1009 yield* turn(true);
1010 yield* signal;
1011 const freed = yield* workflows.waitFor(held.runId, (run) => run.status === "completed");
1012 assert.equal(freed.result, "go on");
1013 }).pipe(Effect.scoped, Effect.raceFirst(Effect.forever(TestClock.adjust("1 second"))));
1014 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
1015);