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

PreviewAutomationBroker.ts

649 lines25.0 KB

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