mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-16 03:31:44 +01:00
fix(queue): keep a message a starting run's first turn took out of the queue (#21747)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A message posted while a run is starting goes into that run's first turn, and the task page shows it as sent > - The page shows it as sent only while the live queue lists it as a first-turn message > - When that queue closes, for example after a later Steer, the page has no lasting record of the delivery > - It then infers that the message is queued and shows it again with a Steer button > - This pull request reports each run's own first-turn receipt in the run list, and the page places those messages in that run > - The benefit is that a sent message stays sent ## Linked Issues or Issue Description Follow-up to #21661, found while I verified that change on staging. **What happened?** With a Codex runner, two messages were posted while the run was starting. The first turn took them and the agent acted on both. Then a third message was steered into the running turn. After the Steer, the first two messages came back into the queue with Steer buttons. The server queue was empty. **Expected behavior** Messages that a run's first turn took stay in the conversation as delivered. **Steps to reproduce** 1. Start a task with a Paperclip runner agent. 2. While the runner is starting, post one or two messages. 3. After the turn starts, post another message and click Steer. ## What Changed - `activityService.runsForIssue` returns `firstTurnCommentIds` from the run's `firstTurnQueuedInput` receipt. The field is set only when the receipt names this run, because a retry copies its predecessor's context. - `IssueDetail` adds those ids to the run's start inputs, so the messages are placed in that run and are not inferred as queued. - `RunForIssue` type gets the new optional field. ## Verification Red/green tests. Each failed before the fix and passes after it: - `server/src/__tests__/activity-service.test.ts`: "reports the queued messages a run's own first turn took, not a predecessor's". 33/33 pass. - `ui/src/pages/IssueDetail.test.tsx`: "keeps a message the running turn already took out of the queue after the live queue closes". The IssueDetail, queue helper, and task-chat suites pass (69 files, 1298 tests). UI typecheck passes. Staging, after #21661 deployed, Codex runner: two messages posted while the run started were taken into the first turn and acted on. No Interrupt, error banner, or composer wait was shown. A mid-turn Steer was accepted in seconds. This PR fixes the one defect that the check found. ## Risks - Low. One new read-only field on the run list. A run that took messages and then failed before its provider accepted the turn now shows those messages in that run. The next run still delivers them, and the queue still lists them while they wait. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and code execution. ## 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 - [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 - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e7f31705da
commit
3244780bd0
6 files changed
+120
-2
No files matched your search
@@ -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();
|
||||
|
||||
@@ -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<string[] | null>`${heartbeatRuns.contextSnapshot} -> 'wakeCommentIds'`,
|
||||
// Queued messages this run's own accepted first turn took.
|
||||
firstTurnCommentIds: acceptedFirstTurnCommentIdsSql(heartbeatRuns),
|
||||
queuedCommentSourceWakeIds: sql<string[] | null>`${heartbeatRuns.contextSnapshot} -> 'queuedCommentSourceWakeIds'`,
|
||||
wakeCommentId: sql<string | null>`${heartbeatRuns.contextSnapshot} ->> 'wakeCommentId'`,
|
||||
contextCommentId: sql<string | null>`${heartbeatRuns.contextSnapshot} ->> 'commentId'`,
|
||||
|
||||
@@ -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<string[] | null>`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<Db, "select">, input: {
|
||||
companyId: string; issueId: string; agentId: string; commentIds: string[];
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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" }));
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
Reference in new issue
Block a user