From e40a16e5c53c16e455483b88a41229143637102c Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Fri, 13 Nov 2026 09:58:54 -0600 Subject: [PATCH] fix(heartbeat): let Stop take a task out of the agent's queue (#21407) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Each agent runs a limited number of tasks at once. Other tasks wait in line as queued runs. > - An agent can have hundreds of waiting tasks. People need one click to take a task out of line. > - Stop already cancelled a queued run, but a task that was in progress stayed in progress. It still looked busy. > - The classic task thread also hid Stop until the run started. > - This pull request makes Stop on a waiting task free the task and show it as not started, in both thread views. > - The benefit is that people can clear a long queue one task at a time, and the agent moves on to its next task. ## Linked Issues or Issue Description **What happened?** An agent had many queued runs. A person pressed Stop on a task that waited in line. The run was cancelled, but the task stayed "in progress". In the classic thread, Stop did not show until the run started. **Expected behavior** One Stop click takes the task out of line. The queued run and its wake are cancelled. The task lock is released. The task does not look in progress. No new run starts for that task. The agent's next waiting task still starts. An activity entry records the change. **Steps to reproduce** 1. Give an agent one run slot and keep it busy. 2. Assign two more in-progress tasks to the agent, so their runs wait in line. 3. Press Stop on one waiting task. 4. See that the task still shows "in progress". **Paperclip version or commit** `master` at 30c718e04b. **Agent adapter(s) involved** Not adapter-specific (core bug). ## What Changed - `POST /heartbeat-runs/:runId/cancel`: when the run was queued, the route calls the new `returnStoppedWaitingTaskToTodo` after the cancel. - New `server/src/services/heartbeat/stopped-waiting-task.ts`: one guarded update moves an `in_progress` task to `todo` and logs `issue.updated` (reason `stopped_while_waiting`). It changes the task only if the run never started, the task is still assigned to that agent and not to a person, the task lock is free or held by that run, and no other live run exists for the task. - The route keeps its company and run-read checks and still logs `heartbeat.cancelled`. Recovery already stands down for an operator stop, so no new run starts for the task. - `IssueChatThread` (classic view): the composer shows Stop for a queued run too, in the same place as a running task's Stop. The default `TaskChatThread` already did this; a test now covers it. The waiting banner is unchanged. ## Verification - `server/src/__tests__/heartbeat-stop-queued-task.test.ts` (new, embedded Postgres, real heartbeat): one busy slot, two waiting tasks. Stop one waiting task. The run and wake are cancelled, the lock is released, the task is `todo`, and an activity entry exists for the in-progress case. After the slot frees, the next task runs. The stopped task gets no new run, also after `resumeQueuedRuns` and `reconcileStrandedAssignedIssues`. The in-progress case was red before the fix. - `server/src/__tests__/heartbeat-run-privacy-routes.test.ts`: a real route test. Another user gets 404 and the task does not change. The task's operator gets 200, the task becomes `todo`, and both activity entries are recorded. Red without the route change, green with it. The full file passes (30/30). - The same route test sends a correlated Stop (`cancellationRequestId`) to the waiting legacy run. The server returns 409 and the run and task do not change. Correlated Stop is for native runs only. `ui/src/api/heartbeats.test.ts` checks that task Stop sends the plain request (`{}`). - `ui/src/components/IssueChatThread.test.tsx` and `TaskChatThread.test.tsx`: Stop shows for a queued run and calls the stop action. The classic test was red before the fix. - `pnpm --filter @paperclipai/server typecheck` and `pnpm --filter @paperclipai/ui typecheck` pass. ## Risks - Low risk. The status write is one guarded `UPDATE` and changes nothing if any guard fails. Only the board Stop route calls it, and only for a run that was queued. - A task stopped while waiting shows `todo` instead of `in_progress`. This is intended. A Stop on a running task does not change its status. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, test runs). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- docs/api/agents.md | 17 ++ .../heartbeat-run-privacy-routes.test.ts | 34 ++++ .../heartbeat-stop-queued-task.test.ts | 152 ++++++++++++++++++ server/src/routes/agents.ts | 6 + .../heartbeat/stopped-waiting-task.ts | 66 ++++++++ ui/src/api/heartbeats.test.ts | 12 ++ ui/src/components/IssueChatThread.test.tsx | 19 +++ ui/src/components/IssueChatThread.tsx | 4 +- ui/src/components/TaskChatThread.test.tsx | 10 ++ 9 files changed, 319 insertions(+), 1 deletion(-) create mode 100644 server/src/__tests__/heartbeat-stop-queued-task.test.ts create mode 100644 server/src/services/heartbeat/stopped-waiting-task.ts 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();