Open History to see the last commit
1import {
2 PREVIEW_AUTOMATION_V1_OPERATIONS,
3 PreviewAutomationClientDisconnectedError,
4 PreviewAutomationControlInterruptedError,
5 PreviewAutomationControlReason,
6 PreviewAutomationExecutionError,
7 SERVER_BROWSER_AUTOMATION_CLIENT_ID,
8 PreviewAutomationInvalidSelectorError,
9 PreviewAutomationMalformedResponseError,
10 PreviewAutomationNoAvailableHostError,
11 PreviewAutomationRemoteUnavailableError,
12 PreviewAutomationRecordingTransferError,
13 PreviewAutomationRecordingDesktopUpdateRequiredError,
14 PreviewAutomationRecordingTooLargeError,
15 PreviewAutomationRecordingDeadlineExpiredError,
16 PreviewAutomationRequestQueueClosedError,
17 PreviewAutomationResultTooLargeError,
18 PreviewAutomationTabNotFoundError,
19 PreviewAutomationTargetNotEditableError,
20 PreviewAutomationTimeoutError,
21 PreviewAutomationUnsupportedClientError,
22 PreviewTabId,
23 type PreviewAutomationError,
24 type PreviewAutomationOperation,
25 type PreviewAutomationHost,
26 type PreviewAutomationHostFocus,
27 type PreviewAutomationResponse,
28 type PreviewAutomationStreamEvent,
29} from "@t3tools/contracts";
30import * as Context from "effect/Context";
31import type * as Cause from "effect/Cause";
32import * as SecureRandom from "effect/crypto/SecureRandom";
33import * as Deferred from "effect/Deferred";
34import * as Effect from "effect/Effect";
35import * as Layer from "effect/Layer";
36import * as Option from "effect/Option";
37import * as Queue from "effect/Queue";
38import * as Schema from "effect/Schema";
39import * as Stream from "effect/Stream";
40import * as SynchronizedRef from "effect/SynchronizedRef";
41
42import * as McpInvocationContext from "./McpInvocationContext.ts";
43
44const HOST_RESPONSE_GRACE_MS = 1_000;
45
46export interface PreviewAutomationInvokeInput {
47 readonly scope: McpInvocationContext.McpThreadInvocationScope;
48 readonly operation: PreviewAutomationOperation;
49 readonly input: unknown;
50 readonly tabId?: PreviewTabId;
51 readonly timeoutMs?: number;
52 /** Background metadata reads must not change the agent's current tab. */
53 readonly updateCurrentTab?: boolean;
54 readonly onTargetTab?: (tabId: PreviewTabId | undefined) => void;
55}
56
57export interface PreviewAutomationConnectOptions {
58 readonly preferred?: boolean;
59}
60
61export class PreviewAutomationBroker extends Context.Service<
62 PreviewAutomationBroker,
63 {
64 readonly connect: (
65 host: PreviewAutomationHost,
66 options?: PreviewAutomationConnectOptions,
67 ) => Effect.Effect<Stream.Stream<PreviewAutomationStreamEvent>>;
68 readonly focusHost: (host: PreviewAutomationHostFocus) => Effect.Effect<void>;
69 readonly respond: (
70 response: PreviewAutomationResponse,
71 ) => Effect.Effect<void, PreviewAutomationError>;
72 readonly invoke: <A = unknown>(
73 request: PreviewAutomationInvokeInput,
74 ) => Effect.Effect<A, PreviewAutomationError>;
75 }
76>()("t3/mcp/PreviewAutomationBroker") {}
77
78interface ClientConnection {
79 readonly clientId: string;
80 readonly connectionId: string;
81 readonly environmentId: PreviewAutomationHost["environmentId"];
82 readonly supportedOperations: ReadonlySet<PreviewAutomationOperation>;
83 readonly focused: boolean;
84 readonly preferred: boolean;
85 readonly liveTabs: NonNullable<PreviewAutomationHostFocus["liveTabs"]>;
86 readonly focusOrder: number;
87 readonly queue: Queue.Queue<PreviewAutomationStreamEvent, Cause.Done>;
88}
89
90interface PendingRequest {
91 readonly queue: ClientConnection["queue"];
92 readonly deferred: Deferred.Deferred<unknown, PreviewAutomationError>;
93 readonly context: PreviewAutomationRequestErrorContext;
94}
95
96/** A lease belongs to this exact connectionId/queue; replacing the host invalidates it. */
97interface HostAssignment {
98 readonly clientId: ClientConnection["clientId"];
99 readonly connectionId: ClientConnection["connectionId"];
100 readonly queue: ClientConnection["queue"];
101 readonly tabId?: PreviewTabId;
102 readonly tabSequence?: number;
103}
104
105interface PreviewAutomationRequestErrorContext {
106 readonly operation: PreviewAutomationOperation;
107 readonly environmentId: McpInvocationContext.McpInvocationScope["environmentId"];
108 readonly threadId: McpInvocationContext.McpThreadCaller["threadId"];
109 readonly providerSessionId: string;
110 readonly providerInstanceId: McpInvocationContext.McpThreadCaller["providerInstanceId"];
111 readonly clientId: string;
112 readonly connectionId: ClientConnection["connectionId"];
113 readonly requestId: string;
114 readonly tabId?: PreviewTabId;
115 readonly timeoutMs: number;
116 readonly selectorKind?: "locator" | "selector";
117 readonly selectorLength?: number;
118}
119
120interface BrokerState {
121 readonly clients: ReadonlyMap<string, ClientConnection>;
122 readonly assignments: ReadonlyMap<string, HostAssignment>;
123 readonly pending: ReadonlyMap<string, PendingRequest>;
124 readonly requestSequence: number;
125 readonly focusSequence: number;
126}
127
128const removeConnectionFromState = (
129 current: BrokerState,
130 clientId: string,
131 queue: ClientConnection["queue"],
132): { readonly state: BrokerState; readonly disconnected: ReadonlyArray<PendingRequest> } => {
133 const clients = new Map(current.clients);
134 const assignments = new Map(current.assignments);
135 const pending = new Map(current.pending);
136 const disconnected: PendingRequest[] = [];
137 if (current.clients.get(clientId)?.queue === queue) clients.delete(clientId);
138 for (const [assignmentKey, assignment] of assignments) {
139 if (assignment.queue === queue) assignments.delete(assignmentKey);
140 }
141 for (const [requestId, entry] of pending) {
142 if (entry.queue !== queue) continue;
143 pending.delete(requestId);
144 disconnected.push(entry);
145 }
146 return {
147 state: { ...current, clients, assignments, pending },
148 disconnected,
149 };
150};
151
152const selectorDiagnosticsFromInput = (
153 input: unknown,
154): Pick<PreviewAutomationRequestErrorContext, "selectorKind" | "selectorLength"> => {
155 if (typeof input !== "object" || input === null) return {};
156 if ("locator" in input && typeof input.locator === "string") {
157 return { selectorKind: "locator", selectorLength: input.locator.length };
158 }
159 if ("selector" in input && typeof input.selector === "string") {
160 return { selectorKind: "selector", selectorLength: input.selector.length };
161 }
162 return {};
163};
164
165/** Codex/OpenCode share sessions across threads; include thread id to isolate tabs and ownership. */
166const hostAssignmentKey = (scope: McpInvocationContext.McpThreadInvocationScope): string =>
167 `${scope.environmentId}\u0000${scope.thread.providerSessionId}\u0000${scope.thread.threadId}`;
168
169const isPreviewTabId = Schema.is(PreviewTabId);
170const decodeControlReason = Schema.decodeUnknownOption(PreviewAutomationControlReason);
171
172const readResultTabId = (result: unknown): PreviewTabId | null | undefined => {
173 if (typeof result !== "object" || result === null || !("tabId" in result)) return undefined;
174 const tabId = result.tabId;
175 return tabId === null || isPreviewTabId(tabId) ? tabId : undefined;
176};
177
178const supportsOperation = (
179 connection: ClientConnection,
180 operation: PreviewAutomationOperation,
181): boolean => connection.supportedOperations.has(operation);
182
183type RemoteDetailKind = "null" | "array" | "object" | "string" | "number" | "boolean";
184
185function remoteDetailKind(detail: unknown): RemoteDetailKind {
186 if (detail === null) return "null";
187 if (Array.isArray(detail)) return "array";
188 switch (typeof detail) {
189 case "string":
190 return "string";
191 case "number":
192 return "number";
193 case "boolean":
194 return "boolean";
195 default:
196 return "object";
197 }
198}
199
200const readRemoteTimeoutMs = (detail: unknown): number | undefined => {
201 if (typeof detail !== "object" || detail === null || !("timeoutMs" in detail)) return undefined;
202 const timeoutMs = detail.timeoutMs;
203 return typeof timeoutMs === "number" && Number.isInteger(timeoutMs) && timeoutMs > 0
204 ? timeoutMs
205 : undefined;
206};
207
208const MAX_REASON_CHARS = 500;
209
210const classifyResponseError = (
211 context: PreviewAutomationRequestErrorContext,
212 error: NonNullable<PreviewAutomationResponse["error"]>,
213): PreviewAutomationError => {
214 const remoteDiagnostics = {
215 remoteTag: error._tag,
216 remoteMessageLength: error.message.length,
217 ...(error.detail === undefined ? {} : { remoteDetailKind: remoteDetailKind(error.detail) }),
218 cause: error,
219 };
220 switch (error._tag) {
221 case "PreviewAutomationRecordingDesktopUpdateRequiredError":
222 return new PreviewAutomationRecordingDesktopUpdateRequiredError({
223 threadId: context.threadId,
224 cause: error,
225 });
226 case "PreviewAutomationRecordingTooLargeError":
227 return new PreviewAutomationRecordingTooLargeError({
228 threadId: context.threadId,
229 cause: error,
230 });
231 case "PreviewAutomationRecordingDeadlineExpiredError":
232 return new PreviewAutomationRecordingDeadlineExpiredError({
233 threadId: context.threadId,
234 cause: error,
235 });
236 case "PreviewAutomationRecordingTransferError":
237 return new PreviewAutomationRecordingTransferError({
238 threadId: context.threadId,
239 cause: error,
240 });
241 case "PreviewAutomationNoAvailableHostError":
242 return new PreviewAutomationNoAvailableHostError({
243 ...context,
244 ...remoteDiagnostics,
245 });
246 case "PreviewAutomationUnsupportedClientError":
247 return new PreviewAutomationUnsupportedClientError({
248 ...context,
249 ...remoteDiagnostics,
250 });
251 case "PreviewAutomationTabNotFoundError":
252 return new PreviewAutomationTabNotFoundError({
253 ...context,
254 ...remoteDiagnostics,
255 });
256 case "PreviewAutomationTimeoutError": {
257 const remoteTimeoutMs = readRemoteTimeoutMs(error.detail);
258 return new PreviewAutomationTimeoutError({
259 ...context,
260 ...remoteDiagnostics,
261 ...(remoteTimeoutMs === undefined
262 ? {}
263 : { timeoutMs: Math.min(context.timeoutMs, remoteTimeoutMs) }),
264 });
265 }
266 case "PreviewAutomationControlInterruptedError": {
267 const reason = decodeControlReason(error.detail);
268 return new PreviewAutomationControlInterruptedError({
269 ...context,
270 ...remoteDiagnostics,
271 ...(Option.isSome(reason) ? { reason: reason.value } : {}),
272 });
273 }
274 case "PreviewAutomationInvalidSelectorError": {
275 const staleRef =
276 typeof error.detail === "object" &&
277 error.detail !== null &&
278 "staleRef" in error.detail &&
279 error.detail.staleRef === true;
280 return new PreviewAutomationInvalidSelectorError({
281 ...context,
282 ...remoteDiagnostics,
283 ...(staleRef ? { staleRef } : {}),
284 });
285 }
286 case "PreviewAutomationTargetNotEditableError": {
287 const detail =
288 typeof error.detail === "object" && error.detail !== null ? error.detail : undefined;
289 const remoteSelectorKind =
290 detail &&
291 "selectorKind" in detail &&
292 (detail.selectorKind === "focused-element" ||
293 detail.selectorKind === "locator" ||
294 detail.selectorKind === "selector")
295 ? detail.selectorKind
296 : undefined;
297 const remoteSelectorLength =
298 detail &&
299 "selectorLength" in detail &&
300 typeof detail.selectorLength === "number" &&
301 Number.isInteger(detail.selectorLength) &&
302 detail.selectorLength >= 0
303 ? detail.selectorLength
304 : undefined;
305 return new PreviewAutomationTargetNotEditableError({
306 ...context,
307 ...remoteDiagnostics,
308 ...(remoteSelectorKind === undefined && context.selectorKind === undefined
309 ? {}
310 : { selectorKind: remoteSelectorKind ?? context.selectorKind }),
311 ...(remoteSelectorLength === undefined && context.selectorLength === undefined
312 ? {}
313 : { selectorLength: remoteSelectorLength ?? context.selectorLength }),
314 });
315 }
316 case "PreviewAutomationResultTooLargeError": {
317 const detail =
318 typeof error.detail === "object" && error.detail !== null ? error.detail : undefined;
319 const maximumBytes =
320 detail &&
321 "maximumBytes" in detail &&
322 typeof detail.maximumBytes === "number" &&
323 Number.isInteger(detail.maximumBytes) &&
324 detail.maximumBytes > 0
325 ? detail.maximumBytes
326 : undefined;
327 return new PreviewAutomationResultTooLargeError({
328 ...context,
329 ...remoteDiagnostics,
330 ...(maximumBytes === undefined ? {} : { maximumBytes }),
331 });
332 }
333 case "PreviewAutomationUnavailableError":
334 return new PreviewAutomationRemoteUnavailableError({
335 ...context,
336 ...remoteDiagnostics,
337 });
338 default:
339 return new PreviewAutomationExecutionError({
340 ...context,
341 ...remoteDiagnostics,
342 ...(context.clientId === SERVER_BROWSER_AUTOMATION_CLIENT_ID
343 ? { reason: error.message.slice(0, MAX_REASON_CHARS) }
344 : {}),
345 });
346 }
347};
348
349export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
350 const random = yield* SecureRandom.SecureRandom;
351 const state = yield* SynchronizedRef.make<BrokerState>({
352 clients: new Map(),
353 assignments: new Map(),
354 pending: new Map(),
355 requestSequence: 0,
356 focusSequence: 0,
357 });
358
359 const closeConnection = Effect.fn("PreviewAutomationBroker.closeConnection")(function* (
360 queue: ClientConnection["queue"],
361 disconnected: ReadonlyArray<PendingRequest>,
362 completeStream = false,
363 ) {
364 if (completeStream) {
365 // Close the evicted generation's RPC stream so a responsive desktop can re-register.
366 yield* Queue.clear(queue);
367 yield* Queue.end(queue);
368 } else {
369 // Replaced registrations must not reconnect and displace their successor.
370 yield* Queue.shutdown(queue);
371 }
372 yield* Effect.forEach(
373 disconnected,
374 ({ deferred, context }) =>
375 Deferred.fail(deferred, new PreviewAutomationClientDisconnectedError(context)),
376 { discard: true },
377 );
378 });
379
380 const disconnect = Effect.fn("PreviewAutomationBroker.disconnect")(function* (
381 clientId: string,
382 queue: ClientConnection["queue"],
383 completeStream = false,
384 ) {
385 yield* SynchronizedRef.modifyEffect(state, (current) => {
386 if (current.clients.get(clientId)?.queue !== queue) {
387 return Effect.succeed([undefined, current] as const);
388 }
389 const removed = removeConnectionFromState(current, clientId, queue);
390 return closeConnection(queue, removed.disconnected, completeStream).pipe(
391 Effect.as([undefined, removed.state] as const),
392 );
393 });
394 });
395
396 const acquireConnection = Effect.fn("PreviewAutomationBroker.acquireConnection")(function* (
397 host: PreviewAutomationHost,
398 options: PreviewAutomationConnectOptions | undefined,
399 ) {
400 const clientId = host.clientId;
401 const queue = yield* Queue.unbounded<PreviewAutomationStreamEvent, Cause.Done>();
402 const connectionId = yield* random.uuidV4();
403 yield* Queue.offer(queue, { type: "connected", connectionId });
404 const connection: ClientConnection = {
405 clientId,
406 connectionId,
407 environmentId: host.environmentId,
408 supportedOperations: new Set(host.supportedOperations ?? PREVIEW_AUTOMATION_V1_OPERATIONS),
409 focused: false,
410 preferred: options?.preferred ?? false,
411 liveTabs: [],
412 focusOrder: 0,
413 queue,
414 };
415 const registration = yield* SynchronizedRef.modify(state, (current) => {
416 const previousConnection = current.clients.get(clientId);
417 const removed = previousConnection
418 ? removeConnectionFromState(current, clientId, previousConnection.queue)
419 : { state: current, disconnected: [] };
420 const clients = new Map(removed.state.clients);
421 const focusSequence = removed.state.focusSequence + 1;
422 const registeredConnection = { ...connection, focusOrder: focusSequence };
423 clients.set(clientId, registeredConnection);
424 return [
425 {
426 previousConnection,
427 disconnected: removed.disconnected,
428 registeredConnection,
429 },
430 { ...removed.state, clients, focusSequence },
431 ] as const;
432 });
433 if (registration.previousConnection) {
434 yield* closeConnection(registration.previousConnection.queue, registration.disconnected);
435 }
436 return registration.registeredConnection;
437 });
438
439 const connect: PreviewAutomationBroker["Service"]["connect"] = Effect.fn(
440 "PreviewAutomationBroker.connect",
441 )((host, options) =>
442 Effect.succeed(
443 Stream.unwrap(
444 Effect.acquireRelease(acquireConnection(host, options), (connection) =>
445 disconnect(connection.clientId, connection.queue),
446 ).pipe(Effect.map((connection) => Stream.fromQueue(connection.queue))),
447 ),
448 ),
449 );
450
451 const focusHost: PreviewAutomationBroker["Service"]["focusHost"] = Effect.fn(
452 "PreviewAutomationBroker.focusHost",
453 )(function* (host) {
454 yield* SynchronizedRef.update(state, (current) => {
455 const currentHost = current.clients.get(host.clientId);
456 if (
457 !currentHost ||
458 currentHost.environmentId !== host.environmentId ||
459 currentHost.connectionId !== host.connectionId
460 ) {
461 return current;
462 }
463 const clients = new Map(current.clients);
464 const focusSequence = host.focused ? current.focusSequence + 1 : current.focusSequence;
465 clients.set(host.clientId, {
466 ...currentHost,
467 focused: host.focused,
468 liveTabs: host.liveTabs ?? currentHost.liveTabs,
469 focusOrder: host.focused ? focusSequence : currentHost.focusOrder,
470 });
471 return { ...current, clients, focusSequence };
472 });
473 });
474
475 const respond: PreviewAutomationBroker["Service"]["respond"] = Effect.fn(
476 "PreviewAutomationBroker.respond",
477 )(function* (response) {
478 const pending = yield* SynchronizedRef.modify(state, (current) => {
479 const entry = current.pending.get(response.requestId);
480 if (
481 !entry ||
482 entry.context.clientId !== response.clientId ||
483 entry.context.connectionId !== response.connectionId
484 ) {
485 return [undefined, current] as const;
486 }
487 const next = new Map(current.pending);
488 next.delete(response.requestId);
489 return [entry, { ...current, pending: next }] as const;
490 });
491 if (!pending) return;
492 if (response.ok) {
493 yield* Deferred.succeed(pending.deferred, response.result);
494 } else {
495 yield* Deferred.fail(
496 pending.deferred,
497 response.error
498 ? classifyResponseError(pending.context, response.error)
499 : new PreviewAutomationMalformedResponseError(pending.context),
500 );
501 }
502 });
503
504 const invoke = Effect.fn("PreviewAutomationBroker.invoke")(function* <A = unknown>(
505 input: Parameters<PreviewAutomationBroker["Service"]["invoke"]>[0],
506 ): Effect.fn.Return<A, PreviewAutomationError> {
507 const deferred = yield* Deferred.make<unknown, PreviewAutomationError>();
508 const route = yield* SynchronizedRef.modify(state, (current) => {
509 const assignments = new Map(
510 Array.from(current.assignments).filter(([, assignment]) => {
511 const connection = current.clients.get(assignment.clientId);
512 return (
513 connection?.connectionId === assignment.connectionId &&
514 connection.queue === assignment.queue
515 );
516 }),
517 );
518 const assignmentKey = hostAssignmentKey(input.scope);
519 const assigned = assignments.get(assignmentKey);
520 const assignedConnection = assigned ? current.clients.get(assigned.clientId) : undefined;
521 const hasLiveAssignment = assignedConnection?.environmentId === input.scope.environmentId;
522 // Pin interactions to one desktop runtime so cookie/DOM state cannot jump between hosts.
523 const ownsTargetTab = (host: ClientConnection, visibleOnly = false) =>
524 host.liveTabs.some(
525 (tab) =>
526 tab.threadId === input.scope.thread.threadId &&
527 (!visibleOnly || tab.visible === true) &&
528 (input.tabId === undefined || tab.tabId === input.tabId),
529 );
530 const connection =
531 hasLiveAssignment && supportsOperation(assignedConnection, input.operation)
532 ? assignedConnection
533 : hasLiveAssignment
534 ? undefined
535 : Array.from(current.clients.values())
536 .filter(
537 (host) =>
538 host.environmentId === input.scope.environmentId &&
539 supportsOperation(host, input.operation),
540 )
541 .sort(
542 (left, right) =>
543 Number(input.tabId !== undefined && ownsTargetTab(right)) -
544 Number(input.tabId !== undefined && ownsTargetTab(left)) ||
545 Number(right.preferred) - Number(left.preferred) ||
546 Number(ownsTargetTab(right, true)) - Number(ownsTargetTab(left, true)) ||
547 Number(ownsTargetTab(right)) - Number(ownsTargetTab(left)) ||
548 Number(right.focused) - Number(left.focused) ||
549 right.focusOrder - left.focusOrder,
550 )[0];
551 if (!connection) {
552 if (!hasLiveAssignment) assignments.delete(assignmentKey);
553 return [undefined, { ...current, assignments }] as const;
554 }
555 // First open may install Chromium for ten minutes; keep it alive without replaying effects.
556 const timeoutMs =
557 input.timeoutMs ?? (input.operation === "open" && connection.preferred ? 660_000 : 15_000);
558 const canReuseAssignedTab =
559 assigned !== undefined &&
560 assigned.connectionId === connection.connectionId &&
561 assigned.queue === connection.queue;
562 assignments.set(assignmentKey, {
563 clientId: connection.clientId,
564 connectionId: connection.connectionId,
565 queue: connection.queue,
566 ...(canReuseAssignedTab && assigned.tabId !== undefined ? { tabId: assigned.tabId } : {}),
567 ...(canReuseAssignedTab && assigned.tabSequence !== undefined
568 ? { tabSequence: assigned.tabSequence }
569 : {}),
570 });
571
572 const requestSequence = current.requestSequence;
573 const requestId = `preview-${requestSequence}`;
574 const tabId = input.tabId ?? (canReuseAssignedTab ? assigned.tabId : undefined);
575 const selectorDiagnostics = selectorDiagnosticsFromInput(input.input);
576 const context: PreviewAutomationRequestErrorContext = {
577 operation: input.operation,
578 environmentId: input.scope.environmentId,
579 threadId: input.scope.thread.threadId,
580 providerSessionId: input.scope.thread.providerSessionId,
581 providerInstanceId: input.scope.thread.providerInstanceId,
582 clientId: connection.clientId,
583 connectionId: connection.connectionId,
584 requestId,
585 ...(tabId === undefined ? {} : { tabId }),
586 timeoutMs,
587 ...selectorDiagnostics,
588 };
589 const pending = new Map(current.pending);
590 pending.set(requestId, { queue: connection.queue, deferred, context });
591 return [
592 { connection, requestId, requestContext: context, requestSequence },
593 { ...current, assignments, pending, requestSequence: current.requestSequence + 1 },
594 ] as const;
595 });
596 if (!route) {
597 return yield* new PreviewAutomationNoAvailableHostError({
598 operation: input.operation,
599 environmentId: input.scope.environmentId,
600 threadId: input.scope.thread.threadId,
601 providerSessionId: input.scope.thread.providerSessionId,
602 providerInstanceId: input.scope.thread.providerInstanceId,
603 });
604 }
605 const { connection, requestId, requestContext, requestSequence } = route;
606 const { timeoutMs } = requestContext;
607 input.onTargetTab?.(requestContext.tabId);
608 const removePending = SynchronizedRef.update(state, (next) => {
609 if (!next.pending.has(requestId)) return next;
610 const pending = new Map(next.pending);
611 pending.delete(requestId);
612 return { ...next, pending };
613 });
614 const awaitResponse = Effect.fn("PreviewAutomationBroker.awaitResponse")(function* () {
615 const offered = yield* SynchronizedRef.modifyEffect(state, (current) => {
616 // Serialize generation checks and offers with queue closure; routes can outlive eviction.
617 if (
618 current.clients.get(connection.clientId)?.queue !== connection.queue ||
619 !current.pending.has(requestId)
620 ) {
621 return Effect.succeed([false, current] as const);
622 }
623 return Queue.offer(connection.queue, {
624 type: "request",
625 connectionId: connection.connectionId,
626 request: {
627 requestId,
628 threadId: input.scope.thread.threadId,
629 tabId: requestContext.tabId,
630 tabIdExplicit: input.tabId !== undefined,
631 agentSessionId: hostAssignmentKey(input.scope),
632 operation: input.operation,
633 input: input.input,
634 timeoutMs,
635 },
636 }).pipe(Effect.map((offered) => [offered, current] as const));
637 });
638 if (!offered) {
639 const completion = yield* Deferred.poll(deferred);
640 if (Option.isSome(completion)) {
641 return (yield* completion.value) as A;
642 }
643 return yield* new PreviewAutomationRequestQueueClosedError(requestContext);
644 }
645 // The browser timer starts on delivery; allow its timeout response before evicting the host.
646 const responseTimeoutMs =
647 input.updateCurrentTab === false ? timeoutMs : timeoutMs + HOST_RESPONSE_GRACE_MS;
648 const result = yield* Deferred.await(deferred).pipe(Effect.timeoutOption(responseTimeoutMs));
649 return yield* Option.match(result, {
650 // The enclosing operation owns the span for this inline handler.
651 onNone: Effect.fnUntraced(function* () {
652 // Never replay possibly applied actions; slow metadata reads must not evict the host.
653 if (input.updateCurrentTab !== false) {
654 yield* disconnect(connection.clientId, connection.queue, true);
655 }
656 return yield* new PreviewAutomationTimeoutError(requestContext);
657 }),
658 onSome: (value) => Effect.succeed(value as A),
659 });
660 });
661 const result = yield* awaitResponse().pipe(Effect.ensuring(removePending));
662 if (input.updateCurrentTab === false) return result;
663 const responseTabId = readResultTabId(result);
664 const resultTabId = responseTabId === undefined ? input.tabId : responseTabId;
665 if (resultTabId === undefined) return result;
666 const assignmentKey = hostAssignmentKey(input.scope);
667 yield* SynchronizedRef.update(state, (current) => {
668 const assignment = current.assignments.get(assignmentKey);
669 if (
670 !assignment ||
671 assignment.connectionId !== connection.connectionId ||
672 assignment.queue !== connection.queue ||
673 (assignment.tabSequence ?? -1) > requestSequence
674 ) {
675 return current;
676 }
677 const assignments = new Map(current.assignments);
678 if (resultTabId === null) {
679 const { tabId: _tabId, ...withoutTabId } = assignment;
680 assignments.set(assignmentKey, { ...withoutTabId, tabSequence: requestSequence });
681 } else {
682 assignments.set(assignmentKey, {
683 ...assignment,
684 ...(resultTabId === undefined ? {} : { tabId: resultTabId }),
685 tabSequence: requestSequence,
686 });
687 }
688 return { ...current, assignments };
689 });
690 return result;
691 });
692
693 return PreviewAutomationBroker.of({ connect, focusHost, respond, invoke });
694}).pipe(Effect.withSpan("PreviewAutomationBroker.make"));
695
696export const layer = Layer.effect(PreviewAutomationBroker, make);