fix(chat): do not wake the assignee for a decision its own run recorded (#20842)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A task can be bound to a chat conversation (Slack, Telegram).
Confirmation cards are published there
> - The assignee's running turn can record the user's chat reply as the
decision on a card (resolve-from-comment). That run already owns the
decision, and the in-app route does not wake the agent again
> - The chat continuation worker (`interaction_wakeup`) still woke the
assignee for that decision
> - The wake waited behind the running turn. When it was promoted, the
reply was already delivered, so its context kept `source:
chat:<provider>` but no chat message
> - Reviewed-chat attestation then refused the run
(`reviewed_chat_execution_binding_not_authorized`, `context_mismatch`).
The refusal is correct; the wake should not exist
> - This pull request makes the worker settle that action without a wake
> - The benefit is no failed setup run on the task, and no change to any
permission check

## Linked Issues or Issue Description

Refs #20809

**What happened?**
On staging, an automation-triggered run failed in about 5 s with
`setup_failed` and error
`reviewed_chat_execution_binding_not_authorized` (denial reason
`context_mismatch`). The task was bound to a Slack thread and was
`in_review`. The assignee's previous run had recorded the user's Slack
reply as acceptance of a plan confirmation and kept working. The chat
continuation worker then queued a second wake for the same decision.
That wake carried no undelivered chat message, so attestation found zero
admitted comment ids.

**Expected behavior**
No second wake. The responding run already acts on the decision, as in
the in-app path.

**Steps to reproduce**
1. Bind a task to a Slack conversation and publish a
`request_confirmation` card with `continuationPolicy: wake_assignee`.
2. While the assignee's run is active, the user replies in Slack. The
run calls `POST
/api/issues/:id/interactions/:interactionId/resolve-from-comment`.
3. The worker processes the `interaction_wakeup` chat action and wakes
the assignee. The wake is deferred behind the active run and loses the
delivered reply. With the task `in_review`, the next run fails
attestation.

## What Changed

- `server/src/services/chat-channels/interactions/continuations.ts`:
when the current interaction was resolved by the assignee's own run from
a comment (`resolvedByAgentId` is the assignee, `resolvedByRunId` is
set, no `resolvedByUserId`, and `result.commentId` is set; only
resolve-from-comment writes that), the worker marks the action
`processed` with `interaction_wakeup_owned_by_responding_run` and
creates no wake. Actions saved before the deploy take the same path.
- `server/src/__tests__/chat-interaction-publications.test.ts`: real
resolve-from-comment flow (no wake) and the board-accept control (one
wake).
- Reviewed-chat attestation and every authorization check are unchanged.

## Verification

- Red on master: the new test fails, `wakeup` called 1 time.
- Green: `server/src/__tests__/chat-interaction-publications.test.ts`
32/32 pass.
- `pnpm --filter @paperclipai/server typecheck` passes.

## Risks

- Low. Only a self-resolved, comment-recorded decision skips the wake. A
user decision through a chat button or the board still wakes the
assignee.
- Not covered here: a user decision made through a chat button while
another run of the task is active can still be deferred and lose its
chat comment id. That is a separate case and is not changed by this PR.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Claude (Anthropic), model ID `claude-opus-5-5`, used through Claude
Code with tool use (shell, file edits, test runs).

## 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 Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Fable 5.2 authored and GitHub committed 2026-11-11 09:47:43 -06:00
1 parent 4529dfb77f
commit a4b872477e
2 files changed
+99 -1

No files matched your search

@@ -1,6 +1,6 @@
import { randomUUID } from "node:crypto";
import { and, eq, sql } from "drizzle-orm";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import {
agents,
applyPendingMigrations,
@@ -24,6 +24,8 @@ import {
import type { ChatProvider } from "@paperclipai/shared";
import { enqueueIssueInteractionChatPublications, enqueueTerminalIssueInteractionChatPublications } from "../services/chat-interaction-publications.js";
import { issueThreadInteractionService } from "../services/issue-thread-interactions.js";
import { resolveConfirmationFromComment } from "../services/confirmation-comment-resolution.js";
import { createChatInteractionContinuations } from "../services/chat-channels/interactions/continuations.js";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
@@ -1496,5 +1498,61 @@ describeEmbeddedPostgres(
),
).toBe(true);
});
// Staging run 55207345: the assignee's running turn recorded the user's
// Slack reply as acceptance (resolve-from-comment) and kept working. The
// chat continuation worker still woke the assignee; that wake waited
// behind the running turn, lost the already-delivered reply from its
// context, and reviewed-chat attestation refused it as a failed run
// (reviewed_chat_execution_binding_not_authorized, context_mismatch).
it.each(["responding_run", "board"] as const)(
"wakes the assignee for a chat-bound confirmation only when no responding run owns the decision (%s)", async resolver => {
const fixture = await seedBoundIssue(["slack"]);
const runId = randomUUID();
await db.insert(heartbeatRuns).values({ id: runId, companyId: fixture.companyId, agentId: fixture.agentId,
status: "running", responsibleUserId: "board-user", contextSnapshot: { issueId: fixture.issueId } });
await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, fixture.issueId));
const service = issueThreadInteractionService(db);
const interaction = await service.create(
{ id: fixture.issueId, companyId: fixture.companyId },
{ kind: "request_confirmation", continuationPolicy: "wake_assignee",
payload: { version: 1, prompt: "May I merge both pull requests?" } },
{ agentId: fixture.agentId, runId },
);
await markInteractionCardsPublished(fixture.companyId, interaction.id);
if (resolver === "responding_run") {
const [reply] = await db.insert(issueComments).values({ companyId: fixture.companyId, issueId: fixture.issueId,
authorType: "user", authorUserId: "board-user", body: "yes, merge them", createdAt: new Date(Date.now() + 1_000) }).returning();
await resolveConfirmationFromComment(db, { companyId: fixture.companyId, issueId: fixture.issueId,
interactionId: interaction.id, input: { commentId: reply!.id, decision: "accept" },
actor: { agentId: fixture.agentId, runId } });
} else {
await service.acceptInteraction(
{ id: fixture.issueId, companyId: fixture.companyId, projectId: null, goalId: null },
interaction.id, {}, { userId: "board-user" },
);
}
const wakeup = vi.fn(async () => ({ id: randomUUID() }));
const continuations = createChatInteractionContinuations(db, {
heartbeat: { wakeup } as never,
preparePublications: async () => undefined,
redactError: (error: unknown) => String(error),
CONFIRMATION_WAKEUP_RETRY_BACKOFF_MS: 1_000,
});
const forInteraction = and(eq(chatActions.kind, "interaction_wakeup"),
eq(sql<string>`${chatActions.payload}->>'interactionId'`, interaction.id));
const [issued] = await db.select({ id: chatActions.id }).from(chatActions).where(forInteraction);
expect(issued).toBeDefined();
await continuations.processPendingInteractionWakeups(1, issued!.id);
const actions = await db.select({ status: chatActions.status, result: chatActions.result }).from(chatActions)
.where(forInteraction);
if (resolver === "responding_run") {
expect(wakeup).not.toHaveBeenCalled();
expect(actions).toEqual([{ status: "processed", result: { code: "interaction_wakeup_owned_by_responding_run" } }]);
} else {
expect(wakeup).toHaveBeenCalledTimes(1);
expect(actions[0]?.status).toBe("processed");
}
});
},
);
@@ -43,6 +43,24 @@ type InteractionContinuationsOptions = {
CONFIRMATION_WAKEUP_RETRY_BACKOFF_MS: number;
};
/**
* A confirmation that the assignee's own run resolved from the user's reply:
* only resolve-from-comment records the reply's comment on the result, and it
* requires the active responding run of the current assignee.
*/
function decidedByRespondingRun(
interaction: { resolvedByAgentId?: string | null; resolvedByRunId?: string | null;
resolvedByUserId?: string | null; result?: unknown },
assigneeAgentId: string,
): boolean {
const result = interaction.result && typeof interaction.result === "object"
? interaction.result as Record<string, unknown> : null;
return interaction.resolvedByAgentId === assigneeAgentId
&& typeof interaction.resolvedByRunId === "string"
&& !interaction.resolvedByUserId
&& typeof result?.commentId === "string";
}
export function createChatInteractionContinuations(db: Db, options: InteractionContinuationsOptions) {
const { redactError, CONFIRMATION_WAKEUP_RETRY_BACKOFF_MS } = options;
@@ -204,6 +222,28 @@ export function createChatInteractionContinuations(db: Db, options: InteractionC
processed += 1;
continue;
}
if (decidedByRespondingRun(currentInteraction, payload.agentId)) {
// The assignee's own running turn recorded this decision from the
// user's reply (resolve-from-comment) and already acts on it. The
// in-app route skips this self-wake too. A second wake would carry no
// undelivered chat message, so reviewed-chat attestation would refuse
// it as a failed run.
await writeAction(tx => tx
.update(chatActions)
.set({
status: "processed",
result: { code: "interaction_wakeup_owned_by_responding_run" },
updatedAt: new Date(),
})
.where(
and(
eq(chatActions.id, claimed.id),
eq(chatActions.status, "processing"),
),
));
processed += 1;
continue;
}
const idempotencyKey = `interaction:${payload.interactionId}:${payload.interactionStatus}`;
try {
const sourceCommentId = currentInteraction.sourceCommentId ?? null;