mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 23:56:43 +01:00
perf(server): schedule browser cleanup only while sessions exist (#15757)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Hosted instances must become quiet when they have no work. > - Browser Use queried its session table every three seconds, even when empty. > - Existing session rows already store the next poll time and cleanup lease. > - This pull request uses commit signals and those saved deadlines to schedule cleanup. > - Empty instances stop browser database scans. Live sessions keep their safety checks. ## Linked Issues or Issue Description **What existing behavior does this improve?** Browser Use background cleanup and recovery. This follows #15625 and #15750. **Subsystem affected** server/ — REST API and orchestration services. **Current behavior** The app scans for due sessions every three seconds, including instances that have never used Browser Use. **Proposed behavior** Scan once at startup. Wake after session creation, provider-create settlement, stop requests, or credential-removal cleanup. Schedule the next check from `nextPollAt` and `leaseUntil`. Stop scheduling when all sessions are terminal. **Reason and benefit** Remove empty database traffic so idle stacks and their database connections can become quiet. **Breaking changes** No API or schema change. Running and idle sessions retain provider polling, cost accounting, access checks, expiry checks, and cleanup retries. ## What Changed - Register browser cleanup with the existing work coordinator. Remove the app's three-second interval. - Signal existing session transactions before writes. No new tables or provider infrastructure. - Restore deadlines from live sessions and their leases. Wake after a credential-removal sweep releases its lease. - Wait for concurrent cleanup instead of returning while it still runs. Drain and standby preserve deferred work. - Add scheduler tests and database-backed commit and restart coverage. Update the connector guide and sleep inventory. ## Verification - Passed: focused browser worker and shared coordinator tests, 17 tests. - Passed: browser lifecycle, route-scope, viewport, and transport tests, 50 tests. The lifecycle suite uses real local Postgres and a simulated provider. - Passed: `pnpm -r typecheck` and `pnpm build`. - Passed: all hosted test groups for this commit. Started full local `pnpm test:run`, then stopped its duplicate serial run after the complete hosted sharded suite passed; no full local-suite pass is claimed. - Passed: direct server TypeScript check. Greptile reviewed `99c3217a2dea505be94081e729941e542e6fbc03` at 5/5 with no findings. All 54 applicable hosted checks passed; the two Storybook checks were skipped because this PR has no UI changes. ## Risks - Process-local signals cover services that share the instrumented database owner. Independent processes and direct SQL writes require startup recovery; this does not add cross-process notification. - Live sessions still poll. This removes empty scans; it does not make a running hosted browser sleep. - Cleanup uses the existing provider protocol and lease fences. Tests simulate the provider; no paid live browser was created for this scheduling change. ## Model Used OpenAI Codex, GPT-6, with reasoning, tool use, and code execution. The exact deployment model ID and context window are not exposed in this session. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
eedf25655b
commit
35511366dc
8 files changed
+316
-113
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);
|
||||
});
|
||||
});
|
||||
+2
-7
@@ -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";
|
||||
@@ -1290,12 +1291,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,
|
||||
@@ -1408,7 +1404,6 @@ export async function createApp(
|
||||
chatPublicationTimer = null;
|
||||
}
|
||||
await chatReconciliation.drain();
|
||||
clearInterval(browserUseTimer);
|
||||
if (importTransferSweepTimer) {
|
||||
clearInterval(importTransferSweepTimer);
|
||||
importTransferSweepTimer = null;
|
||||
|
||||
@@ -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
@@ -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",
|
||||
|
||||
Reference in new issue
Block a user