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