Open History to see the last commit
1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as Layer from "effect/Layer";
4import { expect, it } from "@effect/vitest";
5import {
6 EnvironmentId,
7 PreviewAutomationClientDisconnectedError,
8 PreviewAutomationMalformedResponseError,
9 PreviewAutomationNoAvailableHostError,
10 PreviewTabId,
11 ProviderInstanceId,
12 ThreadId,
13 type PreviewAutomationHost,
14 type PreviewAutomationRequest,
15 type PreviewAutomationStreamEvent,
16 SERVER_BROWSER_AUTOMATION_CLIENT_ID,
17} from "@t3tools/contracts";
18import * as Effect from "effect/Effect";
19import * as Deferred from "effect/Deferred";
20import * as Fiber from "effect/Fiber";
21import * as Queue from "effect/Queue";
22import * as Result from "effect/Result";
23import * as Stream from "effect/Stream";
24import * as TestClock from "effect/testing/TestClock";
25
26import { PreviewBrowserRootError } from "../preview/PreviewBrowserHost.ts";
27import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
28
29const makeBroker = PreviewAutomationBroker.make.pipe(
30 Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
31);
32
33const scope = {
34 environmentId: EnvironmentId.make("environment-1"),
35 requestNamespace: "provider-session-1",
36 thread: {
37 threadId: ThreadId.make("thread-1"),
38 providerSessionId: "provider-session-1",
39 providerInstanceId: ProviderInstanceId.make("codex"),
40 },
41 client: undefined,
42 capabilities: new Set(["preview"] as const),
43 issuedAt: 1,
44};
45
46const makeHost = (overrides: Partial<PreviewAutomationHost> = {}): PreviewAutomationHost => ({
47 clientId: "client-1",
48 environmentId: scope.environmentId,
49 ...overrides,
50});
51
52type RoutedRequest = PreviewAutomationRequest & {
53 readonly connectionId: PreviewAutomationStreamEvent["connectionId"];
54};
55
56const requestsFrom = (
57 events: Stream.Stream<PreviewAutomationStreamEvent>,
58 onConnected: (connectionId: PreviewAutomationStreamEvent["connectionId"]) => void = () => {},
59): Stream.Stream<RoutedRequest> =>
60 events.pipe(
61 Stream.filterMap((event) => {
62 if (event.type === "connected") {
63 onConnected(event.connectionId);
64 return Result.failVoid;
65 }
66 return Result.succeed({ ...event.request, connectionId: event.connectionId });
67 }),
68 );
69
70it.effect("atomically registers a connected host and correlates its response", () =>
71 Effect.gen(function* () {
72 const broker = yield* makeBroker;
73 const requests = requestsFrom(yield* broker.connect(makeHost()));
74 yield* Stream.runForEach(requests, (request) =>
75 broker.respond({
76 clientId: "client-1",
77 connectionId: request.connectionId,
78 requestId: request.requestId,
79 ok: true,
80 result: { available: true },
81 }),
82 ).pipe(Effect.forkScoped);
83 yield* Effect.yieldNow;
84
85 const result = yield* broker.invoke<{ available: boolean }>({
86 scope,
87 operation: "open",
88 input: {},
89 });
90
91 expect(result).toEqual({ available: true });
92 }),
93);
94
95it.effect("targets multiple tabs explicitly while retaining a default tab", () =>
96 Effect.gen(function* () {
97 const broker = yield* makeBroker;
98 const appTabId = PreviewTabId.make("tab-web-app");
99 const simulatorTabId = PreviewTabId.make("tab-ios-simulator");
100 const openedTabIds = [appTabId, simulatorTabId];
101 let openIndex = 0;
102 const routedRequests: RoutedRequest[] = [];
103 const requests = requestsFrom(yield* broker.connect(makeHost()));
104 yield* Stream.runForEach(requests, (request) => {
105 routedRequests.push(request);
106 return broker.respond({
107 clientId: "client-1",
108 connectionId: request.connectionId,
109 requestId: request.requestId,
110 ok: true,
111 result:
112 request.operation === "open"
113 ? { available: true, tabId: openedTabIds[openIndex++] }
114 : { url: "http://localhost:3200" },
115 });
116 }).pipe(Effect.forkScoped);
117 yield* Effect.yieldNow;
118
119 yield* broker.invoke({ scope, operation: "open", input: { reuseExistingTab: false } });
120 yield* broker.invoke({ scope, operation: "open", input: { reuseExistingTab: false } });
121 yield* broker.invoke({ scope, operation: "snapshot", input: {} });
122 yield* broker.invoke({ scope, operation: "snapshot", input: {}, tabId: appTabId });
123 yield* broker.invoke({ scope, operation: "snapshot", input: {} });
124
125 expect(routedRequests).toHaveLength(5);
126 expect(routedRequests[0]?.tabId).toBeUndefined();
127 expect(routedRequests[1]?.tabId).toBe(appTabId);
128 expect(routedRequests[2]?.tabId).toBe(simulatorTabId);
129 expect(routedRequests[2]?.tabIdExplicit).toBe(false);
130 expect(routedRequests[3]?.tabId).toBe(appTabId);
131 expect(routedRequests[3]?.tabIdExplicit).toBe(true);
132 expect(routedRequests[4]?.tabId).toBe(appTabId);
133 }),
134);
135
136it.effect.each([true, false])(
137 "keeps an older target stable while a newer explicit tab responds (implicit: %s)",
138 (implicit) =>
139 Effect.gen(function* () {
140 const broker = yield* makeBroker;
141 const olderTabId = PreviewTabId.make("tab-older-request");
142 const newerTabId = PreviewTabId.make("tab-newer-request");
143 const releaseOlderResponse = yield* Deferred.make<void>();
144 const routedRequests: RoutedRequest[] = [];
145 const requests = requestsFrom(yield* broker.connect(makeHost()));
146 yield* Stream.runForEach(requests, (request) => {
147 routedRequests.push(request);
148 const response = Effect.gen(function* () {
149 if (request.tabId === olderTabId && request.operation === "snapshot") {
150 yield* Deferred.await(releaseOlderResponse);
151 }
152 yield* broker.respond({
153 clientId: "client-1",
154 connectionId: request.connectionId,
155 requestId: request.requestId,
156 ok: true,
157 result: { url: "http://localhost:3200" },
158 });
159 if (request.tabId === newerTabId) {
160 yield* Deferred.succeed(releaseOlderResponse, undefined);
161 }
162 });
163 return response.pipe(Effect.forkScoped, Effect.asVoid);
164 }).pipe(Effect.forkScoped);
165 yield* Effect.yieldNow;
166
167 yield* broker.invoke({ scope, operation: "status", input: {}, tabId: olderTabId });
168 let capturedTabId: PreviewTabId | undefined;
169 const older = yield* broker
170 .invoke({
171 scope,
172 operation: "snapshot",
173 input: {},
174 ...(implicit ? {} : { tabId: olderTabId }),
175 onTargetTab: (tabId) => {
176 capturedTabId = tabId;
177 },
178 })
179 .pipe(Effect.forkScoped);
180 yield* Effect.yieldNow;
181 const newer = yield* broker
182 .invoke({ scope, operation: "snapshot", input: {}, tabId: newerTabId })
183 .pipe(Effect.forkScoped);
184 yield* Fiber.join(newer);
185 yield* Fiber.join(older);
186 yield* broker.invoke({
187 scope,
188 operation: "status",
189 input: {},
190 tabId: olderTabId,
191 updateCurrentTab: false,
192 });
193 yield* broker.invoke({ scope, operation: "snapshot", input: {} });
194
195 expect(routedRequests.at(-1)?.tabId).toBe(newerTabId);
196 expect(capturedTabId).toBe(olderTabId);
197 }),
198);
199
200it.effect("does not let a no-tab response suppress an earlier tab decision", () =>
201 Effect.gen(function* () {
202 const broker = yield* makeBroker;
203 const initialTabId = PreviewTabId.make("tab-initial");
204 const openedTabId = PreviewTabId.make("tab-opened-late");
205 const releaseOpenResponse = yield* Deferred.make<void>();
206 const routedRequests: RoutedRequest[] = [];
207 const requests = requestsFrom(yield* broker.connect(makeHost()));
208 yield* Stream.runForEach(requests, (request) => {
209 routedRequests.push(request);
210 const marker =
211 typeof request.input === "object" && request.input !== null && "marker" in request.input
212 ? request.input.marker
213 : undefined;
214 const response = Effect.gen(function* () {
215 if (marker === "older") {
216 yield* Deferred.await(releaseOpenResponse);
217 }
218 yield* broker.respond({
219 clientId: "client-1",
220 connectionId: request.connectionId,
221 requestId: request.requestId,
222 ok: true,
223 result:
224 request.operation === "open"
225 ? { available: true, tabId: marker === "older" ? openedTabId : initialTabId }
226 : { url: "http://localhost:3200" },
227 });
228 if (marker === "newer") {
229 yield* Deferred.succeed(releaseOpenResponse, undefined);
230 }
231 });
232 return response.pipe(Effect.forkScoped, Effect.asVoid);
233 }).pipe(Effect.forkScoped);
234 yield* Effect.yieldNow;
235
236 yield* broker.invoke({ scope, operation: "open", input: {} });
237 const older = yield* broker
238 .invoke({
239 scope,
240 operation: "open",
241 input: { marker: "older", reuseExistingTab: false },
242 })
243 .pipe(Effect.forkScoped);
244 yield* Effect.yieldNow;
245 const newer = yield* broker
246 .invoke({ scope, operation: "snapshot", input: { marker: "newer" } })
247 .pipe(Effect.forkScoped);
248 yield* Fiber.join(newer);
249 yield* Fiber.join(older);
250 yield* broker.invoke({ scope, operation: "snapshot", input: {} });
251
252 expect(routedRequests.at(-1)?.tabId).toBe(openedTabId);
253 }),
254);
255
256it.effect("announces a live replacement stream before delivering requests", () =>
257 Effect.gen(function* () {
258 const broker = yield* makeBroker;
259 const events = yield* broker.connect(makeHost());
260 const receivedTypes: PreviewAutomationStreamEvent["type"][] = [];
261 const consumer = yield* events.pipe(
262 Stream.take(2),
263 Stream.runForEach((event) => {
264 receivedTypes.push(event.type);
265 return event.type === "connected"
266 ? Effect.void
267 : broker.respond({
268 clientId: "client-1",
269 connectionId: event.connectionId,
270 requestId: event.request.requestId,
271 ok: true,
272 result: "ready",
273 });
274 }),
275 Effect.forkScoped,
276 );
277 yield* Effect.yieldNow;
278
279 const result = yield* broker.invoke<string>({ scope, operation: "status", input: {} });
280 yield* Fiber.join(consumer);
281
282 expect(receivedTypes).toEqual(["connected", "request"]);
283 expect(result).toBe("ready");
284 }),
285);
286
287it.effect.each([
288 {
289 clientId: SERVER_BROWSER_AUTOMATION_CLIENT_ID,
290 shown: true,
291 message: "page.goto: net::ERR_CONNECTION_REFUSED at http://localhost:4719/",
292 },
293 {
294 clientId: "client-1",
295 shown: false,
296 message: "page.goto: net::ERR_CONNECTION_REFUSED at http://localhost:4719/",
297 },
298 {
299 clientId: SERVER_BROWSER_AUTOMATION_CLIENT_ID,
300 shown: true,
301 message: new PreviewBrowserRootError().message,
302 },
303])("preserves server browser failure guidance ($clientId)", ({ clientId, shown, message }) =>
304 Effect.gen(function* () {
305 const broker = yield* makeBroker;
306 const requests = requestsFrom(yield* broker.connect(makeHost({ clientId })));
307 yield* Stream.runForEach(requests, (request) =>
308 broker.respond({
309 clientId,
310 connectionId: request.connectionId,
311 requestId: request.requestId,
312 ok: false,
313 error: {
314 _tag: "PreviewAutomationExecutionError",
315 message,
316 },
317 }),
318 ).pipe(Effect.forkScoped);
319 yield* Effect.yieldNow;
320 const error = yield* broker
321 .invoke<void>({ scope, operation: "open", input: {} })
322 .pipe(Effect.flip);
323 expect(error._tag).toBe("PreviewAutomationExecutionError");
324 expect(error.message.includes(message)).toBe(shown);
325 }),
326);
327
328it.effect("names the click target that matched nothing when the server browser times out", () =>
329 Effect.gen(function* () {
330 const broker = yield* makeBroker;
331 const clientId = SERVER_BROWSER_AUTOMATION_CLIENT_ID;
332 const requests = requestsFrom(yield* broker.connect(makeHost({ clientId })));
333 yield* Stream.runForEach(requests, (request) =>
334 broker.respond({
335 clientId,
336 connectionId: request.connectionId,
337 requestId: request.requestId,
338 ok: false,
339 error: {
340 _tag: "PreviewAutomationTimeoutError",
341 message: "No element matches the target.",
342 detail: { reason: 'No element matches ".definitely-no-such-t3-target".' },
343 },
344 }),
345 ).pipe(Effect.forkScoped);
346 yield* Effect.yieldNow;
347
348 const error = yield* broker
349 .invoke<void>({
350 scope,
351 operation: "click",
352 input: { selector: ".definitely-no-such-t3-target", timeoutMs: 15_000 },
353 })
354 .pipe(Effect.flip);
355
356 expect(error._tag).toBe("PreviewAutomationTimeoutError");
357 expect(error.message).toBe(
358 'Preview automation click timed out after 15000ms. No element matches ".definitely-no-such-t3-target".',
359 );
360 }),
361);
362
363it.effect("distinguishes malformed remote failures", () =>
364 Effect.gen(function* () {
365 const broker = yield* makeBroker;
366 const requests = requestsFrom(yield* broker.connect(makeHost()));
367 yield* Stream.runForEach(requests, (request) =>
368 broker.respond({
369 clientId: "client-1",
370 connectionId: request.connectionId,
371 requestId: request.requestId,
372 ok: false,
373 }),
374 ).pipe(Effect.forkScoped);
375 yield* Effect.yieldNow;
376
377 const error = yield* broker
378 .invoke<void>({ scope, operation: "status", input: {}, timeoutMs: 2_000 })
379 .pipe(Effect.flip);
380
381 expect(error).toBeInstanceOf(PreviewAutomationMalformedResponseError);
382 expect(error).toMatchObject({
383 operation: "status",
384 environmentId: scope.environmentId,
385 threadId: scope.thread.threadId,
386 providerSessionId: scope.thread.providerSessionId,
387 providerInstanceId: scope.thread.providerInstanceId,
388 clientId: "client-1",
389 requestId: "preview-0",
390 timeoutMs: 2_000,
391 });
392 }),
393);
394
395it.effect("does not create host state from focus updates without a live stream", () =>
396 Effect.gen(function* () {
397 const broker = yield* makeBroker;
398 yield* broker.focusHost({
399 clientId: "client-1",
400 environmentId: scope.environmentId,
401 connectionId: "connection-missing",
402 focused: true,
403 });
404
405 const error = yield* broker
406 .invoke<void>({ scope, operation: "status", input: {} })
407 .pipe(Effect.flip);
408 expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
409 }),
410);
411
412it.effect("removes host availability when the authoritative request stream disconnects", () =>
413 Effect.gen(function* () {
414 const broker = yield* makeBroker;
415 const requests = requestsFrom(yield* broker.connect(makeHost()));
416 const beforeAcquisition = yield* broker
417 .invoke<void>({ scope, operation: "status", input: {} })
418 .pipe(Effect.flip);
419 expect(beforeAcquisition).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
420
421 const consumer = yield* Stream.runDrain(requests).pipe(Effect.forkScoped);
422 yield* Effect.yieldNow;
423 yield* Fiber.interrupt(consumer);
424
425 const error = yield* broker
426 .invoke<void>({ scope, operation: "status", input: {} })
427 .pipe(Effect.flip);
428 expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
429 }),
430);
431
432it.effect("routes requests for background threads through an environment-level host", () =>
433 Effect.gen(function* () {
434 const broker = yield* makeBroker;
435 const backgroundThreadId = ThreadId.make("thread-background");
436 const requests = requestsFrom(yield* broker.connect(makeHost()));
437 let routedThreadId: string | undefined;
438 yield* Stream.runForEach(requests, (request) => {
439 routedThreadId = request.threadId;
440 return broker.respond({
441 clientId: "client-1",
442 connectionId: request.connectionId,
443 requestId: request.requestId,
444 ok: true,
445 result: "background",
446 });
447 }).pipe(Effect.forkScoped);
448 yield* Effect.yieldNow;
449
450 const result = yield* broker.invoke<string>({
451 scope: {
452 ...scope,
453 thread: {
454 ...scope.thread,
455 threadId: backgroundThreadId,
456 providerSessionId: "provider-session-background",
457 },
458 },
459 operation: "status",
460 input: {},
461 });
462
463 expect(result).toBe("background");
464 expect(routedThreadId).toBe(backgroundThreadId);
465 }),
466);
467
468it.effect("never routes a provider session to a host from another environment", () =>
469 Effect.gen(function* () {
470 const broker = yield* makeBroker;
471 const matchingRequests = requestsFrom(
472 yield* broker.connect(makeHost({ clientId: "client-matching" })),
473 );
474 const foreignRequests = requestsFrom(
475 yield* broker.connect(
476 makeHost({
477 clientId: "client-foreign",
478 environmentId: EnvironmentId.make("environment-foreign"),
479 }),
480 ),
481 );
482 yield* Stream.runForEach(matchingRequests, (request) =>
483 broker.respond({
484 clientId: "client-matching",
485 connectionId: request.connectionId,
486 requestId: request.requestId,
487 ok: true,
488 result: "matching",
489 }),
490 ).pipe(Effect.forkScoped);
491 yield* Stream.runForEach(foreignRequests, (request) =>
492 broker.respond({
493 clientId: "client-foreign",
494 connectionId: request.connectionId,
495 requestId: request.requestId,
496 ok: true,
497 result: "foreign",
498 }),
499 ).pipe(Effect.forkScoped);
500 yield* Effect.yieldNow;
501
502 expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
503 "matching",
504 );
505 }),
506);
507
508it.effect("pins a provider session to its initial host despite later focus changes", () =>
509 Effect.gen(function* () {
510 const broker = yield* makeBroker;
511 let firstConnectionId = "";
512 let secondConnectionId = "";
513 const firstRequests = requestsFrom(
514 yield* broker.connect(makeHost({ clientId: "client-first" })),
515 (connectionId) => {
516 firstConnectionId = connectionId;
517 },
518 );
519 const secondRequests = requestsFrom(
520 yield* broker.connect(makeHost({ clientId: "client-second" })),
521 (connectionId) => {
522 secondConnectionId = connectionId;
523 },
524 );
525 yield* Stream.runForEach(firstRequests, (request) =>
526 broker.respond({
527 clientId: "client-first",
528 connectionId: request.connectionId,
529 requestId: request.requestId,
530 ok: true,
531 result: "first",
532 }),
533 ).pipe(Effect.forkScoped);
534 yield* Stream.runForEach(secondRequests, (request) =>
535 broker.respond({
536 clientId: "client-second",
537 connectionId: request.connectionId,
538 requestId: request.requestId,
539 ok: true,
540 result: "second",
541 }),
542 ).pipe(Effect.forkScoped);
543 yield* Effect.yieldNow;
544
545 yield* broker.focusHost({
546 clientId: "client-first",
547 environmentId: scope.environmentId,
548 connectionId: "connection-stale",
549 focused: true,
550 liveTabs: [{ threadId: scope.thread.threadId, tabId: PreviewTabId.make("stale-tab") }],
551 });
552 expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe("second");
553 yield* broker.focusHost({
554 clientId: "client-first",
555 environmentId: scope.environmentId,
556 connectionId: firstConnectionId,
557 focused: true,
558 });
559
560 const firstPinnedScope = {
561 ...scope,
562 thread: { ...scope.thread, providerSessionId: "provider-session-first-pinned" },
563 };
564 expect(
565 yield* broker.invoke<string>({ scope: firstPinnedScope, operation: "status", input: {} }),
566 ).toBe("first");
567
568 yield* broker.focusHost({
569 clientId: "client-second",
570 environmentId: scope.environmentId,
571 connectionId: secondConnectionId,
572 focused: true,
573 });
574
575 expect(
576 yield* broker.invoke<string>({ scope: firstPinnedScope, operation: "status", input: {} }),
577 ).toBe("first");
578 expect(
579 yield* broker.invoke<string>({
580 scope: {
581 ...scope,
582 thread: { ...scope.thread, providerSessionId: "provider-session-second-pinned" },
583 },
584 operation: "status",
585 input: {},
586 }),
587 ).toBe("second");
588 }),
589);
590
591it.effect("prefers the live tab owner for new sessions without moving existing leases", () =>
592 Effect.gen(function* () {
593 const broker = yield* makeBroker;
594 const connections = new Map<string, string>();
595 for (const clientId of ["owner", "other"]) {
596 const requests = requestsFrom(yield* broker.connect(makeHost({ clientId })), (connectionId) =>
597 connections.set(clientId, connectionId),
598 );
599 yield* Stream.runForEach(requests, (request) =>
600 broker.respond({
601 clientId,
602 connectionId: request.connectionId,
603 requestId: request.requestId,
604 ok: true,
605 result: clientId,
606 }),
607 ).pipe(Effect.forkScoped);
608 }
609 yield* Effect.yieldNow;
610 yield* broker.focusHost({
611 clientId: "owner",
612 environmentId: scope.environmentId,
613 connectionId: connections.get("owner")!,
614 focused: false,
615 liveTabs: [
616 { threadId: scope.thread.threadId, tabId: PreviewTabId.make("signed-in"), visible: true },
617 ],
618 });
619 yield* broker.focusHost({
620 clientId: "other",
621 environmentId: scope.environmentId,
622 connectionId: connections.get("other")!,
623 focused: true,
624 liveTabs: [
625 {
626 threadId: scope.thread.threadId,
627 tabId: PreviewTabId.make("signed-in"),
628 visible: false,
629 },
630 {
631 threadId: ThreadId.make("another-thread"),
632 tabId: PreviewTabId.make("different-tab"),
633 visible: true,
634 },
635 ],
636 });
637 expect(yield* broker.invoke<string>({ scope, operation: "evaluate", input: {} })).toBe("owner");
638 expect(
639 yield* broker.invoke<string>({
640 scope: { ...scope, thread: { ...scope.thread, providerSessionId: "explicit-owner" } },
641 tabId: PreviewTabId.make("signed-in"),
642 operation: "snapshot",
643 input: {},
644 }),
645 ).toBe("owner");
646 expect(
647 yield* broker.invoke<string>({
648 scope: { ...scope, thread: { ...scope.thread, providerSessionId: "other-tab" } },
649 tabId: PreviewTabId.make("different-tab"),
650 operation: "evaluate",
651 input: {},
652 }),
653 ).toBe("other");
654
655 yield* broker.focusHost({
656 clientId: "owner",
657 environmentId: scope.environmentId,
658 connectionId: connections.get("owner")!,
659 focused: false,
660 liveTabs: [],
661 });
662 expect(yield* broker.invoke<string>({ scope, operation: "evaluate", input: {} })).toBe("owner");
663 expect(
664 yield* broker.invoke<string>({
665 scope: { ...scope, thread: { ...scope.thread, providerSessionId: "after-tab-closed" } },
666 operation: "evaluate",
667 input: {},
668 }),
669 ).toBe("other");
670 }),
671);
672
673it.effect("routes resize to a capable host instead of a newer legacy connection", () =>
674 Effect.gen(function* () {
675 const broker = yield* makeBroker;
676 const capableRequests = requestsFrom(
677 yield* broker.connect(
678 makeHost({ clientId: "client-capable", supportedOperations: ["resize"] }),
679 ),
680 );
681 const legacyRequests = requestsFrom(
682 yield* broker.connect(makeHost({ clientId: "client-legacy" })),
683 );
684 yield* Stream.runForEach(capableRequests, (request) =>
685 broker.respond({
686 clientId: "client-capable",
687 connectionId: request.connectionId,
688 requestId: request.requestId,
689 ok: true,
690 result: "capable",
691 }),
692 ).pipe(Effect.forkScoped);
693 yield* Stream.runForEach(legacyRequests, (request) =>
694 broker.respond({
695 clientId: "client-legacy",
696 connectionId: request.connectionId,
697 requestId: request.requestId,
698 ok: true,
699 result: "legacy",
700 }),
701 ).pipe(Effect.forkScoped);
702 yield* Effect.yieldNow;
703
704 expect(
705 yield* broker.invoke<string>({ scope, operation: "resize", input: { mode: "fill" } }),
706 ).toBe("capable");
707 }),
708);
709
710it.effect("does not move a live legacy assignment to another runtime for resize", () =>
711 Effect.gen(function* () {
712 const broker = yield* makeBroker;
713 const legacyRequests = requestsFrom(
714 yield* broker.connect(makeHost({ clientId: "client-legacy" })),
715 );
716 yield* Stream.runForEach(legacyRequests, (request) =>
717 broker.respond({
718 clientId: "client-legacy",
719 connectionId: request.connectionId,
720 requestId: request.requestId,
721 ok: true,
722 result: "legacy",
723 }),
724 ).pipe(Effect.forkScoped);
725 yield* Effect.yieldNow;
726
727 expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe("legacy");
728
729 const capableRequests = requestsFrom(
730 yield* broker.connect(
731 makeHost({ clientId: "client-capable", supportedOperations: ["resize"] }),
732 ),
733 );
734 yield* Stream.runForEach(capableRequests, (request) =>
735 broker.respond({
736 clientId: "client-capable",
737 connectionId: request.connectionId,
738 requestId: request.requestId,
739 ok: true,
740 result: "capable",
741 }),
742 ).pipe(Effect.forkScoped);
743 yield* Effect.yieldNow;
744
745 const error = yield* broker
746 .invoke<void>({ scope, operation: "resize", input: { mode: "fill" } })
747 .pipe(Effect.flip);
748 expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
749 expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe("legacy");
750 }),
751);
752
753it.effect("ignores stale focus updates for a different environment", () =>
754 Effect.gen(function* () {
755 const broker = yield* makeBroker;
756 let firstConnectionId = "";
757 const firstRequests = requestsFrom(
758 yield* broker.connect(makeHost({ clientId: "client-first" })),
759 (connectionId) => {
760 firstConnectionId = connectionId;
761 },
762 );
763 const secondRequests = requestsFrom(
764 yield* broker.connect(makeHost({ clientId: "client-second" })),
765 );
766 yield* Stream.runForEach(firstRequests, (request) =>
767 broker.respond({
768 clientId: "client-first",
769 connectionId: request.connectionId,
770 requestId: request.requestId,
771 ok: true,
772 result: "first",
773 }),
774 ).pipe(Effect.forkScoped);
775 yield* Stream.runForEach(secondRequests, (request) =>
776 broker.respond({
777 clientId: "client-second",
778 connectionId: request.connectionId,
779 requestId: request.requestId,
780 ok: true,
781 result: "second",
782 }),
783 ).pipe(Effect.forkScoped);
784 yield* Effect.yieldNow;
785
786 yield* broker.focusHost({
787 clientId: "client-first",
788 environmentId: EnvironmentId.make("environment-stale"),
789 connectionId: firstConnectionId,
790 focused: true,
791 });
792
793 expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe("second");
794 }),
795);
796
797it.effect("fails over a pinned provider session only after its host disconnects", () =>
798 Effect.gen(function* () {
799 const broker = yield* makeBroker;
800 const firstTabId = PreviewTabId.make("tab-on-first-host");
801 let firstConnectionId = "";
802 let secondRoutedTabId: PreviewTabId | undefined;
803 const firstRequests = requestsFrom(
804 yield* broker.connect(makeHost({ clientId: "client-first" })),
805 (connectionId) => {
806 firstConnectionId = connectionId;
807 },
808 );
809 const secondRequests = requestsFrom(
810 yield* broker.connect(makeHost({ clientId: "client-second" })),
811 );
812 const firstConsumer = yield* Stream.runForEach(firstRequests, (request) =>
813 broker.respond({
814 clientId: "client-first",
815 connectionId: request.connectionId,
816 requestId: request.requestId,
817 ok: true,
818 result: request.operation === "open" ? { host: "first", tabId: firstTabId } : "first",
819 }),
820 ).pipe(Effect.forkScoped);
821 yield* Stream.runForEach(secondRequests, (request) => {
822 secondRoutedTabId = request.tabId;
823 return broker.respond({
824 clientId: "client-second",
825 connectionId: request.connectionId,
826 requestId: request.requestId,
827 ok: true,
828 result: "second",
829 });
830 }).pipe(Effect.forkScoped);
831 yield* Effect.yieldNow;
832
833 yield* broker.focusHost({
834 clientId: "client-first",
835 environmentId: scope.environmentId,
836 connectionId: firstConnectionId,
837 focused: true,
838 liveTabs: [{ threadId: scope.thread.threadId, tabId: firstTabId }],
839 });
840 expect(yield* broker.invoke({ scope, operation: "open", input: {} })).toEqual({
841 host: "first",
842 tabId: firstTabId,
843 });
844
845 yield* Fiber.interrupt(firstConsumer);
846 yield* Effect.yieldNow;
847
848 expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe("second");
849 expect(secondRoutedTabId).toBeUndefined();
850 }),
851);
852
853it.effect("keeps a replacement stream authoritative when the old stream finalizes", () =>
854 Effect.gen(function* () {
855 const broker = yield* makeBroker;
856 let firstConnectionId = "";
857 let replacementConnectionId = "";
858 const firstRequests = requestsFrom(yield* broker.connect(makeHost()), (connectionId) => {
859 firstConnectionId = connectionId;
860 });
861 yield* Stream.runDrain(firstRequests).pipe(Effect.forkScoped);
862 yield* Effect.yieldNow;
863
864 const replacementRequests = requestsFrom(yield* broker.connect(makeHost()), (connectionId) => {
865 replacementConnectionId = connectionId;
866 });
867 yield* Stream.runForEach(replacementRequests, (request) =>
868 broker.respond({
869 clientId: "client-1",
870 connectionId: request.connectionId,
871 requestId: request.requestId,
872 ok: true,
873 result: "replacement",
874 }),
875 ).pipe(Effect.forkScoped);
876 yield* Effect.yieldNow;
877
878 expect(replacementConnectionId).not.toBe(firstConnectionId);
879 const result = yield* broker.invoke<string>({ scope, operation: "status", input: {} });
880 expect(result).toBe("replacement");
881 }),
882);
883
884it.effect("does not carry a tab id across a replacement automation stream", () =>
885 Effect.gen(function* () {
886 const broker = yield* makeBroker;
887 const openedTabId = PreviewTabId.make("tab-first-webcontents");
888 const firstRequests = requestsFrom(yield* broker.connect(makeHost()));
889 yield* Stream.runForEach(firstRequests, (request) =>
890 broker.respond({
891 clientId: "client-1",
892 connectionId: request.connectionId,
893 requestId: request.requestId,
894 ok: true,
895 result:
896 request.operation === "open" ? { host: "first", tabId: openedTabId } : { host: "first" },
897 }),
898 ).pipe(Effect.forkScoped);
899 yield* Effect.yieldNow;
900
901 expect(yield* broker.invoke({ scope, operation: "open", input: {} })).toEqual({
902 host: "first",
903 tabId: openedTabId,
904 });
905
906 const routedRequests: RoutedRequest[] = [];
907 const replacementRequests = requestsFrom(yield* broker.connect(makeHost()));
908 yield* Stream.runForEach(replacementRequests, (request) => {
909 routedRequests.push(request);
910 return broker.respond({
911 clientId: "client-1",
912 connectionId: request.connectionId,
913 requestId: request.requestId,
914 ok: true,
915 result: "replacement",
916 });
917 }).pipe(Effect.forkScoped);
918 yield* Effect.yieldNow;
919
920 expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
921 "replacement",
922 );
923 expect(routedRequests.at(-1)?.tabId).toBeUndefined();
924 }),
925);
926
927it.effect("fails requests assigned to the stream that is replaced", () =>
928 Effect.gen(function* () {
929 const broker = yield* makeBroker;
930 const requests = requestsFrom(yield* broker.connect(makeHost()));
931 yield* Stream.runDrain(requests).pipe(Effect.forkScoped);
932 const pending = yield* broker
933 .invoke<void>({ scope, operation: "status", input: {} })
934 .pipe(Effect.flip, Effect.forkScoped);
935 yield* Effect.yieldNow;
936
937 const replacementRequests = requestsFrom(yield* broker.connect(makeHost()));
938 yield* Stream.runDrain(replacementRequests).pipe(Effect.forkScoped);
939
940 const error = yield* Fiber.join(pending);
941 expect(error).toBeInstanceOf(PreviewAutomationClientDisconnectedError);
942 expect(error).toMatchObject({
943 operation: "status",
944 environmentId: scope.environmentId,
945 threadId: scope.thread.threadId,
946 providerSessionId: scope.thread.providerSessionId,
947 providerInstanceId: scope.thread.providerInstanceId,
948 clientId: "client-1",
949 requestId: "preview-0",
950 timeoutMs: 15_000,
951 });
952 }),
953);
954
955it.effect(
956 "keeps another thread's request alive when one request times out on the shared server browser",
957 () =>
958 Effect.gen(function* () {
959 const broker = yield* makeBroker;
960 const clientId = SERVER_BROWSER_AUTOMATION_CLIENT_ID;
961 const delivered = yield* Queue.unbounded<RoutedRequest>();
962 const requests = requestsFrom(
963 yield* broker.connect(makeHost({ clientId }), { preferred: true }),
964 );
965 yield* Stream.runForEach(requests, (request) => Queue.offer(delivered, request)).pipe(
966 Effect.forkScoped,
967 );
968 yield* Effect.yieldNow;
969 const otherScope = {
970 ...scope,
971 requestNamespace: "provider-session-2",
972 thread: {
973 threadId: ThreadId.make("thread-2"),
974 providerSessionId: "provider-session-2",
975 providerInstanceId: ProviderInstanceId.make("codex"),
976 },
977 };
978
979 const otherWait = yield* broker
980 .invoke<string>({ scope: otherScope, operation: "waitFor", input: {}, timeoutMs: 40_000 })
981 .pipe(Effect.result, Effect.forkScoped);
982 const otherRequest = yield* Queue.take(delivered);
983 // The browser never answers this one, as when it waits behind the thread's own running action.
984 const stalled = yield* broker
985 .invoke<string>({ scope, operation: "evaluate", input: {} })
986 .pipe(Effect.flip, Effect.forkScoped);
987 yield* Queue.take(delivered);
988
989 yield* TestClock.adjust("16 seconds");
990 expect((yield* Fiber.join(stalled))._tag).toBe("PreviewAutomationTimeoutError");
991
992 yield* broker.respond({
993 clientId,
994 connectionId: otherRequest.connectionId,
995 requestId: otherRequest.requestId,
996 ok: true,
997 result: "ready",
998 });
999 expect(yield* Fiber.join(otherWait)).toEqual(Result.succeed("ready"));
1000 }),
1001);
1002
1003it.effect("accepts responses only from the host that received the request", () =>
1004 Effect.gen(function* () {
1005 const broker = yield* makeBroker;
1006 const requests = requestsFrom(yield* broker.connect(makeHost()));
1007 yield* Stream.runForEach(requests, (request) =>
1008 Effect.gen(function* () {
1009 yield* broker.respond({
1010 clientId: "client-foreign",
1011 connectionId: request.connectionId,
1012 requestId: request.requestId,
1013 ok: true,
1014 result: "foreign",
1015 });
1016 yield* broker.respond({
1017 clientId: "client-1",
1018 connectionId: "connection-stale",
1019 requestId: request.requestId,
1020 ok: true,
1021 result: "stale",
1022 });
1023 yield* broker.respond({
1024 clientId: "client-1",
1025 connectionId: request.connectionId,
1026 requestId: request.requestId,
1027 ok: true,
1028 result: "owner",
1029 });
1030 }),
1031 ).pipe(Effect.forkScoped);
1032 yield* Effect.yieldNow;
1033
1034 const result = yield* broker.invoke<string>({ scope, operation: "status", input: {} });
1035 expect(result).toBe("owner");
1036 }),
1037);
1038
1039it.effect("keeps each thread's current tab when threads share a provider session", () =>
1040 Effect.gen(function* () {
1041 const broker = yield* makeBroker;
1042 const routed: Array<RoutedRequest> = [];
1043 const requests = requestsFrom(yield* broker.connect(makeHost(), { preferred: true }));
1044 yield* Stream.runForEach(requests, (request) => {
1045 routed.push(request);
1046 return broker.respond({
1047 clientId: "client-1",
1048 connectionId: request.connectionId,
1049 requestId: request.requestId,
1050 ok: true,
1051 result: { tabId: request.tabId ?? `tab-${request.threadId}` },
1052 });
1053 }).pipe(Effect.forkScoped);
1054 yield* Effect.yieldNow;
1055 // Codex runs every thread of an instance in one provider session.
1056 const otherThread = {
1057 ...scope,
1058 thread: { ...scope.thread, threadId: ThreadId.make("thread-2") },
1059 };
1060
1061 yield* broker.invoke({ scope, operation: "open", input: {} });
1062 yield* broker.invoke({ scope: otherThread, operation: "snapshot", input: {} });
1063 yield* broker.invoke({ scope, operation: "snapshot", input: {} });
1064 yield* broker.invoke({ scope: otherThread, operation: "snapshot", input: {} });
1065
1066 expect(routed.map(({ threadId, tabId }) => [threadId, tabId])).toEqual([
1067 ["thread-1", undefined],
1068 ["thread-2", undefined],
1069 ["thread-1", "tab-thread-1"],
1070 ["thread-2", "tab-thread-2"],
1071 ]);
1072 expect(routed[0]!.agentSessionId).not.toBe(routed[1]!.agentSessionId);
1073 }),
1074);