From 65614fa87ec64dd2af4956f71333b611216b4e55 Mon Sep 17 00:00:00 2001 From: james8814 <65702381+james8814@users.noreply.github.com> Date: Sat, 5 Dec 2026 20:03:07 +0800 Subject: [PATCH] fix(issues): tell a reviewer to decide again when a reply to it is queued (#20745) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Execution policies route an issue through review and approval stages, and agents can be stage participants > - The issue update route refuses an agent handoff to review while a human reply to that agent is still queued (`interaction_response_queued`) > - The refusal protects the reply: if the issue gets a new assignee first, the dispatcher cancels the queued continuation with `issue_assignee_changed` and the reply is never delivered > - A reviewer agent that approves an intermediate stage also hits this refusal, because the policy moves the issue to the next participant and keeps it `in_review` > - The error tells the reviewer to "keep the current assignee". The reviewer did not choose the assignee, and the error does not say that the decision was dropped > - This pull request keeps the refusal and gives stage decisions a message the reviewer can act on: the decision was not saved, read the reply in the next run, then decide again ## Linked Issues or Issue Description No issue exists for this bug. I searched issues and PRs for `interaction_response_queued`, "queued response stage approval", "review stage approve 409 queued" and "queued interaction response handoff". - Refs #19376. That closed PR changed which queued receipts count as delivered. It did not change this check. - Refs #20264. That open PR reworks stage decisions into explicit operations. Its description does not mention this check. If it lands first, this change needs a rebase onto its decision path. **What happened?** A two-stage policy has a review stage (agent A) and an approval stage (agent B). Agent A is the active reviewer and the assignee. A human reply to agent A is queued, for example an answer to a question that agent A asked. Agent A sends `PATCH /api/issues/:id` with `status: "done"` and an approval comment. The policy turns this into an approval of the review stage, which would set `status: "in_review"` and assign agent B. The route returns 409 `interaction_response_queued`: "Keep the current assignee so the queued response can continue after this run". The update, the decision row and the comment are not saved, and the message does not say so. **Expected behavior** The reply still reaches agent A, so the refusal stays. The error tells agent A that the decision was not saved and that it should read the reply in its next run and submit the decision again. I first tried to let the decision through. That loses the reply: the queued continuation for agent A is a resolved-interaction continuation, and `decideQueuedRunStaleness` cancels it with `issue_assignee_changed` once agent B is the assignee (`server/src/modules/run-dispatch/domain/policy.ts:538-556`). The human input would also not inform the decision. So this change keeps the refusal. **Steps to reproduce** 1. Configure an execution policy with a review stage (agent A) and an approval stage (agent B). 2. Move the issue into the review stage with agent A as the current participant and assignee. 3. Queue a resolved interaction response for agent A on the issue. 4. As agent A, send `PATCH /api/issues/:id` with `{ "status": "done", "comment": "Approved." }`. 5. The response is 409 with the generic "keep the current assignee" message. **Paperclip version or commit** `master` at 8b3348c6b. The check is at `server/src/routes/issues.ts:15483-15489`. ## What Changed - `server/src/routes/issues.ts`: when the execution policy returns a stage decision, the `interaction_response_queued` error now says: "The user already responded to you. This stage decision was not saved. Read the queued response in your next run on this issue, then submit the decision again." The condition and the error code do not change. Other handoffs keep the old message. - `server/src/__tests__/issue-execution-policy-routes.test.ts`: - The `hasQueuedInteractionResponse` mock is now a shared handle, so a test can make it return `true`. The mocked transaction also supports `insert`, so a test can see the decision row. - New test: a reviewer approves the review stage with no reply queued. The issue moves to agent B and an `approved` decision row is written. - New test: the same approval with a reply to the reviewer queued. The response is 409 with the new message. There is no update, no comment and no decision row, so the reviewer stays the assignee. - New test: an agent submits its own work for review with a reply queued. The response is 409 with the old message and no update. - `server/src/modules/run-dispatch/domain/policy.test.ts`: new test for the delivery rule this refusal depends on. A queued response to a reviewer runs while the reviewer is still the assignee, and is cancelled with `issue_assignee_changed` after a handoff. ## Verification - `cd server && npx vitest run src/__tests__/issue-execution-policy-routes.test.ts src/modules/run-dispatch/domain/policy.test.ts` - Route file from `master`: 1 failed, 111 passed. The queued-reply approval test fails on the message. - Route file that lets stage decisions skip the check: 1 failed, 111 passed. The same test fails with 200 instead of 409. - With this change: 112 passed. - With this change, also `src/__tests__/issue-agent-mutation-ownership-routes.test.ts` and `src/__tests__/issue-comment-reopen-routes.test.ts`: 4 files, 446 passed in total. - The new policy test passes on `master` too. It documents the existing dispatcher rule. It does not test a change. - Not run locally: `issue-queued-comments-routes.test.ts`. It needs embedded Postgres, which my environment cannot start. No end-to-end test with a real queue was run. ## Risks - Behavior: no change to which requests are refused. Only the message text for stage decisions changes. Clients that match on the error code are not affected. - Not covered by this PR: a change request (`in_progress`) and a final approval (`done`) do not end in `in_review`, so they pass this check today. If a change request moves the issue back to the executor while a reply to the reviewer is queued, the dispatcher cancels that reply in the same way. I found this by reading `policy.ts` and did not reproduce it on a running instance. It needs a separate decision. - #20264 changes the same route area. Whichever PR lands second needs a rebase. ## Model Used Claude Opus 5.5 (claude-opus-5-5), agentic coding with tool use. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [ ] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge Co-authored-by: Paperclip --- .../issue-execution-policy-routes.test.ts | 140 +++++++++++++++++- .../run-dispatch/domain/policy.test.ts | 12 ++ server/src/routes/issues.ts | 9 +- 3 files changed, 155 insertions(+), 6 deletions(-) diff --git a/server/src/__tests__/issue-execution-policy-routes.test.ts b/server/src/__tests__/issue-execution-policy-routes.test.ts index fcd1b67036f..cefcf1e08d9 100644 --- a/server/src/__tests__/issue-execution-policy-routes.test.ts +++ b/server/src/__tests__/issue-execution-policy-routes.test.ts @@ -59,10 +59,11 @@ const mockDbSelectWhere = vi.hoisted(() => vi.fn(() => ({ }))); const mockDbSelectFrom = vi.hoisted(() => vi.fn((_table: unknown): { where: (...args: never[]) => unknown } => ({ where: mockDbSelectWhere }))); const mockDbSelect = vi.hoisted(() => vi.fn(() => ({ from: mockDbSelectFrom }))); +const mockDbInsertValues = vi.hoisted(() => vi.fn(async (_row: unknown) => [])); const mockDb = vi.hoisted(() => ({ select: mockDbSelect, - transaction: vi.fn(async (callback: (tx: { select: typeof mockDbSelect }) => Promise) => - callback({ select: mockDbSelect })), + transaction: vi.fn(async (callback: (tx: { select: typeof mockDbSelect; insert: () => { values: typeof mockDbInsertValues } }) => Promise) => + callback({ select: mockDbSelect, insert: () => ({ values: mockDbInsertValues }) })), })); const mockLogActivity = vi.hoisted(() => vi.fn(async (_db: unknown, _input: unknown) => undefined)); @@ -74,6 +75,7 @@ const mockIssueThreadInteractionService = vi.hoisted(() => ({ const mockIssueApprovalService = vi.hoisted(() => ({ listApprovalsForIssue: vi.fn(async () => []), })); +const mockHasQueuedInteractionResponse = vi.hoisted(() => vi.fn(async () => false)); const mockRunnerGoalService = vi.hoisted(() => ({ projection: vi.fn(async () => null), act: vi.fn(), @@ -81,7 +83,7 @@ const mockRunnerGoalService = vi.hoisted(() => ({ function registerModuleMocks() { vi.doMock("../services/queued-interaction-response.js", () => ({ - hasQueuedInteractionResponse: vi.fn(async () => false), + hasQueuedInteractionResponse: mockHasQueuedInteractionResponse, })); vi.doMock("../services/runner-goals.js", () => ({ runnerGoalService: () => mockRunnerGoalService, @@ -226,6 +228,7 @@ describe("issue execution policy routes", () => { mockIssueThreadInteractionService.listForIssue.mockResolvedValue([]); mockIssueThreadInteractionService.expireRequestConfirmationsSupersededByComment.mockResolvedValue([]); mockIssueApprovalService.listApprovalsForIssue.mockResolvedValue([]); + mockHasQueuedInteractionResponse.mockResolvedValue(false); mockDbSelect.mockImplementation(() => ({ from: mockDbSelectFrom })); mockDbSelectFrom.mockImplementation((table) => { const name = getTableName(table as Parameters[0]); @@ -1135,6 +1138,137 @@ describe("issue execution policy routes", () => { expect(mockHeartbeatService.cancelRun).not.toHaveBeenCalled(); }); + async function approveReviewStage(replyQueued: boolean) { + const policy = normalizeIssueExecutionPolicy({ + stages: [ + { + id: "11111111-1111-4111-8111-111111111111", + type: "review", + participants: [{ type: "agent", agentId: "33333333-3333-4333-8333-333333333333" }], + }, + { + id: "22222222-2222-4222-8222-222222222222", + type: "approval", + participants: [{ type: "agent", agentId: "66666666-6666-4666-8666-666666666666" }], + }, + ], + })!; + const issue = { + id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + companyId: "company-1", + status: "in_review", + assigneeAgentId: "33333333-3333-4333-8333-333333333333", + assigneeUserId: null, + createdByUserId: "local-board", + title: "Queued reply during review", + executionPolicy: policy, + executionState: { + status: "pending", + currentStageId: "11111111-1111-4111-8111-111111111111", + currentStageIndex: 0, + currentStageType: "review", + currentParticipant: { type: "agent", agentId: "33333333-3333-4333-8333-333333333333" }, + returnAssignee: { type: "agent", agentId: "44444444-4444-4444-8444-444444444444" }, + completedStageIds: [], + lastDecisionId: null, + lastDecisionOutcome: null, + }, + }; + mockIssueService.getById.mockResolvedValue(issue); + mockIssueService.update.mockImplementation(async (_id: string, patch: Record) => ({ + ...issue, + ...patch, + updatedAt: new Date(), + })); + mockIssueService.addComment.mockResolvedValue({ + id: "77777777-7777-4777-8777-777777777777", + issueId: issue.id, + companyId: "company-1", + body: "Approved after review.", + createdAt: new Date(), + }); + mockHasQueuedInteractionResponse.mockResolvedValue(replyQueued); + + return request(await createApp({ + type: "agent", + agentId: "33333333-3333-4333-8333-333333333333", + companyId: "company-1", + runId: "55555555-5555-4555-8555-555555555555", + })) + .patch("/api/issues/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa") + .send({ status: "done", comment: "Approved after review." }); + } + + it("hands a stage approval to the next participant when no reply is queued", async () => { + const res = await approveReviewStage(false); + + expect(res.status, JSON.stringify(res.body)).toBe(200); + const updatePatch = mockIssueService.update.mock.calls[0]?.[1] as Record; + expect(updatePatch.status).toBe("in_review"); + expect(updatePatch.assigneeAgentId).toBe("66666666-6666-4666-8666-666666666666"); + expect(updatePatch.executionState).toMatchObject({ + status: "pending", + currentStageId: "22222222-2222-4222-8222-222222222222", + completedStageIds: ["11111111-1111-4111-8111-111111111111"], + lastDecisionOutcome: "approved", + }); + expect(mockDbInsertValues).toHaveBeenCalledWith(expect.objectContaining({ + stageId: "11111111-1111-4111-8111-111111111111", + actorAgentId: "33333333-3333-4333-8333-333333333333", + outcome: "approved", + })); + }); + + it("keeps the reviewer assigned and asks it to decide again when a reply to it is queued", async () => { + const res = await approveReviewStage(true); + + expect(res.status).toBe(409); + expect(res.body.details.code).toBe("interaction_response_queued"); + expect(res.body.error).toContain("This stage decision was not saved"); + expect(res.body.error).toContain("submit the decision again"); + expect(mockIssueService.update).not.toHaveBeenCalled(); + expect(mockIssueService.addComment).not.toHaveBeenCalled(); + expect(mockDbInsertValues).not.toHaveBeenCalled(); + }); + + it("keeps the assignee when an agent submits for review while a reply to it is queued", async () => { + const policy = normalizeIssueExecutionPolicy({ + stages: [ + { + id: "11111111-1111-4111-8111-111111111111", + type: "review", + participants: [{ type: "agent", agentId: "44444444-4444-4444-8444-444444444444" }], + }, + ], + })!; + mockIssueService.getById.mockResolvedValue({ + id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + companyId: "company-1", + status: "in_progress", + assigneeAgentId: "33333333-3333-4333-8333-333333333333", + assigneeUserId: null, + createdByUserId: "local-board", + title: "Queued reply before review", + executionPolicy: policy, + executionState: null, + }); + mockHasQueuedInteractionResponse.mockResolvedValue(true); + + const res = await request(await createApp({ + type: "agent", + agentId: "33333333-3333-4333-8333-333333333333", + companyId: "company-1", + runId: "55555555-5555-4555-8555-555555555555", + })) + .patch("/api/issues/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa") + .send({ status: "in_review" }); + + expect(res.status).toBe(409); + expect(res.body.details.code).toBe("interaction_response_queued"); + expect(res.body.error).toBe("The user already responded. Keep the current assignee so the queued response can continue after this run."); + expect(mockIssueService.update).not.toHaveBeenCalled(); + }); + it("dissolves the review when a board user reassigns an in_review task to a non-participant", async () => { const policy = normalizeIssueExecutionPolicy({ stages: [ diff --git a/server/src/modules/run-dispatch/domain/policy.test.ts b/server/src/modules/run-dispatch/domain/policy.test.ts index d0d50fb357b..f6a67397fdf 100644 --- a/server/src/modules/run-dispatch/domain/policy.test.ts +++ b/server/src/modules/run-dispatch/domain/policy.test.ts @@ -295,6 +295,18 @@ describe("decideQueuedRunStaleness", () => { .toMatchObject({ stale: true, errorCode: "issue_waiting_for_response" }); }); + it("delivers a queued response to a reviewer only while the reviewer keeps the issue", () => { + const reviewer: ReviewParticipantFacts = { isInReview: true, hasParticipant: true, participantIsAgent: true, + participantAgentId: "agent-1", currentStageType: "review", currentParticipant: { type: "agent", agentId: "agent-1" } }; + const response = { ...baseStalenessFacts(), isResolvedInteractionContinuation: true, + issueStatus: "in_review", reviewParticipant: reviewer }; + expect(decideQueuedRunStaleness(response, NOW)).toEqual({ stale: false }); + expect(decideQueuedRunStaleness({ ...response, issueAssigneeAgentId: "agent-2", + reviewParticipant: { ...reviewer, participantAgentId: "agent-2", currentStageType: "approval", + currentParticipant: { type: "agent", agentId: "agent-2" } } }, NOW)) + .toMatchObject({ stale: true, errorCode: "issue_assignee_changed" }); + }); + it("is not stale when every rule passes", () => { expect(decideQueuedRunStaleness(baseStalenessFacts(), NOW)).toEqual({ stale: false, diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index 20657ce867a..e766dbdca86 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -16079,9 +16079,12 @@ export function issueRoutes( if (assigneeWillChange && actor.actorType === "agent" && existing.assigneeAgentId === actor.agentId && updateFields.status === "in_review" && await hasQueuedInteractionResponse(db, existing.companyId, existing.id, existing.assigneeAgentId)) { - throw conflict("The user already responded. Keep the current assignee so the queued response can continue after this run.", { - code: "interaction_response_queued", - }); + throw conflict( + transition.decision + ? "The user already responded to you. This stage decision was not saved. Read the queued response in your next run on this issue, then submit the decision again." + : "The user already responded. Keep the current assignee so the queued response can continue after this run.", + { code: "interaction_response_queued" }, + ); } if (assigneeWillChange && !transition.workflowControlledAssignment) { if (!isAgentReturningIssueToCreator) {