Skip to content

Commit 5f9afdb

Browse files
committed
fix(server): desktop attach timeouts no longer split browser pages
1 parent ed0f7b9 commit 5f9afdb

2 files changed

Lines changed: 299 additions & 32 deletions

File tree

‎apps/server/src/preview/ServerBrowser.test.ts‎

Lines changed: 200 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,11 @@ vi.mock("./ServerBrowserContexts.ts", () => ({
5151
}
5252
async connectDesktopPage(endpoint: string) {
5353
const context = makeContext();
54-
desktopConnections.push({ endpoint, context });
55-
return { browser: { close: async () => {} }, page: context.page as unknown as Page };
54+
const close = vi.fn(async () => desktopConnectionClosed?.resolve());
55+
desktopConnections.push({ endpoint, context, close });
56+
desktopConnectionStarted?.resolve();
57+
await desktopConnectionGate?.promise;
58+
return { browser: { close }, page: context.page as unknown as Page };
5659
}
5760
async close() {
5861
for (const context of contexts) await context.close();
@@ -158,6 +161,10 @@ let clipboardBinding: ClipboardBinding | null = null;
158161
let contextFailure: Error | null = null;
159162
/** Server tabs the fake desktop renders, and the endpoints the server connected to. */
160163
let desktopRendersNext = false;
164+
let desktopAvailable = false;
165+
let desktopConnectionGate: PromiseWithResolvers<void> | null = null;
166+
let desktopConnectionStarted: PromiseWithResolvers<void> | null = null;
167+
let desktopConnectionClosed: PromiseWithResolvers<void> | null = null;
161168
/** Pages the fake desktop takes back or returns; the channel's streams emit them. */
162169
const desktopDetaches = new NodeEvents.EventEmitter();
163170
const desktopTabs = new Set<string>();
@@ -169,7 +176,11 @@ const desktopRenders = (tabId: string) => {
169176
return desktopTabs.has(tabId);
170177
};
171178
const releasedDesktopTabs: Array<string> = [];
172-
const desktopConnections: Array<{ endpoint: string; context: ReturnType<typeof makeContext> }> = [];
179+
const desktopConnections: Array<{
180+
endpoint: string;
181+
context: ReturnType<typeof makeContext>;
182+
close: ReturnType<typeof vi.fn>;
183+
}> = [];
173184
const testThread = {
174185
threadId: ThreadId.make("browser-test-thread"),
175186
providerSessionId: "agent-a",
@@ -200,8 +211,10 @@ const dependencies = Layer.mergeAll(
200211
installed: Effect.die("mock Chromium does not need an executable"),
201212
}),
202213
Layer.succeed(DesktopChannel.DesktopBrowserChannel, {
203-
// Only tabs a test marks render on the desktop; the rest stay headless.
204-
available: true,
214+
// Standalone tests have no desktop; native tests explicitly enable it.
215+
get available() {
216+
return desktopAvailable || desktopRendersNext || desktopTabs.size > 0;
217+
},
205218
awaitAttached: (key) => Effect.sync(() => desktopRenders(key.tabId)),
206219
detached: Stream.callback<{ threadId: string; tabId: string }>((queue) =>
207220
Effect.acquireRelease(
@@ -274,6 +287,10 @@ beforeEach(() => {
274287
contextFailure = null;
275288
desktopTabs.clear();
276289
desktopRendersNext = false;
290+
desktopAvailable = false;
291+
desktopConnectionGate = null;
292+
desktopConnectionStarted = null;
293+
desktopConnectionClosed = null;
277294
releasedDesktopTabs.length = 0;
278295
desktopConnections.length = 0;
279296
});
@@ -1310,6 +1327,184 @@ it.live("viewers see the agent's pointer move to its target and click there", ()
13101327
).pipe(Effect.provide(layer)),
13111328
);
13121329

1330+
it.live("a late native attachment retries the same tab without opening headless", () =>
1331+
Effect.scoped(
1332+
Effect.gen(function* () {
1333+
const broker = yield* Broker.PreviewAutomationBroker;
1334+
const manager = yield* Manager.PreviewManager;
1335+
yield* Effect.yieldNow;
1336+
desktopAvailable = true;
1337+
const failure = yield* broker
1338+
.invoke<PreviewAutomationStatus>({
1339+
scope,
1340+
operation: "open",
1341+
input: { reuseExistingTab: false, show: false },
1342+
})
1343+
.pipe(Effect.flip);
1344+
expect(failure).toMatchObject({
1345+
_tag: "PreviewAutomationExecutionError",
1346+
message: expect.stringContaining("in-app browser tab has not attached"),
1347+
});
1348+
const { sessions } = yield* manager.list({ threadId: scope.thread.threadId });
1349+
expect(sessions).toHaveLength(1);
1350+
const pending = yield* broker.invoke<PreviewAutomationStatus>({
1351+
scope,
1352+
operation: "status",
1353+
input: {},
1354+
});
1355+
const tabId = PreviewTabId.make(sessions[0]!.tabId);
1356+
expect(pending).toMatchObject({ available: false, tabId });
1357+
expect(pending.tabs).toEqual([
1358+
expect.objectContaining({ tabId, owner: "agent", ownedByCaller: true }),
1359+
]);
1360+
expect(contexts).toEqual([]);
1361+
expect(contextRequests).toEqual([]);
1362+
for (const operation of ["open", "evaluate"] as const) {
1363+
expect(
1364+
yield* broker
1365+
.invoke({
1366+
scope,
1367+
tabId,
1368+
operation,
1369+
input: operation === "open" ? { reuseExistingTab: true } : { expression: "42" },
1370+
})
1371+
.pipe(Effect.flip),
1372+
).toMatchObject({
1373+
_tag: "PreviewAutomationExecutionError",
1374+
message: expect.stringContaining("in-app browser tab has not attached"),
1375+
});
1376+
}
1377+
expect((yield* manager.list({ threadId: scope.thread.threadId })).sessions).toHaveLength(1);
1378+
expect(contexts).toEqual([]);
1379+
desktopTabs.add(tabId);
1380+
desktopDetaches.emit("attach", { threadId: scope.thread.threadId, tabId });
1381+
const retried = yield* broker.invoke<PreviewAutomationStatus>({
1382+
scope,
1383+
tabId,
1384+
operation: "open",
1385+
input: { reuseExistingTab: true, show: false },
1386+
});
1387+
expect(retried).toMatchObject({ available: true, tabId });
1388+
expect(desktopConnections).toHaveLength(1);
1389+
expect(contexts).toEqual([]);
1390+
expect((yield* manager.list({ threadId: scope.thread.threadId })).sessions).toHaveLength(1);
1391+
}),
1392+
).pipe(Effect.provide(layer)),
1393+
);
1394+
1395+
it.live("only the owning agent can close a native tab that has not attached", () =>
1396+
Effect.scoped(
1397+
Effect.gen(function* () {
1398+
const broker = yield* Broker.PreviewAutomationBroker;
1399+
const manager = yield* Manager.PreviewManager;
1400+
yield* Effect.yieldNow;
1401+
desktopAvailable = true;
1402+
yield* broker
1403+
.invoke<PreviewAutomationStatus>({
1404+
scope,
1405+
operation: "open",
1406+
input: { reuseExistingTab: false, show: false },
1407+
})
1408+
.pipe(Effect.flip);
1409+
const { sessions } = yield* manager.list({ threadId: scope.thread.threadId });
1410+
const tabId = PreviewTabId.make(sessions[0]!.tabId);
1411+
expect(
1412+
yield* broker
1413+
.invoke<void>({
1414+
scope: asSession("another-agent"),
1415+
tabId,
1416+
operation: "close",
1417+
input: {},
1418+
})
1419+
.pipe(Effect.flip),
1420+
).toMatchObject({
1421+
_tag: "PreviewAutomationControlInterruptedError",
1422+
reason: "agentMismatch",
1423+
});
1424+
// Status makes the pending tab current, so the owner can close without an explicit ID.
1425+
yield* broker.invoke({ scope, operation: "status", input: {} });
1426+
yield* broker.invoke({ scope, operation: "close", input: {} });
1427+
expect((yield* manager.list({ threadId: scope.thread.threadId })).sessions).toEqual([]);
1428+
expect(contexts).toEqual([]);
1429+
const queried = Promise.withResolvers<void>();
1430+
const list = manager.list;
1431+
vi.spyOn(manager, "list").mockImplementation((input) =>
1432+
list(input).pipe(Effect.tap(() => Effect.sync(() => queried.resolve()))),
1433+
);
1434+
desktopTabs.add(tabId);
1435+
desktopDetaches.emit("attach", { threadId: scope.thread.threadId, tabId });
1436+
yield* Effect.promise(() => queried.promise);
1437+
expect(desktopConnections).toEqual([]);
1438+
}),
1439+
).pipe(Effect.provide(layer)),
1440+
);
1441+
1442+
it.live("closing a pending native session cancels its connection already in flight", () =>
1443+
Effect.scoped(
1444+
Effect.gen(function* () {
1445+
const broker = yield* Broker.PreviewAutomationBroker;
1446+
const manager = yield* Manager.PreviewManager;
1447+
yield* Effect.yieldNow;
1448+
desktopAvailable = true;
1449+
yield* broker
1450+
.invoke({ scope, operation: "open", input: { reuseExistingTab: false, show: false } })
1451+
.pipe(Effect.flip);
1452+
const { sessions } = yield* manager.list({ threadId: scope.thread.threadId });
1453+
const tabId = PreviewTabId.make(sessions[0]!.tabId);
1454+
const connecting = Promise.withResolvers<void>();
1455+
const connected = Promise.withResolvers<void>();
1456+
const disconnected = Promise.withResolvers<void>();
1457+
desktopConnectionStarted = connecting;
1458+
desktopConnectionGate = connected;
1459+
desktopConnectionClosed = disconnected;
1460+
desktopTabs.add(tabId);
1461+
desktopDetaches.emit("attach", { threadId: scope.thread.threadId, tabId });
1462+
yield* Effect.promise(() => connecting.promise);
1463+
const closingStarted = Promise.withResolvers<void>();
1464+
const closeCommitted = Promise.withResolvers<void>();
1465+
const close = manager.close;
1466+
vi.spyOn(manager, "close").mockImplementationOnce((input) =>
1467+
Effect.promise(async () => {
1468+
closingStarted.resolve();
1469+
await closeCommitted.promise;
1470+
}).pipe(Effect.andThen(close(input))),
1471+
);
1472+
yield* Effect.addFinalizer(() =>
1473+
Effect.sync(() => {
1474+
connected.resolve();
1475+
closeCommitted.resolve();
1476+
}),
1477+
);
1478+
const closing = yield* broker
1479+
.invoke({ scope, tabId, operation: "close", input: {} })
1480+
.pipe(Effect.forkScoped);
1481+
yield* Effect.promise(() => closingStarted.promise);
1482+
connected.resolve();
1483+
// The page connection tears down before the manager close can publish.
1484+
yield* Effect.promise(() => disconnected.promise);
1485+
expect(desktopConnections[0]!.close).toHaveBeenCalledOnce();
1486+
closeCommitted.resolve();
1487+
yield* Fiber.join(closing);
1488+
expect((yield* manager.list({ threadId: scope.thread.threadId })).sessions).toEqual([]);
1489+
expect(contexts).toEqual([]);
1490+
}),
1491+
).pipe(Effect.provide(layer)),
1492+
);
1493+
1494+
it.live("a standalone server still opens a headless page when no desktop channel exists", () =>
1495+
Effect.scoped(
1496+
Effect.gen(function* () {
1497+
const { broker, tabId } = yield* ready;
1498+
expect(desktopAvailable).toBe(false);
1499+
expect(contexts).toHaveLength(1);
1500+
expect(desktopConnections).toEqual([]);
1501+
expect(
1502+
yield* broker.invoke({ scope, tabId, operation: "evaluate", input: { expression: "42" } }),
1503+
).toBe("evaluated");
1504+
}),
1505+
).pipe(Effect.provide(layer)),
1506+
);
1507+
13131508
it.live("drives the desktop's own page for a tab the desktop renders", () =>
13141509
Effect.scoped(
13151510
Effect.gen(function* () {

0 commit comments

Comments
 (0)