merge: preserve workspace callbacks through runtime selection extraction

Adopt upstream runtime-selection boundary and forward the task workspace checkpoint/phase callbacks without moving their run-log policy out of heartbeat. Runtime selection, project repository admission, and responsible-user invariants pass43 tests; server typecheck passes.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-10 07:42:08 -05:00
commit 0f8cea002a
46 files changed
+2399 -1103

No files matched your search

@@ -34,6 +34,8 @@ import {
import { toolAccessService } from "../services/tool-access.js";
import { createToolGatewayService } from "../services/tool-gateway.js";
import { browserUseViewports } from "../services/browser-use-viewport.js";
import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js";
import { registerBrowserUseCleanup } from "../services/browser-use-work.js";
import { browserUseService } from "../services/browser-use.js";
import { applyConnectorSkills, prepareConnectorSkillDelivery, resolveConnectorAssignments } from "../services/connector-runtime.js";
import { registerAssignedMcpGateway } from "../services/native-runtime/assigned-mcp-tools.js";
@@ -313,6 +315,47 @@ const actor = { actorType: "user" as const, actorId: "browser-reviewer" };
},
};
}
it("wakes the app worker from request-service commits and restores durable poll and lease deadlines", async () => {
const f = await fixture();
const background = browserUseService(db, f.request);
const sweep = vi.spyOn(background, "sweep");
const onError = vi.fn();
const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError });
try {
await registerBrowserUseCleanup(coordinator, background, () => true).ready;
expect(coordinator.nextWakeAt()).toBeNull();
expect(await background.nextSweepAt()).toBeNull();
const started = await f.service.execute(f.binding, f.grant, randomUUID(), "browser_start", { task: "Read example.com" }) as { sessionId: string };
await vi.waitFor(() => expect(sweep.mock.calls.length).toBeGreaterThan(1));
await coordinator.stop();
expect(onError).not.toHaveBeenCalled();
const poll = new Date(Date.now() + 60_000);
const lease = new Date(Date.now() + 180_000);
await db.update(browserUseSessions).set({ nextPollAt: poll, leaseUntil: lease })
.where(eq(browserUseSessions.id, started.sessionId));
expect(await background.nextSweepAt()).toBe(lease.getTime());
const restarted = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError });
try {
await registerBrowserUseCleanup(restarted, browserUseService(db, f.request), () => true).ready;
expect(restarted.nextWakeAt()).toBe(lease.getTime());
} finally { await restarted.stop(); }
await db.update(browserUseSessions).set({ leaseUntil: new Date(0) })
.where(eq(browserUseSessions.id, started.sessionId));
expect(await background.nextSweepAt()).toBe(poll.getTime());
await db.update(browserUseSessions).set({ leaseUntil: null })
.where(eq(browserUseSessions.id, started.sessionId));
expect(await background.nextSweepAt()).toBe(poll.getTime());
const [session] = await db.select().from(browserUseSessions).where(eq(browserUseSessions.id, started.sessionId));
await f.service.control(session, "end");
expect(await background.nextSweepAt()).toBeLessThan(poll.getTime());
await db.update(browserUseSessions).set({ status: "closed" }).where(eq(browserUseSessions.id, started.sessionId));
expect(await background.nextSweepAt()).toBeNull();
} finally {
await coordinator.stop();
await db.update(browserUseSessions).set({ status: "closed" }).where(eq(browserUseSessions.companyId, f.company.id));
}
});
it("keeps Cloud instructions out of universal skills and unassigned runtime overlays", async () => {
const skills = await listPaperclipSkillEntries(fileURLToPath(new URL("../", import.meta.url)), [fileURLToPath(new URL("../../../skills", import.meta.url))]);
expect(skills.some(skill => skill.runtimeName === "paperclip")).toBe(true);
@@ -0,0 +1,108 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { installDatabaseWorkSignals } from "../../../packages/db/src/work-signals.js";
import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js";
import { DELIVERY_QUEUES, notifyDeliveryWork } from "../services/delivery-work-notifications.js";
import { registerBrowserUseCleanup } from "../services/browser-use-work.js";
const coordinators: ReturnType<typeof createDeliveryWorkCoordinator>[] = [];
afterEach(async () => {
for (const coordinator of coordinators.splice(0)) await coordinator.stop();
vi.useRealTimers();
});
function setup() {
vi.useFakeTimers();
const execute = vi.fn(async () => [{ xid: "42", status: "committed" }]);
const owner = installDatabaseWorkSignals({ execute, async transaction(callback: (tx: any) => Promise<any>) {
return callback({ execute });
} });
const enabled = vi.fn(() => true), primary = vi.fn(() => true), onError = vi.fn();
const coordinator = createDeliveryWorkCoordinator({
owner, canRun: () => enabled() && primary(), canReconcile: primary, onError,
});
coordinators.push(coordinator);
const service = { sweep: vi.fn(async () => {}), nextSweepAt: vi.fn(async (): Promise<number | null> => null) };
const start = () => registerBrowserUseCleanup(coordinator, service, enabled);
const commit = () => owner.transaction(tx => notifyDeliveryWork(tx, DELIVERY_QUEUES.browser));
return { service, coordinator, start, commit, enabled, primary, onError };
}
describe("browser cleanup scheduling", () => {
it("stays quiet after an empty startup, wakes on commit, and stops after the final session closes", async () => {
const s = setup();
await s.start().ready;
await vi.advanceTimersByTimeAsync(3_600_000);
expect(s.service.sweep).toHaveBeenCalledTimes(1);
expect(s.service.nextSweepAt).toHaveBeenCalledTimes(1);
expect(vi.getTimerCount()).toBe(0);
const due = Date.now() + 15_000;
s.service.nextSweepAt.mockResolvedValue(due);
await s.commit();
await vi.advanceTimersByTimeAsync(1);
expect(s.service.sweep).toHaveBeenCalledTimes(2);
expect(s.coordinator.nextWakeAt()).toBe(due);
await vi.advanceTimersByTimeAsync(14_998);
expect(s.service.sweep).toHaveBeenCalledTimes(2);
s.service.nextSweepAt.mockResolvedValue(null);
await vi.advanceTimersByTimeAsync(1);
expect(s.service.sweep).toHaveBeenCalledTimes(3);
expect(vi.getTimerCount()).toBe(0);
});
it("restores a future lease/retry deadline at startup and lets a control commit preempt it", async () => {
const s = setup();
const due = Date.now() + 180_000;
s.service.nextSweepAt.mockResolvedValue(due);
await s.start().ready;
await vi.advanceTimersByTimeAsync(120_000);
expect(s.service.sweep).toHaveBeenCalledTimes(1);
await s.commit();
await vi.advanceTimersByTimeAsync(1);
expect(s.service.sweep).toHaveBeenCalledTimes(2);
expect(s.coordinator.nextWakeAt()).toBe(due);
});
it("retries a failed scan and bounds already-due batches", async () => {
const s = setup();
s.service.sweep.mockRejectedValueOnce(new Error("database unavailable"));
await s.start().ready;
expect(s.onError).toHaveBeenCalledTimes(1);
s.service.nextSweepAt.mockResolvedValue(Date.now() - 1000);
await vi.advanceTimersByTimeAsync(3000);
expect(s.service.sweep).toHaveBeenCalledTimes(2);
expect(s.coordinator.nextWakeAt()).toBe(Date.now() + 1000);
s.service.nextSweepAt.mockResolvedValue(null);
await vi.advanceTimersByTimeAsync(1000);
expect(vi.getTimerCount()).toBe(0);
});
it("does no session SQL during standby or drain and recovers a first commit after drain", async () => {
const s = setup();
s.primary.mockReturnValue(false);
await s.start().ready;
await vi.advanceTimersByTimeAsync(6000);
expect(s.service.sweep).not.toHaveBeenCalled();
expect(s.service.nextSweepAt).not.toHaveBeenCalled();
s.primary.mockReturnValue(true);
s.enabled.mockReturnValue(false);
await s.commit();
await vi.advanceTimersByTimeAsync(6000);
expect(s.service.sweep).not.toHaveBeenCalled();
expect(s.service.nextSweepAt).not.toHaveBeenCalled();
s.enabled.mockReturnValue(true);
await vi.advanceTimersByTimeAsync(3000);
expect(s.service.sweep).toHaveBeenCalledTimes(1);
expect(vi.getTimerCount()).toBe(0);
});
it("waits for in-flight cleanup on shutdown without rearming its deadline", async () => {
const s = setup();
let finish!: () => void;
s.service.sweep.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
const worker = s.start();
await vi.advanceTimersByTimeAsync(1);
let stopped = false;
const stop = s.coordinator.stop().then(() => { stopped = true; });
await Promise.resolve();
expect(stopped).toBe(false);
finish();
await stop;
await worker.ready;
expect(s.service.nextSweepAt).not.toHaveBeenCalled();
expect(vi.getTimerCount()).toBe(0);
});
});
@@ -25,6 +25,7 @@ import {
import { heartbeatService } from "../services/heartbeat.ts";
import { runningProcesses } from "../adapters/index.ts";
import { drainHeartbeatRunsToQuiescence } from "./helpers/drain-heartbeat-runs.js";
import { createLifecycleDriver } from "../services/agent-lifecycle-driver.js";
const mockAdapterExecute = vi.hoisted(() =>
vi.fn(async () => ({
@@ -166,6 +167,27 @@ describeEmbeddedPostgres("heartbeat responsible-user invariant", () => {
return { companyId, ownerUserId, agentId };
}
it("dispatches saved work on readiness with company scoping and normal admission checks", async () => {
const { companyId, agentId, ownerUserId } = await seedCompany();
await db.update(agents).set({ status: "paused", lifecycleState: "verifying" }).where(eq(agents.id, agentId));
const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, status: "queued",
invocationSource: "on_demand", contextSnapshot: { responsibleUserId: ownerUserId } }).returning();
const driver = createLifecycleDriver(db, {} as never);
const currentAgent = async () => (await db.select().from(agents).where(eq(agents.id, agentId)))[0];
await driver.onReady!(await currentAgent());
expect(mockAdapterExecute).not.toHaveBeenCalled();
expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, run.id)))[0].status).toBe("queued");
await db.update(agents).set({ status: "idle", lifecycleState: "ready" }).where(eq(agents.id, agentId));
await heartbeat.resumeQueuedRunsForAgent(randomUUID(), agentId);
expect(mockAdapterExecute).not.toHaveBeenCalled();
expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, run.id)))[0].status).toBe("queued");
await driver.onReady!(await currentAgent());
expect(await waitForRun(db, run.id)).toMatchObject({ status: "succeeded", responsibleUserId: ownerUserId });
expect(mockAdapterExecute).toHaveBeenCalledOnce();
});
it("dispatches an interrupted queue under the clicking operator through the real startup path", async () => {
const { companyId, agentId, ownerUserId } = await seedCompany();
const operatorId = `operator-${randomUUID()}`, issueId = randomUUID(), commentId = randomUUID(), queueId = randomUUID();
+2 -7
View File
@@ -9,6 +9,7 @@ import { customerSuccessRoutes } from "./routes/customer-success.js";
import { cloudWarmStandbyMiddleware } from "./middleware/cloud-warm-standby.js";
import type { CloudWarmStandby } from "./services/cloud-warm-standby.js";
import { browserUseRoutes } from "./routes/browser-use.js";
import { registerBrowserUseCleanup } from "./services/browser-use-work.js";
import { browserUseService } from "./services/browser-use.js";
import { slackToolRoutes } from "./routes/slack-tools.js";
import { createPublicMcpOAuth, publicMcpConfig } from "./services/public-mcp/oauth.js";
@@ -1292,12 +1293,7 @@ export async function createApp(
);
});
};
const browserUseTimer = setInterval(() => {
if (isWarmStandby() || isIdleTaskDrainActive()) return;
void browserUse.sweep().catch(() => logger.warn("Browser Use reconciliation failed; retrying."));
}, 3000);
browserUseTimer.unref?.();
if (!isWarmStandby() && !isIdleTaskDrainActive()) void browserUse.sweep().catch(() => logger.warn("Browser Use startup reconciliation failed; retrying."));
registerBrowserUseCleanup(deliveryWork, browserUse, () => !isIdleTaskDrainActive());
let importTransferSweepTimer: ReturnType<typeof setInterval> | null =
setInterval(
sweepImportTransferSpools,
@@ -1410,7 +1406,6 @@ export async function createApp(
chatPublicationTimer = null;
}
await chatReconciliation.drain();
clearInterval(browserUseTimer);
if (importTransferSweepTimer) {
clearInterval(importTransferSweepTimer);
importTransferSweepTimer = null;
@@ -13,14 +13,58 @@ function fixture() {
const store = { get: vi.fn(), claim: vi.fn().mockResolvedValue(agent), renew: vi.fn().mockResolvedValue(true),
setRequiredPlugins: vi.fn().mockResolvedValue(true), completeHost: vi.fn().mockResolvedValue(true),
completePlugin: vi.fn().mockResolvedValue(true), defer: vi.fn().mockResolvedValue(true),
change: vi.fn().mockResolvedValue({ ...agent, lifecycleState: "ready" }), pending: vi.fn().mockResolvedValue([agent.id]) } satisfies LifecycleStore;
change: vi.fn().mockResolvedValue({ ...agent, lifecycleState: "ready", lifecycleVersion: 4, lifecycleOperation: null }), pending: vi.fn().mockResolvedValue([agent.id]) } satisfies LifecycleStore;
const driver = { requiredPluginIds: vi.fn().mockResolvedValue(["plugin"]), runHost: vi.fn().mockResolvedValue("complete"),
runPlugin: vi.fn().mockResolvedValue("complete") } satisfies LifecycleDriver;
runPlugin: vi.fn().mockResolvedValue("complete"), onReady: vi.fn().mockResolvedValue(undefined) } satisfies LifecycleDriver;
const report = vi.fn();
return { store, driver, report, worker: createLifecycleWorker(store, driver, report) };
}
afterEach(() => { vi.restoreAllMocks(); vi.useRealTimers(); });
describe("lifecycle readiness handoff", () => {
it("notifies the scheduler only after host, plugins, and readiness have committed", async () => {
const { store, driver, worker } = fixture();
let commit!: (ready: LifecycleAgent) => void;
store.change.mockReturnValue(new Promise(resolve => { commit = resolve; }));
driver.onReady.mockImplementation(async ready => {
expect(store.completeHost).toHaveBeenCalledOnce();
expect(store.completePlugin).toHaveBeenCalledOnce();
expect(store.change).toHaveBeenCalledOnce();
expect(ready).toMatchObject({ lifecycleState: "ready", lifecycleVersion: 4, lifecycleOperation: null });
});
const work = worker.process(agent.id);
await vi.waitFor(() => expect(store.change).toHaveBeenCalledOnce());
expect(driver.onReady).not.toHaveBeenCalled();
commit({ ...agent, lifecycleState: "ready", lifecycleVersion: 4, lifecycleOperation: null });
await work;
expect(driver.onReady).toHaveBeenCalledOnce();
await worker.stop();
});
it.each(["host", "plugin", "transition", "hold"])("does not dispatch when %s prevents readiness", async stage => {
const { store, driver, worker } = fixture();
if (stage === "host") driver.runHost.mockResolvedValue("pending");
if (stage === "plugin") driver.runPlugin.mockResolvedValue("pending");
if (stage === "transition") store.change.mockResolvedValue(null);
if (stage === "hold") store.change.mockResolvedValue({ ...agent, lifecycleState: "paused" });
await worker.process(agent.id);
expect(driver.onReady).not.toHaveBeenCalled();
await worker.stop();
});
it("preserves committed readiness after a dispatch failure for the queue sweep to recover", async () => {
const { store, driver, report, worker } = fixture();
const error = new Error("queue unavailable");
driver.onReady.mockRejectedValue(error);
await worker.process(agent.id);
expect(report).toHaveBeenCalledWith(expect.objectContaining({ stage: "ready", phase: "ready", version: 4 }), error);
expect(store.defer).not.toHaveBeenCalled();
expect(driver.runHost).toHaveBeenCalledOnce();
expect(store.change).toHaveBeenCalledOnce();
await worker.stop();
});
});
describe("lifecycle failure diagnostics", () => {
it.each(["host", "plugin", "claim", "renew", "scan", "defer"] as const)("reports %s failures with the available context", async stage => {
const { store, driver, report, worker } = fixture();
@@ -27,11 +27,13 @@ export interface LifecycleDriver {
requiredPluginIds(agent: LifecycleAgent): Promise<string[]>;
runHost(agent: LifecycleAgent): Promise<"complete" | "pending">;
runPlugin(agent: LifecycleAgent, pluginId: string): Promise<"complete" | "pending">;
/** Notify the scheduler only after readiness has committed. */
onReady?(agent: LifecycleAgent): Promise<void>;
}
export interface LifecycleFailure {
stage: "claim" | "renew" | "select_plugins" | "save_plugins" | "host" | "plugin"
| "complete_host" | "complete_plugin" | "transition" | "defer" | "scan" | "policy_scan";
| "complete_host" | "complete_plugin" | "transition" | "defer" | "scan" | "policy_scan" | "ready";
agentId?: string;
companyId?: string;
phase?: AgentLifecycleState;
@@ -56,6 +56,14 @@ export function createLifecycleWorker(store: LifecycleStore, driver: LifecycleDr
if (!await runStep("complete_plugin", () => store.completePlugin(agent, owner, pluginId), pluginId)) continue phase;
}
const changed = await runStep("transition", () => store.change(id, "complete", { version: agent.lifecycleVersion, owner }));
if (changed?.lifecycleState === "ready" && !stopped && canRun()) {
// Accepted messages may already be waiting for verification. Do not
// leave them until the periodic queue sweep. Readiness is committed;
// a dispatch failure must not replay setup or defer the old phase.
await attempt({ ...context, stage: "ready", phase: changed.lifecycleState,
version: changed.lifecycleVersion, operationId: changed.lifecycleOperation?.id },
async () => { await driver.onReady?.(changed); }).catch(() => {});
}
if (changed && !isLifecycleWorkPending(changed.lifecycleState)) return;
} catch {
if (!await runStep("defer", () => store.defer(agent, owner, "The lifecycle step failed. Retry the operation.", new Date()))) continue;
@@ -10,6 +10,9 @@ export function createLifecycleDriver(db: Db, manager: PluginWorkerManager): Lif
const { verify } = agentHarnessVerificationService(db, manager);
const heartbeat = heartbeatService(db, { pluginWorkerManager: manager });
return {
async onReady(agent) {
await heartbeat.resumeQueuedRunsForAgent(agent.companyId, agent.id);
},
async requiredPluginIds(agent) {
if (agent.lifecycleRequiredPluginIds !== null) return agent.lifecycleRequiredPluginIds;
const installed = await db.select().from(plugins).where(inArray(plugins.status, ["ready", "error", "installed", "upgrade_pending"]));
+23
View File
@@ -0,0 +1,23 @@
import type { createDeliveryWorkCoordinator } from "./delivery-work-coordinator.js";
import { DELIVERY_QUEUES } from "./delivery-work-notifications.js";
/** The app owns this worker; request-scoped services only signal durable writes. */
export function registerBrowserUseCleanup(
coordinator: ReturnType<typeof createDeliveryWorkCoordinator>,
service: { sweep(): Promise<void>; nextSweepAt(): Promise<number | null> },
canRun: () => boolean,
) {
let next: number | null = null;
return coordinator.register(DELIVERY_QUEUES.browser, {
retryMs: 3000,
run: () => service.sweep(),
hasPending: async () => {
// During idle drain retain a memory-only wake, including startup or a
// newly committed first session. Warm standby is gated by the coordinator.
next = canRun() ? await service.nextSweepAt() : Date.now() + 3000;
return false;
},
// Bound overdue batches without spinning on a busy database.
nextRunAt: () => next === null ? null : Math.max(Date.now() + 1000, next),
});
}
+125 -101
View File
@@ -43,6 +43,7 @@ import { createCostEventInTransaction } from "./costs.js";
import { createFinanceEventInTransaction } from "./finance.js";
import { withAccountingTransaction } from "./accounting-transaction.js";
import { logActivity } from "./activity-log.js";
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
import { browserUseViewports } from "./browser-use-viewport.js";
import { forbidden, notFound, conflict } from "../errors.js";
@@ -64,6 +65,7 @@ const argsSchema = z
})
.strict();
const terminalSessions = ["closed", "failed"];
const liveSessions = ["starting", "running", "idle", "stopping"];
const requestMarker = (invocationId: string) => `\n\n[Paperclip request: ${invocationId}]`;
export function browserUseService(
@@ -422,6 +424,7 @@ export function browserUseService(
);
const sid = args.sessionId;
const s = await db.transaction(async (tx) => {
await notifyDeliveryWork(tx, DELIVERY_QUEUES.browser);
let row: Session;
if (sid) {
await owned(binding, grant, sid);
@@ -429,6 +432,7 @@ export function browserUseService(
.update(sessions)
.set({
status: "starting",
nextPollAt: new Date(),
idleDeadline: null,
updatedAt: new Date(),
})
@@ -486,6 +490,7 @@ export function browserUseService(
...(maxCostUsd === undefined ? {} : { maxCostUsd }),
});
await db.transaction(async (tx) => {
await notifyDeliveryWork(tx, DELIVERY_QUEUES.browser);
await tx
.update(runs)
.set({ providerRunId: result.id, status: result.status })
@@ -507,6 +512,7 @@ export function browserUseService(
const message = rejected ? error.message :
"Browser run creation could not be confirmed. Paperclip is locating and stopping possible provider work. Do not start another run yet.";
await db.transaction(async tx => {
await notifyDeliveryWork(tx, DELIVERY_QUEUES.browser);
const [current] = await tx.select().from(sessions).where(eq(sessions.id, s.id)).for("update");
// A restart must not leave a drained rejection attached to a starting
// session: that combination has neither recovery work nor an idle timer.
@@ -566,25 +572,28 @@ export function browserUseService(
throw conflict("Only an idle browser can be kept open.");
} else {
if (terminalSessions.includes(s.status)) return;
await db
.update(sessions)
.set({
stopRequested: action,
...(action === "end" ? { status: "stopping" } : {}),
nextPollAt: new Date(),
updatedAt: new Date(),
})
.where(
and(
eq(sessions.id, s.id),
action === "cancel"
? or(
isNull(sessions.stopRequested),
ne(sessions.stopRequested, "end"),
)
: undefined,
),
);
await db.transaction(async tx => {
await notifyDeliveryWork(tx, DELIVERY_QUEUES.browser);
await tx
.update(sessions)
.set({
stopRequested: action,
...(action === "end" ? { status: "stopping" } : {}),
nextPollAt: new Date(),
updatedAt: new Date(),
})
.where(
and(
eq(sessions.id, s.id),
action === "cancel"
? or(
isNull(sessions.stopRequested),
ne(sessions.stopRequested, "end"),
)
: undefined,
),
);
});
}
await signal(
s,
@@ -1218,97 +1227,109 @@ export function browserUseService(
);
}
}
let sweeping = false;
async function sweep(connectionId?: string) {
if (sweeping) return;
sweeping = true;
try {
const due = await db
.select()
.from(sessions)
// Wait for a concurrent sweep rather than reporting completion while its
// lease is still held. A filtered cleanup must still inspect its own scope.
let sweeping: Promise<void> | null = null;
async function sweep(connectionId?: string): Promise<void> {
if (sweeping) {
await sweeping;
return sweep(connectionId);
}
sweeping = reconcileDue(connectionId);
try { await sweeping; } finally { sweeping = null; }
}
async function reconcileDue(connectionId?: string) {
const due = await db
.select()
.from(sessions)
.where(
and(
connectionId ? eq(sessions.connectionId, connectionId) : undefined,
inArray(sessions.status, liveSessions),
lte(sessions.nextPollAt, new Date()),
or(
isNull(sessions.leaseUntil),
lte(sessions.leaseUntil, new Date()),
),
),
)
.limit(30);
for (const s of due) {
const token = randomUUID();
const lease = await db
.update(sessions)
.set({
leaseToken: token,
leaseUntil: new Date(Date.now() + 180_000),
})
.where(
and(
connectionId ? eq(sessions.connectionId, connectionId) : undefined,
inArray(sessions.status, [
"starting",
"running",
"idle",
"stopping",
]),
lte(sessions.nextPollAt, new Date()),
eq(sessions.id, s.id),
or(
isNull(sessions.leaseUntil),
lte(sessions.leaseUntil, new Date()),
),
),
)
.limit(30);
for (const s of due) {
const token = randomUUID();
const lease = await db
.returning();
if (!lease.length) continue;
// Renew while paginating provider events or stopping multiple browsers.
const renewal = setInterval(() => {
void db
.update(sessions)
.set({ leaseUntil: new Date(Date.now() + 180_000) })
.where(and(eq(sessions.id, s.id), eq(sessions.leaseToken, token)))
.catch(() => {});
}, 30_000);
renewal.unref?.();
let delay = s.status === "idle" ? 15000 : 3000;
try {
await reconcile(s);
} catch (e) {
delay = Math.max(
10000,
e instanceof BrowserUseError ? e.retryAfterMs : 0,
);
await db
.update(sessions)
.set({
leaseToken: token,
leaseUntil: new Date(Date.now() + 180_000),
error:
s.stopRequested === "end"
? "Browser shutdown is not confirmed. Paperclip will retry."
: "Browser synchronization failed. Paperclip will retry.",
})
.where(
and(
eq(sessions.id, s.id),
or(
isNull(sessions.leaseUntil),
lte(sessions.leaseUntil, new Date()),
),
),
)
.returning();
if (!lease.length) continue;
// Renew while paginating provider events or stopping multiple browsers.
const renewal = setInterval(() => {
void db
.update(sessions)
.set({ leaseUntil: new Date(Date.now() + 180_000) })
.where(and(eq(sessions.id, s.id), eq(sessions.leaseToken, token)))
.catch(() => {});
}, 30_000);
renewal.unref?.();
let delay = s.status === "idle" ? 15000 : 3000;
try {
await reconcile(s);
} catch (e) {
delay = Math.max(
10000,
e instanceof BrowserUseError ? e.retryAfterMs : 0,
);
await db
.update(sessions)
.set({
error:
s.stopRequested === "end"
? "Browser shutdown is not confirmed. Paperclip will retry."
: "Browser synchronization failed. Paperclip will retry.",
})
.where(eq(sessions.id, s.id));
} finally {
clearInterval(renewal);
await db
.update(sessions)
.set({
leaseToken: null,
leaseUntil: null,
nextPollAt: new Date(
Date.now() + delay + Math.floor(Math.random() * 500),
),
})
.where(and(eq(sessions.id, s.id), eq(sessions.leaseToken, token)));
.where(eq(sessions.id, s.id));
} finally {
clearInterval(renewal);
const release = (tx: Pick<Db, "update">) => tx.update(sessions).set({
leaseToken: null,
leaseUntil: null,
nextPollAt: new Date(Date.now() + delay + Math.floor(Math.random() * 500)),
}).where(and(eq(sessions.id, s.id), eq(sessions.leaseToken, token)));
if (connectionId) {
// Credential-removal sweeps can race the app worker. Wake it when
// their lease ends so it does not wait for the old lease expiry.
await db.transaction(async tx => {
await notifyDeliveryWork(tx, DELIVERY_QUEUES.browser);
await release(tx);
});
} else {
await release(db);
}
}
} finally {
sweeping = false;
}
}
async function nextSweepAt(): Promise<number | null> {
const [row] = await db.select({
// An overdue row owned by another sweep cannot run before its lease ends.
at: sql<string | null>`min(greatest(${sessions.nextPollAt}, ${sessions.leaseUntil}))`,
}).from(sessions).where(inArray(sessions.status, liveSessions));
return row?.at == null ? null : new Date(row.at).getTime();
}
return {
execute,
sweep,
nextSweepAt,
list,
viewer,
resize,
@@ -1322,16 +1343,19 @@ export function browserUseService(
const scope = and(
eq(sessions.companyId, companyId),
eq(sessions.connectionId, connectionId),
inArray(sessions.status, ["starting", "running", "idle", "stopping"]),
inArray(sessions.status, liveSessions),
);
await db
.update(sessions)
.set({
stopRequested: "end",
nextPollAt: new Date(),
updatedAt: new Date(),
})
.where(scope);
await db.transaction(async tx => {
await notifyDeliveryWork(tx, DELIVERY_QUEUES.browser);
await tx
.update(sessions)
.set({
stopRequested: "end",
nextPollAt: new Date(),
updatedAt: new Date(),
})
.where(scope);
});
await sweep(connectionId);
const [pending] = await db
.select({ id: sessions.id })
@@ -2,6 +2,7 @@ import { signalDatabaseWork, subscribeDatabaseWork } from "@paperclipai/db";
/** Topics for existing durable queues; register intent before their writes. */
export const DELIVERY_QUEUES = {
browser: "browser-use",
email: "email-channels",
feedback: "feedback-exports",
chatCompletion: "chat-completions",
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,233 @@
import { randomUUID } from "node:crypto";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { agents, companies, completionContracts, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, heartbeatRuns, issues, nativeRunFinalizations, type Db } from "@paperclipai/db";
import { eq, sql } from "drizzle-orm";
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
import { CHAT_CONTROL_RECOVERY_ADMISSION_KEY } from "../chat-control-recovery-stop.js";
import { buildNativeRuntimeContext } from "../native-runtime/runtime-context.js";
import { nativeRuntimeContextFixture } from "../native-runtime/runtime-context.test-fixture.js";
import { prepareNativeWorkspaceSync } from "../native-runtime/native-workspace-sync.js";
import { resolveHeartbeatNativeRuntimeMode } from "../native-runtime/runtime-mode.js";
import { canonicalNativeRuntimeContextDigest } from "../../vendor/paperclip-runner/index.js";
import { selectHeartbeatRuntime, type HeartbeatRuntimeSelectionInput } from "./runtime-selection.js";
// Keep the real contract, session, and runtime-selection transactions. Replace only
// filesystem materialization and sandbox synchronization at their external boundaries.
vi.mock("../native-runtime/runtime-context.js", async (original) => ({
...await original<typeof import("../native-runtime/runtime-context.js")>(),
buildNativeRuntimeContext: vi.fn(async () => nativeRuntimeContextFixture()),
}));
vi.mock("../native-runtime/native-workspace-sync.js", async (original) => ({
...await original<typeof import("../native-runtime/native-workspace-sync.js")>(),
prepareNativeWorkspaceSync: vi.fn(async () => null),
}));
const support = await getEmbeddedPostgresTestSupport();
describe.skipIf(!support.supported)("heartbeat runtime selection boundary", () => {
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: Db;
let instructionRoot: string;
beforeAll(async () => {
instructionRoot = await mkdtemp(join(tmpdir(), "paperclip-selection-instructions-"));
await writeFile(join(instructionRoot, "AGENTS.md"), "Complete the assigned task.\n");
database = await startEmbeddedPostgresTestDatabase("paperclip-runtime-selection");
db = createDb(database.connectionString);
await db.execute(sql`set client_min_messages = warning`);
}, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
afterAll(async () => { await db?.$client.end(); await database?.cleanup(); if (instructionRoot) await rm(instructionRoot, { recursive: true, force: true }); });
beforeEach(async () => {
await db.execute(sql`truncate table companies restart identity cascade`);
vi.clearAllMocks();
vi.mocked(prepareNativeWorkspaceSync).mockResolvedValue(null);
vi.mocked(buildNativeRuntimeContext).mockImplementation(async () => {
const context = nativeRuntimeContextFixture();
context.instructions.bundle.rootPath = instructionRoot;
return { ...context, aggregateDigest: canonicalNativeRuntimeContextDigest(context) };
});
});
async function fixture(adapterType = "paperclip_runner") {
const [company] = await db.insert(companies).values({ name: "Runtime selection", issuePrefix: "SEL" }).returning();
const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Selecting agent", status: "running", adapterType, adapterConfig: { provider: "codex", model: "gpt-5.6-luna" } }).returning();
const [issue] = await db.insert(issues).values({ companyId: company.id, title: "Complete this task", description: "Preserve the requested work", assigneeAgentId: agent.id }).returning();
const [run] = await db.insert(heartbeatRuns).values({ companyId: company.id, agentId: agent.id, issueId: issue.id, scopeKind: "issue", status: "running" }).returning();
const now = new Date();
const input: HeartbeatRuntimeSelectionInput = {
run, agent,
nativeRuntimeResolution: resolveHeartbeatNativeRuntimeMode({ persisted: run, enabled: true, runtimeConfig: {}, adapterConfig: agent.adapterConfig, agent, issue, target: null, workspaceId: null }),
task: { issueRef: issue, issueContext: null, context: { paperclipTaskMarkdown: "Complete this task" }, executionContinuation: null, safeWakeComments: [], safeWakeCommentContext: null, paperclipWakePayload: null, acceptedPlanContinuationWake: false },
session: { persistedNativeExecutionInput: null, persistedRunnerProfile: {}, taskSessionCredentialCompatible: true, taskSessionDecodedParams: null, taskSessionForRun: null, isFailedChatRunRetry: false, getFreshSessionHandoff: vi.fn(async () => "Earlier context") },
workspace: { persistedExecutionWorkspace: null, executionWorkspace: { cwd: "/tmp/paperclip-runtime-selection", repoUrl: null, repoRef: null, branchName: null }, executionTarget: null, isDotRun: false, projectRepositoryPaths: [],
activeEnvironmentLease: { lease: { id: randomUUID(), companyId: company.id, environmentId: null, executionWorkspaceId: null, issueId: issue.id, heartbeatRunId: run.id, status: "active", leasePolicy: "ephemeral", provider: null, providerLeaseId: null, acquiredAt: now, lastUsedAt: now, expiresAt: null, releasedAt: null, failureReason: null, cleanupStatus: null, metadata: null, createdAt: now, updatedAt: now } },
},
config: { runtimeConfig: {}, runtimeSkillEntries: [], runScopedMentionedSkillKeys: [], instructionCopy: null, agentIdentity: undefined, issueAssigneeOverrides: null, resolvedConfig: {}, managedAiRuntime: undefined },
recovery: {}, trace: { providerTraceRequested: false, providerTraceCapture: null },
issuesSvc: { addComment: vi.fn() }, runtimeEnv: {}, onAdapterEvent: vi.fn(async () => {}),
onNativeLifecycleSelected: vi.fn(), onProviderResourceDisposition: vi.fn(), onNativeOwnershipHeld: vi.fn(), stopControllerLease: vi.fn(),
};
return { input, issue, run, agent };
}
const read = (id: string) => db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, id)).then(rows => rows[0]!);
const coordinators = (id: string) => db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, id));
const sandbox = { kind: "remote" as const, transport: "sandbox" as const, remoteCwd: "/workspace", reusableLeaseConfigured: false };
it("persists the native input, completion contract, and coordinator before transferring cleanup ownership", async () => {
const { input, run } = await fixture();
input.workspace.onCheckpoint = vi.fn(async () => {});
input.workspace.onPhase = async (_name, work) => work();
vi.mocked(prepareNativeWorkspaceSync).mockImplementationOnce(async args => {
expect(await read(run.id)).toMatchObject({ runtimeMode: "native", nativeIssueId: input.task.issueRef!.id });
expect(await coordinators(run.id)).toHaveLength(1);
expect(input.stopControllerLease).toHaveBeenCalledOnce();
expect(args).toMatchObject({ runId: run.id, workspaceId: run.id, workspaceLocalDir: input.workspace.executionWorkspace.cwd });
expect(args.onCheckpoint).toBe(input.workspace.onCheckpoint);
expect(args.onPhase).toBe(input.workspace.onPhase);
return null;
});
const selected = await selectHeartbeatRuntime(db, input);
expect(selected.selected).toBe(true);
if (!selected.selected) throw new Error("Expected selection");
const saved = await read(run.id);
expect(saved).toMatchObject({ runtimeMode: "native", driverKind: "codex_app_server", nativePhase: "observed", nativeSessionId: expect.any(String), runnerInstanceId: selected.nativeRunnerInstanceId,
runnerProfileJson: { nativeExecutionInput: selected.nativeExecution, recoveryEventInventoryVersion: 1 } });
expect(await db.select().from(completionContracts)).toHaveLength(1);
expect(selected.getNativeFreshSessionHandoff).toBe(input.session.getFreshSessionHandoff);
expect(input.onNativeOwnershipHeld).not.toHaveBeenCalled();
});
it("persists configured GitHub instruction skills without admitting provider-mentioned skills", async () => {
const { input, issue, run } = await fixture();
input.config.runScopedMentionedSkillKeys = ["company/test/configured"];
input.task.context.paperclipWake = {
reason: "External chat message received", externalChatProvider: "github", checkedOutByHarness: true,
issue: { id: issue.id, workMode: "standard" },
comments: [{ id: "review-comment", body: "Please use /provider-mentioned" }],
commentIds: ["review-comment"], latestCommentId: "review-comment",
commentWindow: { requestedCount: 1, includedCount: 1, missingCount: 0 }, fallbackFetchNeeded: false,
};
vi.mocked(buildNativeRuntimeContext).mockImplementationOnce(async () => {
const context = nativeRuntimeContextFixture();
context.instructions.bundle.rootPath = instructionRoot;
context.skills = ["configured", "provider-mentioned"].map(name => ({
key: `company/test/${name}`, runtimeName: name, versionId: null,
bundle: { ...context.instructions.bundle },
}));
return { ...context, aggregateDigest: canonicalNativeRuntimeContextDigest(context) };
});
expect(await selectHeartbeatRuntime(db, input)).toMatchObject({
selected: true, nativeExecution: { task: { description: "Configured GitHub instruction skills:\n/configured" } },
});
expect((await read(run.id)).runnerProfileJson).toMatchObject({
nativeExecutionInput: { task: { description: "Configured GitHub instruction skills:\n/configured" } },
});
});
it("restores the immutable admitted input and saved checkpoint when newer context arrives", async () => {
const { input, run } = await fixture();
const selected = await selectHeartbeatRuntime(db, input);
if (!selected.selected || !selected.nativeExecution) throw new Error("Expected native selection");
const saved = await read(run.id);
const profile = { ...saved.runnerProfileJson, sessionCheckpoint: { retained: "checkpoint" } };
await db.update(heartbeatRuns).set({ runnerProfileJson: profile }).where(eq(heartbeatRuns.id, run.id));
input.run = await read(run.id);
input.session.persistedRunnerProfile = profile;
input.session.persistedNativeExecutionInput = selected.nativeExecution;
input.task.context.paperclipTaskMarkdown = "A newer unrelated request";
input.task.safeWakeComments = [{ id: randomUUID(), body: "New direction belongs to a separate wake" }];
vi.mocked(buildNativeRuntimeContext).mockClear();
const resumed = await selectHeartbeatRuntime(db, input);
expect(resumed).toMatchObject({ selected: true, nativeExecution: selected.nativeExecution, nativeRunnerInstanceId: selected.nativeRunnerInstanceId });
expect((await read(run.id)).runnerProfileJson).toMatchObject(profile);
expect(await db.select().from(completionContracts)).toHaveLength(1);
expect(await coordinators(run.id)).toHaveLength(1);
expect(buildNativeRuntimeContext).not.toHaveBeenCalled();
});
it("rejects an admitted input bound to another run without replacing the saved runtime", async () => {
const { input, run } = await fixture();
const selected = await selectHeartbeatRuntime(db, input);
if (!selected.selected || !selected.nativeExecution) throw new Error("Expected native selection");
const saved = await read(run.id);
input.run = saved;
input.session.persistedNativeExecutionInput = { ...selected.nativeExecution, binding: { ...selected.nativeExecution.binding, runId: randomUUID() } };
await expect(selectHeartbeatRuntime(db, input)).rejects.toThrow("native_execution_input_persisted_binding_mismatch");
expect((await read(run.id)).runnerProfileJson).toEqual(saved.runnerProfileJson);
});
it.each(["cancelled", "startup_cancellation"])("does not create a native coordinator when %s wins preparation", async winner => {
const { input, run } = await fixture();
input.beforeNativeRuntimeSelection = async () => {
await db.update(heartbeatRuns).set(winner === "cancelled" ? { status: "cancelled" } : { resultJson: { startupCancellation: { beforeNativeSelection: true } } }).where(eq(heartbeatRuns.id, run.id));
};
expect(await selectHeartbeatRuntime(db, input)).toEqual({ selected: false });
expect(await read(run.id)).toMatchObject({ runtimeMode: "legacy", nativeSessionId: null, completionContractId: null });
expect(await coordinators(run.id)).toHaveLength(0);
expect(input.stopControllerLease).not.toHaveBeenCalled();
expect(prepareNativeWorkspaceSync).not.toHaveBeenCalled();
});
it("reports a lost controller lease before returning without native selection", async () => {
const { input, run } = await fixture();
await db.update(heartbeatRuns).set({ controllerBootId: randomUUID(), controllerLeaseExpiresAt: new Date(Date.now() + 60_000) }).where(eq(heartbeatRuns.id, run.id));
expect(await selectHeartbeatRuntime(db, input)).toEqual({ selected: false });
expect(input.onNativeOwnershipHeld).toHaveBeenCalledOnce();
expect(input.stopControllerLease).not.toHaveBeenCalled();
expect(await coordinators(run.id)).toHaveLength(0);
});
it("rejects a competing persisted legacy selection atomically", async () => {
const { input, run } = await fixture();
input.beforeNativeRuntimeSelection = async () => {
await db.update(heartbeatRuns).set({ runtimeModeResolvedAt: new Date(), runtimeMode: "legacy" }).where(eq(heartbeatRuns.id, run.id));
};
await expect(selectHeartbeatRuntime(db, input)).rejects.toThrow("native_runtime_mode_conflict");
expect((await read(run.id)).runtimeMode).toBe("legacy");
expect(await coordinators(run.id)).toHaveLength(0);
expect(input.stopControllerLease).not.toHaveBeenCalled();
});
it("reports sandbox teardown policy even when a later preparation step throws", async () => {
const { input, run } = await fixture();
input.workspace.executionTarget = sandbox;
input.beforeNativeRuntimeSelection = async () => { throw new Error("selection interrupted"); };
await expect(selectHeartbeatRuntime(db, input)).rejects.toThrow("selection interrupted");
expect(input.onNativeLifecycleSelected).toHaveBeenCalledWith({ provider: "codex", harness: "codex_app_server", lifecycleMode: "per_turn", sandboxResource: "destroy_after_turn" });
expect(input.onProviderResourceDisposition).toHaveBeenCalledWith("destroy");
expect(input.stopControllerLease).not.toHaveBeenCalled();
expect(await coordinators(run.id)).toHaveLength(0);
});
it("retains native admission and teardown state if workspace sync preparation fails", async () => {
const { input, run } = await fixture();
input.workspace.executionTarget = sandbox;
vi.mocked(prepareNativeWorkspaceSync).mockRejectedValueOnce(new Error("sync preparation failed"));
await expect(selectHeartbeatRuntime(db, input)).rejects.toThrow("sync preparation failed");
expect(input.onProviderResourceDisposition).toHaveBeenCalledWith("destroy");
expect(input.stopControllerLease).toHaveBeenCalledOnce();
expect((await read(run.id)).runtimeMode).toBe("native");
expect(await coordinators(run.id)).toHaveLength(1);
});
it("rejects a warm native sandbox that cannot reuse its lease", async () => {
const { input, run } = await fixture();
input.workspace.executionTarget = { ...sandbox, runnerLifecyclePolicy: { mode: "warm", idleTimeoutMs: 300_000 } };
await expect(selectHeartbeatRuntime(db, input)).rejects.toThrow("runner_warm_environment_requires_reusable_lease");
expect(input.onNativeLifecycleSelected).not.toHaveBeenCalled();
expect(await coordinators(run.id)).toHaveLength(0);
});
it("preserves only server-owned admission and dispatch evidence when recording legacy selection", async () => {
const { input, run } = await fixture("process");
const admission = { version: 1, kind: "fixture" }, dispatch = { entered: true };
await db.update(heartbeatRuns).set({ runnerProfileJson: { [CHAT_CONTROL_RECOVERY_ADMISSION_KEY]: admission, adapterDispatch: dispatch, unrelated: "drop" } }).where(eq(heartbeatRuns.id, run.id));
input.trace = { providerTraceRequested: true, providerTraceCapture: { metadata: { id: "trace-id" } } };
expect(await selectHeartbeatRuntime(db, input)).toMatchObject({ selected: true, nativeExecution: null, nativeWorkspaceSync: null });
expect((await read(run.id)).runnerProfileJson).toEqual({ [CHAT_CONTROL_RECOVERY_ADMISSION_KEY]: admission, adapterDispatch: dispatch, providerTrace: { mode: "raw", traceId: "trace-id", maxBytes: 64 * 1024 * 1024 } });
expect(await coordinators(run.id)).toHaveLength(0);
expect(input.stopControllerLease).not.toHaveBeenCalled();
expect(buildNativeRuntimeContext).not.toHaveBeenCalled();
});
});
File diff suppressed because it is too large. Load diff
@@ -461,7 +461,7 @@ describe("capability-gated connection tool refresh", () => {
it("wires exact-session recovery and guarded selected identity into heartbeat persistence", () => {
const source = readFileSync(
new URL("../heartbeat.ts", import.meta.url),
new URL("../heartbeat/runtime-selection.ts", import.meta.url),
"utf8",
);
expect(source).toContain("await findNativeSessionResumeRun(db,");