feat(preview): run the browser on the environment server #15328
Mergedmaria-rcksmerged 68 commits into
main fromrefs/pull/15328/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
juliusmarminge added labelsmacroscope-review
- apps/mobile/src/features/browser/BrowserPreviewRouteScreen.tsx line 177Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +155,21 @@155+ },156+ ]157+ : []158+ }159+ />160+ {Platform.OS === "ios" ? (161+ <NativeHeaderToolbar placement="left">162+ <NativeHeaderToolbar.Button163+ icon="xmark"164+ accessibilityLabel="Close browser"165+ onPress={onClose}166+ separateBackground167+ />168+ </NativeHeaderToolbar>169+ ) : null}170+ {tab ? (171+ <>172+ <BrowserAddressBar173+ key={tab.tabId}174+ tab={tab}175+ onCommand={(input) => streamRef.current?.command(input)}apps/web/src/components/preview/localServerTabs.ts line 36OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +16,21 @@16+ open: () => Promise<R>,17+): Promise<R> {18+ const threadKey = scopedThreadKey(threadRef);19+ pendingOpens.set(threadKey, (pendingOpens.get(threadKey) ?? 0) + 1);20+ try {21+ const result = await open();22+ if (result._tag === "Success" && "value" in result) {23+ const snapshot = result.value as PreviewSessionSnapshot;24+ openedTabs.add(tabKey(threadKey, snapshot.tabId));25+ }26+ return result;27+ } finally {28+ const remaining = (pendingOpens.get(threadKey) ?? 1) - 1;29+ if (remaining > 0) pendingOpens.set(threadKey, remaining);30+ else pendingOpens.delete(threadKey);31+ }32+}33+34+export function isLocalServerTab(threadRef: ScopedThreadRef, tabId: string): boolean {35+ const threadKey = scopedThreadKey(threadRef);36+ return openedTabs.has(tabKey(threadKey, tabId)) || pendingOpens.has(threadKey);apps/server/src/mcp/PreviewAutomationBroker.ts lines 531 to 533OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -517,3 +530,4 @@517530 (left, right) =>518531 Number(ownsTargetTab(right, true)) - Number(ownsTargetTab(left, true)) ||519532 Number(ownsTargetTab(right)) - Number(ownsTargetTab(left)) ||533+ Number(right.preferred) - Number(left.preferred) ||apps/web/src/browser/ServerBrowserSurface.tsx line 483OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +463,21 @@463+ send({ type: "mouse", action: "up", ...at, button: "left", buttons: 0, clickCount });464+ return;465+ }466+ if (!mousePressedRef.current) return;467+ mousePressedRef.current = false;468+ const point = pagePoint(event.clientX, event.clientY, true);469+ if (!point) return;470+ flushInput();471+ send({472+ type: "mouse",473+ action: "up",474+ x: point.x,475+ y: point.y,476+ button: buttonOf(event.button),477+ buttons: event.buttons,478+ clickCount: lastClickRef.current?.count ?? 1,479+ modifiers: previewStreamModifiers(event),480+ });481+ };482+483+ const handlePointerCancel = (event: PointerEvent<HTMLCanvasElement>) => {apps/server/src/preview/ServerBrowserToolchain.ts line 512OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +492,21 @@492+ args: [],493+ source: "bundled",494+ };495+ const bundled = (pack: PinnedAsset) =>496+ Effect.all(497+ [498+ browserInstallLock499+ .withPermit(installOnce(BROWSER_TOOL, SERVER_BROWSER_VERSION, populateBrowser(pack)))500+ .pipe(501+ Effect.timeoutOrElse({502+ duration: BROWSER_INSTALL_TIMEOUT,503+ orElse: () =>504+ Effect.fail(505+ new ServerBrowserInstallError({506+ tool: BROWSER_TOOL,507+ step: "installing (timed out)",508+ }),509+ ),510+ }),511+ ),512+ ensureFonts,apps/server/src/preview/ServerBrowser.ts line 657OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +637,21 @@637+ } finally {638+ await Promise.all([639+ ...viewers.map((viewer) => viewer.resume()),640+ recording && tab.recording === recording641+ ? recording.session642+ .send("Page.startScreencast", RECORDING_SCREENCAST)643+ .catch(() => undefined)644+ : undefined,645+ ]);646+ }647+ };648+649+ const stopRecording = async (tab: ServerTab) => {650+ const recording = tab.recording;651+ if (!recording) {652+ throw new ServerBrowserPage.ServerBrowserOperationError(653+ "PreviewAutomationRecordingNotActiveError",654+ "No recording is active for this tab.",655+ );656+ }657+ tab.recording = null;apps/server/src/preview/ServerBrowser.ts lines 1044 to 1044OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1024,21 @@1024+ return;1025+ case "reload":1026+ void tab.page.reload().catch(() => undefined);1027+ return;1028+ case "probe": {1029+ const x = num(message.x);1030+ const y = num(message.y);1031+ const result = await session.send("Runtime.evaluate", {1032+ expression: `(${EDITABLE_AT_POINT_SCRIPT})(${x}, ${y})`,1033+ returnByValue: true,1034+ });1035+ viewer.push({ _tag: "probe", x, y, editable: result.result.value === true });1036+ return;1037+ }1038+ }1039+ };1040+1041+ const attachViewer: ServerBrowser["Service"]["attachViewer"] = (input) =>1042+ Effect.gen(function* () {1043+ const tab = yield* findTab(input.threadId, input.tabId);1044+ const output = yield* Queue.unbounded<ServerBrowserViewerOutput>();apps/server/src/preview/ServerBrowserPage.ts lines 217 to 223OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +203,21 @@203+ const locator = targetLocator(page, input);204+ if (locator === null) {205+ await page.mouse.click(input.x!, input.y!);206+ return { x: input.x!, y: input.y! };207+ }208+ await locator.scrollIntoViewIfNeeded({ timeout });209+ const box = await locator.boundingBox({ timeout });210+ await locator.click({ timeout });211+ return box ? { x: box.x + box.width / 2, y: box.y + box.height / 2 } : { x: 0, y: 0 };212+};213+214+export const type = async (page: Page, input: PreviewAutomationTypeInput) => {215+ const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;216+ const locator = targetLocator(page, input);217+ if (locator !== null) {218+ if (input.clear) {219+ await locator.fill(input.text, { timeout });220+ return;221+ }222+ await locator.focus({ timeout });223+ } else if (input.clear) {apps/mobile/src/features/browser/preview-stream.browser.ts line 295OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +275,21 @@275+ };276+ wheelFrame ??= requestAnimationFrame(flushWheel);277+ };278+279+ const onPointerDown = (event: PointerEvent) => {280+ if (!event.isPrimary) return;281+ event.preventDefault();282+ touch = {283+ pointerId: event.pointerId,284+ startX: event.clientX,285+ startY: event.clientY,286+ lastX: event.clientX,287+ lastY: event.clientY,288+ panning: false,289+ };290+ const point = pagePoint(event.clientX, event.clientY, false);291+ probe = point ? { x: point.x, y: point.y, editable: null, tapped: false } : null;292+ if (point) send({ type: "probe", x: point.x, y: point.y });293+ };294+ const onPointerMove = (event: PointerEvent) => {295+ if (!touch || touch.pointerId !== event.pointerId) return;apps/server/src/preview/ServerBrowser.ts line 669OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +649,21 @@649+ const stopRecording = async (tab: ServerTab) => {650+ const recording = tab.recording;651+ if (!recording) {652+ throw new ServerBrowserPage.ServerBrowserOperationError(653+ "PreviewAutomationRecordingNotActiveError",654+ "No recording is active for this tab.",655+ );656+ }657+ tab.recording = null;658+ await recording.session.send("Page.stopScreencast").catch(() => undefined);659+ await recording.session.detach().catch(() => undefined);660+ type EncoderWindow = {661+ __t3Recorder: {662+ stop(): Promise<{ mimeType: string | null; count: number }>;663+ chunk(index: number): Promise<string>;664+ };665+ };666+ const { mimeType, count } = await recording.encoder.evaluate(() =>667+ (globalThis as unknown as EncoderWindow).__t3Recorder.stop(),668+ );669+ const chunks: Array<Buffer> = [];apps/server/src/preview/ServerBrowser.ts line 631OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +611,21 @@611+ .catch(() => undefined)612+ .finally(() => {613+ void session614+ .send("Page.screencastFrameAck", { sessionId: frame.sessionId })615+ .catch(() => undefined);616+ });617+ });618+ await session.send("Page.startScreencast", RECORDING_SCREENCAST);619+ const recording: Recording = { encoder, session, startedAt: new Date().toISOString() };620+ tab.recording = recording;621+ return recording;622+ };623+624+ /**625+ * Runs a scaled capture with the tab's screencasts stopped, so viewers and626+ * recordings never receive the frame it renders at the capture scale.627+ */628+ const withScreencastsPaused = async <A>(tab: ServerTab, capture: () => Promise<A>) => {629+ const viewers = [...tab.viewers];630+ const recording = tab.recording;631+ await Promise.all([apps/server/src/preview/ServerBrowserToolchain.ts line 262OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +242,21 @@242+ "chromium-browser",243+ "microsoft-edge-stable",244+ "microsoft-edge",245+ ];246+};247+248+/** `chromium_headless_shell-<revision>/<these>`, from playwright-core's registry. */249+const PLAYWRIGHT_HEADLESS_SHELL: Partial<Record<string, ReadonlyArray<string>>> = {250+ "linux-x64": ["chrome-headless-shell-linux64", "chrome-headless-shell"],251+ "linux-arm64": ["chrome-linux", "headless_shell"],252+ "darwin-x64": ["chrome-headless-shell-mac-x64", "chrome-headless-shell"],253+ "darwin-arm64": ["chrome-headless-shell-mac-arm64", "chrome-headless-shell"],254+ "win32-x64": ["chrome-headless-shell-win64", "chrome-headless-shell.exe"],255+};256+257+const playwrightCacheDir = (258+ platform: NodeJS.Platform,259+ env: NodeJS.ProcessEnv,260+ path: Path.Path,261+): string | undefined => {262+ if (env.PLAYWRIGHT_BROWSERS_PATH && env.PLAYWRIGHT_BROWSERS_PATH !== "0") {apps/server/src/preview/ServerBrowserPage.ts line 274OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +254,21 @@254+ result.exceptionDetails.exception?.description ?? result.exceptionDetails.text,255+ );256+ }257+ const value =258+ "value" in result.result ? result.result.value : (result.result.description ?? null);259+ const actualBytes = Buffer.byteLength(JSON.stringify(value ?? null), "utf8");260+ if (actualBytes > MAX_EVALUATION_BYTES) {261+ throw new ServerBrowserOperationError(262+ "PreviewAutomationResultTooLargeError",263+ `Evaluation result is ${actualBytes} bytes; the limit is ${MAX_EVALUATION_BYTES}.`,264+ { maximumBytes: MAX_EVALUATION_BYTES },265+ );266+ }267+ return value;268+};269+270+export const waitFor = async (page: Page, input: PreviewAutomationWaitForInput) => {271+ const deadline = Date.now() + (input.timeoutMs ?? DEFAULT_TIMEOUT_MS);272+ const remaining = () => Math.max(1, deadline - Date.now());273+ const locator = targetLocator(page, input);274+ if (locator !== null) await locator.waitFor({ state: "visible", timeout: remaining() });
- apps/mobile/src/features/browser/PreviewStreamWebView.tsx lines 194 to 207Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +74,21 @@74+ ref={ref}75+ configuration={configuration}76+ background={props.background}77+ compact={props.compact ?? false}78+ onGone={props.onGone}79+ onViewport={props.onViewport}80+ onPictureInPicture={props.onPictureInPicture}81+ onUnauthorized={() => {82+ // The client has stopped. Restart it, and back off when fresh tickets keep83+ // getting refused, e.g. a session without operate scope.84+ const retry = unauthorized.current++;85+ if (refreshTimer.current !== null) clearTimeout(refreshTimer.current);86+ refreshTimer.current = setTimeout(87+ () => {88+ refreshTimer.current = null;89+ setAttempt((current) => current + 1);90+ props.onUnauthorized();91+ },92+ retry === 0 ? 0 : Math.min(1_000 * 2 ** retry, UNAUTHORIZED_RETRY_MAX_MS),93+ );94+ }}apps/server/src/preview/ServerBrowser.ts lines 1962 to 1993Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +1052,21 @@1052+ session1053+ .send("Page.stopScreencast")1054+ .catch(() => undefined)1055+ .then(() => session.detach())1056+ .catch(() => undefined),1057+ ),1058+ );1059+ const viewer: ViewerState = {1060+ push: (next) => void Queue.offerUnsafe(output, next),1061+ pause: () => {1062+ screencastParams = screencastParams.then(() =>1063+ session.send("Page.stopScreencast").then(1064+ () => undefined,1065+ () => undefined,1066+ ),1067+ );1068+ return screencastParams;1069+ },1070+ resume: () => startScreencast(motion ? 0.5 : 1),1071+ scrolledAt: 0,1072+ };apps/server/src/preview/ServerBrowser.ts lines 1186 to 1211OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +1191,21 @@1191+ supportedOperations: [...PREVIEW_AUTOMATION_OPERATIONS],1192+ },1193+ { preferred: true },1194+ )1195+ .pipe(1196+ Effect.flatMap((events) =>1197+ events.pipe(1198+ Stream.runForEach((event) => {1199+ if (event.type === "connected") {1200+ hostConnectionId = event.connectionId;1201+ return Effect.sync(reportLiveTabs);1202+ }1203+ return handleRequest(event.connectionId, event.request).pipe(1204+ Effect.forkScoped,1205+ Effect.asVoid,1206+ );1207+ }),1208+ ),1209+ ),1210+ Effect.forkScoped,1211+ );apps/web/src/browser/serverPictureInPicture.ts line 136OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +116,21 @@116+ let stopped = false;117+ const connect = async (refresh: boolean) => {118+ const access = await readPreviewStreamAccess(input.environmentId, refresh);119+ if (stopped) return;120+ if (!access) {121+ closeServerPictureInPicture();122+ return;123+ }124+ client = createPreviewStreamClient(125+ {126+ access,127+ threadId: input.threadId,128+ tabId: input.tabId,129+ maxWidth: STREAM_CAP_PX,130+ maxHeight: STREAM_CAP_PX,131+ },132+ {133+ onFrame: painter.paint,134+ onViewport: () => undefined,135+ onConnectedChange: () => undefined,136+ onUnauthorized: () => void connect(true),apps/web/src/components/ChatView.tsx lines 5131 to 5139OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -5116,3 +5124,16 @@51165124 deviceState.sessions,51175125 deviceState.devices,51185126 ]);5127+ // A server tab the agent opens floats over chat, as a desktop automation5128+ // host does for its own tabs. The first snapshot is a baseline so reloads do5129+ // not resurrect tabs; tabs this client opened or already shows stay put.5130+ const previousServerPreviewTabs = useRef(new Map<string, Set<string>>());5131+ useEffect(() => {5132+ if (!activeThreadRef || !activeEnvironmentServerBrowser) return;5133+ const threadKey = scopedThreadKey(activeThreadRef);5134+ const serverTabIds = Object.values(activePreviewState.sessions)5135+ .filter((session) => session.runtime === "server")5136+ .map((session) => session.tabId);5137+ const previous = previousServerPreviewTabs.current.get(threadKey);5138+ previousServerPreviewTabs.current.set(threadKey, new Set(serverTabIds));5139+ if (!previous || !autoShowFloatingPreview) return;
- apps/server/src/preview/ServerBrowser.ts line 1340OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1320,21 @@1320+ )1321+ .pipe(1322+ Effect.flatMap((events) =>1323+ events.pipe(1324+ Stream.runForEach((event) => {1325+ if (event.type === "connected") {1326+ hostConnectionId = event.connectionId;1327+ return Effect.sync(reportLiveTabs);1328+ }1329+ return handleRequest(event.connectionId, event.request).pipe(1330+ Effect.forkScoped,1331+ Effect.asVoid,1332+ );1333+ }),1334+ ),1335+ ),1336+ );1337+ // The broker ends a host's stream when a request outlives its deadline,1338+ // e.g. the first open while Chromium installs. Register again, or agents1339+ // lose the browser until the server restarts.1340+ yield* hostSession.pipe(apps/web/src/browser/ServerBrowserSurface.tsx line 715Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +572,21 @@572+ code: event.code,573+ keyCode: event.keyCode,574+ ...(action === "down" && text !== undefined ? { text } : {}),575+ modifiers: previewStreamModifiers(event),576+ });577+ // Shortcuts stay with the app (copy, paste, keybindings); other keys belong to the page.578+ if (shortcut) return;579+ event.preventDefault();580+ event.stopPropagation();581+ };582+583+ const handleInput = (event: FormEvent<HTMLTextAreaElement>) => {584+ const native = event.nativeEvent;585+ if (native instanceof InputEvent && native.isComposing) return;586+ const textarea = event.currentTarget;587+ const inputType = native instanceof InputEvent ? native.inputType : "";588+ if (inputType === "deleteContentBackward") sendKeyPress(BACKSPACE);589+ else if (inputType === "deleteContentForward") sendKeyPress(DELETE);590+ else {591+ const text = textarea.value.replaceAll(INPUT_SENTINEL, "");592+ if (text) send({ type: "text", text });apps/web/src/previewStateStore.ts lines 318 to 318OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -311,4 +314,5 @@311314 ): void {312315 updateThreadPreviewState(ref, (current) => {313316 const sameServer = current.serverEpoch === result.serverEpoch;314- if (sameServer && result.revision < current.serverRevision) return current;317+ if (sameServer && result.revision < current.serverRevision) {318+ return current.listLoaded ? current : { ...current, listLoaded: true };packages/client-runtime/src/preview/serverBrowserStream.ts lines 195 to 195OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +175,21 @@175+ typeof y === "number" &&176+ typeof editable === "boolean"177+ ) {178+ events.onProbe?.({ x, y, editable });179+ }180+ });181+ ws.addEventListener("close", (event) => {182+ if (socket !== ws) return;183+ socket = null;184+ if (opened) events.onConnectedChange(false);185+ if (stopped) return;186+ if (event.code === PREVIEW_STREAM_TAB_GONE_CODE) {187+ stopped = true;188+ events.onGone?.();189+ return;190+ }191+ // A rejected upgrade surfaces as 1006 before open, including an expired ticket.192+ if (193+ event.code === 1008 ||194+ event.code === 4401 ||195+ (!opened && event.code === 1006 && target.access.query.wsTicket !== undefined)apps/server/src/preview/ServerBrowser.ts line 1734Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1015,21 @@1015+ ok: false as const,1016+ error: {1017+ _tag: error.tag,1018+ message: error.message,1019+ ...(error.detail === undefined ? {} : { detail: error.detail }),1020+ },1021+ }),1022+ }),1023+ Effect.flatMap((outcome) =>1024+ broker.respond({1025+ clientId: SERVER_HOST_CLIENT_ID,1026+ connectionId,1027+ requestId: request.requestId,1028+ ...outcome,1029+ }),1030+ ),1031+ Effect.ignore,1032+ );1033+1034+ const mirrorManagerEvent = (event: PreviewEvent) =>1035+ Effect.promise(async () => {apps/server/src/preview/ServerBrowserToolchain.ts line 342OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +322,21 @@322+323+ yield* Effect.gen(function* () {324+ yield* populate(stagingDir);325+ yield* fs326+ .writeFileString(path.join(stagingDir, SENTINEL), `${version}\n`)327+ .pipe(Effect.mapError(fail("recording the completed install")));328+ yield* fs.rename(stagingDir, installDir).pipe(329+ Effect.catch((cause) =>330+ // A concurrent server may have published the same version first.331+ isInstalled(installDir, version).pipe(332+ Effect.flatMap((published) =>333+ published ? Effect.void : Effect.fail(fail("publishing the install")(cause)),334+ ),335+ ),336+ ),337+ );338+ // Only runs right after an upgrade; dot entries are other installs' staging dirs.339+ const names = yield* fs.readDirectory(parentDir).pipe(Effect.orElseSucceed(() => []));340+ yield* Effect.forEach(341+ names.filter((name) => !name.startsWith(".") && name !== version),342+ (name) => fs.remove(path.join(parentDir, name), { recursive: true, force: true }),apps/server/src/preview/ServerBrowser.ts line 385OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +365,21 @@365+ }),366+ ),367+ ),368+ );369+ };370+371+ const broadcastViewport = (tab: ServerTab) => {372+ const size = tab.page.viewportSize();373+ if (!size) return;374+ for (const viewer of tab.viewers) viewer.push({ _tag: "viewport", ...size });375+ };376+377+ const applySetting = async (tab: ServerTab, setting: PreviewViewportSetting) => {378+ tab.setting = setting;379+ const size =380+ fixedViewportSize(setting) ??381+ [...tab.viewers]382+ .map((viewer) => viewer.requestedSize)383+ .filter((requested) => requested !== null)384+ .sort((left, right) => right.order - left.order)[0];385+ if (size) await tab.page.setViewportSize({ width: size.width, height: size.height });apps/server/src/preview/ServerBrowserToolchain.ts line 313OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +293,21 @@293+ platform === "linux" && hostUsesGlibc() ? BROWSER_PACKS[architecture] : undefined;294+295+ const isInstalled = (installDir: string, version: string) =>296+ fs.readFileString(path.join(installDir, SENTINEL)).pipe(297+ Effect.map((sentinel) => sentinel.trim() === version),298+ Effect.orElseSucceed(() => false),299+ );300+301+ /** Stages, publishes, and prunes `<baseDir>/tools/<tool>/<version>` unless it is already complete. */302+ const installOnce = Effect.fn("ServerBrowserToolchain.installOnce")(function* (303+ tool: string,304+ version: string,305+ populate: (stagingDir: string) => Effect.Effect<void, ServerBrowserInstallError>,306+ ) {307+ const fail = (step: string) => (cause: unknown) =>308+ new ServerBrowserInstallError({ tool, step, cause });309+ const parentDir = path.join(toolsDir, tool);310+ const installDir = path.join(parentDir, version);311+ if (yield* isInstalled(installDir, version)) return;312+313+ yield* fsapps/mobile/src/features/browser/PreviewStreamWebView.tsx line 94OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +74,21 @@74+ } satisfies PreviewStreamConfiguration);75+ return (76+ <PreviewStreamDocumentView77+ key={`${attempt}:${configuration}`}78+ ref={ref}79+ configuration={configuration}80+ background={props.background}81+ compact={props.compact ?? false}82+ onGone={props.onGone}83+ onViewport={props.onViewport}84+ onPictureInPicture={props.onPictureInPicture}85+ onStreamingChange={props.onStreamingChange}86+ onUnauthorized={() => {87+ // The client has stopped. Restart it with a fresh ticket, backing off between refusals.88+ const refusals = ++unauthorized.current;89+ if (refusals >= MAX_REFUSALS) return false;90+ if (refreshTimer.current !== null) clearTimeout(refreshTimer.current);91+ refreshTimer.current = setTimeout(92+ () => {93+ refreshTimer.current = null;94+ setAttempt((current) => current + 1);
- apps/mobile/src/features/browser/preview-stream.browser.ts line 1Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +1 @@1+import {apps/server/src/preview/ServerBrowser.ts lines 888 to 894OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +874,21 @@874+ };875+ if (existing) {876+ if (url) await navigate(existing, url, "load", request.timeoutMs);877+ await revealTab(existing);878+ return statusWithTitle(existing);879+ }880+ const snapshot = await Effect.runPromise(881+ manager.open({882+ threadId: request.threadId,883+ ...(url ? { url } : {}),884+ runtime: "server",885+ reveal: false,886+ }),887+ );888+ const tab = await ensureTab(snapshot);889+ await revealTab(tab);890+ if (url) {891+ await tab.page892+ .waitForLoadState("load", { timeout: request.timeoutMs })893+ .catch(() => undefined);894+ }apps/web/src/browser/ServerBrowserSurface.tsx lines 699 to 702Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +560,21 @@560+ // Enter carries "\r" like Puppeteer's key table, so forms submit and textareas break lines.561+ const text = shortcut562+ ? undefined563+ : [...event.key].length === 1564+ ? event.key565+ : event.key === "Enter"566+ ? "\r"567+ : undefined;568+ send({569+ type: "key",570+ action,571+ key: event.key,572+ code: event.code,573+ keyCode: event.keyCode,574+ ...(action === "down" && text !== undefined ? { text } : {}),575+ modifiers: previewStreamModifiers(event),576+ });577+ // Shortcuts stay with the app (copy, paste, keybindings); other keys belong to the page.578+ if (shortcut) return;579+ event.preventDefault();580+ event.stopPropagation();
- apps/web/src/browser/ServerBrowserSurface.tsx line 383OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +363,21 @@363+ event.preventDefault();364+ const unit =365+ event.deltaMode === WheelEvent.DOM_DELTA_LINE366+ ? WHEEL_LINE_PX367+ : event.deltaMode === WheelEvent.DOM_DELTA_PAGE368+ ? (viewportRef.current?.height ?? 0)369+ : 1;370+ queueWheel(point, event.deltaX * unit, event.deltaY * unit, previewStreamModifiers(event));371+ };372+ canvas.addEventListener("wheel", onWheel, { passive: false });373+ return () => canvas.removeEventListener("wheel", onWheel);374+ }, [pagePoint, queueWheel]);375+376+ useEffect(377+ () => () => {378+ if (inputFrameRef.current !== null) cancelAnimationFrame(inputFrameRef.current);379+ },380+ [],381+ );382+383+ const handlePointerDown = (event: PointerEvent<HTMLCanvasElement>) => {
- @@ -0,0 +493,21 @@493+ await popup.close().catch(() => undefined);494+ if (url !== "about:blank") await page.goto(url).catch(() => undefined);495+ });496+ });497+ page.on("close", () => {498+ if (!tab.closing) dropTab(tab, true);499+ });500+ // Playwright cannot reload a crashed page. Remove it so clients stop501+ // displaying its stale frame and the agent can open a fresh tab.502+ page.on("crash", () => {503+ if (!tab.closing) dropTab(tab, true);504+ });505+ tabs.set(tabKey(tab.threadId, tab.tabId), tab);506+ reportLiveTabs();507+ if (snapshot.navStatus._tag === "Loading") {508+ tab.initialNavigation = page509+ .goto(snapshot.navStatus.url, { waitUntil: "commit", timeout: NAVIGATION_TIMEOUT_MS })510+ .then(511+ () => undefined,512+ () => undefined,513+ );packages/client-runtime/src/preview/serverBrowserStream.ts line 375Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +172,21 @@172+ } else if (173+ type === "probe" &&174+ typeof x === "number" &&175+ typeof y === "number" &&176+ typeof editable === "boolean"177+ ) {178+ events.onProbe?.({ x, y, editable });179+ }180+ });181+ ws.addEventListener("close", (event) => {182+ if (socket !== ws) return;183+ socket = null;184+ if (opened) events.onConnectedChange(false);185+ if (stopped) return;186+ if (event.code === PREVIEW_STREAM_TAB_GONE_CODE) {187+ stopped = true;188+ events.onGone?.();189+ return;190+ }191+ // Rejected upgrades surface as 1006 before open for both cookies and tickets.192+ if (event.code === 1008 || event.code === 4401 || (!opened && event.code === 1006)) {
- apps/server/src/preview/Manager.ts line 237OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -221,4 +233,5 @@221233222234 const open: PreviewManager["Service"]["open"] = Effect.fn("PreviewManager.open")(223235 function* (input) {224- const tabId = newPreviewTabId();236+ // Persisted client surfaces must not bind to a different tab after a server restart.237+ const tabId = `${newPreviewTabId()}${input.runtime === "server" ? `_${serverEpoch}` : ""}`;apps/server/src/preview/ServerBrowser.ts line 301OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +281,21 @@281+ deviceScaleFactor: RENDER_SCALE,282+ };283+ if (profileId === INCOGNITO_BROWSER_PROFILE_ID) {284+ const browser = await chromium.launch(launchOptions);285+ try {286+ const context = await browser.newContext(contextOptions);287+ context.on("close", () => void browser.close().catch(() => undefined));288+ return context;289+ } catch (cause) {290+ await browser.close().catch(() => undefined);291+ throw cause;292+ }293+ }294+ const userDataDir = NodePath.join(profilesDir, encodeURIComponent(profileId));295+ await NodeFSP.mkdir(userDataDir, { recursive: true });296+ return chromium.launchPersistentContext(userDataDir, { ...launchOptions, ...contextOptions });297+ };298+ // The namespace sandbox needs unprivileged user namespaces, which some299+ // containers disable. Running unsandboxed there matches what the agent300+ // already has: a shell as the same user.301+ const context = await launch(true).catch(() => launch(false));apps/mobile/src/features/browser/preview-stream.browser.ts lines 541 to 541Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +519,21 @@519+ }520+ if (touch?.pointerId !== event.pointerId) return;521+ touch = null;522+ if (probe) probe.end = "panned";523+ };524+ // Trackpads and mice on tablets scroll with wheel events.525+ const onWheel = (event: WheelEvent) => {526+ const point = pagePoint(event.clientX, event.clientY, false);527+ if (!point) return;528+ event.preventDefault();529+ const unit =530+ event.deltaMode === WheelEvent.DOM_DELTA_LINE531+ ? WHEEL_LINE_PX532+ : event.deltaMode === WheelEvent.DOM_DELTA_PAGE533+ ? (viewport?.height ?? 0)534+ : 1;535+ queueWheel(point, event.deltaX * unit, event.deltaY * unit);536+ };537+ // Keeps focus in the page input and stops native selection and callouts.538+ const preventDefault = (event: Event) => event.preventDefault();539+apps/web/src/browser/ServerBrowserSurface.tsx line 385Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +285,21 @@285+286+ useEffect(() => {287+ const canvas = canvasRef.current;288+ if (!visible || accessDenied || !access || !cap || !canvas) return;289+ let refreshTimer: ReturnType<typeof setTimeout> | null = null;290+ const painter = createPreviewFramePainter(canvas, () => {291+ if (hasFrameRef.current) return;292+ hasFrameRef.current = true;293+ firstFrame();294+ });295+ const client = createPreviewStreamClient(296+ { access, threadId, tabId, maxWidth: cap.width, maxHeight: cap.height },297+ {298+ onFrame: (jpeg) => {299+ unauthorizedRef.current = 0;300+ painter.paint(jpeg);301+ },302+ onProbe: (result) => {303+ lastProbeRef.current = { ...result, at: performance.now() };304+ const probe = probeRef.current;305+ if (!probe || probe.x !== result.x || probe.y !== result.y) return;
- apps/server/src/preview/Manager.ts lines 233 to 240OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -221,7 +233,8 @@221233222234 const open: PreviewManager["Service"]["open"] = Effect.fn("PreviewManager.open")(223235 function* (input) {224- const tabId = newPreviewTabId();236+ // Persisted client surfaces must not bind to a different tab after a server restart.237+ const tabId = `${newPreviewTabId()}${input.runtime === "server" ? `_${serverEpoch}` : ""}`;225238 const updatedAt = yield* currentIsoTimestamp;226239 // Clients with a configured default send the viewport up front so the227240 // session is born at the right size; older clients omit it and keep the
- apps/server/src/ws.ts line 3449OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -3442,5 +3443,7 @@34423443 ),34433444 { "rpc.aggregate": "terminal" },34443445 ),3445- [WS_METHODS.previewOpen]: (input) =>3446- observeRpcEffect(WS_METHODS.previewOpen, previewManager.open(input), {3446+ [WS_METHODS.previewOpen]: (input) => {3447+ // Without a server browser nothing renders server tabs, so the client renders it.3448+ const { runtime, ...rest } = input;3449+ const open = runtime === "server" && !isServerBrowserEnabled(config.mode) ? rest : input;
- @@ -0,0 +337,21 @@337+ const index = history?.currentIndex ?? 0;338+ const count = history?.entries.length ?? 0;339+ runFork(340+ manager341+ .reportStatus({342+ threadId: tab.threadId,343+ tabId: tab.tabId,344+ navStatus,345+ canGoBack: index > 0,346+ canGoForward: index < count - 1,347+ })348+ .pipe(Effect.ignore),349+ );350+ });351+ };352+353+ const reportLoaded = async (tab: ServerTab) => {354+ const url = tab.page.url();355+ // Chromium's error page loads after `requestfailed` and must not clear LoadFailed.356+ if (url === "about:blank" || url.startsWith("chrome-error://")) return;357+ const title = (await tab.page.title().catch(() => "")).slice(0, 512);apps/server/src/preview/ServerBrowser.ts line 407OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +387,21 @@387+ };388+389+ const applySetting = async (tab: ServerTab, setting: PreviewViewportSetting) => {390+ tab.setting = setting;391+ const size =392+ fixedViewportSize(setting) ??393+ [...tab.viewers]394+ .map((viewer) => viewer.requestedSize)395+ .filter((requested) => requested !== null)396+ .sort((left, right) => right.order - left.order)[0] ??397+ UNATTACHED_FILL_VIEWPORT;398+ await tab.page.setViewportSize({ width: size.width, height: size.height });399+ broadcastViewport(tab);400+ };401+402+ const dropTab = (tab: ServerTab, closeSession: boolean) => {403+ const key = tabKey(tab.threadId, tab.tabId);404+ if (tabs.get(key) !== tab) return;405+ tabs.delete(key);406+ tab.closing = true;407+ for (const viewer of tab.viewers) viewer.push({ _tag: "gone" });apps/server/src/preview/ServerBrowser.ts lines 1477 to 1500Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +860,21 @@860+ }861+ return tab;862+ };863+864+ const runOperation = async (request: PreviewAutomationRequest): Promise<unknown> => {865+ const input = request.input;866+ switch (request.operation) {867+ case "status":868+ return statusWithTitle(869+ request.tabId === undefined870+ ? latestThreadTab(request.threadId)871+ : tabs.get(tabKey(request.threadId, request.tabId)),872+ );873+ case "open": {874+ const open = input as PreviewAutomationOpenInput;875+ const url = open.url === undefined ? undefined : normalizePreviewUrl(open.url);876+ const reuse = open.reuseExistingTab ?? true;877+ const existing =878+ reuse && request.tabId !== undefined879+ ? tabs.get(tabKey(request.threadId, request.tabId))880+ : undefined;
- apps/web/src/browser/ServerBrowserSurface.tsx line 414OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +394,21 @@394+ };395+ const point = pagePoint(event.clientX, event.clientY, false);396+ const last = lastProbeRef.current;397+ const reusable =398+ point !== null &&399+ last !== null &&400+ performance.now() - last.at < PROBE_REUSE_MS &&401+ Math.hypot(point.x - last.x, point.y - last.y) < PROBE_REUSE_PX;402+ probeRef.current = point403+ ? {404+ x: point.x,405+ y: point.y,406+ editable: reusable ? last.editable : null,407+ answered: false,408+ tapped: false,409+ }410+ : null;411+ if (point) send({ type: "probe", x: point.x, y: point.y });412+ return;413+ }414+ focusInput();apps/mobile/src/features/browser/preview-stream.browser.ts lines 595 to 595OutdatedResolvedby maria-rcks@@ -0,0 +575,21 @@575+ if (!shortcut) event.preventDefault();576+ };577+ const onKeyDown = (event: KeyboardEvent) => onKey("down", event);578+ const onKeyUp = (event: KeyboardEvent) => onKey("up", event);579+ const resetInput = () => {580+ input.value = SENTINEL;581+ input.setSelectionRange(SENTINEL.length, SENTINEL.length);582+ };583+ const pressKey = (key: "Backspace" | "Delete", keyCode: number) => {584+ for (const action of ["down", "up"] as const) {585+ send({ type: "key", action, key, code: key, keyCode, modifiers: 0 });586+ }587+ };588+ const onInput = (event: Event) => {589+ if (event instanceof InputEvent && event.isComposing) return;590+ const inputType = event instanceof InputEvent ? event.inputType : "";591+ if (keySent) keySent = false;592+ else if (inputType === "deleteContentBackward") pressKey("Backspace", 8);593+ else if (inputType === "deleteContentForward") pressKey("Delete", 46);594+ else {595+ const text = input.value.replaceAll(SENTINEL, "");
Sign in to join this conversation.




















macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed