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

PreviewAutomationBroker.ts

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