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) {