Skip to content

A personal agent with a browser, terminal, files, and work that keeps going built with CopilotKit and AG-UI.

TypeScript

fix(actions): fence provider execution against task cancellation (#119)

Kevin Rajande8c232417a3
diff --git a/apps/server/src/actions.ts b/apps/server/src/actions.ts
index 9e5f3f6..e430a3d 100644
--- a/apps/server/src/actions.ts
+++ b/apps/server/src/actions.ts
@@ -164,6 +164,22 @@ export class ActionService {
decision === "deny" ? "Declined; no changes made" : "Approved; execution started",
);
if (decision === "deny") return claimed;
+ if (claimed.taskId) {
+ const task = await this.db.get<{ status: string }>(owner, "tasks", claimed.taskId);
+ if (!task || !["running", "waiting_approval"].includes(task.status)) {
+ await this.db.compareAndSwap<ActionProposal>(
+ owner,
+ "actions",
+ id,
+ { status: "executing" },
+ { status: "awaiting_review" },
+ );
+ throw new AppError(
+ "Resume the task before approving this action. Cancelled tasks cannot execute.",
+ 409,
+ );
+ }
+ }
let finished: ActionProposal;
try {
const input = proposalSchema.parse({ kind: claimed.kind, data: claimed.data });
diff --git a/tests/actions.test.ts b/tests/actions.test.ts
index 71fdd27..e875b05 100644
--- a/tests/actions.test.ts
+++ b/tests/actions.test.ts
@@ -285,3 +285,40 @@ test("an expired stale review cannot overwrite a concurrently executing action",
await approval;
assert.equal(saved?.status, "executing");
});
+
+test("a task cancelled between claim and execution never reaches the provider", async (t) => {
+ let calls = 0;
+ const service = new ActionService(db, {
+ execute: async () => {
+ calls++;
+ return "sent";
+ },
+ connected: async () => true,
+ });
+ const proposal = await service.propose("cancel-race", email, undefined, "task-1");
+ await db.put("cancel-race", "tasks", { id: "task-1", status: "running" });
+ const originalClaim = db.claim.bind(db);
+ let intercept = true;
+ t.mock.method(db, "claim", async (...args: Parameters<Store["claim"]>) => {
+ const result = await originalClaim(...args);
+ if (intercept && args[0] === "cancel-race") {
+ intercept = false;
+ // Inject the race: the task is cancelled after the claim commits, before execute runs.
+ await db.compareAndSwap(
+ "cancel-race",
+ "tasks",
+ "task-1",
+ { status: "running" },
+ { status: "cancelled" },
+ );
+ }
+ return result;
+ });
+ await assert.rejects(
+ service.decide("cancel-race", proposal.id, proposal.hash, "approve"),
+ /resume the task/i,
+ );
+ assert.equal(calls, 0);
+ const saved = await db.get<ActionProposal>("cancel-race", "actions", proposal.id);
+ assert.equal(saved?.status, "awaiting_review");
+});