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

PreviewAutomationBroker.ts

700 lines27.2 KB

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