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

PreviewAutomationBroker.ts

585 lines22.1 KB

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