Merge current master into external-agent sleep recovery

* commit '36101ebcb9647b110757ac15ca935d53c01df99f':
  fix(evals): grade five cohort-14 chat cases by saved state and clicked links (#21667)
  fix(runner): count returned validation rejections and give a copyable call in repeated-failure corrections (#21666)
  fix(runner): bound ACPX instructions only where the sandbox delivers them (#21646)
  perf(ui): open a task restored from the saved read cache through the chat bootstrap (#21650)
  feat(native-runtime): ask the Runner for provider-started turns on native ACPX Claude runs (#21456)
  fix(github): read only the webhook secrets each delivery step uses (#21651)
  fix(runner): recover provider-started turns after a controller restart (#21612)
  fix(runner): settle every recorded tool result and free sessions blocked by a closed turn's pending call (#21490)
  fix(chat): report an outcome once and create no run when an earlier reply gave it (#21489)
  test(evals): write the hard-stop setup note in plain words (#21487)
  fix(runs): say who started a retry run in the issue run read (#21486)
  feat(db): attribute work signals by caller behind a debug flag (#21640)
  perf(github): reuse repository installation tokens until shortly before expiry (#21641)
  perf(workspaces): start a full terminal workspace pass only at startup and on the hourly backstop (#21630)
  fix(native): wait for a live warm session owner during a deploy overlap (#21627)
  perf(recovery): stop re-asserting a failed legacy run whose decision is recorded (#21621)
  feat(runner): let a caller ask the transport for provider-started turns (#21607)
  perf(workspaces): read a sweep page's task trees and active runs in two statements (#21618)
  perf(workspaces): inspect only due workspaces and wait for a holding run's release (#21617)
This commit is contained in:
Dotta committed 2026-11-14 17:13:19 -06:00
commit ea15c9c419
124 files changed
+6308 -430

No files matched your search

@@ -0,0 +1,102 @@
import { randomUUID } from "node:crypto";
import { eq } from "drizzle-orm";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { agents, agentWakeupRequests, companies, createDb, heartbeatRuns, issueComments, issueThreadInteractions, issues } from "@paperclipai/db";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js";
import { createReleaseIssueExecution } from "../application/use-cases.js";
import { ALREADY_REPORTED_WAKE_REASON, createPostgresWakeQueueAdapter } from "./postgres.js";
import { recordDeclinedInteractionRead } from "../../../services/chat-interaction-outcome-report.js";
const support = await getEmbeddedPostgresTestSupport();
// Chat eval questions-and-approvals.decline-tool: the person said "Do not use that app" and
// declined the tool review a second later. The turn woken by the message read the action
// declined and said so. The decline continuation, saved behind that turn, then posted the
// same declined outcome again.
describe.skipIf(!support.supported)("release of a decline continuation an earlier reply already reported", () => {
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: ReturnType<typeof createDb>;
let companyId: string;
let agentId: string;
beforeAll(async () => {
database = await startEmbeddedPostgresTestDatabase("wake-chat-declined-");
db = createDb(database.connectionString);
const [company] = await db.insert(companies).values({ name: "Declined outcome fixture", issuePrefix: "CDO" }).returning();
const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Lead", adapterType: "process" }).returning();
companyId = company.id;
agentId = agent.id;
}, 60_000);
afterAll(async () => {
await db?.$client.end();
await database?.cleanup();
});
async function seed(input: { outcomeCount?: number; read: boolean; toolAction?: boolean; status?: string; historical?: number }) {
const [issue] = await db.insert(issues).values({ companyId, title: "Chat with CEO", status: "in_progress", assigneeAgentId: agentId,
conversationAgentId: agentId, conversationUserId: `person-${randomUUID()}`, conversationState: "waiting" }).returning();
// Older declines come first in the agent's interaction list.
const history = input.historical ? await db.insert(issueThreadInteractions).values(Array.from({ length: input.historical }, (_, index) => ({
companyId, issueId: issue.id, kind: "request_confirmation", status: "rejected", resolvedByUserId: "person",
createdAt: new Date(Date.now() - 600_000 + index), resolvedAt: new Date(Date.now() - 500_000 + index),
payload: { version: 1, prompt: "Approve an earlier read?", toolAction: { connectionId: randomUUID() } } as never,
}))).returning() : [];
const resolvedAt = new Date(Date.now() - 30_000);
const [card] = await db.insert(issueThreadInteractions).values({ companyId, issueId: issue.id, kind: "request_confirmation",
status: input.status ?? "rejected", resolvedAt, resolvedByUserId: "person",
payload: { version: 1, prompt: "Approve Read launch notes?", ...(input.toolAction === false ? {} : { toolAction: { connectionId: randomUUID() } }) } as never,
}).returning();
// The turn woken by the person's message was running when the card was declined.
const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, status: "running", invocationSource: "automation",
startedAt: new Date(Date.now() - 31_000), contextSnapshot: { issueId: issue.id } }).returning();
if (input.read) {
await recordDeclinedInteractionRead(db, { companyId, agentId, runId: run.id, issue,
interactions: [...history, card].map(row => ({ id: row.id, kind: row.kind, status: row.status, payload: row.payload })) });
}
const [reply] = await db.insert(issueComments).values({ companyId, issueId: issue.id, authorAgentId: agentId, createdByRunId: run.id,
body: "Understood. The approval for that read was already declined, so I won't use the app." }).returning();
await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }).where(eq(heartbeatRuns.id, run.id));
await db.update(issues).set({ executionRunId: run.id, executionLockedAt: new Date() }).where(eq(issues.id, issue.id));
const context = { issueId: issue.id, taskId: issue.id, interactionId: card.id, interactionIds: [card.id],
interactionKind: "request_confirmation", interactionStatus: card.status, wakeReason: "issue_commented", source: "tool_action_review",
...(input.outcomeCount === undefined ? {} : { toolActionOutcomeCount: input.outcomeCount }) };
const [wake] = await db.insert(agentWakeupRequests).values({ companyId, agentId, source: "automation", triggerDetail: "system",
reason: "issue_commented", status: "deferred_issue_execution", requestedByActorType: "user", requestedByActorId: "person",
payload: { ...context, mutation: "interaction", _paperclipWakeContext: context } }).returning();
return { issue, run, wake, reply };
}
function release(promotion: () => never) {
return createReleaseIssueExecution({
issueLock: createPostgresWakeQueueAdapter(db, { resolveResponsibleUserId: promotion, getRoutineEnv: promotion,
resolveSessionBeforeForWakeup: promotion } as never),
recovery: { escalateStrandedAssignedIssue: promotion, escalateStrandedRecoveryIssueInPlace: promotion } as never,
});
}
it.each([0, 20])("settles the decline continuation with no run when the earlier turn read the decline and replied after it (%s older declines)", async historical => {
const { issue, run, wake } = await seed({ read: true, historical });
const promotion = vi.fn((): never => { throw new Error("promotion reached the host"); });
const result = await release(promotion)({ companyId, runId: run.id, now: new Date() });
expect(result.outcome.kind).not.toBe("promoted");
expect(promotion).not.toHaveBeenCalled();
const [settled] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wake.id));
expect(settled).toMatchObject({ status: "skipped", runId: null, error: ALREADY_REPORTED_WAKE_REASON });
expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, companyId)))
.filter(row => row.contextSnapshot?.issueId === issue.id && row.id !== run.id)).toEqual([]);
});
it.each([
["the earlier turn never read the decline", { read: false }],
["the card is not a tool action", { read: true, toolAction: false }],
["the card was accepted", { read: true, status: "accepted" }],
["the batch recorded more outcomes than it lists", { read: true, outcomeCount: 9 }],
] as const)("still runs the continuation when %s", async (_label, input) => {
const { run, wake } = await seed(input);
const promotion = vi.fn((): never => { throw new Error("promotion reached the host"); });
await expect(release(promotion)({ companyId, runId: run.id, now: new Date() })).rejects.toThrow("promotion reached the host");
const [saved] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wake.id));
expect(saved.status).not.toBe("skipped");
});
});
@@ -11,7 +11,8 @@ import { DELIVERY_QUEUES, notifyDeliveryWork } from "../../../services/delivery-
import { isAcknowledgedNativeReassignmentStop, isAcknowledgedNativeStop } from "../../../services/acknowledged-native-stop.js";
import { readRunCancellation } from "../../../services/run-cancellation.js";
import { withRunRedactionHistory } from "../../../services/run-secret-redaction.js";
import { isCompletedOnboardingHandoffWake } from "../../../services/chat-completion-delivery.js";
import { CHAT_COMPLETION_WAKE_REASON, isCompletedOnboardingHandoffWake, settleReportedChatCompletions } from "../../../services/chat-completion-delivery.js";
import { earlierDeclinedOutcomeReply } from "../../../services/chat-interaction-outcome-report.js";
import { instanceSettingsService } from "../../../services/instance-settings.js";
import { currentConversationCommentCondition } from "../../../services/agent-conversations.js";
import { getExecutionBlocker, hasPendingRunCleanup } from "../../../services/execution-blocker.js";
@@ -88,6 +89,8 @@ import type {
import type { RunSummary } from "../application/types.js";
const DEFERRED_WAKE_STATUS = "deferred_issue_execution";
/** Wake outcome for a deferred chat wake whose news an earlier reply already gave. */
export const ALREADY_REPORTED_WAKE_REASON = "Already reported by an earlier reply in this conversation";
const DEFERRED_WAKE_CONTEXT_KEY = "_paperclipWakeContext";
const EXECUTION_PATH_HEARTBEAT_RUN_STATUSES = ["queued", "running", "scheduled_retry"] as const;
@@ -542,6 +545,22 @@ function buildTransaction(tx: Db, deps: WakeQueuePostgresAdapterDeps, db: Db, ru
});
},
async skipAlreadyReportedChatWake({ companyId, issueId, wake, now }) {
if (wake.authorizedFailedChatRetry || wake.queuedCommentIds.length > 0) return false;
const reported = (wake.wakeReason ?? wake.reason) === CHAT_COMPLETION_WAKE_REASON
? await settleReportedChatCompletions(tx, { companyId, conversationId: issueId, agentId: wake.agentId })
: Boolean(await earlierDeclinedOutcomeReply(tx, { companyId, issueId, agentId: wake.agentId, payload: wake.payload }));
if (!reported) return false;
await notifyStrandedAgentStatus(tx, { companyId, agentId: wake.agentId });
await notifyChatInboundWakeNotices(tx, { companyId });
const rows = await tx.update(agentWakeupRequests)
.set({ status: "skipped", finishedAt: now, error: ALREADY_REPORTED_WAKE_REASON, updatedAt: now })
.where(and(eq(agentWakeupRequests.id, wake.id), eq(agentWakeupRequests.agentId, wake.agentId),
eq(agentWakeupRequests.companyId, companyId), eq(agentWakeupRequests.status, DEFERRED_WAKE_STATUS)))
.returning({ id: agentWakeupRequests.id });
return rows.length > 0;
},
async isCompletedOnboardingHandoffWake(input) {
return isCompletedOnboardingHandoffWake(tx, input);
},
@@ -201,6 +201,13 @@ export interface WakeQueueTransaction {
}): Promise<boolean>;
/** Reopens to todo, or straight to in_progress for an owed answer, which continues the assignee's own execution. */
reopenIssue(input: { companyId: string; issueId: string; runId: string; status?: "todo" | "in_progress" }): Promise<IssueSnapshot | null>;
/**
* Settles a deferred chat wake whose only news an earlier reply in the same conversation
* already reported (a delegated task's completion, or a declined tool action), so it ends
* with no run. Marks reported completions delivered by that reply and the wake `skipped`.
* Returns `false`, with no write to the wake, when anything is still owed to the person.
*/
skipAlreadyReportedChatWake(input: { companyId: string; issueId: string; wake: DeferredWakeCandidate; now: Date }): Promise<boolean>;
/** Verifies a Done onboarding parent's completion wake against its own completed children. */
isCompletedOnboardingHandoffWake(input: { companyId: string; issueId: string; agentId: string;
reason: string | null; contextSnapshot: Record<string, unknown> }): Promise<boolean>;
@@ -100,6 +100,7 @@ function createFakeTransaction(overrides: Partial<WakeQueueTransaction> = {}): W
return {
findInvokableAgent: vi.fn(async () => AGENT),
isCompletedOnboardingHandoffWake: vi.fn(async () => false),
skipAlreadyReportedChatWake: vi.fn(async () => false),
findNextDeferredWake: vi.fn(async () => null),
getQueuedCommentLiveness: vi.fn(async () => ({ liveNonSelfCommentIds: [], containedSelfAuthoredComment: false })),
cancelDeferredWake: vi.fn(async () => true),
@@ -148,6 +149,25 @@ function createFakeRecovery(): RecoveryEscalationPort {
}
describe("releaseIssueExecution", () => {
it.each([true, false])("settles an already-reported chat wake without a run (%s)", async reported => {
const completion = wakeCandidate({ id: "completion-wake", reason: "chat_task_completed", wakeReason: "chat_task_completed" });
const queue = [completion];
const transaction = createFakeTransaction({
findNextDeferredWake: vi.fn(async () => queue.shift() ?? null),
skipAlreadyReportedChatWake: vi.fn(async () => reported),
});
const release = createReleaseIssueExecution({
issueLock: createFakeIssueLock(createFakeHost(), transaction), recovery: createFakeRecovery(),
});
const result = await release({ companyId: RUN.companyId, runId: RUN.id, now: new Date() });
expect(transaction.skipAlreadyReportedChatWake).toHaveBeenCalledWith(expect.objectContaining({ issueId: ISSUE.id, wake: completion }));
if (reported) {
expect(result.outcome.kind).not.toBe("promoted");
expect(transaction.finalizePromotedWake).not.toHaveBeenCalled();
} else {
expect(result.outcome.kind).toBe("promoted");
}
});
it.each([false, true])("preserves a paused head without blocking an eligible follower (%s)", async withFollower => {
const paused = wakeCandidate({ id: "paused-wake", wakeReason: "issue_comment_mentioned", queuedCommentIds: ["paused-comment"] });
const ready = wakeCandidate({ id: "ready-wake", agentId: "ready-agent", queuedCommentIds: ["ready-comment"] });
@@ -177,6 +177,12 @@ async function runReleaseDrain(
continue;
}
// An earlier reply in this conversation already reported this wake's
// outcome. Settle it here so a duplicate report never becomes a run.
if (await ports.transaction.skipAlreadyReportedChatWake({ companyId: run.companyId, issueId: issue.id, wake: candidate, now: input.now })) {
continue;
}
// A lead can post its closing comment before committing Done. Check
// again when the source run releases its queue, using every original
// comment ID so coalesced human or unrelated input is never hidden.