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