diff --git a/server/src/__tests__/issue-comment-reopen-routes.test.ts b/server/src/__tests__/issue-comment-reopen-routes.test.ts index 66fd8f24682..983bc810ab8 100644 --- a/server/src/__tests__/issue-comment-reopen-routes.test.ts +++ b/server/src/__tests__/issue-comment-reopen-routes.test.ts @@ -258,6 +258,12 @@ vi.mock("../services/external-objects.js", () => ({ externalObjectService: () => mockExternalObjectService, })); +const mockAgentTaskWorkspaceHoldRefusesStart = vi.hoisted(() => vi.fn(async (_db: unknown, _input: Record) => false)); +vi.mock("../services/remote-workspace-writer-hold.js", async importOriginal => ({ + ...await importOriginal(), + agentTaskWorkspaceHoldRefusesStart: mockAgentTaskWorkspaceHoldRefusesStart, +})); + vi.mock("../services/cross-issue-influence-limit.js", () => ({ observeCrossIssueInfluence: mockObserveCrossIssueInfluence, crossIssueInfluenceLimitError: mockCrossIssueInfluenceLimitError, @@ -631,6 +637,52 @@ describe("issue comment reopen routes", () => { ); }); + it.each([ + ["post", true, true, 0], ["patch", true, true, 0], ["post", false, true, 1], ["patch", false, true, 1], ["post", true, false, 1], + ] as const)("%s comment (agent author: %s) behind a refusing workspace hold (%s) wakes the assignee %i time(s)", + async (method, agentAuthor, refuses, wakes) => { + const issue = makeIssue("in_progress"); + mockIssueService.getById.mockResolvedValue(issue); + mockIssueService.update.mockImplementation(async (_id: string, patch: Record) => + makeIssueUpdateReceipt(issue, patch)); + mockAgentTaskWorkspaceHoldRefusesStart.mockReset().mockResolvedValue(refuses); + const app = request(await installActor(createApp(), agentAuthor + ? { ...agentActor("33333333-3333-4333-8333-333333333333"), runId: "77777777-7777-4777-8777-777777777777" } : undefined)); + + const res = method === "post" ? await app.post(`/api/issues/${issue.id}/comments`).send({ body: "note" }) + : await app.patch(`/api/issues/${issue.id}`).send({ comment: "note" }); + + expect(res.status, JSON.stringify(res.body)).toBe(method === "post" ? 201 : 200); + if (agentAuthor) await vi.waitFor(() => expect(mockAgentTaskWorkspaceHoldRefusesStart).toHaveBeenCalledWith(mockDb, + { companyId: issue.companyId, issueId: issue.id, agentId: issue.assigneeAgentId })); + else expect(mockAgentTaskWorkspaceHoldRefusesStart).not.toHaveBeenCalled(); + await new Promise(resolve => setImmediate(resolve)); + await vi.waitFor(() => expect(mockHeartbeatService.wakeup.mock.calls.filter(([agentId, wake]) => + agentId === issue.assigneeAgentId && wake.reason === "issue_commented")).toHaveLength(wakes)); + }); + + it.each([[true, 0], [false, 1]] as const)( + "an agent PATCH moving a blocked task to todo with a comment behind a refusing workspace hold (%s) wakes the assignee %i time(s)", + async (refuses, wakes) => { + const issue = makeIssue("blocked"); + mockIssueService.getById.mockResolvedValue(issue); + mockIssueService.update.mockImplementation(async (_id: string, patch: Record) => + makeIssueUpdateReceipt(issue, patch)); + mockAgentTaskWorkspaceHoldRefusesStart.mockReset().mockResolvedValue(refuses); + mockAccessService.decide.mockImplementation(async (input: { action?: string }) => ({ + allowed: input.action !== "tasks:manage_active_checkouts", action: input.action, + reason: "allow_visible_issue_write", explanation: "Allowed by the shared visible-issue write rule." })); + const app = request(await installActor(createApp(), + { ...agentActor("33333333-3333-4333-8333-333333333333"), runId: "77777777-7777-4777-8777-777777777777" })); + + const res = await app.patch(`/api/issues/${issue.id}`).send({ comment: "note", status: "todo" }); + + expect(res.status, JSON.stringify(res.body)).toBe(200); + expect(mockAgentTaskWorkspaceHoldRefusesStart).toHaveBeenCalledTimes(1); + await new Promise(resolve => setImmediate(resolve)); + expect(mockHeartbeatService.wakeup.mock.calls.filter(([agentId]) => agentId === issue.assigneeAgentId)).toHaveLength(wakes); + }); + it.each(["comment", "update"])("accepts an authorized cross-task %s without restoring the target's files", async operation => { const issue = { ...makeIssue("done"), executionWorkspaceId: "33333333-3333-4333-8333-333333333333" }; const actor = { ...agentActor(), source: "agent_jwt", runId: "66666666-6666-4666-8666-666666666666" }; diff --git a/server/src/__tests__/released-writer-escalation.test.ts b/server/src/__tests__/released-writer-escalation.test.ts index 62d3c534c24..60792622299 100644 --- a/server/src/__tests__/released-writer-escalation.test.ts +++ b/server/src/__tests__/released-writer-escalation.test.ts @@ -13,8 +13,8 @@ import { createStorageService } from "../storage/service.js"; import { createReusableLeaseHandoff } from "../services/environment-lease-handoff.js"; import { heartbeatService } from "../services/heartbeat.js"; import { remoteTerminationReceipt } from "../services/remote-execution-termination.js"; -import { readRemoteWorkspaceWriterHold, REMOTE_WORKSPACE_WRITER_PENDING_MESSAGE, remoteWorkspaceHoldRefusesStart } - from "../services/remote-workspace-writer-hold.js"; +import { agentTaskWorkspaceHoldRefusesStart, readRemoteWorkspaceWriterHold, REMOTE_WORKSPACE_WRITER_PENDING_MESSAGE, + remoteWorkspaceHoldRefusesStart } from "../services/remote-workspace-writer-hold.js"; import { REMOTE_WORKSPACE_ABANDONED_EPOCH_SCHEMA } from "../services/remote-workspace-epoch-abandonment.js"; import { reserveRemoteWorkspace } from "../services/remote-workspaces.js"; import { continueTasksAfterWorkspaceWriterReleased, RELEASED_WORKSPACE_WRITER_OUTCOME } @@ -230,6 +230,21 @@ describePostgres("a task stranded behind its own workspace's ended writer", () = expect(wakesFor(f.task.id)).toHaveLength(1); }, 60_000); + it("holds an agent comment wake only while the agent's latest run failed on the hold that still refuses a start", async () => { + const f = await seedStrandedTask({ laterDecision: null }); + const refuses = (agentId = f.agentId) => agentTaskWorkspaceHoldRefusesStart(db, { companyId: f.companyId, issueId: f.task.id, agentId }); + expect(await refuses()).toBe(true); + expect(await refuses(randomUUID())).toBe(false); + + await f.releaseWriter(); + expect(await refuses()).toBe(false); + + const g = await seedStrandedTask({ laterDecision: null }); + await db.insert(heartbeatRuns).values({ companyId: g.companyId, agentId: g.agentId, issueId: g.task.id, status: "succeeded", + finishedAt: new Date(), contextSnapshot: { issueId: g.task.id } }); + expect(await agentTaskWorkspaceHoldRefusesStart(db, { companyId: g.companyId, issueId: g.task.id, agentId: g.agentId })).toBe(false); + }, 60_000); + it("delivers a wake that a crash left pending, and keeps backing off a refused one", async () => { const f = await seedStrandedTask({ laterDecision: null }); await f.releaseWriter(); diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index 0048ee3535e..47762806d9f 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -349,6 +349,7 @@ import { isCloudTrialWorkGateExemptOriginKind, } from "../services/cloud-trial-inference.js"; import { shouldWakeAssigneeForIssueComment } from "../services/issue-comment-wakeup.js"; +import { agentTaskWorkspaceHoldRefusesStart } from "../services/remote-workspace-writer-hold.js"; import { createSecretProposalsService } from "../services/secret-proposals.js"; import { renderOnboardingGreeting, @@ -3695,6 +3696,17 @@ async function recordAgentChildTaskRead(db: Db, req: Request, issue: { id: strin .catch(error => logger.warn({ err: error, runId: req.actor.runId }, "could not record the child task a run read")); } +async function agentWakeHeldByWorkspace(db: Db, input: { + actorType: string; companyId: string; issueId: string; assigneeAgentId: string; +}): Promise { + if (input.actorType !== "agent") return false; + return agentTaskWorkspaceHoldRefusesStart(db, { companyId: input.companyId, issueId: input.issueId, agentId: input.assigneeAgentId }) + .catch(error => { + logger.warn({ err: error, issueId: input.issueId }, "could not read the task workspace hold before an agent-requested wake"); + return false; + }); +} + /** How long a Retry answer waits for admission before it reports the saved request as accepted. */ const TASK_RETRY_ANSWER_ADMISSION_WAIT_MS = 5_000; @@ -17413,13 +17425,23 @@ export function issueRoutes( }); } + let assigneeWakeHeld: Promise | null = null; + const assigneeWakeHeldByWorkspace = (assigneeAgentId: string) => + (assigneeWakeHeld ??= agentWakeHeldByWorkspace(db, { + actorType: actor.actorType, + companyId: issue.companyId, + issueId: issue.id, + assigneeAgentId, + })); + if ( !assigneeChanged && (statusChangedFromBacklog || statusChangedFromBlockedToTodo || statusChangedFromClosedToTodo || userResumedFromReviewToTodo) && - issue.assigneeAgentId + issue.assigneeAgentId && + !(await assigneeWakeHeldByWorkspace(issue.assigneeAgentId)) ) { addWakeup(issue.assigneeAgentId, { source: "automation", @@ -17471,7 +17493,8 @@ export function issueRoutes( assigneeId && !assigneeChanged && !goalCommentSteered && - shouldWakeAssigneeForComment + shouldWakeAssigneeForComment && + !(await assigneeWakeHeldByWorkspace(assigneeId)) ) { addWakeup(assigneeId, { source: "automation", @@ -20974,7 +20997,17 @@ export function issueRoutes( reopened, currentStatus: wakeIssueSnapshot.status, }); - if (assigneeId && !goalCommentSteered && shouldWakeAssigneeForComment) { + if ( + assigneeId && + !goalCommentSteered && + shouldWakeAssigneeForComment && + !(await agentWakeHeldByWorkspace(db, { + actorType: actor.actorType, + companyId: currentIssue.companyId, + issueId: currentIssue.id, + assigneeAgentId: assigneeId, + })) + ) { if (reopened) { addWakeup(assigneeId, { source: "automation", diff --git a/server/src/services/remote-workspace-writer-hold.ts b/server/src/services/remote-workspace-writer-hold.ts index b51f254bd50..af7c98ae7fb 100644 --- a/server/src/services/remote-workspace-writer-hold.ts +++ b/server/src/services/remote-workspace-writer-hold.ts @@ -1,4 +1,4 @@ -import { and, eq, inArray, or, sql } from "drizzle-orm"; +import { and, desc, eq, inArray, or, sql } from "drizzle-orm"; import { environmentLeases, executionWorkspaces, heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations, workspaceOperations, type Db } from "@paperclipai/db"; import { readRemoteWorkspaceAuthority, remoteWorkspaceRunReferenceSchema, type RemoteWorkspaceAuthority } from "@paperclipai/shared"; @@ -185,6 +185,18 @@ export async function failedRunWorkspaceHoldRefusesStart(tx: Db, run: { return remoteWorkspaceHoldRefusesStart(await readRemoteWorkspaceWriterHold(tx, { companyId: run.companyId, authority, runId: run.id }), now); } +export async function agentTaskWorkspaceHoldRefusesStart(tx: Db, input: { + companyId: string; issueId: string; agentId: string; +}, now = Date.now()): Promise { + const [latest] = await tx.select({ id: heartbeatRuns.id, companyId: heartbeatRuns.companyId, errorCode: heartbeatRuns.errorCode, + error: heartbeatRuns.error, contextSnapshot: heartbeatRuns.contextSnapshot }).from(heartbeatRuns) + .where(and(eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.agentId, input.agentId), + sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${input.issueId}`)) + .orderBy(desc(heartbeatRuns.createdAt)).limit(1); + if (!latest) return false; + return failedRunWorkspaceHoldRefusesStart(tx, { ...latest, issueId: input.issueId }, now); +} + /** * Abandons a dirty remote workspace epoch whose ended writer was already * superseded by a recorded successor run, once that successor has also ended