diff --git a/docs/api/issues.md b/docs/api/issues.md index 272bd18e67a..b4f0a6645ca 100644 --- a/docs/api/issues.md +++ b/docs/api/issues.md @@ -189,6 +189,24 @@ POST /api/issues/{issueId}/comments Agent @-mentions are context only and do not trigger heartbeats. Normal comment feedback can still wake the current assignee. Use explicit assignment or a review request to ask another agent to act. +### Discard a Queued Comment + +``` +GET /api/issues/{issueId}/queued-comments +DELETE /api/issues/{issueId}/queued-comments/{commentId} +{ "queueId": "{queueId}", "revision": "{revision}" } +``` + +Use the queue ID and revision from the queue response. Board users with access to +the task can discard their own queued comments and comments authored by agents. +Other people's queued comments remain author-only. Editing remains author-only. +Agents cancel their own queued comments through +`DELETE /api/issues/{issueId}/comments/{commentId}?mode=cancel`. + +The discard removes the pending comment and its queue linkage. Removing the last +entry also cancels its queued continuation. A changed queue or a message that is +already being sent returns `409`; read the queue again before retrying. + ## Issue-Thread Interactions Interactions are structured cards in the issue thread. Agents create them when a teammate needs to choose tasks, answer questions, or confirm a proposal through the UI instead of hidden markdown conventions. diff --git a/server/src/__tests__/issue-comment-cancel-routes.test.ts b/server/src/__tests__/issue-comment-cancel-routes.test.ts index 88fb71596f0..7d9a387393e 100644 --- a/server/src/__tests__/issue-comment-cancel-routes.test.ts +++ b/server/src/__tests__/issue-comment-cancel-routes.test.ts @@ -392,6 +392,22 @@ describe("issue comment cancel routes", () => { expect(mockIssueService.removeComment).not.toHaveBeenCalled(); }); + it("points a non-author agent at a board user for an agent-authored queued message", async () => { + mockIssueService.getComment.mockResolvedValue(makeComment({ + authorUserId: null, authorAgentId: "33333333-3333-4333-8333-333333333333", + })); + const agent = { type: "agent", agentId: "22222222-2222-4222-8222-222222222222", companyId: "company-1", runId: "run-1", source: "agent_key" }; + const res = await request(await installActor(createApp(), agent)) + .delete("/api/issues/11111111-1111-4111-8111-111111111111/queued-comments/comment-1") + .send({ queueId: "queue-1", revision: "revision-1" }); + + expect(res.status).toBe(403); + expect(res.body.error).toContain("board user with access"); + expect(res.body.error).toContain("[PAP-1353](/PAP/issues/PAP-1353)"); + expect(res.body.error).not.toContain("no board, admin or agent override"); + expect(mockIssueService.removeComment).not.toHaveBeenCalled(); + }); + it("returns 404 without task details when the agent cannot read the private task", async () => { mockAccessService.decide.mockImplementation(async ({ action }: { action: string }) => ({ action, allowed: false, reason: "deny_issue_private", explanation: "Private task", diff --git a/server/src/__tests__/issue-queued-comments-routes.test.ts b/server/src/__tests__/issue-queued-comments-routes.test.ts index b7fa23db6e7..dc527c5c8a9 100644 --- a/server/src/__tests__/issue-queued-comments-routes.test.ts +++ b/server/src/__tests__/issue-queued-comments-routes.test.ts @@ -1773,6 +1773,68 @@ describeEmbeddedPostgres("issue queued-comment routes", () => { expect(discard.status).toBe(403); }); + it.each(["running", "failed"] as const)("lets the board discard an agent message while the previous run is %s", async (status) => { + const seeded = await seedQueue(); + await db.update(issueComments).set({ authorType: "agent", authorUserId: null, authorAgentId: seeded.agentId }) + .where(eq(issueComments.id, seeded.commentIds[0])); + if (status === "failed") { + await db.update(heartbeatRuns).set({ status, finishedAt: new Date("2026-08-22T15:04:00Z") }) + .where(eq(heartbeatRuns.id, seeded.runId)); + await db.update(issues).set({ executionRunId: null, status: "todo" }).where(eq(issues.id, seeded.issueId)); + } + const initial = await request(app(seeded.companyId)).get(`/api/issues/${seeded.issueId}/queued-comments`); + expect(initial.status).toBe(200); + expect(initial.body.entries[0]).toMatchObject({ canEdit: false, canDiscard: true }); + + const edit = await request(app(seeded.companyId)) + .patch(`/api/issues/${seeded.issueId}/queued-comments/${seeded.commentIds[0]}`) + .send({ queueId: seeded.wakeId, revision: initial.body.revision, body: "changed author text" }); + expect(edit.status).toBe(403); + + const discarded = await request(app(seeded.companyId)) + .delete(`/api/issues/${seeded.issueId}/queued-comments/${seeded.commentIds[0]}`) + .send({ queueId: seeded.wakeId, revision: initial.body.revision }); + expect(discarded.status, JSON.stringify(discarded.body)).toBe(200); + expect(discarded.body.entries.map((entry: { comment: { id: string } }) => entry.comment.id)).toEqual([seeded.commentIds[1]]); + + const reloaded = await request(app(seeded.companyId)).get(`/api/issues/${seeded.issueId}/queued-comments`); + expect(reloaded.body.entries.map((entry: { comment: { id: string } }) => entry.comment.id)).toEqual([seeded.commentIds[1]]); + const deleted = await db.select().from(issueComments).where(eq(issueComments.id, seeded.commentIds[0])); + expect(deleted).toHaveLength(0); + const wake = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, seeded.wakeId)).then(rows => rows[0]); + expect((wake?.payload as any)._paperclipWakeContext.wakeCommentIds).toEqual([seeded.commentIds[1]]); + const activity = await db.select().from(activityLog).where(eq(activityLog.entityId, seeded.issueId)); + expect(activity).toEqual(expect.arrayContaining([expect.objectContaining({ + actorType: "user", actorId: "queue-owner", action: "issue.queued_comment_discarded", + })])); + }); + + it.each(["private task", "other company"] as const)("hides an agent queue from a board user outside its %s access", async (boundary) => { + const seeded = await seedQueue(); + await db.update(issueComments).set({ authorType: "agent", authorUserId: null, authorAgentId: seeded.agentId }) + .where(eq(issueComments.id, seeded.commentIds[0])); + const initial = await request(app(seeded.companyId)).get(`/api/issues/${seeded.issueId}/queued-comments`); + let actorCompanyId = seeded.companyId; + if (boundary === "private task") { + await db.update(issues).set({ visibility: "private", privacyRootIssueId: seeded.issueId, + createdByUserId: "queue-owner", responsibleUserId: "queue-owner" }).where(eq(issues.id, seeded.issueId)); + } else { + actorCompanyId = randomUUID(); + await db.insert(companies).values({ id: actorCompanyId, name: "Other company", issuePrefix: "OTHER" }); + await db.insert(companyMemberships).values({ companyId: actorCompanyId, principalType: "user", + principalId: "foreign-operator", status: "active", membershipRole: "operator" }); + } + + const response = await request(app(actorCompanyId, boundary === "private task" ? "other-operator" : "foreign-operator")) + .delete(`/api/issues/${seeded.issueId}/queued-comments/${seeded.commentIds[0]}`) + .send({ queueId: seeded.wakeId, revision: initial.body.revision }); + expect(response.status).toBe(404); + expect(await db.select().from(issueComments).where(eq(issueComments.id, seeded.commentIds[0]))).toHaveLength(1); + const wake = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, seeded.wakeId)).then(rows => rows[0]); + expect((wake?.payload as any)._paperclipWakeContext.wakeCommentIds).toEqual(seeded.commentIds); + expect(await db.select().from(activityLog).where(eq(activityLog.entityId, seeded.issueId))).toHaveLength(0); + }); + it("leaves the selected row queued when no native steering session is attached", async () => { const seeded = await seedQueue(); const initial = await request(app(seeded.companyId)) diff --git a/server/src/modules/wake-queue/application/queued-comment-use-cases.test.ts b/server/src/modules/wake-queue/application/queued-comment-use-cases.test.ts index d7baf864385..cda69a85b10 100644 --- a/server/src/modules/wake-queue/application/queued-comment-use-cases.test.ts +++ b/server/src/modules/wake-queue/application/queued-comment-use-cases.test.ts @@ -395,7 +395,7 @@ describe("discardQueuedComment", () => { it("rejects a discard from an actor who did not author the comment", async () => { const locked = lockedState({ queue: queueSnapshot({ entries: [ - entry({ comment: commentFixture({ authorUserId: "user-2", authorAgentId: null }) }), + entry({ canDiscard: false, comment: commentFixture({ authorUserId: "user-2", authorAgentId: null }) }), ] }) }); const discardQueuedComment = createDiscardQueuedComment({ issueLock: createFakeIssueLock(locked, createFakeTransaction()) }); @@ -411,6 +411,46 @@ describe("discardQueuedComment", () => { ).rejects.toBeInstanceOf(QueuedCommentMutationForbiddenError); }); + it("lets the board discard an agent message allowed by the locked queue and cancels its empty continuation", async () => { + const locked = lockedState({ + state: "queued", + queueRun: runRow(), + queue: queueSnapshot({ state: "queued", entries: [entry({ + comment: commentFixture({ authorType: "agent", authorUserId: null, authorAgentId: "agent-1" }), + canEdit: false, + canDiscard: true, + })] }), + }); + const transaction = createFakeTransaction(); + const discard = createDiscardQueuedComment({ issueLock: createFakeIssueLock(locked, transaction) }); + + const result = await discard({ issue: ISSUE, actor: USER_ACTOR, commentId: "comment-1", + queueId: "wake-1", revision: "rev-1", now: new Date(), logActivity: true }); + + expect(transaction.deleteComment).toHaveBeenCalledWith({ issueId: ISSUE.id, commentId: "comment-1" }); + expect(transaction.cancelWake).toHaveBeenCalledOnce(); + expect(result.cancelledRun).toEqual({ id: "run-1" }); + expect(transaction.logActivity).toHaveBeenCalledWith(expect.objectContaining({ + actorType: "user", actorId: USER_ACTOR.actorId, action: "issue.queued_comment_discarded", + })); + }); + + it.each([ + { actor: USER_ACTOR, canDiscard: false }, + { actor: AGENT_ACTOR, canDiscard: true }, + ])("does not grant a non-author $actor.actorType a denied or board-only discard", async ({ actor, canDiscard }) => { + const locked = lockedState({ queue: queueSnapshot({ entries: [entry({ + comment: commentFixture({ authorType: "agent", authorUserId: null, authorAgentId: "agent-2" }), + canDiscard, + })] }) }); + const transaction = createFakeTransaction(); + const discard = createDiscardQueuedComment({ issueLock: createFakeIssueLock(locked, transaction) }); + + await expect(discard({ issue: ISSUE, actor, commentId: "comment-1", queueId: "wake-1", + revision: "rev-1", now: new Date() })).rejects.toBeInstanceOf(QueuedCommentMutationForbiddenError); + expect(transaction.deleteComment).not.toHaveBeenCalled(); + }); + it("authorizes an agent actor discarding its own queued message", async () => { const locked = lockedState({ queue: queueSnapshot({ entries: [ diff --git a/server/src/modules/wake-queue/application/queued-comment-use-cases.ts b/server/src/modules/wake-queue/application/queued-comment-use-cases.ts index 8fc16245599..68fe32cbc80 100644 --- a/server/src/modules/wake-queue/application/queued-comment-use-cases.ts +++ b/server/src/modules/wake-queue/application/queued-comment-use-cases.ts @@ -263,7 +263,7 @@ export function createDiscardQueuedComment(deps: { issueLock: QueuedCommentIssue authorAgentId: entry.comment.authorAgentId, authorUserId: entry.comment.authorUserId, }); - if (!owns) { + if (!owns && !(input.actor.actorType === "user" && entry.canDiscard)) { throw new QueuedCommentMutationForbiddenError("Only the queued message author can discard it"); } diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index af797a9618d..f49b584b194 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -435,15 +435,14 @@ const MAX_ISSUE_COMMENT_LIMIT = 500; const updateIssueRouteSchema = updateIssueSchema.extend({ interrupt: z.boolean().optional(), }); -/** - * Sent only to a caller that did not write the queued comment: its author is the - * only one who can discard it, and no board, admin or agent override exists. Say so with the task link, so an agent that tried can - * relay the human route at once instead of searching for another endpoint. - */ -function queuedCommentAuthorOnlyDenial(issue: { identifier?: string | null }) { +function queuedCommentDiscardDenial(issue: { identifier?: string | null }, comment: { authorAgentId: string | null }) { const identifier = issue.identifier ?? null; const prefix = identifier && /^[A-Z][A-Z0-9]*-\d+$/.test(identifier) ? identifier.split("-")[0] : null; const where = identifier && prefix ? `[${identifier}](/${prefix}/issues/${identifier})` : "its task"; + if (comment.authorAgentId) { + return `A board user with access to ${where} can discard this agent-authored queued message from its queue. ` + + "The authoring agent can also cancel its own message. Do not try other agent routes."; + } return `Only the author of a queued comment can discard it, from that queued message's menu on ${where}. ` + "This denial is final: no board, admin or agent override exists, so do not try other routes. " + `Tell the author to discard it there.`; @@ -18269,7 +18268,7 @@ export function issueRoutes( + `DELETE /api/issues/${issue.id}/comments/${comment.id}?mode=cancel, not this board route.`, ); } - throw forbidden(queuedCommentAuthorOnlyDenial(issue)); + throw forbidden(queuedCommentDiscardDenial(issue, comment)); } assertBoard(req); if (!req.actor.userId) throw forbidden("Board user context required"); @@ -18282,6 +18281,7 @@ export function issueRoutes( "Issue not found", ); if (!issue) return; + if (!(await assertIssueReadAllowed(req, res, issue))) return; const actor = getActorInfo(req); const result = await runQueuedCommentMutation(() => queuedCommentQueue.discardQueuedComment({ @@ -19547,7 +19547,7 @@ export function issueRoutes( if (!actorOwnsComment) { if (!(await assertIssueReadAllowed(req, res, issue))) return; res.status(403).json({ - error: queuedCommentAuthorOnlyDenial(issue), + error: queuedCommentDiscardDenial(issue, comment), }); return; } diff --git a/server/src/services/issue-queued-comment-queue.test.ts b/server/src/services/issue-queued-comment-queue.test.ts index 01929b5efd6..43bb8fd41f7 100644 --- a/server/src/services/issue-queued-comment-queue.test.ts +++ b/server/src/services/issue-queued-comment-queue.test.ts @@ -100,7 +100,7 @@ describe("buildQueuedCommentQueueSnapshot entry permissions", () => { ...baseFacts, actorType: "user", actorId: "user-1", - comments: [{ id: "comment-1", updatedAt: new Date(), authorUserId: "user-1" }], + comments: [{ id: "comment-1", updatedAt: new Date(), authorUserId: "user-1", authorAgentId: null }], }); expect(queue.entries[0]?.canEdit).toBe(true); @@ -112,7 +112,7 @@ describe("buildQueuedCommentQueueSnapshot entry permissions", () => { ...baseFacts, actorType: "user", actorId: "user-1", - comments: [{ id: "comment-1", updatedAt: new Date(), authorUserId: "user-2" }], + comments: [{ id: "comment-1", updatedAt: new Date(), authorUserId: "user-2", authorAgentId: null }], }); expect(queue.entries[0]?.canEdit).toBe(false); @@ -124,12 +124,24 @@ describe("buildQueuedCommentQueueSnapshot entry permissions", () => { ...baseFacts, actorType: "agent", actorId: "user-1", - comments: [{ id: "comment-1", updatedAt: new Date(), authorUserId: "user-1" }], + comments: [{ id: "comment-1", updatedAt: new Date(), authorUserId: "user-1", authorAgentId: null }], }); expect(queue.entries[0]?.canEdit).toBe(false); expect(queue.entries[0]?.canDiscard).toBe(false); }); + + it.each(["deferred", "queued"] as const)("lets the board discard an agent message in a %s queue without editing it", (state) => { + const queue = buildQueuedCommentQueueSnapshot({ + ...baseFacts, + state, + actorType: "user", + actorId: "user-1", + comments: [{ id: "comment-1", updatedAt: new Date(), authorUserId: null, authorAgentId: "agent-1" }], + }); + + expect(queue.entries[0]).toMatchObject({ canEdit: false, canDiscard: true }); + }); }); describe("withQueuedCommentIdsInRunContext", () => { diff --git a/server/src/services/issue-queued-comment-queue.ts b/server/src/services/issue-queued-comment-queue.ts index e50809fe6c7..87707f62942 100644 --- a/server/src/services/issue-queued-comment-queue.ts +++ b/server/src/services/issue-queued-comment-queue.ts @@ -176,6 +176,7 @@ type QueuedCommentQueueEntryFacts = { id: string; updatedAt: Date; authorUserId: string | null; + authorAgentId: string | null; }; /** @@ -212,7 +213,8 @@ export function buildQueuedCommentQueueSnapshot