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

preview.ts

406 lines13.6 KB

1import { Schema } from "effect";
2import { NonNegativeInt, PositiveInt, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts";
3import { BROWSER_PROFILE_MAX_COUNT, BrowserProfile, BrowserProfileId } from "./browserProfile.ts";
4​
5export const PREVIEW_URL_MAX_LENGTH = 2_048;
6export const CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS = 32;
7​
8const Url = TrimmedNonEmptyString.check(Schema.isMaxLength(PREVIEW_URL_MAX_LENGTH));
9​
10export const ConfiguredLocalServerUrls = Schema.Array(Url).check(
11 Schema.isMaxLength(CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS),
12);
13const Title = Schema.String.check(Schema.isMaxLength(512));
14​
15export const PreviewTabId = TrimmedNonEmptyString.check(Schema.isMaxLength(128));
16export type PreviewTabId = typeof PreviewTabId.Type;
17​
18export const PREVIEW_VIEWPORT_MIN_DIMENSION = 240;
19export const PREVIEW_VIEWPORT_MAX_DIMENSION = 3840;
20export const PREVIEW_VIEWPORT_MAX_AREA = 3840 * 2160;
21​
22const PreviewViewportDimension = Schema.Int.check(
23 Schema.isBetween({
24 minimum: PREVIEW_VIEWPORT_MIN_DIMENSION,
25 maximum: PREVIEW_VIEWPORT_MAX_DIMENSION,
26 }),
27);
28​
29const viewportAreaFilter = Schema.makeFilter(
30 ({ width, height }: { readonly width: number; readonly height: number }) =>
31 width * height <= PREVIEW_VIEWPORT_MAX_AREA ||
32 `Viewport area must not exceed ${PREVIEW_VIEWPORT_MAX_AREA} pixels.`,
33);
34​
35export const PreviewViewportSize = Schema.Struct({
36 width: PreviewViewportDimension,
37 height: PreviewViewportDimension,
38}).check(viewportAreaFilter);
39export type PreviewViewportSize = typeof PreviewViewportSize.Type;
40​
41/** Fill mode can measure below selectable minimum sizes; validate measurements separately. */
42export const PreviewRenderedViewportSize = Schema.Struct({
43 width: Schema.Int.check(Schema.isGreaterThan(0)),
44 height: Schema.Int.check(Schema.isGreaterThan(0)),
45});
46export type PreviewRenderedViewportSize = typeof PreviewRenderedViewportSize.Type;
47​
48export const PREVIEW_VIEWPORT_PRESET_IDS = [
49 "iphone-se",
50 "iphone-xr",
51 "iphone-12-pro",
52 "iphone-14-pro-max",
53 "pixel-7",
54 "samsung-galaxy-s8-plus",
55 "samsung-galaxy-s20-ultra",
56 "ipad-mini",
57 "ipad-air",
58 "ipad-pro",
59 "surface-pro-7",
60 "surface-duo",
61 "galaxy-z-fold-5",
62 "asus-zenbook-fold",
63 "samsung-galaxy-a51-71",
64 "nest-hub",
65 "nest-hub-max",
66] as const;
67​
68export const PreviewViewportPresetId = Schema.Literals(PREVIEW_VIEWPORT_PRESET_IDS);
69export type PreviewViewportPresetId = typeof PreviewViewportPresetId.Type;
70​
71const LEGACY_PREVIEW_VIEWPORT_PRESET_IDS = [
72 "desktop-1920x1080",
73 "desktop-1440x900",
74 "laptop-1366x768",
75 "laptop-1280x800",
76 "ipad-pro-11",
77 "iphone-15-pro",
78 "pixel-8",
79 "galaxy-s24",
80] as const;
81​
82const StoredPreviewViewportPresetId = Schema.Literals([
83 ...PREVIEW_VIEWPORT_PRESET_IDS,
84 ...LEGACY_PREVIEW_VIEWPORT_PRESET_IDS,
85]);
86​
87export const PreviewViewportSetting = Schema.Union([
88 Schema.TaggedStruct("fill", {}),
89 Schema.TaggedStruct("freeform", {
90 ...PreviewViewportSize.fields,
91 }).check(viewportAreaFilter),
92 Schema.TaggedStruct("preset", {
93 ...PreviewViewportSize.fields,
94 presetId: StoredPreviewViewportPresetId,
95 }).check(viewportAreaFilter),
96]);
97export type PreviewViewportSetting = typeof PreviewViewportSetting.Type;
98​
99export const FILL_PREVIEW_VIEWPORT = {
100 _tag: "fill",
101} as const satisfies PreviewViewportSetting;
102​
103/** Shared steps keep settings aligned with desktop Chromium zoom controls. */
104export const PREVIEW_ZOOM_LEVELS = [
105 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,
106] as const;
107​
108export const PreviewZoomFactor = Schema.Literals(PREVIEW_ZOOM_LEVELS);
109export type PreviewZoomFactor = typeof PreviewZoomFactor.Type;
110​
111export const DEFAULT_PREVIEW_ZOOM_FACTOR: PreviewZoomFactor = 1.0;
112​
113export const PreviewAppearancePreference = Schema.Literals(["system", "light", "dark"]);
114export type PreviewAppearancePreference = typeof PreviewAppearancePreference.Type;
115​
116export const DEFAULT_PREVIEW_APPEARANCE: PreviewAppearancePreference = "system";
117​
118const PreviewFileDownload = Schema.Struct({ id: Schema.String, fileName: Schema.String });
119​
120export const PreviewNavStatus = Schema.Union([
121 Schema.TaggedStruct("Idle", {}),
122 Schema.TaggedStruct("Loading", {
123 url: Url,
124 title: Title,
125 }),
126 Schema.TaggedStruct("Success", {
127 url: Url,
128 title: Title,
129 }),
130 Schema.TaggedStruct("LoadFailed", {
131 url: Url,
132 title: Title,
133 code: Schema.Int,
134 description: Schema.String,
135 download: Schema.optional(PreviewFileDownload),
136 }),
137]);
138export type PreviewNavStatus = typeof PreviewNavStatus.Type;
139​
140export const PreviewRuntime = Schema.Literals(["desktop", "server"]);
141export type PreviewRuntime = typeof PreviewRuntime.Type;
142​
143/** JSON reason for preview stream close code 4503; must fit the 123-byte close-reason limit. */
144export const PreviewStreamHostSetup = Schema.Struct({
145 need: Schema.Literals(["sandbox", "libraries"]),
146 command: Schema.String,
147});
148export type PreviewStreamHostSetup = typeof PreviewStreamHostSetup.Type;
149export const PREVIEW_STREAM_HOST_SETUP_CLOSE_CODE = 4503;
150​
151export const PreviewSessionSnapshot = Schema.Struct({
152 threadId: TrimmedNonEmptyString,
153 tabId: PreviewTabId,
154 navStatus: PreviewNavStatus,
155 canGoBack: Schema.Boolean,
156 canGoForward: Schema.Boolean,
157 viewport: Schema.optional(PreviewViewportSetting),
158 colorScheme: Schema.optional(PreviewAppearancePreference),
159 zoomFactor: Schema.optional(PreviewZoomFactor),
160 /** Fixed at open; Electron cannot change a webview partition after attach without losing page state. */
161 profileId: Schema.optional(BrowserProfileId),
162 runtime: Schema.optional(PreviewRuntime),
163 /** The server runs this tab in headless Chromium, so the desktop streams it like other clients. */
164 headless: Schema.optional(Schema.Boolean),
165 automationOwner: Schema.optional(Schema.String),
166 reveal: Schema.optional(Schema.Boolean),
167 revealRequest: Schema.optional(Schema.Struct({ id: Schema.String, force: Schema.Boolean })),
168 updatedAt: Schema.String,
169});
170export type PreviewSessionSnapshot = typeof PreviewSessionSnapshot.Type;
171​
172export const PreviewOpenInput = Schema.Struct({
173 threadId: ThreadId,
174 url: Schema.optional(Url),
175 viewport: Schema.optional(PreviewViewportSetting),
176 profileId: Schema.optional(BrowserProfileId),
177 runtime: Schema.optional(PreviewRuntime),
178 reveal: Schema.optional(Schema.Boolean),
179});
180export type PreviewOpenInput = typeof PreviewOpenInput.Type;
181​
182export const PreviewReportStatusInput = Schema.Struct({
183 threadId: ThreadId,
184 tabId: PreviewTabId,
185 navStatus: PreviewNavStatus,
186 canGoBack: Schema.Boolean,
187 canGoForward: Schema.Boolean,
188});
189export type PreviewReportStatusInput = typeof PreviewReportStatusInput.Type;
190​
191export const PreviewResizeInput = Schema.Struct({
192 threadId: ThreadId,
193 tabId: PreviewTabId,
194 viewport: PreviewViewportSetting,
195});
196export type PreviewResizeInput = typeof PreviewResizeInput.Type;
197​
198/** Requires no tab control, unlike page input. */
199export const PreviewAdjustInput = Schema.Struct({
200 threadId: ThreadId,
201 tabId: PreviewTabId,
202 colorScheme: Schema.optional(PreviewAppearancePreference),
203 zoomFactor: Schema.optional(PreviewZoomFactor),
204 hardReload: Schema.optional(Schema.Boolean),
205 clear: Schema.optional(Schema.Literals(["cookies", "cache"])),
206});
207export type PreviewAdjustInput = typeof PreviewAdjustInput.Type;
208​
209export const PreviewCloseInput = Schema.Struct({
210 threadId: ThreadId,
211 tabId: Schema.optional(PreviewTabId),
212});
213export type PreviewCloseInput = typeof PreviewCloseInput.Type;
214​
215export const BROWSER_RECORDING_FRAME_RATES = [30, 60] as const;
216export const BrowserRecordingFrameRate = Schema.Literals(BROWSER_RECORDING_FRAME_RATES);
217export type BrowserRecordingFrameRate = typeof BrowserRecordingFrameRate.Type;
218export const DEFAULT_BROWSER_RECORDING_FRAME_RATE: BrowserRecordingFrameRate = 30;
219​
220export const PreviewReportProfilesInput = Schema.Struct({
221 profiles: Schema.Array(BrowserProfile).check(Schema.isMaxLength(BROWSER_PROFILE_MAX_COUNT)),
222 defaultProfileId: BrowserProfileId,
223 /** Optional so older clients keep reporting; omitting it keeps the last reported rate. */
224 recordingFrameRate: Schema.optional(BrowserRecordingFrameRate),
225});
226export type PreviewReportProfilesInput = typeof PreviewReportProfilesInput.Type;
227​
228export const PreviewClearProfileInput = Schema.Struct({
229 profileId: BrowserProfileId,
230});
231export type PreviewClearProfileInput = typeof PreviewClearProfileInput.Type;
232​
233export const PreviewListInput = Schema.Struct({
234 threadId: ThreadId,
235});
236export type PreviewListInput = typeof PreviewListInput.Type;
237​
238export const PreviewListResult = Schema.Struct({
239 sessions: Schema.Array(PreviewSessionSnapshot),
240 /** Identifies the current server process so revision resets are safe. */
241 serverEpoch: TrimmedNonEmptyString,
242 revision: NonNegativeInt,
243});
244export type PreviewListResult = typeof PreviewListResult.Type;
245​
246const PreviewEventBaseSchema = Schema.Struct({
247 threadId: TrimmedNonEmptyString,
248 tabId: PreviewTabId,
249 createdAt: Schema.String,
250 serverEpoch: TrimmedNonEmptyString,
251 /** Monotonic server state revision shared with PreviewListResult. */
252 revision: PositiveInt,
253});
254​
255const PreviewOpenedEvent = Schema.Struct({
256 ...PreviewEventBaseSchema.fields,
257 type: Schema.Literal("opened"),
258 snapshot: PreviewSessionSnapshot,
259});
260​
261const PreviewNavigatedEvent = Schema.Struct({
262 ...PreviewEventBaseSchema.fields,
263 type: Schema.Literal("navigated"),
264 snapshot: PreviewSessionSnapshot,
265});
266​
267const PreviewResizedEvent = Schema.Struct({
268 ...PreviewEventBaseSchema.fields,
269 type: Schema.Literal("resized"),
270 snapshot: PreviewSessionSnapshot,
271 request: Schema.optional(
272 Schema.Struct({
273 hardReload: Schema.optional(Schema.Boolean),
274 clear: Schema.optional(Schema.Literals(["cookies", "cache"])),
275 }),
276 ),
277});
278​
279const PreviewFailedEvent = Schema.Struct({
280 ...PreviewEventBaseSchema.fields,
281 type: Schema.Literal("failed"),
282 url: Url,
283 title: Title,
284 code: Schema.Int,
285 description: Schema.String,
286 download: Schema.optional(PreviewFileDownload),
287});
288​
289const PreviewClosedEvent = Schema.Struct({
290 ...PreviewEventBaseSchema.fields,
291 type: Schema.Literal("closed"),
292});
293​
294export const PreviewEvent = Schema.Union([
295 PreviewOpenedEvent,
296 PreviewNavigatedEvent,
297 PreviewResizedEvent,
298 PreviewFailedEvent,
299 PreviewClosedEvent,
300]);
301export type PreviewEvent = typeof PreviewEvent.Type;
302​
303const LocalServerPort = Schema.Int.check(Schema.isGreaterThan(0)).check(Schema.isLessThan(65536));
304​
305export const DiscoveredLocalServer = Schema.Struct({
306 host: TrimmedNonEmptyString,
307 port: LocalServerPort,
308 url: Url,
309 processName: Schema.NullOr(TrimmedNonEmptyString),
310 pid: Schema.NullOr(Schema.Int.check(Schema.isGreaterThan(0))),
311 terminal: Schema.NullOr(
312 Schema.Struct({
313 threadId: ThreadId,
314 terminalId: TrimmedNonEmptyString,
315 }),
316 ),
317 /** Started by the thread's agent. Older servers omit it. */
318 agent: Schema.optionalKey(Schema.NullOr(Schema.Struct({ threadId: ThreadId }))),
319});
320export type DiscoveredLocalServer = typeof DiscoveredLocalServer.Type;
321​
322export const PreviewStopLocalServerInput = Schema.Struct({
323 pid: PositiveInt,
324 port: LocalServerPort,
325});
326export type PreviewStopLocalServerInput = typeof PreviewStopLocalServerInput.Type;
327​
328export class PreviewStopLocalServerError extends Schema.TaggedError<PreviewStopLocalServerError>()(
329 "PreviewStopLocalServerError",
330 {
331 reason: Schema.Literals(["not-found", "shared-group", "unsupported", "signal-failed"]),
332 cause: Schema.optional(Schema.Defect()),
333 },
334) {
335 override get message() {
336 switch (this.reason) {
337 case "not-found":
338 return "This server is no longer running.";
339 case "shared-group":
340 return "This server shares a process group with T3 Code, an agent, or a terminal shell, so it can't be stopped on its own.";
341 case "unsupported":
342 return "Stopping servers is not supported on this environment's platform.";
343 case "signal-failed":
344 return "The server's processes could not be signaled.";
345 }
346 }
348​
349export const DiscoveredLocalServerList = Schema.Struct({
350 servers: Schema.Array(DiscoveredLocalServer),
351 scannedAt: Schema.String,
352 configuredUrlProbing: Schema.optional(Schema.Literal(true)),
353});
354export type DiscoveredLocalServerList = typeof DiscoveredLocalServerList.Type;
355​
356export class PreviewSessionLookupError extends Schema.TaggedError<PreviewSessionLookupError>()(
357 "PreviewSessionLookupError",
358 {
359 threadId: Schema.String,
360 tabId: Schema.String,
361 },
362) {
363 override get message() {
364 return `Unknown preview session: thread=${this.threadId}, tab=${this.tabId}`;
365 }
367​
368export class PreviewInvalidUrlError extends Schema.TaggedError<PreviewInvalidUrlError>()(
369 "PreviewInvalidUrlError",
370 {
371 inputLength: Schema.Number,
372 reason: Schema.Literals(["empty", "parse", "unsupported-protocol", "unexpected"]),
373 protocol: Schema.optional(Schema.String),
374 cause: Schema.Defect(),
375 },
376) {
377 override get message() {
378 const protocol = this.protocol === undefined ? "" : `: ${this.protocol}`;
379 return `Invalid preview URL (${this.reason}${protocol}; input length ${this.inputLength}).`;
380 }
382​
383export class PreviewControlRequiredError extends Schema.TaggedError<PreviewControlRequiredError>()(
384 "PreviewControlRequiredError",
385 { tabId: Schema.String },
386) {
387 override get message() {
388 return "Take control of the server browser and use its viewer controls.";
389 }
391​
392export class PreviewClearProfileError extends Schema.TaggedError<PreviewClearProfileError>()(
393 "PreviewClearProfileError",
394 { profileId: Schema.String, cause: Schema.Defect() },
395) {
396 override get message() {
397 return "The environment could not delete this browser profile's data.";
398 }
400​
401export const PreviewError = Schema.Union([
402 PreviewSessionLookupError,
403 PreviewInvalidUrlError,
404 PreviewControlRequiredError,
405]);
406export type PreviewError = typeof PreviewError.Type;