Open History to see the last commit
1/**
2 * Preview - Schemas for the in-app browser preview surface.
3 *
4 * The preview is desktop-only (Chromium <webview>); the server tracks per-thread
5 * tab metadata so it survives client reconnects and multi-window. The desktop
6 * renderer mediates: it owns the actual <webview> and reports navigation back to
7 * the server via these RPCs, the server fans events to all subscribers.
8 *
9 * @module Preview
10 */
11import { Schema } from "effect";
12import { NonNegativeInt, PositiveInt, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts";
13import { BrowserProfileId } from "./browserProfile.ts";
14
15export const PREVIEW_URL_MAX_LENGTH = 2_048;
16export const CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS = 32;
17
18const Url = TrimmedNonEmptyString.check(Schema.isMaxLength(PREVIEW_URL_MAX_LENGTH));
19
20export const ConfiguredLocalServerUrls = Schema.Array(Url).check(
21 Schema.isMaxLength(CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS),
22);
23const Title = Schema.String.check(Schema.isMaxLength(512));
24
25export const PreviewTabId = TrimmedNonEmptyString.check(Schema.isMaxLength(128));
26export type PreviewTabId = typeof PreviewTabId.Type;
27
28export const PREVIEW_VIEWPORT_MIN_DIMENSION = 240;
29export const PREVIEW_VIEWPORT_MAX_DIMENSION = 3840;
30export const PREVIEW_VIEWPORT_MAX_AREA = 3840 * 2160;
31
32const PreviewViewportDimension = Schema.Int.check(
33 Schema.isBetween({
34 minimum: PREVIEW_VIEWPORT_MIN_DIMENSION,
35 maximum: PREVIEW_VIEWPORT_MAX_DIMENSION,
36 }),
37);
38
39const viewportAreaFilter = Schema.makeFilter(
40 ({ width, height }: { readonly width: number; readonly height: number }) =>
41 width * height <= PREVIEW_VIEWPORT_MAX_AREA ||
42 `Viewport area must not exceed ${PREVIEW_VIEWPORT_MAX_AREA} pixels.`,
43);
44
45export const PreviewViewportSize = Schema.Struct({
46 width: PreviewViewportDimension,
47 height: PreviewViewportDimension,
48}).check(viewportAreaFilter);
49export type PreviewViewportSize = typeof PreviewViewportSize.Type;
50
51/**
52 * The page's measured viewport can be smaller than the minimum selectable
53 * fixed size while fill mode follows a narrow panel. Keep measurement
54 * validation separate from the stricter user-selectable size constraints.
55 */
56export const PreviewRenderedViewportSize = Schema.Struct({
57 width: Schema.Int.check(Schema.isGreaterThan(0)),
58 height: Schema.Int.check(Schema.isGreaterThan(0)),
59});
60export type PreviewRenderedViewportSize = typeof PreviewRenderedViewportSize.Type;
61
62export const PREVIEW_VIEWPORT_PRESET_IDS = [
63 "iphone-se",
64 "iphone-xr",
65 "iphone-12-pro",
66 "iphone-14-pro-max",
67 "pixel-7",
68 "samsung-galaxy-s8-plus",
69 "samsung-galaxy-s20-ultra",
70 "ipad-mini",
71 "ipad-air",
72 "ipad-pro",
73 "surface-pro-7",
74 "surface-duo",
75 "galaxy-z-fold-5",
76 "asus-zenbook-fold",
77 "samsung-galaxy-a51-71",
78 "nest-hub",
79 "nest-hub-max",
80] as const;
81
82export const PreviewViewportPresetId = Schema.Literals(PREVIEW_VIEWPORT_PRESET_IDS);
83export type PreviewViewportPresetId = typeof PreviewViewportPresetId.Type;
84
85/**
86 * Preset IDs shipped before the Chrome-compatible catalog. Existing sessions
87 * can still reconnect with these values, but new resize requests only expose
88 * PREVIEW_VIEWPORT_PRESET_IDS.
89 */
90const LEGACY_PREVIEW_VIEWPORT_PRESET_IDS = [
91 "desktop-1920x1080",
92 "desktop-1440x900",
93 "laptop-1366x768",
94 "laptop-1280x800",
95 "ipad-pro-11",
96 "iphone-15-pro",
97 "pixel-8",
98 "galaxy-s24",
99] as const;
100
101const StoredPreviewViewportPresetId = Schema.Literals([
102 ...PREVIEW_VIEWPORT_PRESET_IDS,
103 ...LEGACY_PREVIEW_VIEWPORT_PRESET_IDS,
104]);
105
106export const PreviewViewportSetting = Schema.Union([
107 Schema.TaggedStruct("fill", {}),
108 Schema.TaggedStruct("freeform", {
109 ...PreviewViewportSize.fields,
110 }).check(viewportAreaFilter),
111 Schema.TaggedStruct("preset", {
112 ...PreviewViewportSize.fields,
113 presetId: StoredPreviewViewportPresetId,
114 }).check(viewportAreaFilter),
115]);
116export type PreviewViewportSetting = typeof PreviewViewportSetting.Type;
117
118export const FILL_PREVIEW_VIEWPORT = {
119 _tag: "fill",
120} as const satisfies PreviewViewportSetting;
121
122/**
123 * Discrete zoom levels mirroring Chrome's preset ladder. Zoom is applied by the
124 * desktop main process to the Chromium guest, but the ladder lives here so the
125 * settings UI can offer exactly the steps the zoom controls step through.
126 */
127export const PREVIEW_ZOOM_LEVELS = [
128 0.25, 0.33, 0.5, 0.67, 0.75, 0.8, 0.9, 1.0, 1.1, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0, 4.0, 5.0,
129] as const;
130
131export const PreviewZoomFactor = Schema.Literals(PREVIEW_ZOOM_LEVELS);
132export type PreviewZoomFactor = typeof PreviewZoomFactor.Type;
133
134export const DEFAULT_PREVIEW_ZOOM_FACTOR: PreviewZoomFactor = 1.0;
135
136/**
137 * Preferred `prefers-color-scheme` for preview guests. `system` clears the
138 * emulation override so the guest follows the OS. Structurally identical to
139 * `DesktopPreviewColorScheme`, which is the IPC-layer spelling of the same set.
140 */
141export const PreviewAppearancePreference = Schema.Literals(["system", "light", "dark"]);
142export type PreviewAppearancePreference = typeof PreviewAppearancePreference.Type;
143
144export const DEFAULT_PREVIEW_APPEARANCE: PreviewAppearancePreference = "system";
145
146export const PreviewNavStatus = Schema.Union([
147 Schema.TaggedStruct("Idle", {}),
148 Schema.TaggedStruct("Loading", {
149 url: Url,
150 title: Title,
151 }),
152 Schema.TaggedStruct("Success", {
153 url: Url,
154 title: Title,
155 }),
156 Schema.TaggedStruct("LoadFailed", {
157 url: Url,
158 title: Title,
159 code: Schema.Int,
160 description: Schema.String,
161 }),
162]);
163export type PreviewNavStatus = typeof PreviewNavStatus.Type;
164
165/**
166 * Where a tab's page runs. `desktop` is an Electron <webview> owned by one
167 * desktop client; `server` is headless Chromium owned by the environment
168 * server, viewed by any client through `/api/preview-stream` and driven by
169 * agents with no client attached. Absent means `desktop`.
170 */
171export const PreviewRuntime = Schema.Literals(["desktop", "server"]);
172export type PreviewRuntime = typeof PreviewRuntime.Type;
173
174/**
175 * Host setup the server's browser is missing, sent as JSON in the reason when
176 * the preview stream closes with code 4503. Fixing it needs the host's
177 * operator, so viewers stop retrying and show `command`, the one line that
178 * fixes it. Close reasons are capped at 123 bytes, which this fits.
179 */
180export const PreviewStreamHostSetup = Schema.Struct({
181 need: Schema.Literals(["sandbox", "libraries"]),
182 /** For example `sudo npx t3 browser setup`, matching how the server was launched. */
183 command: Schema.String,
184});
185export type PreviewStreamHostSetup = typeof PreviewStreamHostSetup.Type;
186export const PREVIEW_STREAM_HOST_SETUP_CLOSE_CODE = 4503;
187
188export const PreviewSessionSnapshot = Schema.Struct({
189 threadId: TrimmedNonEmptyString,
190 tabId: PreviewTabId,
191 navStatus: PreviewNavStatus,
192 canGoBack: Schema.Boolean,
193 canGoForward: Schema.Boolean,
194 /** Missing snapshots from older servers are treated as fill-panel mode. */
195 viewport: Schema.optional(PreviewViewportSetting),
196 /** Server tabs only; the desktop keeps its own tabs' appearance. Absent means `system`. */
197 colorScheme: Schema.optional(PreviewAppearancePreference),
198 /** Server tabs only. Absent means 1. */
199 zoomFactor: Schema.optional(PreviewZoomFactor),
200 /**
201 * Browser profile the tab's Chromium partition is derived from. Fixed at
202 * open: Electron only honours a `<webview>`'s partition before attach, so
203 * switching would require tearing the guest down and losing page state.
204 */
205 profileId: Schema.optional(BrowserProfileId),
206 runtime: Schema.optional(PreviewRuntime),
207 /** Authenticated provider session owning an isolated server tab. */
208 automationOwner: Schema.optional(Schema.String),
209 /** An agent opened this tab and asked to show it, so viewers float it. */
210 reveal: Schema.optional(Schema.Boolean),
211 /** A fresh presentation request, including whether it overrides automatic-floating settings. */
212 revealRequest: Schema.optional(Schema.Struct({ id: Schema.String, force: Schema.Boolean })),
213 updatedAt: Schema.String,
214});
215export type PreviewSessionSnapshot = typeof PreviewSessionSnapshot.Type;
216
217export const PreviewOpenInput = Schema.Struct({
218 threadId: ThreadId,
219 /** Omit to create an empty (Idle) tab the user can type into. */
220 url: Schema.optional(Url),
221 /**
222 * Initial viewport for the new tab. Omitting it keeps the historical
223 * fill-panel behaviour; clients that have a configured default send it here
224 * so the session is born at the right size instead of being resized a frame
225 * later (which the user would see as a visible reflow).
226 */
227 viewport: Schema.optional(PreviewViewportSetting),
228 /** Omit to open under the client's configured default profile. */
229 profileId: Schema.optional(BrowserProfileId),
230 /** Omit for a desktop tab. `server` requires the `serverBrowser` capability. */
231 runtime: Schema.optional(PreviewRuntime),
232 /** Set by agent opens that should float for viewers; see the snapshot field. */
233 reveal: Schema.optional(Schema.Boolean),
234});
235export type PreviewOpenInput = typeof PreviewOpenInput.Type;
236
237export const PreviewNavigateInput = Schema.Struct({
238 threadId: ThreadId,
239 tabId: PreviewTabId,
240 url: Url,
241 resolvedTitle: Schema.optional(Title),
242});
243export type PreviewNavigateInput = typeof PreviewNavigateInput.Type;
244
245export const PreviewReportStatusInput = Schema.Struct({
246 threadId: ThreadId,
247 tabId: PreviewTabId,
248 navStatus: PreviewNavStatus,
249 canGoBack: Schema.Boolean,
250 canGoForward: Schema.Boolean,
251});
252export type PreviewReportStatusInput = typeof PreviewReportStatusInput.Type;
253
254export const PreviewRefreshInput = Schema.Struct({
255 threadId: ThreadId,
256 tabId: PreviewTabId,
257});
258export type PreviewRefreshInput = typeof PreviewRefreshInput.Type;
259
260export const PreviewResizeInput = Schema.Struct({
261 threadId: ThreadId,
262 tabId: PreviewTabId,
263 viewport: PreviewViewportSetting,
264});
265export type PreviewResizeInput = typeof PreviewResizeInput.Type;
266
267/**
268 * Changes how a server tab renders, or clears its profile's site data, for any
269 * client. Unlike page input, these need no control of the tab.
270 */
271export const PreviewAdjustInput = Schema.Struct({
272 threadId: ThreadId,
273 tabId: PreviewTabId,
274 colorScheme: Schema.optional(PreviewAppearancePreference),
275 zoomFactor: Schema.optional(PreviewZoomFactor),
276 /** Reloads the page past its cache, as Chrome's Shift+Reload does. */
277 hardReload: Schema.optional(Schema.Boolean),
278 /** Clears the tab's profile's cookies or HTTP cache; its other storage stays. */
279 clear: Schema.optional(Schema.Literals(["cookies", "cache"])),
280});
281export type PreviewAdjustInput = typeof PreviewAdjustInput.Type;
282
283export const PreviewCloseInput = Schema.Struct({
284 threadId: ThreadId,
285 tabId: Schema.optional(PreviewTabId),
286});
287export type PreviewCloseInput = typeof PreviewCloseInput.Type;
288
289export const PreviewClearProfileInput = Schema.Struct({
290 profileId: BrowserProfileId,
291});
292export type PreviewClearProfileInput = typeof PreviewClearProfileInput.Type;
293
294export const PreviewListInput = Schema.Struct({
295 threadId: ThreadId,
296});
297export type PreviewListInput = typeof PreviewListInput.Type;
298
299export const PreviewListResult = Schema.Struct({
300 sessions: Schema.Array(PreviewSessionSnapshot),
301 /** Identifies the current server process so revision resets are safe. */
302 serverEpoch: TrimmedNonEmptyString,
303 /** Monotonic server state revision used to reject stale list responses. */
304 revision: NonNegativeInt,
305});
306export type PreviewListResult = typeof PreviewListResult.Type;
307
308const PreviewEventBaseSchema = Schema.Struct({
309 threadId: TrimmedNonEmptyString,
310 tabId: PreviewTabId,
311 createdAt: Schema.String,
312 /** Identifies the server process that emitted this event. */
313 serverEpoch: TrimmedNonEmptyString,
314 /** Monotonic server state revision shared with PreviewListResult. */
315 revision: PositiveInt,
316});
317
318const PreviewOpenedEvent = Schema.Struct({
319 ...PreviewEventBaseSchema.fields,
320 type: Schema.Literal("opened"),
321 snapshot: PreviewSessionSnapshot,
322});
323
324const PreviewNavigatedEvent = Schema.Struct({
325 ...PreviewEventBaseSchema.fields,
326 type: Schema.Literal("navigated"),
327 snapshot: PreviewSessionSnapshot,
328});
329
330const PreviewResizedEvent = Schema.Struct({
331 ...PreviewEventBaseSchema.fields,
332 type: Schema.Literal("resized"),
333 snapshot: PreviewSessionSnapshot,
334 /** A one-off action for the server's browser, such as a hard reload. */
335 request: Schema.optional(
336 Schema.Struct({
337 hardReload: Schema.optional(Schema.Boolean),
338 clear: Schema.optional(Schema.Literals(["cookies", "cache"])),
339 }),
340 ),
341});
342
343const PreviewFailedEvent = Schema.Struct({
344 ...PreviewEventBaseSchema.fields,
345 type: Schema.Literal("failed"),
346 url: Url,
347 title: Title,
348 code: Schema.Int,
349 description: Schema.String,
350});
351
352const PreviewClosedEvent = Schema.Struct({
353 ...PreviewEventBaseSchema.fields,
354 type: Schema.Literal("closed"),
355});
356
357export const PreviewEvent = Schema.Union([
358 PreviewOpenedEvent,
359 PreviewNavigatedEvent,
360 PreviewResizedEvent,
361 PreviewFailedEvent,
362 PreviewClosedEvent,
363]);
364export type PreviewEvent = typeof PreviewEvent.Type;
365
366/**
367 * A localhost server detected by the port scanner. Used to populate the
368 * "Local" recommendations in the empty-state of the preview panel.
369 */
370export const DiscoveredLocalServer = Schema.Struct({
371 host: TrimmedNonEmptyString,
372 port: Schema.Int.check(Schema.isGreaterThan(0)).check(Schema.isLessThan(65536)),
373 url: Url,
374 processName: Schema.NullOr(TrimmedNonEmptyString),
375 pid: Schema.NullOr(Schema.Int.check(Schema.isGreaterThan(0))),
376 terminal: Schema.NullOr(
377 Schema.Struct({
378 threadId: ThreadId,
379 terminalId: TrimmedNonEmptyString,
380 }),
381 ),
382});
383export type DiscoveredLocalServer = typeof DiscoveredLocalServer.Type;
384
385export const DiscoveredLocalServerList = Schema.Struct({
386 servers: Schema.Array(DiscoveredLocalServer),
387 scannedAt: Schema.String,
388 configuredUrlProbing: Schema.optional(Schema.Literal(true)),
389});
390export type DiscoveredLocalServerList = typeof DiscoveredLocalServerList.Type;
391
392export class PreviewSessionLookupError extends Schema.TaggedError<PreviewSessionLookupError>()(
393 "PreviewSessionLookupError",
394 {
395 threadId: Schema.String,
396 tabId: Schema.String,
397 },
398) {
399 override get message() {
400 return `Unknown preview session: thread=${this.threadId}, tab=${this.tabId}`;
401 }
402}
403
404export class PreviewInvalidUrlError extends Schema.TaggedError<PreviewInvalidUrlError>()(
405 "PreviewInvalidUrlError",
406 {
407 inputLength: Schema.Number,
408 reason: Schema.Literals(["empty", "parse", "unsupported-protocol", "unexpected"]),
409 protocol: Schema.optional(Schema.String),
410 cause: Schema.Defect(),
411 },
412) {
413 override get message() {
414 const protocol = this.protocol === undefined ? "" : `: ${this.protocol}`;
415 return `Invalid preview URL (${this.reason}${protocol}; input length ${this.inputLength}).`;
416 }
417}
418
419export class PreviewControlRequiredError extends Schema.TaggedError<PreviewControlRequiredError>()(
420 "PreviewControlRequiredError",
421 { tabId: Schema.String },
422) {
423 override get message() {
424 return "Take control of the server browser and use its viewer controls.";
425 }
426}
427
428export class PreviewClearProfileError extends Schema.TaggedError<PreviewClearProfileError>()(
429 "PreviewClearProfileError",
430 { profileId: Schema.String, cause: Schema.Defect() },
431) {
432 override get message() {
433 return "The environment could not delete this browser profile's data.";
434 }
435}
436
437export const PreviewError = Schema.Union([
438 PreviewSessionLookupError,
439 PreviewInvalidUrlError,
440 PreviewControlRequiredError,
441]);
442export type PreviewError = typeof PreviewError.Type;