Files
PaperClipAI/server/src/__tests__/issue-update-comment-wakeup-routes.test.ts
T
d30c8f42b8 feat(ui): keep writes durable through temporary disconnects (#17960)
<!-- entire-trail-link-start -->
https://entire.com/gh/paperclipai/-/trails/123/changes/paperclip/123
<!-- entire-trail-link-end -->

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - People save tasks, write documents, make decisions and send board
messages.
> - A disconnect can hide a response after the server accepts a write.
> - Recovery must keep the original account, task and request key.
> - The merged connection foundation in #15754 handles reads and shared
outage state.
> - This change adds bounded write recovery and explicit actions when
recovery stops.

## Linked Issues or Issue Description

**What happened?**

Temporary failures could lose edits, report accepted writes as failures,
or require people to copy and send input again. A retry could target a
newly selected task or account. Restoring attachments could create a
second task.

**Expected behavior**

Keep the draft, its owner and its target. Retry only operations with a
server contract that prevents duplicate writes. Verify uncertain
results. Show conflicts and permanent failures, with an explicit resend
or cancel action.

**Steps to reproduce**

1. Save a task title during an outage, then open another task before
recovery.
2. Restore a task creation that needs files, selecting those files in
another order.
3. Lose a document or decision response, then interrupt the verification
read.
4. Switch accounts while a create, upload or connected-channel
publication is pending.
5. Type and erase a new-task draft before the first account lookup
completes, then reopen it.

This PR carries the write layer from #15769 and its review fixes. It
targets master after #15754 merged. Related test cleanup #16952 already
covers the unchanged copy-link toast test; this PR does not duplicate
that work.

## What Changed

- Add bounded autosave and submit jobs for supported writes, with
pending, conflict and manual retry states. Retain admitted autosaves
after navigation and preserve newer task revisions.
- Keep each job with its original account, task and operation. First
account resolution adopts admitted startup work; a later account change
cancels old work. Remount inline and document editors when their owner
or document subject changes.
- Preserve task-creation keys and immutable request snapshots through
file reattachment. Restore generated document keys before comparing
reselected files. Reject changed requests instead of creating a second
task.
- Check the original account scope before creates and each upload. Save
successful upload receipts before stopping on an account change.
Identify attachments by content digest and metadata.
- Verify uncertain document and decision results. Replay only plain,
keyed comments automatically; combined reassignment, reopen and
run-setting changes require receipt reconciliation or cancel. Settle
each request once when a receipt races its retry.
- Scope drafts and connected-channel publication reads to their owner.
Keep unowned older records unread and unreplayed, with an explicit
confirmed discard action after Activity inspection. Preserve typing
through the first session lookup, keep erased text erased, and report
browser persistence only when storage succeeds.
- Wait for the first account lookup before sending startup status
changes or decisions. Retry failed required lookups with a fixed limit
and surface exhaustion to the original action. Preserve uncertain
comment keys on account cancellation. Check the account generation
before a comment retry calls its sender and again immediately before
POST after asynchronous preparation. Retire only that request’s
optimistic echo on completion.
- Return an ordinary comment’s accepted same-company, same-task,
same-user receipt before workspace reopening, task status changes or
wakeups. Reused keys with changed text still conflict. Complete
reference and activity records through the same finalizer for initial
sends and accepted retries. It locks the task before its comment,
matching task and company deletion, comment removal and tombstoning,
rejects removed or tombstoned comments, repairs references and inserts a
missing activity record in one transaction, and publishes after commit.
- Remove reader-only record and comment-body size caps so accepted
browser writes remain readable, including JSON-escaped comment requests
in local and session storage. Update four existing Storybook fixtures to
use owned draft keys.
- Document the write contracts and add regression and real browser
recovery coverage.

- Add the exact reviewed-save recovery regression for both composer
implementations and reloads. Align receipt completion, both comment
deletion methods and company deletion with task deletion by locking
tasks first. Cover real task and company deletion races.

## Verification

- The exact reviewed-unknown-save regression fails in all four cases on
original commit `1ed0af4186`. It passes with this PR for both composers,
before and after reload. Cancel keeps the text and uploaded receipt. The
retained draft sends, and the next message also sends. Run `pnpm exec
vitest run --project @paperclipai/ui
ui/src/components/composer-recovery.test.tsx`.
- The new real PostgreSQL task-deletion race fails with SQLSTATE `40P01`
on parent commit `f3253a00c4`. The company-deletion race also fails with
`40P01` on `e8cf0e02dd`. All six receipt tests pass after the final
lock-order fixes. They cover company deletion, task deletion, comment
removal, tombstoning, concurrent cross-task references and interrupted
reference repair. Run `pnpm exec vitest run --project
@paperclipai/server
server/src/__tests__/issue-comment-receipt-postgres.test.ts`.
- The full UI run passed 9,656 of 9,659 tests across 816 files. Three
cases failed under that run: two large-tree timeouts and one
plugin-panel assertion. All 67 tests in those two files passed in an
isolated rerun. These failures remain recorded; this does not claim a
clean full UI run.
- `pnpm -r typecheck`, `pnpm build`, token gates and map checks pass on
the final change. The local full repository test command was started,
then stopped when the delivery moved to this existing PR. Fresh PR CI
must provide the full-suite gate.
- A local Storybook walkthrough used the real rich editor. Cancel kept
the restored text, Send cleared it after the simulated save, and a new
draft enabled Send again. Storybook simulates submission; it is not
staging acceptance.
- Earlier verification on `f3253a00c4` recorded five browser journeys
for title saves, cached-task offline recovery, startup recovery,
accepted comment replay and session lookup failure. Those results remain
prior-head evidence. No new staging deployment is claimed.

- On `e8cf0e02dd`, all CI checks passed after one browser-shard rerun.
Its first failure copied page text instead of YAML in an unrelated
agent-configuration test. On final commit `35131d4380`, Greptile is 5/5
with no unresolved review threads. The first CI attempt has two failures
outside this diff: runner close-attachment suspension and
scheduled-retry teardown. The scheduled-retry file passes all 14 tests
in isolation; the isolated runner test still fails locally. The single
standard CI rerun passed both jobs, and the aggregate verification gate
passed. All CI checks are green on `35131d4380`; Apex is 5/5 on that
same commit with no unresolved findings.

## Risks

- Automatic replay requires server duplicate prevention or result
verification. Uncertain combined mutations require receipt observation
or cancel and a fresh intentional send.
- Old unowned form drafts remain stored but are not assigned to an
account. Unowned channel records can be retired after Activity
inspection; this never cancels an accepted remote update.
- Browser storage and hashing can be unavailable. Storage failure is
reported honestly. Without a digest, replay can duplicate an upload
rather than silently drop a selected file.
- Detached autosaves remain bounded and check account ownership on each
attempt. Conflicts or exhaustion retain the draft for explicit recovery.
- No schema, credential or agent permission change is included. This PR
does not claim staging deployment or original-task acceptance.

## Model Used

Anthropic Claude Opus 5.5 (`claude-opus-5-5`) produced the original
implementation with tool use. OpenAI Codex, GPT-6 family, assisted with
restoration, integration, verification and review fixes. This Codex
session does not expose its exact serving model ID or context window
size.

## 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
- [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: devinfoley <139239+devinfoley@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Amy (Opus) <claude@users.noreply.github.com>
Co-authored-by: Dotta <bippadotta@protonmail.com>
2026-10-28 10:52:06 -07:00

882 lines
36 KiB
TypeScript

import express from "express";
import request from "supertest";
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("../services/activity-log.js", () => ({
logActivity: vi.fn(async () => undefined),
publishActivity: vi.fn(),
}));
vi.mock("../services/fast-responses.js", () => ({
enqueueFastResponse: vi.fn(async () => undefined),
}));
const ASSIGNEE_AGENT_ID = "11111111-1111-4111-8111-111111111111";
const PREVIOUS_AGENT_ID = "22222222-2222-4222-8222-222222222222";
const MENTIONED_AGENT_ID = "33333333-3333-4333-8333-333333333333";
const SOURCE_RUN_ID = "44444444-4444-4444-8444-444444444444";
const mockIssueService = vi.hoisted(() => ({
getById: vi.fn(),
getByIdentifier: vi.fn(),
getByIdForUpdate: vi.fn(),
update: vi.fn(),
addComment: vi.fn(),
findMentionedAgents: vi.fn(),
getRelationSummaries: vi.fn(),
getDependencyReadiness: vi.fn(),
listWakeableBlockedDependents: vi.fn(),
getWakeableParentAfterChildCompletion: vi.fn(),
getCurrentScheduledRetry: vi.fn(),
listReviewAttention: vi.fn(),
}));
const mockPauseGate = vi.hoisted(() => vi.fn(async (): Promise<Record<string, unknown> | null> => null));
const mockExecutionBlocker = vi.hoisted(() => vi.fn(async (): Promise<Record<string, unknown> | null> => null));
vi.mock("../services/execution-blocker.js", () => ({ getExecutionBlocker: mockExecutionBlocker }));
const mockAccessDecide = vi.hoisted(() => vi.fn(async (input: { action?: string; resource?: { issueId?: string } }) => ({
allowed: true,
action: input.action,
reason: "allow_explicit_grant",
explanation: "Allowed by test grant.",
})));
const mockHeartbeatService = vi.hoisted(() => ({
wakeup: vi.fn(async () => undefined),
reportRunActivity: vi.fn(async () => undefined),
getRun: vi.fn(async () => null),
getActiveRunForAgent: vi.fn(async () => null),
cancelRun: vi.fn(async () => null),
}));
const mockIssueThreadInteractionService = vi.hoisted(() => ({
expirePendingInteractionsForTerminalIssue: vi.fn(async () => []),
expireRequestConfirmationsSupersededByComment: vi.fn(async () => []),
expireStaleRequestConfirmationsForIssueDocument: vi.fn(async () => []),
}));
const mockRunnerGoalService = vi.hoisted(() => ({
projection: vi.fn(async () => null),
act: vi.fn(),
}));
vi.mock("../services/native-runtime/native-question-bridge.js", () => ({
deliverNativeQuestionResponse: vi.fn(async () => "not_native"),
nativeQuestionRunToCancel: vi.fn(async () => null),
validateNativeQuestionResponseInput: vi.fn(),
}));
vi.mock("../services/runner-goals.js", () => ({
runnerGoalService: () => mockRunnerGoalService,
RunnerGoalActionError: class RunnerGoalActionError extends Error {},
RunnerGoalConflictError: class RunnerGoalConflictError extends Error {},
}));
vi.mock("../services/index.js", () => ({
companyService: () => ({
getById: vi.fn(async () => ({ id: "company-1" })),
}),
accessService: () => ({
canUser: vi.fn(async () => true),
decide: mockAccessDecide,
hasPermission: vi.fn(async () => true),
}),
agentService: () => ({
getById: vi.fn(async () => null),
resolveByReference: vi.fn(async (_companyId: string, raw: string) => ({
ambiguous: false,
agent: { id: raw },
})),
}),
companySkillService: () => ({
completeTestRunForIssue: vi.fn(async () => null),
}),
documentAnnotationService: () => ({ remapOpenThreadsForDocument: async () => [] }),
documentService: () => ({}),
executionWorkspaceService: () => ({}),
feedbackService: () => ({
listIssueVotesForUser: vi.fn(async () => []),
saveIssueVote: vi.fn(async () => ({ vote: null, consentEnabledNow: false, sharingEnabled: false })),
}),
goalService: () => ({}),
heartbeatService: () => mockHeartbeatService,
instanceSettingsService: () => ({
get: vi.fn(async () => ({
id: "instance-settings-1",
general: {
censorUsernameInLogs: false,
feedbackDataSharingPreference: "prompt",
},
})),
listCompanyIds: vi.fn(async () => ["company-1"]),
}),
issueApprovalService: () => ({}),
issueReferenceService: () => ({
deleteDocumentSource: async () => undefined,
diffIssueReferenceSummary: () => ({
addedReferencedIssues: [],
removedReferencedIssues: [],
currentReferencedIssues: [],
}),
emptySummary: () => ({ outbound: [], inbound: [] }),
listIssueReferenceSummary: async () => ({ outbound: [], inbound: [] }),
syncComment: async () => undefined,
syncDocument: async () => undefined,
syncIssue: async () => undefined,
}),
issueRecoveryActionService: () => ({
getActiveForIssue: vi.fn(async () => null),
listActiveForIssues: vi.fn(async () => new Map()),
}),
issueTreeControlService: () => ({ getActivePauseHoldGate: mockPauseGate }),
issueService: () => mockIssueService,
issueThreadInteractionService: () => mockIssueThreadInteractionService,
logActivity: vi.fn(async () => undefined),
projectService: () => ({}),
questionResponseDeliveryService: () => ({
deliver: vi.fn(async () => undefined),
}),
routineService: () => ({
syncRunStatusForIssue: vi.fn(async () => undefined),
}),
workProductService: () => ({}),
}));
function registerModuleMocks() {
vi.doMock("../services/external-objects.js", () => ({
externalObjectService: () => ({
syncCommentSafely: vi.fn(async () => undefined),
syncIssueSafely: vi.fn(async () => undefined),
}),
}));
vi.doMock("../services/index.js", () => ({
companyService: () => ({
getById: vi.fn(async () => ({ id: "company-1" })),
}),
accessService: () => ({
canUser: vi.fn(async () => true),
decide: mockAccessDecide,
hasPermission: vi.fn(async () => true),
}),
agentService: () => ({
getById: vi.fn(async () => null),
resolveByReference: vi.fn(async (_companyId: string, raw: string) => ({
ambiguous: false,
agent: { id: raw },
})),
}),
companySkillService: () => ({
completeTestRunForIssue: vi.fn(async () => null),
}),
documentAnnotationService: () => ({ remapOpenThreadsForDocument: async () => [] }),
documentService: () => ({}),
executionWorkspaceService: () => ({}),
feedbackService: () => ({
listIssueVotesForUser: vi.fn(async () => []),
saveIssueVote: vi.fn(async () => ({ vote: null, consentEnabledNow: false, sharingEnabled: false })),
}),
goalService: () => ({}),
heartbeatService: () => mockHeartbeatService,
instanceSettingsService: () => ({
get: vi.fn(async () => ({
id: "instance-settings-1",
general: {
censorUsernameInLogs: false,
feedbackDataSharingPreference: "prompt",
},
})),
listCompanyIds: vi.fn(async () => ["company-1"]),
}),
issueApprovalService: () => ({}),
issueReferenceService: () => ({
deleteDocumentSource: async () => undefined,
diffIssueReferenceSummary: () => ({
addedReferencedIssues: [],
removedReferencedIssues: [],
currentReferencedIssues: [],
}),
emptySummary: () => ({ outbound: [], inbound: [] }),
listIssueReferenceSummary: async () => ({ outbound: [], inbound: [] }),
syncComment: async () => undefined,
syncDocument: async () => undefined,
syncIssue: async () => undefined,
}),
issueRecoveryActionService: () => ({
getActiveForIssue: vi.fn(async () => null),
listActiveForIssues: vi.fn(async () => new Map()),
}),
issueTreeControlService: () => ({ getActivePauseHoldGate: mockPauseGate }),
issueService: () => mockIssueService,
issueThreadInteractionService: () => mockIssueThreadInteractionService,
logActivity: vi.fn(async () => undefined),
projectService: () => ({}),
questionResponseDeliveryService: () => ({
deliver: vi.fn(async () => undefined),
}),
routineService: () => ({
syncRunStatusForIssue: vi.fn(async () => undefined),
}),
workProductService: () => ({}),
}));
}
async function loadAppModules() {
return Promise.all([
vi.importActual<typeof import("../middleware/index.js")>("../middleware/index.js"),
vi.importActual<typeof import("../routes/issues.js")>("../routes/issues.js"),
]);
}
async function createApp(transaction: (callback: (tx: Record<string, never>) => Promise<unknown>) => Promise<unknown> =
async (callback) => callback({ select: () => ({ from: () => ({ where: () => Object.assign(Promise.resolve([]), { for: async () => [{ id: "comment-3" }] }) }) }) } as any)) {
const [{ errorHandler }, { issueRoutes }] = await loadAppModules();
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
(req as any).actor = {
type: "board",
userId: "local-board",
companyIds: ["company-1"],
source: "local_implicit",
runId: req.header("x-paperclip-run-id") ?? null,
isInstanceAdmin: false,
};
next();
});
app.use("/api", issueRoutes({
transaction,
select: () => ({ from: () => ({ where: async () => [] }) }),
} as any, {} as any));
app.use(errorHandler);
return app;
}
function makeIssue(overrides: Record<string, unknown> = {}) {
return {
id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
companyId: "company-1",
status: "todo",
priority: "medium",
projectId: null,
goalId: null,
parentId: null,
assigneeAgentId: null,
assigneeUserId: "local-board",
createdByUserId: "local-board",
identifier: "PAP-999",
title: "Wake test",
executionPolicy: null,
executionState: null,
hiddenAt: null,
...overrides,
};
}
describe("issue update comment wakeups", () => {
beforeAll(async () => {
vi.resetModules();
vi.doUnmock("../routes/issues.js");
vi.doUnmock("../routes/authz.js");
vi.doUnmock("../middleware/index.js");
registerModuleMocks();
await loadAppModules();
});
beforeEach(() => {
vi.resetAllMocks();
mockAccessDecide.mockImplementation(async (input) => ({ allowed: true, action: input.action, reason: "allow_explicit_grant", explanation: "Allowed by test grant." }));
mockPauseGate.mockResolvedValue(null);
mockExecutionBlocker.mockResolvedValue(null);
mockIssueService.findMentionedAgents.mockResolvedValue([]);
mockIssueService.getByIdentifier.mockResolvedValue(null);
mockIssueService.getByIdForUpdate.mockImplementation(async () => mockIssueService.getById());
mockIssueService.getRelationSummaries.mockResolvedValue({ blockedBy: [], blocks: [] });
mockIssueService.getDependencyReadiness.mockResolvedValue({ unresolvedBlockerCount: 1 });
mockIssueService.listWakeableBlockedDependents.mockResolvedValue([]);
mockIssueService.getWakeableParentAfterChildCompletion.mockResolvedValue(null);
mockIssueService.getCurrentScheduledRetry.mockResolvedValue(null);
mockIssueService.listReviewAttention.mockResolvedValue(new Map());
});
it.each(["post", "patch"] as const)("rejects %s board messages under an inherited pause before any mutation", async (method) => {
const existing = makeIssue();
mockIssueService.getById.mockResolvedValue(existing);
mockPauseGate.mockResolvedValue({ holdId: "hold-1", rootIssueId: "parent-1" });
const app = await createApp();
const res = method === "post"
? await request(app).post(`/api/issues/${existing.id}/comments`).send({ body: "go", reopen: true, interrupt: true })
: await request(app).patch(`/api/issues/${existing.id}`).send({ comment: "go", assigneeAgentId: ASSIGNEE_AGENT_ID, status: "todo" });
expect(res.status).toBe(409);
expect(res.body.error).toBe("Task is paused. Resume it before sending a message.");
expect(res.body.details.rootIssueId).toBe("parent-1");
expect(mockPauseGate).toHaveBeenCalledWith(existing.companyId, existing.id);
expect(mockIssueService.addComment).not.toHaveBeenCalled();
expect(mockIssueService.update).not.toHaveBeenCalled();
expect(mockHeartbeatService.wakeup).not.toHaveBeenCalled();
});
it.each(["done", "cancelled"])(
"keeps %s assignment-only updates from waking completed work",
async (status) => {
// A parent may restore the assignee after releasing a completed child.
// That is recordkeeping, not a request to execute the child again.
const existing = makeIssue({ status, assigneeAgentId: null, assigneeUserId: null });
const updated = makeIssue({ status, assigneeAgentId: ASSIGNEE_AGENT_ID, assigneeUserId: null });
mockIssueService.getById.mockResolvedValue(existing);
mockIssueService.update.mockResolvedValue(updated);
const res = await request(await createApp())
.patch(`/api/issues/${existing.id}`)
.send({ assigneeAgentId: ASSIGNEE_AGENT_ID });
expect(res.status).toBe(200);
expect(res.body).toMatchObject({ status, assigneeAgentId: ASSIGNEE_AGENT_ID });
await new Promise((resolve) => setImmediate(resolve));
expect(mockHeartbeatService.wakeup).not.toHaveBeenCalled();
},
);
it.each([false, true])("still wakes explicitly reopened work (reassigned: %s)", async (reassigned) => {
const existing = makeIssue({ status: "done", assigneeAgentId: PREVIOUS_AGENT_ID, assigneeUserId: null });
const agentId = reassigned ? ASSIGNEE_AGENT_ID : PREVIOUS_AGENT_ID;
mockIssueService.getById.mockResolvedValue(existing);
mockIssueService.update.mockResolvedValue(makeIssue({ status: "todo", assigneeAgentId: agentId, assigneeUserId: null }));
const res = await request(await createApp())
.patch(`/api/issues/${existing.id}`)
.send({ status: "todo", ...(reassigned ? { assigneeAgentId: agentId } : {}) });
expect(res.status).toBe(200);
await vi.waitFor(() => expect(mockHeartbeatService.wakeup).toHaveBeenCalledTimes(1));
expect(mockHeartbeatService.wakeup).toHaveBeenCalledWith(agentId, expect.objectContaining({
reason: reassigned ? "issue_assigned" : "issue_status_changed",
payload: expect.objectContaining({ issueId: existing.id }),
}));
});
it.each([null, "active"] as const)("includes the new comment and shared session key in assignment wakes (external: %s)", async (externalConversationState) => {
const existing = makeIssue({ externalConversationState });
const updated = makeIssue({
externalConversationState,
assigneeAgentId: ASSIGNEE_AGENT_ID,
assigneeUserId: null,
assigneeAdapterOverrides: { adapterConfig: { model: "gpt-6-astra", modelReasoningEffort: "ultra", fastMode: true } },
});
mockIssueService.getById.mockResolvedValue(existing);
mockIssueService.update.mockResolvedValue(updated);
mockIssueService.addComment.mockResolvedValue({
id: "comment-1",
issueId: existing.id,
companyId: existing.companyId,
body: "write the whole thing",
});
const res = await request(await createApp())
.patch(`/api/issues/${existing.id}`)
.send({
assigneeAgentId: ASSIGNEE_AGENT_ID,
assigneeUserId: null,
comment: "write the whole thing",
commentClientRequestId: "55555555-5555-4555-8555-555555555555",
assigneeAdapterOverrides: updated.assigneeAdapterOverrides,
});
expect(res.status).toBe(200);
expect(mockIssueService.update).toHaveBeenCalledWith(existing.id, expect.objectContaining({
assigneeAdapterOverrides: updated.assigneeAdapterOverrides,
}), expect.anything());
expect(mockIssueService.addComment).toHaveBeenCalledWith(existing.id, "write the whole thing", expect.anything(),
expect.objectContaining({ clientRequestId: "55555555-5555-4555-8555-555555555555" }), expect.anything());
expect(mockIssueService.update.mock.calls[0]?.[2]).toBe(mockIssueService.addComment.mock.calls[0]?.[4]);
// The route dispatches the wake after it sends the response, so wait for
// the fire-and-forget dispatch to settle. This keeps the wake inside this
// test and stops it from leaking into the next test as an extra call.
await vi.waitFor(() => expect(mockHeartbeatService.wakeup).toHaveBeenCalledTimes(1));
expect(mockHeartbeatService.wakeup).toHaveBeenCalledWith(
ASSIGNEE_AGENT_ID,
expect.objectContaining({
source: "assignment",
reason: "issue_assigned",
payload: expect.objectContaining({
issueId: existing.id,
commentId: "comment-1",
mutation: "update",
}),
contextSnapshot: expect.objectContaining({
issueId: existing.id,
taskId: existing.id,
commentId: "comment-1",
wakeCommentId: "comment-1",
...(externalConversationState ? { taskKey: existing.identifier } : {}),
source: "issue.update",
}),
}),
);
});
it("rolls back adapter settings if the accompanying comment fails", async () => {
const existing = makeIssue({ assigneeAgentId: ASSIGNEE_AGENT_ID, assigneeUserId: null });
let persistedModel = "gpt-6-sol";
mockIssueService.getById.mockResolvedValue(existing);
mockIssueService.update.mockImplementation(async (_id, fields) => {
persistedModel = fields.assigneeAdapterOverrides.adapterConfig.model;
return { ...existing, ...fields };
});
mockIssueService.addComment.mockRejectedValue(new Error("comment write failed"));
const transaction = vi.fn(async (callback: (tx: Record<string, never>) => Promise<unknown>) => {
const previousModel = persistedModel;
try {
return await callback({});
} catch (error) {
persistedModel = previousModel;
throw error;
}
});
const res = await request(await createApp(transaction))
.patch(`/api/issues/${existing.id}`)
.send({ comment: "use Astra", assigneeAdapterOverrides: { adapterConfig: { model: "gpt-6-astra" } } });
expect(res.status).toBe(500);
expect(transaction).toHaveBeenCalledOnce();
expect(persistedModel).toBe("gpt-6-sol");
expect(mockHeartbeatService.wakeup).not.toHaveBeenCalled();
});
it("interrupts the active run and wakes the newly assigned agent with handoff context", async () => {
const existing = makeIssue({
assigneeAgentId: PREVIOUS_AGENT_ID,
assigneeUserId: null,
executionRunId: "run-1",
status: "in_progress",
});
const updated = makeIssue({
assigneeAgentId: ASSIGNEE_AGENT_ID,
assigneeUserId: null,
executionRunId: "run-1",
status: "in_progress",
});
mockIssueService.getById.mockResolvedValue(existing);
mockIssueService.update.mockResolvedValue(updated);
mockIssueService.addComment.mockResolvedValue({
id: "comment-interrupt-agent",
issueId: existing.id,
companyId: existing.companyId,
body: "stop and hand this to CodexCoder",
});
mockHeartbeatService.getRun.mockResolvedValue({
id: "run-1",
companyId: existing.companyId,
agentId: PREVIOUS_AGENT_ID,
status: "running",
contextSnapshot: { issueId: existing.id },
});
mockHeartbeatService.cancelRun.mockResolvedValue({
id: "run-1",
companyId: existing.companyId,
agentId: PREVIOUS_AGENT_ID,
status: "cancelled",
});
const res = await request(await createApp())
.patch(`/api/issues/${existing.id}`)
.send({
assigneeAgentId: ASSIGNEE_AGENT_ID,
assigneeUserId: null,
comment: "stop and hand this to CodexCoder",
interrupt: true,
});
expect(res.status).toBe(200);
expect(mockHeartbeatService.cancelRun).toHaveBeenCalledWith(
"run-1",
"Interrupted by board comment",
expect.objectContaining({
errorCode: "operator_interrupted",
resultJson: expect.objectContaining({
operatorInterrupted: true,
interruptionSource: "issue_comment_interrupt",
interruptedIssueId: existing.id,
}),
eventMessage: "run interrupted by board comment",
eventPayload: expect.objectContaining({
issueId: existing.id,
source: "issue_comment_interrupt",
}),
}),
);
await vi.waitFor(() => expect(mockHeartbeatService.wakeup).toHaveBeenCalledTimes(1));
expect(mockHeartbeatService.wakeup).toHaveBeenCalledWith(
ASSIGNEE_AGENT_ID,
expect.objectContaining({
source: "assignment",
reason: "issue_assigned",
payload: expect.objectContaining({
issueId: existing.id,
commentId: "comment-interrupt-agent",
interruptedRunId: "run-1",
mutation: "update",
}),
contextSnapshot: expect.objectContaining({
issueId: existing.id,
taskId: existing.id,
commentId: "comment-interrupt-agent",
wakeCommentId: "comment-interrupt-agent",
interruptedRunId: "run-1",
source: "issue.update",
}),
}),
);
});
it("interrupts the active run without waking an agent when the handoff assigns a user", async () => {
const existing = makeIssue({
assigneeAgentId: PREVIOUS_AGENT_ID,
assigneeUserId: null,
executionRunId: "run-2",
status: "in_progress",
});
const updated = makeIssue({
assigneeAgentId: null,
assigneeUserId: "local-board",
executionRunId: "run-2",
status: "in_progress",
});
mockIssueService.getById.mockResolvedValue(existing);
mockIssueService.update.mockResolvedValue(updated);
mockIssueService.addComment.mockResolvedValue({
id: "comment-interrupt-user",
issueId: existing.id,
companyId: existing.companyId,
body: "stop here, I will take it",
});
mockHeartbeatService.getRun.mockResolvedValue({
id: "run-2",
companyId: existing.companyId,
agentId: PREVIOUS_AGENT_ID,
status: "running",
contextSnapshot: { issueId: existing.id },
});
mockHeartbeatService.cancelRun.mockResolvedValue({
id: "run-2",
companyId: existing.companyId,
agentId: PREVIOUS_AGENT_ID,
status: "cancelled",
});
const res = await request(await createApp())
.patch(`/api/issues/${existing.id}`)
.send({
assigneeAgentId: null,
assigneeUserId: "local-board",
comment: "stop here, I will take it",
interrupt: true,
});
expect(res.status).toBe(200);
expect(mockHeartbeatService.cancelRun).toHaveBeenCalledWith(
"run-2",
"Interrupted by board comment",
expect.objectContaining({
errorCode: "operator_interrupted",
resultJson: expect.objectContaining({
operatorInterrupted: true,
interruptionSource: "issue_comment_interrupt",
interruptedIssueId: existing.id,
}),
eventMessage: "run interrupted by board comment",
}),
);
await new Promise<void>((resolve) => setImmediate(resolve));
expect(mockHeartbeatService.wakeup).not.toHaveBeenCalled();
});
it("defers the assignment wake when a structured goal owns the next run", async () => {
const existing = makeIssue({ assigneeAgentId: null, assigneeUserId: null, status: "todo" });
mockIssueService.getById.mockResolvedValue(existing);
mockIssueService.update.mockResolvedValue(makeIssue({ assigneeAgentId: ASSIGNEE_AGENT_ID, status: "todo" }));
const res = await request(await createApp()).patch(`/api/issues/${existing.id}`).send({
assigneeAgentId: ASSIGNEE_AGENT_ID, assigneeUserId: null, deferWakeForGoal: true,
});
expect(res.status).toBe(200);
expect(mockIssueService.update).toHaveBeenCalled();
expect(mockIssueService.addComment).not.toHaveBeenCalled();
expect(mockHeartbeatService.wakeup).not.toHaveBeenCalled();
});
it("does not allow goal wake deferral to suppress an unrelated status change", async () => {
const existing = makeIssue({ assigneeAgentId: ASSIGNEE_AGENT_ID, status: "todo" });
mockIssueService.getById.mockResolvedValue(existing);
const res = await request(await createApp()).patch(`/api/issues/${existing.id}`).send({
assigneeAgentId: ASSIGNEE_AGENT_ID, status: "in_progress", deferWakeForGoal: true,
});
expect(res.status).toBe(400);
expect(mockIssueService.update).not.toHaveBeenCalled();
});
it("wakes the assignee on comment-only issue updates", async () => {
const existing = makeIssue({
assigneeAgentId: ASSIGNEE_AGENT_ID,
assigneeUserId: null,
status: "in_progress",
});
const updated = { ...existing };
mockIssueService.getById.mockResolvedValue(existing);
mockIssueService.update.mockResolvedValue(updated);
mockIssueService.addComment.mockResolvedValue({
id: "comment-2",
issueId: existing.id,
companyId: existing.companyId,
body: "please revise this",
});
const res = await request(await createApp())
.patch(`/api/issues/${existing.id}`)
.send({
comment: "please revise this",
});
expect(res.status).toBe(200);
expect(mockHeartbeatService.wakeup).toHaveBeenCalledTimes(1);
expect(mockHeartbeatService.wakeup).toHaveBeenCalledWith(
ASSIGNEE_AGENT_ID,
expect.objectContaining({
source: "automation",
reason: "issue_commented",
payload: expect.objectContaining({
issueId: existing.id,
commentId: "comment-2",
mutation: "comment",
}),
contextSnapshot: expect.objectContaining({
issueId: existing.id,
taskId: existing.id,
commentId: "comment-2",
wakeCommentId: "comment-2",
wakeReason: "issue_commented",
source: "issue.comment",
}),
}),
);
});
it.each([null, "active"] as const)("wakes the assignee on top-level board comments with external conversation %s", async (externalConversationState) => {
const existing = makeIssue({
externalConversationState,
assigneeAgentId: ASSIGNEE_AGENT_ID,
assigneeUserId: null,
status: "in_progress",
});
mockIssueService.getById.mockResolvedValue(existing);
mockIssueService.addComment.mockResolvedValue({
id: "comment-3",
issueId: existing.id,
companyId: existing.companyId,
body: "please handle this top-level thread comment",
});
const res = await request(await createApp())
.post(`/api/issues/${existing.id}/comments`)
.send({
body: "please handle this top-level thread comment",
clientRequestId: "66666666-6666-4666-8666-666666666666",
});
expect(res.status).toBe(201);
if (externalConversationState) expect(mockRunnerGoalService.projection).not.toHaveBeenCalled();
expect(mockIssueService.addComment).toHaveBeenCalledWith(existing.id, "please handle this top-level thread comment", expect.anything(),
expect.objectContaining({ clientRequestId: "66666666-6666-4666-8666-666666666666", mirrorToSlack: true }), expect.anything());
await vi.waitFor(() => expect(mockHeartbeatService.wakeup).toHaveBeenCalledTimes(1));
expect(mockHeartbeatService.wakeup).toHaveBeenCalledWith(
ASSIGNEE_AGENT_ID,
expect.objectContaining({
source: "automation",
reason: "issue_commented",
payload: expect.objectContaining({
issueId: existing.id,
commentId: "comment-3",
mutation: "comment",
}),
contextSnapshot: expect.objectContaining({
issueId: existing.id,
taskId: existing.id,
commentId: "comment-3",
wakeCommentId: "comment-3",
...(externalConversationState ? { taskKey: existing.identifier } : {}),
wakeReason: "issue_commented",
source: "issue.comment",
}),
}),
);
});
it("retains the Slack session key when reopening strips the read-only conversation projection", async () => {
const existing = makeIssue({ externalConversationState: "active", status: "done", assigneeAgentId: ASSIGNEE_AGENT_ID });
const updated = makeIssue({ status: "todo", assigneeAgentId: ASSIGNEE_AGENT_ID });
mockIssueService.getById.mockResolvedValue(existing);
mockIssueService.update.mockResolvedValue(updated);
mockIssueService.addComment.mockResolvedValue({ id: "comment-reopen-slack", issueId: existing.id, companyId: existing.companyId, body: "Continue from Paperclip" });
const res = await request(await createApp()).post(`/api/issues/${existing.id}/comments`).send({ body: "Continue from Paperclip", reopen: true });
expect(res.status).toBe(201);
await vi.waitFor(() => expect(mockHeartbeatService.wakeup).toHaveBeenCalledTimes(1));
expect(mockHeartbeatService.wakeup).toHaveBeenCalledWith(ASSIGNEE_AGENT_ID, expect.objectContaining({
contextSnapshot: expect.objectContaining({ source: "issue.comment.reopen", taskKey: existing.identifier, wakeCommentId: "comment-reopen-slack" }),
}));
});
it.each(["post", "patch"] as const)("saves a %s comment without promoting a workspace-held task to Todo", async method => {
const existing = makeIssue({ status: "blocked", assigneeAgentId: ASSIGNEE_AGENT_ID, assigneeUserId: null });
mockIssueService.getById.mockResolvedValue(existing);
mockIssueService.update.mockResolvedValue(existing);
mockIssueService.addComment.mockResolvedValue({ id: "saved-comment", issueId: existing.id, companyId: existing.companyId, body: "Continue after recovery." });
mockExecutionBlocker.mockResolvedValue({ workspaceRepairRequired: true });
const app = await createApp();
const res = method === "post"
? await request(app).post(`/api/issues/${existing.id}/comments`).send({ body: "Continue after recovery." })
: await request(app).patch(`/api/issues/${existing.id}`).send({ comment: "Continue after recovery." });
expect(res.status).toBe(method === "post" ? 201 : 200);
expect(mockIssueService.addComment).toHaveBeenCalledOnce();
expect(mockIssueService.update.mock.calls.every(([, patch]) => patch.status !== "todo")).toBe(true);
expect(mockExecutionBlocker).toHaveBeenCalled();
});
it.each((["post", "patch"] as const).flatMap((method) =>
["assignee_comment", "board_comment", "human_owned", "unassigned", "blocked_parent", "done_parent", "done_comment", ...(method === "patch" ? ["closing_comment"] : [])].map((scenario) => ({ method, scenario })),
))("keeps $method mentions as context for $scenario", async ({ method, scenario }) => {
const selfComment = ["assignee_comment", "blocked_parent", "done_parent", "done_comment", "closing_comment"].includes(scenario);
const existing = makeIssue({
assigneeAgentId: ["human_owned", "unassigned"].includes(scenario) ? null : ASSIGNEE_AGENT_ID,
assigneeUserId: scenario === "human_owned" ? "local-board" : null,
status: scenario === "blocked_parent" ? "blocked" : ["done_parent", "done_comment"].includes(scenario) ? "done" : "in_progress",
executionRunId: selfComment ? SOURCE_RUN_ID : null,
});
const child = makeIssue({
id: "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", identifier: "PAP-1000", parentId: existing.id,
assigneeAgentId: MENTIONED_AGENT_ID, assigneeUserId: null,
status: scenario === "done_parent" ? "done" : "in_progress",
executionRunId: "55555555-5555-4555-8555-555555555555",
});
const body = ["blocked_parent", "done_parent"].includes(scenario)
? `[@QA](agent://${MENTIONED_AGENT_ID}) is relevant; see [${child.identifier}](/PAP/issues/${child.identifier}).`
: `Finished the task. [@QA](agent://${MENTIONED_AGENT_ID}) has relevant context.`;
const originalComment = {
id: "context-note", issueId: existing.id, companyId: existing.companyId, body,
createdByRunId: selfComment ? SOURCE_RUN_ID : null,
};
mockIssueService.getById.mockImplementation(async (id) => id === child.id ? child : existing);
mockIssueService.getByIdentifier.mockResolvedValue(child);
mockIssueService.update.mockResolvedValue(scenario === "closing_comment" ? { ...existing, status: "done" } : existing);
mockIssueService.addComment.mockResolvedValue(originalComment);
mockIssueService.findMentionedAgents.mockResolvedValue([MENTIONED_AGENT_ID]);
mockIssueService.getRelationSummaries.mockResolvedValue({ blockedBy: [child], blocks: [] });
mockHeartbeatService.getRun.mockImplementation(async (id) => ({
id, companyId: existing.companyId, status: "running",
agentId: id === SOURCE_RUN_ID ? ASSIGNEE_AGENT_ID : MENTIONED_AGENT_ID,
contextSnapshot: { issueId: id === SOURCE_RUN_ID ? existing.id : child.id },
}));
const app = await createApp();
const req = method === "post"
? request(app).post(`/api/issues/${existing.id}/comments`)
: request(app).patch(`/api/issues/${existing.id}`);
if (selfComment) req.set("X-Paperclip-Run-Id", SOURCE_RUN_ID);
const res = await req.send(method === "post" ? { body } : { comment: body, ...(scenario === "closing_comment" ? { status: "done" } : {}) });
expect(res.status).toBe(method === "post" ? 201 : 200);
// Wake scheduling runs after sending the response. Drain its resolved
// mock promises before asserting that no extra work was dispatched.
await new Promise<void>((resolve) => setImmediate(resolve));
expect(mockIssueService.addComment).toHaveBeenCalledTimes(1);
expect(mockIssueService.addComment.mock.calls[0].slice(0, 2)).toEqual([existing.id, body]);
expect(mockHeartbeatService.wakeup).toHaveBeenCalledTimes(scenario === "board_comment" ? 1 : 0);
if (scenario === "board_comment") {
expect(mockHeartbeatService.wakeup).toHaveBeenCalledWith(ASSIGNEE_AGENT_ID, expect.objectContaining({
reason: "issue_commented", contextSnapshot: expect.objectContaining({ issueId: existing.id }),
}));
}
expect(mockIssueService.update.mock.calls.every(([id]) => id === existing.id)).toBe(true);
});
it("preserves an explicit resume on a run-authenticated top-level comment", async () => {
const existing = makeIssue({
assigneeAgentId: ASSIGNEE_AGENT_ID,
assigneeUserId: null,
status: "in_progress",
});
mockIssueService.getById.mockResolvedValue(existing);
mockIssueService.addComment.mockResolvedValue({
id: "comment-self-resume",
issueId: existing.id,
companyId: existing.companyId,
body: "Resume intentionally.",
createdByRunId: SOURCE_RUN_ID,
});
mockHeartbeatService.getRun.mockResolvedValue({
id: SOURCE_RUN_ID,
companyId: existing.companyId,
agentId: ASSIGNEE_AGENT_ID,
status: "succeeded",
});
const res = await request(await createApp())
.post(`/api/issues/${existing.id}/comments`)
.set("X-Paperclip-Run-Id", SOURCE_RUN_ID)
.send({ body: "Resume intentionally.", resume: true });
expect(res.status).toBe(201);
await vi.waitFor(() => expect(mockHeartbeatService.wakeup).toHaveBeenCalledTimes(1));
expect(mockHeartbeatService.wakeup).toHaveBeenCalledWith(
ASSIGNEE_AGENT_ID,
expect.objectContaining({
reason: "issue_commented",
contextSnapshot: expect.objectContaining({
resumeIntent: true,
}),
}),
);
});
it("tags the wake when a board comment supersedes the last review interaction", async () => {
const existing = makeIssue({
assigneeAgentId: ASSIGNEE_AGENT_ID,
assigneeUserId: null,
status: "in_review",
});
mockIssueService.getById.mockResolvedValue(existing);
mockIssueService.addComment.mockResolvedValue({
id: "comment-review-path",
issueId: existing.id,
companyId: existing.companyId,
body: "one more review note",
});
mockIssueThreadInteractionService.expireRequestConfirmationsSupersededByComment.mockResolvedValue([{
id: "interaction-review-path",
kind: "request_confirmation",
status: "expired",
}]);
mockIssueService.listReviewAttention.mockResolvedValue(new Map([[
existing.id,
{ state: "stalled", paths: [], reason: "review path consumed" },
]]));
const res = await request(await createApp())
.post(`/api/issues/${existing.id}/comments`)
.send({ body: "one more review note" });
expect(res.status).toBe(201);
await vi.waitFor(() => expect(mockHeartbeatService.wakeup).toHaveBeenCalledTimes(1));
expect(mockHeartbeatService.wakeup).toHaveBeenCalledWith(
ASSIGNEE_AGENT_ID,
expect.objectContaining({
payload: expect.objectContaining({
reviewPathLost: true,
reviewPathConsumedRef: "interaction-review-path",
reviewPathInstruction: expect.stringContaining("Restore a reviewer"),
}),
contextSnapshot: expect.objectContaining({
reviewPathLost: true,
reviewPathConsumedRef: "interaction-review-path",
}),
}),
);
});
});