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
165export const PreviewSessionSnapshot = Schema.Struct({
166 threadId: TrimmedNonEmptyString,
167 tabId: PreviewTabId,
168 navStatus: PreviewNavStatus,
169 canGoBack: Schema.Boolean,
170 canGoForward: Schema.Boolean,
171 /** Missing snapshots from older servers are treated as fill-panel mode. */
172 viewport: Schema.optional(PreviewViewportSetting),
173 /**
174 * Browser profile the tab's Chromium partition is derived from. Fixed at
175 * open: Electron only honours a `<webview>`'s partition before attach, so
176 * switching would require tearing the guest down and losing page state.
177 */
178 profileId: Schema.optional(BrowserProfileId),
179 updatedAt: Schema.String,
180});
181export type PreviewSessionSnapshot = typeof PreviewSessionSnapshot.Type;
182
183export const PreviewOpenInput = Schema.Struct({
184 threadId: ThreadId,
185 /** Omit to create an empty (Idle) tab the user can type into. */
186 url: Schema.optional(Url),
187 /**
188 * Initial viewport for the new tab. Omitting it keeps the historical
189 * fill-panel behaviour; clients that have a configured default send it here
190 * so the session is born at the right size instead of being resized a frame
191 * later (which the user would see as a visible reflow).
192 */
193 viewport: Schema.optional(PreviewViewportSetting),
194 /** Omit to open under the client's configured default profile. */
195 profileId: Schema.optional(BrowserProfileId),
196});
197export type PreviewOpenInput = typeof PreviewOpenInput.Type;
198
199export const PreviewNavigateInput = Schema.Struct({
200 threadId: ThreadId,
201 tabId: PreviewTabId,
202 url: Url,
203 resolvedTitle: Schema.optional(Title),
204});
205export type PreviewNavigateInput = typeof PreviewNavigateInput.Type;
206
207export const PreviewReportStatusInput = Schema.Struct({
208 threadId: ThreadId,
209 tabId: PreviewTabId,
210 navStatus: PreviewNavStatus,
211 canGoBack: Schema.Boolean,
212 canGoForward: Schema.Boolean,
213});
214export type PreviewReportStatusInput = typeof PreviewReportStatusInput.Type;
215
216export const PreviewRefreshInput = Schema.Struct({
217 threadId: ThreadId,
218 tabId: PreviewTabId,
219});
220export type PreviewRefreshInput = typeof PreviewRefreshInput.Type;
221
222export const PreviewResizeInput = Schema.Struct({
223 threadId: ThreadId,
224 tabId: PreviewTabId,
225 viewport: PreviewViewportSetting,
226});
227export type PreviewResizeInput = typeof PreviewResizeInput.Type;
228
229export const PreviewCloseInput = Schema.Struct({
230 threadId: ThreadId,
231 tabId: Schema.optional(PreviewTabId),
232});
233export type PreviewCloseInput = typeof PreviewCloseInput.Type;
234
235export const PreviewListInput = Schema.Struct({
236 threadId: ThreadId,
237});
238export type PreviewListInput = typeof PreviewListInput.Type;
239
240export const PreviewListResult = Schema.Struct({
241 sessions: Schema.Array(PreviewSessionSnapshot),
242 /** Identifies the current server process so revision resets are safe. */
243 serverEpoch: TrimmedNonEmptyString,
244 /** Monotonic server state revision used to reject stale list responses. */
245 revision: NonNegativeInt,
246});
247export type PreviewListResult = typeof PreviewListResult.Type;
248
249const PreviewEventBaseSchema = Schema.Struct({
250 threadId: TrimmedNonEmptyString,
251 tabId: PreviewTabId,
252 createdAt: Schema.String,
253 /** Identifies the server process that emitted this event. */
254 serverEpoch: TrimmedNonEmptyString,
255 /** Monotonic server state revision shared with PreviewListResult. */
256 revision: PositiveInt,
257});
258
259const PreviewOpenedEvent = Schema.Struct({
260 ...PreviewEventBaseSchema.fields,
261 type: Schema.Literal("opened"),
262 snapshot: PreviewSessionSnapshot,
263});
264
265const PreviewNavigatedEvent = Schema.Struct({
266 ...PreviewEventBaseSchema.fields,
267 type: Schema.Literal("navigated"),
268 snapshot: PreviewSessionSnapshot,
269});
270
271const PreviewResizedEvent = Schema.Struct({
272 ...PreviewEventBaseSchema.fields,
273 type: Schema.Literal("resized"),
274 snapshot: PreviewSessionSnapshot,
275});
276
277const PreviewFailedEvent = Schema.Struct({
278 ...PreviewEventBaseSchema.fields,
279 type: Schema.Literal("failed"),
280 url: Url,
281 title: Title,
282 code: Schema.Int,
283 description: Schema.String,
284});
285
286const PreviewClosedEvent = Schema.Struct({
287 ...PreviewEventBaseSchema.fields,
288 type: Schema.Literal("closed"),
289});
290
291export const PreviewEvent = Schema.Union([
292 PreviewOpenedEvent,
293 PreviewNavigatedEvent,
294 PreviewResizedEvent,
295 PreviewFailedEvent,
296 PreviewClosedEvent,
297]);
298export type PreviewEvent = typeof PreviewEvent.Type;
299
300/**
301 * A localhost server detected by the port scanner. Used to populate the
302 * "Local" recommendations in the empty-state of the preview panel.
303 */
304export const DiscoveredLocalServer = Schema.Struct({
305 host: TrimmedNonEmptyString,
306 port: Schema.Int.check(Schema.isGreaterThan(0)).check(Schema.isLessThan(65536)),
307 url: Url,
308 processName: Schema.NullOr(TrimmedNonEmptyString),
309 pid: Schema.NullOr(Schema.Int.check(Schema.isGreaterThan(0))),
310 terminal: Schema.NullOr(
311 Schema.Struct({
312 threadId: ThreadId,
313 terminalId: TrimmedNonEmptyString,
314 }),
315 ),
316});
317export type DiscoveredLocalServer = typeof DiscoveredLocalServer.Type;
318
319export const DiscoveredLocalServerList = Schema.Struct({
320 servers: Schema.Array(DiscoveredLocalServer),
321 scannedAt: Schema.String,
322 configuredUrlProbing: Schema.optional(Schema.Literal(true)),
323});
324export type DiscoveredLocalServerList = typeof DiscoveredLocalServerList.Type;
325
326export class PreviewSessionLookupError extends Schema.TaggedError<PreviewSessionLookupError>()(
327 "PreviewSessionLookupError",
328 {
329 threadId: Schema.String,
330 tabId: Schema.String,
331 },
332) {
333 override get message() {
334 return `Unknown preview session: thread=${this.threadId}, tab=${this.tabId}`;
335 }
336}
337
338export class PreviewInvalidUrlError extends Schema.TaggedError<PreviewInvalidUrlError>()(
339 "PreviewInvalidUrlError",
340 {
341 inputLength: Schema.Number,
342 reason: Schema.Literals(["empty", "parse", "unsupported-protocol", "unexpected"]),
343 protocol: Schema.optional(Schema.String),
344 cause: Schema.Defect(),
345 },
346) {
347 override get message() {
348 const protocol = this.protocol === undefined ? "" : `: ${this.protocol}`;
349 return `Invalid preview URL (${this.reason}${protocol}; input length ${this.inputLength}).`;
350 }
351}
352
353export const PreviewError = Schema.Union([PreviewSessionLookupError, PreviewInvalidUrlError]);
354export type PreviewError = typeof PreviewError.Type;