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

preview.ts

420 lines14.0 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 PreviewNavigateInput = Schema.Struct({
183 threadId: ThreadId,
184 tabId: PreviewTabId,
185 url: Url,
186 resolvedTitle: Schema.optional(Title),
187});
188export type PreviewNavigateInput = typeof PreviewNavigateInput.Type;
189​
190export const PreviewReportStatusInput = Schema.Struct({
191 threadId: ThreadId,
192 tabId: PreviewTabId,
193 navStatus: PreviewNavStatus,
194 canGoBack: Schema.Boolean,
195 canGoForward: Schema.Boolean,
196});
197export type PreviewReportStatusInput = typeof PreviewReportStatusInput.Type;
198​
199export const PreviewRefreshInput = Schema.Struct({
200 threadId: ThreadId,
201 tabId: PreviewTabId,
202});
203export type PreviewRefreshInput = typeof PreviewRefreshInput.Type;
204​
205export const PreviewResizeInput = Schema.Struct({
206 threadId: ThreadId,
207 tabId: PreviewTabId,
208 viewport: PreviewViewportSetting,
209});
210export type PreviewResizeInput = typeof PreviewResizeInput.Type;
211​
212/** Requires no tab control, unlike page input. */
213export const PreviewAdjustInput = Schema.Struct({
214 threadId: ThreadId,
215 tabId: PreviewTabId,
216 colorScheme: Schema.optional(PreviewAppearancePreference),
217 zoomFactor: Schema.optional(PreviewZoomFactor),
218 hardReload: Schema.optional(Schema.Boolean),
219 clear: Schema.optional(Schema.Literals(["cookies", "cache"])),
220});
221export type PreviewAdjustInput = typeof PreviewAdjustInput.Type;
222​
223export const PreviewCloseInput = Schema.Struct({
224 threadId: ThreadId,
225 tabId: Schema.optional(PreviewTabId),
226});
227export type PreviewCloseInput = typeof PreviewCloseInput.Type;
228​
229export const BROWSER_RECORDING_FRAME_RATES = [30, 60] as const;
230export const BrowserRecordingFrameRate = Schema.Literals(BROWSER_RECORDING_FRAME_RATES);
231export type BrowserRecordingFrameRate = typeof BrowserRecordingFrameRate.Type;
232export const DEFAULT_BROWSER_RECORDING_FRAME_RATE: BrowserRecordingFrameRate = 30;
233​
234export const PreviewReportProfilesInput = Schema.Struct({
235 profiles: Schema.Array(BrowserProfile).check(Schema.isMaxLength(BROWSER_PROFILE_MAX_COUNT)),
236 defaultProfileId: BrowserProfileId,
237 /** Optional so older clients keep reporting; omitting it keeps the last reported rate. */
238 recordingFrameRate: Schema.optional(BrowserRecordingFrameRate),
239});
240export type PreviewReportProfilesInput = typeof PreviewReportProfilesInput.Type;
241​
242export const PreviewClearProfileInput = Schema.Struct({
243 profileId: BrowserProfileId,
244});
245export type PreviewClearProfileInput = typeof PreviewClearProfileInput.Type;
246​
247export const PreviewListInput = Schema.Struct({
248 threadId: ThreadId,
249});
250export type PreviewListInput = typeof PreviewListInput.Type;
251​
252export const PreviewListResult = Schema.Struct({
253 sessions: Schema.Array(PreviewSessionSnapshot),
254 /** Identifies the current server process so revision resets are safe. */
255 serverEpoch: TrimmedNonEmptyString,
256 revision: NonNegativeInt,
257});
258export type PreviewListResult = typeof PreviewListResult.Type;
259​
260const PreviewEventBaseSchema = Schema.Struct({
261 threadId: TrimmedNonEmptyString,
262 tabId: PreviewTabId,
263 createdAt: Schema.String,
264 serverEpoch: TrimmedNonEmptyString,
265 /** Monotonic server state revision shared with PreviewListResult. */
266 revision: PositiveInt,
267});
268​
269const PreviewOpenedEvent = Schema.Struct({
270 ...PreviewEventBaseSchema.fields,
271 type: Schema.Literal("opened"),
272 snapshot: PreviewSessionSnapshot,
273});
274​
275const PreviewNavigatedEvent = Schema.Struct({
276 ...PreviewEventBaseSchema.fields,
277 type: Schema.Literal("navigated"),
278 snapshot: PreviewSessionSnapshot,
279});
280​
281const PreviewResizedEvent = Schema.Struct({
282 ...PreviewEventBaseSchema.fields,
283 type: Schema.Literal("resized"),
284 snapshot: PreviewSessionSnapshot,
285 request: Schema.optional(
286 Schema.Struct({
287 hardReload: Schema.optional(Schema.Boolean),
288 clear: Schema.optional(Schema.Literals(["cookies", "cache"])),
289 }),
290 ),
291});
292​
293const PreviewFailedEvent = Schema.Struct({
294 ...PreviewEventBaseSchema.fields,
295 type: Schema.Literal("failed"),
296 url: Url,
297 title: Title,
298 code: Schema.Int,
299 description: Schema.String,
300 download: Schema.optional(PreviewFileDownload),
301});
302​
303const PreviewClosedEvent = Schema.Struct({
304 ...PreviewEventBaseSchema.fields,
305 type: Schema.Literal("closed"),
306});
307​
308export const PreviewEvent = Schema.Union([
309 PreviewOpenedEvent,
310 PreviewNavigatedEvent,
311 PreviewResizedEvent,
312 PreviewFailedEvent,
313 PreviewClosedEvent,
314]);
315export type PreviewEvent = typeof PreviewEvent.Type;
316​
317const LocalServerPort = Schema.Int.check(Schema.isGreaterThan(0)).check(Schema.isLessThan(65536));
318​
319export const DiscoveredLocalServer = Schema.Struct({
320 host: TrimmedNonEmptyString,
321 port: LocalServerPort,
322 url: Url,
323 processName: Schema.NullOr(TrimmedNonEmptyString),
324 pid: Schema.NullOr(Schema.Int.check(Schema.isGreaterThan(0))),
325 terminal: Schema.NullOr(
326 Schema.Struct({
327 threadId: ThreadId,
328 terminalId: TrimmedNonEmptyString,
329 }),
330 ),
331 /** Started by the thread's agent. Older servers omit it. */
332 agent: Schema.optionalKey(Schema.NullOr(Schema.Struct({ threadId: ThreadId }))),
333});
334export type DiscoveredLocalServer = typeof DiscoveredLocalServer.Type;
335​
336export const PreviewStopLocalServerInput = Schema.Struct({
337 pid: PositiveInt,
338 port: LocalServerPort,
339});
340export type PreviewStopLocalServerInput = typeof PreviewStopLocalServerInput.Type;
341​
342export class PreviewStopLocalServerError extends Schema.TaggedError<PreviewStopLocalServerError>()(
343 "PreviewStopLocalServerError",
344 {
345 reason: Schema.Literals(["not-found", "shared-group", "unsupported", "signal-failed"]),
346 cause: Schema.optional(Schema.Defect()),
347 },
348) {
349 override get message() {
350 switch (this.reason) {
351 case "not-found":
352 return "This server is no longer running.";
353 case "shared-group":
354 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.";
355 case "unsupported":
356 return "Stopping servers is not supported on this environment's platform.";
357 case "signal-failed":
358 return "The server's processes could not be signaled.";
359 }
360 }
362​
363export const DiscoveredLocalServerList = Schema.Struct({
364 servers: Schema.Array(DiscoveredLocalServer),
365 scannedAt: Schema.String,
366 configuredUrlProbing: Schema.optional(Schema.Literal(true)),
367});
368export type DiscoveredLocalServerList = typeof DiscoveredLocalServerList.Type;
369​
370export class PreviewSessionLookupError extends Schema.TaggedError<PreviewSessionLookupError>()(
371 "PreviewSessionLookupError",
372 {
373 threadId: Schema.String,
374 tabId: Schema.String,
375 },
376) {
377 override get message() {
378 return `Unknown preview session: thread=${this.threadId}, tab=${this.tabId}`;
379 }
381​
382export class PreviewInvalidUrlError extends Schema.TaggedError<PreviewInvalidUrlError>()(
383 "PreviewInvalidUrlError",
384 {
385 inputLength: Schema.Number,
386 reason: Schema.Literals(["empty", "parse", "unsupported-protocol", "unexpected"]),
387 protocol: Schema.optional(Schema.String),
388 cause: Schema.Defect(),
389 },
390) {
391 override get message() {
392 const protocol = this.protocol === undefined ? "" : `: ${this.protocol}`;
393 return `Invalid preview URL (${this.reason}${protocol}; input length ${this.inputLength}).`;
394 }
396​
397export class PreviewControlRequiredError extends Schema.TaggedError<PreviewControlRequiredError>()(
398 "PreviewControlRequiredError",
399 { tabId: Schema.String },
400) {
401 override get message() {
402 return "Take control of the server browser and use its viewer controls.";
403 }
405​
406export class PreviewClearProfileError extends Schema.TaggedError<PreviewClearProfileError>()(
407 "PreviewClearProfileError",
408 { profileId: Schema.String, cause: Schema.Defect() },
409) {
410 override get message() {
411 return "The environment could not delete this browser profile's data.";
412 }
414​
415export const PreviewError = Schema.Union([
416 PreviewSessionLookupError,
417 PreviewInvalidUrlError,
418 PreviewControlRequiredError,
419]);
420export type PreviewError = typeof PreviewError.Type;