From 08341ea134b9fbc39b00b450fdbb9b0857287457 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Fri, 13 Nov 2026 13:03:46 -0600 Subject: [PATCH] fix(queue): let board users discard agent-authored queued messages (#21458) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The task composer holds messages that an agent has not consumed yet. > - A board operator needs to remove an agent-authored pending message before it starts more work. > - The queue currently grants discard only to the human author, so these messages have a disabled trash button and the API rejects the board user. > - This change derives the board discard permission in the queue snapshot and uses that same permission under the existing issue lock. > - The route checks task access before it changes the queue. The benefit is a working discard action with the existing company, privacy, revision, and dispatch guards. ## Linked Issues or Issue Description Fixes #15464. Supersedes #15465 with an independent implementation and red/green regression evidence. Thanks to @MMTE for identifying the gap and proposing a fix. Related: #18958 addresses deletion of comments that have already been delivered; this change covers pending queue entries. ## What Changed - Queue responses grant board users discard permission for agent-authored messages. Editing and other human authors' messages retain their existing permissions. - The discard use case honors the actor-specific permission rebuilt under the queue lock. Author agents keep their existing cancellation path. - The board discard route checks private-task access before deletion. The denial for a non-author agent now points to the board action instead of saying that no board action exists. - Tests cover queue states, cancellation of an empty continuation, persistence, queue linkage, audit attribution, private-task denial, and cross-company denial. The API reference describes the supported action. ## Verification - Red before the fix: the two snapshot regressions returned `canDiscard: false`; the discard regression threw `QueuedCommentMutationForbiddenError`. The route regressions also caught the disabled permission, missing private-task guard, and stale agent denial text. - Green after the fix: 30 queue snapshot and use-case tests; all five focused route regressions with real disposable Postgres; six Postgres adapter tests; 42 existing queue UI tests. - Server typecheck: `cd server && node scripts/typecheck-layers.mjs` passes. `node scripts/check-module-boundaries.mjs` and `git diff --check` pass. - The [complete PR workflow](https://github.com/paperclipai/paperclip/actions/runs/43484735280) passes on head `164200602828e23f01a8b209ff954821c5e14e9a`. [Greptile reports 5/5](https://github.com/paperclipai/paperclip/pull/21458#issuecomment-6861824451) on that same head with no open review threads. - Local scope: the 83 focused snapshot, use-case, route, adapter, and UI checks pass. The existing queue UI suite has 42 tests. The new route cases use real disposable Postgres and verify the resulting database state after reload. - Additional local full-suite attempt: 174 tests passed and 13 approval-related tests failed with cleanup timeouts, Postgres deadlocks, and duplicate-prefix errors after cleanup failed. The first failure, `queues request_confirmation resolution while its legacy source run is still running`, also fails on unchanged base code with the same 30-second `afterEach` and `afterAll` timeouts. This broader local run is not counted as a pass. No test timeout or assertion was weakened. CI supplies the broad passing result for the committed head. - `node scripts/local-verify.mjs --explain` returned exit 2 because the API documentation is a global CI input; all of its required CI lanes passed. The initial adapter attempt could not initialize local Postgres under the sandbox; the same six checks passed with local-process access. The initial cross-company fixture was corrected to use a distinct company prefix. ## Risks - This grants board operators a new action on agent-authored pending messages. The route must pass company membership and private-task access checks; the mutation retains its transaction, revision, and dispatch protections. - No schema or migration is required. The UI uses its existing discard control and error handling. - The staging task was inspected to confirm the cause. No staging data was deleted, and a deployed UI retest is not claimed by these local and CI checks. ## Model Used - OpenAI Codex, GPT-6, with reasoning, repository inspection, tool use, and code execution. The exact runtime model ID and context limit are not exposed in this session. ## 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 - [x] I have run tests locally and they pass — the focused regression, adapter, and UI checks listed above; the additional broad local cleanup failure is documented separately - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge Co-authored-by: Paperclip --- docs/api/issues.md | 18 ++++++ .../issue-comment-cancel-routes.test.ts | 16 +++++ .../issue-queued-comments-routes.test.ts | 62 +++++++++++++++++++ .../queued-comment-use-cases.test.ts | 42 ++++++++++++- .../application/queued-comment-use-cases.ts | 2 +- server/src/routes/issues.ts | 16 ++--- .../issue-queued-comment-queue.test.ts | 18 +++++- .../services/issue-queued-comment-queue.ts | 4 +- 8 files changed, 164 insertions(+), 14 deletions(-) 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