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