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 Option from "effect/Option";
13import * as Queue from "effect/Queue";
14import * as Path from "effect/Path";
15import * as PlatformError from "effect/PlatformError";
16import * as Stream from "effect/Stream";
17import * as TestClock from "effect/testing/TestClock";
18import { ChildProcess, ChildProcessSpawner } from "effect/process";
19
20import WorkflowsMigration from "../persistence/Migrations/110_Workflows.ts";
21import WorkflowSkippedRunsMigration from "../persistence/Migrations/113_WorkflowSkippedRuns.ts";
22import WorkflowRunTagsMigration from "../persistence/Migrations/115_WorkflowRunTags.ts";
23import WorkflowMailSenderMigration from "../persistence/Migrations/117_WorkflowMailSender.ts";
24import WorkflowPoolsMigration from "../persistence/Migrations/118_WorkflowPools.ts";
25import WorkflowRunSubjectMigration from "../persistence/Migrations/119_WorkflowRunSubject.ts";
26import { type AgentResult, WorkflowAgents } from "./WorkflowAgents.ts";
27import * as WorkflowEngine from "./WorkflowEngine.ts";
28import * as WorkflowRuntime from "./WorkflowRuntime.ts";
29import { engineTag, type WorkflowDefinition } from "./workflow.ts";
30import * as Workflows from "./Workflows.ts";
31
32/** Waits to be let go. */
33const hold = `T3.workflow("hold", { version: 1, payload: Schema.Struct({}), returns: Schema.String }, () =>
34 Effect.map(T3.wait("go", { returns: Schema.String }), (said) => Option.getOrElse(said, () => "nobody")),
35);
36`;
37const greet = (says: string) => `const { workflow } = T3;
38workflow("greet", { version: 1, payload: Schema.Struct({}), returns: Schema.String }, () =>
39 Effect.succeed(${JSON.stringify(says)}),
40);
41`;
42
43/**
44 * A folder holding `hold.ts`, and the workflow runtime over it on a fresh database. `engine`
45 * stands in for the real one, which needs the clock to run for as long as it is up.
46 */
47const setup = Effect.fn("setup")(function* (
48 wrap: (fileSystem: FileSystem.FileSystem) => FileSystem.FileSystem = (fileSystem) => fileSystem,
49 engine?: (definitions: ReadonlyArray<WorkflowDefinition>) => Layer.Layer<Workflows.Workflows>,
50 agents?: WorkflowAgents["Service"],
51) {
52 const fileSystem = yield* FileSystem.FileSystem;
53 const path = yield* Path.Path;
54 const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-workflow-defs-" });
55 const directory = path.join(home, "workflows");
56 const at = (name: string) => path.join(directory, name);
57 yield* fileSystem.makeDirectory(directory);
58 yield* fileSystem.writeFileString(at("hold.ts"), hold);
59 const database = NodeSqliteClient.layer({ filename: path.join(home, "state.sqlite") });
60 yield* Effect.provide(
61 Effect.andThen(WorkflowsMigration, WorkflowSkippedRunsMigration).pipe(
62 Effect.andThen(WorkflowRunTagsMigration),
63 Effect.andThen(WorkflowMailSenderMigration),
64 Effect.andThen(WorkflowPoolsMigration),
65 Effect.andThen(WorkflowRunSubjectMigration),
66 ),
67 database,
68 );
69 const made = WorkflowRuntime.make(
70 Effect.succeed(
71 (definitions: ReadonlyArray<WorkflowDefinition>) =>
72 engine?.(definitions) ??
73 WorkflowEngine.layer(definitions).pipe(
74 Layer.provide(
75 agents === undefined
76 ? Layer.mock(WorkflowAgents)({})
77 : Layer.succeed(WorkflowAgents, agents),
78 ),
79 Layer.provide(database),
80 Layer.provide(NodeCrypto.layer),
81 ),
82 ),
83 directory,
84 Effect.succeed(true),
85 ).pipe(Effect.provideService(FileSystem.FileSystem, wrap(fileSystem)));
86 return { fileSystem, at, directory, made, runtime: Layer.effectContext(made) };
87});
88
89it.effect(
90 "every file in the folder defines workflows, and a saved file is verified before it runs",
91 () =>
92 Effect.gen(function* () {
93 const { fileSystem, at, runtime } = yield* setup();
94
95 yield* Effect.gen(function* () {
96 const workflows = yield* Workflows.Workflows;
97 const definitions = yield* WorkflowRuntime.WorkflowDefinitions;
98 const held = yield* workflows.start("hold", {}, { idempotencyKey: "h" });
99 yield* workflows.waitFor(held.runId, (run) => run.status === "waiting");
100
101 // A file that does not parse is not written, and says where it breaks.
102 const broken = yield* definitions.save("greet.ts", "T3.workflow(\n 'x',\n];\n");
103 assert.isFalse(broken.changed);
104 assert.deepStrictEqual(
105 broken.problems.map((problem) => [problem.file, problem.line]),
106 [["greet.ts", 3]],
107 );
108 // Nor is one that defines what another file already does, or drops what a run needs.
109 const twice = yield* definitions.save("again.ts", hold);
110 assert.include(
111 twice.problems[0]?.message ?? "",
112 "hold@1 is defined twice, in again.ts and hold.ts",
113 );
114 const dropped = yield* definitions.save("hold.ts", greet("hello"));
115 assert.include(
116 dropped.problems[0]?.message ?? "",
117 "hold@1 is no longer defined, and 1 of its runs",
118 );
119 // Nor one that exports something shaped like a workflow without what the engine walks.
120 const shaped = yield* definitions.save(
121 "shaped.ts",
122 'export default [{ name: "shaped", version: 1, body: () => Effect.void }];\n',
123 );
124 assert.include(shaped.problems[0]?.message ?? "", "is not a workflow");
125 // Nor one with an option nothing reads, or a time a schedule cannot fire at.
126 const misspelt = yield* definitions.save(
127 "misspelt.ts",
128 'T3.workflow("misspelt", { version: 1, payload: Schema.Struct({}), retries: 2 }, () => Effect.void);\n',
129 );
130 assert.include(misspelt.problems[0]?.message ?? "", "does not take `retries`");
131 const late = yield* definitions.save(
132 "late.ts",
133 'T3.workflow("late", { version: 1, payload: T3.Tick, triggers: [T3.daily("9am")] }, () => Effect.void);\n',
134 );
135 assert.include(late.problems[0]?.message ?? "", "24-hour time");
136 const banana = yield* definitions.save(
137 "banana.ts",
138 'T3.workflow("banana", { version: 1, payload: T3.Tick, triggers: [T3.every("banana")] }, () => Effect.void);\n',
139 );
140 assert.include(banana.problems[0]?.message ?? "", 'Write one such as "5 minutes"');
141 const twoHooks = yield* definitions.save(
142 "hooks.ts",
143 'T3.workflow("hooks", { version: 1, payload: T3.WebhookRequest, triggers: [T3.webhook("in"), T3.webhook("in")] }, () => Effect.void);\n',
144 );
145 assert.include(twoHooks.problems[0]?.message ?? "", 'two hooks named "in"');
146 assert.include((yield* definitions.remove("hold.ts")).problems[0]?.message ?? "", "hold@1");
147 assert.deepStrictEqual(
148 (yield* definitions.read).files.map((file) => file.name),
149 ["hold.ts"],
150 );
151 // The same change made outside the app is refused as a whole: the file still reads as the
152 // version that runs, until it is put back.
153 const told = (wanted: boolean) =>
154 Workflows.wholeLists(workflows.watch).pipe(
155 Stream.filter((snapshot) => (snapshot.definition?.problem != null) === wanted),
156 Stream.runHead,
157 );
158 yield* fileSystem.writeFileString(at("hold.ts"), greet("hello"));
159 yield* told(true);
160 assert.deepStrictEqual(
161 (yield* definitions.read).files.map((file) => file.workflows),
162 [["hold@1"]],
163 );
164 // Only that file is held back: another file's change still runs, and the held one says why.
165 const other =
166 'T3.workflow("other", { version: 1, payload: Schema.Struct({}) }, () => Effect.void);\n';
167 // A file the folder's naming leaves out says so, instead of never running without a word.
168 yield* fileSystem.writeFileString(at("my flow.ts"), other);
169 assert.deepStrictEqual(yield* definitions.save("other.ts", other), {
170 changed: true,
171 problems: [],
172 });
173 yield* workflows.start("other", {}, { idempotencyKey: "o" });
174 assert.deepStrictEqual(
175 (yield* definitions.read).files.map((file) => [file.name, file.problems.length]),
176 [
177 ["hold.ts", 1],
178 ["other.ts", 0],
179 ],
180 );
181 assert.deepStrictEqual(
182 (yield* definitions.read).problems.map((problem) => problem.file),
183 ["my flow.ts"],
184 );
185 yield* fileSystem.remove(at("my flow.ts"));
186 assert.deepStrictEqual(yield* definitions.remove("other.ts"), {
187 changed: true,
188 problems: [],
189 });
190 yield* fileSystem.writeFileString(at("hold.ts"), hold);
191 yield* told(false);
192
193 // A new file that passes is there from now on, and what it defines can be started.
194 const saved = { changed: true, problems: [] };
195 assert.deepStrictEqual(yield* definitions.save("greet.ts", greet("hello")), saved);
196 assert.equal(yield* fileSystem.readFileString(at("greet.ts")), greet("hello"));
197 const greeted = yield* workflows.start("greet", {}, { idempotencyKey: "g" });
198 const done = yield* workflows.waitFor(greeted.runId, (run) => run.status === "completed");
199 assert.equal(done.result, "hello");
200 // The run that was waiting came through the reload and can still be let go.
201 yield* workflows.signal({ runId: held.runId, wait: "go" }, "go on", { id: "s1" });
202 const freed = yield* workflows.waitFor(held.runId, (run) => run.status === "completed");
203 assert.equal(freed.result, "go on");
204
205 // Someone breaks a file outside the app: its last good version keeps running, and the
206 // other files go on changing.
207 const problem = (wanted: boolean) =>
208 Workflows.wholeLists(workflows.watch).pipe(
209 Stream.filter((snapshot) => (snapshot.definition?.problem != null) === wanted),
210 Stream.runHead,
211 );
212 yield* fileSystem.writeFileString(at("greet.ts"), "T3.workflow(");
213 yield* problem(true);
214 const read = yield* definitions.read;
215 assert.deepStrictEqual(
216 read.files.map((file) => [file.name, file.problems.length]),
217 [
218 ["greet.ts", 1],
219 ["hold.ts", 0],
220 ],
221 );
222 const still = yield* workflows.start("greet", {}, { idempotencyKey: "g2" });
223 assert.equal(
224 (yield* workflows.waitFor(still.runId, (run) => run.status === "completed")).result,
225 "hello",
226 );
227 // And fixes it, saying something else, this time as the file's one default export.
228 yield* fileSystem.writeFileString(
229 at("greet.ts"),
230 greet("hi").replace("\nworkflow(", "\nexport default workflow("),
231 );
232 yield* problem(false);
233 const fixed = yield* workflows.start("greet", {}, { idempotencyKey: "g3" });
234 assert.equal(
235 (yield* workflows.waitFor(fixed.runId, (run) => run.status === "completed")).result,
236 "hi",
237 );
238 // A file taken away takes its workflows with it.
239 assert.deepStrictEqual(yield* definitions.remove("greet.ts"), saved);
240 const gone = yield* workflows
241 .start("greet", {}, { idempotencyKey: "g4" })
242 .pipe(Effect.flip);
243 assert.equal(gone._tag, "WorkflowNotRegisteredError");
244 // With no file left, nothing runs, and the runs that ended can still be read.
245 assert.deepStrictEqual(yield* definitions.remove("hold.ts"), saved);
246 assert.equal((yield* workflows.get(held.runId)).run.status, "completed");
247 assert.includeMembers(
248 (yield* workflows.list()).map((run) => run.runId),
249 [held.runId, greeted.runId],
250 );
251 }).pipe(
252 Effect.provide(runtime),
253 Effect.scoped,
254 Effect.raceFirst(Effect.forever(TestClock.adjust("1 second"))),
255 );
256 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
257);
258
259it.effect(
260 "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",
261 () =>
262 Effect.gen(function* () {
263 let refuse = false;
264 // What each engine was built to run. One that registers `broken` does not come up.
265 const builds: Array<ReadonlyArray<string>> = [];
266 // No file events: only the runtime's own retry can pick up what changed.
267 const { at, fileSystem, runtime } = yield* setup(
268 (real) => ({
269 ...real,
270 exists: (target) =>
271 refuse
272 ? Effect.fail(
273 PlatformError.systemError({
274 _tag: "PermissionDenied",
275 module: "FileSystem",
276 method: "exists",
277 pathOrDescriptor: target,
278 }),
279 )
280 : real.exists(target),
281 watch: () => Stream.never,
282 }),
283 (definitions) =>
284 definitions.some((definition) => definition.name === "broken")
285 ? Layer.effect(Workflows.Workflows, Effect.die(new Error("broken took it down")))
286 : Layer.sync(Workflows.Workflows, () => {
287 builds.push(definitions.map(engineTag));
288 return Workflows.disabled;
289 }),
290 );
291
292 yield* Effect.gen(function* () {
293 const workflows = yield* Workflows.Workflows;
294 const definitions = yield* WorkflowRuntime.WorkflowDefinitions;
295 const revision = Effect.map(
296 Stream.runHead(Workflows.wholeLists(workflows.watch)),
297 (snapshot) => Option.getOrThrow(snapshot).definition?.revision ?? 0,
298 );
299 refuse = true;
300 // Written, but the folder could not be listed, so it is not said to run.
301 const unlisted = yield* definitions.save("greet.ts", greet("hi"));
302 assert.isTrue(unlisted.changed);
303 assert.include(unlisted.problems[0]?.message ?? "", "could not be read");
304 // What was loaded stays, and greet is not taken in yet.
305 assert.deepStrictEqual(builds, [["hold@1"]]);
306 const before = yield* revision;
307 refuse = false;
308 yield* TestClock.adjust("30 seconds");
309 yield* Workflows.wholeLists(workflows.watch).pipe(
310 Stream.filter((snapshot) => (snapshot.definition?.revision ?? 0) > before),
311 Stream.runHead,
312 );
313 assert.deepStrictEqual(builds.at(-1), ["greet@1", "hold@1"]);
314
315 // A definition that passes the checks but takes the engine down at start changes nothing.
316 yield* fileSystem.writeFileString(
317 at("broken.ts"),
318 'T3.workflow("broken", { version: 1, payload: Schema.Struct({}) }, () => Effect.void);\n',
319 );
320 const fellBack = yield* definitions.save("greet.ts", greet("hello"));
321 assert.isTrue(fellBack.changed);
322 assert.include(fellBack.problems[0]?.message ?? "", "did not start");
323 assert.deepStrictEqual(builds.slice(1), [
324 ["greet@1", "hold@1"],
325 ["greet@1", "hold@1"],
326 ]);
327 assert.include(
328 (yield* Stream.runHead(Workflows.wholeLists(workflows.watch))).pipe(Option.getOrThrow)
329 .definition?.problem ?? "",
330 "did not start",
331 );
332 }).pipe(Effect.provide(runtime), Effect.scoped);
333 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
334);
335
336it.effect("a file that never finishes loading is given up on, and later files still load", () =>
337 Effect.gen(function* () {
338 const { at, fileSystem } = yield* setup();
339 yield* fileSystem.writeFileString(at("stuck.ts"), "await new Promise(() => {});\n");
340 yield* fileSystem.writeFileString(at("greet.ts"), greet("hi"));
341 const stuck = yield* WorkflowRuntime.loadDefinitions(at("stuck.ts"), 0, 50).pipe(Effect.flip);
342 assert.include(String(stuck.cause), "did not finish loading");
343 const loaded = yield* WorkflowRuntime.loadDefinitions(at("greet.ts"));
344 assert.deepStrictEqual(
345 loaded.map((definition) => definition.name),
346 ["greet"],
347 );
348 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
349);
350
351it.effect("a file loads whatever kinds its asks name, and only a malformed `asks` is refused", () =>
352 Effect.gen(function* () {
353 const { at, fileSystem } = yield* setup();
354 const sorter = (asks: string) => `const { workflow, ask } = T3;
355workflow("sorter", { version: 1, payload: Schema.Struct({})${asks} }, () =>
356 ask("sort", { kind: "feture", title: "Which way?", choices: ["Yes", "No"] }),
357);
358`;
359 // A kind the workflow does not declare, and one on a workflow that declares none.
360 for (const asks of [', asks: { feature: "Feature wanted?" }', ""]) {
361 yield* fileSystem.writeFileString(at("sorter.ts"), sorter(asks));
362 const loaded = yield* WorkflowRuntime.loadDefinitions(at("sorter.ts"), asks.length);
363 assert.deepStrictEqual(
364 loaded.map((definition) => Object.keys(definition.asks)),
365 [asks === "" ? [] : ["feature"]],
366 );
367 }
368 yield* fileSystem.writeFileString(at("sorter.ts"), sorter(', asks: { feature: "" }'));
369 const refused = yield* WorkflowRuntime.loadDefinitions(at("sorter.ts"), 1).pipe(Effect.flip);
370 assert.include(String(refused.cause), 'asks gives the kind "feature" no label');
371 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
372);
373
374it.effect("a file given up on registers nothing into the file that loads after it", () =>
375 Effect.gen(function* () {
376 const { at, fileSystem } = yield* setup();
377 yield* fileSystem.writeFileString(
378 at("slow.ts"),
379 'await new Promise((resolve) => { globalThis.t3TestResume = resolve; });\nT3.workflow("slow", { version: 1, payload: Schema.Struct({}) }, () => Effect.void);\n',
380 );
381 // The second file goes on loading until the first one's top level has run to its end.
382 yield* fileSystem.writeFileString(
383 at("next.ts"),
384 `${greet("hi")}globalThis.t3TestResume();\nawait new Promise((resolve) => setImmediate(resolve));\n`,
385 );
386 yield* WorkflowRuntime.loadDefinitions(at("slow.ts"), 0, 50).pipe(Effect.flip);
387 const loaded = yield* WorkflowRuntime.loadDefinitions(at("next.ts"));
388 assert.deepStrictEqual(
389 loaded.map((definition) => definition.name),
390 ["greet"],
391 );
392 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
393);
394
395// Vitest's module runner loads a file its own way; only Node keeps a CommonJS file by its path.
396it.live("a file without imports or exports loads again after it changes", () =>
397 Effect.gen(function* () {
398 const { at, fileSystem } = yield* setup();
399 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
400 yield* fileSystem.writeFileString(at("greet.ts"), greet("hi"));
401 const twice = `
402 import * as NodeFS from "node:fs";
403 import * as NodeServices from "@effect/platform-node/NodeServices";
404 import * as Context from "effect/Context";
405import * as Effect from "effect/Effect";
406 import { loadDefinitions } from ${JSON.stringify(new URL("./WorkflowRuntime.ts", import.meta.url).href)};
407 const file = process.argv.at(-1);
408 const program = Effect.gen(function* () {
409 const first = yield* loadDefinitions(file, 1);
410 NodeFS.writeFileSync(file, NodeFS.readFileSync(file, "utf8").replace('"hi"', '"hello"'));
411 const second = yield* loadDefinitions(file, 2);
412 return [first.length, second.length];
413 });
414 console.log(JSON.stringify(await Effect.runPromise(Effect.provide(program, NodeServices.layer))));
415 `;
416 const child = yield* spawner.spawn(
417 ChildProcess.make(
418 process.execPath,
419 ["--input-type=module", "--eval", twice, at("greet.ts")],
420 { cwd: import.meta.dirname },
421 ),
422 );
423 const [stdout, stderr] = yield* Effect.all(
424 [
425 child.stdout.pipe(Stream.decodeText(), Stream.mkString),
426 child.stderr.pipe(Stream.decodeText(), Stream.mkString),
427 ],
428 { concurrency: "unbounded" },
429 );
430 assert.equal(stdout.trim(), "[1,1]", stderr);
431 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
432);
433
434it.effect("a change held back by a run goes in once that run ends, with no further edit", () =>
435 Effect.gen(function* () {
436 // The folder's changes are told by hand, so the test does not hang on a watcher starting.
437 const changed = yield* Queue.unbounded<FileSystem.WatchEvent>();
438 const { fileSystem, at, runtime } = yield* setup((fileSystem) => ({
439 ...fileSystem,
440 watch: () => Stream.fromQueue(changed),
441 }));
442 yield* Effect.gen(function* () {
443 const workflows = yield* Workflows.Workflows;
444 const definitions = yield* WorkflowRuntime.WorkflowDefinitions;
445 const held = yield* workflows.start("hold", {}, { idempotencyKey: "h" });
446 yield* workflows.waitFor(held.runId, (run) => run.status === "waiting");
447 const problem = (wanted: boolean) =>
448 Workflows.wholeLists(workflows.watch).pipe(
449 Stream.filter((snapshot) => (snapshot.definition?.problem != null) === wanted),
450 Stream.runHead,
451 );
452 yield* fileSystem.writeFileString(at("hold.ts"), greet("hello"));
453 yield* Queue.offer(changed, { _tag: "Update", path: at("hold.ts") });
454 yield* problem(true);
455 yield* workflows.signal({ runId: held.runId, wait: "go" }, "go on", { id: "s1" });
456 yield* workflows.waitFor(held.runId, (run) => run.status === "completed");
457 // Nothing is told of the folder now: the held change goes in on its own.
458 yield* problem(false);
459 assert.deepStrictEqual(
460 (yield* definitions.read).files.map((file) => file.workflows),
461 [["greet@1"]],
462 );
463 }).pipe(
464 Effect.provide(runtime),
465 Effect.scoped,
466 Effect.raceFirst(Effect.forever(TestClock.adjust("1 second"))),
467 );
468 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
469);
470
471it.effect(
472 "a reload does not wait for an agent that is still at work, and its step ends with the turn",
473 () =>
474 Effect.gen(function* () {
475 const ended = yield* Deferred.make<AgentResult>();
476 const started = yield* Deferred.make<void>();
477 const { fileSystem, at, runtime } = yield* setup(undefined, undefined, {
478 start: (input) =>
479 Effect.as(Deferred.succeed(started, undefined), {
480 threadId: "thread",
481 turnId: input.key,
482 }),
483 result: () => Deferred.await(ended),
484 interrupt: () => Effect.succeed("stopped" as const),
485 });
486 yield* fileSystem.writeFileString(
487 at("helper.ts"),
488 `T3.workflow("helper", { version: 1, payload: Schema.Struct({}), returns: Schema.String }, () =>
489 Effect.map(T3.agent("work", { brief: "Do it.", project: "p" }), (done) => done.value),
490);
491`,
492 );
493 const ticking = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
494 Effect.raceFirst(effect, Effect.forever(TestClock.adjust("1 second")));
495 yield* Effect.gen(function* () {
496 const workflows = yield* Workflows.Workflows;
497 const definitions = yield* WorkflowRuntime.WorkflowDefinitions;
498 const helped = yield* ticking(
499 Effect.gen(function* () {
500 const run = yield* workflows.start("helper", {}, { idempotencyKey: "a" });
501 yield* Deferred.await(started);
502 yield* workflows.waitFor(run.runId, (row) => row.status === "waiting");
503 return run;
504 }),
505 );
506
507 // The test clock stands still during the save, so an engine that waited for the agent's
508 // step to finish would never stop: the step is not given up on, and the turn does not end.
509 // The swap cannot be interrupted, so a stuck save is unblocked by ending the turn.
510 const saving = yield* Effect.forkChild(definitions.save("greet.ts", greet("hello")));
511 const saved = yield* Fiber.await(saving).pipe(
512 Effect.timeoutOption("10 seconds"),
513 TestClock.withLive,
514 );
515 if (Option.isNone(saved)) {
516 yield* Deferred.succeed(ended, { ending: "completed", detail: "", reply: "late" });
517 yield* ticking(Fiber.await(saving));
518 assert.fail("The reload waited for the agent's turn to end.");
519 }
520 assert.isTrue(Exit.isSuccess(saved.value) && saved.value.value.changed);
521 assert.equal((yield* workflows.get(helped.runId)).run.status, "waiting");
522
523 // The turn ends after the reload, and the new engine carries its result into the run.
524 yield* Deferred.succeed(ended, { ending: "completed", detail: "", reply: "all done" });
525 const done = yield* ticking(
526 workflows.waitFor(helped.runId, (run) => run.status === "completed"),
527 );
528 assert.equal(done.result, "all done");
529 }).pipe(Effect.provide(runtime), Effect.scoped);
530 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
531);
532
533it.effect(
534 "workflows are off until turned on, and a run left waiting when they are turned off goes on once they are on again",
535 () =>
536 Effect.gen(function* () {
537 const { fileSystem, at, directory, made } = yield* setup();
538 // Its top level counts the times it was loaded.
539 yield* fileSystem.writeFileString(
540 at("counted.ts"),
541 "globalThis.t3GatedLoads = (globalThis.t3GatedLoads ?? 0) + 1;\nexport default [];\n",
542 );
543 const loads = () => (globalThis as { t3GatedLoads?: number }).t3GatedLoads ?? 0;
544 yield* Effect.gen(function* () {
545 const { turn, context } = yield* WorkflowRuntime.gate(made, directory);
546 const workflows = Context.get(context, Workflows.Workflows);
547 const definitions = Context.get(context, WorkflowRuntime.WorkflowDefinitions);
548 const start = workflows.start("hold", {}, { idempotencyKey: "h" });
549
550 assert.equal((yield* Effect.flip(start)).message, Workflows.OFF);
551 assert.equal((yield* Effect.flip(workflows.list())).message, Workflows.OFF);
552 assert.deepStrictEqual((yield* definitions.read).files, []);
553 assert.equal(loads(), 0);
554
555 yield* turn(true);
556 assert.equal(loads(), 1);
557 const held = yield* start;
558 yield* workflows.waitFor(held.runId, (run) => run.status === "waiting");
559
560 yield* turn(false);
561 const signal = workflows.signal({ runId: held.runId, wait: "go" }, "go on", { id: "s1" });
562 assert.equal((yield* Effect.flip(signal)).message, Workflows.OFF);
563
564 yield* turn(true);
565 yield* signal;
566 const freed = yield* workflows.waitFor(held.runId, (run) => run.status === "completed");
567 assert.equal(freed.result, "go on");
568 }).pipe(Effect.scoped, Effect.raceFirst(Effect.forever(TestClock.adjust("1 second"))));
569 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
570);