Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions apps/desktop/src/acp/mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1391,6 +1391,10 @@ export class MockEngine {
return {
run: { run_id: str(obj(params)?.runId) ?? "", status: "running", driven: true },
};
case "_rustcode/workflows/retry":
return {
run: { run_id: str(obj(params)?.runId) ?? "", status: "running", driven: true },
};
case "_rustcode/workflows/stop":
// The mock has no runs of its own: a staged run (state/workflows.ts) is simply stopped.
return {
Expand Down
1 change: 1 addition & 0 deletions apps/desktop/src/acp/workflows.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export const WorkflowMethod = {
list: "_rustcode/workflows/list",
stop: "_rustcode/workflows/stop",
resume: "_rustcode/workflows/resume",
retry: "_rustcode/workflows/retry",
wake: "_rustcode/workflows/wake",
changed: "_rustcode/workflows/changed",
} as const;
Expand Down
40 changes: 40 additions & 0 deletions apps/desktop/src/state/workflows.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { resetForTests, useApp, watchMachineConnection } from "./store";
import { emptyThread, isContinueMessage, WORKFLOW_MARK, wakeLine } from "./thread";
import { runIdOf } from "./toolNames";
import {
canRetry,
currentPhase,
elapsedMs,
endNotice,
Expand All @@ -15,6 +16,7 @@ import {
progressText,
resetWorkflows,
resumeWorkflow,
retryWorkflow,
runLine,
runTitle,
shouldWake,
Expand Down Expand Up @@ -327,3 +329,41 @@ test("Resume targets the owning machine and keeps the saved progress", async ()
expect(useWorkflows.getState().runs[key]?.[0]?.workers).toHaveLength(3);
conn.close("test finished");
});

test("Retry continues a failed run on its machine and only a run that ended unfinished offers it", async () => {
expect(canRetry({ ...run(), status: "failed" })).toBe(true);
expect(canRetry({ ...run(), status: "timed_out" })).toBe(true);
expect(canRetry({ ...run(), status: "cancelled" })).toBe(true);
expect(canRetry({ ...run(), status: "done" })).toBe(false);
expect(canRetry(run())).toBe(false);

const { conn, calls } = engine(
(method): JsonObject =>
method === WorkflowMethod.retry
? { run: { run_id: "wf-1-aaaaaaaa", status: "running", driven: true } }
: {},
);
watchMachineConnection("machine", conn);
const key = "machine/t1";
upsertRun(key, { ...run(), status: "failed", error: "a worker failed", finishedAt: 5 });
await retryWorkflow(key, "wf-1-aaaaaaaa");
expect(calls.find((c) => c.method === WorkflowMethod.retry)?.params).toEqual({
sessionId: "t1",
runId: "wf-1-aaaaaaaa",
});
const retried = useWorkflows.getState().runs[key]?.[0];
expect(retried?.status).toBe("running");
expect(retried?.error).toBeUndefined();
expect(retried?.workers).toHaveLength(3);
conn.close("test finished");

const refused = engine(() => ({
error: { code: "failed", message: "run wf-1-aaaaaaaa finished; there is nothing to retry" },
}));
watchMachineConnection("other", refused.conn);
upsertRun("other/t1", { ...run(), status: "done" });
await retryWorkflow("other/t1", "wf-1-aaaaaaaa");
expect(useWorkflows.getState().runs["other/t1"]?.[0]?.status).toBe("done");
expect(useApp.getState().toasts.some((t) => t.text.includes("Could not retry the workflow"))).toBe(true);
refused.conn.close("test finished");
});
38 changes: 38 additions & 0 deletions apps/desktop/src/state/workflows.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,44 @@ export async function stopWorkflow(key: string, runId: string): Promise<void> {
}
}

/** Whether a run ended without finishing, so Retry can continue it from its finished calls (issue 4383). */
export function canRetry(run: WorkflowRun): boolean {
return run.status === "failed" || run.status === "timed_out" || run.status === "cancelled";
}

/**
* Retry a failed, timed-out or stopped run on the machine that owns it: the engine answers its finished
* calls from the run and starts workers only for the failed or missing ones.
*/
export async function retryWorkflow(key: string, runId: string): Promise<void> {
try {
const { host, id } = splitThreadKey(key);
const conn = connectionFor(host);
if (!conn) throw new Error("That machine is not connected.");
const answer = obj(await conn.request(WorkflowMethod.retry, { sessionId: id, runId }, 30_000));
const error = obj(answer?.error);
if (error) throw new Error(str(error.message) ?? "The engine rejected the request.");
const run = parseWorkflowRun(answer?.run);
if (!run) throw new Error("The engine did not return the workflow.");
const known = useWorkflows.getState().runs[key]?.find((candidate) => candidate.id === runId);
upsertRun(
key,
known && !run.workers.length
? {
...known,
status: run.status,
error: run.error,
finishedAt: run.finishedAt,
driven: run.driven,
woken: run.woken,
}
: run,
);
} catch (error) {
toast(`Could not retry the workflow: ${errorText(error)}`, "error");
}
}

/** Resume one saved run on the machine that owns it. */
export async function resumeWorkflow(key: string, runId: string): Promise<void> {
try {
Expand Down
27 changes: 27 additions & 0 deletions apps/desktop/src/ui/WorkflowRuns.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,14 @@ import { selectThread } from "../state/store";
import { formatDuration } from "../state/thread";
import { splitThreadKey } from "../state/threadKeys";
import {
canRetry,
elapsedMs,
isLive,
type PhaseStepState,
phaseSteps,
progressText,
resumeWorkflow,
retryWorkflow,
runLine,
runTitle,
statusWord,
Expand Down Expand Up @@ -154,6 +156,30 @@ function ResumeButton({ run, threadId }: { run: WorkflowRun; threadId: string })
);
}

function RetryButton({ run, threadId }: { run: WorkflowRun; threadId: string }) {
const [pending, setPending] = useState(false);
return (
<Tooltip label="Run the failed and unfinished workers again; finished ones are kept">
<button
type="button"
disabled={pending}
aria-label={`Retry ${runTitle(run)}`}
className="shrink-0 rounded-sm px-1.5 py-0.5 text-accent hover:bg-fill disabled:opacity-50"
onClick={async () => {
setPending(true);
try {
await retryWorkflow(threadId, run.id);
} finally {
setPending(false);
}
}}
>
{pending ? "Retrying…" : "Retry"}
</button>
</Tooltip>
);
}

function StopButton({ run, threadId }: { run: WorkflowRun; threadId: string }) {
const stopping = useWorkflows((s) => s.stopping[run.id] === true);
return (
Expand Down Expand Up @@ -256,6 +282,7 @@ export function WorkflowCard({ threadId, runId }: { threadId: string; runId: str
<span className="ml-auto shrink-0 text-fg-faint">{formatDuration(elapsedMs(run, now))}</span>
{live && !run.driven && <ResumeButton run={run} threadId={threadId} />}
{live && <StopButton run={run} threadId={threadId} />}
{canRetry(run) && <RetryButton run={run} threadId={threadId} />}
</div>
<div className="px-2">
<PhaseSteps run={run} />
Expand Down
10 changes: 10 additions & 0 deletions docs/workflows.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,16 @@ they **nest under it**, count against its delegate slots (`delegates-per-thread`
the agent starts by hand. When every slot is taken, the run waits and tries
again rather than failing.

**Retrying a run.** A run that ended `failed`, `timed_out` or `cancelled` can
be retried (#4383): `run_workflow` with `retry_run_id` (and no `script`, `name`
or `args`), or **Retry** on the run's card in the app
(`_rustcode/workflows/retry`). The run goes back to `running` under the same id
with its saved script; its finished calls are answered from `calls.jsonl` with
no thread started and no budget spent, and only failed or missing calls start
workers. `concurrency`, `call_budget` and `timeout_minutes` may lower its
limits, the timeout counts from the retry, and the thread is told once when it
ends. A `done` or still `running` run is refused.

## Durability

Everything is under the starting thread's folder,
Expand Down
6 changes: 6 additions & 0 deletions rustcode/engine/src/acp/dispatch_table_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -605,6 +605,12 @@ fn every_dispatched_method_matches_its_request_type() {
),
"method mismatch for workflows::WorkflowResumeRequest"
);
assert!(
<workflows::WorkflowRetryRequest as agent_client_protocol::JsonRpcMessage>::matches_method(
"_rustcode/workflows/retry"
),
"method mismatch for workflows::WorkflowRetryRequest"
);
assert!(
<workflows::WorkflowWakeRequest as agent_client_protocol::JsonRpcMessage>::matches_method(
"_rustcode/workflows/wake"
Expand Down
17 changes: 6 additions & 11 deletions rustcode/engine/src/acp/extension_dispatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1885,19 +1885,14 @@ pub(super) async fn dispatch_request(
}
"_rustcode/workflows/resume" => {
let request: workflows::WorkflowResumeRequest = parse_params(params)?;
let asker = server.clients.info(client_id).orchestration;
let host = (asker >= 2)
.then(|| {
super::preview::orchestration_client_for(
true,
&server.clients.session(&request.session_id),
)
})
.flatten()
.map(|client| (client, asker));

let host = workflows::host(&server.clients, client_id, &request.session_id);
responder.respond(workflows::resume(request, host))
}
"_rustcode/workflows/retry" => {
let request: workflows::WorkflowRetryRequest = parse_params(params)?;
let host = workflows::host(&server.clients, client_id, &request.session_id);
responder.respond(workflows::retry(request, host))
}
"_rustcode/workflows/wake" => {
let request: workflows::WorkflowWakeRequest = parse_params(params)?;

Expand Down
39 changes: 39 additions & 0 deletions rustcode/engine/src/acp/workflows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,45 @@ pub(crate) fn resume(
}
}

/// The orchestration host a resume or retry asked by `client_id` starts its
/// workers through: that client's, when it advertised orchestration v2 or up.
pub(crate) fn host(
clients: &Clients,
client_id: super::clients::ClientId,
session_id: &str,
) -> Option<(Arc<dyn crate::preview::PreviewClient>, u8)> {
let asker = clients.info(client_id).orchestration;
(asker >= 2)
.then(|| super::preview::orchestration_client_for(true, &clients.session(session_id)))
.flatten()
.map(|client| (client, asker))
}

/// Retry one failed, timed-out or stopped run from its finished calls (#4383).
#[derive(
Debug, Clone, serde::Serialize, serde::Deserialize, agent_client_protocol::JsonRpcRequest,
)]
#[request(method = "_rustcode/workflows/retry", response = serde_json::Value)]
#[serde(rename_all = "camelCase")]
pub(crate) struct WorkflowRetryRequest {
pub session_id: String,
pub run_id: String,
}

pub(crate) fn retry(
request: WorkflowRetryRequest,
host: Option<(Arc<dyn crate::preview::PreviewClient>, u8)>,
) -> Value {
let (client, version) = match host {
Some((client, version)) => (Some(client), version),
None => (None, 0),
};
match crate::workflow::retry_run(&request.session_id, &request.run_id, client, version) {
Ok(run) => json!({ "run": run }),
Err(message) => json!({ "error": { "code": "failed", "message": message } }),
}
}

/// `_rustcode/workflows/wake`: claim the wake of an ended run. Answers
/// `{claimed}`: true once, for the client that should tell the thread.
#[derive(
Expand Down
Loading
Loading