@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

main
ts 716 lines 27.9 KB
Raw
1 import {
2 PREVIEW_AUTOMATION_V1_OPERATIONS,
3 PreviewAutomationClientDisconnectedError,
4 PreviewAutomationControlInterruptedError,
5 PreviewAutomationControlReason,
6 PreviewAutomationExecutionError,
7 SERVER_BROWSER_AUTOMATION_CLIENT_ID,
8 PreviewAutomationInvalidSelectorError,
9 PreviewAutomationMalformedResponseError,
10 PreviewAutomationNoAvailableHostError,
11 PreviewAutomationRemoteUnavailableError,
12 PreviewAutomationRecordingTransferError,
13 PreviewAutomationRecordingDesktopUpdateRequiredError,
14 PreviewAutomationRecordingTooLargeError,
15 PreviewAutomationRecordingDeadlineExpiredError,
16 PreviewAutomationRequestQueueClosedError,
17 PreviewAutomationResultTooLargeError,
18 PreviewAutomationTabNotFoundError,
19 PreviewAutomationTargetNotEditableError,
20 PreviewAutomationTimeoutError,
21 PreviewAutomationTimeoutDetail,
22 PreviewAutomationUnsupportedClientError,
23 PreviewTabId,
24 type PreviewAutomationError,
25 type PreviewAutomationOperation,
26 type PreviewAutomationHost,
27 type PreviewAutomationHostFocus,
28 type PreviewAutomationResponse,
29 type PreviewAutomationStreamEvent,
30 } from "@t3tools/contracts";
31 import * as Context from "effect/Context";
32 import type * as Cause from "effect/Cause";
33 import * as SecureRandom from "effect/crypto/SecureRandom";
34 import * as Deferred from "effect/Deferred";
35 import * as Effect from "effect/Effect";
36 import * as Layer from "effect/Layer";
37 import * as Option from "effect/Option";
38 import * as Queue from "effect/Queue";
39 import * as Schema from "effect/Schema";
40 import * as Stream from "effect/Stream";
41 import * as SynchronizedRef from "effect/SynchronizedRef";
42
43 import * as McpInvocationContext from "./McpInvocationContext.ts";
44
45 const HOST_RESPONSE_GRACE_MS = 1_000;
46
47 export interface PreviewAutomationInvokeInput {
48 readonly scope: McpInvocationContext.McpThreadInvocationScope;
49 readonly operation: PreviewAutomationOperation;
50 readonly input: unknown;
51 readonly tabId?: PreviewTabId;
52 readonly timeoutMs?: number;
53 /** Background metadata reads must not change the agent's current tab. */
54 readonly updateCurrentTab?: boolean;
55 readonly onTargetTab?: (tabId: PreviewTabId | undefined) => void;
56 }
57
58 export interface PreviewAutomationConnectOptions {
59 readonly preferred?: boolean;
60 }
61
62 export class PreviewAutomationBroker extends Context.Service<
63 PreviewAutomationBroker,
64 {
65 readonly connect: (
66 host: PreviewAutomationHost,
67 options?: PreviewAutomationConnectOptions,
68 ) => Effect.Effect<Stream.Stream<PreviewAutomationStreamEvent>>;
69 readonly focusHost: (host: PreviewAutomationHostFocus) => Effect.Effect<void>;
70 readonly respond: (
71 response: PreviewAutomationResponse,
72 ) => Effect.Effect<void, PreviewAutomationError>;
73 readonly invoke: <A = unknown>(
74 request: PreviewAutomationInvokeInput,
75 ) => Effect.Effect<A, PreviewAutomationError>;
76 }
77 >()("t3/mcp/PreviewAutomationBroker") {}
78
79 interface ClientConnection {
80 readonly clientId: string;
81 readonly connectionId: string;
82 readonly environmentId: PreviewAutomationHost["environmentId"];
83 readonly supportedOperations: ReadonlySet<PreviewAutomationOperation>;
84 readonly focused: boolean;
85 readonly preferred: boolean;
86 readonly liveTabs: NonNullable<PreviewAutomationHostFocus["liveTabs"]>;
87 readonly focusOrder: number;
88 readonly queue: Queue.Queue<PreviewAutomationStreamEvent, Cause.Done>;
89 }
90
91 interface PendingRequest {
92 readonly queue: ClientConnection["queue"];
93 readonly deferred: Deferred.Deferred<unknown, PreviewAutomationError>;
94 readonly context: PreviewAutomationRequestErrorContext;
95 }
96
97 /** A lease belongs to this exact connectionId/queue; replacing the host invalidates it. */
98 interface HostAssignment {
99 readonly clientId: ClientConnection["clientId"];
100 readonly connectionId: ClientConnection["connectionId"];
101 readonly queue: ClientConnection["queue"];
102 readonly tabId?: PreviewTabId;
103 readonly tabSequence?: number;
104 }
105
106 interface PreviewAutomationRequestErrorContext {
107 readonly operation: PreviewAutomationOperation;
108 readonly environmentId: McpInvocationContext.McpInvocationScope["environmentId"];
109 readonly threadId: McpInvocationContext.McpThreadCaller["threadId"];
110 readonly providerSessionId: string;
111 readonly providerInstanceId: McpInvocationContext.McpThreadCaller["providerInstanceId"];
112 readonly clientId: string;
113 readonly connectionId: ClientConnection["connectionId"];
114 readonly requestId: string;
115 readonly tabId?: PreviewTabId;
116 readonly timeoutMs: number;
117 readonly selectorKind?: "locator" | "selector";
118 readonly selectorLength?: number;
119 }
120
121 interface BrokerState {
122 readonly clients: ReadonlyMap<string, ClientConnection>;
123 readonly assignments: ReadonlyMap<string, HostAssignment>;
124 readonly pending: ReadonlyMap<string, PendingRequest>;
125 readonly requestSequence: number;
126 readonly focusSequence: number;
127 }
128
129 const removeConnectionFromState = (
130 current: BrokerState,
131 clientId: string,
132 queue: ClientConnection["queue"],
133 ): { readonly state: BrokerState; readonly disconnected: ReadonlyArray<PendingRequest> } => {
134 const clients = new Map(current.clients);
135 const assignments = new Map(current.assignments);
136 const pending = new Map(current.pending);
137 const disconnected: PendingRequest[] = [];
138 if (current.clients.get(clientId)?.queue === queue) clients.delete(clientId);
139 for (const [assignmentKey, assignment] of assignments) {
140 if (assignment.queue === queue) assignments.delete(assignmentKey);
141 }
142 for (const [requestId, entry] of pending) {
143 if (entry.queue !== queue) continue;
144 pending.delete(requestId);
145 disconnected.push(entry);
146 }
147 return {
148 state: { ...current, clients, assignments, pending },
149 disconnected,
150 };
151 };
152
153 const selectorDiagnosticsFromInput = (
154 input: unknown,
155 ): Pick<PreviewAutomationRequestErrorContext, "selectorKind" | "selectorLength"> => {
156 if (typeof input !== "object" || input === null) return {};
157 if ("locator" in input && typeof input.locator === "string") {
158 return { selectorKind: "locator", selectorLength: input.locator.length };
159 }
160 if ("selector" in input && typeof input.selector === "string") {
161 return { selectorKind: "selector", selectorLength: input.selector.length };
162 }
163 return {};
164 };
165
166 /** Codex/OpenCode share sessions across threads; include thread id to isolate tabs and ownership. */
167 const hostAssignmentKey = (scope: McpInvocationContext.McpThreadInvocationScope): string =>
168 `${scope.environmentId}\u0000${scope.thread.providerSessionId}\u0000${scope.thread.threadId}`;
169
170 const isPreviewTabId = Schema.is(PreviewTabId);
171 const decodeControlReason = Schema.decodeUnknownOption(PreviewAutomationControlReason);
172
173 const readResultTabId = (result: unknown): PreviewTabId | null | undefined => {
174 if (typeof result !== "object" || result === null || !("tabId" in result)) return undefined;
175 const tabId = result.tabId;
176 return tabId === null || isPreviewTabId(tabId) ? tabId : undefined;
177 };
178
179 const supportsOperation = (
180 connection: ClientConnection,
181 operation: PreviewAutomationOperation,
182 ): boolean => connection.supportedOperations.has(operation);
183
184 type RemoteDetailKind = "null" | "array" | "object" | "string" | "number" | "boolean";
185
186 function remoteDetailKind(detail: unknown): RemoteDetailKind {
187 if (detail === null) return "null";
188 if (Array.isArray(detail)) return "array";
189 switch (typeof detail) {
190 case "string":
191 return "string";
192 case "number":
193 return "number";
194 case "boolean":
195 return "boolean";
196 default:
197 return "object";
198 }
199 }
200
201 const readRemoteTimeoutMs = (detail: unknown): number | undefined => {
202 if (typeof detail !== "object" || detail === null || !("timeoutMs" in detail)) return undefined;
203 const timeoutMs = detail.timeoutMs;
204 return typeof timeoutMs === "number" && Number.isInteger(timeoutMs) && timeoutMs > 0
205 ? timeoutMs
206 : undefined;
207 };
208
209 const readRemoteReason = (detail: unknown): string | undefined =>
210 typeof detail === "object" &&
211 detail !== null &&
212 "reason" in detail &&
213 typeof detail.reason === "string"
214 ? detail.reason
215 : undefined;
216
217 const MAX_REASON_CHARS = 500;
218 const decodeTimeoutDetail = Schema.decodeUnknownOption(PreviewAutomationTimeoutDetail);
219
220 const classifyResponseError = (
221 context: PreviewAutomationRequestErrorContext,
222 error: NonNullable<PreviewAutomationResponse["error"]>,
223 ): PreviewAutomationError => {
224 const remoteDiagnostics = {
225 remoteTag: error._tag,
226 remoteMessageLength: error.message.length,
227 ...(error.detail === undefined ? {} : { remoteDetailKind: remoteDetailKind(error.detail) }),
228 cause: error,
229 };
230 switch (error._tag) {
231 case "PreviewAutomationRecordingDesktopUpdateRequiredError":
232 return new PreviewAutomationRecordingDesktopUpdateRequiredError({
233 threadId: context.threadId,
234 cause: error,
235 });
236 case "PreviewAutomationRecordingTooLargeError":
237 return new PreviewAutomationRecordingTooLargeError({
238 threadId: context.threadId,
239 cause: error,
240 });
241 case "PreviewAutomationRecordingDeadlineExpiredError":
242 return new PreviewAutomationRecordingDeadlineExpiredError({
243 threadId: context.threadId,
244 cause: error,
245 });
246 case "PreviewAutomationRecordingTransferError":
247 return new PreviewAutomationRecordingTransferError({
248 threadId: context.threadId,
249 cause: error,
250 });
251 case "PreviewAutomationNoAvailableHostError":
252 return new PreviewAutomationNoAvailableHostError({
253 ...context,
254 ...remoteDiagnostics,
255 });
256 case "PreviewAutomationUnsupportedClientError":
257 return new PreviewAutomationUnsupportedClientError({
258 ...context,
259 ...remoteDiagnostics,
260 });
261 case "PreviewAutomationTabNotFoundError":
262 return new PreviewAutomationTabNotFoundError({
263 ...context,
264 ...remoteDiagnostics,
265 });
266 case "PreviewAutomationTimeoutError": {
267 const remoteTimeoutMs = readRemoteTimeoutMs(error.detail);
268 const detail = decodeTimeoutDetail(error.detail);
269 const remoteReason = readRemoteReason(error.detail);
270 return new PreviewAutomationTimeoutError({
271 ...context,
272 ...remoteDiagnostics,
273 ...(context.clientId === SERVER_BROWSER_AUTOMATION_CLIENT_ID && remoteReason !== undefined
274 ? { reason: remoteReason.slice(0, MAX_REASON_CHARS) }
275 : {}),
276 ...(remoteTimeoutMs === undefined
277 ? {}
278 : { timeoutMs: Math.min(context.timeoutMs, remoteTimeoutMs) }),
279 ...(Option.isSome(detail) ? { pendingStages: detail.value.pendingStages } : {}),
280 });
281 }
282 case "PreviewAutomationControlInterruptedError": {
283 const reason = decodeControlReason(error.detail);
284 return new PreviewAutomationControlInterruptedError({
285 ...context,
286 ...remoteDiagnostics,
287 ...(Option.isSome(reason) ? { reason: reason.value } : {}),
288 });
289 }
290 case "PreviewAutomationInvalidSelectorError": {
291 const staleRef =
292 typeof error.detail === "object" &&
293 error.detail !== null &&
294 "staleRef" in error.detail &&
295 error.detail.staleRef === true;
296 return new PreviewAutomationInvalidSelectorError({
297 ...context,
298 ...remoteDiagnostics,
299 ...(staleRef ? { staleRef } : {}),
300 });
301 }
302 case "PreviewAutomationTargetNotEditableError": {
303 const detail =
304 typeof error.detail === "object" && error.detail !== null ? error.detail : undefined;
305 const remoteSelectorKind =
306 detail &&
307 "selectorKind" in detail &&
308 (detail.selectorKind === "focused-element" ||
309 detail.selectorKind === "locator" ||
310 detail.selectorKind === "selector")
311 ? detail.selectorKind
312 : undefined;
313 const remoteSelectorLength =
314 detail &&
315 "selectorLength" in detail &&
316 typeof detail.selectorLength === "number" &&
317 Number.isInteger(detail.selectorLength) &&
318 detail.selectorLength >= 0
319 ? detail.selectorLength
320 : undefined;
321 return new PreviewAutomationTargetNotEditableError({
322 ...context,
323 ...remoteDiagnostics,
324 ...(remoteSelectorKind === undefined && context.selectorKind === undefined
325 ? {}
326 : { selectorKind: remoteSelectorKind ?? context.selectorKind }),
327 ...(remoteSelectorLength === undefined && context.selectorLength === undefined
328 ? {}
329 : { selectorLength: remoteSelectorLength ?? context.selectorLength }),
330 });
331 }
332 case "PreviewAutomationResultTooLargeError": {
333 const detail =
334 typeof error.detail === "object" && error.detail !== null ? error.detail : undefined;
335 const maximumBytes =
336 detail &&
337 "maximumBytes" in detail &&
338 typeof detail.maximumBytes === "number" &&
339 Number.isInteger(detail.maximumBytes) &&
340 detail.maximumBytes > 0
341 ? detail.maximumBytes
342 : undefined;
343 return new PreviewAutomationResultTooLargeError({
344 ...context,
345 ...remoteDiagnostics,
346 ...(maximumBytes === undefined ? {} : { maximumBytes }),
347 });
348 }
349 case "PreviewAutomationUnavailableError":
350 return new PreviewAutomationRemoteUnavailableError({
351 ...context,
352 ...remoteDiagnostics,
353 });
354 default:
355 return new PreviewAutomationExecutionError({
356 ...context,
357 ...remoteDiagnostics,
358 ...(context.clientId === SERVER_BROWSER_AUTOMATION_CLIENT_ID
359 ? { reason: error.message.slice(0, MAX_REASON_CHARS) }
360 : {}),
361 });
362 }
363 };
364
365 export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
366 const random = yield* SecureRandom.SecureRandom;
367 const state = yield* SynchronizedRef.make<BrokerState>({
368 clients: new Map(),
369 assignments: new Map(),
370 pending: new Map(),
371 requestSequence: 0,
372 focusSequence: 0,
373 });
374
375 const closeConnection = Effect.fn("PreviewAutomationBroker.closeConnection")(function* (
376 queue: ClientConnection["queue"],
377 disconnected: ReadonlyArray<PendingRequest>,
378 completeStream = false,
379 ) {
380 if (completeStream) {
381 // Close the evicted generation's RPC stream so a responsive desktop can re-register.
382 yield* Queue.clear(queue);
383 yield* Queue.end(queue);
384 } else {
385 // Replaced registrations must not reconnect and displace their successor.
386 yield* Queue.shutdown(queue);
387 }
388 yield* Effect.forEach(
389 disconnected,
390 ({ deferred, context }) =>
391 Deferred.fail(deferred, new PreviewAutomationClientDisconnectedError(context)),
392 { discard: true },
393 );
394 });
395
396 const disconnect = Effect.fn("PreviewAutomationBroker.disconnect")(function* (
397 clientId: string,
398 queue: ClientConnection["queue"],
399 completeStream = false,
400 ) {
401 yield* SynchronizedRef.modifyEffect(state, (current) => {
402 if (current.clients.get(clientId)?.queue !== queue) {
403 return Effect.succeed([undefined, current] as const);
404 }
405 const removed = removeConnectionFromState(current, clientId, queue);
406 return closeConnection(queue, removed.disconnected, completeStream).pipe(
407 Effect.as([undefined, removed.state] as const),
408 );
409 });
410 });
411
412 const acquireConnection = Effect.fn("PreviewAutomationBroker.acquireConnection")(function* (
413 host: PreviewAutomationHost,
414 options: PreviewAutomationConnectOptions | undefined,
415 ) {
416 const clientId = host.clientId;
417 const queue = yield* Queue.unbounded<PreviewAutomationStreamEvent, Cause.Done>();
418 const connectionId = yield* random.uuidV4();
419 yield* Queue.offer(queue, { type: "connected", connectionId });
420 const connection: ClientConnection = {
421 clientId,
422 connectionId,
423 environmentId: host.environmentId,
424 supportedOperations: new Set(host.supportedOperations ?? PREVIEW_AUTOMATION_V1_OPERATIONS),
425 focused: false,
426 preferred: options?.preferred ?? false,
427 liveTabs: [],
428 focusOrder: 0,
429 queue,
430 };
431 const registration = yield* SynchronizedRef.modify(state, (current) => {
432 const previousConnection = current.clients.get(clientId);
433 const removed = previousConnection
434 ? removeConnectionFromState(current, clientId, previousConnection.queue)
435 : { state: current, disconnected: [] };
436 const clients = new Map(removed.state.clients);
437 const focusSequence = removed.state.focusSequence + 1;
438 const registeredConnection = { ...connection, focusOrder: focusSequence };
439 clients.set(clientId, registeredConnection);
440 return [
441 {
442 previousConnection,
443 disconnected: removed.disconnected,
444 registeredConnection,
445 },
446 { ...removed.state, clients, focusSequence },
447 ] as const;
448 });
449 if (registration.previousConnection) {
450 yield* closeConnection(registration.previousConnection.queue, registration.disconnected);
451 }
452 return registration.registeredConnection;
453 });
454
455 const connect: PreviewAutomationBroker["Service"]["connect"] = Effect.fn(
456 "PreviewAutomationBroker.connect",
457 )((host, options) =>
458 Effect.succeed(
459 Stream.unwrap(
460 Effect.acquireRelease(acquireConnection(host, options), (connection) =>
461 disconnect(connection.clientId, connection.queue),
462 ).pipe(Effect.map((connection) => Stream.fromQueue(connection.queue))),
463 ),
464 ),
465 );
466
467 const focusHost: PreviewAutomationBroker["Service"]["focusHost"] = Effect.fn(
468 "PreviewAutomationBroker.focusHost",
469 )(function* (host) {
470 yield* SynchronizedRef.update(state, (current) => {
471 const currentHost = current.clients.get(host.clientId);
472 if (
473 !currentHost ||
474 currentHost.environmentId !== host.environmentId ||
475 currentHost.connectionId !== host.connectionId
476 ) {
477 return current;
478 }
479 const clients = new Map(current.clients);
480 const focusSequence = host.focused ? current.focusSequence + 1 : current.focusSequence;
481 clients.set(host.clientId, {
482 ...currentHost,
483 focused: host.focused,
484 liveTabs: host.liveTabs ?? currentHost.liveTabs,
485 focusOrder: host.focused ? focusSequence : currentHost.focusOrder,
486 });
487 return { ...current, clients, focusSequence };
488 });
489 });
490
491 const respond: PreviewAutomationBroker["Service"]["respond"] = Effect.fn(
492 "PreviewAutomationBroker.respond",
493 )(function* (response) {
494 const pending = yield* SynchronizedRef.modify(state, (current) => {
495 const entry = current.pending.get(response.requestId);
496 if (
497 !entry ||
498 entry.context.clientId !== response.clientId ||
499 entry.context.connectionId !== response.connectionId
500 ) {
501 return [undefined, current] as const;
502 }
503 const next = new Map(current.pending);
504 next.delete(response.requestId);
505 return [entry, { ...current, pending: next }] as const;
506 });
507 if (!pending) return;
508 if (response.ok) {
509 yield* Deferred.succeed(pending.deferred, response.result);
510 } else {
511 yield* Deferred.fail(
512 pending.deferred,
513 response.error
514 ? classifyResponseError(pending.context, response.error)
515 : new PreviewAutomationMalformedResponseError(pending.context),
516 );
517 }
518 });
519
520 const invoke = Effect.fn("PreviewAutomationBroker.invoke")(function* <A = unknown>(
521 input: Parameters<PreviewAutomationBroker["Service"]["invoke"]>[0],
522 ): Effect.fn.Return<A, PreviewAutomationError> {
523 const deferred = yield* Deferred.make<unknown, PreviewAutomationError>();
524 const route = yield* SynchronizedRef.modify(state, (current) => {
525 const assignments = new Map(
526 Array.from(current.assignments).filter(([, assignment]) => {
527 const connection = current.clients.get(assignment.clientId);
528 return (
529 connection?.connectionId === assignment.connectionId &&
530 connection.queue === assignment.queue
531 );
532 }),
533 );
534 const assignmentKey = hostAssignmentKey(input.scope);
535 const assigned = assignments.get(assignmentKey);
536 const assignedConnection = assigned ? current.clients.get(assigned.clientId) : undefined;
537 const hasLiveAssignment = assignedConnection?.environmentId === input.scope.environmentId;
538 // Pin interactions to one desktop runtime so cookie/DOM state cannot jump between hosts.
539 const ownsTargetTab = (host: ClientConnection, visibleOnly = false) =>
540 host.liveTabs.some(
541 (tab) =>
542 tab.threadId === input.scope.thread.threadId &&
543 (!visibleOnly || tab.visible === true) &&
544 (input.tabId === undefined || tab.tabId === input.tabId),
545 );
546 const connection =
547 hasLiveAssignment && supportsOperation(assignedConnection, input.operation)
548 ? assignedConnection
549 : hasLiveAssignment
550 ? undefined
551 : Array.from(current.clients.values())
552 .filter(
553 (host) =>
554 host.environmentId === input.scope.environmentId &&
555 supportsOperation(host, input.operation),
556 )
557 .sort(
558 (left, right) =>
559 Number(input.tabId !== undefined && ownsTargetTab(right)) -
560 Number(input.tabId !== undefined && ownsTargetTab(left)) ||
561 Number(right.preferred) - Number(left.preferred) ||
562 Number(ownsTargetTab(right, true)) - Number(ownsTargetTab(left, true)) ||
563 Number(ownsTargetTab(right)) - Number(ownsTargetTab(left)) ||
564 Number(right.focused) - Number(left.focused) ||
565 right.focusOrder - left.focusOrder,
566 )[0];
567 if (!connection) {
568 if (!hasLiveAssignment) assignments.delete(assignmentKey);
569 return [undefined, { ...current, assignments }] as const;
570 }
571 // First open may install Chromium for ten minutes; keep it alive without replaying effects.
572 const timeoutMs =
573 input.timeoutMs ?? (input.operation === "open" && connection.preferred ? 660_000 : 15_000);
574 const canReuseAssignedTab =
575 assigned !== undefined &&
576 assigned.connectionId === connection.connectionId &&
577 assigned.queue === connection.queue;
578 assignments.set(assignmentKey, {
579 clientId: connection.clientId,
580 connectionId: connection.connectionId,
581 queue: connection.queue,
582 ...(canReuseAssignedTab && assigned.tabId !== undefined ? { tabId: assigned.tabId } : {}),
583 ...(canReuseAssignedTab && assigned.tabSequence !== undefined
584 ? { tabSequence: assigned.tabSequence }
585 : {}),
586 });
587
588 const requestSequence = current.requestSequence;
589 const requestId = `preview-${requestSequence}`;
590 const tabId = input.tabId ?? (canReuseAssignedTab ? assigned.tabId : undefined);
591 const selectorDiagnostics = selectorDiagnosticsFromInput(input.input);
592 const context: PreviewAutomationRequestErrorContext = {
593 operation: input.operation,
594 environmentId: input.scope.environmentId,
595 threadId: input.scope.thread.threadId,
596 providerSessionId: input.scope.thread.providerSessionId,
597 providerInstanceId: input.scope.thread.providerInstanceId,
598 clientId: connection.clientId,
599 connectionId: connection.connectionId,
600 requestId,
601 ...(tabId === undefined ? {} : { tabId }),
602 timeoutMs,
603 ...selectorDiagnostics,
604 };
605 const pending = new Map(current.pending);
606 pending.set(requestId, { queue: connection.queue, deferred, context });
607 return [
608 { connection, requestId, requestContext: context, requestSequence },
609 { ...current, assignments, pending, requestSequence: current.requestSequence + 1 },
610 ] as const;
611 });
612 if (!route) {
613 return yield* new PreviewAutomationNoAvailableHostError({
614 operation: input.operation,
615 environmentId: input.scope.environmentId,
616 threadId: input.scope.thread.threadId,
617 providerSessionId: input.scope.thread.providerSessionId,
618 providerInstanceId: input.scope.thread.providerInstanceId,
619 });
620 }
621 const { connection, requestId, requestContext, requestSequence } = route;
622 const { timeoutMs } = requestContext;
623 input.onTargetTab?.(requestContext.tabId);
624 const removePending = SynchronizedRef.update(state, (next) => {
625 if (!next.pending.has(requestId)) return next;
626 const pending = new Map(next.pending);
627 pending.delete(requestId);
628 return { ...next, pending };
629 });
630 const awaitResponse = Effect.fn("PreviewAutomationBroker.awaitResponse")(function* () {
631 const offered = yield* SynchronizedRef.modifyEffect(state, (current) => {
632 // Serialize generation checks and offers with queue closure; routes can outlive eviction.
633 if (
634 current.clients.get(connection.clientId)?.queue !== connection.queue ||
635 !current.pending.has(requestId)
636 ) {
637 return Effect.succeed([false, current] as const);
638 }
639 return Queue.offer(connection.queue, {
640 type: "request",
641 connectionId: connection.connectionId,
642 request: {
643 requestId,
644 threadId: input.scope.thread.threadId,
645 tabId: requestContext.tabId,
646 tabIdExplicit: input.tabId !== undefined,
647 agentSessionId: hostAssignmentKey(input.scope),
648 operation: input.operation,
649 input: input.input,
650 timeoutMs,
651 },
652 }).pipe(Effect.map((offered) => [offered, current] as const));
653 });
654 if (!offered) {
655 const completion = yield* Deferred.poll(deferred);
656 if (Option.isSome(completion)) {
657 return (yield* completion.value) as A;
658 }
659 return yield* new PreviewAutomationRequestQueueClosedError(requestContext);
660 }
661 // The browser timer starts on delivery; allow its timeout response before evicting the host.
662 const responseTimeoutMs =
663 input.updateCurrentTab === false ? timeoutMs : timeoutMs + HOST_RESPONSE_GRACE_MS;
664 const result = yield* Deferred.await(deferred).pipe(Effect.timeoutOption(responseTimeoutMs));
665 return yield* Option.match(result, {
666 // The enclosing operation owns the span for this inline handler.
667 onNone: Effect.fnUntraced(function* () {
668 // Never replay possibly applied actions; slow metadata reads must not evict the host.
669 // The in-process server browser is shared by every thread and cannot hang its stream.
670 if (
671 input.updateCurrentTab !== false &&
672 connection.clientId !== SERVER_BROWSER_AUTOMATION_CLIENT_ID
673 ) {
674 yield* disconnect(connection.clientId, connection.queue, true);
675 }
676 return yield* new PreviewAutomationTimeoutError(requestContext);
677 }),
678 onSome: (value) => Effect.succeed(value as A),
679 });
680 });
681 const result = yield* awaitResponse().pipe(Effect.ensuring(removePending));
682 if (input.updateCurrentTab === false) return result;
683 const responseTabId = readResultTabId(result);
684 const resultTabId = responseTabId === undefined ? input.tabId : responseTabId;
685 if (resultTabId === undefined) return result;
686 const assignmentKey = hostAssignmentKey(input.scope);
687 yield* SynchronizedRef.update(state, (current) => {
688 const assignment = current.assignments.get(assignmentKey);
689 if (
690 !assignment ||
691 assignment.connectionId !== connection.connectionId ||
692 assignment.queue !== connection.queue ||
693 (assignment.tabSequence ?? -1) > requestSequence
694 ) {
695 return current;
696 }
697 const assignments = new Map(current.assignments);
698 if (resultTabId === null) {
699 const { tabId: _tabId, ...withoutTabId } = assignment;
700 assignments.set(assignmentKey, { ...withoutTabId, tabSequence: requestSequence });
701 } else {
702 assignments.set(assignmentKey, {
703 ...assignment,
704 ...(resultTabId === undefined ? {} : { tabId: resultTabId }),
705 tabSequence: requestSequence,
706 });
707 }
708 return { ...current, assignments };
709 });
710 return result;
711 });
712
713 return PreviewAutomationBroker.of({ connect, focusHost, respond, invoke });
714 }).pipe(Effect.withSpan("PreviewAutomationBroker.make"));
715
716 export const layer = Layer.effect(PreviewAutomationBroker, make);