diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index 0e802f1d336..41f8670bc5c 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -1648,6 +1648,8 @@ timeout retries still require a fresh allocation under the policy above. A person's task Retry on a connected task first asks the chat retry owner to repeat the exact failed chat request. When the latest run is that person's own saved board turn that cannot be certified for replay, when no chat retry owner is available, or when that owner refuses (`chat_failed_run_retry_not_authorized`), the refusal and any writes it made are rolled back and the same Retry receipt becomes an ordinary board continuation: the clicking person is the responsible user, the run starts a fresh session from saved work, and no chat action, chat authority, or output replay is created. This is the same authority as a new message from that person. When the conversation still holds saved or unadmitted chat input for the task, Retry keeps the exact-replay path and its refusal, because that input continues through its own admission. Dispatch keeps every normal gate (current task access, executor containment, recovery holds, unadmitted chat input). Projection and the route therefore agree: a shown Retry on a connected task is accepted. Retry that Paperclip requests by itself on a person's behalf (restart recovery, provider limit reset) keeps the exact-replay requirement and still settles on the refusal. A budget resume continues the person's own Retry, so it takes the board continuation too. No migration is needed; tasks blocked by an earlier release become retryable at the next click. +A task whose run was interrupted and whose fresh continuation is recorded reads as continuing (`working`, no Retry) while the continuation waits to be delivered and while it waits in the agent's queue. Once the delivered continuation run has waited in the queue for 15 minutes, the task also offers Retry with `retryAction: "move_forward"`, labelled "Move it forward now". The Retry names that queued run as its observed run, so admission joins it to the run (`coalesced`) and starts no second run; a run that a person joined starts ahead of system recovery work. The offer ends once a person has joined the run or the run starts. While the continuation is still waiting to be delivered, no Retry is offered: a Retry there would start its own run beside the recorded continuation. + The exact replay can also be refused after the click is accepted. This happens when chat source authorization was deferred by a busy identity or endpoint lock, or when it later fails, so the chat retry action settles `failed` with no admitted run. The task Retry receipt is then not failed. If it is a person's Retry, its source run is still the latest run, its chat wake has no run, and no saved or unadmitted chat input remains, the same receipt drops its chat action and becomes the board continuation described above, recorded as `issue.retry_continued_from_saved_work`. Saved chat input whose source comment was written no later than the failed run's stop boundary (the user's recorded Stop request, otherwise `finishedAt`, the same boundary admission uses) does not block this: admission holds such input as `message_predates_stop`, so it can never start alone. The continuation adopts it (the input receipt is coalesced into the Retry receipt) and the task continues from saved work. Saved input that arrived after the stop keeps its own admission path, and the Retry still settles as failed. When the latest run is an admission that the recovery hold cancelled before dispatch (`execution_reconciliation_required`), the saved work that counts is the recovered work of the run whose recovery action held it. The deferred-receipt worker dispatches it with every normal gate. Retry that Paperclip requests by itself still settles as failed. When a failed run's saved work is recovered, the task's execution blocker offers Retry (also on a connected task) and says "Saved work recovered. Retry continues from it." A stopped (cancelled) run keeps "Send a message to continue." ### Saved chat Retry preparation diff --git a/packages/shared/src/types/execution-projection.ts b/packages/shared/src/types/execution-projection.ts index e72e641602b..247fd3cc8e1 100644 --- a/packages/shared/src/types/execution-projection.ts +++ b/packages/shared/src/types/execution-projection.ts @@ -145,6 +145,7 @@ export interface TaskInterruptionPresentation { state: "working" | "retry_scheduled" | "failed" | "waiting_for_user" | "resolved"; nextRetryAt: string | null; canRetry: boolean; + retryAction?: "move_forward"; userAction: "approval" | "reconnect" | "assign_agent" | "choose_model" | "resume" | "budget" | "project_access" /** Board confirms that a previous server, which can no longer report, stopped its workspace copyback. */ | "confirm_owner_stop" diff --git a/packages/shared/src/validators/issue.ts b/packages/shared/src/validators/issue.ts index 307eb382514..120ffa23b57 100644 --- a/packages/shared/src/validators/issue.ts +++ b/packages/shared/src/validators/issue.ts @@ -646,6 +646,7 @@ export const retryWorkspaceExportSchema = z.object({ export const taskRetrySchema = z.object({ idempotencyKey: z.string().guid(), observedRunId: z.string().guid().nullable(), + retryAction: z.literal("move_forward").optional(), }).strict(); export const recoverWorkspaceSchema = z.object({ diff --git a/server/src/__tests__/recovery-wake-herd.test.ts b/server/src/__tests__/recovery-wake-herd.test.ts index 8b6eeee1231..e83b7fb2735 100644 --- a/server/src/__tests__/recovery-wake-herd.test.ts +++ b/server/src/__tests__/recovery-wake-herd.test.ts @@ -14,6 +14,7 @@ import { PENDING_CONTINUATION_BOUND_MS, assignedWorkSweep } from "../services/re import { evaluateAssignedWork } from "../services/recovery/assigned-work-invariant.js"; import { taskInterruptionPresentation } from "../services/task-interruption-presentation.js"; import { executionControlSchedule } from "../services/execution-control-work.js"; +import { requestTaskRetry } from "../services/task-retry.js"; const support = await getEmbeddedPostgresTestSupport(); const suite = support.supported ? describe : describe.skip; @@ -702,4 +703,136 @@ suite("recovery wake herd", () => { await heartbeat.drainActiveRunExecutions(); } }, 60_000); + + async function continuationWaitingInQueue(agentId: string, queuedMinutesAgo: number) { + const record = await pendingContinuation(agentId, queuedMinutesAgo + 2); + const wake = fakeWake(); + await deliverReconciledExecutions(db, wake as never); + expect(wake).toHaveBeenCalledTimes(1); + const delivered = await wake.mock.results[0]!.value as typeof heartbeatRuns.$inferSelect; + const [continuation] = await db.update(heartbeatRuns).set({ createdAt: new Date(Date.now() - queuedMinutesAgo * 60_000) }) + .where(eq(heartbeatRuns.id, delivered.id)).returning(); + const busy = await task(agentId); + const [olderWork] = await db.insert(heartbeatRuns).values({ companyId, agentId, issueId: busy.id, invocationSource: "assignment", + status: "queued", createdAt: new Date(Date.now() - (queuedMinutesAgo + 4) * 60_000), + contextSnapshot: { issueId: busy.id, wakeReason: "issue_assigned" } }).returning(); + const [issueRow] = await db.select().from(issues).where(eq(issues.id, record.issue.id)); + return { ...record, continuation: continuation!, olderWork: olderWork!, issueRow: issueRow! }; + } + + const runsOfTask = async (issueId: string, sourceRunId: string) => db.select().from(heartbeatRuns) + .where(and(eq(heartbeatRuns.issueId, issueId), sql`${heartbeatRuns.id} <> ${sourceRunId}`)); + + it("moves a continuation that waited 15 minutes forward on a person's Retry, which joins it and starts no second run", async () => { + const agentId = await seedCompany(1); + const waiting = await continuationWaitingInQueue(agentId, 16); + expect(await deliveryOf(waiting.action.id)).toBe("delivered"); + const shown = await taskInterruptionPresentation(db, waiting.issueRow); + expect(shown).toMatchObject({ responsibility: "system", state: "working", canRetry: true, retryAction: "move_forward", + observedRunId: waiting.continuation.id }); + const heartbeat = heartbeatService(db); + try { + const receipt = await requestTaskRetry({ db, companyId, issueId: waiting.issue.id, actorId: userId, + observedRunId: shown!.observedRunId, retryAction: shown!.retryAction, idempotencyKey: randomUUID() }); + expect(receipt).toMatchObject({ accepted: true, stale: false }); + await heartbeat.resumeTaskRetry(companyId, receipt.requestId!); + expect((await runsOfTask(waiting.issue.id, waiting.source.id)).map(run => run.id)).toEqual([waiting.continuation.id]); + const [retryWake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, receipt.requestId!)); + expect(retryWake).toMatchObject({ status: "coalesced", runId: waiting.continuation.id, requestedByActorType: "user" }); + const after = await taskInterruptionPresentation(db, waiting.issueRow); + expect(after).toMatchObject({ state: "working", canRetry: false }); + expect(after?.retryAction).toBeUndefined(); + + await deliverReconciledExecutions(db, fakeWake() as never); + await heartbeat.resumeQueuedRuns(); + expect((await readRun(waiting.continuation.id)).startedAt).not.toBeNull(); + expect(await readRun(waiting.olderWork.id)).toMatchObject({ status: "queued", startedAt: null }); + } finally { + await heartbeat.drainActiveRunExecutions(); + } + await heartbeat.resumeQueuedRuns(); + await heartbeat.drainActiveRunExecutions(); + expect((await runsOfTask(waiting.issue.id, waiting.source.id)).map(run => run.id)).toEqual([waiting.continuation.id]); + }, 120_000); + + it("starts nothing when the continuation ended between showing Move it forward now and the click", async () => { + const agentId = await seedCompany(1); + const waiting = await continuationWaitingInQueue(agentId, 16); + const shown = await taskInterruptionPresentation(db, waiting.issueRow); + expect(shown).toMatchObject({ canRetry: true, retryAction: "move_forward", observedRunId: waiting.continuation.id }); + await db.update(heartbeatRuns).set({ status: "failed", errorCode: "adapter_failed", startedAt: new Date(), finishedAt: new Date() }) + .where(eq(heartbeatRuns.id, waiting.continuation.id)); + const heartbeat = heartbeatService(db); + try { + const receipt = await requestTaskRetry({ db, companyId, issueId: waiting.issue.id, actorId: userId, + observedRunId: shown!.observedRunId, retryAction: shown!.retryAction, idempotencyKey: randomUUID() }); + expect(receipt).toMatchObject({ accepted: false, alreadyMovedOn: true, requestId: null }); + await heartbeat.resumeQueuedRuns(); + expect((await runsOfTask(waiting.issue.id, waiting.source.id)).map(run => run.id)).toEqual([waiting.continuation.id]); + expect(await db.select().from(agentWakeupRequests).where(and(eq(agentWakeupRequests.reason, "task_retry"), + sql`${agentWakeupRequests.payload}->>'issueId' = ${waiting.issue.id}`))).toEqual([]); + } finally { + await heartbeat.drainActiveRunExecutions(); + } + }, 120_000); + + async function endContinuationAndRunEveryPass(waiting: Awaited>, + heartbeat: ReturnType, retryRequestId?: string) { + await heartbeat.cancelRun(waiting.continuation.id); + expect(await readRun(waiting.continuation.id)).toMatchObject({ status: "cancelled" }); + for (let pass = 0; pass < 2; pass += 1) { + await heartbeat.resumeExecutionWaitComments({ companyId }); + if (retryRequestId) await heartbeat.resumeTaskRetry(companyId, retryRequestId); + await deliverReconciledExecutions(db, heartbeat.wakeup); + await heartbeat.resumeQueuedRuns(); + } + return (await runsOfTask(waiting.issue.id, waiting.source.id)).filter(run => run.id !== waiting.continuation.id) + .map(run => run.contextSnapshot?.wakeReason); + } + + it("never turns a joined move-forward click into a new run after the continuation it joined ends", async () => { + let withoutClick: unknown[] = []; + { + const agentId = await seedCompany(1); + const control = await continuationWaitingInQueue(agentId, 16); + const heartbeat = heartbeatService(db); + try { withoutClick = await endContinuationAndRunEveryPass(control, heartbeat); } + finally { await heartbeat.drainActiveRunExecutions(); } + } + const agentId = await seedCompany(1); + const waiting = await continuationWaitingInQueue(agentId, 16); + const shown = await taskInterruptionPresentation(db, waiting.issueRow); + const heartbeat = heartbeatService(db); + try { + const receipt = await requestTaskRetry({ db, companyId, issueId: waiting.issue.id, actorId: userId, + observedRunId: shown!.observedRunId, retryAction: shown!.retryAction, idempotencyKey: randomUUID() }); + expect(receipt).toMatchObject({ accepted: true }); + await heartbeat.resumeTaskRetry(companyId, receipt.requestId!); + await endContinuationAndRunEveryPass(waiting, heartbeat, receipt.requestId!); + const [retryWake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, receipt.requestId!)); + expect(retryWake).toMatchObject({ status: "coalesced", runId: waiting.continuation.id }); + const later = (await runsOfTask(waiting.issue.id, waiting.source.id)).filter(run => run.id !== waiting.continuation.id); + expect(later.filter(run => run.wakeupRequestId === receipt.requestId || run.contextSnapshot?.wakeReason === "task_retry" + || run.contextSnapshot?.taskRetryRequestId)).toEqual([]); + expect(later.map(run => run.contextSnapshot?.wakeReason)).toEqual(withoutClick); + } finally { + await heartbeat.drainActiveRunExecutions(); + } + }, 120_000); + + it("leaves a continuation that waited under 15 minutes in its place, with no Retry", async () => { + const agentId = await seedCompany(1); + const waiting = await continuationWaitingInQueue(agentId, 14); + const shown = await taskInterruptionPresentation(db, waiting.issueRow); + expect(shown).toMatchObject({ state: "working", canRetry: false }); + expect(shown?.retryAction).toBeUndefined(); + const heartbeat = heartbeatService(db); + try { + await heartbeat.resumeQueuedRuns(); + expect((await readRun(waiting.olderWork.id)).startedAt).not.toBeNull(); + expect(await readRun(waiting.continuation.id)).toMatchObject({ status: "queued", startedAt: null }); + } finally { + await heartbeat.drainActiveRunExecutions(); + } + }, 120_000); }); diff --git a/server/src/__tests__/task-interruption-automatic-path.test.ts b/server/src/__tests__/task-interruption-automatic-path.test.ts index 1fea7c136d6..9ef720cfacc 100644 --- a/server/src/__tests__/task-interruption-automatic-path.test.ts +++ b/server/src/__tests__/task-interruption-automatic-path.test.ts @@ -144,6 +144,78 @@ describe.skipIf(!support.supported)("Retry is offered only when no automatic pat expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ state: "failed", canRetry: true, observedRunId: nextRunId }); }); + async function seedQueuedContinuation(queuedMinutesAgo: number, status: "queued" | "running" = "queued") { + const task = await seedRecordedContinuation(queuedMinutesAgo + 2); + await db.update(heartbeatRuns).set({ createdAt: new Date(Date.now() - (queuedMinutesAgo + 4) * 60_000) }) + .where(eq(heartbeatRuns.id, task.runId)); + const nextRunId = randomUUID(); + await db.insert(heartbeatRuns).values({ id: nextRunId, companyId: task.companyId, agentId: task.agentId, nativeIssueId: task.issue.id, + scopeKind: "issue", status, runtimeMode: "native", retryOfRunId: task.runId, + createdAt: new Date(Date.now() - queuedMinutesAgo * 60_000), + contextSnapshot: { issueId: task.issue.id, wakeReason: "issue_recovery_action_restored", previousRunId: task.runId, + recoveryActionId: task.primary.id } }); + await db.update(issueRecoveryActions).set({ evidence: { ...task.primary.evidence, continuationDelivery: "delivered", + continuationRunId: nextRunId } }).where(eq(issueRecoveryActions.id, task.primary.id)); + return { ...task, nextRunId }; + } + + it("offers a person a way to move a continuation forward once it has waited 15 minutes to start, without calling it failed", async () => { + for (const minutesAgo of [15, 45, 110]) { + const { issue, nextRunId } = await seedQueuedContinuation(minutesAgo); + expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ responsibility: "system", state: "working", + canRetry: true, retryAction: "move_forward", observedRunId: nextRunId }); + } + }); + + it("keeps a continuation that has waited under 15 minutes as continuing with no Retry", async () => { + const { issue, nextRunId } = await seedQueuedContinuation(14); + const presentation = await taskInterruptionPresentation(db, issue); + expect(presentation).toMatchObject({ state: "working", canRetry: false, observedRunId: nextRunId }); + expect(presentation?.retryAction).toBeUndefined(); + }); + + it("offers no Retry while a recorded continuation is still being delivered, however long it waits", async () => { + for (const minutesAgo of [16, 45, 110]) { + const { issue } = await seedRecordedContinuation(minutesAgo); + const presentation = await taskInterruptionPresentation(db, issue); + expect(presentation).toMatchObject({ state: "working", canRetry: false }); + expect(presentation?.retryAction).toBeUndefined(); + } + }); + + it("offers no Retry for a continuation that is already running", async () => { + const { issue } = await seedQueuedContinuation(45, "running"); + const presentation = await taskInterruptionPresentation(db, issue); + expect(presentation).toMatchObject({ state: "working", canRetry: false }); + expect(presentation?.retryAction).toBeUndefined(); + }); + + it("offers no second Retry once a person already moved the waiting continuation forward", async () => { + const { companyId, agentId, issue, nextRunId } = await seedQueuedContinuation(45); + await db.insert(agentWakeupRequests).values({ companyId, agentId, source: "on_demand", triggerDetail: "manual", + reason: "task_retry", status: "coalesced", requestedByActorType: "user", requestedByActorId: randomUUID(), + runId: nextRunId, finishedAt: new Date(), payload: { issueId: issue.id } }); + const presentation = await taskInterruptionPresentation(db, issue); + expect(presentation).toMatchObject({ state: "working", canRetry: false }); + expect(presentation?.retryAction).toBeUndefined(); + }); + + it("offers no Retry for queued work that is not a recorded continuation, however long it waits", async () => { + const { companyId, agentId, issue } = await seedTask("todo"); + await db.insert(heartbeatRuns).values({ companyId, agentId, nativeIssueId: issue.id, scopeKind: "issue", status: "queued", + runtimeMode: "native", createdAt: new Date(Date.now() - 45 * 60_000), contextSnapshot: { issueId: issue.id, wakeReason: "issue_assigned" } }); + const presentation = await taskInterruptionPresentation(db, issue); + expect(presentation).toMatchObject({ state: "working", canRetry: false }); + expect(presentation?.retryAction).toBeUndefined(); + }); + + it("asks a person to resume a paused agent instead of offering to move its waiting continuation forward", async () => { + const { agentId, issue } = await seedQueuedContinuation(45); + await db.update(agents).set({ status: "paused", pauseReason: "manual" }).where(eq(agents.id, agentId)); + expect(await taskInterruptionPresentation(db, issue)).toMatchObject({ responsibility: "user", state: "waiting_for_user", + userAction: "resume", canRetry: false }); + }); + it("still offers Retry for a resolved recovery record that recorded no continuation", async () => { const { issue, hold } = await seedSwapEndedRun(new Date(Date.now() - 45 * 60_000)); await db.update(issueRecoveryActions).set({ status: "resolved", outcome: "restored", resolvedAt: new Date(Date.now() - 40 * 60_000), diff --git a/server/src/services/task-interruption-presentation.ts b/server/src/services/task-interruption-presentation.ts index 53020da5e06..a4895f42acc 100644 --- a/server/src/services/task-interruption-presentation.ts +++ b/server/src/services/task-interruption-presentation.ts @@ -42,6 +42,7 @@ const NATIVE_RESUME_DISPATCH_GRACE_MS = 2 * 60_000; const QUEUED_INTERRUPT_HANDOFF_GRACE_MS = 5 * 60_000; const QUEUED_INPUT_DISPATCH_GRACE_MS = 2 * 60_000; const AUTOMATIC_DISPOSITION_GRACE_MS = 2 * 60_000; +const WAITING_CONTINUATION_MOVE_FORWARD_MS = 15 * 60_000; type ProjectionIssue = Pick; type ProjectionRun = Pick= WAITING_CONTINUATION_MOVE_FORWARD_MS) + return { ...base, state: "working", canRetry: true, retryAction: "move_forward" }; if (["running", "queued"].includes(run.status)) return { ...base, state: "working" }; // Paperclip is continuing the task by itself: no failed attempt and no Retry. if (input.freshContinuation?.state === "continuing") return { ...base, state: "working", canRetry: false }; @@ -642,6 +648,23 @@ export async function taskInterruptionPresentations(db: Db, companyId: string, i automaticDispositionAt.set(row.issueId, Math.max(automaticDispositionAt.get(row.issueId) ?? 0, row.updatedAt.getTime())); } } + const queuedContinuationIds = runs.filter(run => run.status === "queued" && run.createdAt + && run.createdAt.getTime() <= Date.now() - WAITING_CONTINUATION_MOVE_FORWARD_MS).map(run => run.id); + const [continuationRows, personRows] = queuedContinuationIds.length ? await Promise.all([ + db.select({ runId: sql`${issueRecoveryActions.evidence}->>'continuationRunId'` }).from(issueRecoveryActions).where(and( + eq(issueRecoveryActions.companyId, companyId), inArray(issueRecoveryActions.sourceIssueId, ids), + sql`${issueRecoveryActions.evidence} ? 'freshContinuation'`, + sql`${issueRecoveryActions.evidence}->>'continuationDelivery' = 'delivered'`, + inArray(sql`${issueRecoveryActions.evidence}->>'continuationRunId'`, queuedContinuationIds))), + db.select({ runId: agentWakeupRequests.runId }).from(agentWakeupRequests).where(and( + eq(agentWakeupRequests.companyId, companyId), inArray(agentWakeupRequests.runId, queuedContinuationIds), + eq(agentWakeupRequests.requestedByActorType, "user"))), + ]) : [[], []]; + const waitingContinuationRunIds = new Set(continuationRows.map(row => row.runId)); + const personRequestedRunIds = new Set(personRows.flatMap(row => row.runId ? [row.runId] : [])); + const waitingContinuationFor = (run: typeof runs[number] | undefined): ProjectionState["waitingContinuation"] => + run?.createdAt && waitingContinuationRunIds.has(run.id) + ? { queuedAt: run.createdAt.getTime(), personRequested: personRequestedRunIds.has(run.id) } : undefined; const ownerStops = runIds.length ? await db.select({ issueId: issueRecoveryActions.sourceIssueId, runId: sql`${issueRecoveryActions.evidence}->>'runId'` }).from(issueRecoveryActions).where(and( eq(issueRecoveryActions.companyId, companyId), inArray(issueRecoveryActions.sourceIssueId, ids), @@ -755,6 +778,7 @@ export async function taskInterruptionPresentations(db: Db, companyId: string, i const presentation = projectTaskInterruption(issue, { ...facts, freshContinuation: freshContinuationFor(issue.id, facts.run?.id), automaticDispositionAt: automaticDispositionAt.get(issue.id), + waitingContinuation: waitingContinuationFor(facts.run), recoveryHandedToPerson: handedToPerson.has(issue.id), interruptWait: interruptWaitFor(issue.id), projectAccessAllowed: denied?.length === 0, @@ -793,6 +817,7 @@ export async function taskInterruptionPresentations(db: Db, companyId: string, i const presentation = result.get(issueId); if (!presentation || !blocker || blocker.canRetry) continue; presentation.canRetry = false; + delete presentation.retryAction; if (!presentation.retryWait && blocker.workspaceRecovery && blocker.workspaceRecovery.status !== "recovered") presentation.retryWait = { reason: "workspace_repair_required", message: retryWaitMessages.workspace_repair_required! }; } diff --git a/server/src/services/task-retry.ts b/server/src/services/task-retry.ts index 758418e40b0..80a91e68ef3 100644 --- a/server/src/services/task-retry.ts +++ b/server/src/services/task-retry.ts @@ -244,6 +244,7 @@ export async function retireTaskRetriesContinuedBy(db: Db, input: { type TaskRetryRequest = { db: Db; companyId: string; issueId: string; actorId: string; idempotencyKey: string; observedRunId: string | null; actorSource?: string; + retryAction?: "move_forward"; /** Paperclip requests the user's Retry itself: after a restart lost an * unstarted turn, or once a provider usage limit it waited on has reset. */ initiatedBy?: "restart_recovery" | "provider_limit_reset"; @@ -318,6 +319,8 @@ function admitTaskRetry(input: TaskRetryRequest) { latest.agentId !== issue.assigneeAgentId || input.observedRunId !== latest.id) { return { requestId: null, accepted: false, stale: true, observedRunId: latest?.id ?? null, chatActionId: undefined }; } + if (input.retryAction === "move_forward" && !["queued", "running"].includes(latest.status)) + return { requestId: null, accepted: false, stale: false, alreadyMovedOn: true, observedRunId: latest.id, chatActionId: undefined }; let active = (await tx.select().from(agentWakeupRequests).where(and( eq(agentWakeupRequests.companyId, issue.companyId), eq(agentWakeupRequests.agentId, issue.assigneeAgentId), sql`${agentWakeupRequests.payload}->>'issueId' = ${issue.id}`, diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 247e5601cb2..7aa21208c0c 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -395,7 +395,7 @@ "packages/shared/src/types/email.ts": "556ff6a0dcefa01eb704d6d00d3b191de81ff4dc", "packages/shared/src/types/environment.ts": "a380b9ce9d2d1763011e9adaa58615a3ef1e56c5", "packages/shared/src/types/execution-continuation.ts": "5afe62afd227efa03ff847d8f73291c14707ab5b", - "packages/shared/src/types/execution-projection.ts": "e72e641602b296f6d3e16d07700629df3039a7b1", + "packages/shared/src/types/execution-projection.ts": "247fd3cc8e10fef3f2ebad65d6c1148e1d4c68ab", "packages/shared/src/types/external-object.ts": "7a225e0f5a6777d449019a30530c858b753eb4c1", "packages/shared/src/types/feedback.ts": "c5eb31545c7f67c04ad9afd9db45a6b4774bcb35", "packages/shared/src/types/finance.ts": "5c2208c7950020f1005aa0dd86a1680c54dd4354", @@ -488,7 +488,7 @@ "packages/shared/src/validators/issue-chat-bootstrap.test.ts": "e1ebb9aa94da22c825bc3ddd32ce2cfc98bfe645", "packages/shared/src/validators/issue-tree-control.ts": "7144ef86a83e008ac0626e1d62a1d6164c46f438", "packages/shared/src/validators/issue.test.ts": "9a10bf1112d7c85f80cc1fd5db9920dda8974643", - "packages/shared/src/validators/issue.ts": "307eb382514fdce6124f36cbf313df2c1cbd8c3a", + "packages/shared/src/validators/issue.ts": "120ffa23b571374453a9777992b7e400d789403e", "packages/shared/src/validators/native-finalization.test.ts": "40c68bdd1d0e8a77cd70c4576fae53334fe5be0d", "packages/shared/src/validators/native-finalization.ts": "d4e674de6ac7d36385e6f6c2172fa16ffc9b1830", "packages/shared/src/validators/onboarding-seed.ts": "de302a8400d4199053f379d9ed853522a3ac6d32", diff --git a/ui/src/api/issues.ts b/ui/src/api/issues.ts index 16dfffa285c..150da3e578d 100644 --- a/ui/src/api/issues.ts +++ b/ui/src/api/issues.ts @@ -446,8 +446,8 @@ export const issuesApi = { api.post<{ runId: string; resultId: string | null; status: "queued" }>(`/issues/${id}/recovery-actions/resume-workspace-finalization`, data), retryWorkspaceExport: (id: string, data: { actionId: string; runId: string; repairNote: string }) => api.post<{ runId: string; resultId: string; leaseId: string; status: "queued" }>(`/issues/${id}/recovery-actions/retry-workspace-export`, data), - retryTask: (issueId: string, body: { idempotencyKey: string; observedRunId: string | null }) => - api.post<{ requestId: string | null; accepted: boolean; stale: boolean; + retryTask: (issueId: string, body: { idempotencyKey: string; observedRunId: string | null; retryAction?: "move_forward" }) => + api.post<{ requestId: string | null; accepted: boolean; stale: boolean; alreadyMovedOn?: boolean; scheduledRetry?: { outcome: "promoted" | "already_promoted" | "gate_suppressed" | "waiting" | "no_scheduled_retry"; message: string }; presentation: import("@paperclipai/shared").TaskInterruptionPresentation | null }>(`/issues/${issueId}/retry`, body), recoverWorkspace: (id: string, data: { actionId: string; runId: string; idempotencyKey: string }) => diff --git a/ui/src/components/ExecutionBlockerNotice.test.tsx b/ui/src/components/ExecutionBlockerNotice.test.tsx index 311816ce9d8..2b1d388ca16 100644 --- a/ui/src/components/ExecutionBlockerNotice.test.tsx +++ b/ui/src/components/ExecutionBlockerNotice.test.tsx @@ -66,6 +66,26 @@ describe("ordinary task interruption", () => { it.each(["working", "resolved"] as const)("does not duplicate the thread indicator for %s", async state => { await render({ ...failed, state }); expect(container.textContent).toBe(""); }); + it("offers to move a waiting continuation forward in plain words, without reporting a failure", async () => { + await render({ ...failed, state: "working", retryAction: "move_forward" }); + expect(container.textContent).toContain("Paperclip continues this task by itself."); + expect(container.textContent).not.toMatch(/Couldn’t finish|failed|continuation|queue|run\b/i); + const button = container.querySelector('[data-testid="task-execution-move-forward"]'); + expect(button?.textContent).toBe("Move it forward now"); + expect(container.querySelectorAll("button")).toHaveLength(1); + await act(async () => button!.click()); + expect(retry).toHaveBeenCalledOnce(); + }); + + it("shows a waiting continuation without the button to a read-only user, or once the move was requested", async () => { + await act(async () => root.render()); + expect(container.textContent).toContain("Paperclip continues this task by itself."); + expect(container.querySelector("button")).toBeNull(); + await render({ ...failed, state: "working", canRetry: false }); + expect(container.textContent).toBe(""); + }); + it("names the admission hold a task that has not started waits for", async () => { await render({ ...failed, state: "working", canRetry: false, sourceRunIds: [], observedRunId: null, retryWait: { reason: "budget.blocked", message: "Waiting for the budget to allow new work. The task starts automatically when it does." } }); diff --git a/ui/src/components/ExecutionBlockerNotice.tsx b/ui/src/components/ExecutionBlockerNotice.tsx index e082d512dec..59ad7ec2372 100644 --- a/ui/src/components/ExecutionBlockerNotice.tsx +++ b/ui/src/components/ExecutionBlockerNotice.tsx @@ -71,6 +71,11 @@ export function ExecutionBlockerNotice({ presentation, canRetry, onRetry, optimi } if (step && presentation?.state === "working") return
{`${step}…`}
; + if (!optimistic && presentation?.state === "working" && presentation.retryAction === "move_forward" && presentation.canRetry) + return
+ Waiting for the agent to finish other work. Paperclip continues this task by itself. + {canRetry && } +
; // A task that has not started yet names the admission hold it waits for. if (!optimistic && presentation?.state === "working" && presentation.retryWait) { const dependencies = presentation.retryWait.reason === "dependency_blocked" ? blockers ?? [] : []; diff --git a/ui/src/hooks/useTaskRetry.test.tsx b/ui/src/hooks/useTaskRetry.test.tsx index 773b6dafa8c..4eb14cd3045 100644 --- a/ui/src/hooks/useTaskRetry.test.tsx +++ b/ui/src/hooks/useTaskRetry.test.tsx @@ -57,6 +57,19 @@ describe("optimistic task Retry", () => { await render({ ...waiting, interruption: { ...presentation, state: "working", canRetry: false } } as Issue); expect(container.querySelector('[role="alert"]')).toBeNull(); }); + it("sends the move-forward intent from the offer and says plainly when the task already moved on", async () => { + const presentation = { intentId: null, responsibility: "system" as const, state: "working" as const, canRetry: true, + retryAction: "move_forward" as const, nextRetryAt: null, userAction: null, sourceRunIds: ["continuation"], observedRunId: "continuation" }; + vi.mocked(issuesApi.retryTask).mockResolvedValue({ requestId: null, accepted: false, stale: false, alreadyMovedOn: true, + presentation: { ...presentation, canRetry: false, retryAction: undefined } } as Awaited>); + await render({ ...issue, interruption: presentation } as Issue); + await act(async () => container.querySelector("button")!.click()); + expect(issuesApi.retryTask).toHaveBeenCalledExactlyOnceWith("task", { + observedRunId: "continuation", retryAction: "move_forward", idempotencyKey: expect.any(String), + }); + expect(container.querySelector('[role="alert"]')?.textContent).toContain("already moved on, so nothing new was started"); + }); + it("shows nothing extra when Retry promoted the scheduled run", async () => { vi.mocked(issuesApi.retryTask).mockResolvedValue({ requestId: "retry", accepted: true, stale: false, scheduledRetry: { outcome: "promoted", message: "Retry promoted" }, presentation: null }); diff --git a/ui/src/hooks/useTaskRetry.ts b/ui/src/hooks/useTaskRetry.ts index 54545ff7af9..bbcb06fa6a2 100644 --- a/ui/src/hooks/useTaskRetry.ts +++ b/ui/src/hooks/useTaskRetry.ts @@ -6,12 +6,16 @@ import { issuesApi } from "../api/issues"; import { queryKeys } from "../lib/queryKeys"; import { createUuid } from "../lib/uuid"; -type RetryRequest = { issueId: string; identifier?: string | null; idempotencyKey: string; observedRunId: string | null }; +type RetryRequest = { issueId: string; identifier?: string | null; idempotencyKey: string; observedRunId: string | null; + retryAction?: "move_forward" }; type RetryResult = Awaited>; export const STALE_TASK_RETRY_MESSAGE = "This attempt was already replaced, so Retry did not start new work. The task now shows its current state."; +export const ALREADY_MOVED_ON_MESSAGE = "The task already moved on, so nothing new was started. It now shows its current state."; + export function taskRetryNotStartedReason(result: RetryResult): string | null { + if (!result.accepted && result.alreadyMovedOn) return ALREADY_MOVED_ON_MESSAGE; if (!result.accepted) return STALE_TASK_RETRY_MESSAGE; const outcome = result.scheduledRetry?.outcome; if (outcome && outcome !== "promoted" && outcome !== "already_promoted") return result.scheduledRetry!.message; @@ -95,7 +99,8 @@ export function useTaskRetry(issue: Issue | undefined) { setNotStarted(null); mutation.reset(); request.current ??= { issueId: issue.id, identifier: issue.identifier, idempotencyKey: createUuid(), - observedRunId: issue.interruption?.observedRunId ?? issue.executionBlocker?.runId ?? null }; + observedRunId: issue.interruption?.observedRunId ?? issue.executionBlocker?.runId ?? null, + ...(issue.interruption?.retryAction === "move_forward" ? { retryAction: "move_forward" as const } : {}) }; setOptimistic(true); setTakingLonger(false); mutation.mutate(request.current); diff --git a/ui/src/pages/Inbox.tsx b/ui/src/pages/Inbox.tsx index cc6bb8e57cd..8d5e0c718c3 100644 --- a/ui/src/pages/Inbox.tsx +++ b/ui/src/pages/Inbox.tsx @@ -416,7 +416,7 @@ export function FailedRunInboxRow({ confirm_owner_stop: "Confirm the previous server stopped", confirm_run_stopped: "Confirm the previous run stopped", }[interruption.userAction ?? "resume"]) : runFailureMessage(run); - const retryAvailable = !interruption || interruption.canRetry; + const retryAvailable = !interruption || (interruption.canRetry && interruption.retryAction !== "move_forward"); const showUnreadSlot = unreadState !== null; const showUnreadDot = unreadState === "visible" || unreadState === "fading";