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

preview.ts

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