Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PreviewAutomationBroker.ts

744 lines29.2 KB

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