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