mirror of
https://github.com/software-mansion/argent.git
synced 2026-09-14 19:27:14 +08:00
0f90d182b2
#864 (the executor) and #865 (the `script:` step) are merged. This branch now sits directly on `main` as a single commit, so the diff and the commit list are this change alone. A `script:` step could only enter a flow by being typed into the YAML after the recording ended. The authoring skill said so in as many words, and listed it among the legal unrecorded insertions. That made it the one directive exempt from every rule the recorder exists to enforce, and it cost two things: - **The script never ran while the flow was authored.** It first executed during the closing replay, where a failure reads as a flow that was never right rather than a script that needs one more attempt. Worse, the device steps recorded after it were walked against backend state the author had established by hand — so the recording proved nothing about whether the script establishes that same state. - **The author never saw what the script returned.** A later release reads `{{output:user.id}}`; the only way to know that path exists is to have seen the document. This adds one MCP tool, `flow-add-script`, that runs a local `.mjs` and records the step it ran. **No new flow syntax** — the `script:` step is unchanged, and this is a second way for one to enter a flow file. ```text flow-add-script { name: "checkout", project_root: "/Users/dev/shop", path: "../../scripts/seed-order.mjs", timeout: 60000 } ``` ## What it adds - **One shared execution path.** Path resolution, the on-disk casing guard, the executor call and the verdict were private to `flow-run.ts`. They are now `runFlowScriptStep` in `flow-script-step.ts`, with the file-ref helpers in `flow-file-refs.ts`, and `runScriptStep` is that call plus its `ExecState` plumbing. This is the load-bearing change: "the recording runs the script exactly as replay will" is one function, not two code paths that agree today. - **A failure records nothing.** The opposite of `flow-add-step`, deliberately. A failed script did not establish the state the rest of the walkthrough would then be recorded against, so an appended red step costs every step after it, not just itself. The `message` also says whether a child actually *ran* — a path that resolved to no file forked nothing, while a script that threw halfway did not roll back — because the author's next move is a retry or a cleanup and they cannot pick without knowing. - **The returned document, as JSON text.** Text rather than an object because this is the first tool result carrying bytes the server did not author: every result is deep-walked for `__argentClientFile` and `__argentArtifact` directives, which match on shape alone and write or fetch files on the agent's machine. As a string it inherits none of that. Bounded at 64 KiB with `outputTruncated`, for the reason `log` is bounded. - **`{{output:` refused by `parseFlow`.** Surfacing the document invites an author to write a reference that has no meaning yet — it would be printed literally by a step that passes, green and wrong. The scan runs over exactly the field list the output release declares supported, so it is a seam that release converts from reject to resolve rather than scaffolding it deletes. Patterns are excluded: a `{{` in a regular expression is a quantifier the author meant. - **Two boundaries.** A `client`-mode recording is refused — its `.mjs` never left the agent's machine, the same anchor reason `run:`, `snapshot` and uploaded flows are refused. And the tool is `longRunning`, so the MCP adapter's 30s fetch abort cannot retry a call whose whole purpose is a side effect; the comment records what that flag does *not* close, and where the rest belongs. - **`flow-add-step` says when the call already ran.** The `{{output:` refusal is the one refusal this release adds on a path where the tool call has already fired, and its message asks for an edit-and-retry — which repeats the device action. Verified: a `keyboard` step recorded twice left `{{output:code}}{{output:code}}` in the field. That one refusal now carries what already happened. ## Documentation Rule 5 of `argent-create-flow` no longer lists `script:` as a legal unrecorded insertion — leaving it there would tell agents to keep doing the thing this PR removes. `live-authoring.md` gains the recorder contract, the return fields that are not self-evident, and the ordering rule: a setup script is recorded *before* the `restart-app` it prepares state for, because that is where it runs at replay. A leading script does not make the flow a fragment. `qa-flows` and `reliability-and-recovery` follow the count and the wording. ## Verification `npm run build`, `npx eslint . --max-warnings 0`, `npx prettier --check` over tracked files, and `npm run typecheck:tests -w @argent/tool-server` are green. `npm test -w @argent/tool-server`: 358 files, 4657 passed, 1 skipped. Exercised end to end against a live tool server built from this branch, not only in tests — recorded a flow, then replayed the saved YAML through `argent flow run` with no hand editing: ``` flow-add-script → status "pass", durationMs 124 log: "seeding order for the flow\nwarn: using the fake backend\n" outputJson: {"order":{"id":"ord_4417","total":39.5}, "user":{"id":"usr_9","email":"buyer@example.com"}} recorded: 1. script: ../../scripts/seed-order.mjs (timeout 30000ms) ``` ```yaml steps: - script: path: ../../scripts/seed-order.mjs timeout: 30000 - echo: order seeded; expect Home ``` ``` Flow "checkout" ✓ 1 script ../../scripts/seed-order.mjs │ seeding order for the flow │ warn: using the fake backend › order seeded; expect Home PASS — 1 passed, 0 failed, 0 errored, 0 skipped ``` The three refusals, live on the same recording: - A script that threw after creating records: `status "fail"`, `stepCount` unchanged at 1, and the message naming the side effects that were not rolled back. - A path resolving to no file: refused before any fork, no `durationMs`, and "Nothing ran, so there is nothing to clean up". - `flow-add-echo` holding `{{output:user.id}}`: refused with the author-facing message naming the step, the field and the later release. No device is involved at any point — a recording may open with a seeding script before it boots anything. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added the `flow-add-script` tool to run local `.mjs` scripts and record successful executions in flows. * Added script status, output, duration, logs, and failure details to recording results. * Added clearer handling for script cancellation, timeouts, missing files, and path casing. * **Documentation** * Updated flow guidance to clarify end-to-end classification and script setup or cleanup usage. * Documented script path requirements, failure conditions, and recording workflows. * **Bug Fixes** * Flows now reject unsupported output-reference templates with more precise diagnostics. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
240 lines
9.1 KiB
TypeScript
240 lines
9.1 KiB
TypeScript
import { afterEach, describe, expect, it } from "vitest";
|
|
import {
|
|
FlowScriptExecutor,
|
|
type FlowScriptRequest,
|
|
} from "../../../src/tools/flows/script/flow-script-executor";
|
|
import { createScriptWorkspace, type ScriptWorkspace } from "../../helpers/flow-script-workspace";
|
|
|
|
const workspaces: ScriptWorkspace[] = [];
|
|
|
|
function workspace(): ScriptWorkspace {
|
|
const ws = createScriptWorkspace("queue");
|
|
workspaces.push(ws);
|
|
return ws;
|
|
}
|
|
|
|
afterEach(() => {
|
|
while (workspaces.length) workspaces.pop()!.cleanup();
|
|
});
|
|
|
|
function delay(ms: number): Promise<void> {
|
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
}
|
|
|
|
function stepFor(ws: ScriptWorkspace, scriptPath: string): FlowScriptRequest {
|
|
return { scriptPath, projectRoot: ws.dir };
|
|
}
|
|
|
|
function timedScript(ws: ScriptWorkspace, sleepMs: number): string {
|
|
return ws.write(
|
|
"timed.mjs",
|
|
`output.startedAt = Date.now();
|
|
await new Promise((r) => setTimeout(r, ${sleepMs}));
|
|
output.endedAt = Date.now();`
|
|
);
|
|
}
|
|
|
|
describe("flow script executor — concurrency", () => {
|
|
it("runs no more scripts at once than the limit allows", async () => {
|
|
const ws = workspace();
|
|
const script = timedScript(ws, 400);
|
|
const executor = new FlowScriptExecutor({ concurrency: 2, maxTimeoutMs: 60_000 });
|
|
const results = await Promise.all(
|
|
Array.from({ length: 4 }, () => executor.execute(stepFor(ws, script)))
|
|
);
|
|
|
|
expect(results.every((r) => r.ok)).toBe(true);
|
|
const spans = results.map((r) => ({
|
|
from: r.output!.startedAt as number,
|
|
to: r.output!.endedAt as number,
|
|
}));
|
|
for (const span of spans) {
|
|
const overlapping = spans.filter((other) => other.from < span.to && other.to > span.from);
|
|
expect(overlapping.length).toBeLessThanOrEqual(2);
|
|
}
|
|
expect(results.filter((r) => r.queuedMs > 100).length).toBe(2);
|
|
expect(executor.activeCount).toBe(0);
|
|
}, 30_000);
|
|
|
|
it("does not count the queue wait against the script's own time limit", async () => {
|
|
const ws = workspace();
|
|
const script = timedScript(ws, 500);
|
|
const executor = new FlowScriptExecutor({ concurrency: 1, maxTimeoutMs: 60_000 });
|
|
const [first, second] = await Promise.all([
|
|
executor.execute({ scriptPath: script, projectRoot: ws.dir, timeoutMs: 2_000 }),
|
|
executor.execute({ scriptPath: script, projectRoot: ws.dir, timeoutMs: 2_000 }),
|
|
]);
|
|
|
|
expect(first.ok).toBe(true);
|
|
expect(second.ok).toBe(true);
|
|
expect(second.queuedMs).toBeGreaterThan(300);
|
|
expect(second.durationMs).toBeLessThan(2_000);
|
|
}, 30_000);
|
|
|
|
it("refuses a step once the queue is full", async () => {
|
|
const ws = workspace();
|
|
const script = timedScript(ws, 1_500);
|
|
const executor = new FlowScriptExecutor({ concurrency: 1, maxTimeoutMs: 60_000 });
|
|
const occupier = executor.execute({ scriptPath: script, projectRoot: ws.dir });
|
|
const controllers = Array.from({ length: 32 }, () => new AbortController());
|
|
const queued = controllers.map((controller) =>
|
|
executor.execute({ scriptPath: script, projectRoot: ws.dir, signal: controller.signal })
|
|
);
|
|
const refused = await executor.execute({ scriptPath: script, projectRoot: ws.dir });
|
|
|
|
expect(refused.failure?.kind).toBe("queue");
|
|
expect(refused.failure?.message).toContain("queue is full");
|
|
for (const controller of controllers) controller.abort();
|
|
expect((await Promise.all(queued)).every((r) => r.failure?.kind === "cancelled")).toBe(true);
|
|
expect((await occupier).ok).toBe(true);
|
|
}, 30_000);
|
|
|
|
it("refuses a step that waits past the wait bound", async () => {
|
|
const ws = workspace();
|
|
const script = timedScript(ws, 1_200);
|
|
const executor = new FlowScriptExecutor({
|
|
concurrency: 1,
|
|
maxTimeoutMs: 60_000,
|
|
queueWaitMs: 400,
|
|
});
|
|
const occupier = executor.execute({ scriptPath: script, projectRoot: ws.dir });
|
|
await delay(200);
|
|
const refused = await executor.execute({ scriptPath: script, projectRoot: ws.dir });
|
|
|
|
expect(refused.failure?.kind).toBe("queue");
|
|
expect(refused.failure?.message).toContain("Timed out after 400ms");
|
|
expect((await occupier).ok).toBe(true);
|
|
}, 30_000);
|
|
|
|
it("releases a queue position the moment its run is cancelled", async () => {
|
|
const ws = workspace();
|
|
const script = timedScript(ws, 800);
|
|
const executor = new FlowScriptExecutor({ concurrency: 1, maxTimeoutMs: 60_000 });
|
|
const occupier = executor.execute({ scriptPath: script, projectRoot: ws.dir });
|
|
await delay(100);
|
|
const controller = new AbortController();
|
|
const queued = executor.execute({
|
|
scriptPath: script,
|
|
projectRoot: ws.dir,
|
|
signal: controller.signal,
|
|
});
|
|
const behind = executor.execute({ scriptPath: script, projectRoot: ws.dir });
|
|
const abortedAt = Date.now();
|
|
controller.abort();
|
|
|
|
const cancelled = await queued;
|
|
const answeredAfterMs = Date.now() - abortedAt;
|
|
expect(cancelled.failure?.kind).toBe("cancelled");
|
|
// It never left the queue, so no child of it exists to have done anything.
|
|
expect(cancelled.failure?.beforeFork).toBe(true);
|
|
// The occupier keeps the only slot for another ~700ms. Without the queue's
|
|
// own abort listener the waiter would take a slot later and `runOne`'s
|
|
// guard would answer with the same kind, so the kind alone proves nothing.
|
|
expect(answeredAfterMs).toBeLessThan(300);
|
|
expect((await occupier).ok).toBe(true);
|
|
expect((await behind).ok).toBe(true);
|
|
}, 30_000);
|
|
|
|
it("reports a queue wait longer than five seconds", async () => {
|
|
const ws = workspace();
|
|
const occupying = timedScript(ws, 5_200);
|
|
const quick = ws.write("quick.mjs", `output.ok = true;`);
|
|
const executor = new FlowScriptExecutor({ concurrency: 1, maxTimeoutMs: 60_000 });
|
|
const [, waited] = await Promise.all([
|
|
executor.execute({ scriptPath: occupying, projectRoot: ws.dir, timeoutMs: 20_000 }),
|
|
executor.execute({ scriptPath: quick, projectRoot: ws.dir, timeoutMs: 20_000 }),
|
|
]);
|
|
|
|
expect(waited.ok).toBe(true);
|
|
expect(waited.notes.join(" ")).toMatch(/Waited \d+\.\ds for a free script slot/);
|
|
}, 30_000);
|
|
});
|
|
|
|
describe("flow script executor — the default concurrency", () => {
|
|
it("runs at least two scripts at once on any host", async () => {
|
|
const ws = createScriptWorkspace("queue");
|
|
try {
|
|
// Two intervals that overlap ran at the same time. Elapsed wall clock
|
|
// cannot say that: its bound would have to sit between the concurrent
|
|
// time and the serialized one, which a loaded runner crosses while
|
|
// running both scripts at once.
|
|
const script = ws.write(
|
|
"slow.mjs",
|
|
`output.startedAt = Date.now();
|
|
await new Promise((r) => setTimeout(r, 700));
|
|
output.finishedAt = Date.now();`
|
|
);
|
|
const shared = new FlowScriptExecutor({ maxTimeoutMs: 60_000 });
|
|
const results = await Promise.all([
|
|
shared.execute({ scriptPath: script, projectRoot: ws.dir }),
|
|
shared.execute({ scriptPath: script, projectRoot: ws.dir }),
|
|
]);
|
|
const spans = results.map((result) => ({
|
|
from: result.output?.startedAt as number,
|
|
to: result.output?.finishedAt as number,
|
|
}));
|
|
|
|
expect(results.every((r) => r.ok)).toBe(true);
|
|
expect(Math.min(spans[0]!.to, spans[1]!.to)).toBeGreaterThan(
|
|
Math.max(spans[0]!.from, spans[1]!.from)
|
|
);
|
|
expect(results.every((r) => r.queuedMs < 200)).toBe(true);
|
|
} finally {
|
|
ws.cleanup();
|
|
}
|
|
}, 30_000);
|
|
});
|
|
|
|
describe("flow script executor — bounds that would break every step", () => {
|
|
it("treats concurrency 0 as unset rather than a queue that never drains", async () => {
|
|
const ws = createScriptWorkspace("queue");
|
|
try {
|
|
const script = ws.write("quick.mjs", `output.ok = true;`);
|
|
const result = await new FlowScriptExecutor({ concurrency: 0, maxTimeoutMs: 60_000 }).execute(
|
|
{ scriptPath: script, projectRoot: ws.dir }
|
|
);
|
|
|
|
expect(result.ok).toBe(true);
|
|
} finally {
|
|
ws.cleanup();
|
|
}
|
|
}, 30_000);
|
|
|
|
it("keeps a huge maximum inside what a timer can hold", async () => {
|
|
const ws = createScriptWorkspace("queue");
|
|
try {
|
|
const script = ws.write(
|
|
"slow.mjs",
|
|
`await new Promise((r) => setTimeout(r, 300)); output.ok = true;`
|
|
);
|
|
// Past ~24.9 days the clamped step limit exceeds setTimeout's range, Node
|
|
// clamps the timer to 1ms, and every script "times out" at once.
|
|
const result = await new FlowScriptExecutor({
|
|
concurrency: 2,
|
|
maxTimeoutMs: 3_000_000_000,
|
|
}).execute({ scriptPath: script, projectRoot: ws.dir, timeoutMs: 3_000_000_000 });
|
|
|
|
expect(result.failure).toBeUndefined();
|
|
expect(result.ok).toBe(true);
|
|
} finally {
|
|
ws.cleanup();
|
|
}
|
|
}, 30_000);
|
|
|
|
it("does not note a clamp for a step that asked for nothing", async () => {
|
|
const ws = createScriptWorkspace("queue");
|
|
try {
|
|
const script = ws.write("quick.mjs", `output.ok = true;`);
|
|
const result = await new FlowScriptExecutor({ concurrency: 2, maxTimeoutMs: 5_000 }).execute({
|
|
scriptPath: script,
|
|
projectRoot: ws.dir,
|
|
});
|
|
|
|
expect(result.ok).toBe(true);
|
|
expect(result.notes).toEqual([]);
|
|
} finally {
|
|
ws.cleanup();
|
|
}
|
|
}, 30_000);
|
|
});
|