Files
PaperClipAI/server/src/__tests__/issue-onboarding-first-task-routes.test.ts
T
DottaandClaude Opus 5.5 02898b98de fix(issues): do not wake the assignee for an issue created already closed (#19961)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Creating an issue with an agent assignee queues an `issue_assigned`
wake for that agent
> - The create path skips the wake only for `backlog` and the onboarding
first task
> - An issue created already `done` or `cancelled` is a record of
finished work, but it still wakes the assignee
> - The update path already refuses this case ("Restoring an assignee on
completed work is not a reopen request"), and create-time fast responses
already skip `done` and `cancelled`
> - This pull request applies the same closed-status guard to the
create-time assignment wake
> - The benefit is that recording finished work does not start a run,
spend tokens, or queue behind the agent's current work

## Linked Issues or Issue Description

**What happened**

In a chat eval, setup created a historical issue with `status: "done"`
assigned to an agent that was already running a task. The create queued
a second run for that agent (`invocationSource: assignment`,
`wakeReason: issue_assigned`, `source: issue.create`). The run waited
behind the active run, and then was cancelled or failed. The eval
expected no work for a finished record.

**Expected behavior**

Creating an issue that is already `done` or `cancelled` does not wake
its assignee. This matches the update path, where an assignee change on
closed work is not a reopen request.

**Steps to reproduce**

1. Create an agent.
2. `POST /api/companies/<companyId>/issues` with
`{"title":"Record","status":"done","assigneeAgentId":"<agentId>"}`.
3. See a new `agent_wakeup_requests` row and a queued heartbeat run for
the agent.

## What Changed

- `server/src/routes/issues.ts`: the create route does not call
`queueIssueAssignmentWakeup` when the created issue status is `done` or
`cancelled` (`isClosedIssueStatus`).
- `server/src/__tests__/issue-onboarding-first-task-routes.test.ts`: a
regression test for `done` and `cancelled` creates. The existing test
that an ordinary assigned create still wakes is unchanged.

## Verification

- `cd server && pnpm exec vitest run
src/__tests__/issue-onboarding-first-task-routes.test.ts`: 11 passed.
- Negative control: with the route file from `origin/master`, both new
cases fail.

## Risks

- Low risk. Only creates in a closed status change. A caller that relied
on a create-time wake for a closed issue no longer gets one. To start
work, the caller creates the issue in an open status or reopens it,
which still wakes the assignee.

## Model Used

- Anthropic Claude Opus 5.5 (`claude-opus-5-5`), tool use and code
execution in Claude Code.

## 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>
2026-11-08 00:52:22 -06:00

384 lines
14 KiB
TypeScript

import { randomUUID } from "node:crypto";
import express from "express";
import request from "supertest";
import { and, eq } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import {
costEvents,
activityLog,
agentRuntimeState,
agents,
agentWakeupRequests,
companies,
companySkills,
createDb,
heartbeatRunEvents,
heartbeatRuns,
instanceSettings,
issueComments,
issueThreadInteractions,
issues,
} from "@paperclipai/db";
import { ONBOARDING_FIRST_TASK_ORIGIN_KIND } from "@paperclipai/shared";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
import { actorMiddleware } from "../middleware/auth.js";
import { errorHandler } from "../middleware/index.js";
import { runningProcesses } from "../adapters/index.ts";
import { issueRoutes } from "../routes/issues.js";
import { heartbeatService } from "../services/heartbeat.js";
import { drainHeartbeatRunsToQuiescence } from "./helpers/drain-heartbeat-runs.js";
// The issue-create route dispatches an assignment wake fire-and-forget for an
// assigned agent. The wake dispatches a heartbeat run that calls the server
// adapter. Stub the adapter so the run finishes at once and does not start a
// real agent session. The stub keeps the wake path realistic and fast, so the
// afterEach drain reaches quiescence without a long real run.
const mockAdapterExecute = vi.hoisted(() =>
vi.fn(async () => ({
exitCode: 0,
signal: null,
timedOut: false,
errorMessage: null,
summary: "Onboarding first-task route test run.",
provider: "test",
model: "test-model",
})),
);
vi.mock("../adapters/index.ts", async () => {
const actual = await vi.importActual<typeof import("../adapters/index.ts")>("../adapters/index.ts");
return {
...actual,
getServerAdapter: vi.fn(() => ({
supportsLocalAgentJwt: false,
execute: mockAdapterExecute,
})),
};
});
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
if (!embeddedPostgresSupport.supported) {
console.warn(
`Skipping embedded Postgres onboarding first-task route tests on this host: ${
embeddedPostgresSupport.reason ?? "unsupported environment"
}`,
);
}
describeEmbeddedPostgres("issue create onboarding first-task routes", () => {
let db!: ReturnType<typeof createDb>;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
beforeAll(async () => {
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-issue-onboarding-first-task-routes-");
db = createDb(tempDb.connectionString);
}, 20_000);
afterEach(async () => {
// Wait for the background assignment wake to reach quiescence before the
// deletes. The wake inserts agent_wakeup_requests and heartbeat_runs rows
// asynchronously, and a late row races the teardown deletes. The module
// global promise sets in heartbeat.ts are shared, so a fresh heartbeatService
// drains the route wake that this suite started.
mockAdapterExecute.mockClear();
runningProcesses.clear();
await drainHeartbeatRunsToQuiescence(db, heartbeatService(db));
// Delete heartbeat_runs and its child rows before agents and
// agent_wakeup_requests. heartbeat_runs references both, so a completed run
// row blocks a parent delete with a foreign-key violation.
await db.delete(activityLog);
await db.delete(issueThreadInteractions);
await db.delete(issueComments);
await db.delete(heartbeatRunEvents);
await db.delete(costEvents);
await db.delete(heartbeatRuns);
await db.delete(agentWakeupRequests);
await db.delete(agentRuntimeState);
await db.delete(issues);
await db.delete(agents);
await db.delete(companySkills);
await db.delete(companies);
await db.delete(instanceSettings);
});
afterAll(async () => {
await tempDb?.cleanup();
});
function createApp() {
const app = express();
app.use(express.json());
app.use(actorMiddleware(db, { deploymentMode: "local_trusted" }));
app.use("/api", issueRoutes(db, {} as any));
app.use(errorHandler);
return app;
}
async function seedCompany() {
const companyId = randomUUID();
await db.insert(companies).values({
id: companyId,
name: "Paperclip",
issuePrefix: `D${companyId.replace(/-/g, "").slice(0, 5).toUpperCase()}`,
requireBoardApprovalForNewAgents: false,
});
return companyId;
}
async function seedAgent(companyId: string) {
const agentId = randomUUID();
await db.insert(agents).values({
id: agentId,
companyId,
name: "CEO",
role: "engineer",
status: "running",
adapterType: "codex_local",
adapterConfig: {},
runtimeConfig: {},
permissions: {},
});
return agentId;
}
function listOnboardingIssues(companyId: string) {
return db
.select()
.from(issues)
.where(and(
eq(issues.companyId, companyId),
eq(issues.originKind, ONBOARDING_FIRST_TASK_ORIGIN_KIND),
));
}
it("stamps the onboarding origin and seeds the agent-attributed greeting on the first task", async () => {
const companyId = await seedCompany();
const agentId = await seedAgent(companyId);
const app = createApp();
const created = await request(app)
.post(`/api/companies/${companyId}/issues`)
.send({ title: "Get started", onboardingFirstTask: true, assigneeAgentId: agentId })
.expect(201);
expect(created.body.originKind).toBe(ONBOARDING_FIRST_TASK_ORIGIN_KIND);
const comments = await db
.select()
.from(issueComments)
.where(eq(issueComments.issueId, created.body.id));
expect(comments).toHaveLength(1);
expect(comments[0]).toMatchObject({ authorType: "agent", authorAgentId: agentId });
});
it("seeds the two-option opening question card as the assignee on the first task", async () => {
const companyId = await seedCompany();
const agentId = await seedAgent(companyId);
const app = createApp();
const created = await request(app)
.post(`/api/companies/${companyId}/issues`)
.send({ title: "Get started", onboardingFirstTask: true, assigneeAgentId: agentId })
.expect(201);
const interactions = await db
.select()
.from(issueThreadInteractions)
.where(eq(issueThreadInteractions.issueId, created.body.id));
expect(interactions).toHaveLength(1);
expect(interactions[0]).toMatchObject({
kind: "ask_user_questions",
status: "pending",
createdByAgentId: agentId,
createdByUserId: null,
continuationPolicy: "wake_assignee",
});
const payload = interactions[0].payload as {
supersedeOnUserComment?: boolean;
questions: Array<{ selectionMode: string; options: Array<{ id: string; label: string; freeText?: boolean }> }>;
};
expect(payload.supersedeOnUserComment).toBe(true);
expect(payload.questions).toHaveLength(1);
expect(payload.questions[0].selectionMode).toBe("single");
expect(payload.questions[0].options.map((option) => option.id)).toEqual(["interview", "task"]);
expect(payload.questions[0].options[0].label).toBe(
"Interview me and propose a plan and an agent team to execute it.",
);
expect(payload.questions[0].options[1]).toMatchObject({ label: "I have a task in mind", freeText: true });
// The seeded card is read-only for the thread until the user answers: it
// must not have queued a run by itself.
await drainHeartbeatRunsToQuiescence(db, heartbeatService(db));
expect(mockAdapterExecute).not.toHaveBeenCalled();
});
it("does not seed the opening card on an unassigned onboarding first task", async () => {
const companyId = await seedCompany();
const app = createApp();
const created = await request(app)
.post(`/api/companies/${companyId}/issues`)
.send({ title: "Get started", onboardingFirstTask: true })
.expect(201);
const interactions = await db
.select()
.from(issueThreadInteractions)
.where(eq(issueThreadInteractions.issueId, created.body.id));
expect(interactions).toHaveLength(0);
});
it("fails closed to an ordinary issue when the onboarding origin is already claimed", async () => {
const companyId = await seedCompany();
const agentId = await seedAgent(companyId);
const app = createApp();
// Simulate the losing side of the count-vs-create race: the winning issue
// already claimed the onboarding origin but is hidden, so the zero-count
// fast path still passes and only issues_onboarding_first_task_uq rejects
// the privileged insert.
await db.insert(issues).values({
companyId,
title: "Race winner",
status: "todo",
priority: "medium",
originKind: ONBOARDING_FIRST_TASK_ORIGIN_KIND,
hiddenAt: new Date(),
});
const created = await request(app)
.post(`/api/companies/${companyId}/issues`)
.send({ title: "Race loser", onboardingFirstTask: true, assigneeAgentId: agentId })
.expect(201);
expect(created.body.originKind).toBe("manual");
const comments = await db
.select()
.from(issueComments)
.where(eq(issueComments.issueId, created.body.id));
expect(comments).toHaveLength(0);
expect(await listOnboardingIssues(companyId)).toHaveLength(1);
});
it("allows at most one onboarding first task across concurrent creates", async () => {
const companyId = await seedCompany();
const app = createApp();
const responses = await Promise.all(
["Kick off A", "Kick off B", "Kick off C"].map((title) =>
request(app)
.post(`/api/companies/${companyId}/issues`)
.send({ title, onboardingFirstTask: true }),
),
);
for (const response of responses) expect(response.status).toBe(201);
expect(await listOnboardingIssues(companyId)).toHaveLength(1);
});
it("stores the server-selected skill invocation and ignores the client description", async () => {
const companyId = await seedCompany();
const agentId = await seedAgent(companyId);
const app = createApp();
const created = await request(app)
.post(`/api/companies/${companyId}/issues`)
.send({
title: "Get started",
description: "client supplied description that must be ignored",
onboardingFirstTask: true,
assigneeAgentId: agentId,
})
.expect(201);
expect(created.body.description).toContain("Use the `first-task` skill (/first-task)");
expect(created.body.description).toContain("Single-task proposal mode: `confirmation`.");
expect(created.body.description).not.toContain("Take the path the user picked.");
expect(created.body.description).not.toContain("client supplied description");
});
it("invokes the skill in plan mode when enableFirstTaskPlanProposal is on", async () => {
const companyId = await seedCompany();
const app = createApp();
await db
.insert(instanceSettings)
.values({ singletonKey: "default", general: {}, experimental: { enableFirstTaskPlanProposal: true } })
.onConflictDoUpdate({
target: [instanceSettings.singletonKey],
set: { experimental: { enableFirstTaskPlanProposal: true } },
});
const created = await request(app)
.post(`/api/companies/${companyId}/issues`)
.send({ title: "Get started", onboardingFirstTask: true })
.expect(201);
expect(created.body.description).toContain("Use the `first-task` skill (/first-task)");
expect(created.body.description).toContain("Single-task proposal mode: `plan`.");
expect(created.body.description).not.toContain("request_checkbox_confirmation");
await db.delete(instanceSettings);
});
it("does not queue an assignment wake for the onboarding first task", async () => {
const companyId = await seedCompany();
const agentId = await seedAgent(companyId);
const app = createApp();
await request(app)
.post(`/api/companies/${companyId}/issues`)
.send({ title: "Get started", onboardingFirstTask: true, assigneeAgentId: agentId })
.expect(201);
await drainHeartbeatRunsToQuiescence(db, heartbeatService(db));
const wakeups = await db
.select()
.from(agentWakeupRequests)
.where(eq(agentWakeupRequests.companyId, companyId));
expect(wakeups).toHaveLength(0);
expect(mockAdapterExecute).not.toHaveBeenCalled();
});
it.each(["done", "cancelled"])("does not queue an assignment wake for an issue created already %s", async (status) => {
const companyId = await seedCompany();
const agentId = await seedAgent(companyId);
const app = createApp();
await request(app)
.post(`/api/companies/${companyId}/issues`)
.send({ title: "Historical record", status, assigneeAgentId: agentId })
.expect(201);
await drainHeartbeatRunsToQuiescence(db, heartbeatService(db));
const wakeups = await db
.select()
.from(agentWakeupRequests)
.where(eq(agentWakeupRequests.companyId, companyId));
expect(wakeups).toHaveLength(0);
expect(mockAdapterExecute).not.toHaveBeenCalled();
});
it("still queues an assignment wake for an ordinary assigned issue", async () => {
const companyId = await seedCompany();
const agentId = await seedAgent(companyId);
const app = createApp();
await request(app)
.post(`/api/companies/${companyId}/issues`)
.send({ title: "Ordinary task", assigneeAgentId: agentId })
.expect(201);
await drainHeartbeatRunsToQuiescence(db, heartbeatService(db));
const wakeups = await db
.select()
.from(agentWakeupRequests)
.where(eq(agentWakeupRequests.companyId, companyId));
// An ordinary assigned create still queues the assignment wake for the agent.
expect(wakeups.length).toBeGreaterThan(0);
expect(wakeups.some((row) => row.agentId === agentId)).toBe(true);
});
});