Skip to content

Commit ec443e6

Browse files
authored
fix: cancel delegated browser observations with task execution (#31)
* fix: port cancellation browser.ts * fix: port cancellation browser.test.ts * fix: port cancellation model-worker.test.ts * fix: propagate cancellation through model.ts * fix: propagate cancellation through service.ts
1 parent cdabf8b commit ec443e6

5 files changed

Lines changed: 104 additions & 8 deletions

File tree

‎apps/server/src/browser.ts‎

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ export class BrowserService {
125125
await this.db.put(owner, "browsers", session);
126126
return this.decorate(owner, session);
127127
}
128-
async create(owner: string, url: string) {
128+
async create(owner: string, url: string, signal?: AbortSignal) {
129129
const id = randomUUID();
130130
// Record ownership before calling the worker, including when its response is lost.
131131
await this.db.put(owner, "browsers", {
@@ -135,7 +135,7 @@ export class BrowserService {
135135
status: "idle",
136136
updatedAt: new Date().toISOString(),
137137
});
138-
return this.reopen(owner, id, url);
138+
return this.reopen(owner, id, url, signal);
139139
}
140140
private async openOwned(owner: string, id: string, url?: string, signal?: AbortSignal) {
141141
const value = await this.get(owner, id);
@@ -144,6 +144,7 @@ export class BrowserService {
144144
const response = await this.request("/sessions", { id, url: target }, signal);
145145
return await this.save(owner, await response.json(), id);
146146
} catch (error) {
147+
signal?.throwIfAborted();
147148
await this.save(
148149
owner,
149150
{ ...value, url: target, status: "error", updatedAt: new Date().toISOString() },
@@ -152,8 +153,8 @@ export class BrowserService {
152153
throw error;
153154
}
154155
}
155-
reopen(owner: string, id: string, url?: string) {
156-
return this.serial(id, () => this.openOwned(owner, id, url));
156+
reopen(owner: string, id: string, url?: string, signal?: AbortSignal) {
157+
return this.serial(id, () => this.openOwned(owner, id, url, signal));
157158
}
158159
navigate(owner: string, id: string, url: string) {
159160
return this.reopen(owner, id, url);
@@ -181,11 +182,13 @@ export class BrowserService {
181182
read(owner: string, id: string) {
182183
return this.serial(id, () => this.readOwned(owner, id));
183184
}
184-
async observe(owner: string, url: string, existingId?: string) {
185-
const id = existingId ?? (await this.create(owner, url)).id;
185+
async observe(owner: string, url: string, existingId?: string, signal?: AbortSignal) {
186+
const id = existingId ?? (await this.create(owner, url, signal)).id;
186187
return this.serial(id, async () => {
187-
if (existingId) await this.openOwned(owner, id, url);
188-
return { sessionId: id, ...(await this.readOwned(owner, id)) };
188+
signal?.throwIfAborted();
189+
if (existingId) await this.openOwned(owner, id, url, signal);
190+
signal?.throwIfAborted();
191+
return { sessionId: id, ...(await this.readOwned(owner, id, signal)) };
189192
});
190193
}
191194
async observeForThread(owner: string, threadId: string, url: string, signal?: AbortSignal) {

‎apps/server/src/engine/model.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,7 @@ export async function executeModelTask(
199199
owner,
200200
url,
201201
typeof task.state.browserId === "string" ? task.state.browserId : undefined,
202+
ctx.signal,
202203
);
203204
task = await ctx.checkpoint({
204205
state: { ...task.state, browserId: page.sessionId },

‎apps/server/src/engine/service.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1047,6 +1047,7 @@ export class AgentService {
10471047
owner,
10481048
monitor.url,
10491049
typeof task.state.sessionId === "string" ? task.state.sessionId : undefined,
1050+
ctx.signal,
10501051
);
10511052
}
10521053
const text = observation.text.replace(/\s+/g, " ").trim();

‎tests/browser.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,22 @@ test("browser observations reuse an owned profile and reject unowned reads", asy
158158
assert.equal(fresh.text, read.text);
159159
});
160160

161+
test("cancelled task-style browser observations stop before a follow-up read", async (t) => {
162+
const controller = new AbortController();
163+
const calls: string[] = [];
164+
const { db, service } = await browserFixture(t, (path, body) => {
165+
calls.push(path);
166+
controller.abort();
167+
return { data: { ...savedSession, id: body.id, url: body.url } };
168+
});
169+
await assert.rejects(service.observe("owner", savedSession.url, undefined, controller.signal), {
170+
name: "AbortError",
171+
});
172+
assert.deepEqual(calls, ["/sessions"]);
173+
const [saved] = await db.list<BrowserSession>("owner", "browsers");
174+
assert.equal(saved?.status, "idle", "cancellation must not persist a browser failure");
175+
});
176+
161177
test("chat browser reads reuse a persisted owned profile across turns and service restarts", async (t) => {
162178
const calls: { path: string; body: Record<string, unknown> }[] = [];
163179
let currentUrl = savedSession.url;

‎tests/model-worker.test.ts‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import assert from "node:assert/strict";
2+
import { once } from "node:events";
23
import { mkdtemp, rm } from "node:fs/promises";
4+
import { createServer } from "node:http";
35
import { tmpdir } from "node:os";
46
import { join } from "node:path";
57
import { test } from "node:test";
@@ -291,3 +293,76 @@ test("browser reads keep observation identity distinct while reusing one session
291293
assert.equal(sessionIds.size, 1, "both reads should reuse the same browser session");
292294
assert.equal(new Set(webEvidence.map((item) => item.id)).size, 2);
293295
});
296+
297+
test("aborting delegated read_web stops before page read and requeues the task", async (t) => {
298+
const directory = await mkdtemp(join(tmpdir(), "openmuse-model-browser-abort-"));
299+
const db = await createStore();
300+
const browserCalls: string[] = [];
301+
let resolveNavigation!: () => void;
302+
const navigationStarted = new Promise<void>((resolve) => {
303+
resolveNavigation = resolve;
304+
});
305+
const browserWorker = createServer(async (request, response) => {
306+
for await (const _chunk of request) {
307+
// Drain the request body before holding the navigation response open.
308+
}
309+
const path = request.url ?? "";
310+
browserCalls.push(path);
311+
if (path === "/sessions") {
312+
resolveNavigation();
313+
return;
314+
}
315+
response.writeHead(200, { "content-type": "application/json" });
316+
response.end(
317+
JSON.stringify({
318+
url: "https://example.org/",
319+
title: "Observed",
320+
text: "This read must never happen after abort.",
321+
truncated: false,
322+
}),
323+
);
324+
});
325+
browserWorker.listen(0, "127.0.0.1");
326+
await once(browserWorker, "listening");
327+
const address = browserWorker.address();
328+
assert.ok(address && typeof address !== "string");
329+
330+
await modelFixture(t, (index) =>
331+
index === 0 ? { name: "read_web", arguments: { url: "https://example.org/" } } : undefined,
332+
);
333+
const server = await createApp(db, {
334+
mode: "sample",
335+
port: 8787,
336+
host: "127.0.0.1",
337+
publicUrl: "http://localhost:8787",
338+
dataDir: directory,
339+
agentBackend: "model",
340+
intelligenceApiKey: "test-project-key-never-sent",
341+
model: "openai/fixture",
342+
googleRedirectUri: "http://localhost:8787/api/google/callback",
343+
allowedOrigins: [],
344+
workerUrl: `http://127.0.0.1:${address.port}`,
345+
workerToken: "test-worker-token-at-least-32-characters",
346+
});
347+
348+
try {
349+
const task = await server.agent.createTask("owner", {
350+
prompt: "Read the example page and summarize it",
351+
});
352+
const tick = server.agent.worker.tick();
353+
await navigationStarted;
354+
server.agent.worker.abort(task.id);
355+
await tick;
356+
357+
const settled = await server.agent.getTask("owner", task.id);
358+
assert.equal(settled.status, "queued", settled.error ?? settled.result);
359+
assert.equal(settled.error, undefined);
360+
assert.deepEqual(browserCalls, ["/sessions"]);
361+
} finally {
362+
await server.agent.stop();
363+
browserWorker.closeAllConnections();
364+
await new Promise<void>((resolve) => browserWorker.close(() => resolve()));
365+
await db.close();
366+
await rm(directory, { recursive: true, force: true });
367+
}
368+
});

0 commit comments

Comments
 (0)