From 5c7a025032fc029c06b4e7a70b379878b9e7767a Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:11:29 -0500 Subject: [PATCH] fix(ui): clear consumed messages from the pending queue (#16317) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Task conversations keep follow-up messages pending while an agent works. > - The screen combines optimistic sends, queue snapshots, and run input records. > - A late send response can restore a local queue flag after a run takes the message. > - A stale queue snapshot can then keep the same message in pending. > - This pull request matches the input record to its source queue and clears stale pending flags. > - The benefit is that consumed messages leave pending while unsent messages stay visible. ## Linked Issues or Issue Description **What happened?** A follow-up can remain in the task composer's pending row after a run takes it as input. Local queue state can outlive the send request. The old projection cleared that state for steering, but not for ordinary run-start input. A stale queue read can also retain the consumed entry. **Expected behavior** A message that a started run takes as input appears once in history and leaves pending. Other pending messages remain available. A message assigned to a run that has not started remains pending. **Steps to reproduce** 1. Send a follow-up while a task has a live run. 2. Let a started run record that message as input before or after the send response arrives. 3. Let a queue read still include the consumed message. 4. Observe the message remain pending on the base revision. **Paperclip version or commit** Reproduced against master at `33d24e48ad` with controlled request ordering. **Deployment mode** Source checkout. Browser verification used the production task screen with a simulated native runner and delayed API responses. It did not run a live model or change a deployed instance. Related: [PR #15030](https://github.com/paperclipai/paperclip/pull/15030) addresses acknowledgement matching in the runner console. This change addresses the task-detail composer and does not modify that console. ## What Changed - Clear local pending flags when a started run records the comment as input. - Use live-run input IDs while the run-history query catches up. - Match stale queue entries by their primary or coalesced source wake ID, even when the snapshot targets the previous run or has no target. - Retain coalesced source queue IDs in run context and include receipt IDs in compact task run reads. - Keep unstarted run inputs and authoritative retries pending. Cover send ordering, same-run and successor delivery, queued snapshots, coalesced inputs, and retry consumption. - Add the delivery-race checks to the steering feature map. ## Verification - Before the fix, the first four request-order regressions failed with the consumed message still in pending. Coverage now includes 16 combinations of receipt source, send-response order, and stale snapshot kind. - Focused UI checks: 5 files and 233 tests passed. These cover task detail, queue projection, optimistic comments, queued-message controls, and the task-chat adapter. - `pnpm -r typecheck` passed. - Server receipt checks: 5 files and 139 tests passed with `PAPERCLIP_TEST_POSTGRES_TEMPLATE=0`. These exercise real database reads, coalesced heartbeat input, and polling routes. The default cached-template path timed out during setup on this host; the fresh-cluster path passed without longer timeouts. - Token gates and `node scripts/check-maps.mjs` passed. - Browser: sent a follow-up with a delayed response in the production task screen. The consumed message moved into history. A second unsent follow-up stayed queued. Reload preserved both states. The API and runner were simulated. - `pnpm build` passed. - The full local repository test run was started, then stopped to isolate database setup timeouts. All 55 GitHub CI checks passed on `4ec6820cf1f89880b801fd5f938d72f54591c5e2`, including the full test matrix. One serialized server shard passed on its single rerun after a 15-second route-test timeout; the same 97-test route suite also passed locally. - Greptile reviewed the final head at 5/5. All review threads are resolved. ## Risks - Queue display depends on matching comment IDs, source queue IDs, and a recorded start time. Rows without start evidence stay pending. Newer queues remain visible until their own input receipt arrives. - Run context gains additive receipt metadata. No schema migration is required. Dispatch order, stored queue state, company access, and steering authority stay unchanged. - Browser evidence covers controlled response ordering. It does not establish deployment or live-provider behavior. ## Model Used - OpenAI Codex, GPT-6, with reasoning, tool use, and code execution. The exact serving model ID and context-window 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 #` 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 - [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 --- maps/agent-access-map/steering.md | 4 + maps/feature-map/steering.md | 10 ++ server/src/__tests__/activity-service.test.ts | 11 +- ...artbeat-responsible-user-invariant.test.ts | 2 + server/src/routes/agents.ts | 2 + server/src/services/activity.ts | 2 + server/src/services/heartbeat/queue.ts | 1 + .../src/services/heartbeat/run-state.test.ts | 19 +++ server/src/services/heartbeat/run-state.ts | 2 + .../issue-queued-comment-queue.test.ts | 4 +- .../services/issue-queued-comment-queue.ts | 7 + ui/src/api/activity.ts | 2 + ui/src/api/heartbeats.ts | 4 + ui/src/pages/IssueDetail.test.tsx | 148 ++++++++++++++++++ ui/src/pages/IssueDetail.tsx | 62 +++++++- 15 files changed, 275 insertions(+), 5 deletions(-) diff --git a/maps/agent-access-map/steering.md b/maps/agent-access-map/steering.md index 58035be531e..f5f10a1f49d 100644 --- a/maps/agent-access-map/steering.md +++ b/maps/agent-access-map/steering.md @@ -25,6 +25,10 @@ admission. Policy: Queue inspection follows task visibility; queued user-message mutation and run cancellation require a board actor/user. +Compact task run reads retain `wakeupRequestId` and `queuedCommentSourceWakeIds` +to identify consumed input queues, including coalesced requests. These receipt +fields follow the existing task/run read checks and grant no queue mutation authority. + Evidence: `source-only` — [implementation](../../server/src/routes/issues.ts#L16166) at the reviewed commit above. diff --git a/maps/feature-map/steering.md b/maps/feature-map/steering.md index 8ee67ca3b04..96c81b373a7 100644 --- a/maps/feature-map/steering.md +++ b/maps/feature-map/steering.md @@ -70,6 +70,14 @@ cover durable ordering, authorization, steering acknowledgements, interrupt recovery, and concurrent dispatch. [Composer](../../ui/src/components/task-chat/TaskChatComposer.test.tsx) covers drafts and uncertain saves. +[Task-detail delivery races](../../ui/src/pages/IssueDetail.test.tsx) cover a +consumed message whose send response and queue snapshot arrive late. A started +run's input receipt removes that message from pending, while a separate unsent +message stays queued. Admission to a run that has not started is not delivery. +A later retry of the same message remains visible in its new authoritative queue. +Receipts retain the primary wake and coalesced source queue IDs. They clear a late +snapshot even when its target names the preceding run or is null. + ```sh pnpm exec vitest run ui/src/components/task-chat/TaskChatQueuedMessages.test.tsx server/src/__tests__/issue-queued-comments-routes.test.ts ``` @@ -82,6 +90,8 @@ fixture and opt-in prerequisites; skipped native cases are not native proof. Manual: queue three distinguishable messages. Edit one, reorder them, reload, and confirm the saved order. Discard one and confirm it never reaches execution. +After a queued message enters a started run, confirm it leaves pending even if +the send response arrives later. Reload and confirm it appears once in history. Steer one while busy and verify the agent receives that exact message once. Repeat with a rejected steer and a stale second-tab edit; the UI must preserve retryable content and explain the conflict. On a fresh run, interrupt with a diff --git a/server/src/__tests__/activity-service.test.ts b/server/src/__tests__/activity-service.test.ts index f146fc9ecc1..cf613e0b59e 100644 --- a/server/src/__tests__/activity-service.test.ts +++ b/server/src/__tests__/activity-service.test.ts @@ -3,6 +3,7 @@ import { eq } from "drizzle-orm"; import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; import { activityLog, + agentWakeupRequests, agents, companies, createDb, @@ -68,6 +69,7 @@ describeEmbeddedPostgres("activity service", () => { await db.delete(documents); await db.delete(issues); await db.delete(heartbeatRuns); + await db.delete(agentWakeupRequests); await db.delete(agents); await db.delete(companies); }); @@ -204,6 +206,7 @@ describeEmbeddedPostgres("activity service", () => { const agentId = randomUUID(); const issueId = randomUUID(); const runId = randomUUID(); + const wakeupRequestId = randomUUID(); await db.insert(companies).values({ id: companyId, @@ -233,8 +236,12 @@ describeEmbeddedPostgres("activity service", () => { assigneeAgentId: agentId, }); + await db.insert(agentWakeupRequests).values({ + id: wakeupRequestId, companyId, agentId, source: "issue", status: "claimed", + }); await db.insert(heartbeatRuns).values({ id: runId, + wakeupRequestId, companyId, agentId, scopeKind: "issue", @@ -243,7 +250,7 @@ describeEmbeddedPostgres("activity service", () => { status: errorCode ? "failed" : "succeeded", errorCode, error: "provider-error".repeat(200), - contextSnapshot: { issueId }, + contextSnapshot: { issueId, queuedCommentSourceWakeIds: ["coalesced-queue"] }, usageJson: { inputTokens: 11, output_tokens: 7, @@ -275,7 +282,9 @@ describeEmbeddedPostgres("activity service", () => { expect(runs).toHaveLength(1); expect(runs[0]).toMatchObject({ runId, + wakeupRequestId, agentId, + queuedCommentSourceWakeIds: ["coalesced-queue"], invocationSource: "assignment", contextIssueId: issueId, error: errorCode === "native_provider_model_rejected" ? "provider-error".repeat(200).slice(0, 2000) : null, diff --git a/server/src/__tests__/heartbeat-responsible-user-invariant.test.ts b/server/src/__tests__/heartbeat-responsible-user-invariant.test.ts index 39592ac031e..33fcc283b9b 100644 --- a/server/src/__tests__/heartbeat-responsible-user-invariant.test.ts +++ b/server/src/__tests__/heartbeat-responsible-user-invariant.test.ts @@ -244,6 +244,8 @@ describeEmbeddedPostgres("heartbeat responsible-user invariant", () => { const completed = await waitForRun(db, run!.id); expect(completed).toMatchObject({ status: "succeeded", responsibleUserId: operatorId }); expect(completed?.contextSnapshot?.wakeCommentIds).toEqual([commentId]); + expect(completed?.contextSnapshot?.queuedCommentSourceWakeIds).toEqual([queueId]); + expect(completed?.wakeupRequestId).not.toBe(queueId); await drainHeartbeatRunsToQuiescence(db, heartbeat); expect((await db.select().from(heartbeatRuns)).every(row => row.responsibleUserId === operatorId)).toBe(true); }); diff --git a/server/src/routes/agents.ts b/server/src/routes/agents.ts index fc081b13607..e134f1ebe28 100644 --- a/server/src/routes/agents.ts +++ b/server/src/routes/agents.ts @@ -7401,6 +7401,8 @@ export function agentRoutes( .select({ id: heartbeatRuns.id, runtimeMode: heartbeatRuns.runtimeMode, + wakeupRequestId: heartbeatRuns.wakeupRequestId, + queuedCommentSourceWakeIds: sql`${heartbeatRuns.contextSnapshot} -> 'queuedCommentSourceWakeIds'`.as("queuedCommentSourceWakeIds"), status: heartbeatRuns.status, invocationSource: heartbeatRuns.invocationSource, triggerDetail: heartbeatRuns.triggerDetail, diff --git a/server/src/services/activity.ts b/server/src/services/activity.ts index db231abbb3a..f115a4b8a24 100644 --- a/server/src/services/activity.ts +++ b/server/src/services/activity.ts @@ -412,6 +412,7 @@ export function activityService(db: Db) { .select({ runId: heartbeatRuns.id, runtimeMode: heartbeatRuns.runtimeMode, + wakeupRequestId: heartbeatRuns.wakeupRequestId, status: heartbeatRuns.status, agentId: heartbeatRuns.agentId, adapterType: agents.adapterType, @@ -440,6 +441,7 @@ export function activityService(db: Db) { lastUsefulActionAt: heartbeatRuns.lastUsefulActionAt, nextAction: heartbeatRuns.nextAction, wakeCommentIds: sql`${heartbeatRuns.contextSnapshot} -> 'wakeCommentIds'`, + queuedCommentSourceWakeIds: sql`${heartbeatRuns.contextSnapshot} -> 'queuedCommentSourceWakeIds'`, wakeCommentId: sql`${heartbeatRuns.contextSnapshot} ->> 'wakeCommentId'`, contextCommentId: sql`${heartbeatRuns.contextSnapshot} ->> 'commentId'`, contextIssueId: sql`${heartbeatRuns.contextSnapshot} ->> 'issueId'`, diff --git a/server/src/services/heartbeat/queue.ts b/server/src/services/heartbeat/queue.ts index 2b827796c89..b81906283a5 100644 --- a/server/src/services/heartbeat/queue.ts +++ b/server/src/services/heartbeat/queue.ts @@ -4041,6 +4041,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende ? withQueuedCommentIdsInRunContext( enrichedContextSnapshot, adoptedCommentIds, + adoptedComments.map((wake) => wake.id), ) : enrichedContextSnapshot, sessionIdBefore: explicitContinuation ? null : sessionBefore, diff --git a/server/src/services/heartbeat/run-state.test.ts b/server/src/services/heartbeat/run-state.test.ts index 2a4b2c590e1..2191ca1959d 100644 --- a/server/src/services/heartbeat/run-state.test.ts +++ b/server/src/services/heartbeat/run-state.test.ts @@ -2,6 +2,7 @@ import { randomBytes, randomUUID } from "node:crypto"; import type { Db } from "@paperclipai/db"; import { agents, + agentWakeupRequests, agentTaskSessions, companies, createDb, @@ -121,6 +122,24 @@ describePostgres("heartbeat run state database wiring", () => { return { companyId, agent, issue, state: extracted.createHeartbeatRunState(db) }; } + it("retains the consumed queue identity in issue polling summaries", async () => { + const { companyId, agent, issue, state } = await fixture(); + const [wake] = await db.insert(agentWakeupRequests).values({ + companyId, agentId: agent.id, source: "issue", status: "claimed", + }).returning(); + const [run] = await db.insert(heartbeatRuns).values({ + companyId, agentId: agent.id, issueId: issue.id, status: "running", + startedAt: new Date(), wakeupRequestId: wake.id, + contextSnapshot: { issueId: issue.id, commentId: "delivered-message", queuedCommentSourceWakeIds: ["coalesced-queue"] }, + }).returning(); + for (const summary of [ + await state.getRunIssueSummary(run.id), + await state.getActiveRunIssueSummaryForAgent(agent.id), + ]) { + expect(summary).toMatchObject({ id: run.id, wakeupRequestId: wake.id, contextCommentId: "delivered-message", queuedCommentSourceWakeIds: ["coalesced-queue"] }); + } + }); + it("bounds history at the service boundary and keeps company and agent scope", async () => { const { companyId, agent, state } = await fixture(); await db.execute(sql`insert into heartbeat_runs (company_id, agent_id, created_at) diff --git a/server/src/services/heartbeat/run-state.ts b/server/src/services/heartbeat/run-state.ts index 0f79a984a4f..e979572e222 100644 --- a/server/src/services/heartbeat/run-state.ts +++ b/server/src/services/heartbeat/run-state.ts @@ -353,6 +353,8 @@ const heartbeatRunLogAccessColumns = { const heartbeatRunIssueSummaryColumns = { id: heartbeatRuns.id, runtimeMode: heartbeatRuns.runtimeMode, + wakeupRequestId: heartbeatRuns.wakeupRequestId, + queuedCommentSourceWakeIds: sql`${heartbeatRuns.contextSnapshot} -> 'queuedCommentSourceWakeIds'`.as("queuedCommentSourceWakeIds"), status: heartbeatRuns.status, invocationSource: heartbeatRuns.invocationSource, triggerDetail: heartbeatRuns.triggerDetail, diff --git a/server/src/services/issue-queued-comment-queue.test.ts b/server/src/services/issue-queued-comment-queue.test.ts index 4659954ed1f..01929b5efd6 100644 --- a/server/src/services/issue-queued-comment-queue.test.ts +++ b/server/src/services/issue-queued-comment-queue.test.ts @@ -144,11 +144,12 @@ describe("withQueuedCommentIdsInRunContext", () => { paperclipTaskMarkdownAssignment: "assignment", paperclipTaskMarkdownAssignmentCompact: "assignment compact", paperclipTurnContext: { version: 1, events: { owner: "wake_prompt" } }, - }, ["comment-2"]); + }, ["comment-2"], ["source-wake"]); expect(result).toMatchObject({ issueId: "issue-1", preserved: "keep", + queuedCommentSourceWakeIds: ["source-wake"], wakeCommentIds: ["comment-2"], wakeCommentId: "comment-2", commentId: "comment-2", @@ -160,5 +161,6 @@ describe("withQueuedCommentIdsInRunContext", () => { expect(result).not.toHaveProperty("paperclipTaskMarkdownAssignment"); expect(result).not.toHaveProperty("paperclipTaskMarkdownAssignmentCompact"); expect(result).not.toHaveProperty("paperclipTurnContext"); + expect(withQueuedCommentIdsInRunContext(result, ["comment-3"]).queuedCommentSourceWakeIds).toEqual(["source-wake"]); }); }); diff --git a/server/src/services/issue-queued-comment-queue.ts b/server/src/services/issue-queued-comment-queue.ts index 7e3b5224686..60ca8efea1e 100644 --- a/server/src/services/issue-queued-comment-queue.ts +++ b/server/src/services/issue-queued-comment-queue.ts @@ -76,8 +76,15 @@ export function queuedCommentQueueRevision(input: { export function withQueuedCommentIdsInRunContext( contextValue: unknown, ids: string[], + sourceWakeIds?: string[], ): Record { const context = { ...record(contextValue) }; + if (sourceWakeIds) { + context.queuedCommentSourceWakeIds = uniqueIds([ + ...uniqueIds(context.queuedCommentSourceWakeIds), + ...sourceWakeIds, + ]); + } if (ids.length > 0) { const latestId = ids[ids.length - 1]!; context[QUEUE_IDS_KEY] = ids; diff --git a/ui/src/api/activity.ts b/ui/src/api/activity.ts index 3deac415b69..8e204f4af99 100644 --- a/ui/src/api/activity.ts +++ b/ui/src/api/activity.ts @@ -7,6 +7,8 @@ export interface RunForIssue { runId: string; execution?: ExecutionProjection | null; runtimeMode?: "legacy" | "native"; + wakeupRequestId?: string | null; + queuedCommentSourceWakeIds?: string[] | null; status: string; agentId: string; adapterType: string; diff --git a/ui/src/api/heartbeats.ts b/ui/src/api/heartbeats.ts index 8d565c28e03..3cba6d5daf9 100644 --- a/ui/src/api/heartbeats.ts +++ b/ui/src/api/heartbeats.ts @@ -23,6 +23,8 @@ export interface ActiveRunForIssue { execution?: HeartbeatRun["execution"]; id: string; runtimeMode?: "legacy" | "native"; + wakeupRequestId?: string | null; + queuedCommentSourceWakeIds?: string[] | null; status: string; invocationSource: string; triggerDetail: string | null; @@ -56,6 +58,8 @@ export interface LiveRunForIssue { execution?: HeartbeatRun["execution"]; id: string; runtimeMode?: "legacy" | "native"; + wakeupRequestId?: string | null; + queuedCommentSourceWakeIds?: string[] | null; status: string; invocationSource: string; triggerDetail: string | null; diff --git a/ui/src/pages/IssueDetail.test.tsx b/ui/src/pages/IssueDetail.test.tsx index be63805b1d3..e8e4423cb8f 100644 --- a/ui/src/pages/IssueDetail.test.tsx +++ b/ui/src/pages/IssueDetail.test.tsx @@ -3994,6 +3994,154 @@ describe("IssueDetail", () => { }); }); + it.each(([ + ["history", "before"], + ["history", "after"], + ["live", "before"], + ["live", "after"], + ] as const).flatMap(([source, order]) => + (["same-run", "previous-run", "queued", "adopted"] as const).map(queueTarget => [source, order, queueTarget] as const), + ))("retires a consumed follow-up from %s when its post resolves %s delivery with a %s snapshot", async (receiptSource, postOrder, queueTarget) => { + const postedComment = createDeferred(); + const delivered = createIssueComment({ id: "delivered", body: "Use this direction" }); + const waiting = createIssueComment({ id: "still-waiting", body: "Keep this queued" }); + const run = { + id: queueTarget === "same-run" ? "run-native" : "run-original", runtimeMode: "native" as const, status: "running", + invocationSource: "issue", triggerDetail: null, + contextCommentId: null, contextWakeCommentId: null, + startedAt: "2026-04-21T00:00:01.000Z", finishedAt: null, + createdAt: "2026-04-21T00:00:01.000Z", agentId: "agent-1", + agentName: "Runner", adapterType: "paperclip_runner", issueId: "issue-1", + }; + mockIssuesApi.get.mockResolvedValue(createIssue({ status: "in_progress", executionRunId: run.id })); + mockAgentsApi.list.mockResolvedValue([createAgent({ adapterType: "paperclip_runner" })]); + mockHeartbeatsApi.activeRunForIssue.mockResolvedValue(run); + mockHeartbeatsApi.liveRunsForIssue.mockResolvedValue([run]); + mockIssuesApi.addComment.mockReturnValue(postedComment.promise); + await act(async () => renderIssueView()); + await flushReact(); + + type Props = { + onAdd: (body: string) => Promise; + comments: Array>; + queuedCommentQueue: IssueQueuedCommentQueue | null; + }; + const props = () => mockIssueChatThreadRender.mock.calls.at(-1)![0] as Props; + await act(async () => { void props().onAdd(delivered.body); }); + await waitForAssertion(() => { + expect(props().queuedCommentQueue?.entries[0]?.comment.body).toBe(delivered.body); + }); + if (postOrder === "before") { + await act(async () => postedComment.resolve(delivered)); + await flushReact(); + } + + const staleQueue = createQueuedCommentQueue({ + state: queueTarget === "queued" ? "queued" : "deferred", + targetRunId: queueTarget === "queued" ? null : run.id, + entries: [delivered, waiting].map((comment, position) => ({ + comment, position, canEdit: true, canDiscard: true, + })), + }); + mockIssuesApi.listComments.mockResolvedValue([delivered, waiting]); + mockIssuesApi.getQueuedComments.mockResolvedValue(staleQueue); + await act(async () => { + await queryClient.invalidateQueries({ queryKey: queryKeys.issues.comments("PAP-1") }); + queryClient.setQueryData(queryKeys.issues.queuedComments("issue-1"), staleQueue); + if (receiptSource === "history") { + queryClient.setQueryData(queryKeys.issues.runs("PAP-1"), [{ + ...run, runId: "run-native", + wakeupRequestId: queueTarget === "adopted" ? "other-wake" : staleQueue.queueId, + queuedCommentSourceWakeIds: queueTarget === "adopted" ? [staleQueue.queueId] : null, + wakeCommentIds: [delivered.id], + contextIssueId: "issue-1", logBytes: 1, + }]); + } else { + const consumingRun = { + ...run, id: "run-native", + wakeupRequestId: queueTarget === "adopted" ? "other-wake" : staleQueue.queueId, + queuedCommentSourceWakeIds: queueTarget === "adopted" ? [staleQueue.queueId] : null, + contextCommentId: delivered.id, contextWakeCommentId: delivered.id, + }; + mockHeartbeatsApi.liveRunsForIssue.mockResolvedValue([consumingRun]); + mockHeartbeatsApi.activeRunForIssue.mockResolvedValue(consumingRun); + queryClient.setQueryData(queryKeys.issues.liveRuns("PAP-1"), [consumingRun]); + queryClient.setQueryData(queryKeys.issues.activeRun("PAP-1"), consumingRun); + } + }); + if (postOrder === "after") { + await act(async () => postedComment.resolve(delivered)); + } + await waitForAssertion(() => { + expect(props().queuedCommentQueue?.entries.map(entry => entry.comment.id)).toEqual([waiting.id]); + const comment = props().comments.find(comment => comment.id === delivered.id); + expect(comment).toMatchObject({ consumedByRunId: "run-native" }); + expect(comment?.queueState).toBeUndefined(); + expect(comment?.clientStatus).toBeUndefined(); + expect(props().comments.filter(comment => comment.body === delivered.body)).toHaveLength(1); + }); + await act(async () => { + await queryClient.invalidateQueries({ queryKey: queryKeys.issues.queuedComments("issue-1") }); + }); + expect(props().queuedCommentQueue?.entries.map(entry => entry.comment.id)).toEqual([waiting.id]); + }); + + it("keeps an admitted message pending until its queued run starts", async () => { + const queued = createIssueComment({ id: "not-started" }); + mockIssuesApi.get.mockResolvedValue(createIssue({ status: "in_progress", assigneeAgentId: "agent-1", executionRunId: "run-queued" })); + mockIssuesApi.listComments.mockResolvedValue([queued]); + mockIssuesApi.getQueuedComments.mockResolvedValue(createQueuedCommentQueue({ + state: "queued", targetRunId: null, + entries: [{ comment: queued, position: 0, canEdit: true, canDiscard: true }], + })); + mockActivityApi.runsForIssue.mockResolvedValue([{ + runId: "run-queued", agentId: "agent-1", adapterType: "paperclip_runner", + status: "queued", startedAt: null, finishedAt: null, + createdAt: "2026-04-21T00:00:01.000Z", wakeCommentIds: [queued.id], + wakeupRequestId: "wake-queue-1", + contextIssueId: "issue-1", + }]); + await act(async () => renderIssueView()); + await waitForAssertion(() => { + const props = mockIssueChatThreadRender.mock.calls.at(-1)![0]; + expect(props.queuedCommentQueue?.entries.map((entry: { comment: IssueComment }) => entry.comment.id)).toEqual([queued.id]); + expect(props.comments.find((comment: IssueComment) => comment.id === queued.id)?.consumedByRunId).toBeUndefined(); + }); + }); + + it.each(["queued", "deferred"] as const)("preserves an authoritative %s retry after an older run took the same input", async state => { + const retry = createIssueComment({ id: "retry-message" }); + mockIssuesApi.get.mockResolvedValue(createIssue({ status: "in_progress", assigneeAgentId: "agent-1" })); + mockIssuesApi.listComments.mockResolvedValue([retry]); + mockIssuesApi.getQueuedComments.mockResolvedValue(createQueuedCommentQueue({ + state, targetRunId: state === "deferred" ? "run-new" : null, + entries: [{ comment: retry, position: 0, canEdit: true, canDiscard: true }], + })); + const originalRun = { + runId: "run-old", agentId: "agent-1", adapterType: "paperclip_runner", + status: "failed", startedAt: "2026-04-21T00:00:01.000Z", + finishedAt: "2026-04-21T00:00:02.000Z", + createdAt: "2026-04-21T00:00:01.000Z", wakeCommentIds: [retry.id], + wakeupRequestId: "old-wake-queue", + contextIssueId: "issue-1", + }; + mockActivityApi.runsForIssue.mockResolvedValue([originalRun]); + await act(async () => renderIssueView()); + await waitForAssertion(() => { + const props = mockIssueChatThreadRender.mock.calls.at(-1)![0]; + expect(props.queuedCommentQueue?.entries.map((entry: { comment: IssueComment }) => entry.comment.id)).toEqual([retry.id]); + }); + await act(async () => { + queryClient.setQueryData(queryKeys.issues.runs("PAP-1"), [originalRun, { + ...originalRun, runId: "run-new", status: "running", finishedAt: null, + startedAt: "2026-04-21T00:00:06.000Z", wakeupRequestId: "wake-queue-1", + }]); + }); + await waitForAssertion(() => { + expect(mockIssueChatThreadRender.mock.calls.at(-1)![0].queuedCommentQueue).toBeNull(); + }); + }); + it("does not rebind a queued message when another run becomes live before its request settles", async () => { const postedComment = createDeferred(); mockIssuesApi.get.mockResolvedValue( diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsx index 78ccfa7c010..d68ddcec242 100644 --- a/ui/src/pages/IssueDetail.tsx +++ b/ui/src/pages/IssueDetail.tsx @@ -420,6 +420,7 @@ type IssueDetailComment = (IssueComment | OptimisticIssueComment) & { queueTargetRunId?: string | null; queueReason?: "hold" | "active_run" | "other"; consumedByRunId?: string | null; + consumedQueueIds?: string[]; steeredIntoRunId?: string | null; conversationAnchorAt?: Date | string | null; conversationAnchorSequence?: number; @@ -1680,11 +1681,13 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({ sequence: number; anchorMs: number; kind: "run_start" | "steer"; + queueIds: Set; } >(); for (const run of resolvedLinkedRuns) { agentIdByRunId.set(run.runId, run.agentId); + if (run.status === "queued" || !run.startedAt) continue; const batchedIds = Array.isArray(run.wakeCommentIds) ? run.wakeCommentIds.filter( (value): value is string => @@ -1704,6 +1707,11 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({ const anchorMs = new Date(anchorAt).getTime(); inputIds.forEach((commentId, sequence) => { const existing = inputPlacementByCommentId.get(commentId); + const queueIds = existing?.queueIds ?? new Set(); + if (run.wakeupRequestId) queueIds.add(run.wakeupRequestId); + if (Array.isArray(run.queuedCommentSourceWakeIds)) { + for (const queueId of run.queuedCommentSourceWakeIds) queueIds.add(queueId); + } if (existing && existing.anchorMs <= anchorMs) return; inputPlacementByCommentId.set(commentId, { runId: run.runId, @@ -1711,9 +1719,32 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({ sequence, anchorMs, kind: "run_start", + queueIds, }); }); } + for (const run of [resolvedActiveRun, ...resolvedLiveRuns]) { + if (!run || run.status !== "running" || !run.startedAt) continue; + const anchorAt = new Date(run.startedAt).toISOString(); + for (const commentId of [run.contextCommentId, run.contextWakeCommentId]) { + if (!commentId) continue; + const existing = inputPlacementByCommentId.get(commentId); + const queueIds = existing?.queueIds ?? new Set(); + if (run.wakeupRequestId) queueIds.add(run.wakeupRequestId); + if (Array.isArray(run.queuedCommentSourceWakeIds)) { + for (const queueId of run.queuedCommentSourceWakeIds) queueIds.add(queueId); + } + if (existing) continue; + inputPlacementByCommentId.set(commentId, { + runId: run.id, + anchorAt, + sequence: 0, + anchorMs: new Date(anchorAt).getTime(), + kind: "run_start", + queueIds, + }); + } + } // Same-turn steering has a durable PRP acknowledgement and a matching // activity fact keyed by commentId/targetRunId. Its acknowledgement time, // not the comment submission time, is the causal conversation slot. Use @@ -1750,6 +1781,7 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({ sequence, anchorMs, kind: "steer", + queueIds: inputPlacementByCommentId.get(commentId)?.queueIds ?? new Set(), }); } for (const [commentId, placement] of localSteeringPlacements) { @@ -1760,6 +1792,7 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({ sequence: placement.sequence, anchorMs: new Date(placement.anchorAt).getTime(), kind: "steer", + queueIds: new Set(), }); } for (const evt of resolvedActivity) { @@ -1871,6 +1904,7 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({ ...(inputPlacement ? { consumedByRunId: inputPlacement.runId, + consumedQueueIds: [...inputPlacement.queueIds], ...(inputPlacement.kind === "steer" ? { steeredIntoRunId: inputPlacement.runId } : {}), @@ -1886,8 +1920,14 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({ locallyQueuedCommentRunIds.get(comment.id) ?? nextComment.queueTargetRunId ?? null; - if (inputPlacement?.kind === "steer") { - return nextComment; + if (inputPlacement) { + return { + ...nextComment, + clientStatus: undefined, + queueState: undefined, + queueTargetRunId: null, + queueReason: undefined, + }; } const locallyQueuedComment = applyLocalQueuedIssueCommentState( nextComment, @@ -2038,23 +2078,39 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({ queuedCommentReason, resolvedActivity, resolvedLinkedRuns, + resolvedActiveRun, + resolvedLiveRuns, interruptibleIssueRun, ]); const effectiveQueuedCommentQueue = useMemo(() => { if (!queuedCommentQueueEnabled) return null; + const deliveredCommentRunIds = new Map(); + const deliveredCommentQueueIds = new Map(); + for (const comment of commentsWithRunMeta) { + if (comment.consumedByRunId) { + deliveredCommentRunIds.set(comment.id, comment.consumedByRunId); + deliveredCommentQueueIds.set(comment.id, comment.consumedQueueIds ?? []); + } + } const visibleAuthoritativeQueue = authoritativeQueuedCommentQueue ? { ...authoritativeQueuedCommentQueue, entries: authoritativeQueuedCommentQueue.entries.filter( (entry) => !consumedQueuedCommentIds.has(entry.comment.id) && - !discardedQueuedCommentIds.has(entry.comment.id), + !discardedQueuedCommentIds.has(entry.comment.id) && + !deliveredCommentQueueIds.get(entry.comment.id)?.includes( + authoritativeQueuedCommentQueue.queueId ?? "", + ) && + deliveredCommentRunIds.get(entry.comment.id) !== + authoritativeQueuedCommentQueue.targetRunId, ), } : null; const pendingComments = commentsWithRunMeta.flatMap((comment) => { if ( consumedQueuedCommentIds.has(comment.id) || + deliveredCommentRunIds.has(comment.id) || discardedQueuedCommentIds.has(comment.id) || comment.steeredIntoRunId ) {