paperclip/server/src/__tests__/heartbeat-stale-queue-invalidation.test.ts
Aron Prins 897cc322c7
Improve external agent invite flow (#6183)
## Thinking Path

> - Paperclip orchestrates AI agents for zero-human companies.
> - Agent creation can happen through local runtimes, managed runtimes,
and external agents that onboard through invites.
> - The old OpenClaw-oriented invite UX lived under company
settings/invites and made a gateway-specific path look like a company
access setting.
> - That hid the broader bring-your-own-agent flow and forced operators
to leave the add-agent modal when adding an external agent.
> - This pull request moves external agent invite generation into the
add-agent modal and makes the copy agent-oriented instead of
OpenClaw-only.
> - The benefit is a clearer agent-first onboarding path while company
invites stay focused on human access.

## What Changed

- Added an external-agent invite branch to the add-agent modal,
including a dedicated prompt result view with Back navigation.
- Added a shared agent onboarding prompt builder and focused modal
coverage for prompt replacement/back navigation.
- Removed the agent invite prompt UI from Company Settings and Company
Invites, leaving Company Invites focused on human access links and
invite history.
- Updated the hidden OpenClaw Gateway runtime hint to direct operators
to the add-agent invite flow instead of presenting it as a blocked
runtime card.
- Updated invite/onboarding docs, storybook coverage, and server-side
onboarding copy toward generic agent language while preserving existing
gateway compatibility.

## Verification

- `pnpm -r typecheck`
- `pnpm build`
- `FAKE_BIN="$(mktemp -d)/bin"; mkdir -p "$FAKE_BIN"; printf
'#!/bin/sh\nexit 1\n' > "$FAKE_BIN/tailscale"; chmod +x
"$FAKE_BIN/tailscale"; PATH="$FAKE_BIN:$PATH" pnpm test:run`
- `pnpm test:run` without the fake `tailscale` shim was also attempted;
it failed only in two pre-existing CLI tailnet fallback tests because
this host has a real Tailscale address (`100.125.202.3`) where those
tests expect no Tailscale.
- Focused confirmation for that host-env issue: `FAKE_BIN=...
PATH="$FAKE_BIN:$PATH" pnpm exec vitest run --project paperclipai
cli/src/__tests__/network-bind.test.ts
cli/src/__tests__/onboard.test.ts`
- Manual UI verification: served UI locally in light mode, opened
add-agent modal, generated external agent prompt, verified the generated
prompt replaces the form and Back returns to the form.

### Screenshots

![Add agent
modal](https://raw.githubusercontent.com/aronprins/paperclip/pr-assets/6183-agent-invites/.github/pr-screenshots/6183/add-agent-modal-light.png)

![External agent invite
form](https://raw.githubusercontent.com/aronprins/paperclip/pr-assets/6183-agent-invites/.github/pr-screenshots/6183/external-agent-invite-form-light.png)

![Generated onboarding prompt replacement
view](https://raw.githubusercontent.com/aronprins/paperclip/pr-assets/6183-agent-invites/.github/pr-screenshots/6183/onboarding-prompt-result-light.png)

## Risks

- Existing OpenClaw gateway compatibility remains, but operators now
discover external agent onboarding from the add-agent modal instead of
company settings.
- Agent invites still appear in the invite history table, so that page
may show agent-scoped invite rows even though it no longer creates agent
onboarding prompts.
- Low migration risk: no schema changes.

> 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

- OpenAI Codex, GPT-5 coding agent in Codex desktop; tool-enabled
repository, shell, browser, and GitHub workflow. Context window size was
not exposed by the runtime.

## 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 run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] If this change affects the UI, I have included before/after
screenshots
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] I will address all Greptile and reviewer comments before
requesting merge
2026-05-23 09:09:40 -05:00

829 lines
26 KiB
TypeScript

import { randomUUID } from "node:crypto";
import { eq, sql } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import {
agents,
agentWakeupRequests,
companies,
createDb,
documentRevisions,
documents,
heartbeatRuns,
issueComments,
issueDocuments,
issues,
} from "@paperclipai/db";
import { ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY } from "@paperclipai/shared";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
import {
MAX_TURN_CONTINUATION_RETRY_REASON,
MAX_TURN_CONTINUATION_WAKE_REASON,
heartbeatService,
} from "../services/heartbeat.ts";
import { runningProcesses } from "../adapters/index.ts";
const mockAdapterExecute = vi.hoisted(() =>
vi.fn(async () => ({
exitCode: 0,
signal: null,
timedOut: false,
errorMessage: null,
summary: "Stale-queue invalidation 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 heartbeat stale-queue invalidation tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`,
);
}
async function ensureIssueRelationsTable(db: ReturnType<typeof createDb>) {
await db.execute(sql.raw(`
CREATE TABLE IF NOT EXISTS "issue_relations" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
"company_id" uuid NOT NULL,
"issue_id" uuid NOT NULL,
"related_issue_id" uuid NOT NULL,
"type" text NOT NULL,
"created_by_agent_id" uuid,
"created_by_user_id" text,
"created_at" timestamptz NOT NULL DEFAULT now(),
"updated_at" timestamptz NOT NULL DEFAULT now()
);
`));
}
async function waitForCondition(fn: () => Promise<boolean>, timeoutMs = 3_000) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
if (await fn()) return true;
await new Promise((resolve) => setTimeout(resolve, 50));
}
return fn();
}
async function cleanupHeartbeatInvalidationFixture(db: ReturnType<typeof createDb>) {
for (let attempt = 0; attempt < 10; attempt += 1) {
try {
await db.execute(sql.raw(`
TRUNCATE TABLE
"company_skills",
"issue_comments",
"issue_documents",
"document_revisions",
"documents",
"issue_relations",
"issue_tree_holds",
"issues",
"heartbeat_run_events",
"activity_log",
"heartbeat_runs",
"agent_wakeup_requests",
"agent_runtime_state",
"agents",
"companies"
RESTART IDENTITY CASCADE
`));
return;
} catch (error) {
const isLateCommentRace =
error instanceof Error &&
error.message.includes("issue_comments_issue_id_issues_id_fk");
if (!isLateCommentRace || attempt === 9) {
throw error;
}
// Heartbeat completion can write issue-thread comments shortly after the
// run leaves queued/running. Retry the dependent deletes once those land.
await new Promise((resolve) => setTimeout(resolve, 100));
}
}
}
type SeedOptions = {
agentName?: string;
agentRole?: string;
maxConcurrentRuns?: number;
};
type SeedResult = {
companyId: string;
agentId: string;
};
describeEmbeddedPostgres("heartbeat stale queued-run invalidation", () => {
let db!: ReturnType<typeof createDb>;
let heartbeat!: ReturnType<typeof heartbeatService>;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
const countExecuteCallsForRun = (runId: string) =>
mockAdapterExecute.mock.calls.filter(([context]) => context?.runId === runId).length;
beforeAll(async () => {
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-heartbeat-stale-queue-");
db = createDb(tempDb.connectionString);
heartbeat = heartbeatService(db);
await ensureIssueRelationsTable(db);
}, 20_000);
afterEach(async () => {
mockAdapterExecute.mockReset();
mockAdapterExecute.mockImplementation(async () => ({
exitCode: 0,
signal: null,
timedOut: false,
errorMessage: null,
summary: "Stale-queue invalidation test run.",
provider: "test",
model: "test-model",
}));
runningProcesses.clear();
let idlePolls = 0;
for (let attempt = 0; attempt < 100; attempt += 1) {
const runs = await db
.select({ status: heartbeatRuns.status })
.from(heartbeatRuns);
const hasActiveRun = runs.some((run) => run.status === "queued" || run.status === "running");
if (!hasActiveRun) {
idlePolls += 1;
if (idlePolls >= 3) break;
} else {
idlePolls = 0;
}
await new Promise((resolve) => setTimeout(resolve, 50));
}
await new Promise((resolve) => setTimeout(resolve, 50));
await cleanupHeartbeatInvalidationFixture(db);
});
afterAll(async () => {
await tempDb?.cleanup();
});
async function seedCompanyAndAgent(opts: SeedOptions = {}): Promise<SeedResult> {
const companyId = randomUUID();
const agentId = randomUUID();
await db.insert(companies).values({
id: companyId,
name: "Paperclip",
issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
requireBoardApprovalForNewAgents: false,
});
await db.insert(agents).values({
id: agentId,
companyId,
name: opts.agentName ?? "ClaudeCoder",
role: opts.agentRole ?? "engineer",
status: "active",
adapterType: "codex_local",
adapterConfig: {},
runtimeConfig: {
heartbeat: {
wakeOnDemand: true,
maxConcurrentRuns: opts.maxConcurrentRuns ?? 1,
},
},
permissions: {},
});
return { companyId, agentId };
}
async function seedQueuedRun(input: {
companyId: string;
agentId: string;
issueId: string;
wakeReason: string;
contextExtras?: Record<string, unknown>;
invocationSource?: "assignment" | "automation";
scheduledRetryReason?: string | null;
}) {
const wakeupRequestId = randomUUID();
const runId = randomUUID();
await db.insert(agentWakeupRequests).values({
id: wakeupRequestId,
companyId: input.companyId,
agentId: input.agentId,
source: input.invocationSource ?? "assignment",
triggerDetail: "system",
reason: input.wakeReason,
payload: { issueId: input.issueId },
status: "queued",
});
await db.insert(heartbeatRuns).values({
id: runId,
companyId: input.companyId,
agentId: input.agentId,
invocationSource: input.invocationSource ?? "assignment",
triggerDetail: "system",
status: "queued",
wakeupRequestId,
scheduledRetryReason: input.scheduledRetryReason ?? null,
contextSnapshot: {
issueId: input.issueId,
wakeReason: input.wakeReason,
...(input.contextExtras ?? {}),
},
});
await db
.update(agentWakeupRequests)
.set({ runId })
.where(eq(agentWakeupRequests.id, wakeupRequestId));
return { runId, wakeupRequestId };
}
async function seedContinuationSummary(input: {
companyId: string;
issueId: string;
agentId: string;
body: string;
}) {
const documentId = randomUUID();
const revisionId = randomUUID();
await db.insert(documents).values({
id: documentId,
companyId: input.companyId,
title: "Continuation Summary",
format: "markdown",
latestBody: input.body,
latestRevisionId: revisionId,
latestRevisionNumber: 1,
createdByAgentId: input.agentId,
updatedByAgentId: input.agentId,
});
await db.insert(documentRevisions).values({
id: revisionId,
companyId: input.companyId,
documentId,
revisionNumber: 1,
title: "Continuation Summary",
format: "markdown",
body: input.body,
createdByAgentId: input.agentId,
});
await db.insert(issueDocuments).values({
companyId: input.companyId,
issueId: input.issueId,
documentId,
key: ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY,
});
}
it("cancels queued runs when the issue assignee changes before the run starts", async () => {
const { companyId, agentId } = await seedCompanyAndAgent({ agentName: "OriginalCoder" });
const replacementAgentId = randomUUID();
await db.insert(agents).values({
id: replacementAgentId,
companyId,
name: "ReplacementCoder",
role: "engineer",
status: "active",
adapterType: "codex_local",
adapterConfig: {},
runtimeConfig: {
heartbeat: {
wakeOnDemand: true,
maxConcurrentRuns: 1,
},
},
permissions: {},
});
const issueId = randomUUID();
await db.insert(issues).values({
id: issueId,
companyId,
title: "Reassigned task",
status: "in_progress",
priority: "high",
assigneeAgentId: replacementAgentId,
});
const { runId, wakeupRequestId } = await seedQueuedRun({
companyId,
agentId,
issueId,
wakeReason: "issue_assigned",
});
await heartbeat.resumeQueuedRuns();
await waitForCondition(async () => {
const run = await db
.select({ status: heartbeatRuns.status })
.from(heartbeatRuns)
.where(eq(heartbeatRuns.id, runId))
.then((rows) => rows[0] ?? null);
return run?.status === "cancelled";
});
const [run, wakeup] = await Promise.all([
db
.select({
status: heartbeatRuns.status,
errorCode: heartbeatRuns.errorCode,
resultJson: heartbeatRuns.resultJson,
})
.from(heartbeatRuns)
.where(eq(heartbeatRuns.id, runId))
.then((rows) => rows[0] ?? null),
db
.select({ status: agentWakeupRequests.status, error: agentWakeupRequests.error })
.from(agentWakeupRequests)
.where(eq(agentWakeupRequests.id, wakeupRequestId))
.then((rows) => rows[0] ?? null),
]);
expect(run?.status).toBe("cancelled");
expect(run?.errorCode).toBe("issue_assignee_changed");
expect(run?.resultJson).toMatchObject({ stopReason: "issue_assignee_changed" });
expect(wakeup?.status).toBe("skipped");
expect(wakeup?.error).toContain("assignee changed");
expect(countExecuteCallsForRun(runId)).toBe(0);
});
it("cancels queued runs when the issue reaches a terminal status before the run starts", async () => {
const { companyId, agentId } = await seedCompanyAndAgent();
const issueId = randomUUID();
await db.insert(issues).values({
id: issueId,
companyId,
title: "Already-completed task",
status: "done",
priority: "medium",
assigneeAgentId: agentId,
});
const { runId, wakeupRequestId } = await seedQueuedRun({
companyId,
agentId,
issueId,
wakeReason: "issue_assigned",
});
await heartbeat.resumeQueuedRuns();
await waitForCondition(async () => {
const run = await db
.select({ status: heartbeatRuns.status })
.from(heartbeatRuns)
.where(eq(heartbeatRuns.id, runId))
.then((rows) => rows[0] ?? null);
return run?.status === "cancelled";
});
const [run, wakeup] = await Promise.all([
db
.select({ status: heartbeatRuns.status, errorCode: heartbeatRuns.errorCode })
.from(heartbeatRuns)
.where(eq(heartbeatRuns.id, runId))
.then((rows) => rows[0] ?? null),
db
.select({ status: agentWakeupRequests.status })
.from(agentWakeupRequests)
.where(eq(agentWakeupRequests.id, wakeupRequestId))
.then((rows) => rows[0] ?? null),
]);
expect(run?.status).toBe("cancelled");
expect(run?.errorCode).toBe("issue_terminal_status");
expect(wakeup?.status).toBe("skipped");
expect(countExecuteCallsForRun(runId)).toBe(0);
});
it("cancels queued max-turn continuations when the issue is no longer in_progress before the run starts", async () => {
const { companyId, agentId } = await seedCompanyAndAgent();
const issueId = randomUUID();
await db.insert(issues).values({
id: issueId,
companyId,
title: "Parked max-turn continuation",
status: "blocked",
priority: "medium",
assigneeAgentId: agentId,
});
const { runId, wakeupRequestId } = await seedQueuedRun({
companyId,
agentId,
issueId,
wakeReason: MAX_TURN_CONTINUATION_WAKE_REASON,
invocationSource: "automation",
scheduledRetryReason: MAX_TURN_CONTINUATION_RETRY_REASON,
contextExtras: {
retryReason: MAX_TURN_CONTINUATION_RETRY_REASON,
},
});
await heartbeat.resumeQueuedRuns();
await waitForCondition(async () => {
const run = await db
.select({ status: heartbeatRuns.status })
.from(heartbeatRuns)
.where(eq(heartbeatRuns.id, runId))
.then((rows) => rows[0] ?? null);
return run?.status === "cancelled";
});
const [run, wakeup] = await Promise.all([
db
.select({
status: heartbeatRuns.status,
errorCode: heartbeatRuns.errorCode,
resultJson: heartbeatRuns.resultJson,
})
.from(heartbeatRuns)
.where(eq(heartbeatRuns.id, runId))
.then((rows) => rows[0] ?? null),
db
.select({ status: agentWakeupRequests.status, error: agentWakeupRequests.error })
.from(agentWakeupRequests)
.where(eq(agentWakeupRequests.id, wakeupRequestId))
.then((rows) => rows[0] ?? null),
]);
expect(run?.status).toBe("cancelled");
expect(run?.errorCode).toBe("issue_not_in_progress");
expect(run?.resultJson).toMatchObject({ stopReason: "issue_not_in_progress" });
expect(wakeup?.status).toBe("skipped");
expect(wakeup?.error).toContain("no longer in_progress");
expect(countExecuteCallsForRun(runId)).toBe(0);
});
it("cancels queued max-turn continuations when another continuation owns the issue lock", async () => {
const { companyId, agentId } = await seedCompanyAndAgent();
const issueId = randomUUID();
const lockOwnerRunId = randomUUID();
await db.insert(heartbeatRuns).values({
id: lockOwnerRunId,
companyId,
agentId,
invocationSource: "automation",
triggerDetail: "system",
status: "scheduled_retry",
scheduledRetryReason: MAX_TURN_CONTINUATION_RETRY_REASON,
scheduledRetryAttempt: 1,
scheduledRetryAt: new Date("2026-04-20T12:00:00.000Z"),
contextSnapshot: {
issueId,
wakeReason: MAX_TURN_CONTINUATION_WAKE_REASON,
retryReason: MAX_TURN_CONTINUATION_RETRY_REASON,
},
});
await db.insert(issues).values({
id: issueId,
companyId,
title: "Duplicate max-turn continuation",
status: "in_progress",
priority: "medium",
assigneeAgentId: agentId,
executionRunId: lockOwnerRunId,
executionAgentNameKey: "claudecoder",
executionLockedAt: new Date("2026-04-20T11:59:00.000Z"),
});
const { runId, wakeupRequestId } = await seedQueuedRun({
companyId,
agentId,
issueId,
wakeReason: MAX_TURN_CONTINUATION_WAKE_REASON,
invocationSource: "automation",
scheduledRetryReason: MAX_TURN_CONTINUATION_RETRY_REASON,
contextExtras: {
retryReason: MAX_TURN_CONTINUATION_RETRY_REASON,
},
});
await heartbeat.resumeQueuedRuns();
await waitForCondition(async () => {
const run = await db
.select({ status: heartbeatRuns.status })
.from(heartbeatRuns)
.where(eq(heartbeatRuns.id, runId))
.then((rows) => rows[0] ?? null);
return run?.status === "cancelled";
});
const [run, wakeup, issue] = await Promise.all([
db
.select({
status: heartbeatRuns.status,
errorCode: heartbeatRuns.errorCode,
resultJson: heartbeatRuns.resultJson,
})
.from(heartbeatRuns)
.where(eq(heartbeatRuns.id, runId))
.then((rows) => rows[0] ?? null),
db
.select({ status: agentWakeupRequests.status, error: agentWakeupRequests.error })
.from(agentWakeupRequests)
.where(eq(agentWakeupRequests.id, wakeupRequestId))
.then((rows) => rows[0] ?? null),
db
.select({ executionRunId: issues.executionRunId })
.from(issues)
.where(eq(issues.id, issueId))
.then((rows) => rows[0] ?? null),
]);
expect(run?.status).toBe("cancelled");
expect(run?.errorCode).toBe("issue_execution_lock_changed");
expect(run?.resultJson).toMatchObject({ stopReason: "issue_execution_lock_changed" });
expect(wakeup?.status).toBe("skipped");
expect(wakeup?.error).toContain("execution lock");
expect(issue?.executionRunId).toBe(lockOwnerRunId);
expect(countExecuteCallsForRun(runId)).toBe(0);
});
it("cancels queued in_review runs when the current participant changes before the run starts", async () => {
const { companyId, agentId } = await seedCompanyAndAgent();
const otherAgentId = randomUUID();
await db.insert(agents).values({
id: otherAgentId,
companyId,
name: "ReviewerAgent",
role: "qa",
status: "active",
adapterType: "codex_local",
adapterConfig: {},
runtimeConfig: { heartbeat: { wakeOnDemand: true, maxConcurrentRuns: 1 } },
permissions: {},
});
const issueId = randomUUID();
await db.insert(issues).values({
id: issueId,
companyId,
title: "In-review task now owned by reviewer",
status: "in_review",
priority: "medium",
assigneeAgentId: agentId,
executionState: {
status: "pending",
currentStageId: randomUUID(),
currentStageIndex: 0,
currentStageType: "review",
currentParticipant: { type: "agent", agentId: otherAgentId, userId: null },
returnAssignee: { type: "agent", agentId, userId: null },
reviewRequest: null,
completedStageIds: [],
lastDecisionId: null,
lastDecisionOutcome: null,
},
});
const { runId, wakeupRequestId } = await seedQueuedRun({
companyId,
agentId,
issueId,
wakeReason: "issue_assigned",
});
await heartbeat.resumeQueuedRuns();
await waitForCondition(async () => {
const run = await db
.select({ status: heartbeatRuns.status })
.from(heartbeatRuns)
.where(eq(heartbeatRuns.id, runId))
.then((rows) => rows[0] ?? null);
return run?.status === "cancelled";
});
const [run, wakeup] = await Promise.all([
db
.select({
status: heartbeatRuns.status,
errorCode: heartbeatRuns.errorCode,
resultJson: heartbeatRuns.resultJson,
})
.from(heartbeatRuns)
.where(eq(heartbeatRuns.id, runId))
.then((rows) => rows[0] ?? null),
db
.select({ status: agentWakeupRequests.status, error: agentWakeupRequests.error })
.from(agentWakeupRequests)
.where(eq(agentWakeupRequests.id, wakeupRequestId))
.then((rows) => rows[0] ?? null),
]);
expect(run?.status).toBe("cancelled");
expect(run?.errorCode).toBe("issue_review_participant_changed");
expect(run?.resultJson).toMatchObject({ stopReason: "issue_review_participant_changed" });
expect(wakeup?.status).toBe("skipped");
expect(wakeup?.error).toContain("in-review participant changed");
expect(countExecuteCallsForRun(runId)).toBe(0);
});
it("still runs comment-driven wakes on in_review issues even when the agent is no longer the current participant", async () => {
const { companyId, agentId } = await seedCompanyAndAgent();
const otherAgentId = randomUUID();
await db.insert(agents).values({
id: otherAgentId,
companyId,
name: "ReviewerAgent",
role: "qa",
status: "active",
adapterType: "codex_local",
adapterConfig: {},
runtimeConfig: { heartbeat: { wakeOnDemand: true, maxConcurrentRuns: 1 } },
permissions: {},
});
const issueId = randomUUID();
const commentId = randomUUID();
await db.insert(issues).values({
id: issueId,
companyId,
title: "In-review task with comment feedback",
status: "in_review",
priority: "medium",
assigneeAgentId: agentId,
executionState: {
status: "pending",
currentStageId: randomUUID(),
currentStageIndex: 0,
currentStageType: "review",
currentParticipant: { type: "agent", agentId: otherAgentId, userId: null },
returnAssignee: { type: "agent", agentId, userId: null },
reviewRequest: null,
completedStageIds: [],
lastDecisionId: null,
lastDecisionOutcome: null,
},
});
await db.insert(issueComments).values({
id: commentId,
companyId,
issueId,
authorAgentId: otherAgentId,
body: "Review feedback comment",
});
const { runId } = await seedQueuedRun({
companyId,
agentId,
issueId,
wakeReason: "issue_commented",
invocationSource: "automation",
contextExtras: {
commentId,
wakeCommentId: commentId,
source: "issue.comment",
},
});
await heartbeat.resumeQueuedRuns();
await waitForCondition(async () => {
const run = await db
.select({ status: heartbeatRuns.status })
.from(heartbeatRuns)
.where(eq(heartbeatRuns.id, runId))
.then((rows) => rows[0] ?? null);
return run?.status === "succeeded";
});
const run = await db
.select({ status: heartbeatRuns.status, errorCode: heartbeatRuns.errorCode })
.from(heartbeatRuns)
.where(eq(heartbeatRuns.id, runId))
.then((rows) => rows[0] ?? null);
expect(run?.status).toBe("succeeded");
expect(run?.errorCode).toBeNull();
});
it("baseline: runs queued runs when the issue is in_progress with the same assignee", async () => {
const { companyId, agentId } = await seedCompanyAndAgent();
const issueId = randomUUID();
await db.insert(issues).values({
id: issueId,
companyId,
title: "Still actionable",
status: "in_progress",
priority: "medium",
assigneeAgentId: agentId,
});
const { runId } = await seedQueuedRun({
companyId,
agentId,
issueId,
wakeReason: "issue_assigned",
});
await heartbeat.resumeQueuedRuns();
await waitForCondition(async () => {
const run = await db
.select({ status: heartbeatRuns.status })
.from(heartbeatRuns)
.where(eq(heartbeatRuns.id, runId))
.then((rows) => rows[0] ?? null);
return run?.status === "succeeded";
});
const run = await db
.select({ status: heartbeatRuns.status, errorCode: heartbeatRuns.errorCode })
.from(heartbeatRuns)
.where(eq(heartbeatRuns.id, runId))
.then((rows) => rows[0] ?? null);
expect(run?.status).toBe("succeeded");
expect(run?.errorCode).toBeNull();
expect(countExecuteCallsForRun(runId)).toBe(1);
});
it("cancels queued continuation recovery when the continuation summary parks executor work for review", async () => {
const { companyId, agentId } = await seedCompanyAndAgent();
const issueId = randomUUID();
await db.insert(issues).values({
id: issueId,
companyId,
title: "Implementation parked for review",
status: "in_progress",
priority: "medium",
assigneeAgentId: agentId,
});
await seedContinuationSummary({
companyId,
issueId,
agentId,
body: [
"# Continuation Summary",
"",
"## Next Action",
"",
"- Wait for reviewer feedback or approval before continuing executor work.",
].join("\n"),
});
const { runId, wakeupRequestId } = await seedQueuedRun({
companyId,
agentId,
issueId,
wakeReason: "issue_continuation_needed",
invocationSource: "automation",
contextExtras: {
retryReason: "issue_continuation_needed",
},
});
await heartbeat.resumeQueuedRuns();
await waitForCondition(async () => {
const run = await db
.select({ status: heartbeatRuns.status })
.from(heartbeatRuns)
.where(eq(heartbeatRuns.id, runId))
.then((rows) => rows[0] ?? null);
return run?.status === "cancelled";
});
const [run, wakeup] = await Promise.all([
db
.select({
status: heartbeatRuns.status,
errorCode: heartbeatRuns.errorCode,
resultJson: heartbeatRuns.resultJson,
})
.from(heartbeatRuns)
.where(eq(heartbeatRuns.id, runId))
.then((rows) => rows[0] ?? null),
db
.select({ status: agentWakeupRequests.status, error: agentWakeupRequests.error })
.from(agentWakeupRequests)
.where(eq(agentWakeupRequests.id, wakeupRequestId))
.then((rows) => rows[0] ?? null),
]);
expect(run?.status).toBe("cancelled");
expect(run?.errorCode).toBe("issue_continuation_waiting_on_review");
expect(run?.resultJson).toMatchObject({ stopReason: "issue_continuation_waiting_on_review" });
expect(wakeup?.status).toBe("skipped");
expect(wakeup?.error).toContain("continuation summary says the executor should wait");
expect(countExecuteCallsForRun(runId)).toBe(0);
});
});