Skip to content

The open-source app everyone uses to manage agents at work

perf(server): schedule browser cleanup only while sessions exist (#15757)

Dotta35511366dcbe
diff --git a/doc/connections/BROWSER-USE.md b/doc/connections/BROWSER-USE.md
index 72104d9398..1a1a3c7769 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 0646390908..24db42b22a 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 b206fabe93..f9282b9f08 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 0000000000..ae8a2dfbec
--- /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<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);
+ });
+});
diff --git a/server/src/app.ts b/server/src/app.ts
index bce7324803..c622f62e27 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<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;
diff --git a/server/src/services/browser-use-work.ts b/server/src/services/browser-use-work.ts
new file mode 100644
index 0000000000..ae8c7a3624
--- /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<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),
+ });
+}
diff --git a/server/src/services/browser-use.ts b/server/src/services/browser-use.ts
index 849b1d8bb0..683fe107ca 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<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 })
diff --git a/server/src/services/delivery-work-notifications.ts b/server/src/services/delivery-work-notifications.ts
index d9696da5cf..42bed21ae4 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",