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

PreviewAutomationBroker.ts

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