diff --git a/doc/PRODUCT.md b/doc/PRODUCT.md index c4c28fedf37..8bd41009632 100644 --- a/doc/PRODUCT.md +++ b/doc/PRODUCT.md @@ -93,6 +93,12 @@ Tasks have parentage. Every task exists in service of a parent task, all the way The current issue model includes stable issue identifiers, parent/sub-issues, blockers, a single assignee, comments, issue documents, attachments and work products, and review/approval handoffs. That structure keeps work inspectable by both the board and agents while still allowing agents to decompose work into smaller tasks. +Automatic monitor checks pause when a task is blocked. A person can use Check now +to request one check of a retained monitor through normal execution admission. +Dependencies, recovery, pause, budgets and ownership still apply. Provider-usage +recovery stays paused until the task resumes. A check that +cannot start reports that result instead of claiming it was queued. + The experimental Cases feature also supports persistent work records and prompt-driven agent handoffs. Native case creation requires kickoff and creates one primary task; later handoffs move that same task diff --git a/doc/SPEC-implementation.md b/doc/SPEC-implementation.md index bac9acad7b9..3b9d918e848 100644 --- a/doc/SPEC-implementation.md +++ b/doc/SPEC-implementation.md @@ -767,6 +767,7 @@ V1 non-terminal liveness rule: - A published advisory GitHub review can also remain `in_review` through an authorized external response wait or a saved monitor. Rating, CI state, and merge state alone do not create human attention. The current committed wait is an action path while its assigned endpoint and conversation remain active; it creates no Mine participation. - a blocked chain is covered only when each unresolved leaf issue is live or explicitly waiting - external waits are durable only when persisted as a bounded monitor/scheduled wake, a first-class blocker with a named owner and action, or healthy delegated child work connected by a blocker edge when the source must wait; parent/child structure alone is not a wait path +- automatic monitor checks require an agent-owned task in `in_progress` or `in_review`; an authorized human may request one check of a retained monitor on a `blocked` task through normal admission without changing its status or bypassing dependency, recovery, ownership, pause or budget gates; provider-quota recovery monitors remain paused until the task resumes; a skipped manual dispatch returns a conflict instead of claiming success - unmanaged shell jobs, detached sessions, adapter child processes, local polling loops, PIDs, logs, and comments are evidence rather than liveness; a managed runtime service counts only when paired with a persisted monitor, wake, blocker, or delegated issue that owns the next check - heartbeat finalization evaluates liveness from persisted Paperclip state; an issue cannot remain healthy `in_progress` solely because the exiting heartbeat started a local/background watcher - a continuation cancelled as `issue_continuation_waiting_on_review` first converts a current typed wait target into a first-class wait; without a current target it is classified as `deliberate_wait_without_target` and gives the invokable original owner five normal-model disposition-repair attempts (immediate, then after 60, 120, 240, and 480 seconds, with up to 10 percent jitter) diff --git a/doc/plans/2026-10-25-failed-retry-notices-sleep-audit.md b/doc/plans/2026-10-25-failed-retry-notices-sleep-audit.md index 765bf9e4801..c7b92fcb356 100644 --- a/doc/plans/2026-10-25-failed-retry-notices-sleep-audit.md +++ b/doc/plans/2026-10-25-failed-retry-notices-sleep-audit.md @@ -416,3 +416,35 @@ not been published, and the parent has a new current-head P1 about ordinary inpu restoration that must be repaired and adopted before this slice can merge. Fresh exact-head remote CI/review, full repository acceptance and deployed sleep are separate claims; no live provider or physical sleep result is asserted here. + + +## Final landed-parent acceptance — October 28 + +The preceding inbound notice PR #17647 has now merged at +`1aa3a21ac41f602977638cf0be875b01a243e69f`, including both discovery and restored-input +wake repairs. The current normal two-parent integration is +`43d0f84ea56845b8fc4946a7533ecbf7f07b679a`, with parents the prepared retry slice +`c56cc27611c76587a278ac175470e0b4646b7b5f` and actual master. Squash ancestry makes +the ordinary historical merge report eight conflicts. Using the verified landed +parent `41f7e2c9e351efa6cfa5ef699c0e69df7425012b` as the semantic merge base yields +a clean tree. The full 19-path owned binary patch is identical and all 23 unrelated +master paths/deletions are preserved. That proved tree resolves the ancestry-only +conflicts in an ordinary two-parent merge; no rebase or force push is used. + +Current combined-master acceptance passes **42 distinct cases**: 21 retry-notice, +native-lease and restored-input producer cases (1,651 skipped), plus all 21 cases +in app/startup and task-drain admission release suites. The newly landed sandbox +resume/admission behavior is exercised with this slice's queue notifications. +Checks run after server typechecking/build and module-boundary verification to +avoid competing cold-import setup loads. All those checks pass. Commands/fixtures: +`/tmp/sleep31-landed-acceptance-command.json`; results/receipts: +`/tmp/sleep31-landed-{types,build,boundaries,notices,consumers}.*`. + +The earlier 404-case matrix and subsequent 21-case parent check retain their +original revision scopes and are not counted as freshly rerun. All owned source +and test files remain unchanged through the current normal integration; only +this acceptance documentation follows the current tests. Their 17 hashes are in +`/tmp/sleep31-landed-tested-source-sha256.json`; the complete integration proof is +`/tmp/sleep31-landed-parent-publication-proof.json`. Fresh exact-head remote checks +and Greptile 5/5 remain required after publishing this updated branch. There is +no full local repository, live provider or deployed sleep claim. diff --git a/maps/agent-access-map/tasks.md b/maps/agent-access-map/tasks.md index 859c5304653..ce801ef5f2e 100644 --- a/maps/agent-access-map/tasks.md +++ b/maps/agent-access-map/tasks.md @@ -222,7 +222,7 @@ API: `present` — PATCH /api/issues/{id} with executionPolicy.monitor; POST /ap Agent access: `partial` — native set_task_monitor standard-mode binding; permitted agent REST/call_api policy PATCH/check-now; no CLI monitor flags. No REST operation named set_task_monitor. Queue and HTTP/2 sandbox callbacks admit the wake-diagnostics read and monitor check-now request. Controller task-read, monitor-management and assignment checks still apply. Recovery resolution and scheduled-retry controls are outside this callback allowance. See the [callback bridge](../../packages/adapter-utils/src/sandbox-callback-bridge.ts) and [callback boundary tests](../../packages/adapter-utils/src/sandbox-callback-context-routes.test.ts). -Policy: Native nested monitor|null, optional OWNED target taskId, key<=240, notes1..500, future check/timeouts/attempts<=100; reserved quota service denied, externalRef sanitized. Target assigned same agent/no human, in_progress|in_review; issue:read,runtime:manage,responsible-user authority. REST monitor changes require runtime:manage+current assignee for agent; board role gate differs. Receipt replay returns current schedule without rearming consumed monitor. Check-now cannot bypass recovery/finalization/eligibility. +Policy: Native nested monitor|null, optional OWNED target taskId, key<=240, notes1..500, future check/timeouts/attempts<=100; reserved quota service denied, externalRef sanitized. Target assigned same agent/no human, in_progress|in_review; issue:read,runtime:manage,responsible-user authority. REST monitor changes require runtime:manage+current assignee for agent; board role gate differs. Receipt replay returns current schedule without rearming consumed monitor. Human check-now may request one check of a blocked task with a retained monitor; agents and automatic ticks still require in_progress|in_review. This does not change status or bypass dependency, recovery, finalization, pause, budget or ownership gates. Provider-quota recovery uses a direct retry path and stays paused on blocked tasks; check-now rejects it before consuming the schedule. A skipped check-now returns 409 instead of success. Evidence: `source-only` — reviewed at `3bbc2104b65caf9f7763938a01260a5673e12f7a`; [issues.ts](../../server/src/routes/issues.ts), [paperclip-runner-tool-authority.ts](../../server/src/services/native-runtime/paperclip-runner-tool-authority.ts), [issue-monitors.ts](../../server/src/services/issue-monitors.ts), [issue-monitor-scheduler.test.ts](../../server/src/__tests__/issue-monitor-scheduler.test.ts), [task-monitor.integration.test.ts](../../server/src/services/native-runtime/task-monitor.integration.test.ts), [scheduling.test.ts](../../server/src/services/heartbeat/scheduling.test.ts). No live execution claimed. diff --git a/maps/feature-map/agents.md b/maps/feature-map/agents.md index 8b511c038fe..b745f8de2dd 100644 --- a/maps/feature-map/agents.md +++ b/maps/feature-map/agents.md @@ -34,8 +34,11 @@ Use New agent from the roster or `/agents/new`. Submitting the name creates an inactive record before adapter selection or account setup. A name-only draft returns to adapter selection when reopened. Save & exit keeps its configuration; Finish setup on the agent returns to the -same record. Final submission requests approval when required, then follows the -existing preparation and verification lifecycle. +same record. Open an unfinished agent from the roster to reach its header. +The header shows Finish setup instead of Run or Resume, including during computer +preparation and verification. Terminating agents cannot reopen setup. Final +submission requests approval when required, then follows the existing preparation +and verification lifecycle. Agent-owned plugin environments prepare the saved draft in the background when their driver declares `requiresAgent`. The draft waits in `verifying` with its diff --git a/maps/feature-map/tasks.md b/maps/feature-map/tasks.md index 8716319460c..37e39a58ce3 100644 --- a/maps/feature-map/tasks.md +++ b/maps/feature-map/tasks.md @@ -138,6 +138,13 @@ schema feedback supports a corrected call before a wait is claimed. For a due monitor held by execution recovery, confirm that the schedule remains and task activity explains the deferral. Repeated checks must not replay the held work. Resolve the hold through its existing recovery action, then verify one wake. +On a blocked task with a retained monitor, verify that automatic checks show as +paused. Check now requests one check through normal admission without changing +the task status. Confirm that an unresolved dependency or recovery hold prevents +dispatch and does not produce a success message. Backlog and todo tasks must not +offer Check now. Blocked provider-quota recovery must offer no manual check and +retain its schedule until the task resumes. Agents and automatic ticks cannot +check a blocked task. Hold native finalization after the provider has stopped, and verify that both scheduled and manual checks retain the due monitor. After settlement, verify one wake. If its timeout passes during workspace recovery, verify settlement followed diff --git a/server/src/__tests__/heartbeat-task-drain-admission-release.test.ts b/server/src/__tests__/heartbeat-task-drain-admission-release.test.ts index 72053aac40c..69d793fd87d 100644 --- a/server/src/__tests__/heartbeat-task-drain-admission-release.test.ts +++ b/server/src/__tests__/heartbeat-task-drain-admission-release.test.ts @@ -17,9 +17,11 @@ import { companyMemberships, companySkills, createDb, + environments, heartbeatRunEvents, heartbeatRuns, issues, + plugins, } from "@paperclipai/db"; import { getEmbeddedPostgresTestSupport, @@ -31,6 +33,7 @@ import express from "express"; import request from "supertest"; import { instanceSettingsRoutes } from "../routes/instance-settings.js"; import { errorHandler } from "../middleware/error-handler.js"; +import type { PluginWorkerManager } from "../services/plugin-worker-manager.js"; const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; @@ -298,6 +301,75 @@ describeEmbeddedPostgres("heartbeat task-drain admission release", () => { } }, 20_000); + it("preserves the plugin worker manager when DELETE releases a queued sandbox run", async () => { + const { companyId, agentId, issueId } = await seedAgentAndIssue(); + const environmentId = randomUUID(); + const pluginId = randomUUID(); + const pluginKey = `test.drain-sandbox.${pluginId}`; + const provider = "drain-sandbox"; + const acquisitionFailure = "drain_release_plugin_acquisition_reached"; + const calls: Array<{ pluginId: string; method: string; params: unknown }> = []; + const pluginWorkers = { + isRunning: (id: string) => id === pluginId, + getWorker: () => ({ supportedMethods: ["environmentAcquireLease"] }), + call: async (id: string, method: string, params: unknown) => { + calls.push({ pluginId: id, method, params }); + throw new Error(acquisitionFailure); + }, + } as unknown as PluginWorkerManager; + const heartbeat = heartbeatService(db, { pluginWorkerManager: pluginWorkers }); + try { + await db.insert(plugins).values({ + id: pluginId, pluginKey, packageName: "@test/drain-sandbox", version: "1.0.0", apiVersion: 1, + categories: ["automation"], status: "ready", + manifestJson: { + id: pluginKey, apiVersion: 1, version: "1.0.0", displayName: "Drain sandbox", + description: "Task-drain release fixture", author: "Paperclip", categories: ["automation"], + capabilities: ["environment.drivers.register"], entrypoints: { worker: "worker.js" }, + environmentDrivers: [{ driverKey: provider, kind: "sandbox_provider", displayName: "Drain sandbox", configSchema: { type: "object" } }], + }, + }); + await db.insert(environments).values({ id: environmentId, name: `Drain sandbox ${environmentId}`, + driver: "sandbox", status: "active", config: { provider } }); + await db.update(agents).set({ defaultEnvironmentId: environmentId }).where(eq(agents.id, agentId)); + startTaskDrain({}); + await heartbeat.wakeup(agentId, { + source: "assignment", triggerDetail: "system", reason: "issue_assigned", + payload: { issueId }, contextSnapshot: { issueId, wakeReason: "issue_assigned" }, + requestedByActorType: "system", requestedByActorId: "issue_assignment", + }); + await heartbeat.drainActiveRunExecutions(); + const [queued] = await db.select().from(heartbeatRuns); + expect(queued).toMatchObject({ status: "queued", startedAt: null }); + expect(calls).toEqual([]); + + const app = express(); + app.use(express.json()); + app.use((req, _res, next) => { + req.actor = { type: "board", userId: "local-board", source: "local_implicit", isInstanceAdmin: true }; + next(); + }); + app.use("/api", instanceSettingsRoutes(db, pluginWorkers)); + app.use(errorHandler); + await request(app).delete("/api/instance/task-drain").expect(200); + await heartbeat.drainActiveRunExecutions(); + const runs = await db.select({ id: heartbeatRuns.id, status: heartbeatRuns.status, error: heartbeatRuns.error }) + .from(heartbeatRuns); + expect(runs).toHaveLength(1); + expect.soft(runs[0]).toMatchObject({ id: queued!.id, status: "failed", error: expect.stringContaining(acquisitionFailure) }); + expect.soft(calls).toEqual([{ + pluginId, method: "environmentAcquireLease", + params: expect.objectContaining({ driverKey: provider, companyId, environmentId, + issueId, agentId, runId: queued!.id, adapterType: "process" }), + }]); + } finally { + await heartbeat.drainActiveRunExecutions(); + await db.update(agents).set({ defaultEnvironmentId: null }).where(eq(agents.id, agentId)); + await db.delete(environments).where(eq(environments.id, environmentId)); + await db.delete(plugins).where(eq(plugins.id, pluginId)); + } + }, 20_000); + it("dispatches existing queued work at the drain deadline", async () => { const { agentId, issueId } = await seedAgentAndIssue(); const heartbeat = heartbeatService(db); diff --git a/server/src/__tests__/issue-execution-policy-routes.test.ts b/server/src/__tests__/issue-execution-policy-routes.test.ts index f759f98659b..26dacf2f1c1 100644 --- a/server/src/__tests__/issue-execution-policy-routes.test.ts +++ b/server/src/__tests__/issue-execution-policy-routes.test.ts @@ -19,7 +19,7 @@ const mockIssueService = vi.hoisted(() => ({ const mockHeartbeatService = vi.hoisted(() => ({ wakeup: vi.fn(async () => undefined), - triggerIssueMonitor: vi.fn(async () => ({ outcome: "triggered" as const })), + triggerIssueMonitor: vi.fn(async (): Promise<{ outcome: "triggered" } | { outcome: "skipped"; reason: string }> => ({ outcome: "triggered" })), reportRunActivity: vi.fn(async () => undefined), getRun: vi.fn(async () => null), getActiveRunForAgent: vi.fn(async () => null), @@ -1157,11 +1157,11 @@ describe("issue execution policy routes", () => { expect(mockHeartbeatService.wakeup).not.toHaveBeenCalled(); }); - it("triggers a scheduled monitor immediately from the dedicated route", async () => { + it.each(["in_progress", "blocked"])("triggers a scheduled monitor on an %s task from the dedicated route", async (status) => { const issue = { id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", companyId: "company-1", - status: "in_progress", + status, assigneeAgentId: "33333333-3333-4333-8333-333333333333", assigneeUserId: null, createdByUserId: "local-board", @@ -1194,6 +1194,20 @@ describe("issue execution policy routes", () => { ); }); + it.each(["execution_reconciliation_required", "monitor_dispatch_deferred", "monitor_replaced"])("does not claim success for a skipped monitor check: %s", async (reason) => { + mockIssueService.getById.mockResolvedValue({ + id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", companyId: "company-1", status: "blocked", + assigneeAgentId: "33333333-3333-4333-8333-333333333333", assigneeUserId: null, + }); + mockHeartbeatService.triggerIssueMonitor.mockResolvedValueOnce({ outcome: "skipped", reason }); + const res = await request(await createApp()) + .post("/api/issues/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa/monitor/check-now").send({}); + expect(res.status).toBe(409); + expect(res.body).toMatchObject({ details: { code: "issue_monitor_check_deferred", reason } }); + if (reason === "monitor_replaced") expect(res.body.error).toContain("monitor changed"); + expect(res.body.ok).toBeUndefined(); + }); + it("lets a board user create a child issue with a scheduled monitor", async () => { mockIssueService.getById.mockResolvedValue({ id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", diff --git a/server/src/__tests__/issue-monitor-scheduler.test.ts b/server/src/__tests__/issue-monitor-scheduler.test.ts index 4cfe7d95801..8c051e38f38 100644 --- a/server/src/__tests__/issue-monitor-scheduler.test.ts +++ b/server/src/__tests__/issue-monitor-scheduler.test.ts @@ -17,6 +17,7 @@ import { heartbeatRunEvents, heartbeatRuns, issueComments, + issueRelations, issueRecoveryActions, issueDocuments, issues, @@ -424,7 +425,7 @@ describeEmbeddedPostgres("issue monitor scheduler", () => { if (change === "cleared") expect(issue.monitorNextCheckAt).toBeNull(); }); - it("does not erase a replacement scheduled after wake admission", async () => { + it.each(["manual", "scheduled"] as const)("reports an accepted %s check and preserves a replacement schedule", async (source) => { const { companyId, issueId } = await seedFixture(); const nextCheckAt = new Date("2026-04-11T13:30:00.000Z"); let replaced = false; @@ -443,7 +444,14 @@ describeEmbeddedPostgres("issue monitor scheduler", () => { }; }, }); - await heartbeatService(racingDb).tickTimers(new Date("2026-04-11T12:31:00.000Z")); + const heartbeat = heartbeatService(racingDb); + const now = new Date("2026-04-11T12:31:00.000Z"); + if (source === "manual") { + expect(await heartbeat.triggerIssueMonitor(issueId, { now, actorType: "user", actorId: "local-board" })) + .toMatchObject({ outcome: "triggered" }); + } else { + expect(await heartbeat.tickTimers(now)).toMatchObject({ enqueued: 1, skipped: 0 }); + } expect(replaced).toBe(true); const [issue] = await db.select().from(issues).where(eq(issues.id, issueId)); expect(issue.monitorNextCheckAt).toEqual(nextCheckAt); @@ -547,8 +555,9 @@ describeEmbeddedPostgres("issue monitor scheduler", () => { expect(participantRuns.find((run) => run.id === scheduled.id)?.errorCode).not.toBe("issue_assignee_changed"); }); - it("lets the board trigger a scheduled issue monitor immediately", async () => { + it.each(["in_progress", "blocked"] as const)("lets the board check a scheduled monitor on an %s task", async (status) => { const { issueId, agentId, nextCheckAt } = await seedFixture(); + await db.update(issues).set({ status }).where(eq(issues.id, issueId)); const heartbeat = heartbeatService(db); const triggeredAt = new Date("2026-04-11T12:00:00.000Z"); @@ -577,6 +586,11 @@ describeEmbeddedPostgres("issue monitor scheduler", () => { nextCheckAt: nextCheckAt.toISOString(), source: "manual", }); + expect(wakeup?.runId).toBeTruthy(); + await waitForHeartbeatIdle(); + const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, wakeup!.runId!)); + expect(run?.status).toBe("succeeded"); + expect(run?.startedAt).not.toBeNull(); const activity = await db .select() @@ -593,6 +607,32 @@ describeEmbeddedPostgres("issue monitor scheduler", () => { }); }); + it("retains a blocked task's monitor when a human check is held by a dependency", async () => { + const { issueId, agentId, companyId, nextCheckAt } = await seedFixture(); + await db.update(issues).set({ status: "blocked" }).where(eq(issues.id, issueId)); + const [blocker] = await db.insert(issues).values({ companyId, title: "Unfinished dependency", status: "todo" }).returning(); + await db.insert(issueRelations).values({ companyId, issueId: blocker.id, relatedIssueId: issueId, type: "blocks" }); + const result = await heartbeatService(db).triggerIssueMonitor(issueId, { actorType: "user", actorId: "local-board" }); + expect(result).toMatchObject({ outcome: "skipped" }); + const [issue] = await db.select().from(issues).where(eq(issues.id, issueId)); + expect(issue).toMatchObject({ status: "blocked", monitorNextCheckAt: nextCheckAt, monitorWakeRequestedAt: null, monitorAttemptCount: 0 }); + expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.agentId, agentId))).toHaveLength(0); + }); + + it("does not consume blocked quota recovery when a dependency is unresolved", async () => { + const { issueId, agentId, companyId, nextCheckAt } = await seedFixture({ + monitor: { serviceName: PROVIDER_QUOTA_MONITOR_SERVICE_NAME }, + }); + await db.update(issues).set({ status: "blocked" }).where(eq(issues.id, issueId)); + const [blocker] = await db.insert(issues).values({ companyId, title: "Unfinished dependency", status: "todo" }).returning(); + await db.insert(issueRelations).values({ companyId, issueId: blocker.id, relatedIssueId: issueId, type: "blocks" }); + await expect(heartbeatService(db).triggerIssueMonitor(issueId, { actorType: "user", actorId: "local-board" })) + .rejects.toThrow("Resume this task before checking provider usage."); + const [issue] = await db.select().from(issues).where(eq(issues.id, issueId)); + expect(issue).toMatchObject({ status: "blocked", monitorNextCheckAt: nextCheckAt, monitorWakeRequestedAt: null, monitorAttemptCount: 0 }); + expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.agentId, agentId))).toHaveLength(0); + }); + it("clears due monitors that cannot be dispatched and records a skip", async () => { const { issueId } = await seedFixture({ agentStatus: "paused" }); const heartbeat = heartbeatService(db); diff --git a/server/src/routes/instance-settings.ts b/server/src/routes/instance-settings.ts index 2a8e78cb99f..b8072b8b308 100644 --- a/server/src/routes/instance-settings.ts +++ b/server/src/routes/instance-settings.ts @@ -136,7 +136,7 @@ export function instanceSettingsRoutes(db: Db, pluginWorkers?: PluginWorkerManag const router = Router(); const svc = instanceSettingsService(db); const environments = environmentService(db); - const heartbeat = heartbeatService(db); + const heartbeat = heartbeatService(db, { pluginWorkerManager: pluginWorkers }); router.get("/instance/settings", async (req, res) => { assertBoardOrgAccess(req); diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index db781faa126..245f2314dd6 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -13380,12 +13380,22 @@ export function issueRoutes( ); const actor = getActorInfo(req); - await heartbeat.triggerIssueMonitor(issue.id, { + const result = await heartbeat.triggerIssueMonitor(issue.id, { actorType: actor.actorType, actorId: actor.actorId, agentId: actor.agentId ?? null, runId: actor.runId ?? null, }); + if (result.outcome !== "triggered") { + throw conflict( + result.reason === "execution_reconciliation_required" + ? "The previous run is still being recovered. Try again when recovery finishes." + : result.reason === "monitor_replaced" + ? "The monitor changed during this check. Review the task's current state before trying again." + : "The monitor check did not start. Refresh the task to see its current state.", + { code: "issue_monitor_check_deferred", reason: result.reason }, + ); + } res.json({ ok: true }); }); diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts index 66f617e2592..eea69ddc69e 100644 --- a/server/src/routes/openapi.ts +++ b/server/src/routes/openapi.ts @@ -10791,7 +10791,8 @@ registerCurrentRoute({ method: "post", path: "/api/issues/{id}/monitor/check-now", tags: ["issues"], - summary: "Run an issue monitor check now", + summary: "Run an issue monitor check now; humans may check blocked tasks", + responses: { 200: r.ok(), 401: r.unauthorized, 403: r.forbidden, 404: r.notFound, 409: r.conflict }, }); registerCurrentRoute({ diff --git a/server/src/services/heartbeat/scheduling.test.ts b/server/src/services/heartbeat/scheduling.test.ts index b07e30ab3c6..26b84d48b82 100644 --- a/server/src/services/heartbeat/scheduling.test.ts +++ b/server/src/services/heartbeat/scheduling.test.ts @@ -168,7 +168,7 @@ describe.skipIf(!postgres.supported)("heartbeat scheduling database boundary", ( await db.update(issues).set({ monitorNextCheckAt: replacement, monitorWakeRequestedAt: null }).where(eq(issues.id, f.issue.id)); return admitted; }); - expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 1, enqueued: 0, skipped: 1 }); + expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 1, enqueued: 1, skipped: 0 }); expect(await readIssue(f.issue.id)).toMatchObject({ monitorNextCheckAt: replacement, monitorAttemptCount: 0 }); }); @@ -197,6 +197,28 @@ describe.skipIf(!postgres.supported)("heartbeat scheduling database boundary", ( expect(await readIssue(f.issue.id)).toMatchObject({ monitorNextCheckAt: null }); }); + it("lets a human check a blocked task without resuming automatic checks", async () => { + const f = await fixture(); + await db.update(issues).set({ status: "blocked" }).where(eq(issues.id, f.issue.id)); + expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 0, enqueued: 0, skipped: 0 }); + expect(f.deps.enqueueWakeup).not.toHaveBeenCalled(); + await expect(f.scheduler.triggerIssueMonitor(f.issue.id, { now, actorType: "user", actorId: "board-user" })) + .resolves.toMatchObject({ outcome: "triggered" }); + expect(f.deps.enqueueWakeup).toHaveBeenCalledExactlyOnceWith(f.agent.id, expect.objectContaining({ + source: "on_demand", requestedByActorType: "user", requestedByActorId: "board-user", + issueStateGuard: expect.objectContaining({ statuses: ["blocked"], assigneeAgentId: f.agent.id }), + })); + expect(await readIssue(f.issue.id)).toMatchObject({ status: "blocked", monitorNextCheckAt: null, monitorAttemptCount: 1 }); + }); + + it.each(["agent", "system"] as const)("does not let a %s check a blocked task", async (actorType) => { + const f = await fixture(); + await db.update(issues).set({ status: "blocked" }).where(eq(issues.id, f.issue.id)); + await expect(f.scheduler.triggerIssueMonitor(f.issue.id, { now, actorType, actorId: "caller" })).rejects.toThrow(); + expect(f.deps.enqueueWakeup).not.toHaveBeenCalled(); + expect(await readIssue(f.issue.id)).toMatchObject({ status: "blocked", monitorNextCheckAt: dueAt, monitorWakeRequestedAt: null }); + }); + it("retains monitors after transient admission failures", async () => { const f = await fixture(); f.deps.enqueueWakeup.mockRejectedValueOnce(new Error("Temporary admission failure")); diff --git a/server/src/services/heartbeat/scheduling.ts b/server/src/services/heartbeat/scheduling.ts index c1714de7b55..34a3821b0bf 100644 --- a/server/src/services/heartbeat/scheduling.ts +++ b/server/src/services/heartbeat/scheduling.ts @@ -792,7 +792,9 @@ export function createHeartbeatScheduling( }) .where(issueMonitorClaimCondition(claimed)) .returning({ id: issues.id }); - if (consumed.length === 0) return { outcome: "skipped" as const, reason: "monitor_replaced" }; + // Admission already accepted the check. A replacement schedule must stay + // intact, but losing its consumption fence does not undo that accepted wake. + if (consumed.length === 0) return { outcome: "triggered" as const }; await logActivity(db, { companyId: claimed.companyId, @@ -907,7 +909,18 @@ export function createHeartbeatScheduling( if (!issue.assigneeAgentId || issue.assigneeUserId) { throw conflict("Issue monitor requires an agent assignee"); } - if (!["in_progress", "in_review"].includes(issue.status)) { + if (issue.status === "blocked" && actorType === "user" && + normalizeIssueExecutionPolicy(issue.executionPolicy ?? null)?.monitor?.serviceName === PROVIDER_QUOTA_MONITOR_SERVICE_NAME) { + // Quota recovery schedules a bounded retry directly, rather than using + // ordinary wake admission. It must not consume a blocked task's monitor. + throw conflict("Resume this task before checking provider usage.", { code: "blocked_quota_monitor" }); + } + // A human can request one check of a blocked task. Admission still owns + // dependencies, recovery, pause and budget gates; automatic ticks stay idle. + const allowedStatuses = actorType === "user" + ? ["in_progress", "in_review", "blocked"] + : ["in_progress", "in_review"]; + if (!allowedStatuses.includes(issue.status)) { throw conflict( "Issue monitor can only run while the issue is in progress or in review", ); @@ -928,7 +941,7 @@ export function createHeartbeatScheduling( sql`${issues.monitorNextCheckAt} is not null`, isNull(issues.assigneeUserId), sql`${issues.assigneeAgentId} is not null`, - inArray(issues.status, ["in_progress", "in_review"]), + inArray(issues.status, allowedStatuses), or( isNull(issues.monitorWakeRequestedAt), lt(issues.monitorWakeRequestedAt, staleClaimThreshold), diff --git a/tests/e2e/onboarding.spec.ts b/tests/e2e/onboarding.spec.ts index 4f8299ade88..bf0f86d916b 100644 --- a/tests/e2e/onboarding.spec.ts +++ b/tests/e2e/onboarding.spec.ts @@ -136,6 +136,12 @@ test.describe("Onboarding wizard", () => { await expect(page.getByRole("heading", { name: "Choose an adapter", exact: true })).toBeVisible(); await page.keyboard.press("Escape"); await page.getByRole("main").getByRole("link", { name: /^Atlas / }).click(); + await expect(page.getByRole("button", { name: "Run now", exact: true })).toHaveCount(0); + await expect(page.getByRole("button", { name: "Resume", exact: true })).toHaveCount(0); + await expect(page.getByRole("button", { name: "Finish setup", exact: true })).toHaveCount(1); + await page.reload(); + await expect(page.getByRole("button", { name: "Finish setup", exact: true })).toBeVisible(); + await expect(page.getByRole("button", { name: "Run now", exact: true })).toHaveCount(0); await page.getByRole("button", { name: "Finish setup", exact: true }).click(); await expect(page.getByRole("heading", { name: "Choose an adapter", exact: true })).toBeVisible(); await page.locator("label").filter({ has: page.locator('input[name="new-agent-adapter"][value="codex_local"]') }).click(); diff --git a/ui/src/components/AgentActionButtons.test.tsx b/ui/src/components/AgentActionButtons.test.tsx index 1177ccb02d1..442f75d6ee7 100644 --- a/ui/src/components/AgentActionButtons.test.tsx +++ b/ui/src/components/AgentActionButtons.test.tsx @@ -7,11 +7,14 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import type { Agent } from "@paperclipai/shared"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { AgentActionButtons } from "./AgentActionButtons"; +import { useAgentLifecycleStatus } from "./AgentLifecycleStatus"; +import { queryKeys } from "../lib/queryKeys"; const mockNavigate = vi.hoisted(() => vi.fn()); const mockOpenNewIssue = vi.hoisted(() => vi.fn()); const mockPushToast = vi.hoisted(() => vi.fn()); const mockAgentsApi = vi.hoisted(() => ({ + get: vi.fn(), invoke: vi.fn(), pause: vi.fn(), resume: vi.fn(), @@ -134,7 +137,7 @@ describe("AgentActionButtons", () => { ); } - it.each(["codex_local", "claude_local", "paperclip_runner"])("returns unfinished %s agents to their saved runner", async adapterType => { + it.each(["codex_local", "claude_local", "opencode_local", "pi_local", "paperclip_runner"])("returns unfinished %s agents to their saved runner", async adapterType => { render(makeAgent({ adapterType, status: "paused", lifecycleState: "paused", pauseReason: "setup" })); await flushReact(); const finish = [...container.querySelectorAll("button")].find(button => button.textContent === "Finish setup"); @@ -146,6 +149,84 @@ describe("AgentActionButtons", () => { expect(mockAgentsApi.resume).not.toHaveBeenCalled(); }); + it.each(["paused", "preparing", "verifying", "pausing", undefined] as const)("replaces run controls with one setup action when lifecycle is %s", async lifecycleState => { + render(makeAgent({ adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "claude" }, status: "paused", lifecycleState, pauseReason: "setup" })); + await flushReact(); + const buttons = [...container.querySelectorAll("button")]; + const finish = buttons.filter(button => button.textContent === "Finish setup"); + expect(finish).toHaveLength(1); + expect(buttons.some(button => /Run Heartbeat|^Resume$|^Pause$/.test(button.textContent ?? ""))).toBe(false); + await act(() => finish[0].click()); + const target = new URL(mockNavigate.mock.calls[0][0], "https://example.test"); + expect(target.pathname).toBe("/agents/new"); + expect(Object.fromEntries(target.searchParams)).toMatchObject({ setupAgentId: "agent-1", adapterType: "paperclip_runner", runnerProvider: "claude", runner: "paperclip" }); + expect(mockAgentsApi.invoke).not.toHaveBeenCalled(); + expect(mockAgentsApi.resume).not.toHaveBeenCalled(); + }); + + it.each(["terminating", "cleaning_up", "terminated", "rejected"] as const)("does not reopen setup during %s", async lifecycleState => { + render(makeAgent({ status: "terminated", lifecycleState, pauseReason: "setup" })); + await flushReact(); + expect(container.textContent).not.toContain("Finish setup"); + }); + + it("restores Run after lifecycle refresh completes setup without replacing the editable record", async () => { + const draft = makeAgent({ status: "paused", lifecycleState: "paused", lifecycleVersion: 1, pauseReason: "setup", pausedAt: new Date("2026-01-01T00:00:00Z"), adapterConfig: { model: "saved-model" } }); + queryClient.setQueryData(queryKeys.agents.detail("alpha"), draft); + mockAgentsApi.get.mockResolvedValueOnce(draft); + function LiveActions() { + const lifecycle = useAgentLifecycleStatus(draft); + return ; + } + root = createRoot(container); + root.render(); + await flushReact(); + expect(container.textContent).toContain("Finish setup"); + mockAgentsApi.get.mockResolvedValue({ ...draft, status: "idle", lifecycleState: "ready", lifecycleVersion: 2, pauseReason: null, pausedAt: null, adapterConfig: { model: "updated-on-server" } }); + await act(async () => { await queryClient.invalidateQueries({ queryKey: [...queryKeys.agents.detail(draft.id), "lifecycle", draft.companyId] }); }); + await flushReact(); + expect(container.textContent).not.toContain("Finish setup"); + const run = [...container.querySelectorAll("button")].find(button => button.textContent === "Run Heartbeat"); + expect(run?.disabled).toBe(false); + expect(queryClient.getQueryData(queryKeys.agents.detail("alpha"))?.adapterConfig).toEqual({ model: "saved-model" }); + expect(mockAgentsApi.get).toHaveBeenLastCalledWith("agent-1", "company-1"); + await act(() => run!.click()); + await flushReact(); + expect(mockAgentsApi.invoke).toHaveBeenCalledWith("agent-1", "company-1"); + }); + + it("checks unsaved changes before leaving to finish setup", async () => { + const onBeforeNavigate = vi.fn(() => false); + render(makeAgent({ status: "paused", lifecycleState: "paused", pauseReason: "setup" }), { hasPendingNavigationChanges: true, onBeforeNavigate }); + await flushReact(); + await act(() => [...container.querySelectorAll("button")].find(button => button.textContent === "Finish setup")!.click()); + expect(onBeforeNavigate).toHaveBeenCalledOnce(); + expect(mockNavigate).not.toHaveBeenCalled(); + expect(mockAgentsApi.invoke).not.toHaveBeenCalled(); + }); + + it("keeps setup available when the caller hides Run or blocks work", async () => { + render(makeAgent({ status: "paused", lifecycleState: "paused", pauseReason: "setup" }), { showRun: false, workActionsDisabled: true }); + await flushReact(); + expect([...container.querySelectorAll("button")].find(button => button.textContent === "Finish setup")!.disabled).toBe(false); + }); + + it("offers Run after setup completes without turning a manual pause into setup", async () => { + render(makeAgent({ status: "paused", lifecycleState: "paused", pauseReason: "setup" })); + await flushReact(); + render(makeAgent({ status: "paused", lifecycleState: "paused", pauseReason: "manual" })); + await flushReact(); + expect(container.textContent).toContain("Resume"); + expect(container.textContent).not.toContain("Finish setup"); + render(makeAgent({ status: "idle", lifecycleState: "ready", pauseReason: null })); + await flushReact(); + const run = [...container.querySelectorAll("button")].find(button => button.textContent === "Run Heartbeat"); + expect(run?.disabled).toBe(false); + await act(() => run!.click()); + await flushReact(); + expect(mockAgentsApi.invoke).toHaveBeenCalledWith("agent-1", "company-1"); + }); + it.each(["preparing", "verifying", "resuming"] as const)("offers pause rather than resume during %s", async lifecycleState => { render(makeAgent({ status: "paused", lifecycleState })); await flushReact(); diff --git a/ui/src/components/AgentActionButtons.tsx b/ui/src/components/AgentActionButtons.tsx index 6ee48a346e7..b24dc415b55 100644 --- a/ui/src/components/AgentActionButtons.tsx +++ b/ui/src/components/AgentActionButtons.tsx @@ -240,6 +240,8 @@ export function AgentActionButtons({ const canonicalAgentRef = agentRouteRef(agent); const isPaused = agent.lifecycleState ? agent.lifecycleState === "paused" : agent.status === "paused"; const isError = agent.status === "error"; + const needsSetup = agent.pauseReason === "setup" && agent.status !== "terminated" + && !["terminating", "cleaning_up", "terminated", "rejected"].includes(agent.lifecycleState ?? ""); const reportError = useCallback( (message: string) => { @@ -382,7 +384,16 @@ export function AgentActionButtons({ {assignLabel} - {showRun && { + if (!confirmNavigationStart(agentActionStartedDirtyRef)) return; + navigate(`/agents/new?${new URLSearchParams({ + name: agent.name, adapterType: agent.adapterType, setupAgentId: agent.id, + runnerProvider: String(agent.adapterConfig.provider === "acpx" ? agent.adapterConfig.acpxAgent : agent.adapterConfig.provider ?? "codex"), + ...(agent.adapterType === "paperclip_runner" ? { runner: "paperclip" } : ["codex_local", "claude_local", "opencode_local", "pi_local"].includes(agent.adapterType) ? { runner: "legacy" } : {}), + })}`); + }}>Finish setup + ) : showRun && { if (navigateToRunOnInvoke && !confirmNavigationStart(agentActionStartedDirtyRef)) return; agentAction.mutate("invoke"); @@ -391,18 +402,12 @@ export function AgentActionButtons({ label={runLabel} size={size} />} - {isError ? ( + {!needsSetup && (isError ? ( agentAction.mutate("clear_error")} disabled={clearErrorDisabled} size={size} /> - ) : agent.pauseReason === "setup" && agent.lifecycleState === "paused" ? ( - ) : ( - )} + ))} {pauseConfirm && ( diff --git a/ui/src/components/AgentLifecycleStatus.tsx b/ui/src/components/AgentLifecycleStatus.tsx index 689a54b8314..65998141514 100644 --- a/ui/src/components/AgentLifecycleStatus.tsx +++ b/ui/src/components/AgentLifecycleStatus.tsx @@ -35,7 +35,7 @@ export function useAgentLifecycleStatus(agent?: Agent) { queryKey: [...queryKeys.agents.detail(agent?.id ?? ""), "lifecycle", agent?.companyId], queryFn: () => agentsApi.get(agent!.id, agent!.companyId), enabled: Boolean(agent), - select: current => ({ status: current.status, lifecycleState: current.lifecycleState, + select: current => ({ status: current.status, pauseReason: current.pauseReason, pausedAt: current.pausedAt, lifecycleState: current.lifecycleState, lifecycleVersion: current.lifecycleVersion, lifecycleError: current.lifecycleError }), refetchInterval: query => agentLifecycleRefetchInterval(query.state.data?.lifecycleState ?? agent?.lifecycleState), }); diff --git a/ui/src/components/IssueMonitorBanner.test.tsx b/ui/src/components/IssueMonitorBanner.test.tsx index 5680dc963af..9156408fc95 100644 --- a/ui/src/components/IssueMonitorBanner.test.tsx +++ b/ui/src/components/IssueMonitorBanner.test.tsx @@ -3,7 +3,7 @@ import { act } from "react"; import { flushSync } from "react-dom"; import { createRoot } from "react-dom/client"; -import type { Issue, IssueWorkProduct } from "@paperclipai/shared"; +import { PROVIDER_QUOTA_MONITOR_SERVICE_NAME, type Issue, type IssueWorkProduct } from "@paperclipai/shared"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { @@ -260,6 +260,49 @@ describe("IssueMonitorBanner / IssueMonitorComposerStrip rendering", () => { flushSync(() => root.unmount()); }); + it("offers a manual check on a blocked task without promising an automatic wake", () => { + const onCheckNow = vi.fn(); + const issue = { ...issueWithMonitor(new Date(NOW.getTime() - 12 * 60_000).toISOString()), status: "blocked" as const }; + const root = createRoot(container); + flushSync(() => root.render(<> + + + )); + expect(container.textContent).toContain("Automatic checks paused"); + expect(container.textContent).not.toMatch(/overdue|next tick|scheduled check/i); + const buttons = Array.from(container.querySelectorAll("button")); + expect(buttons.map(button => button.textContent)).toEqual(["Check now", "Check now"]); + flushSync(() => buttons[1]!.click()); + expect(onCheckNow).toHaveBeenCalledTimes(1); + flushSync(() => root.unmount()); + }); + + it.each(["backlog", "todo"] as const)("does not offer a monitor check on a %s task", (status) => { + const issue = { ...issueWithMonitor(NOW.toISOString()), status }; + const root = createRoot(container); + flushSync(() => root.render(<> + + + )); + expect(container.textContent).toContain("Resume this task to continue checking."); + expect(container.querySelector("button")).toBeNull(); + expect(container.textContent).not.toMatch(/next tick|momentarily|reply wakes/i); + flushSync(() => root.unmount()); + }); + + it("keeps blocked quota recovery paused until the task resumes", () => { + const issue = { ...issueWithMonitor(NOW.toISOString()), status: "blocked" as const }; + issue.executionState!.monitor!.serviceName = PROVIDER_QUOTA_MONITOR_SERVICE_NAME; + const root = createRoot(container); + flushSync(() => root.render(<> + + + )); + expect(container.textContent).toContain("Resume this task to continue checking."); + expect(container.querySelector("button")).toBeNull(); + flushSync(() => root.unmount()); + }); + it("hides the banner and strip when there is no monitor", () => { expect(hasVisibleMonitorSurface(issueWithMonitor(null))).toBe(false); const root = createRoot(container); diff --git a/ui/src/components/IssueMonitorBanner.tsx b/ui/src/components/IssueMonitorBanner.tsx index 78f36b8ca11..01021dd1c3a 100644 --- a/ui/src/components/IssueMonitorBanner.tsx +++ b/ui/src/components/IssueMonitorBanner.tsx @@ -18,6 +18,8 @@ import { IssuePullRequestLinks } from "@/components/IssuePullRequestLinks"; import { getIssuePullRequests, pullRequestNeedsReview } from "@/lib/issue-pull-requests"; import { cn } from "@/lib/utils"; import { + areAutomaticMonitorChecksPaused, + canCheckIssueMonitorNow, deriveMonitorState, formatMonitorAbsolute, formatMonitorEta, @@ -63,6 +65,8 @@ export interface MonitorSurfaceCopy { tone: "info" | "warning"; workspaceWait?: boolean; pullRequestReview?: boolean; + automaticChecksPaused?: boolean; + checkUnavailable?: boolean; } function capitalize(value: string): string { @@ -79,9 +83,26 @@ export function buildMonitorSurfaceCopy( now: MonitorDate, scheduledRetryReason?: string | null, pendingPullRequestReviews = 0, + issueStatus?: string, ): MonitorSurfaceCopy | null { if (!isWaitingMonitorState(derived.state) || !derived.nextCheckAt) return null; + if (derived.source === "monitor" && areAutomaticMonitorChecksPaused({ status: issueStatus })) { + const canCheckNow = canCheckIssueMonitorNow({ status: issueStatus }, derived.serviceName); + const hint = canCheckNow + ? "This task is blocked. You can ask the agent to check now." + : "Resume this task to continue checking."; + return { + bannerTitle: "Automatic checks paused", + stripTitle: "Automatic checks paused", + bannerMeta: [hint], + stripMeta: [hint], + tone: "info", + automaticChecksPaused: true, + checkUnavailable: !canCheckNow, + }; + } + if (derived.source === "scheduled-retry" && scheduledRetryReason === "workspace_busy") { return { bannerTitle: "Waiting for workspace", @@ -162,9 +183,12 @@ function useMonitorSurfaceCopy(issue: Issue, pendingPullRequestReviews: number): // `nextCheckAt` is stable for a given issue; derive once to seed the ticking // countdown cadence, then re-derive against the live clock so the surfaces // roll scheduled → due → overdue on their own. - const nextCheckAt = useMemo(() => deriveMonitorState(issue).nextCheckAt, [issue]); + const nextCheckAt = useMemo(() => { + const derived = deriveMonitorState(issue); + return derived.source === "monitor" && areAutomaticMonitorChecksPaused(issue) ? null : derived.nextCheckAt; + }, [issue]); const now = useMonitorCountdown(nextCheckAt); - return useMemo(() => buildMonitorSurfaceCopy(deriveMonitorState(issue, now), now, issue.scheduledRetry?.scheduledRetryReason, pendingPullRequestReviews), [issue, now, pendingPullRequestReviews]); + return useMemo(() => buildMonitorSurfaceCopy(deriveMonitorState(issue, now), now, issue.scheduledRetry?.scheduledRetryReason, pendingPullRequestReviews, issue.status), [issue, now, pendingPullRequestReviews]); } function CheckNowButton({ @@ -262,7 +286,7 @@ export function IssueMonitorBanner({ icon={Clock} title={copy.bannerTitle} className={cn("relative my-3", canCancel && "pr-12")} - actions={onCheckNow && !copy.workspaceWait ? : null} + actions={onCheckNow && !copy.workspaceWait && !copy.checkUnavailable ? : null} > {canCancel ? : null}
@@ -306,15 +330,17 @@ export function IssueMonitorComposerStrip({
{copy.stripMeta.join(" · ")}
- {onCheckNow && !copy.workspaceWait ? : null} + {onCheckNow && !copy.workspaceWait && !copy.checkUnavailable ? : null} -

- {copy.pullRequestReview - ? "Review on GitHub, then check status to have the agent verify the result." - : copy.workspaceWait - ? "You can keep sending instructions while the agent waits." - : "Sending a reply wakes the agent now — before the scheduled check."} -

+ {!copy.automaticChecksPaused ? ( +

+ {copy.pullRequestReview + ? "Review on GitHub, then check status to have the agent verify the result." + : copy.workspaceWait + ? "You can keep sending instructions while the agent waits." + : "Sending a reply wakes the agent now — before the scheduled check."} +

+ ) : null} {checkError ?

{checkError}

: null} ); diff --git a/ui/src/components/IssueProperties.test.tsx b/ui/src/components/IssueProperties.test.tsx index cb981180726..5ed4d721649 100644 --- a/ui/src/components/IssueProperties.test.tsx +++ b/ui/src/components/IssueProperties.test.tsx @@ -3032,6 +3032,7 @@ describe("IssueProperties", () => { }; renderMonitor(createIssue({ + status: "in_progress", executionPolicy: createExecutionPolicy({ monitor: { ...baseMonitorState, serviceName: "vercel-deploy" } }), executionState: createExecutionState({ monitor: baseMonitorState }), monitorAttemptCount: 1, @@ -3045,6 +3046,7 @@ describe("IssueProperties", () => { expect(monitorRowText()).toContain("Today, 4:08 PM · Attempt 1"); renderMonitor(createIssue({ + status: "in_progress", executionPolicy: createExecutionPolicy({ monitor: { ...baseMonitorState, nextCheckAt: at(252) } }), executionState: createExecutionState({ monitor: { ...baseMonitorState, nextCheckAt: at(132) } }), monitorNextCheckAt: new Date(at(192)), @@ -3054,6 +3056,7 @@ describe("IssueProperties", () => { expect(monitorRowText()).toContain("Today, 4:08 PM"); renderMonitor(createIssue({ + status: "in_progress", executionPolicy: createExecutionPolicy({ monitor: { ...baseMonitorState, serviceName: "vercel-deploy" } }), executionState: createExecutionState({ monitor: { ...baseMonitorState, attemptCount: 3 } }), monitorAttemptCount: 3, @@ -3062,6 +3065,7 @@ describe("IssueProperties", () => { expect(monitorRowText()).toContain("Attempt 3"); renderMonitor(createIssue({ + status: "in_progress", executionPolicy: createExecutionPolicy({ monitor: { ...baseMonitorState, nextCheckAt: at(0) } }), executionState: createExecutionState({ monitor: { ...baseMonitorState, nextCheckAt: at(0) } }), })); @@ -3070,6 +3074,7 @@ describe("IssueProperties", () => { expect(monitorRowText()).toContain("checking momentarily…"); renderMonitor(createIssue({ + status: "in_progress", executionPolicy: createExecutionPolicy({ monitor: { ...baseMonitorState, nextCheckAt: at(-18) } }), executionState: createExecutionState({ monitor: { ...baseMonitorState, nextCheckAt: at(-18) } }), })); @@ -3078,6 +3083,17 @@ describe("IssueProperties", () => { expect(monitorRowText()).toContain("Today, 1:38 PM · fires on next tick"); renderMonitor(createIssue({ + status: "blocked", + executionPolicy: createExecutionPolicy({ monitor: { ...baseMonitorState, nextCheckAt: at(-18) } }), + executionState: createExecutionState({ monitor: { ...baseMonitorState, nextCheckAt: at(-18) } }), + })); + await flush(); + expect(monitorRowText()).toContain("Automatic checks paused"); + expect(monitorRowText()).toContain("Check now to request a manual check"); + expect(monitorRowText()).not.toMatch(/overdue|next tick/i); + + renderMonitor(createIssue({ + status: "in_progress", executionPolicy: createExecutionPolicy(), executionState: createExecutionState({ monitor: { ...baseMonitorState, diff --git a/ui/src/components/issue-properties/IssueProperties.tsx b/ui/src/components/issue-properties/IssueProperties.tsx index 924c7c8eb05..91ccdb43932 100644 --- a/ui/src/components/issue-properties/IssueProperties.tsx +++ b/ui/src/components/issue-properties/IssueProperties.tsx @@ -50,6 +50,8 @@ import { formatAssigneeUserLabel, formatUserLabel } from "../../lib/assignees"; import { buildExecutionPolicy, stageParticipantValues } from "../../lib/issue-execution-policy"; import { useExecutionPolicy } from "../../hooks/useExecutionPolicy"; import { + areAutomaticMonitorChecksPaused, + canCheckIssueMonitorNow, formatMonitorAbsolute, formatMonitorAbsoluteFull, formatMonitorEta, @@ -1323,17 +1325,21 @@ export function IssueProperties({ const monitorLastTriggeredAt = issue.monitorLastTriggeredAt ?? monitorState?.lastTriggeredAt ?? null; const monitorServiceName = executionPolicy?.monitor?.serviceName ?? monitorState?.serviceName ?? null; const monitorNotes = executionPolicy?.monitor?.notes ?? monitorState?.notes ?? null; - const monitorNow = useMonitorCountdown(monitorNextCheckAt); + const monitorPaused = areAutomaticMonitorChecksPaused(issue); + const canCheckMonitorNow = canCheckIssueMonitorNow(issue, monitorServiceName); + const monitorNow = useMonitorCountdown(monitorPaused ? null : monitorNextCheckAt); const monitorRelative = monitorNextCheckAt ? formatMonitorEta(monitorNextCheckAt, monitorNow) : null; const monitorIsDueNow = monitorRelative === "due now"; const monitorIsOverdue = Boolean(monitorRelative?.startsWith("overdue by ")); const monitorPrimary = monitorNextCheckAt - ? formatMonitorEtaLabel(monitorNextCheckAt, monitorNow) + ? monitorPaused ? "Automatic checks paused" : formatMonitorEtaLabel(monitorNextCheckAt, monitorNow) : monitorState?.status === "cleared" ? "Cleared" : "None"; const monitorSecondary = monitorNextCheckAt - ? monitorIsDueNow + ? monitorPaused + ? canCheckMonitorNow ? "Check now to request a manual check" : "Resume this task to continue checking" + : monitorIsDueNow ? "checking momentarily…" : `${formatMonitorAbsolute(monitorNextCheckAt, {}, monitorNow)}${monitorIsOverdue ? " · fires on next tick" : monitorAttemptCount > 0 ? ` · Attempt ${monitorAttemptCount}` : ""}` : monitorState?.status === "cleared" @@ -1376,7 +1382,7 @@ export function IssueProperties({
Next check
{formatMonitorAbsoluteFull(monitorNextCheckAt)}
-
{monitorRelative}
+
{monitorPaused ? "Automatic checks paused" : monitorRelative}
Watching
@@ -1392,7 +1398,7 @@ export function IssueProperties({
- {onCheckMonitorNow ? ( + {onCheckMonitorNow && canCheckMonitorNow ? ( diff --git a/ui/src/lib/issue-monitor.ts b/ui/src/lib/issue-monitor.ts index 3a313b1ba17..90eecaeb9c4 100644 --- a/ui/src/lib/issue-monitor.ts +++ b/ui/src/lib/issue-monitor.ts @@ -1,4 +1,5 @@ import { useEffect, useState } from "react"; +import { PROVIDER_QUOTA_MONITOR_SERVICE_NAME } from "@paperclipai/shared"; const SECOND_MS = 1_000; const MINUTE_MS = 60 * SECOND_MS; @@ -56,6 +57,15 @@ export interface MonitorDateTimeFormatOptions { timeZone?: string; } +export function areAutomaticMonitorChecksPaused(issue: Pick): boolean { + return issue.status !== undefined && issue.status !== "in_progress" && issue.status !== "in_review"; +} + +export function canCheckIssueMonitorNow(issue: Pick, serviceName?: string | null): boolean { + return !areAutomaticMonitorChecksPaused(issue) || + (issue.status === "blocked" && serviceName !== PROVIDER_QUOTA_MONITOR_SERVICE_NAME); +} + function toTimestamp(value: MonitorDate): number { const timestamp = new Date(value).getTime(); if (Number.isNaN(timestamp)) throw new RangeError("Invalid monitor date"); diff --git a/ui/storybook/stories/task-coordination/monitor-surfaces.stories.tsx b/ui/storybook/stories/task-coordination/monitor-surfaces.stories.tsx index 35585c557b3..c74133c5ee0 100644 --- a/ui/storybook/stories/task-coordination/monitor-surfaces.stories.tsx +++ b/ui/storybook/stories/task-coordination/monitor-surfaces.stories.tsx @@ -1,7 +1,9 @@ import type { Meta, StoryObj } from "@storybook/react-vite"; +import { useState } from "react"; import type { Issue } from "@paperclipai/shared"; import { IssueMonitorBanner, IssueMonitorComposerStrip } from "@/components/IssueMonitorBanner"; import { IssueProperties } from "@/components/IssueProperties"; +import { prepareFixtureApi } from "../../support/capability-gaps/api"; import { storybookExecutionWorkspaces, storybookIssueDocuments, @@ -335,3 +337,27 @@ export default meta; type Story = StoryObj; export const MonitorSurfaces: Story = {}; + +export const BlockedTask: Story = { + beforeEach: () => prepareFixtureApi([ + { path: `/api/issues/${overdueMonitorIssue.id}/work-products`, read: () => [] }, + ]).cleanup, + render: function BlockedMonitor() { + const [checkingNow, setCheckingNow] = useState(false); + const issue = { ...overdueMonitorIssue, status: "blocked" as const }; + const onCheckNow = () => setCheckingNow(true); + return
+ + + undefined} onCheckMonitorNow={onCheckNow} checkingMonitorNow={checkingNow} inline /> +
; + }, + parameters: { + paperclip: { + capabilities: ["task-coordination/tree-control", "tasks/properties"], + implementation: "production", + boundary: "fixtures", + notes: "A retained monitor on a blocked task. Automatic checks are paused. Clicking Check now shows the shared pending state; dispatch is simulated.", + }, + }, +};