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

PreviewAutomationBroker.ts

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