Files
PaperClipAI/server/src/modules/wake-queue/adapters/chat-wake-delivered.test.ts
T
d018a9d1cd fix(queue): retain chat bindings on resolved card continuations (#20825)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - A task can receive a card response while its agent runs.
> - The queue saves this response for the next turn.
> - Chat authorization requires the saved inbound message binding.
> - Queue promotion removed this binding when a prior turn received the
message.
> - This pull request retains live bindings for resolved card responses.
> - The next turn can check current chat access and continue the
approved work.

## Linked Issues or Issue Description

**What happened?**

An accepted plan card queued behind a chat run could start with a chat
source and no message IDs. Reviewed chat authorization then failed with
context_mismatch before provider work started.

**Expected behavior**

A resolved card must retain its live chat binding through queue
promotion. The new run must check current access. A consumed
message-only wake must not start another turn.

**Steps to reproduce**

1. Start a chat run with an inbound message.
2. Queue a card response with that message binding.
3. Complete the first run and release its queue.
4. Inspect the promoted context and check chat authorization.

Related work: #20689 cancels consumed message-only wakes. #19156
protects a successor checkout. This change retains the binding for an
independent card response.

## What Changed

- Retain delivered message bindings for resolved chat card responses
during queue promotion.
- Keep deleted, foreign-task, and self-authored message filters and
current chat authorization.
- Add a persisted queue regression and Slack/Discord
promotion-to-authorization checks, including access revocation.
- Document the queue behavior.

## Verification

- Before the fix, the persisted queue test failed because the promoted
context had no wakeCommentIds. Three existing tests passed.
- The first focused run passed 108 tests. The added Slack and Discord
checks passed after promotion and refused revoked access.
- Final head a38bcb9bc5: 110/110 focused
tests pass. Low-memory server typecheck passes. pnpm verify exits 2 and
requires broad hosted CI. CI typecheck, build, all
E2E/general/serialized tests and Runner checks pass except the Runner
support suite and its aggregate gate. The support suite fails on
inherited stale SDK lock pins (source-sdk-public-type,
source-sdk-evidence and source-sdk-public-inputs); existing PR #20623
owns that repair and has passing CI. No retry is appropriate for this
deterministic failure. Greptile reviewed this exact head at 5/5 with no
actionable findings; there are no inline or unresolved review threads.
- The hosted failed task independently resumed. No source task replay or
deployment was performed. Fixed-release hosted provider acceptance
remains unverified.
- Preflight installed dependencies but could not build Rust binaries
because Cargo is absent. The first server typecheck ended without a
diagnostic; the low-memory retry passed.

## Risks

An overly broad exception could deliver consumed input twice. The
exception applies only to resolved card responses with a chat source.
Message-only wakes still cancel. Message existence, task scope, author
filters, execution ownership, and current chat access still apply.

## Model Used

OpenAI GPT-6 Codex agent with reasoning, repository tools, and code
execution. The runtime did not expose a more specific model build ID.

## 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 described the issue in-PR following the relevant issue
template
- [x] I have not referenced internal/instance-local Paperclip issues or
links
- [x] My branch name describes the change and contains no internal
ticket id
- [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
- [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 <noreply@paperclip.ing>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 14:12:02 -06:00

158 lines
10 KiB
TypeScript

import { randomUUID } from "node:crypto";
import { eq } from "drizzle-orm";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { agents, agentWakeupRequests, companies, createDb, heartbeatRuns, issueComments, issues, issueThreadInteractions } from "@paperclipai/db";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js";
import { createReleaseIssueExecution } from "../application/use-cases.js";
import { createPostgresWakeQueueAdapter } from "./postgres.js";
import { resolveInboundWakeReceipt } from "../../../services/chat-inbound-wakeup-publications.js";
import { createDurableChatWakeupRequest } from "../../../services/durable-chat-wakeup.js";
const support = await getEmbeddedPostgresTestSupport();
// A GitHub message arrives while the agent's run is active. The wake is saved
// behind that run. The run reads the message (it is in its wake input) and
// finishes. Before this fix the saved wake was still promoted, with its message
// ids removed. A reviewed chat run with no message cannot be attested, so it
// failed with `reviewed_chat_execution_binding_not_authorized` (context_mismatch)
// and blocked the task.
describe.skipIf(!support.supported)("release of a saved chat wake whose message was delivered", () => {
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: ReturnType<typeof createDb>;
let companyId: string;
let agentId: string;
beforeAll(async () => {
database = await startEmbeddedPostgresTestDatabase("wake-chat-delivered-");
db = createDb(database.connectionString);
const [company] = await db.insert(companies).values({ name: "Chat wake fixture", issuePrefix: "CWD" }).returning();
const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Reviewer", adapterType: "process" }).returning();
companyId = company.id;
agentId = agent.id;
}, 60_000);
afterAll(async () => {
await db?.$client.end();
await database?.cleanup();
});
async function seed(delivered: boolean, interaction = false) {
const [issue] = await db.insert(issues).values({ companyId, title: "Review a pull request", status: "in_review",
assigneeAgentId: agentId }).returning();
const [message] = await db.insert(issueComments).values({ companyId, issueId: issue.id, authorUserId: "chat-user",
body: "GitHub review request.", createdAt: new Date(Date.now() - 60_000), updatedAt: new Date(Date.now() - 60_000) }).returning();
// The finishing run started after the message and received it as wake input.
const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, status: "succeeded",
invocationSource: "assignment", triggerDetail: "system", startedAt: new Date(Date.now() - 30_000), finishedAt: new Date(),
contextSnapshot: { issueId: issue.id, source: "chat:github", wakeReason: "External chat message received",
chatConversationId: randomUUID(), ...(delivered ? { wakeCommentIds: [message.id] } : { wakeCommentIds: [randomUUID()] }) },
}).returning();
await db.update(issues).set({ executionRunId: run.id, executionLockedAt: new Date() }).where(eq(issues.id, issue.id));
// The person accepted the card while the run was active.
const card = interaction ? (await db.insert(issueThreadInteractions).values({ companyId, issueId: issue.id,
kind: "request_confirmation", status: "accepted", payload: { version: 1, prompt: "Proceed?" },
resolvedByUserId: "chat-user", resolvedAt: new Date(Date.now() - 10_000) }).returning())[0] : null;
const context = { issueId: issue.id, taskId: issue.id, source: "chat:github", wakeReason: "External chat message received",
wakeSource: "assignment", chatConversationId: randomUUID(), commentId: message.id, wakeCommentId: message.id,
wakeCommentIds: [message.id], ...(card ? { interactionId: card.id, interactionKind: "request_confirmation", interactionStatus: "accepted" } : {}) };
const wakeId = randomUUID();
const { idempotencyKey } = createDurableChatWakeupRequest({ id: wakeId, companyId, agentId, issueId: issue.id,
commentId: message.id, requestedByActorType: "user", requestedByActorId: "chat-user", requestedAt: new Date(),
authorize: async () => {} });
const [wake] = await db.insert(agentWakeupRequests).values({ id: wakeId, idempotencyKey, companyId, agentId, source: "assignment",
triggerDetail: "system", reason: "External chat message received", status: "deferred_issue_execution",
requestedByActorType: "user", requestedByActorId: "chat-user",
payload: { issueId: issue.id, mutation: interaction ? "interaction" : "chat_message_received", wakeCommentId: message.id,
...(card ? { interactionId: card.id, interactionKind: card.kind, interactionStatus: "accepted" } : {}), _paperclipWakeContext: context },
}).returning();
return { issue, run, wake, message };
}
function release(unexpected: () => never) {
return createReleaseIssueExecution({
issueLock: createPostgresWakeQueueAdapter(db, { resolveResponsibleUserId: unexpected, getRoutineEnv: unexpected,
resolveSessionBeforeForWakeup: unexpected } as never),
recovery: { escalateStrandedAssignedIssue: unexpected, escalateStrandedRecoveryIssueInPlace: unexpected } as never,
});
}
it("consumes the saved chat wake instead of starting a run with no message", async () => {
const { run, wake } = await seed(true);
const unexpected = vi.fn((): never => { throw new Error("Unexpected promotion of a consumed chat wake"); });
const result = await release(unexpected)({ companyId, runId: run.id, now: new Date() });
expect(result.outcome.kind).toBe("released");
expect(unexpected).not.toHaveBeenCalled();
const [saved] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wake.id));
expect(saved).toMatchObject({ status: "cancelled", runId: null, error: "Queued messages were already delivered to a completed run" });
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, companyId)).then(rows =>
rows.filter(row => row.contextSnapshot?.issueId === saved.payload?.issueId && row.id !== run.id))).toEqual([]);
});
it("keeps the live chat binding when an accepted card queues behind a run that received its message", async () => {
const { issue, run, wake, message } = await seed(true, true);
const release = createReleaseIssueExecution({
issueLock: createPostgresWakeQueueAdapter(db, {
resolveResponsibleUserId: async () => "chat-user",
getRoutineEnv: async () => ({ routineId: null, env: null, responsibleUserId: null }),
resolveSessionBeforeForWakeup: async () => null,
} as never),
recovery: {} as never,
});
const result = await release({ companyId, runId: run.id, now: new Date() });
expect(result.outcome.kind).toBe("promoted");
const [saved] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wake.id));
const [promoted] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, saved.runId!));
expect(promoted.contextSnapshot).toMatchObject({
issueId: issue.id, source: "chat:github",
interactionStatus: "accepted",
wakeCommentIds: [message.id],
});
const [locked] = await db.select().from(issues).where(eq(issues.id, issue.id));
expect(locked.executionRunId).toBe(promoted.id);
});
it("continues an accepted card owed to a task the finishing run closed, without reopening it to todo", async () => {
const { issue, run, wake, message } = await seed(true, true);
// The run that received the message closed the task after the person accepted the card.
await db.update(issues).set({ status: "done", completedAt: new Date() }).where(eq(issues.id, issue.id));
const result = await createReleaseIssueExecution({
issueLock: createPostgresWakeQueueAdapter(db, {
resolveResponsibleUserId: async () => "chat-user",
getRoutineEnv: async () => ({ routineId: null, env: null, responsibleUserId: null }),
resolveSessionBeforeForWakeup: async () => null,
} as never),
recovery: {} as never,
})({ companyId, runId: run.id, now: new Date() });
const [saved] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wake.id));
expect(result.outcome.kind, JSON.stringify(saved)).toBe("promoted");
const [task] = await db.select().from(issues).where(eq(issues.id, issue.id));
expect(task.status).toBe("in_progress");
const [promoted] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, saved.runId!));
expect(promoted.contextSnapshot).toMatchObject({ source: "chat:github", interactionStatus: "accepted",
wakeCommentIds: [message.id] });
});
it("does not report a delivered chat message as not started", async () => {
const { wake } = await seed(true);
const action = { id: wake.id, companyId, kind: "inbound_wakeup", conversationId: randomUUID(), deliveryId: randomUUID(),
principalId: randomUUID(), createdAt: wake.requestedAt, status: "processed",
payload: { version: 1, agentId, issueId: wake.payload?.issueId, commentId: wake.payload?.wakeCommentId,
requestedByActorType: "user", requestedByActorId: "chat-user" } };
const consumed = { ...wake, status: "cancelled", error: "Queued messages were already delivered to a completed run" };
expect(resolveInboundWakeReceipt(action as never, consumed, consumed)).toBeNull();
// Other declines keep their notice.
const refused = { ...wake, status: "cancelled", error: "Deferred wake suppressed by active subtree pause hold" };
expect(resolveInboundWakeReceipt(action as never, refused, refused)).toMatchObject({ state: "not_started" });
});
it("still promotes a saved chat wake whose message no run has received", async () => {
const { run, wake } = await seed(false);
// Promotion reaches the host; the refusal proves the wake was not consumed.
const unexpected = vi.fn((): never => { throw new Error("promotion reached the host"); });
await expect(release(unexpected)({ companyId, runId: run.id, now: new Date() })).rejects.toThrow("promotion reached the host");
expect(unexpected).toHaveBeenCalled();
const [saved] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wake.id));
expect(saved.status).not.toBe("cancelled");
});
});