From 35511366dcbe359626de9a698c71b7a583432a2b Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:06:31 -0500 Subject: [PATCH] perf(server): schedule browser cleanup only while sessions exist (#15757) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 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 --- doc/connections/BROWSER-USE.md | 7 +- ...-instance-sleep-and-scheduler-inventory.md | 12 +- .../__tests__/browser-use-connection.test.ts | 43 ++++ server/src/__tests__/browser-use-work.test.ts | 108 +++++++++ server/src/app.ts | 9 +- server/src/services/browser-use-work.ts | 23 ++ server/src/services/browser-use.ts | 226 ++++++++++-------- .../services/delivery-work-notifications.ts | 1 + 8 files changed, 316 insertions(+), 113 deletions(-) create mode 100644 server/src/__tests__/browser-use-work.test.ts create mode 100644 server/src/services/browser-use-work.ts diff --git a/doc/connections/BROWSER-USE.md b/doc/connections/BROWSER-USE.md index 72104d93981..1a1a3c7769e 100644 --- a/doc/connections/BROWSER-USE.md +++ b/doc/connections/BROWSER-USE.md @@ -72,7 +72,12 @@ runs and browser instances. Each hosted run records its invocation, parent run, event cursor and cost checkpoint. A leased reconciler polls minimal status, drains bounded event pages, discovers browser instances by conversation, and checks each instance's authoritative conversation association. Restarting the -server resumes reconciliation. A lost paid-create response becomes an explicit +server resumes reconciliation. The app schedules the next check from saved +session deadlines and cleanup leases. Session writes wake it after commit. +With no live sessions it performs no recurring browser database scan. Existing +sessions still poll provider state (about three seconds while running, fifteen +while idle), enforce expiry and access changes, and retry failed cleanup. +A lost paid-create response becomes an explicit unknown outcome and is never submitted again automatically; the operator must inspect Browser Use before starting replacement work. diff --git a/doc/plans/2026-10-08-instance-sleep-and-scheduler-inventory.md b/doc/plans/2026-10-08-instance-sleep-and-scheduler-inventory.md index 0646390908a..24db42b22ac 100644 --- a/doc/plans/2026-10-08-instance-sleep-and-scheduler-inventory.md +++ b/doc/plans/2026-10-08-instance-sleep-and-scheduler-inventory.md @@ -438,10 +438,14 @@ Longer polling intervals alone do not complete an item. catch-up remain the recovery boundaries. Source: [email-channels.ts](../../server/src/services/email-channels.ts). -- [ ] **JOB-03 — Browser-use cleanup.** Current: every **3s** with due-session - queries even when empty. Change: register actual session reconciliation/expiry - deadlines. **Complete when:** no sessions means no queries, while active leases, - expiry, and failed cleanup remain recoverable. Sources: +- [x] **JOB-03 — Browser-use cleanup.** Replaced the empty **3s** scan with + transaction-aware session signals and deadlines from existing `nextPollAt` and + `leaseUntil` columns. Startup restores unfinished work; no live sessions means + no recurring browser SQL or timer. Active and idle sessions retain provider + polling, expiry checks, lease renewal, and cleanup retries. Credential-removal + sweeps signal lease release so background cleanup resumes promptly. Standby + suppresses SQL; idle drain defers dispatch with a memory-only wake. No new + tables. Independent DB roots/direct SQL require restart recovery. Sources: [app.ts](../../server/src/app.ts), [browser-use.ts](../../server/src/services/browser-use.ts). diff --git a/server/src/__tests__/browser-use-connection.test.ts b/server/src/__tests__/browser-use-connection.test.ts index b206fabe93c..f9282b9f082 100644 --- a/server/src/__tests__/browser-use-connection.test.ts +++ b/server/src/__tests__/browser-use-connection.test.ts @@ -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); diff --git a/server/src/__tests__/browser-use-work.test.ts b/server/src/__tests__/browser-use-work.test.ts new file mode 100644 index 00000000000..ae8a2dfbec2 --- /dev/null +++ b/server/src/__tests__/browser-use-work.test.ts @@ -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[] = []; +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) { + 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 => 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); + }); +}); diff --git a/server/src/app.ts b/server/src/app.ts index bce7324803c..c622f62e27c 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -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 | null = setInterval( sweepImportTransferSpools, @@ -1408,7 +1404,6 @@ export async function createApp( chatPublicationTimer = null; } await chatReconciliation.drain(); - clearInterval(browserUseTimer); if (importTransferSweepTimer) { clearInterval(importTransferSweepTimer); importTransferSweepTimer = null; diff --git a/server/src/services/browser-use-work.ts b/server/src/services/browser-use-work.ts new file mode 100644 index 00000000000..ae8c7a36244 --- /dev/null +++ b/server/src/services/browser-use-work.ts @@ -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, + service: { sweep(): Promise; nextSweepAt(): Promise }, + 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), + }); +} diff --git a/server/src/services/browser-use.ts b/server/src/services/browser-use.ts index 849b1d8bb08..683fe107ca8 100644 --- a/server/src/services/browser-use.ts +++ b/server/src/services/browser-use.ts @@ -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 | null = null; + async function sweep(connectionId?: string): Promise { + 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) => 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 { + const [row] = await db.select({ + // An overdue row owned by another sweep cannot run before its lease ends. + at: sql`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 }) diff --git a/server/src/services/delivery-work-notifications.ts b/server/src/services/delivery-work-notifications.ts index d9696da5cf2..42bed21ae4d 100644 --- a/server/src/services/delivery-work-notifications.ts +++ b/server/src/services/delivery-work-notifications.ts @@ -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",