diff --git a/docs/api/agents.md b/docs/api/agents.md index ce510a4b5d3..7adee3ceb61 100644 --- a/docs/api/agents.md +++ b/docs/api/agents.md @@ -152,6 +152,23 @@ POST /api/agents/{agentId}/heartbeat/invoke Manually triggers a heartbeat for the agent. +## Stop a Run + +``` +POST /api/heartbeat-runs/{runId}/cancel +``` + +Board only. Stops a run that is running or still waiting in line (`queued`). The caller must be able to read the run, or the response is 404. The run and its wake are cancelled, the task's execution lock is released, and a `heartbeat.cancelled` activity entry is logged. Paperclip does not start another run for that task by itself. The agent's next waiting task starts as usual. + +When the stopped run was still waiting in line, the task also returns from `in_progress` to `todo`, and an `issue.updated` activity entry is logged with the reason `stopped_while_waiting`. The task is left unchanged when any of these is true: + +- The run had already started. +- The task is not `in_progress`. +- The task is no longer assigned to that agent, or it is assigned to a person. +- Another run holds the task's execution lock, or another run for the task is queued, running, or scheduled to retry. + +Send an empty body. The optional `cancellationRequestId` is only for native runs; for any other run, the response is `409`. + ## Assigned-Work Invariant Report ``` diff --git a/server/src/__tests__/heartbeat-run-privacy-routes.test.ts b/server/src/__tests__/heartbeat-run-privacy-routes.test.ts index cfbf7e79ed0..cf32abde6fe 100644 --- a/server/src/__tests__/heartbeat-run-privacy-routes.test.ts +++ b/server/src/__tests__/heartbeat-run-privacy-routes.test.ts @@ -502,6 +502,40 @@ describeEmbeddedPostgres("heartbeat run privacy routes", { concurrent: false }, .toMatchObject({ status: "failed", resultJson: null }); }); + it("Stop on a task waiting in line cancels its run and wake, frees the task, and logs both changes", async () => { + const fixture = await seedFixture(); + await db.update(heartbeatRuns).set({ status: "queued", startedAt: null, finishedAt: null, resultJson: null, + nextEventSeq: 100 }) + .where(eq(heartbeatRuns.id, fixture.privateRunId)); + await db.update(issues).set({ executionRunId: fixture.privateRunId, executionLockedAt: new Date() }) + .where(eq(issues.id, fixture.issueId)); + + const denied = await request(createBoardApp(fixture.companyId, fixture.otherUserId)) + .post(`/api/heartbeat-runs/${fixture.privateRunId}/cancel`).send({}); + expect(denied.status).toBe(404); + expect((await db.select().from(issues).where(eq(issues.id, fixture.issueId)))[0]?.status).toBe("in_progress"); + + // Correlated Stop is for native runs only. It must leave a waiting legacy + // run and its task untouched; task Stop sends the plain request below. + const correlated = await request(createBoardApp(fixture.companyId, fixture.ownerUserId)) + .post(`/api/heartbeat-runs/${fixture.privateRunId}/cancel`).send({ cancellationRequestId: randomUUID() }); + expect(correlated.status).toBe(409); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.privateRunId)))[0]?.status).toBe("queued"); + expect((await db.select().from(issues).where(eq(issues.id, fixture.issueId)))[0]?.status).toBe("in_progress"); + + const stopped = await request(createBoardApp(fixture.companyId, fixture.ownerUserId)) + .post(`/api/heartbeat-runs/${fixture.privateRunId}/cancel`).send({}); + expect(stopped.status).toBe(200); + expect(stopped.body.status).toBe("cancelled"); + expect((await db.select().from(issues).where(eq(issues.id, fixture.issueId)))[0]) + .toMatchObject({ status: "todo", executionRunId: null }); + const activity = await db.select().from(activityLog).where(eq(activityLog.companyId, fixture.companyId)); + expect(activity.map((row) => row.action)).toEqual(expect.arrayContaining(["heartbeat.cancelled", "issue.updated"])); + expect(activity.find((row) => row.action === "issue.updated")).toMatchObject({ actorType: "user", + actorId: fixture.ownerUserId, entityId: fixture.issueId, details: expect.objectContaining({ status: "todo", + previousStatus: "in_progress", reason: "stopped_while_waiting" }) }); + }); + it("conceals private runs from unauthorized cancellation and watchdog mutations", async () => { const fixture = await seedFixture(); diff --git a/server/src/__tests__/heartbeat-stop-queued-task.test.ts b/server/src/__tests__/heartbeat-stop-queued-task.test.ts new file mode 100644 index 00000000000..f99b5537d86 --- /dev/null +++ b/server/src/__tests__/heartbeat-stop-queued-task.test.ts @@ -0,0 +1,152 @@ +import { randomUUID } from "node:crypto"; +import { eq, sql } from "drizzle-orm"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { + activityLog, + agents, + agentWakeupRequests, + applyPendingMigrations, + authUsers, + companies, + companyMemberships, + createDb, + EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, + heartbeatRuns, + issues, +} from "@paperclipai/db"; +import { + getEmbeddedPostgresTestSupport, + startEmbeddedPostgresTestDatabase, +} from "./helpers/embedded-postgres.js"; +import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; +import { drainHeartbeatRunsToQuiescence } from "./helpers/drain-heartbeat-runs.js"; +import { truncateTablesWithDeadlockRetry } from "./helpers/truncate-with-deadlock-retry.js"; +import { heartbeatService } from "../services/heartbeat.ts"; +import { returnStoppedWaitingTaskToTodo } from "../services/heartbeat/stopped-waiting-task.ts"; +import type { AdapterExecutionContext, AdapterExecutionResult } from "../adapters/index.ts"; + +const gates = vi.hoisted(() => new Map void) | null>()); +const mockAdapterExecute = vi.hoisted(() => + vi.fn(async (context: AdapterExecutionContext): Promise => { + const issueId = (context.context as Record | undefined)?.issueId; + // One-shot gate: hold only the first run of a gated task so the slot stays busy. + if (typeof issueId === "string" && gates.get(issueId) === null) { + await new Promise((resolve) => gates.set(issueId, resolve)); + } + return { exitCode: 0, signal: null, timedOut: false, errorMessage: null, summary: "ok", provider: "test", model: "test" }; + }), +); + +vi.mock("../adapters/index.ts", async () => { + const actual = await vi.importActual("../adapters/index.ts"); + return { ...actual, getServerAdapter: vi.fn(() => ({ supportsLocalAgentJwt: false, execute: mockAdapterExecute })) }; +}); + +const external = resolveExternalTestDatabaseUrl("PAPERCLIP_STOP_QUEUED_TEST_DATABASE_URL"); +const embeddedPostgresSupport = external ? { supported: true, reason: undefined } : await getEmbeddedPostgresTestSupport(); +const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; + +describeEmbeddedPostgres("Stop on a task whose run is still waiting in line", () => { + let db!: ReturnType; + let heartbeat!: ReturnType; + let tempDb: Awaited> | null = null; + + const executedIssueIds = () => + mockAdapterExecute.mock.calls.map(([context]) => (context.context as Record)?.issueId); + + beforeAll(async () => { + if (external) await applyPendingMigrations(external); + else tempDb = await startEmbeddedPostgresTestDatabase("paperclip-stop-queued-task-"); + db = createDb(external ?? tempDb!.connectionString); + heartbeat = heartbeatService(db, { runtimeEnv: { ...process.env, PAPERCLIP_IN_WORKTREE: "false" } }); + }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); + + afterEach(async () => { + for (const release of gates.values()) release?.(); + gates.clear(); + await drainHeartbeatRunsToQuiescence(db, heartbeat); + mockAdapterExecute.mockClear(); + await truncateTablesWithDeadlockRetry(db, ` + TRUNCATE TABLE "issue_comments", "issues", "heartbeat_run_events", "cost_events", "activity_log", + "heartbeat_runs", "agent_wakeup_requests", "agent_runtime_state", "agents", "companies" + RESTART IDENTITY CASCADE + `, { attempts: 10, delayMs: () => 100 }); + await db.delete(authUsers).where(eq(authUsers.id, "responsible-user")); + }); + + afterAll(async () => { + await tempDb?.cleanup(); + }); + + async function seed() { + const companyId = randomUUID(); + const agentId = randomUUID(); + await db.insert(companies).values({ + id: companyId, name: "Paperclip", issuePrefix: `S${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`, + defaultResponsibleUserId: "responsible-user", requireBoardApprovalForNewAgents: false, + }); + await db.insert(authUsers).values({ id: "responsible-user", name: "Fixture user", email: "responsible-user@example.test", + createdAt: new Date(), updatedAt: new Date() }).onConflictDoNothing(); + await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: "responsible-user", + status: "active", membershipRole: "member" }); + await db.insert(agents).values({ id: agentId, companyId, name: "Codie", role: "engineer", status: "active", + adapterType: "codex_local", adapterConfig: {}, + runtimeConfig: { heartbeat: { wakeOnDemand: true, maxConcurrentRuns: 1 } }, permissions: {} }); + return { companyId, agentId }; + } + + async function assignAndWake(companyId: string, agentId: string, title: string, status: "todo" | "in_progress" = "todo") { + const [issue] = await db.insert(issues).values({ companyId, title, status, assigneeAgentId: agentId }).returning(); + const run = await heartbeat.wakeup(agentId, { source: "assignment", triggerDetail: "system", reason: "issue_assigned", + requestedByActorType: "system", payload: { issueId: issue.id } }); + expect(run).toBeTruthy(); + return { issue, run: run! }; + } + + it.each(["todo", "in_progress"] as const)("takes a %s task out of line in one Stop and still promotes the agent's next task", async (waitingStatus) => { + const { companyId, agentId } = await seed(); + const busy = randomUUID(); + const [busyIssue] = await db.insert(issues).values({ id: busy, companyId, title: "Busy", status: "todo", assigneeAgentId: agentId }).returning(); + gates.set(busyIssue.id, null); + const busyRun = await heartbeat.wakeup(agentId, { source: "assignment", triggerDetail: "system", reason: "issue_assigned", + requestedByActorType: "system", payload: { issueId: busyIssue.id } }); + await vi.waitFor(() => expect(executedIssueIds()).toContain(busyIssue.id), { timeout: 10_000 }); + + const waiting = await assignAndWake(companyId, agentId, "Waiting task", waitingStatus); + const next = await assignAndWake(companyId, agentId, "Next task"); + expect((await heartbeat.getRun(waiting.run.id))?.status).toBe("queued"); + expect((await heartbeat.getRun(next.run.id))?.status).toBe("queued"); + + const stopped = await heartbeat.cancelRun(waiting.run.id, "Cancelled by a board operator", { + resultJson: { cancelledByActorType: "user", cancelledByUserId: "responsible-user" }, + }); + expect(stopped?.status).toBe("cancelled"); + // The board Stop route follows the cancel with this status return. + await returnStoppedWaitingTaskToTodo(db, stopped!, { userId: "responsible-user" }); + + const [wake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, waiting.run.wakeupRequestId!)); + expect(wake.status).toBe("cancelled"); + const [waitingIssue] = await db.select().from(issues).where(eq(issues.id, waiting.issue.id)); + expect(waitingIssue.executionRunId).toBeNull(); + expect(waitingIssue.status).toBe("todo"); + const statusActivity = await db.select().from(activityLog).where(eq(activityLog.entityId, waiting.issue.id)); + expect(statusActivity.filter((row) => row.action === "issue.updated")).toHaveLength(waitingStatus === "in_progress" ? 1 : 0); + + // Free the slot: the agent's next task promotes, the stopped one never runs again. + gates.get(busyIssue.id)?.(); + await vi.waitFor(() => expect(executedIssueIds()).toContain(next.issue.id), { timeout: 45_000 }); + await drainHeartbeatRunsToQuiescence(db, heartbeat); + await heartbeat.resumeQueuedRuns(); + await heartbeat.reconcileStrandedAssignedIssues(); + await drainHeartbeatRunsToQuiescence(db, heartbeat); + + expect(executedIssueIds()).not.toContain(waiting.issue.id); + const laterRuns = await db.select({ id: heartbeatRuns.id, status: heartbeatRuns.status }).from(heartbeatRuns) + .where(sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${waiting.issue.id}`); + expect(laterRuns).toEqual([{ id: waiting.run.id, status: "cancelled" }]); + const [afterIssue] = await db.select().from(issues).where(eq(issues.id, waiting.issue.id)); + expect(afterIssue.status).toBe("todo"); + expect(afterIssue.executionRunId).toBeNull(); + expect(busyRun).toBeTruthy(); + }, 120_000); +}); diff --git a/server/src/routes/agents.ts b/server/src/routes/agents.ts index 26946de51ad..eef96b704c6 100644 --- a/server/src/routes/agents.ts +++ b/server/src/routes/agents.ts @@ -62,6 +62,7 @@ import { paperclipRunnerTransitionConfig, normalizeLegacyRunnerProvider, isPaper import { applyMcpReasoningEffort } from "../services/public-mcp/agent-config.js"; import { executionProjectionForRun, executionProjectionsForRuns } from "../services/execution-projection.js"; import { issueRunPresenceService } from "../services/issue-run-presence.js"; +import { returnStoppedWaitingTaskToTodo } from "../services/heartbeat/stopped-waiting-task.js"; import { selectDashboardRunIds } from "../services/dashboard-run-selection.js"; import { Router, type NextFunction, type Request, type Response } from "express"; import { generateKeyPairSync, randomUUID } from "node:crypto"; @@ -7366,6 +7367,11 @@ export function agentRoutes( entityId: run.id, details: { agentId: run.agentId }, }); + // Stop on a task still waiting in line: the run never started, so the + // task should not keep looking in progress. + if (existing.status === "queued") { + await returnStoppedWaitingTaskToTodo(db, run, { userId: req.actor.userId ?? null }); + } } res.json(run ? await runRedactions.redactForRun(run.companyId, run.id, run, diff --git a/server/src/services/heartbeat/stopped-waiting-task.ts b/server/src/services/heartbeat/stopped-waiting-task.ts new file mode 100644 index 00000000000..38f40f6b7da --- /dev/null +++ b/server/src/services/heartbeat/stopped-waiting-task.ts @@ -0,0 +1,66 @@ +import { and, eq, inArray, isNull, notExists, or, sql } from "drizzle-orm"; +import type { Db } from "@paperclipai/db"; +import { heartbeatRuns, issues } from "@paperclipai/db"; +import { logActivity, publishActivity, type ActivityPublication } from "../activity-log.js"; + +type StoppedRun = Pick; + +const LIVE_RUN_STATUSES = ["queued", "running", "scheduled_retry"]; + +/** + * A person pressed Stop on a task whose run was still waiting in line. The run + * never started, so nothing is working on the task any more: an `in_progress` + * task goes back to `todo` instead of looking busy. The write is guarded so it + * never touches a task another run (or a person) has picked up meanwhile. + * Recovery already stands down for an operator-cancelled run, so this does not + * start or promote another run for the task. + */ +export async function returnStoppedWaitingTaskToTodo( + db: Db, + run: StoppedRun, + actor: { userId: string | null }, +): Promise<{ issueId: string } | null> { + if (run.status !== "cancelled" || run.startedAt) return null; + const issueId = typeof run.contextSnapshot?.issueId === "string" ? run.contextSnapshot.issueId : null; + if (!issueId) return null; + // Publish only after the status change commits, so a viewer that refreshes + // on the event reads the new status. + const publications: ActivityPublication[] = []; + const result = await db.transaction(async (tx) => { + const otherLiveRun = tx.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and( + eq(heartbeatRuns.companyId, run.companyId), + inArray(heartbeatRuns.status, LIVE_RUN_STATUSES), + sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${issueId}`, + )); + const [updated] = await tx.update(issues).set({ + status: "todo", + checkoutRunId: sql`case when ${issues.checkoutRunId} = ${run.id} then null else ${issues.checkoutRunId} end`, + executionRunId: null, + executionLockedAt: null, + updatedAt: new Date(), + }).where(and( + eq(issues.companyId, run.companyId), + eq(issues.id, issueId), + eq(issues.status, "in_progress"), + eq(issues.assigneeAgentId, run.agentId), + isNull(issues.assigneeUserId), + or(isNull(issues.executionRunId), eq(issues.executionRunId, run.id)), + notExists(otherLiveRun), + )).returning({ id: issues.id }); + if (!updated) return null; + await logActivity(tx as unknown as Db, { + companyId: run.companyId, + actorType: "user", + actorId: actor.userId ?? "board", + action: "issue.updated", + entityType: "issue", + entityId: updated.id, + agentId: run.agentId, + runId: run.id, + details: { status: "todo", previousStatus: "in_progress", reason: "stopped_while_waiting", _previous: { status: "in_progress" } }, + }, publications); + return { issueId: updated.id }; + }); + publications.forEach(publishActivity); + return result; +} diff --git a/ui/src/api/heartbeats.test.ts b/ui/src/api/heartbeats.test.ts index ff517cf4342..86bfca14ece 100644 --- a/ui/src/api/heartbeats.test.ts +++ b/ui/src/api/heartbeats.test.ts @@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; const mockApi = vi.hoisted(() => ({ get: vi.fn(), + post: vi.fn(), })); vi.mock("./client", () => ({ @@ -19,6 +20,17 @@ afterEach(() => { vi.unstubAllGlobals(); }); +describe("heartbeatsApi.cancel", () => { + it("sends an uncorrelated Stop so a run still waiting in line can be stopped", async () => { + // Correlated Stop (cancellationRequestId) is only for native runs; the + // server rejects it for a queued legacy run. Task Stop must not send it. + mockApi.post.mockReset(); + mockApi.post.mockResolvedValue({ id: "waiting-run", status: "cancelled" }); + await expect(heartbeatsApi.cancel("waiting-run")).resolves.toMatchObject({ status: "cancelled" }); + expect(mockApi.post).toHaveBeenCalledWith("/heartbeat-runs/waiting-run/cancel", {}); + }); +}); + describe("heartbeatsApi.list", () => { beforeEach(() => { mockApi.get.mockReset(); diff --git a/ui/src/components/IssueChatThread.test.tsx b/ui/src/components/IssueChatThread.test.tsx index fccea4c9000..52112cd04ae 100644 --- a/ui/src/components/IssueChatThread.test.tsx +++ b/ui/src/components/IssueChatThread.test.tsx @@ -459,6 +459,25 @@ describe("IssueChatThread", () => { markdownBodyRenderMock.mockClear(); }); + it("offers Stop for a run still waiting in line and calls the task's stop action", async () => { + const root = createRoot(container); + const onCancelRun = vi.fn(async () => {}); + const waitingRun = { + id: "waiting-run", issueId: "issue-1", status: "queued", invocationSource: "assignment", triggerDetail: null, + startedAt: null, finishedAt: null, createdAt: "2026-11-13T12:00:00.000Z", + agentId: "agent-1", agentName: "Codie", adapterType: "codex_local", + }; + act(() => renderIssueThread(root, { liveRuns: [waitingRun], issueStatus: "todo", onCancelRun })); + const stop = container.querySelector('button[aria-label="Stop"]'); + expect(stop).not.toBeNull(); + await act(async () => { stop!.click(); }); + expect(onCancelRun).toHaveBeenCalledOnce(); + + act(() => renderIssueThread(root, { liveRuns: [], issueStatus: "todo", onCancelRun })); + expect(container.querySelector('button[aria-label="Stop"]')).toBeNull(); + act(() => root.unmount()); + }); + it("drops the count heading and does not use an internal scrollbox", () => { const root = createRoot(container); diff --git a/ui/src/components/IssueChatThread.tsx b/ui/src/components/IssueChatThread.tsx index 138d2000e9e..be1a04a9822 100644 --- a/ui/src/components/IssueChatThread.tsx +++ b/ui/src/components/IssueChatThread.tsx @@ -6925,7 +6925,9 @@ export function IssueChatThread({ mentions={mentions} agentMap={agentMap} hasActiveRun={!!hasActiveRun} - onStop={hasActiveRun ? onCancelRun : undefined} + // A run still waiting in line is stoppable too: Stop takes the + // task out of the agent's queue before it ever starts. + onStop={activeRunIds.size > 0 ? onCancelRun : undefined} stopPending={stopPending} stopScope={stopScope} currentUserId={currentUserId} diff --git a/ui/src/components/TaskChatThread.test.tsx b/ui/src/components/TaskChatThread.test.tsx index 747f2d0ecac..fbb312553dd 100644 --- a/ui/src/components/TaskChatThread.test.tsx +++ b/ui/src/components/TaskChatThread.test.tsx @@ -6095,6 +6095,16 @@ describe("TaskChatThread composer execution controls", () => { render( {}} issueStatus="in_progress" activeRun={run} onCancelRun={onStop} stopPending />); expect(container.querySelector('[data-testid="task-chat-composer-stop"]')?.disabled).toBe(true); }); + it("offers Stop where a running task's Stop lives while its run is still waiting in line", async () => { + const onStop = vi.fn(async () => {}); + const waiting = { id: "waiting-run", status: "queued", invocationSource: "assignment", triggerDetail: null, startedAt: null, + finishedAt: null, createdAt: "2026-11-13T12:00:00Z", agentId: "agent-1", agentName: "Codie", adapterType: "codex_local" }; + render( {}} issueStatus="todo" liveRuns={[waiting]} onCancelRun={onStop} />); + const button = container.querySelector('[data-testid="task-chat-composer-stop"]'); + expect(button).not.toBeNull(); + await act(async () => { button!.click(); }); + expect(onStop).toHaveBeenCalledOnce(); + }); it("does not offer Stop for settled work even when a callback is available", () => { render( {}} issueStatus="todo" onCancelRun={vi.fn()} />); expect(container.querySelector('[data-testid="task-chat-composer-stop"]')).toBeNull();