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

previewAutomation.ts

824 lines30.4 KB

1import { Schema } from "effect";
2​
3import { EnvironmentId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts";
4import {
5 PREVIEW_VIEWPORT_MAX_AREA,
6 PreviewRenderedViewportSize,
7 PreviewTabId,
8 PreviewViewportPresetId,
9 PreviewViewportSetting,
10 PreviewViewportSize,
11} from "./preview.ts";
12import { ProviderInstanceId } from "./providerInstance.ts";
13​
14const BoundedUrl = Schema.String.check(Schema.isTrimmed())
15 .check(
16 Schema.isNonEmpty({
17 description:
18 "Absolute http(s) URL or a schemeless host such as t3.chat or localhost:5173. Schemeless public hosts use https; loopback hosts use http.",
19 }),
20 )
21 .check(Schema.isMaxLength(2048));
22const OptionalTimeoutMs = Schema.optional(
23 Schema.Int.check(Schema.isGreaterThan(0))
24 .check(Schema.isLessThanOrEqualTo(60_000))
25 .annotate({ description: "Maximum wait in milliseconds. Defaults to 15000; maximum 60000." }),
26).annotate({ description: "Maximum wait in milliseconds. Defaults to 15000; maximum 60000." });
27​
28/** Operations understood by desktop hosts predating viewport resizing. */
29export const PREVIEW_AUTOMATION_V1_OPERATIONS = [
30 "status",
31 "open",
32 "navigate",
33 "snapshot",
34 "click",
35 "type",
36 "press",
37 "scroll",
38 "evaluate",
39 "waitFor",
40 "recordingStart",
41 "recordingStop",
42] as const;
43​
44/** Advertised by current desktop hosts for mixed-version routing. */
45export const PREVIEW_AUTOMATION_OPERATIONS = [
46 ...PREVIEW_AUTOMATION_V1_OPERATIONS,
47 "resize",
48] as const;
49​
50export const PreviewAutomationOperation = Schema.Literals(PREVIEW_AUTOMATION_OPERATIONS);
51export type PreviewAutomationOperation = typeof PreviewAutomationOperation.Type;
52​
53export const PreviewAutomationStatus = Schema.Struct({
54 available: Schema.Boolean,
55 visible: Schema.Boolean,
56 tabId: Schema.NullOr(PreviewTabId),
57 url: Schema.NullOr(Schema.String),
58 title: Schema.NullOr(Schema.String),
59 loading: Schema.Boolean,
60 /** Optional for compatibility with desktop hosts predating viewport sizing. */
61 viewportSetting: Schema.optional(PreviewViewportSetting),
62 /** Measured guest-page viewport in CSS pixels when a webview is ready. */
63 viewport: Schema.optional(PreviewRenderedViewportSize),
64});
65export type PreviewAutomationStatus = typeof PreviewAutomationStatus.Type;
66​
67export const PreviewAutomationOpenInput = Schema.Struct({
68 url: Schema.optional(BoundedUrl).annotate({
69 description:
70 "Optional initial page URL, for example https://t3.chat or localhost:5173. Omit to open a blank tab.",
71 }),
72 show: Schema.optional(
73 Schema.Boolean.annotate({
74 description: "Whether to reveal the preview panel to the human. Defaults to true.",
75 }),
76 ),
77 reuseExistingTab: Schema.optional(
78 Schema.Boolean.annotate({
79 description:
80 "Reuse the thread's active browser tab when available. Defaults to true; set false to create a new tab.",
81 }),
82 ),
83}).annotate({
84 description:
85 "Opens the collaborative browser for the current thread. Use preview_navigate afterward when readiness waiting matters.",
86});
87export type PreviewAutomationOpenInput = typeof PreviewAutomationOpenInput.Type;
88​
89export const BrowserNavigationTarget = Schema.Union([
90 Schema.Struct({
91 kind: Schema.Literal("url").annotate({
92 description: "Selects direct URL navigation.",
93 }),
94 url: BoundedUrl.annotate({
95 description: "Direct website URL.",
96 }),
97 }),
98 Schema.Struct({
99 kind: Schema.Literal("environment-port").annotate({
100 description: "Selects a dev-server port relative to the current execution environment.",
101 }),
102 port: Schema.Int.check(Schema.isGreaterThan(0))
103 .check(Schema.isLessThan(65_536))
104 .annotate({ description: "Dev-server TCP port inside the current environment." }),
105 protocol: Schema.optional(
106 Schema.Literals(["http", "https"]).annotate({
107 description: "Dev-server protocol. Defaults to http.",
108 }),
109 ),
110 path: Schema.optional(
111 Schema.String.annotate({
112 description: "Optional path, query, and fragment, for example /settings?tab=account.",
113 }),
114 ),
115 }),
116]);
117export type BrowserNavigationTarget = typeof BrowserNavigationTarget.Type;
118​
119export const PreviewAutomationNavigateInput = Schema.Struct({
120 url: Schema.optional(BoundedUrl).annotate({
121 description:
122 "Website URL, for example https://t3.chat. Use this for public pages and directly reachable URLs.",
123 }),
124 target: Schema.optional(
125 BrowserNavigationTarget.annotate({
126 description:
127 "Environment-relative target. Prefer {kind:'environment-port',port:5173} for a dev server in the current environment.",
128 }),
129 ).annotate({
130 description:
131 "Environment-relative target. Prefer {kind:'environment-port',port:5173} for a dev server in the current environment.",
132 }),
133 readiness: Schema.optional(
134 Schema.Literals(["load", "domContentLoaded", "none"]).annotate({
135 description:
136 "Readiness milestone before returning. 'load' waits for loading to stop (default), 'domContentLoaded' waits for an interactive document, and 'none' returns immediately.",
137 }),
138 ).annotate({
139 description:
140 "Readiness milestone before returning. 'load' is the default; use 'none' only when a later wait call will verify the page.",
141 }),
142 timeoutMs: OptionalTimeoutMs,
143})
144 .check(
145 Schema.makeFilter(
146 (input) =>
147 Number(input.url !== undefined) + Number(input.target !== undefined) === 1 ||
148 "Provide exactly one of url or target.",
149 ),
150 )
151 .annotate({
152 description:
153 "Navigates the active browser tab. Provide exactly one of url or target; for most public pages use url.",
154 });
155export type PreviewAutomationNavigateInput = typeof PreviewAutomationNavigateInput.Type;
156​
157export const PreviewAutomationResizeInput = Schema.Struct({
158 mode: Schema.Literals(["fill", "freeform", "preset"]).annotate({
159 description:
160 "Viewport mode: fill follows the preview panel, freeform uses exact independently resizable dimensions, and preset uses a named device size.",
161 }),
162 preset: Schema.optional(
163 PreviewViewportPresetId.annotate({
164 description: "Named viewport from Chrome DevTools' standard device catalog.",
165 }),
166 ).annotate({
167 description: "Named device size. Required only when mode is preset.",
168 }),
169 width: Schema.optional(
170 PreviewViewportSize.fields.width.annotate({
171 description: "Freeform viewport width in CSS pixels. Required only in freeform mode.",
172 }),
173 ).annotate({
174 description: "Freeform viewport width in CSS pixels. Required only in freeform mode.",
175 }),
176 height: Schema.optional(
177 PreviewViewportSize.fields.height.annotate({
178 description: "Freeform viewport height in CSS pixels. Required only in freeform mode.",
179 }),
180 ).annotate({
181 description: "Freeform viewport height in CSS pixels. Required only in freeform mode.",
182 }),
183 orientation: Schema.optional(
184 Schema.Literals(["portrait", "landscape"]).annotate({
185 description:
186 "Orientation for a fixed device preset. Defaults to the preset's native orientation.",
187 }),
188 ).annotate({
189 description:
190 "Orientation for a named device preset. It is not accepted in fill or freeform mode.",
191 }),
192 timeoutMs: OptionalTimeoutMs,
193})
194 .check(
195 Schema.makeFilter((input) => {
196 const hasPreset = input.preset !== undefined;
197 const hasWidth = input.width !== undefined;
198 const hasHeight = input.height !== undefined;
199 if (hasWidth !== hasHeight) return "Custom dimensions require both width and height.";
200 if (input.mode === "fill") {
201 return !hasPreset && !hasWidth && input.orientation === undefined
202 ? true
203 : "Fill mode does not accept a preset, dimensions, or orientation.";
204 }
205 if (input.mode === "freeform") {
206 if (!hasWidth || !hasHeight || hasPreset || input.orientation !== undefined) {
207 return "Freeform mode requires width and height and does not accept a preset or orientation.";
208 }
209 } else if (!hasPreset || hasWidth || hasHeight) {
210 return "Preset mode requires a preset and does not accept custom dimensions.";
211 }
212 if (hasWidth && hasHeight && input.width! * input.height! > PREVIEW_VIEWPORT_MAX_AREA) {
213 return `Custom viewport area must not exceed ${PREVIEW_VIEWPORT_MAX_AREA} pixels.`;
214 }
215 return true;
216 }),
217 )
218 .annotate({
219 description:
220 "Sets the active browser tab to fill-panel, independently resizable freeform, or named device-preset sizing.",
221 });
222export type PreviewAutomationResizeInput = typeof PreviewAutomationResizeInput.Type;
223​
224export const PreviewAutomationResizeResult = Schema.Struct({
225 tabId: PreviewTabId,
226 setting: PreviewViewportSetting,
227 viewport: PreviewRenderedViewportSize,
228});
229export type PreviewAutomationResizeResult = typeof PreviewAutomationResizeResult.Type;
230​
231const Locator = TrimmedNonEmptyString.annotate({
232 description:
233 "Playwright selector, preferably role/text based, for example role=button[name='Send'] or text=Continue. Use snapshot first to inspect the page.",
234});
235​
236const LegacySelector = TrimmedNonEmptyString.annotate({
237 description:
238 "Legacy CSS selector such as button[type='submit']. Prefer locator for resilient role/text targeting.",
239});
240​
241export const PreviewAutomationClickInput = Schema.Struct({
242 selector: Schema.optional(LegacySelector).annotate({
243 description:
244 "Legacy CSS selector such as button[type='submit']. Prefer locator for resilient role/text targeting.",
245 }),
246 locator: Schema.optional(Locator).annotate({
247 description:
248 "Playwright selector, preferably role/text based, for example role=button[name='Send'] or text=Continue. Use snapshot first to inspect the page.",
249 }),
250 x: Schema.optional(
251 Schema.Finite.annotate({
252 description: "Viewport-relative X coordinate in CSS pixels. Must be paired with y.",
253 }),
254 ),
255 y: Schema.optional(
256 Schema.Finite.annotate({
257 description: "Viewport-relative Y coordinate in CSS pixels. Must be paired with x.",
258 }),
259 ),
260 timeoutMs: OptionalTimeoutMs,
261})
262 .check(
263 Schema.makeFilter((input) => {
264 const selectorModes =
265 Number(input.selector !== undefined) + Number(input.locator !== undefined);
266 const hasX = input.x !== undefined;
267 const hasY = input.y !== undefined;
268 if (hasX !== hasY) return "Coordinates require both x and y.";
269 const coordinateModes = hasX && hasY ? 1 : 0;
270 return selectorModes + coordinateModes === 1 || "Provide exactly one click target.";
271 }),
272 )
273 .annotate({
274 description:
275 "Clicks one target. Provide exactly one of locator, selector, or the x/y coordinate pair.",
276 });
277export type PreviewAutomationClickInput = typeof PreviewAutomationClickInput.Type;
278​
279export const PreviewAutomationTypeInput = Schema.Struct({
280 text: Schema.String.annotate({ description: "Literal text to insert." }),
281 selector: Schema.optional(LegacySelector).annotate({
282 description: "Legacy CSS selector for the input. Prefer locator.",
283 }),
284 locator: Schema.optional(Locator).annotate({
285 description:
286 "Playwright selector for the input, for example role=textbox[name='Message'] or textarea[placeholder*='Message'].",
287 }),
288 clear: Schema.optional(
289 Schema.Boolean.annotate({
290 description: "Clear the existing input value before inserting text. Defaults to false.",
291 }),
292 ),
293 timeoutMs: OptionalTimeoutMs,
294})
295 .check(
296 Schema.makeFilter(
297 (input) =>
298 !(input.selector !== undefined && input.locator !== undefined) ||
299 "Provide at most one of selector or locator.",
300 ),
301 )
302 .annotate({
303 description:
304 "Types into locator/selector, or into the currently focused element when neither target is provided.",
305 });
306export type PreviewAutomationTypeInput = typeof PreviewAutomationTypeInput.Type;
307​
308export const PreviewAutomationPressInput = Schema.Struct({
309 key: Schema.String.check(Schema.isTrimmed())
310 .check(
311 Schema.isNonEmpty({
312 description:
313 "Keyboard key name such as Enter, Escape, Tab, ArrowDown, Backspace, or a single character.",
314 }),
315 )
316 .annotateKey({
317 description:
318 "Keyboard key name such as Enter, Escape, Tab, ArrowDown, Backspace, or a single character.",
319 }),
320 modifiers: Schema.optional(
321 Schema.Array(Schema.Literals(["Alt", "Control", "Meta", "Shift"])).annotate({
322 description: "Modifier keys held while pressing key.",
323 }),
324 ),
325}).annotate({ description: "Presses one keyboard key in the active browser tab." });
326export type PreviewAutomationPressInput = typeof PreviewAutomationPressInput.Type;
327​
328export const PreviewAutomationScrollInput = Schema.Struct({
329 deltaX: Schema.optional(
330 Schema.Finite.annotate({
331 description: "Horizontal scroll delta in CSS pixels. Positive scrolls right. Defaults to 0.",
332 }),
333 ),
334 deltaY: Schema.optional(
335 Schema.Finite.annotate({
336 description: "Vertical scroll delta in CSS pixels. Positive scrolls down. Defaults to 0.",
337 }),
338 ),
339 selector: Schema.optional(LegacySelector).annotate({
340 description: "Legacy CSS selector for a scrollable container. Omit to scroll the viewport.",
341 }),
342 locator: Schema.optional(Locator).annotate({
343 description: "Playwright selector for a scrollable container. Omit to scroll the viewport.",
344 }),
345})
346 .check(
347 Schema.makeFilter((input) => {
348 if (input.selector !== undefined && input.locator !== undefined) {
349 return "Provide at most one of selector or locator.";
350 }
351 return (
352 input.deltaX !== undefined || input.deltaY !== undefined || "Provide deltaX or deltaY."
353 );
354 }),
355 )
356 .annotate({
357 description:
358 "Scrolls the viewport, or a locator/selector container. Provide deltaX, deltaY, or both.",
359 });
360export type PreviewAutomationScrollInput = typeof PreviewAutomationScrollInput.Type;
361​
362export const PreviewAutomationEvaluateInput = Schema.Struct({
363 expression: Schema.String.check(Schema.isTrimmed())
364 .check(
365 Schema.isNonEmpty({
366 description:
367 "JavaScript expression evaluated in the page's main frame, for example document.title or (() => ({href: location.href}))().",
368 }),
369 )
370 .check(Schema.isMaxLength(64_000))
371 .annotateKey({
372 description:
373 "JavaScript expression evaluated in the page's main frame, for example document.title or (() => ({href: location.href}))().",
374 }),
375 awaitPromise: Schema.optional(
376 Schema.Boolean.annotate({ description: "Await a returned Promise. Defaults to true." }),
377 ),
378 returnByValue: Schema.optional(
379 Schema.Boolean.annotate({
380 description:
381 "Serialize and return the value instead of a remote object reference. Defaults to true.",
382 }),
383 ),
384}).annotate({
385 description:
386 "Evaluates JavaScript in the page. Prefer snapshot and semantic actions; use evaluate for inspection or unsupported interactions.",
387});
388export type PreviewAutomationEvaluateInput = typeof PreviewAutomationEvaluateInput.Type;
389​
390export const PreviewAutomationWaitForInput = Schema.Struct({
391 selector: Schema.optional(LegacySelector).annotate({
392 description: "Legacy CSS selector that must match an element. Prefer locator.",
393 }),
394 locator: Schema.optional(Locator).annotate({
395 description:
396 "Playwright selector that must match an element, for example role=button[name='Send'].",
397 }),
398 text: Schema.optional(
399 TrimmedNonEmptyString.annotate({
400 description: "Case-sensitive substring that must appear in visible document text.",
401 }),
402 ).annotate({
403 description: "Case-sensitive substring that must appear in visible document text.",
404 }),
405 urlIncludes: Schema.optional(
406 TrimmedNonEmptyString.annotate({
407 description: "Substring that must appear in the current absolute URL.",
408 }),
409 ).annotate({ description: "Substring that must appear in the current absolute URL." }),
410 timeoutMs: OptionalTimeoutMs,
411})
412 .check(
413 Schema.makeFilter((input) => {
414 if (input.selector !== undefined && input.locator !== undefined) {
415 return "Provide at most one of selector or locator.";
416 }
417 return (
418 input.selector !== undefined ||
419 input.locator !== undefined ||
420 input.text !== undefined ||
421 input.urlIncludes !== undefined ||
422 "Provide at least one wait condition."
423 );
424 }),
425 )
426 .annotate({
427 description:
428 "Waits until all provided conditions match. Use after click/type when the page changes asynchronously.",
429 });
430export type PreviewAutomationWaitForInput = typeof PreviewAutomationWaitForInput.Type;
431​
432export const PreviewAutomationElement = Schema.Struct({
433 tag: Schema.String,
434 role: Schema.NullOr(Schema.String),
435 name: Schema.String,
436 selector: Schema.String,
437 x: Schema.Number,
438 y: Schema.Number,
439 width: Schema.Number,
440 height: Schema.Number,
441});
442export type PreviewAutomationElement = typeof PreviewAutomationElement.Type;
443​
444export const PreviewAutomationConsoleEntry = Schema.Struct({
445 level: Schema.String,
446 text: Schema.String,
447 timestamp: Schema.String,
448 source: Schema.optional(Schema.String),
449});
450export type PreviewAutomationConsoleEntry = typeof PreviewAutomationConsoleEntry.Type;
451​
452export const PreviewAutomationNetworkEntry = Schema.Struct({
453 url: Schema.String,
454 method: Schema.String,
455 status: Schema.NullOr(Schema.Number),
456 failed: Schema.Boolean,
457 errorText: Schema.optional(Schema.String),
458 timestamp: Schema.String,
459});
460export type PreviewAutomationNetworkEntry = typeof PreviewAutomationNetworkEntry.Type;
461​
462export const PreviewAutomationActionEvent = Schema.Struct({
463 id: Schema.String,
464 action: Schema.String,
465 status: Schema.Literals(["running", "succeeded", "failed", "interrupted"]),
466 startedAt: Schema.String,
467 completedAt: Schema.optional(Schema.String),
468 error: Schema.optional(Schema.String),
469});
470export type PreviewAutomationActionEvent = typeof PreviewAutomationActionEvent.Type;
471​
472export const PreviewAutomationSnapshot = Schema.Struct({
473 url: Schema.String,
474 title: Schema.String,
475 loading: Schema.Boolean,
476 visibleText: Schema.String,
477 interactiveElements: Schema.Array(PreviewAutomationElement),
478 accessibilityTree: Schema.Unknown,
479 consoleEntries: Schema.Array(PreviewAutomationConsoleEntry),
480 networkEntries: Schema.Array(PreviewAutomationNetworkEntry),
481 actionTimeline: Schema.Array(PreviewAutomationActionEvent),
482 screenshot: Schema.Struct({
483 mimeType: Schema.Literal("image/png"),
484 data: Schema.String,
485 width: Schema.Int,
486 height: Schema.Int,
487 }),
488});
489export type PreviewAutomationSnapshot = typeof PreviewAutomationSnapshot.Type;
490​
491export const PreviewAutomationRecordingStatus = Schema.Struct({
492 tabId: PreviewTabId,
493 recording: Schema.Boolean,
494 startedAt: Schema.NullOr(Schema.String),
495});
496export type PreviewAutomationRecordingStatus = typeof PreviewAutomationRecordingStatus.Type;
497​
498export const PreviewAutomationRecordingArtifact = Schema.Struct({
499 id: Schema.String,
500 tabId: PreviewTabId,
501 path: Schema.String,
502 mimeType: Schema.String,
503 sizeBytes: Schema.Int,
504 createdAt: Schema.String,
505});
506export type PreviewAutomationRecordingArtifact = typeof PreviewAutomationRecordingArtifact.Type;
507​
508export const PreviewAutomationClientId = TrimmedNonEmptyString.check(Schema.isMaxLength(128));
509export type PreviewAutomationClientId = typeof PreviewAutomationClientId.Type;
510export const PreviewAutomationConnectionId = TrimmedNonEmptyString.check(Schema.isMaxLength(64));
511export type PreviewAutomationConnectionId = typeof PreviewAutomationConnectionId.Type;
512​
513export const PreviewAutomationHostIdentity = Schema.Struct({
514 clientId: PreviewAutomationClientId,
515 environmentId: EnvironmentId,
516});
517export type PreviewAutomationHostIdentity = typeof PreviewAutomationHostIdentity.Type;
518​
519export const PreviewAutomationHost = Schema.Struct({
520 ...PreviewAutomationHostIdentity.fields,
521 /**
522 * Missing means the pre-capability-negotiation V1 operation set. This lets
523 * a newer server safely coexist with an older desktop during rollout.
524 */
525 supportedOperations: Schema.optional(Schema.Array(PreviewAutomationOperation)),
526});
527export type PreviewAutomationHost = typeof PreviewAutomationHost.Type;
528​
529export const PreviewAutomationHostFocus = Schema.Struct({
530 ...PreviewAutomationHostIdentity.fields,
531 connectionId: PreviewAutomationConnectionId,
532 focused: Schema.Boolean,
533});
534export type PreviewAutomationHostFocus = typeof PreviewAutomationHostFocus.Type;
535​
536export const PreviewAutomationRequest = Schema.Struct({
537 requestId: TrimmedNonEmptyString,
538 threadId: ThreadId,
539 tabId: Schema.optional(PreviewTabId),
540 operation: PreviewAutomationOperation,
541 input: Schema.Unknown,
542 timeoutMs: Schema.Int.check(Schema.isGreaterThan(0)),
543});
544export type PreviewAutomationRequest = typeof PreviewAutomationRequest.Type;
545​
546export const PreviewAutomationStreamEvent = Schema.Union([
547 Schema.Struct({
548 type: Schema.Literal("connected"),
549 connectionId: PreviewAutomationConnectionId,
550 }),
551 Schema.Struct({
552 type: Schema.Literal("request"),
553 connectionId: PreviewAutomationConnectionId,
554 request: PreviewAutomationRequest,
555 }),
556]);
557export type PreviewAutomationStreamEvent = typeof PreviewAutomationStreamEvent.Type;
558​
559export const PreviewAutomationResponse = Schema.Struct({
560 clientId: PreviewAutomationClientId,
561 connectionId: PreviewAutomationConnectionId,
562 requestId: TrimmedNonEmptyString,
563 ok: Schema.Boolean,
564 result: Schema.optional(Schema.Unknown),
565 error: Schema.optional(
566 Schema.Struct({
567 _tag: TrimmedNonEmptyString,
568 message: Schema.String,
569 detail: Schema.optional(Schema.Unknown),
570 }),
571 ),
572});
573export type PreviewAutomationResponse = typeof PreviewAutomationResponse.Type;
574​
575export class PreviewAutomationUnavailableError extends Schema.TaggedErrorClass<PreviewAutomationUnavailableError>()(
576 "PreviewAutomationUnavailableError",
577 {
578 capability: Schema.Literal("preview"),
579 environmentId: EnvironmentId,
580 threadId: ThreadId,
581 providerSessionId: TrimmedNonEmptyString,
582 providerInstanceId: ProviderInstanceId,
583 },
584) {
585 override get message(): string {
586 return `MCP credential does not grant the ${this.capability} capability.`;
587 }
589​
590const PreviewAutomationScopeErrorFields = {
591 operation: PreviewAutomationOperation,
592 environmentId: EnvironmentId,
593 threadId: ThreadId,
594 providerSessionId: TrimmedNonEmptyString,
595 providerInstanceId: ProviderInstanceId,
596};
597​
598const PreviewAutomationRequestErrorFields = {
599 ...PreviewAutomationScopeErrorFields,
600 clientId: TrimmedNonEmptyString,
601 connectionId: PreviewAutomationConnectionId,
602 requestId: TrimmedNonEmptyString,
603 tabId: Schema.optional(PreviewTabId),
604 timeoutMs: Schema.Int.check(Schema.isGreaterThan(0)),
605};
606​
607const PreviewAutomationRemoteDiagnosticFields = {
608 remoteTag: TrimmedNonEmptyString,
609 remoteMessageLength: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
610 remoteDetailKind: Schema.optional(
611 Schema.Literals(["null", "array", "object", "string", "number", "boolean"]),
612 ),
613 cause: Schema.Defect(),
614};
615​
616const PreviewAutomationOptionalRemoteDiagnosticFields = {
617 remoteTag: Schema.optional(TrimmedNonEmptyString),
618 remoteMessageLength: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
619 remoteDetailKind: Schema.optional(
620 Schema.Literals(["null", "array", "object", "string", "number", "boolean"]),
621 ),
622 cause: Schema.optional(Schema.Defect()),
623};
624​
625export class PreviewAutomationNoAvailableHostError extends Schema.TaggedErrorClass<PreviewAutomationNoAvailableHostError>()(
626 "PreviewAutomationNoAvailableHostError",
627 {
628 ...PreviewAutomationScopeErrorFields,
629 clientId: Schema.optional(TrimmedNonEmptyString),
630 connectionId: Schema.optional(PreviewAutomationConnectionId),
631 requestId: Schema.optional(TrimmedNonEmptyString),
632 tabId: Schema.optional(PreviewTabId),
633 timeoutMs: Schema.optional(Schema.Int.check(Schema.isGreaterThan(0))),
634 ...PreviewAutomationOptionalRemoteDiagnosticFields,
635 },
636) {
637 override get message(): string {
638 const summary = `No preview automation host is available for ${this.operation} in environment ${this.environmentId}.`;
639 return summary;
640 }
642​
643export class PreviewAutomationUnsupportedClientError extends Schema.TaggedErrorClass<PreviewAutomationUnsupportedClientError>()(
644 "PreviewAutomationUnsupportedClientError",
645 {
646 ...PreviewAutomationRequestErrorFields,
647 ...PreviewAutomationRemoteDiagnosticFields,
648 },
649) {
650 override get message(): string {
651 return `Preview automation client ${this.clientId} does not support ${this.operation}.`;
652 }
654​
655export class PreviewAutomationTabNotFoundError extends Schema.TaggedErrorClass<PreviewAutomationTabNotFoundError>()(
656 "PreviewAutomationTabNotFoundError",
657 {
658 ...PreviewAutomationRequestErrorFields,
659 ...PreviewAutomationRemoteDiagnosticFields,
660 },
661) {
662 override get message(): string {
663 const summary = this.tabId
664 ? `Preview tab ${this.tabId} was not found for ${this.operation}.`
665 : `No active preview tab was found for ${this.operation}.`;
666 return summary;
667 }
669​
670export class PreviewAutomationTimeoutError extends Schema.TaggedErrorClass<PreviewAutomationTimeoutError>()(
671 "PreviewAutomationTimeoutError",
672 {
673 ...PreviewAutomationRequestErrorFields,
674 ...PreviewAutomationOptionalRemoteDiagnosticFields,
675 },
676) {
677 override get message(): string {
678 const summary = `Preview automation ${this.operation} timed out after ${this.timeoutMs}ms.`;
679 return summary;
680 }
682​
683export class PreviewAutomationControlInterruptedError extends Schema.TaggedErrorClass<PreviewAutomationControlInterruptedError>()(
684 "PreviewAutomationControlInterruptedError",
685 {
686 ...PreviewAutomationRequestErrorFields,
687 ...PreviewAutomationRemoteDiagnosticFields,
688 },
689) {
690 override get message(): string {
691 return `Preview automation ${this.operation} was interrupted on client ${this.clientId}.`;
692 }
694​
695export class PreviewAutomationExecutionError extends Schema.TaggedErrorClass<PreviewAutomationExecutionError>()(
696 "PreviewAutomationExecutionError",
697 {
698 ...PreviewAutomationRequestErrorFields,
699 ...PreviewAutomationRemoteDiagnosticFields,
700 },
701) {
702 override get message(): string {
703 return `Preview automation ${this.operation} failed on client ${this.clientId}.`;
704 }
706​
707export class PreviewAutomationInvalidSelectorError extends Schema.TaggedErrorClass<PreviewAutomationInvalidSelectorError>()(
708 "PreviewAutomationInvalidSelectorError",
709 {
710 ...PreviewAutomationRequestErrorFields,
711 ...PreviewAutomationRemoteDiagnosticFields,
712 selectorKind: Schema.optional(Schema.Literals(["locator", "selector"])),
713 selectorLength: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
714 },
715) {
716 override get message(): string {
717 if (this.selectorKind !== undefined && this.selectorLength !== undefined) {
718 return `Preview automation ${this.operation} received an invalid ${this.selectorKind} (${this.selectorLength} characters).`;
719 }
720 return `Preview automation ${this.operation} received an invalid selector.`;
721 }
723​
724export class PreviewAutomationTargetNotEditableError extends Schema.TaggedErrorClass<PreviewAutomationTargetNotEditableError>()(
725 "PreviewAutomationTargetNotEditableError",
726 {
727 ...PreviewAutomationRequestErrorFields,
728 ...PreviewAutomationRemoteDiagnosticFields,
729 selectorKind: Schema.optional(Schema.Literals(["focused-element", "locator", "selector"])),
730 selectorLength: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
731 },
732) {
733 override get message(): string {
734 if (this.selectorKind === "focused-element") {
735 return `Preview automation ${this.operation} requires an editable focused element.`;
736 }
737 if (this.selectorKind !== undefined && this.selectorLength !== undefined) {
738 return `Preview automation ${this.operation} requires an editable ${this.selectorKind} (${this.selectorLength} characters).`;
739 }
740 return `Preview automation ${this.operation} requires an editable target.`;
741 }
743​
744export class PreviewAutomationResultTooLargeError extends Schema.TaggedErrorClass<PreviewAutomationResultTooLargeError>()(
745 "PreviewAutomationResultTooLargeError",
746 {
747 ...PreviewAutomationRequestErrorFields,
748 ...PreviewAutomationRemoteDiagnosticFields,
749 maximumBytes: Schema.optional(Schema.Int.check(Schema.isGreaterThan(0))),
750 },
751) {
752 override get message(): string {
753 const summary =
754 this.maximumBytes === undefined
755 ? `Preview automation ${this.operation} produced a result that is too large.`
756 : `Preview automation ${this.operation} produced a result larger than ${this.maximumBytes} bytes.`;
757 return summary;
758 }
760​
761export class PreviewAutomationClientDisconnectedError extends Schema.TaggedErrorClass<PreviewAutomationClientDisconnectedError>()(
762 "PreviewAutomationClientDisconnectedError",
763 PreviewAutomationRequestErrorFields,
764) {
765 override get message(): string {
766 return `Preview automation client ${this.clientId} disconnected during ${this.operation}.`;
767 }
769​
770export class PreviewAutomationRequestQueueClosedError extends Schema.TaggedErrorClass<PreviewAutomationRequestQueueClosedError>()(
771 "PreviewAutomationRequestQueueClosedError",
772 PreviewAutomationRequestErrorFields,
773) {
774 override get message(): string {
775 return `Preview automation client ${this.clientId} stopped accepting ${this.operation} requests.`;
776 }
778​
779export class PreviewAutomationRemoteUnavailableError extends Schema.TaggedErrorClass<PreviewAutomationRemoteUnavailableError>()(
780 "PreviewAutomationRemoteUnavailableError",
781 {
782 ...PreviewAutomationRequestErrorFields,
783 ...PreviewAutomationRemoteDiagnosticFields,
784 },
785) {
786 override get message(): string {
787 return `Preview automation ${this.operation} is unavailable on client ${this.clientId}.`;
788 }
790​
791export class PreviewAutomationMalformedResponseError extends Schema.TaggedErrorClass<PreviewAutomationMalformedResponseError>()(
792 "PreviewAutomationMalformedResponseError",
793 PreviewAutomationRequestErrorFields,
794) {
795 override get message(): string {
796 return `Preview automation client ${this.clientId} returned a malformed response for ${this.operation}.`;
797 }
799​
800export const PreviewAutomationError = Schema.Union([
801 PreviewAutomationUnavailableError,
802 PreviewAutomationNoAvailableHostError,
803 PreviewAutomationUnsupportedClientError,
804 PreviewAutomationTabNotFoundError,
805 PreviewAutomationTimeoutError,
806 PreviewAutomationControlInterruptedError,
807 PreviewAutomationExecutionError,
808 PreviewAutomationInvalidSelectorError,
809 PreviewAutomationTargetNotEditableError,
810 PreviewAutomationResultTooLargeError,
811 PreviewAutomationClientDisconnectedError,
812 PreviewAutomationRequestQueueClosedError,
813 PreviewAutomationRemoteUnavailableError,
814 PreviewAutomationMalformedResponseError,
815]);
816export type PreviewAutomationError = typeof PreviewAutomationError.Type;
817​
818export const PreviewUrlResolution = Schema.Struct({
819 requestedUrl: Schema.String,
820 resolvedUrl: Schema.String,
821 resolutionKind: Schema.Literals(["direct", "direct-private-network"]),
822 environmentId: EnvironmentId,
823});
824export type PreviewUrlResolution = typeof PreviewUrlResolution.Type;