diff --git a/server/src/__tests__/activity-service.test.ts b/server/src/__tests__/activity-service.test.ts index 2ac88be6d82..ddebc3f5339 100644 --- a/server/src/__tests__/activity-service.test.ts +++ b/server/src/__tests__/activity-service.test.ts @@ -10,6 +10,7 @@ import { createDb, documentRevisions, documents, + heartbeatRunEvents, heartbeatRuns, issueComments, issueDocuments, @@ -69,6 +70,7 @@ describeEmbeddedPostgres("activity service", () => { await db.delete(documentRevisions); await db.delete(documents); await db.delete(issues); + await db.delete(heartbeatRunEvents); await db.delete(heartbeatRuns); await db.delete(agentWakeupRequests); await db.delete(agents); @@ -275,6 +277,45 @@ describeEmbeddedPostgres("activity service", () => { expect(rows.map((row) => row.action)).not.toContain("private.changed"); }); + it("reports the queued messages a run's own accepted first turn took", async () => { + const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(); + const acceptedRunId = randomUUID(), unacceptedRunId = randomUUID(), retryRunId = randomUUID(); + const taken = [randomUUID(), randomUUID()], editedAfterSeal = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Paperclip", + issuePrefix: `F${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`, requireBoardApprovalForNewAgents: false }); + await db.insert(agents).values({ id: agentId, companyId, name: "Runner", role: "engineer", status: "running", + adapterType: "paperclip_runner", adapterConfig: {}, runtimeConfig: {}, permissions: {} }); + await db.insert(issues).values({ id: issueId, companyId, title: "First turn", status: "in_progress", + priority: "medium", assigneeAgentId: agentId }); + await db.insert(issueComments).values([...taken, editedAfterSeal].map((id, index) => ({ + id, companyId, issueId, authorType: "user" as const, authorUserId: "board-user", body: `Message ${index}`, + createdAt: new Date("2026-11-14T23:59:00.000Z"), + // Edited after the run sealed its input: still waiting to be delivered. + updatedAt: new Date(id === editedAfterSeal ? "2026-11-15T00:00:05.000Z" : "2026-11-14T23:59:00.000Z"), + }))); + const receipt = (runId: string) => ({ schema: "paperclip.first-turn-queued-input.v1", runId, + wakeupRequestIds: [], commentIds: [...taken, editedAfterSeal], claimedAt: "2026-11-15T00:00:00.000Z" }); + await db.insert(heartbeatRuns).values([ + { id: acceptedRunId, receiptRunId: acceptedRunId, status: "running" }, + // Sealed its input, then failed to start: the receipt proves nothing. + { id: unacceptedRunId, receiptRunId: unacceptedRunId, status: "failed" }, + // A retry copies its predecessor's context; that receipt is not its own. + { id: retryRunId, receiptRunId: acceptedRunId, status: "running" }, + ].map((run, index) => ({ + id: run.id, companyId, agentId, scopeKind: "issue" as const, issueId, invocationSource: "assignment", + status: run.status, createdAt: new Date(Date.now() - (3 - index) * 1000), + contextSnapshot: { issueId, firstTurnQueuedInput: receipt(run.receiptRunId) }, + }))); + await db.insert(heartbeatRunEvents).values([acceptedRunId, retryRunId].map(runId => ({ + companyId, runId, agentId, seq: 1, eventType: "turn.accepted", stream: "system", level: "info", + message: "turn accepted" }))); + const runs = await activityService(db).runsForIssue(companyId, issueId); + const ids = (runId: string) => runs.find(run => run.runId === runId)?.firstTurnCommentIds ?? null; + expect(ids(acceptedRunId)).toEqual(taken); + expect(ids(unacceptedRunId)).toBeNull(); + expect(ids(retryRunId)).toBeNull(); + }); + it.each([null, "native_provider_model_rejected", "adapter_failed"])("returns compact issue runs with bounded model rejection details: %s", async (errorCode) => { const companyId = randomUUID(); const agentId = randomUUID(); diff --git a/server/src/services/activity.ts b/server/src/services/activity.ts index c44b130dd26..4fa79b84104 100644 --- a/server/src/services/activity.ts +++ b/server/src/services/activity.ts @@ -1,6 +1,7 @@ import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js"; import { skillAccessService } from "./skill-access.js"; import { credentialAccessConnectionNameSql } from "./credential-access-visibility.js"; +import { acceptedFirstTurnCommentIdsSql } from "./queued-comment-delivery.js"; import { executionProjectionsForRuns } from "./execution-projection.js"; import { and, asc, desc, eq, inArray, isNull, or, sql, type SQL } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; @@ -549,6 +550,8 @@ export function activityService(db: Db) { lastUsefulActionAt: heartbeatRuns.lastUsefulActionAt, nextAction: heartbeatRuns.nextAction, wakeCommentIds: sql`${heartbeatRuns.contextSnapshot} -> 'wakeCommentIds'`, + // Queued messages this run's own accepted first turn took. + firstTurnCommentIds: acceptedFirstTurnCommentIdsSql(heartbeatRuns), queuedCommentSourceWakeIds: sql`${heartbeatRuns.contextSnapshot} -> 'queuedCommentSourceWakeIds'`, wakeCommentId: sql`${heartbeatRuns.contextSnapshot} ->> 'wakeCommentId'`, contextCommentId: sql`${heartbeatRuns.contextSnapshot} ->> 'commentId'`, diff --git a/server/src/services/queued-comment-delivery.ts b/server/src/services/queued-comment-delivery.ts index 343671a16ec..d2846bf6c4b 100644 --- a/server/src/services/queued-comment-delivery.ts +++ b/server/src/services/queued-comment-delivery.ts @@ -166,6 +166,34 @@ function firstTurnDeliveredSql(companyId: string, issueId: string, agentId: stri and accepted.event_type in ('turn.accepted', 'turn.started')))`; } +/** + * The comment ids a run's own first-turn receipt sealed, once that run's + * provider accepted the turn. A receipt alone proves nothing: the run may + * have failed before acceptance, and a retry copies its predecessor's + * receipt. A message edited after the seal is still undelivered. Same + * evidence as `firstTurnDeliveredSql`. + */ +export function acceptedFirstTurnCommentIdsSql(run: { id: typeof heartbeatRuns.id; companyId: typeof heartbeatRuns.companyId; + contextSnapshot: typeof heartbeatRuns.contextSnapshot }) { + return sql`case + when ${run.contextSnapshot} #>> '{firstTurnQueuedInput,schema}' = 'paperclip.first-turn-queued-input.v1' + and ${run.contextSnapshot} #>> '{firstTurnQueuedInput,runId}' = ${run.id}::text + and ${run.contextSnapshot} #>> '{firstTurnQueuedInput,claimedAt}' is not null + and jsonb_typeof(${run.contextSnapshot} #> '{firstTurnQueuedInput,commentIds}') = 'array' + and exists (select 1 from ${heartbeatRunEvents} accepted + where accepted.company_id = ${run.companyId} and accepted.run_id = ${run.id} + and accepted.event_type in ('turn.accepted', 'turn.started')) + then (select jsonb_agg(sealed_comment.id::text order by sealed.position) + from (select case when raw.id ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + then raw.id::uuid end as id, raw.position + from jsonb_array_elements_text(${run.contextSnapshot} #> '{firstTurnQueuedInput,commentIds}') + with ordinality as raw(id, position)) sealed + join ${issueComments} sealed_comment on sealed_comment.id = sealed.id + and sealed_comment.company_id = ${run.companyId} + where (${run.contextSnapshot} #>> '{firstTurnQueuedInput,claimedAt}')::timestamptz + >= date_trunc('milliseconds', sealed_comment.updated_at)) end`; +} + /** Ids that an accepted first provider turn already received (see `deliveredQueuedCommentIds`). */ export async function firstTurnDeliveredCommentIds(tx: Pick, input: { companyId: string; issueId: string; agentId: string; commentIds: string[]; diff --git a/ui/src/api/activity.ts b/ui/src/api/activity.ts index f2011f7eabd..75ca32163d2 100644 --- a/ui/src/api/activity.ts +++ b/ui/src/api/activity.ts @@ -38,6 +38,8 @@ export interface RunForIssue { lastUsefulActionAt?: string | null; nextAction?: string | null; wakeCommentIds?: string[] | null; + /** Queued messages this run's first provider turn took while it was starting. */ + firstTurnCommentIds?: string[] | null; wakeCommentId?: string | null; contextCommentId?: string | null; contextIssueId?: string | null; diff --git a/ui/src/pages/IssueDetail.test.tsx b/ui/src/pages/IssueDetail.test.tsx index 8015df04df7..c2547cdda51 100644 --- a/ui/src/pages/IssueDetail.test.tsx +++ b/ui/src/pages/IssueDetail.test.tsx @@ -5616,6 +5616,42 @@ describe("IssueDetail", () => { expect(props().queuedCommentQueue?.entries.map(entry => entry.comment.id)).toEqual([waiting.id]); }); + it("keeps a message the running turn already took out of the queue after the live queue closes", async () => { + // Posted while the run was still starting; its first turn took it. + const taken = createIssueComment({ id: "first-turn-message", body: "Include the word PINEAPPLE" }); + const run = { + id: "run-native", 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", assigneeAgentId: "agent-1", executionRunId: run.id })); + mockAgentsApi.list.mockResolvedValue([createAgent({ adapterType: "paperclip_runner" })]); + mockHeartbeatsApi.activeRunForIssue.mockResolvedValue(run); + mockHeartbeatsApi.liveRunsForIssue.mockResolvedValue([run]); + mockIssuesApi.listComments.mockResolvedValue([taken]); + // The deferred wake has retired, so the live queue no longer lists it. + mockIssuesApi.getQueuedComments.mockResolvedValue(createQueuedCommentQueue({ + queueId: null, state: null, targetRunId: null, entries: [], + })); + mockActivityApi.runsForIssue.mockResolvedValue([{ + runId: run.id, agentId: "agent-1", adapterType: "paperclip_runner", + status: "running", startedAt: run.startedAt, finishedAt: null, + createdAt: run.createdAt, wakeCommentIds: null, firstTurnCommentIds: [taken.id], + wakeupRequestId: "wake-start", contextIssueId: "issue-1", + }]); + await act(async () => renderIssueView()); + await waitForAssertion(() => { + const props = mockIssueChatThreadRender.mock.calls.at(-1)![0]; + expect(props.queuedCommentQueue?.entries ?? []).toEqual([]); + const comment = props.comments.find((comment: IssueComment) => comment.id === taken.id); + expect(comment).toMatchObject({ consumedByRunId: run.id }); + expect(comment?.queueState).toBeUndefined(); + }); + }); + 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" })); diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsx index d1d77565620..a852c5ede64 100644 --- a/ui/src/pages/IssueDetail.tsx +++ b/ui/src/pages/IssueDetail.tsx @@ -1793,8 +1793,16 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({ run.contextCommentId.length > 0 ? run.contextCommentId : null; - const inputIds = - batchedIds.length > 0 ? batchedIds : fallbackId ? [fallbackId] : []; + // Messages posted while the run was starting, which its first turn took. + const firstTurnIds = Array.isArray(run.firstTurnCommentIds) + ? run.firstTurnCommentIds.filter( + (value): value is string => typeof value === "string" && value.length > 0, + ) + : []; + const inputIds = [...new Set([ + ...(batchedIds.length > 0 ? batchedIds : fallbackId ? [fallbackId] : []), + ...firstTurnIds, + ])]; const anchorAt = run.startedAt ?? run.createdAt; const anchorMs = new Date(anchorAt).getTime(); inputIds.forEach((commentId, sequence) => {