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

PreviewAutomationBroker.ts

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