Repository navigation
Expand file tree
/
Copy pathServerBrowser.ts
More file actions
2458 lines (2366 loc) · 93.9 KB
/
Copy pathServerBrowser.ts
File metadata and controls
2458 lines (2366 loc) · 93.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @effect-diagnostics nodeBuiltinImport:off globalDate:off globalTimers:off - Playwright callbacks run outside the Effect runtime.
// Screencasts ignore emulated device scale; real 2x keeps captures sharp.
// --disable-gpu uses cheaper software compositing while preserving SwiftShader WebGL.
import {
BUILT_IN_BROWSER_PROFILES,
DEFAULT_BROWSER_PROFILE_ID,
FILL_PREVIEW_VIEWPORT,
findBrowserProfile,
INCOGNITO_BROWSER_PROFILE_ID,
resolveBrowserProfiles,
type BrowserProfile,
type PreviewReportProfilesInput,
PREVIEW_AUTOMATION_SERVER_OPERATIONS,
PreviewViewportSetting as PreviewViewportSettingSchema,
PROVIDER_SEND_TURN_MAX_FILE_BYTES,
type PreviewAutomationActionEvent,
type PreviewAutomationClickInput,
type PreviewAutomationDialogInput,
type PreviewAutomationConsoleEntry,
type PreviewAutomationDragInput,
type PreviewAutomationEvaluateInput,
type PreviewAutomationHoverInput,
type PreviewAutomationNavigateInput,
type PreviewAutomationNetworkEntry,
type PreviewAutomationOpenInput,
type PreviewAutomationPressInput,
type PreviewAutomationRequest,
type PreviewAutomationResizeInput,
type PreviewAutomationScrollInput,
type PreviewAutomationSelectInput,
type PreviewAutomationSetColorSchemeInput,
type PreviewAutomationStatus,
type PreviewAutomationTypeInput,
type PreviewAutomationUploadInput,
type PreviewAutomationWaitForInput,
PreviewClearProfileError,
type PreviewEvent,
type PreviewNavStatus,
type PreviewSessionSnapshot,
type PreviewViewportSetting,
ThreadId,
SERVER_BROWSER_AUTOMATION_CLIENT_ID,
type PreviewAppearancePreference,
} from "@t3tools/contracts";
import * as HostProcess from "@t3tools/shared/HostProcess";
import { normalizePreviewUrl } from "@t3tools/shared/preview";
import { resolvePreviewViewport } from "@t3tools/shared/previewViewport";
import * as NodeCrypto from "node:crypto";
import * as NodeFSP from "node:fs/promises";
import * as NodePath from "node:path";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import { constVoid } from "effect/Function";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Schedule from "effect/Schedule";
import * as Schema from "effect/Schema";
import * as Exit from "effect/Exit";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import type * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
import type {
BrowserContext,
CDPSession,
Dialog,
Download,
FileChooser,
Page,
} from "playwright-core";
import { PENDING_ATTACHMENT_THREAD_SEGMENT } from "../attachmentStore.ts";
import * as ServerConfig from "../config.ts";
import { resolveRootCliCommand } from "../cli/invocation.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as PreviewAutomationBroker from "../mcp/PreviewAutomationBroker.ts";
import * as DesktopBrowserChannel from "./DesktopBrowserChannel.ts";
import * as PreviewManager from "./Manager.ts";
import * as ServerBrowserPage from "./ServerBrowserPage.ts";
import * as PreviewBrowser from "./PreviewBrowser.ts";
import * as PreviewBrowserHost from "./PreviewBrowserHost.ts";
import { presentAsChrome, ServerBrowserContexts } from "./ServerBrowserContexts.ts";
import { BrowserControlInterrupted, SessionControl } from "./SessionControl.ts";
const SERVER_HOST_CLIENT_ID = SERVER_BROWSER_AUTOMATION_CLIENT_ID;
const RENDER_SCALE = 2;
// Chromium allows three unacked frames, so 100 ms pacing caps viewers near 30 fps.
const SCREENCAST_ACK_PACE_MS = 100;
const SCREENCAST_SETTLE_MS = 200;
// Only scrolling triggers reduced-quality motion frames; animations stay sharp.
const SCREENCAST_MOTION_FRAMES = 4;
const SCREENCAST_MOTION_WINDOW_MS = 300;
const SCREENCAST_MOTION_QUALITY = 50;
const HOST_RECONNECT_DELAY = "1 second";
/** How long a new tab waits for the desktop app to mount it before running headless. */
const DESKTOP_ATTACH_TIMEOUT = "10 seconds";
const VIEWER_OUTPUT_LIMIT = 64;
const RECORDING_SCREENCAST = { format: "jpeg", quality: 90, everyNthFrame: 1 } as const;
const decodeViewportSetting = Schema.decodeUnknownSync(PreviewViewportSettingSchema);
/** The agent cursor glides to its target, then pulses just before the press, like desktop tabs. */
const AGENT_CURSOR_MOVE_MS = 160;
const AGENT_CURSOR_CLICK_LEAD_MS = 40;
const sleepUntil = (deadline: number) =>
new Promise<void>((resolve) => setTimeout(resolve, Math.max(0, deadline - Date.now())));
// Touch viewers raise the keyboard for editable targets, including opaque frames.
const EDITABLE_AT_POINT_SCRIPT = `(x, y) => {
let element = document.elementFromPoint(x, y);
while (element && element.shadowRoot) {
const inner = element.shadowRoot.elementFromPoint(x, y);
if (!inner || inner === element) break;
element = inner;
}
if (element && element.tagName === "LABEL" && element.control) element = element.control;
if (!element) return false;
if (element.tagName === "IFRAME" || element.tagName === "FRAME") return true;
if (element.isContentEditable) return true;
if (element.tagName === "TEXTAREA") return !element.disabled && !element.readOnly;
if (element.tagName !== "INPUT") return false;
const nonText = ["button", "checkbox", "color", "file", "hidden", "image", "radio", "range", "reset", "submit"];
return !nonText.includes(element.type) && !element.disabled && !element.readOnly;
}`;
const UNATTACHED_FILL_VIEWPORT = { width: 1280, height: 800 } as const;
const NAVIGATION_TIMEOUT_MS = 15_000;
const VIEWER_NAVIGATION_OPTIONS = { waitUntil: "commit", timeout: NAVIGATION_TIMEOUT_MS } as const;
const ACTION_TIMELINE_LIMIT = 50;
export class ServerBrowserTabNotFoundError extends Schema.TaggedError<ServerBrowserTabNotFoundError>()(
"ServerBrowserTabNotFoundError",
{ threadId: Schema.String, tabId: Schema.String },
) {
override get message(): string {
return "The server preview tab does not exist.";
}
}
const isTabNotFound = Schema.is(ServerBrowserTabNotFoundError);
const isHostSetupError = Schema.is(
Schema.Union([
PreviewBrowserHost.PreviewBrowserSandboxError,
PreviewBrowserHost.PreviewBrowserLibrariesError,
]),
);
export class ServerBrowserLaunchError extends Schema.TaggedError<ServerBrowserLaunchError>()(
"ServerBrowserLaunchError",
{ cause: Schema.Defect() },
) {
override get message(): string {
return "The server preview browser could not start.";
}
}
export type ServerBrowserViewerOutput =
| {
readonly _tag: "frame";
readonly data: Uint8Array;
readonly ack: Effect.Effect<void>;
}
| { readonly _tag: "viewport"; readonly width: number; readonly height: number }
| {
readonly _tag: "control";
readonly canOperate: boolean;
readonly controller: "agent" | "you" | "another-viewer" | "unclaimed";
readonly generation: number;
readonly dialog: {
readonly type: string;
readonly message: string;
readonly defaultValue: string;
} | null;
}
| {
readonly _tag: "probe";
readonly x: number;
readonly y: number;
readonly editable: boolean;
}
| { readonly _tag: "clipboard"; readonly text: string }
| {
readonly _tag: "pointer";
readonly phase: "move" | "click";
readonly x: number;
readonly y: number;
readonly sequence: number;
}
| {
readonly _tag: "fileChooser";
readonly id: string;
readonly multiple: boolean;
readonly accept: string;
}
| { readonly _tag: "fileChooserClosed"; readonly id: string }
/** The page this viewer controls opened a new tab; the viewer shows it, as a browser would. */
| { readonly _tag: "popup"; readonly tabId: string }
| {
readonly _tag: "download";
readonly id: string;
readonly fileName: string;
readonly sizeBytes: number;
}
| { readonly _tag: "gone" }
/** The page is still open, but this connection to it ended; the viewer reconnects. */
| { readonly _tag: "reconnect" };
export interface ServerBrowserViewer {
readonly output: Queue.Dequeue<ServerBrowserViewerOutput>;
readonly input: (message: unknown) => Effect.Effect<void>;
}
export class ServerBrowser extends Context.Service<
ServerBrowser,
{
readonly attachViewer: (input: {
readonly threadId: string;
readonly tabId: string;
readonly maxWidth: number;
readonly maxHeight: number;
readonly quality: number;
readonly canOperate: boolean;
}) => Effect.Effect<
ServerBrowserViewer,
ServerBrowserTabNotFoundError | ServerBrowserLaunchError,
Scope.Scope
>;
/**
* Gives a page's open file picker the files a viewer uploaded, by path, and
* closes it. No files cancels the pick. False when that picker is gone.
*/
readonly answerFileChooser: (input: {
readonly threadId: string;
readonly tabId: string;
readonly chooserId: string;
readonly files: ReadonlyArray<{
readonly name: string;
readonly mimeType: string;
readonly buffer: Buffer;
}>;
}) => Effect.Effect<boolean>;
/** A finished download of a live tab, for the authenticated download route. */
readonly openDownload: (input: {
readonly threadId: string;
readonly tabId: string;
readonly downloadId: string;
}) => Effect.Effect<Option.Option<{ readonly path: string; readonly fileName: string }>>;
/** Deletes a human profile's server-side storage, closing its open tabs first. */
readonly clearProfile: (profileId: string) => Effect.Effect<void, PreviewClearProfileError>;
/**
* Records a client's browser profiles for agents' preview_open. In memory:
* clients report again on connect and whenever the list changes.
*/
readonly reportProfiles: (input: PreviewReportProfilesInput) => Effect.Effect<void>;
}
>()("t3/preview/ServerBrowser") {}
interface ViewerState {
readonly id: string;
readonly canOperate: boolean;
readonly pressedKeys: Map<string, { key: string; code: string }>;
readonly pressedButtons: Map<"left" | "middle" | "right", { x: number; y: number }>;
readonly push: (output: ServerBrowserViewerOutput) => void;
readonly pause: () => Promise<void>;
readonly resume: () => Promise<void>;
scrolledAt: number;
/** Last input from this viewer; page copies reach its clipboard only right after. */
inputAt: number;
/** Panel bounds, retained in fixed mode; passive viewers never request a size. */
requestedSize: { width: number; height: number; order: number } | null;
}
interface EncoderWindow {
__t3Recorder: {
cursor(x: number, y: number, click: boolean): void;
frame(data: string, width: number): Promise<boolean>;
stop(): Promise<{ mimeType: string | null; count: number; bytes: number }>;
chunk(index: number): Promise<string>;
};
}
interface Recording {
readonly encoder: Page;
readonly session: CDPSession;
readonly startedAt: string;
/** Frames still being handed to the encoder; stopping waits for them. */
readonly framesInFlight: Set<Promise<void>>;
}
interface ServerTab {
readonly threadId: ThreadId;
readonly tabId: string;
readonly page: Page;
readonly cdp: CDPSession;
readonly createdAt: number;
/** The agent's latest request on this tab; idle agent tabs close. */
usedAt: number;
readonly viewers: Set<ViewerState>;
readonly consoleEntries: Array<PreviewAutomationConsoleEntry>;
readonly networkEntries: Array<PreviewAutomationNetworkEntry>;
readonly actionTimeline: Array<PreviewAutomationActionEvent>;
readonly control: SessionControl;
/** The tab's own storage context, closed with it. Popups share their opener's. */
readonly isolatedContext: boolean;
/**
* Set when the desktop app renders this tab. The server drives the desktop's
* page; the desktop owns its size, storage, and window.
*/
readonly desktop: { readonly close: () => Promise<void> } | null;
readonly profileId: string | undefined;
/** Set when a page in another tab opened this one with `window.open` or a link. */
readonly openerTabId: string | undefined;
/** Finished downloads, newest last; files live until the tab closes. */
readonly downloads: Array<ServerDownload>;
/** A page's open file picker, waiting for the controlling viewer's files. */
fileChooser: {
readonly id: string;
readonly chooser: FileChooser;
readonly accept: string;
} | null;
dialog: Dialog | null;
setting: PreviewViewportSetting;
colorScheme: PreviewAppearancePreference;
zoomFactor: number;
loading: boolean;
closing: boolean;
recording: Recording | null;
initialNavigation: Promise<void> | null;
/** Counts main-frame navigation requests, so late events can tell they were superseded. */
navigationGeneration: number;
/**
* The latest main-frame navigation, when it aborted, to tell a navigation's
* download from a page's. The timer settles it if no download follows.
*/
abortedNavigation: {
readonly url: string;
readonly generation: number;
readonly timer: ReturnType<typeof setTimeout>;
} | null;
/** The latest queued start, so a stop can find a recording still starting. */
recordingStart: Promise<Recording> | null;
/** Serializes captures and recording start/stop. */
captureLock: Promise<void>;
/** Scaled captures rendering now; screencasts stay stopped meanwhile. */
capturing: number;
}
interface ServerDownload {
readonly id: string;
readonly fileName: string;
readonly path: string;
readonly sizeBytes: number;
readonly url: string;
readonly completedAt: string;
}
/** One agent session and the whole server; each tab holds a renderer process. */
/**
* Operations an agent may run on any tab in its thread, even while a human
* drives it. Evaluate is not one: page script can change anything, so it needs
* the same control as clicking.
*/
const READ_OPERATIONS: ReadonlySet<PreviewAutomationRequest["operation"]> = new Set([
"status",
"snapshot",
"waitFor",
]);
const AGENT_TAB_LIMIT = 8;
const SERVER_TAB_LIMIT = 32;
/** Agent tabs nobody watches close after this long without an agent request. */
const AGENT_TAB_IDLE_MS = 30 * 60 * 1000;
const IDLE_SWEEP_INTERVAL = "1 minute";
const DOWNLOAD_LIMIT = 20;
/** How long an aborted navigation waits for the download that usually explains it. */
const ABORTED_NAVIGATION_DOWNLOAD_WAIT_MS = 5_000;
const DOWNLOAD_MAX_BYTES = 1024 * 1024 * 1024;
const tabKey = (threadId: string, tabId: string) => `${threadId}\u0000${tabId}`;
const pushBounded = <A>(
buffer: Array<A>,
entry: A,
limit = ServerBrowserPage.DIAGNOSTIC_BUFFER_LIMIT,
) => {
buffer.push(entry);
if (buffer.length > limit) buffer.splice(0, buffer.length - limit);
};
const viewportSettingsEqual = (left: PreviewViewportSetting, right: PreviewViewportSetting) =>
left._tag === right._tag &&
(left._tag === "fill" ||
(right._tag !== "fill" && left.width === right.width && left.height === right.height));
const fixedViewportSize = (setting: PreviewViewportSetting) =>
setting._tag === "fill" ? null : { width: setting.width, height: setting.height };
const asRecord = (value: unknown): Record<string, unknown> | null =>
typeof value === "object" && value !== null ? (value as Record<string, unknown>) : null;
const num = (value: unknown, fallback = 0) =>
typeof value === "number" && Number.isFinite(value) ? value : fallback;
const modifiersOf = (message: Record<string, unknown>) => {
const value = num(message.modifiers);
return Number.isInteger(value) && value >= 0 && value < 16 ? value : 0;
};
// Cmd shortcuts from Apple viewers are no editing shortcut for Linux or headless
// Chromium, so they carry the command. Ctrl already works natively on Linux,
// except copy and cut, which headless Chromium only runs as commands.
const editingCommand = (key: string, modifiers: number) => {
const modifier = modifiers & 0b0111;
if (modifier !== 2 && modifier !== 4) return null;
const lower = key.toLowerCase();
const command =
lower === "c"
? "copy"
: lower === "x"
? "cut"
: modifier !== 4
? null
: lower === "a"
? "selectAll"
: lower === "z"
? modifiers & 8
? "redo"
: "undo"
: null;
return command ? { commands: [command] } : null;
};
const CLIPBOARD_TEXT_LIMIT = 1024 * 1024;
/** Copies reach the viewer only this soon after it last touched the page. */
const CLIPBOARD_GESTURE_MS = 5_000;
const CLIPBOARD_BINDING = "__t3PreviewClipboard";
// Headless Chromium shares one clipboard between every context, so pages
// report their own copies instead of the clipboard being read back.
const CLIPBOARD_SCRIPT = `(() => {
const send = (text) => {
if (typeof text !== "string" || text.length === 0) return;
try { globalThis.${CLIPBOARD_BINDING}?.(text.slice(0, ${CLIPBOARD_TEXT_LIMIT})); } catch {}
};
const selection = () => {
const field = document.activeElement;
if ((field instanceof HTMLInputElement || field instanceof HTMLTextAreaElement) && field.selectionStart !== null)
return field.value.slice(field.selectionStart, field.selectionEnd ?? field.selectionStart);
return String(document.getSelection() ?? "");
};
// Bubbling to window runs after page handlers, before cut removes the selection.
const copied = (event) =>
send(event.defaultPrevented ? event.clipboardData?.getData("text/plain") : selection());
addEventListener("copy", copied);
addEventListener("cut", copied);
const proto = globalThis.Clipboard?.prototype;
if (!proto) return;
const writeText = proto.writeText;
proto.writeText = function (text) {
const result = writeText.call(this, text);
result.then(() => send(String(text)), () => {});
return result;
};
const write = proto.write;
proto.write = function (items) {
const result = write.call(this, items);
result.then(async () => {
const item = [...items].find((candidate) => candidate.types.includes("text/plain"));
if (item) send(await (await item.getType("text/plain")).text());
}, () => {});
return result;
};
})();`;
const make = Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const host = { platform: yield* HostProcess.Platform, arch: yield* HostProcess.Architecture };
const manager = yield* PreviewManager.PreviewManager;
const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
const environment = yield* ServerEnvironment.ServerEnvironment;
const previewBrowser = yield* PreviewBrowser.PreviewBrowser;
const desktopChannel = yield* DesktopBrowserChannel.DesktopBrowserChannel;
const runFork = Effect.runForkWith(yield* Effect.context<never>());
const launchServices = yield* Effect.context<ChildProcessSpawner.ChildProcessSpawner>();
// The fix every host error names, rendered for how this server was launched.
const setupCommand = yield* resolveRootCliCommand(PreviewBrowserHost.SETUP_SUBCOMMAND);
const tabs = new Map<string, ServerTab>();
const pendingTabs = new Map<string, Promise<ServerTab>>();
/** Sessions closed while their tab was still opening; the open discards its page. */
const closedPendingTabs = new Set<string>();
/** Popup pages waiting for the tab their `opened` event creates. */
const adoptedPages = new Map<string, { readonly page: Page; readonly openerTabId: string }>();
/** Sessions the manager closed, so their tabs end for good. Pruned once dropped. */
const closedSessions = new Set<string>();
let hostConnectionId: string | null = null;
let viewerResizeOrder = 0;
const contexts = new ServerBrowserContexts({
profilesDir: NodePath.join(config.stateDir, "server-browser", "profiles"),
executable: () => Effect.runPromise(previewBrowser.executable),
// Playwright's launch error drops Chrome's own output; its sandbox note survives.
diagnose: (executable, cause) =>
Effect.runPromiseWith(launchServices)(
PreviewBrowserHost.diagnoseLaunchFailure({
executable,
setupCommand,
output: /sandboxing failed/i.test(String(cause))
? PreviewBrowserHost.NO_SANDBOX_SIGNATURE
: "",
}),
),
onContextClose: (context) => {
for (const tab of tabs.values()) {
if (tab.page.context() === context) dropTab(tab, true);
}
},
});
const dialogStatus = (tab: ServerTab) =>
tab.dialog
? {
type: tab.dialog.type(),
message: tab.dialog.message().slice(0, 4000),
defaultValue: tab.dialog.defaultValue().slice(0, 4000),
}
: null;
const broadcastControl = (tab: ServerTab) => {
for (const viewer of tab.viewers)
viewer.push({
_tag: "control",
canOperate: viewer.canOperate,
controller:
tab.control.controller === viewer.id
? "you"
: tab.control.controller !== null
? "another-viewer"
: tab.control.agentId !== null
? "agent"
: "unclaimed",
generation: tab.control.generation,
dialog: dialogStatus(tab),
});
};
const resolveDialog = async (tab: ServerTab, input: PreviewAutomationDialogInput) => {
const dialog = tab.dialog;
if (!dialog) throw new Error("No dialog is pending.");
if (input.accept) await dialog.accept(input.promptText);
else await dialog.dismiss();
if (tab.dialog === dialog) tab.dialog = null;
ServerBrowserPage.invalidateRefs(tab.page);
broadcastControl(tab);
};
const report = (tab: ServerTab, navStatus: PreviewNavStatus) => {
void tab.cdp
.send("Page.getNavigationHistory")
.catch(() => null)
.then((history) => {
const index = history?.currentIndex ?? 0;
const count = history?.entries.length ?? 0;
runFork(
manager
.reportStatus({
threadId: tab.threadId,
tabId: tab.tabId,
serverControlled: true,
navStatus,
canGoBack: index > 0,
canGoForward: index < count - 1,
})
.pipe(Effect.ignore),
);
});
};
const reportLoaded = async (tab: ServerTab) => {
const url = tab.page.url();
// Chromium's error page loads after `requestfailed` and must not clear LoadFailed.
if (url === "about:blank" || url.startsWith("chrome-error://")) return;
const title = (await tab.page.title().catch(() => "")).slice(0, 512);
// A navigation that started while reading the title owns the status now.
if (tab.loading || tab.page.url() !== url) return;
report(tab, { _tag: "Success", url: url.slice(0, 2048), title });
};
const reportLiveTabs = () => {
const connectionId = hostConnectionId;
if (connectionId === null) return;
runFork(
environment.getEnvironmentId.pipe(
Effect.flatMap((environmentId) =>
broker.focusHost({
clientId: SERVER_HOST_CLIENT_ID,
environmentId,
connectionId,
focused: true,
liveTabs: [...tabs.values()].map((tab) => ({
threadId: tab.threadId,
tabId: tab.tabId,
visible: tab.viewers.size > 0,
})),
}),
),
),
);
};
/** The CSS size the page lays out in: the viewport shrunk by the tab's zoom, as Chrome zooms. */
const layoutSize = (tab: ServerTab) => {
const size = tab.page.viewportSize();
if (!size || tab.desktop) return size;
return {
width: Math.max(1, Math.round(size.width / tab.zoomFactor)),
height: Math.max(1, Math.round(size.height / tab.zoomFactor)),
};
};
/**
* Zooms a headless page as Chrome's zoom does: it lays out in fewer CSS
* pixels and draws each one larger, so frames keep their size. The desktop
* zooms the pages it renders itself.
*/
const applyZoom = async (tab: ServerTab) => {
if (tab.desktop) return;
const size = tab.page.viewportSize();
if (!size) return;
if (tab.zoomFactor === 1) {
// Playwright's own override carries the plain viewport.
await tab.page.setViewportSize(size);
return;
}
const layout = layoutSize(tab)!;
await tab.cdp.send("Emulation.setDeviceMetricsOverride", {
width: layout.width,
height: layout.height,
deviceScaleFactor: RENDER_SCALE * tab.zoomFactor,
mobile: false,
});
};
const broadcastViewport = (tab: ServerTab) => {
const size = layoutSize(tab);
if (!size) return;
for (const viewer of tab.viewers) viewer.push({ _tag: "viewport", ...size });
};
const applySetting = async (tab: ServerTab, setting: PreviewViewportSetting) => {
tab.setting = setting;
// The desktop lays its webview out at the published setting itself.
if (tab.desktop) return;
const size =
fixedViewportSize(setting) ??
[...tab.viewers]
.map((viewer) => viewer.requestedSize)
.filter((requested) => requested !== null)
.sort((left, right) => right.order - left.order)[0] ??
UNATTACHED_FILL_VIEWPORT;
await tab.page.setViewportSize({ width: size.width, height: size.height });
await applyZoom(tab);
broadcastViewport(tab);
};
/** Applies a tab's published appearance and, for headless tabs, zoom. */
const applyRendering = async (tab: ServerTab, snapshot: PreviewSessionSnapshot) => {
const colorScheme = snapshot.colorScheme ?? "system";
if (colorScheme !== tab.colorScheme) {
tab.colorScheme = colorScheme;
await tab.page.emulateMedia({ colorScheme: colorScheme === "system" ? null : colorScheme });
}
const zoomFactor = snapshot.zoomFactor ?? 1;
if (zoomFactor !== tab.zoomFactor && !tab.desktop) {
tab.zoomFactor = zoomFactor;
await applyZoom(tab);
broadcastViewport(tab);
}
};
/** Whether the preview session for a tab still exists. */
const sessionOpen = (tab: ServerTab) => !closedSessions.has(tabKey(tab.threadId, tab.tabId));
const dropTab = (tab: ServerTab, closeSession: boolean) => {
const key = tabKey(tab.threadId, tab.tabId);
if (tabs.get(key) !== tab) return;
tabs.delete(key);
tab.closing = true;
clearAbortedNavigation(tab);
// A desktop page outlives the connection unless its session closed with it.
const end = tab.desktop && !closeSession && sessionOpen(tab) ? "reconnect" : "gone";
for (const viewer of tab.viewers) viewer.push({ _tag: end });
void tab.control.close().catch(constVoid);
// The desktop owns its page; letting go only ends this connection.
if (tab.desktop) void tab.desktop.close().catch(constVoid);
else void tab.page.close().catch(constVoid);
if (tab.isolatedContext) void tab.page.context().close().catch(constVoid);
void tab.recording?.encoder.close().catch(constVoid);
void NodeFSP.rm(downloadDir(tab), { recursive: true, force: true }).catch(constVoid);
reportLiveTabs();
if (closeSession) {
runFork(manager.close({ threadId: tab.threadId, tabId: tab.tabId }).pipe(Effect.ignore));
}
};
/**
* With a desktop app attached, every tab of this server renders there, so a
* new tab waits for its `<webview>` instead of launching headless.
*/
const desktopRenders = (snapshot: PreviewSessionSnapshot) =>
desktopChannel.available
? Effect.runPromise(
desktopChannel.awaitAttached(
{ threadId: snapshot.threadId, tabId: snapshot.tabId },
DESKTOP_ATTACH_TIMEOUT,
),
)
: Promise.resolve(false);
/** Connects to the desktop's page for a tab, which it renders and the server drives. */
const connectDesktop = async (snapshot: PreviewSessionSnapshot) => {
const scope = await Effect.runPromise(Scope.make());
try {
const endpoint = await Effect.runPromise(
desktopChannel
.endpoint({ threadId: snapshot.threadId, tabId: snapshot.tabId })
.pipe(Scope.provide(scope)),
);
const connected = await contexts.connectDesktopPage(endpoint);
return {
page: connected.page,
close: async () => {
await connected.browser.close().catch(constVoid);
await Effect.runPromise(Scope.close(scope, Exit.void));
},
};
} catch (cause) {
await Effect.runPromise(Scope.close(scope, Exit.void));
throw cause;
}
};
const createTab = async (snapshot: PreviewSessionSnapshot): Promise<ServerTab> => {
const adopted = adoptedPages.get(tabKey(snapshot.threadId, snapshot.tabId));
adoptedPages.delete(tabKey(snapshot.threadId, snapshot.tabId));
const desktop =
adopted === undefined && (await desktopRenders(snapshot))
? await connectDesktop(snapshot)
: null;
// An agent tab without a profile (no client reported one) keeps throwaway storage.
const isolatedContext =
adopted === undefined &&
desktop === null &&
((snapshot.automationOwner !== undefined && snapshot.profileId === undefined) ||
snapshot.profileId === INCOGNITO_BROWSER_PROFILE_ID);
const context =
adopted?.page.context() ??
desktop?.page.context() ??
(await contexts.contextFor(
snapshot.profileId ?? "default",
isolatedContext ? tabKey(snapshot.threadId, snapshot.tabId) : undefined,
));
if (adopted?.page.isClosed()) throw new Error("The popup closed before it opened.");
// The desktop page already has its own clipboard; the bridge script is for headless tabs.
if (!desktop) await prepareContext(context);
const page = adopted?.page ?? desktop?.page ?? (await context.newPage());
const cdp = await context.newCDPSession(page);
// The desktop's page is already a normal browser. A popup's first request
// went out before it became a tab; everything after presents as Chrome.
if (!desktop) await presentAsChrome(cdp, host);
page.setDefaultTimeout(NAVIGATION_TIMEOUT_MS);
page.setDefaultNavigationTimeout(NAVIGATION_TIMEOUT_MS);
const control = new SessionControl(snapshot.automationOwner ?? null, () =>
ServerBrowserPage.invalidateRefs(page),
);
const tab: ServerTab = {
threadId: ThreadId.make(snapshot.threadId),
tabId: snapshot.tabId,
page,
cdp,
createdAt: Date.now(),
usedAt: Date.now(),
viewers: new Set(),
consoleEntries: [],
networkEntries: [],
actionTimeline: [],
control,
isolatedContext,
desktop: desktop === null ? null : { close: desktop.close },
profileId: snapshot.profileId,
openerTabId: adopted?.openerTabId,
downloads: [],
fileChooser: null,
dialog: null,
setting: snapshot.viewport ?? FILL_PREVIEW_VIEWPORT,
colorScheme: "system",
zoomFactor: 1,
loading: false,
closing: false,
recording: null,
recordingStart: null,
initialNavigation: null,
navigationGeneration: 0,
abortedNavigation: null,
captureLock: Promise.resolve(),
capturing: 0,
};
if (!desktop) {
await page.setViewportSize(fixedViewportSize(tab.setting) ?? UNATTACHED_FILL_VIEWPORT);
}
await applyRendering(tab, snapshot);
const isMainNavigation = (request: { isNavigationRequest(): boolean; frame(): unknown }) =>
request.isNavigationRequest() && request.frame() === page.mainFrame();
const navigationGenerations = new WeakMap<object, number>();
page.on("request", (request) => {
if (!isMainNavigation(request)) return;
navigationGenerations.set(request, ++tab.navigationGeneration);
clearAbortedNavigation(tab);
tab.loading = true;
report(tab, { _tag: "Loading", url: request.url().slice(0, 2048), title: "" });
});
page.on("load", () => {
tab.loading = false;
void reportLoaded(tab);
});
page.on("framenavigated", (frame) => {
// Same-document navigations (SPA routes) fire no load event.
if (frame === page.mainFrame() && !tab.loading) void reportLoaded(tab);
});
page.on("requestfailed", (request) => {
const errorText = request.failure()?.errorText ?? "";
pushBounded(tab.networkEntries, {
url: request.url(),
method: request.method(),
status: null,
failed: true,
errorText,
timestamp: new Date().toISOString(),
});
if (!isMainNavigation(request)) return;
// A navigation a newer one replaced leaves the status to the newer one. A
// popup's first request can predate the listener, so it is untracked and
// superseded by any tracked one.
const generation = navigationGenerations.get(request) ?? 0;
if (generation !== tab.navigationGeneration) return;
// An aborted navigation is usually a download; its `download` event settles the status.
if (errorText.includes("ERR_ABORTED")) {
const url = request.url();
const navigationGeneration = tab.navigationGeneration;
clearAbortedNavigation(tab);
tab.abortedNavigation = {
url,
generation: navigationGeneration,
timer: setTimeout(() => {
if (tab.abortedNavigation?.generation !== navigationGeneration) return;
tab.abortedNavigation = null;
if (!tab.closing) settleAbortedNavigation(tab, navigationGeneration, url, undefined);
}, ABORTED_NAVIGATION_DOWNLOAD_WAIT_MS),
};
return;
}
tab.loading = false;
const { code, description } = ServerBrowserPage.parseNetError(errorText);
report(tab, {
_tag: "LoadFailed",
url: request.url().slice(0, 2048),
title: "",
code,
description,
});
});
page.on("response", (response) => {
pushBounded(tab.networkEntries, {
url: response.url(),
method: response.request().method(),
status: response.status(),
failed: false,
timestamp: new Date().toISOString(),
});
});
page.on("console", (message) => {
pushBounded(tab.consoleEntries, {
level: message.type(),
text: message.text().slice(0, 2_000),
timestamp: new Date().toISOString(),
});
});
page.on("dialog", (dialog) => {
tab.dialog = dialog;
broadcastControl(tab);
});
page.on("download", (download) => void saveDownload(tab, download));
page.on("filechooser", (chooser) => void offerFileChooser(tab, chooser));
// Popups become tabs and keep `window.opener`, so sign-in popups can report back.
page.on("popup", (popup) => void adoptPopup(tab, popup));
// Playwright cannot reload a crashed page, so it must leave the tab list.
const key = tabKey(tab.threadId, tab.tabId);
if (closedPendingTabs.delete(key)) {
await control.close().catch(constVoid);
if (desktop) await desktop.close().catch(constVoid);
else await page.close().catch(constVoid);
if (isolatedContext) await context.close().catch(constVoid);
throw new ServerBrowserTabNotFoundError({ threadId: tab.threadId, tabId: tab.tabId });
}
page.on("close", () => dropTab(tab, true));
page.on("crash", () => dropTab(tab, true));
tabs.set(key, tab);
reportLiveTabs();
// A popup is already loading its own URL, and the desktop loads its tab's.
if (!adopted && !desktop && snapshot.navStatus._tag === "Loading") {
tab.initialNavigation = page
.goto(snapshot.navStatus.url, { waitUntil: "commit", timeout: NAVIGATION_TIMEOUT_MS })
.then(constVoid);
// Background creation keeps the failed tab; automation awaits the original error.
void tab.initialNavigation.catch(constVoid);
}
return tab;
};
const downloadsRoot = NodePath.join(config.stateDir, "server-browser", "downloads");
// Tab ids are opaque server strings; hashing keeps them out of the path.
const downloadDir = (tab: ServerTab) =>
NodePath.join(
downloadsRoot,
NodeCrypto.createHash("sha256").update(tabKey(tab.threadId, tab.tabId)).digest("hex"),
);
const clearAbortedNavigation = (tab: ServerTab) => {
if (tab.abortedNavigation !== null) clearTimeout(tab.abortedNavigation.timer);
tab.abortedNavigation = null;
};
/**
* Settles the status of a navigation that aborted, usually into a download.
* A tab opened straight to the file has no page to show, so it reports the
* file with its download; a page that linked to it keeps showing itself.
*/
const settleAbortedNavigation = (
tab: ServerTab,
generation: number,
url: string,
offered: { readonly id: string; readonly fileName: string } | undefined,
) => {
// A newer navigation owns the status.
if (tab.navigationGeneration !== generation) return;
tab.loading = false;
if (tab.page.url() !== "about:blank") {
void reportLoaded(tab);
return;
}
report(tab, {
_tag: "LoadFailed",
url: url.slice(0, 2048),
title: "",
code: -3,
description: "ERR_ABORTED",
...(offered === undefined ? {} : { download: offered }),
});
};
const saveDownload = async (tab: ServerTab, download: Download) => {
const id = NodeCrypto.randomUUID();
const path = NodePath.join(downloadDir(tab), id);
const navigation =
download.url() === tab.abortedNavigation?.url ? tab.abortedNavigation.generation : null;
if (navigation !== null) clearAbortedNavigation(tab);
let offered: { readonly id: string; readonly fileName: string } | undefined;
try {
if (await download.failure()) return;
await NodeFSP.mkdir(downloadDir(tab), { recursive: true });
await download.saveAs(path);
const { size } = await NodeFSP.stat(path);
if (tab.closing || size > DOWNLOAD_MAX_BYTES) {
await NodeFSP.rm(path, { force: true });
return;
}
const saved: ServerDownload = {
id,
fileName: download.suggestedFilename().slice(0, 255) || "download",
path,
sizeBytes: size,
url: download.url().slice(0, 2048),
completedAt: new Date().toISOString(),
};
tab.downloads.push(saved);
for (const evicted of tab.downloads.splice(0, tab.downloads.length - DOWNLOAD_LIMIT)) {
await NodeFSP.rm(evicted.path, { force: true }).catch(constVoid);
}
offered = { id, fileName: saved.fileName };
// A tab whose own address was the file shows it in place (see
// settleAbortedNavigation), unless it navigated on while the file saved.
const shownInTab =
navigation === tab.navigationGeneration && tab.page.url() === "about:blank";
if (shownInTab) return;
// Only the person driving the page gets the file offered; agents read it from status.
const controller = [...tab.viewers].find((viewer) => viewer.id === tab.control.controller);
controller?.push({
_tag: "download",
id,
fileName: saved.fileName,
sizeBytes: saved.sizeBytes,
});