diff --git a/apps/mobile/src/features/browser/preview-stream.browser.ts b/apps/mobile/src/features/browser/preview-stream.browser.ts
index 75cf5608b475e..c7a5f259864f0 100644
--- a/apps/mobile/src/features/browser/preview-stream.browser.ts
+++ b/apps/mobile/src/features/browser/preview-stream.browser.ts
@@ -135,10 +135,14 @@ export function start(configuration: PreviewStreamConfiguration) {
streaming = status === "streaming";
post({ type: "status", status });
};
- const painter = createPreviewFramePainter(canvas, () => {
- if (!streaming && !stopped) reportStatus("streaming");
- sendPictureInPictureFrame();
- });
+ const painter = createPreviewFramePainter(
+ canvas,
+ () => {
+ if (!streaming && !stopped) reportStatus("streaming");
+ sendPictureInPictureFrame();
+ },
+ () => client?.requestKeyFrame(),
+ );
const send = (message: PreviewStreamInput) => client?.send(message) ?? false;
const clearInput = () => {
if (wheelFrame !== null) cancelAnimationFrame(wheelFrame);
@@ -170,7 +174,7 @@ export function start(configuration: PreviewStreamConfiguration) {
interactive,
},
{
- onFrame: (jpeg) => painter.paint(jpeg),
+ onFrame: (frame) => painter.paint(frame),
onPointer: showAgentCursor,
onClipboard: (text) => post({ type: "clipboard", text }),
onDownload: (download) => post({ type: "download", ...download }),
diff --git a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx
index 4fa4874da13b9..8e7bcaa026454 100644
--- a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx
+++ b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx
@@ -88,6 +88,7 @@ vi.mock("./components/SettingsEnvironmentFilterHeader", () => ({
SettingsEnvironmentFilterHeader: () => null,
}));
vi.mock("./components/DatabaseStorageNotice", () => ({ DatabaseStorageNotice: () => null }));
+vi.mock("./components/BrowserRenderingSections", () => ({ BrowserRenderingSections: () => null }));
vi.mock("./components/SettingsSection", () => ({ SettingsSection: Children }));
vi.mock("../../components/ui/ListChoiceRow", () => ({ ListChoiceRow: () => null }));
vi.mock("./components/SettingsSwitchRow", () => ({
diff --git a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx
index ccc504f6d6f74..3649cee5df9c8 100644
--- a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx
@@ -24,6 +24,7 @@ import {
SettingsEnvironmentFilterHeader,
} from "./components/SettingsEnvironmentFilterHeader";
import { BranchNamingSettings } from "./components/BranchNamingSettings";
+import { BrowserRenderingSections } from "./components/BrowserRenderingSections";
import { DatabaseStorageNotice } from "./components/DatabaseStorageNotice";
import { ListChoiceRow as SettingsChoiceRow } from "../../components/ui/ListChoiceRow";
import { SettingsSection } from "./components/SettingsSection";
@@ -378,6 +379,17 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
onValueChange={(value) => write({ enableAgentBrowserAccess: value })}
/>
+ {projectSelected ? null : (
+
+ )}
0} />
>
) : null}
diff --git a/apps/mobile/src/features/settings/components/BrowserRenderingSections.tsx b/apps/mobile/src/features/settings/components/BrowserRenderingSections.tsx
new file mode 100644
index 0000000000000..79dcbd2df9494
--- /dev/null
+++ b/apps/mobile/src/features/settings/components/BrowserRenderingSections.tsx
@@ -0,0 +1,84 @@
+import { useAtomValue } from "@effect/atom-react";
+import {
+ DEFAULT_SERVER_BROWSER_GPU,
+ DEFAULT_SERVER_BROWSER_RENDER_SCALE,
+ type EnvironmentId,
+ type ServerBrowserGpuList,
+ type ServerBrowserRenderScale,
+ type ServerSettingsPatch,
+} from "@t3tools/contracts";
+import { AsyncResult, Atom } from "effect/reactivity";
+
+import { ListChoiceRow } from "../../../components/ui/ListChoiceRow";
+import { previewEnvironment } from "../../../state/preview";
+import { SettingsSection } from "./SettingsSection";
+
+const NO_GPUS_ATOM = Atom.make(AsyncResult.success({ gpus: [] }));
+const RENDER_SCALES: ReadonlyArray = [1, 1.5, 2, 3];
+const APPLIES = "Changing this reloads the environment's open browser tabs.";
+
+/** Null values mean the selected environments differ. */
+export function BrowserRenderingSections(props: {
+ readonly environmentId: EnvironmentId | null;
+ readonly gpu: string | null;
+ readonly scale: ServerBrowserRenderScale | null;
+ readonly disabled: boolean;
+ readonly write: (patch: ServerSettingsPatch) => void;
+}) {
+ // GPUs belong to one host, so they are listed only when one environment is selected.
+ const discovered = useAtomValue(
+ props.environmentId
+ ? previewEnvironment.gpus({ environmentId: props.environmentId, input: {} })
+ : NO_GPUS_ATOM,
+ );
+ const gpus = AsyncResult.isSuccess(discovered) ? discovered.value.gpus : [];
+ const gpuChoices = [
+ {
+ id: DEFAULT_SERVER_BROWSER_GPU,
+ label: "Software",
+ description: `Render on the CPU. The default. ${APPLIES}`,
+ },
+ { id: "auto", label: "Automatic", description: "Let the browser pick a GPU." },
+ ...gpus.map((gpu) => ({
+ id: gpu.id,
+ label: gpu.name,
+ description: gpu.driver ? `${gpu.driver} · ${gpu.id}` : gpu.id,
+ })),
+ ];
+ if (props.gpu !== null && !gpuChoices.some((choice) => choice.id === props.gpu)) {
+ gpuChoices.push({ id: props.gpu, label: props.gpu, description: "Not found on this host." });
+ }
+
+ return (
+ <>
+
+ {gpuChoices.map((choice, index) => (
+ 0}
+ disabled={props.disabled}
+ onPress={() => props.write({ serverBrowserGpu: choice.id })}
+ />
+ ))}
+
+
+ {RENDER_SCALES.map((scale, index) => (
+ 0}
+ disabled={props.disabled}
+ onPress={() => props.write({ serverBrowserRenderScale: scale })}
+ />
+ ))}
+
+ >
+ );
+}
diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts
index a1b05c32a0027..7ad94c9515485 100644
--- a/apps/server/src/auth/RpcAuthorization.ts
+++ b/apps/server/src/auth/RpcAuthorization.ts
@@ -184,6 +184,7 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.previewAdjust]: AuthPreviewOperateScope,
[WS_METHODS.previewClose]: AuthPreviewOperateScope,
[WS_METHODS.previewList]: AuthOrchestrationReadScope,
+ [WS_METHODS.previewListGpus]: AuthOrchestrationReadScope,
[WS_METHODS.previewClearProfile]: AuthPreviewOperateScope,
[WS_METHODS.previewReportProfiles]: AuthPreviewOperateScope,
[WS_METHODS.previewReportStatus]: AuthPreviewOperateScope,
diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts
index fcbbde88f4b1d..2b625710c1764 100644
--- a/apps/server/src/observability/RpcInstrumentation.ts
+++ b/apps/server/src/observability/RpcInstrumentation.ts
@@ -194,6 +194,7 @@ const RPC_AGGREGATES = {
[WS_METHODS.previewAdjust]: "preview",
[WS_METHODS.previewClose]: "preview",
[WS_METHODS.previewList]: "preview",
+ [WS_METHODS.previewListGpus]: "preview",
[WS_METHODS.previewClearProfile]: "preview",
[WS_METHODS.previewReportProfiles]: "preview",
[WS_METHODS.previewReportStatus]: "preview",
diff --git a/apps/server/src/preview/ServerBrowser.test.ts b/apps/server/src/preview/ServerBrowser.test.ts
index 99df18c10cf5a..0894bf45aa7e0 100644
--- a/apps/server/src/preview/ServerBrowser.test.ts
+++ b/apps/server/src/preview/ServerBrowser.test.ts
@@ -14,7 +14,9 @@ import {
ThreadId,
type PreviewAutomationSnapshot,
type PreviewAutomationStatus,
+ type ServerSettings,
} from "@t3tools/contracts";
+import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts/settings";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
@@ -28,6 +30,7 @@ import type { BrowserContext, Page } from "playwright-core";
import { beforeEach, expect, vi } from "vite-plus/test";
import * as ServerConfig from "../config.ts";
+import * as ServerSettingsService from "../serverSettings.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as Broker from "../mcp/PreviewAutomationBroker.ts";
import * as DesktopChannel from "./DesktopBrowserChannel.ts";
@@ -59,6 +62,9 @@ vi.mock("./ServerBrowserContexts.ts", () => ({
desktopConnections.push({ endpoint, context });
return { browser: { close: async () => {} }, page: context.page as unknown as Page };
}
+ async relaunch() {
+ relaunches.count += 1;
+ }
async close() {
for (const context of contexts) await context.close();
}
@@ -87,7 +93,7 @@ function makeSession(frame?: ReturnType) {
const events = new NodeEvents.EventEmitter();
return {
on: vi.fn((name: string, listener: () => void) => events.on(name, listener)),
- emit: (name: string) => events.emit(name),
+ emit: (name: string, ...args: unknown[]) => events.emit(name, ...args),
detach: vi.fn(async () => {}),
send: vi.fn(async (method: string, input?: unknown): Promise> => {
if (method === "Page.getNavigationHistory") return { currentIndex: 0, entries: [{}] };
@@ -259,6 +265,8 @@ function makeEncoderPage() {
}
const contexts: ReturnType[] = [];
+const relaunches = { count: 0 };
+const settingsChanges = new NodeEvents.EventEmitter();
const encoderStreams: Array<{ frameRate: number | undefined; bitsPerSecond: number }> = [];
const contextRequests: Array<{ profileId: string; isolated: boolean }> = [];
let contextGate: PromiseWithResolvers | null = null;
@@ -342,6 +350,19 @@ const dependencies = Layer.mergeAll(
turn: (threadId, active) => Effect.sync(() => desktopTurns.emit("turn", threadId, active)),
}),
PreviewAgentActivity.layer,
+ Layer.mock(ServerSettingsService.ServerSettingsService, {
+ getSettings: Effect.succeed(DEFAULT_SERVER_SETTINGS),
+ streamChanges: Stream.callback((queue) =>
+ Effect.acquireRelease(
+ Effect.sync(() => {
+ const onChange = (settings: ServerSettings) => Queue.offerUnsafe(queue, settings);
+ settingsChanges.on("change", onChange);
+ return onChange;
+ }),
+ (onChange) => Effect.sync(() => settingsChanges.off("change", onChange)),
+ ),
+ ),
+ }),
).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-server-browser-" })),
Layer.provideMerge(NodeServices.layer),
@@ -542,6 +563,117 @@ it.live.each([
).pipe(Effect.provide(layer)),
);
+it.live("a rendering change relaunches the browser and reopens its tabs at their page", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const { browser, tabId } = yield* ready;
+ const manager = yield* Manager.PreviewManager;
+ const url = "http://localhost:5173/settings";
+ yield* manager.reportStatus({
+ threadId: scope.thread.threadId,
+ tabId,
+ serverControlled: true,
+ navStatus: { _tag: "Success", url, title: "Settings" },
+ canGoBack: false,
+ canGoForward: false,
+ });
+ const viewer = yield* browser.attachViewer(viewerInput(tabId, true));
+ const relaunchesBefore = relaunches.count;
+ settingsChanges.emit("change", { ...DEFAULT_SERVER_SETTINGS, serverBrowserGpu: "auto" });
+ let output = yield* Queue.take(viewer.output);
+ while (output._tag !== "reconnect" && output._tag !== "gone") {
+ output = yield* Queue.take(viewer.output);
+ }
+ // Viewers reconnect rather than lose the tab, and it reopens where it was.
+ expect(output._tag).toBe("reconnect");
+ yield* browser.attachViewer(viewerInput(tabId, true));
+ expect(relaunches.count).toBe(relaunchesBefore + 1);
+ expect(contexts.at(-1)!.page.goto).toHaveBeenLastCalledWith(
+ url,
+ expect.objectContaining({ waitUntil: "commit" }),
+ );
+ }),
+ ).pipe(Effect.provide(layer)),
+);
+
+it.live("viewers skip a screencast frame identical to the one before it", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const { browser, tabId } = yield* ready;
+ const viewer = yield* browser.attachViewer(viewerInput(tabId, false));
+ const session = contexts[0]!.sessions.at(-1)!;
+ const frames: string[] = [];
+ const nextFrame = Effect.gen(function* () {
+ let output = yield* Queue.take(viewer.output);
+ while (output._tag !== "frame") output = yield* Queue.take(viewer.output);
+ if (!(output.data instanceof Uint8Array)) throw new Error("expected a JPEG frame");
+ frames.push(Buffer.from(output.data).toString());
+ });
+ yield* nextFrame;
+ // A still capture repaints the page, and Chromium sends the same picture again.
+ for (const [index, data] of ["first", "first", "second"].entries()) {
+ session.emit("Page.screencastFrame", {
+ data: Buffer.from(data).toString("base64"),
+ sessionId: index,
+ });
+ }
+ yield* nextFrame;
+ yield* nextFrame;
+ expect(frames.slice(1)).toEqual(["first", "second"]);
+ expect(session.send).toHaveBeenCalledWith("Page.screencastFrameAck", { sessionId: 1 });
+ }),
+ ).pipe(Effect.provide(layer)),
+);
+
+it.live("wheels and pointer moves waiting behind a slow page merge into one dispatch", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const { browser, tabId } = yield* ready;
+ const viewer = yield* browser.attachViewer(viewerInput(tabId, true));
+ yield* viewer.input({ type: "takeControl" });
+ const cdp = contexts[0]!.sessions.at(-1)!;
+ const send = cdp.send.getMockImplementation()!;
+ const dispatched: Array = [];
+ const started = Promise.withResolvers();
+ const handled = Promise.withResolvers();
+ cdp.send.mockImplementation(async (operation, input) => {
+ const event = input as { type?: string; deltaY?: number; x?: number; key?: string };
+ if (operation === "Input.dispatchMouseEvent") {
+ dispatched.push(`${event.type} ${event.type === "mouseWheel" ? event.deltaY : event.x}`);
+ } else if (operation === "Input.dispatchKeyEvent")
+ dispatched.push(`${event.type} ${event.key}`);
+ if (dispatched.length === 1) {
+ started.resolve();
+ await handled.promise;
+ }
+ return send(operation, input);
+ });
+ const wheel = (deltaY: number) => ({ type: "wheel", x: 10, y: 20, deltaX: 0, deltaY });
+ const move = (x: number) => ({ type: "mouse", action: "move", x, y: 5, button: "none" });
+ const key = { type: "key", action: "up", key: "a", code: "KeyA" };
+ const first = yield* viewer
+ .input(wheel(10))
+ .pipe(Effect.forkChild({ startImmediately: true }));
+ yield* Effect.promise(() => started.promise);
+ // A key between wheels keeps its place; only neighbouring motion merges.
+ const rest = yield* Effect.forEach(
+ [wheel(20), wheel(30), key, wheel(40), move(1), move(7)],
+ (input) => viewer.input(input).pipe(Effect.forkChild({ startImmediately: true })),
+ );
+ handled.resolve();
+ yield* Fiber.join(first);
+ yield* Effect.forEach(rest, Fiber.join);
+ expect(dispatched).toEqual([
+ "mouseWheel 10",
+ "mouseWheel 50",
+ "keyUp a",
+ "mouseWheel 40",
+ "mouseMoved 7",
+ ]);
+ }),
+ ).pipe(Effect.provide(layer)),
+);
+
// The fake encoder decodes every frame at 1280x800, so 30 fps hits the bitrate floor.
it.live.each([
{ reports: [], frameRate: 30, bitsPerSecond: 2.5e6 },
diff --git a/apps/server/src/preview/ServerBrowser.ts b/apps/server/src/preview/ServerBrowser.ts
index 78097b761cb74..8745b60e22459 100644
--- a/apps/server/src/preview/ServerBrowser.ts
+++ b/apps/server/src/preview/ServerBrowser.ts
@@ -1,6 +1,6 @@
// @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.
+// Screencasts ignore emulated device scale; a real device scale keeps captures sharp.
+// The software default (--disable-gpu) composites cheaply while preserving SwiftShader WebGL.
import {
BUILT_IN_BROWSER_PROFILES,
DEFAULT_BROWSER_PROFILE_ID,
@@ -39,6 +39,10 @@ import {
type PreviewNavStatus,
type PreviewSessionSnapshot,
type PreviewViewportSetting,
+ encodePreviewStreamVideoFrame,
+ type ServerBrowserGpuList,
+ DEFAULT_SERVER_BROWSER_GPU,
+ DEFAULT_SERVER_BROWSER_RENDER_SCALE,
ThreadId,
SERVER_BROWSER_AUTOMATION_CLIENT_ID,
type PreviewAppearancePreference,
@@ -73,6 +77,7 @@ import type {
import { PENDING_ATTACHMENT_THREAD_SEGMENT } from "../attachmentStore.ts";
import * as ServerConfig from "../config.ts";
+import * as ServerSettings from "../serverSettings.ts";
import { resolveRootCliCommand } from "../cli/invocation.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as PreviewAutomationBroker from "../mcp/PreviewAutomationBroker.ts";
@@ -83,17 +88,21 @@ 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 { discoverGpus, gpuLaunchArgs } from "./ServerBrowserGpus.ts";
import { BrowserControlInterrupted, SessionControl } from "./SessionControl.ts";
import { installPdfDocumentNavigation, isPdfAssetUrl } from "./PdfDocumentNavigation.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;
const SCREENCAST_MOTION_FRAMES = 4;
const SCREENCAST_MOTION_WINDOW_MS = 300;
const SCREENCAST_MOTION_QUALITY = 50;
+// Video frames are tiny, so they pace only Chromium's capture: three in flight allow 60 fps.
+const VIDEO_ACK_PACE_MS = 50;
+// Video blurs text, so a JPEG still follows once the page stops changing.
+const VIDEO_SETTLE_MS = 400;
const HOST_RECONNECT_DELAY = "1 second";
const DESKTOP_ATTACH_TIMEOUT = "10 seconds";
const VIEWER_OUTPUT_LIMIT = 64;
@@ -156,7 +165,8 @@ export class ServerBrowserLaunchError extends Schema.TaggedError;
readonly ack: Effect.Effect;
}
| { readonly _tag: "viewport"; readonly width: number; readonly height: number }
@@ -205,6 +215,8 @@ export type ServerBrowserViewerOutput =
export interface ServerBrowserViewer {
readonly output: Queue.Dequeue;
readonly input: (message: unknown) => Effect.Effect;
+ /** Read-only viewers decode video too, so this is not gated on control. */
+ readonly requestKeyFrame: Effect.Effect;
}
export class ServerBrowser extends Context.Service<
@@ -217,6 +229,8 @@ export class ServerBrowser extends Context.Service<
readonly maxHeight: number;
readonly quality: number;
readonly canOperate: boolean;
+ /** Codecs the viewer decodes, preferred first; empty keeps JPEG frames. */
+ readonly videoCodecs?: ReadonlyArray;
}) => Effect.Effect<
ServerBrowserViewer,
ServerBrowserTabNotFoundError | ServerBrowserLaunchError,
@@ -242,6 +256,9 @@ export class ServerBrowser extends Context.Service<
readonly clearProfile: (profileId: string) => Effect.Effect;
readonly reportProfiles: (input: PreviewReportProfilesInput) => Effect.Effect;
+
+ /** GPUs this host's browser can render on, for the rendering setting. */
+ readonly listGpus: Effect.Effect;
}
>()("t3/preview/ServerBrowser") {}
@@ -256,6 +273,8 @@ interface ViewerState {
scrolledAt: number;
requestedSize: { width: number; height: number; order: number } | null;
+ /** A wheel or pointer move still waiting for earlier input, which later ones merge into. */
+ waitingMotion: Record | null;
}
interface EncoderWindow {
@@ -460,6 +479,22 @@ const make = Effect.gen(function* () {
const runPromise = Effect.runPromiseWith(yield* Effect.context());
const launchServices = yield* Effect.context();
const setupCommand = yield* resolveRootCliCommand(PreviewBrowserHost.SETUP_SUBCOMMAND);
+ const serverSettings = yield* ServerSettings.ServerSettingsService;
+ const renderingOf = (settings: {
+ readonly serverBrowserGpu: string;
+ readonly serverBrowserRenderScale: number;
+ }) => ({ gpu: settings.serverBrowserGpu, scale: settings.serverBrowserRenderScale });
+ let rendering = renderingOf(
+ yield* serverSettings.getSettings.pipe(
+ Effect.orElseSucceed(() => ({
+ serverBrowserGpu: DEFAULT_SERVER_BROWSER_GPU,
+ serverBrowserRenderScale: DEFAULT_SERVER_BROWSER_RENDER_SCALE,
+ })),
+ ),
+ );
+ // Tabs reopen only after the old browsers close, so a profile is never opened twice.
+ let relaunched = Promise.resolve();
+ const relaunchedTabs = new Set();
const tabs = new Map();
const pendingTabs = new Map>();
@@ -472,6 +507,10 @@ const make = Effect.gen(function* () {
const contexts = new ServerBrowserContexts({
profilesDir: NodePath.join(config.stateDir, "server-browser", "profiles"),
+ rendering: async () => ({
+ args: await gpuLaunchArgs(rendering.gpu, host.platform),
+ scale: rendering.scale,
+ }),
executable: () => runPromise(previewBrowser.executable),
// Playwright's launch error drops Chrome's own output; its sandbox note survives.
diagnose: (executable, cause) =>
@@ -612,7 +651,7 @@ const make = Effect.gen(function* () {
await tab.cdp.send("Emulation.setDeviceMetricsOverride", {
width: layout.width,
height: layout.height,
- deviceScaleFactor: RENDER_SCALE * tab.zoomFactor,
+ deviceScaleFactor: rendering.scale * tab.zoomFactor,
mobile: false,
});
};
@@ -655,14 +694,15 @@ const make = Effect.gen(function* () {
const sessionOpen = (tab: ServerTab) => !closedSessions.has(tabKey(tab.threadId, tab.tabId));
- const dropTab = (tab: ServerTab, closeSession: boolean) => {
+ const dropTab = (tab: ServerTab, closeSession: boolean, reopens = false) => {
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";
+ const end =
+ reopens || (tab.desktop && !closeSession && sessionOpen(tab)) ? "reconnect" : "gone";
for (const viewer of tab.viewers) viewer.push({ _tag: end });
void tab.control.close().catch(constVoid);
if (tab.desktop) void tab.desktop.close().catch(constVoid);
@@ -891,16 +931,20 @@ const make = Effect.gen(function* () {
page.on("crash", () => dropTab(tab, true));
tabs.set(key, tab);
reportLiveTabs();
- // Existing desktop and popup PDFs can start loading before interception attaches.
- if (
- snapshot.navStatus._tag === "Loading" &&
- ((!adopted && !desktop) || isPdfAssetUrl(snapshot.navStatus.url))
- ) {
+ // Existing desktop and popup PDFs can start loading before interception attaches. A tab
+ // reopened by a browser relaunch returns to its page even after that page loaded.
+ const navStatus = snapshot.navStatus;
+ const reopened = relaunchedTabs.delete(key);
+ const resumeUrl =
+ navStatus._tag === "Loading" || (reopened && navStatus._tag !== "Idle")
+ ? navStatus.url
+ : null;
+ if (resumeUrl !== null && ((!adopted && !desktop) || isPdfAssetUrl(resumeUrl))) {
const options = { waitUntil: "commit", timeout: NAVIGATION_TIMEOUT_MS } as const;
tab.initialNavigation = (
- (desktop || adopted) && page.url() === snapshot.navStatus.url
+ (desktop || adopted) && page.url() === resumeUrl
? page.reload(options)
- : page.goto(snapshot.navStatus.url, options)
+ : page.goto(resumeUrl, options)
).then(constVoid, (cause: unknown) => {
throw ServerBrowserPage.toOperationError(cause, NAVIGATION_TIMEOUT_MS);
});
@@ -1225,7 +1269,8 @@ const make = Effect.gen(function* () {
if (pending) return pending;
const existing = tabs.get(key);
if (existing) return Promise.resolve(existing);
- const opening = createTab(snapshot)
+ const opening = relaunched
+ .then(() => createTab(snapshot))
.catch((cause: unknown) => {
runFork(
Effect.logWarning(
@@ -1467,6 +1512,28 @@ const make = Effect.gen(function* () {
return run;
};
+ const openVideoEncoder = async (codecs: ReadonlyArray) => {
+ const page = await contexts.scratchPage().catch(() => null);
+ if (!page) return null;
+ try {
+ await page.route(ServerBrowserPage.VIDEO_ENCODER_URL, (route) =>
+ route.fulfill({ contentType: "text/html", body: "" }),
+ );
+ await page.goto(ServerBrowserPage.VIDEO_ENCODER_URL);
+ await page.evaluate(ServerBrowserPage.videoEncoderScript);
+ const codec = await page.evaluate(
+ (candidates) =>
+ (globalThis as unknown as ServerBrowserPage.VideoEncoderWindow).__t3Video.pick(
+ candidates,
+ ),
+ codecs,
+ );
+ if (codec !== null) return { page, codec };
+ } catch {}
+ await page.close().catch(constVoid);
+ return null;
+ };
+
const startRecording = (tab: ServerTab): Promise => {
const started = withCaptureLock(tab, async () => {
if (tab.recording) return tab.recording;
@@ -1968,7 +2035,7 @@ const make = Effect.gen(function* () {
return withScreencastsPaused(tab, () =>
ServerBrowserPage.snapshot({
...tab,
- renderScale: tab.desktop ? "display" : RENDER_SCALE,
+ renderScale: tab.desktop ? "display" : rendering.scale,
}),
);
}
@@ -2108,6 +2175,13 @@ const make = Effect.gen(function* () {
viewer.requestedSize = null;
};
+ const motionKind = (message: Record) =>
+ message.type === "wheel"
+ ? "wheel"
+ : message.type === "mouse" && message.action === "move"
+ ? "move"
+ : null;
+
const dispatchViewerInput = async (
tab: ServerTab,
session: CDPSession,
@@ -2267,9 +2341,46 @@ const make = Effect.gen(function* () {
),
);
const quality = Math.min(100, Math.max(1, Math.round(input.quality)));
+ const video =
+ input.videoCodecs && input.videoCodecs.length > 0
+ ? yield* Effect.acquireRelease(
+ Effect.promise(() => openVideoEncoder(input.videoCodecs ?? [])),
+ (opened) => Effect.promise(async () => opened?.page.close().catch(constVoid)),
+ )
+ : null;
+ let videoEncoder = video;
+ const encodeFrame = async (jpeg: string) => {
+ const current = videoEncoder;
+ if (!current) return Buffer.from(jpeg, "base64");
+ try {
+ const encoded = await current.page.evaluate(
+ (data) =>
+ (globalThis as unknown as ServerBrowserPage.VideoEncoderWindow).__t3Video.encode(data),
+ jpeg,
+ );
+ if (!encoded) return null;
+ const data = Buffer.from(encoded.data, "base64");
+ return encodePreviewStreamVideoFrame(
+ encoded.key
+ ? {
+ type: "key",
+ codec: current.codec,
+ width: encoded.width,
+ height: encoded.height,
+ data,
+ }
+ : { type: "delta", data },
+ );
+ } catch {
+ // A failed encoder, e.g. past the codec's size limit, leaves this viewer on JPEG.
+ videoEncoder = null;
+ return Buffer.from(jpeg, "base64");
+ }
+ };
// Chromium may drop the final frame during a burst; send a still when it settles.
let framesInFlight = 0;
let mayHaveDropped = false;
+ let videoSinceStill = false;
let motion = false;
const recentFrames: Array = [];
let screencastParams = Promise.resolve();
@@ -2320,6 +2431,7 @@ const make = Effect.gen(function* () {
resume: () => startScreencast(screencastScale),
scrolledAt: 0,
requestedSize: null,
+ waitingMotion: null,
};
yield* Effect.acquireRelease(
Effect.sync(() => {
@@ -2352,48 +2464,77 @@ const make = Effect.gen(function* () {
}),
);
let screencastStarted = false;
+ let previousFrame: string | null = null;
session.on("Page.screencastFrame", (frame) => {
screencastStarted = true;
+ // A capture can repaint an unchanged page. Sending that frame would only cost bandwidth,
+ // and for video it would schedule another still, whose capture repaints again.
+ if (frame.data === previousFrame) {
+ void session
+ .send("Page.screencastFrameAck", { sessionId: frame.sessionId })
+ .then(constVoid, constVoid);
+ return;
+ }
+ previousFrame = frame.data;
if (framesInFlight > 0) mayHaveDropped = true;
framesInFlight += 1;
const arrivedAt = Date.now();
- recentFrames.push(arrivedAt);
- while (recentFrames[0]! < arrivedAt - SCREENCAST_MOTION_WINDOW_MS) recentFrames.shift();
- if (
- !motion &&
- recentFrames.length >= SCREENCAST_MOTION_FRAMES &&
- arrivedAt - viewer.scrolledAt < SCREENCAST_MOTION_WINDOW_MS
- ) {
- motion = true;
- void startScreencast(0.5);
- } else if (motion && arrivedAt - viewer.scrolledAt > SCREENCAST_SETTLE_MS) {
- motion = false;
- recentFrames.length = 0;
- void startScreencast(1);
- }
- if (settleTimer !== null) clearTimeout(settleTimer);
- settleTimer = setTimeout(() => {
- settleTimer = null;
- if (!motion && !mayHaveDropped) return;
- mayHaveDropped = false;
- if (motion) {
+ // Video already keeps moving frames small, so only JPEG viewers drop resolution.
+ if (!video) {
+ recentFrames.push(arrivedAt);
+ while (recentFrames[0]! < arrivedAt - SCREENCAST_MOTION_WINDOW_MS) recentFrames.shift();
+ if (
+ !motion &&
+ recentFrames.length >= SCREENCAST_MOTION_FRAMES &&
+ arrivedAt - viewer.scrolledAt < SCREENCAST_MOTION_WINDOW_MS
+ ) {
+ motion = true;
+ void startScreencast(0.5);
+ } else if (motion && arrivedAt - viewer.scrolledAt > SCREENCAST_SETTLE_MS) {
motion = false;
recentFrames.length = 0;
void startScreencast(1);
}
- void pushStill();
- }, SCREENCAST_SETTLE_MS);
+ }
+ if (settleTimer !== null) clearTimeout(settleTimer);
+ settleTimer = setTimeout(
+ () => {
+ settleTimer = null;
+ if (!motion && !mayHaveDropped && !videoSinceStill) return;
+ mayHaveDropped = false;
+ videoSinceStill = false;
+ if (motion) {
+ motion = false;
+ recentFrames.length = 0;
+ void startScreencast(1);
+ }
+ void pushStill();
+ },
+ video ? VIDEO_SETTLE_MS : SCREENCAST_SETTLE_MS,
+ );
+ let released: Promise | null = null;
+ const release = () =>
+ (released ??= sleepUntil(
+ arrivedAt + (video ? VIDEO_ACK_PACE_MS : SCREENCAST_ACK_PACE_MS),
+ ).then(() => {
+ framesInFlight -= 1;
+ return session
+ .send("Page.screencastFrameAck", { sessionId: frame.sessionId })
+ .then(constVoid, constVoid);
+ }));
+ if (videoEncoder) videoSinceStill = true;
viewer.push({
_tag: "frame",
- data: Buffer.from(frame.data, "base64"),
- ack: Effect.promise(() =>
- sleepUntil(arrivedAt + SCREENCAST_ACK_PACE_MS).then(() => {
- framesInFlight -= 1;
- return session
- .send("Page.screencastFrameAck", { sessionId: frame.sessionId })
- .catch(constVoid);
- }),
- ),
+ // The window between server and viewer bounds video, so Chromium is released once a
+ // frame is encoded rather than when the viewer acks it.
+ data: video
+ ? Effect.promise(() =>
+ encodeFrame(frame.data).finally(() => {
+ void release();
+ }),
+ )
+ : Buffer.from(frame.data, "base64"),
+ ack: Effect.promise(release),
});
});
broadcastViewport(tab);
@@ -2403,6 +2544,15 @@ const make = Effect.gen(function* () {
if (!screencastStarted) yield* Effect.promise(pushStill);
return {
output,
+ requestKeyFrame: Effect.promise(async () => {
+ await videoEncoder?.page
+ .evaluate(() =>
+ (
+ globalThis as unknown as ServerBrowserPage.VideoEncoderWindow
+ ).__t3Video.requestKeyFrame(),
+ )
+ .catch(constVoid);
+ }),
input: (raw: unknown) =>
Effect.promise(async () => {
if (!viewer.canOperate) return;
@@ -2432,9 +2582,26 @@ const make = Effect.gen(function* () {
: {}),
});
} else {
- await tab.control.human(viewer.id, () =>
- dispatchViewerInput(tab, session, viewer, message),
- );
+ // Each dispatch waits for the page to handle it, so a slow page would replay seconds
+ // of queued wheels and moves. Ones arriving while another waits merge into it.
+ const waiting = viewer.waitingMotion;
+ if (waiting && motionKind(waiting) === motionKind(message)) {
+ const deltas =
+ message.type === "wheel"
+ ? {
+ deltaX: num(waiting.deltaX) + num(message.deltaX),
+ deltaY: num(waiting.deltaY) + num(message.deltaY),
+ }
+ : {};
+ Object.assign(waiting, message, deltas);
+ return;
+ }
+ const input = motionKind(message) === null ? message : { ...message };
+ viewer.waitingMotion = input === message ? null : input;
+ await tab.control.human(viewer.id, () => {
+ if (viewer.waitingMotion === input) viewer.waitingMotion = null;
+ return dispatchViewerInput(tab, session, viewer, input);
+ });
}
} catch {
broadcastControl(tab);
@@ -2444,6 +2611,25 @@ const make = Effect.gen(function* () {
});
yield* manager.events.pipe(Stream.runForEach(mirrorManagerEvent), Effect.forkScoped);
+ // GPU and scale are launch flags, so a change relaunches the browser. Its tabs reload in
+ // place: viewers reconnect and each tab reopens at its page on first use.
+ yield* serverSettings.streamChanges.pipe(
+ Stream.map(renderingOf),
+ Stream.runForEach((next) =>
+ Effect.promise(() => {
+ if (next.gpu === rendering.gpu && next.scale === rendering.scale) return relaunched;
+ rendering = next;
+ for (const tab of tabs.values()) {
+ if (tab.desktop) continue;
+ relaunchedTabs.add(tabKey(tab.threadId, tab.tabId));
+ dropTab(tab, false, true);
+ }
+ relaunched = relaunched.then(() => contexts.relaunch());
+ return relaunched;
+ }),
+ ),
+ Effect.forkScoped,
+ );
if (
!PreviewBrowserHost.sandboxDisabled(yield* HostProcess.Environment) &&
(yield* PreviewBrowserHost.sandboxBlocked)
@@ -2530,10 +2716,16 @@ const make = Effect.gen(function* () {
catch: (cause) => new PreviewClearProfileError({ profileId, cause }),
});
+ const listGpus = Effect.promise(() => discoverGpus(host.platform)).pipe(
+ Effect.map((gpus) => ({ gpus })),
+ Effect.withSpan("ServerBrowser.listGpus"),
+ );
+
return ServerBrowser.of({
attachViewer,
clearProfile,
reportProfiles,
+ listGpus,
openDownload,
answerFileChooser,
});
diff --git a/apps/server/src/preview/ServerBrowserContexts.test.ts b/apps/server/src/preview/ServerBrowserContexts.test.ts
index 7a3babd0dcc0a..37f3193fd5d40 100644
--- a/apps/server/src/preview/ServerBrowserContexts.test.ts
+++ b/apps/server/src/preview/ServerBrowserContexts.test.ts
@@ -53,6 +53,7 @@ const options = () => ({
profilesDir: "/test/profiles",
executable: vi.fn(async () => "/test/chromium"),
env: {},
+ rendering: async () => ({ args: ["--disable-gpu"], scale: 2 }),
});
beforeEach(() => {
@@ -210,6 +211,41 @@ describe("ServerBrowserContexts", () => {
await pool.close();
});
+ it("relaunches every browser with the rendering options current at the next launch", async () => {
+ const human = makeContext();
+ const browsers = [makeBrowser(), makeBrowser()];
+ launches.launch
+ .mockResolvedValueOnce(browsers[0] as unknown as Browser)
+ .mockResolvedValueOnce(browsers[1] as unknown as Browser);
+ launches.persistent.mockResolvedValue(human as unknown as BrowserContext);
+ let rendering = { args: ["--disable-gpu"], scale: 2 };
+ const onContextClose = vi.fn();
+ const pool = new ServerBrowserContexts({
+ ...options(),
+ rendering: async () => rendering,
+ onContextClose,
+ });
+ await pool.contextFor("default");
+ await pool.contextFor("default", "agent");
+
+ rendering = { args: ["--enable-gpu"], scale: 1 };
+ await pool.relaunch();
+ expect(human.close).toHaveBeenCalledTimes(1);
+ expect(browsers[0]!.close).toHaveBeenCalledTimes(1);
+ expect(onContextClose).toHaveBeenCalledTimes(2);
+
+ await pool.contextFor("default", "agent");
+ expect(launches.launch).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ args: ["--enable-gpu", "--force-device-scale-factor=1", expect.any(String)],
+ }),
+ );
+ expect(browsers[1]!.newContext).toHaveBeenCalledWith(
+ expect.objectContaining({ deviceScaleFactor: 1 }),
+ );
+ await pool.close();
+ });
+
it("cleans up a browser whose launch finishes during shutdown and rejects future work", async () => {
const browser = makeBrowser();
const launch = Promise.withResolvers();
diff --git a/apps/server/src/preview/ServerBrowserContexts.ts b/apps/server/src/preview/ServerBrowserContexts.ts
index 0e0f71d4e53ca..bdf475072699e 100644
--- a/apps/server/src/preview/ServerBrowserContexts.ts
+++ b/apps/server/src/preview/ServerBrowserContexts.ts
@@ -20,6 +20,11 @@ interface Options {
readonly diagnose?: (executable: string, cause: unknown) => Promise;
readonly env?: NodeJS.ProcessEnv;
readonly onContextClose?: (context: BrowserContext) => void;
+ /** GPU flags and device scale, read at each launch so a relaunch applies new settings. */
+ readonly rendering: () => Promise<{
+ readonly args: ReadonlyArray;
+ readonly scale: number;
+ }>;
}
const UA_PLATFORMS: Partial> = {
@@ -81,12 +86,13 @@ export class ServerBrowserContexts {
private async launchOptions() {
const executablePath = await this.options.executable();
const env = this.options.env ?? process.env;
+ const rendering = await this.options.rendering();
return {
executablePath,
env,
args: [
- "--disable-gpu",
- "--force-device-scale-factor=2",
+ ...rendering.args,
+ `--force-device-scale-factor=${rendering.scale}`,
"--disable-blink-features=AutomationControlled",
],
ignoreDefaultArgs: ["--enable-automation"],
@@ -150,7 +156,8 @@ export class ServerBrowserContexts {
}
private async createContext(profileId: string, isolationKey?: string) {
- const contextOptions = { viewport: { width: 1280, height: 800 }, deviceScaleFactor: 2 };
+ const { scale } = await this.options.rendering();
+ const contextOptions = { viewport: { width: 1280, height: 800 }, deviceScaleFactor: scale };
if (isolationKey !== undefined || profileId === INCOGNITO_BROWSER_PROFILE_ID) {
const browser = await this.sharedBrowser();
return browser.newContext(contextOptions);
@@ -216,6 +223,17 @@ export class ServerBrowserContexts {
return this.closing;
}
+ /** Closes every browser so the next page launches with the current rendering options. */
+ async relaunch() {
+ if (this.closing) return;
+ const contexts = [...this.contexts.values()];
+ const browser = this.browser;
+ this.contexts.clear();
+ this.browser = undefined;
+ await Promise.allSettled(contexts.map(async (pending) => (await pending).close()));
+ await (await browser?.catch(() => undefined))?.close().catch(constVoid);
+ }
+
private async dispose() {
await Promise.allSettled(
[...this.contexts.values()].map(async (pending) => (await pending).close()),
diff --git a/apps/server/src/preview/ServerBrowserGpus.test.ts b/apps/server/src/preview/ServerBrowserGpus.test.ts
new file mode 100644
index 0000000000000..fa64b7567ff2b
--- /dev/null
+++ b/apps/server/src/preview/ServerBrowserGpus.test.ts
@@ -0,0 +1,88 @@
+// @effect-diagnostics nodeBuiltinImport:off - Builds a fake devfs and sysfs tree on disk.
+import * as NodeFSP from "node:fs/promises";
+import * as NodeOS from "node:os";
+import * as NodePath from "node:path";
+
+import { afterAll, beforeAll, describe, expect, it } from "vite-plus/test";
+
+import { discoverGpus, gpuLaunchArgs } from "./ServerBrowserGpus.ts";
+
+let root = "";
+
+beforeAll(async () => {
+ root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-gpus-"));
+ const write = async (path: string, text: string) => {
+ await NodeFSP.mkdir(NodePath.dirname(NodePath.join(root, path)), { recursive: true });
+ await NodeFSP.writeFile(NodePath.join(root, path), text);
+ };
+ const gpu = async (pci: string, node: string, vendor: string, device: string, driver: string) => {
+ await write(`dev/dri/${node}`, "");
+ await NodeFSP.mkdir(NodePath.join(root, "dev/dri/by-path"), { recursive: true });
+ await NodeFSP.symlink(`../${node}`, NodePath.join(root, `dev/dri/by-path/${pci}-render`));
+ await NodeFSP.symlink(`../${node}`, NodePath.join(root, `dev/dri/by-path/${pci}-card`));
+ await write(`sys/class/drm/${node}/device/vendor`, `0x${vendor}\n`);
+ await write(`sys/class/drm/${node}/device/device`, `0x${device}\n`);
+ await NodeFSP.mkdir(NodePath.join(root, "sys/bus/pci/drivers", driver), { recursive: true });
+ await NodeFSP.symlink(
+ NodePath.join(root, "sys/bus/pci/drivers", driver),
+ NodePath.join(root, `sys/class/drm/${node}/device/driver`),
+ );
+ };
+ await gpu("pci-0000:2b:00.0", "renderD128", "10de", "2504", "nvidia");
+ await gpu("pci-0000:00:02.0", "renderD129", "8086", "a780", "i915");
+ await write(
+ "usr/share/hwdata/pci.ids",
+ [
+ "# comment",
+ "10de NVIDIA Corporation",
+ "\t2503 GA106 [GeForce RTX 3060]",
+ "\t2504 GA106 [GeForce RTX 3060 Lite Hash Rate]",
+ "\t\t1462 397b Subsystem",
+ "10df Emulex Corporation",
+ "\t2504 Not this device",
+ "",
+ ].join("\n"),
+ );
+});
+
+afterAll(async () => {
+ await NodeFSP.rm(root, { recursive: true, force: true });
+});
+
+describe("server browser GPUs", () => {
+ it("lists Linux render nodes by PCI path with names from pci.ids", async () => {
+ expect(await discoverGpus("linux", root)).toEqual([
+ { id: "pci-0000:00:02.0", name: "Intel a780", driver: "i915" },
+ {
+ id: "pci-0000:2b:00.0",
+ name: "NVIDIA Corporation GA106 [GeForce RTX 3060 Lite Hash Rate]",
+ driver: "nvidia",
+ },
+ ]);
+ expect(await discoverGpus("darwin", root)).toEqual([]);
+ });
+
+ it("keeps software rendering unless a GPU that exists is chosen", async () => {
+ const enabled = [
+ "--enable-gpu",
+ "--ignore-gpu-blocklist",
+ "--use-gl=angle",
+ "--use-angle=gl-egl",
+ ];
+ expect(await gpuLaunchArgs("software", "linux", root)).toEqual(["--disable-gpu"]);
+ expect(await gpuLaunchArgs("auto", "linux", root)).toEqual(enabled);
+ expect(await gpuLaunchArgs("auto", "win32", root)).toEqual([
+ "--enable-gpu",
+ "--ignore-gpu-blocklist",
+ ]);
+ expect(await gpuLaunchArgs("pci-0000:2b:00.0", "linux", root)).toEqual([
+ ...enabled,
+ `--render-node-override=${NodePath.join(root, "dev/dri/by-path/pci-0000:2b:00.0-render")}`,
+ ]);
+ // A removed GPU or a malformed id must not reach Chromium's command line.
+ expect(await gpuLaunchArgs("pci-0000:99:00.0", "linux", root)).toEqual(["--disable-gpu"]);
+ expect(await gpuLaunchArgs("pci-0000:2b:00.0 --no-sandbox", "linux", root)).toEqual([
+ "--disable-gpu",
+ ]);
+ });
+});
diff --git a/apps/server/src/preview/ServerBrowserGpus.ts b/apps/server/src/preview/ServerBrowserGpus.ts
new file mode 100644
index 0000000000000..885fa8c0c41d3
--- /dev/null
+++ b/apps/server/src/preview/ServerBrowserGpus.ts
@@ -0,0 +1,95 @@
+// @effect-diagnostics nodeBuiltinImport:off - Reads sysfs and devfs for Chromium launch flags outside the Effect runtime.
+import {
+ DEFAULT_SERVER_BROWSER_GPU,
+ type ServerBrowserGpu,
+ type ServerBrowserGpuDevice,
+} from "@t3tools/contracts";
+import * as NodeFSP from "node:fs/promises";
+import * as NodePath from "node:path";
+
+// A GPU is named by its PCI path, which survives render nodes renumbering across boots.
+const RENDER_NODE_SUFFIX = "-render";
+const PCI_PATH = /^pci-[0-9a-f]{4}:[0-9a-f]{2}:[0-9a-f]{2}\.[0-9a-f]$/;
+const PCI_ID_FILES = ["usr/share/hwdata/pci.ids", "usr/share/misc/pci.ids"];
+const VENDORS: Record = { "10de": "NVIDIA", "1002": "AMD", "8086": "Intel" };
+
+const readTrimmed = (path: string) =>
+ NodeFSP.readFile(path, "utf8").then(
+ (text) => text.trim(),
+ () => null,
+ );
+
+const pciNames = async (root: string, vendor: string, device: string) => {
+ for (const file of PCI_ID_FILES) {
+ const text = await NodeFSP.readFile(NodePath.join(root, file), "utf8").catch(() => null);
+ if (text === null) continue;
+ let vendorName: string | null = null;
+ for (const line of text.split("\n")) {
+ if (vendorName === null) {
+ if (line.startsWith(`${vendor} `)) vendorName = line.slice(6);
+ } else if (line.startsWith(`\t${device} `)) {
+ return { vendor: vendorName, device: line.slice(7) };
+ } else if (line !== "" && !line.startsWith("\t") && !line.startsWith("#")) break;
+ }
+ return vendorName === null ? null : { vendor: vendorName, device: null };
+ }
+ return null;
+};
+
+/** Lists Linux GPUs Chromium can render on. Other platforms only choose software or automatic. */
+export const discoverGpus = async (
+ platform: NodeJS.Platform,
+ root = "/",
+): Promise> => {
+ if (platform !== "linux") return [];
+ const byPath = NodePath.join(root, "dev/dri/by-path");
+ const entries = await NodeFSP.readdir(byPath).catch(() => []);
+ const gpus: Array = [];
+ for (const entry of entries.toSorted()) {
+ if (!entry.endsWith(RENDER_NODE_SUFFIX)) continue;
+ const id = entry.slice(0, -RENDER_NODE_SUFFIX.length);
+ if (!PCI_PATH.test(id)) continue;
+ const node = NodePath.basename(
+ await NodeFSP.readlink(NodePath.join(byPath, entry)).catch(() => ""),
+ );
+ const device = NodePath.join(root, "sys/class/drm", node, "device");
+ const vendorId = (await readTrimmed(NodePath.join(device, "vendor")))?.replace(/^0x/, "");
+ const deviceId = (await readTrimmed(NodePath.join(device, "device")))?.replace(/^0x/, "");
+ const driverLink = await NodeFSP.readlink(NodePath.join(device, "driver")).catch(() => null);
+ const names = vendorId && deviceId ? await pciNames(root, vendorId, deviceId) : null;
+ const vendor = names?.vendor ?? (vendorId ? VENDORS[vendorId] : undefined) ?? "GPU";
+ gpus.push({
+ id,
+ name: names?.device ? `${vendor} ${names.device}` : `${vendor} ${deviceId ?? id}`,
+ driver: driverLink ? NodePath.basename(driverLink) : null,
+ });
+ }
+ return gpus;
+};
+
+/**
+ * Chromium flags for a GPU setting. Software keeps the CPU rasterizer; a GPU that is no longer
+ * present falls back to it rather than to whichever GPU Chromium would pick.
+ */
+export const gpuLaunchArgs = async (
+ gpu: ServerBrowserGpu,
+ platform: NodeJS.Platform,
+ root = "/",
+): Promise> => {
+ const software = ["--disable-gpu"];
+ if (gpu === DEFAULT_SERVER_BROWSER_GPU) return software;
+ // Headless Chromium otherwise keeps SwiftShader on Linux even with the GPU enabled.
+ const enabled = [
+ "--enable-gpu",
+ "--ignore-gpu-blocklist",
+ ...(platform === "linux" ? ["--use-gl=angle", "--use-angle=gl-egl"] : []),
+ ];
+ if (gpu === "auto") return enabled;
+ if (platform !== "linux" || !PCI_PATH.test(gpu)) return software;
+ const node = NodePath.join(root, "dev/dri/by-path", `${gpu}${RENDER_NODE_SUFFIX}`);
+ const present = await NodeFSP.access(node).then(
+ () => true,
+ () => false,
+ );
+ return present ? [...enabled, `--render-node-override=${node}`] : software;
+};
diff --git a/apps/server/src/preview/ServerBrowserPage.ts b/apps/server/src/preview/ServerBrowserPage.ts
index 9525ac7c5b579..e5a2a39a86768 100644
--- a/apps/server/src/preview/ServerBrowserPage.ts
+++ b/apps/server/src/preview/ServerBrowserPage.ts
@@ -898,6 +898,89 @@ export const parseNetError = (errorText: string) => {
return { description, code: NET_ERROR_CODES[description] ?? -2 };
};
+export interface VideoEncoderWindow {
+ __t3Video: {
+ pick(codecs: ReadonlyArray): Promise;
+ requestKeyFrame(): void;
+ encode(jpeg: string): Promise<{
+ key: boolean;
+ data: string;
+ width: number;
+ height: number;
+ } | null>;
+ };
+}
+
+// WebCodecs only exists in secure contexts, and a scratch page starts on about:blank.
+export const VIDEO_ENCODER_URL = "https://video-encoder.t3.invalid/";
+
+/** Re-encodes a viewer's JPEG screencast as video; resolves null when rate control drops a frame. */
+export const videoEncoderScript = `(() => {
+ let encoder = null;
+ let size = null;
+ let key = true;
+ let sink = null;
+ let codec = null;
+ const configFor = (codec, width, height) => ({
+ codec,
+ width,
+ height,
+ bitrate: Math.round(Math.min(12e6, Math.max(2e6, width * height * 2))),
+ framerate: 30,
+ latencyMode: "realtime",
+ ...(codec.startsWith("avc1") ? { avc: { format: "annexb" } } : {}),
+ });
+ window.__t3Video = {
+ async pick(codecs) {
+ for (const candidate of codecs) {
+ const support = await VideoEncoder.isConfigSupported(configFor(candidate, 1280, 720)).catch(() => null);
+ if (support && support.supported) return (codec = candidate);
+ }
+ return null;
+ },
+ requestKeyFrame() {
+ key = true;
+ },
+ async encode(jpeg) {
+ const decoder = new ImageDecoder({ data: Uint8Array.fromBase64(jpeg), type: "image/jpeg" });
+ const { image } = await decoder.decode().finally(() => decoder.close());
+ // 4:2:0 video needs even dimensions; the odd edge pixel is dropped.
+ const width = image.displayWidth & ~1;
+ const height = image.displayHeight & ~1;
+ try {
+ if (!encoder || encoder.state === "closed" || size.width !== width || size.height !== height) {
+ if (encoder && encoder.state !== "closed") encoder.close();
+ encoder = new VideoEncoder({ output: (chunk) => sink && sink.push(chunk), error: () => {} });
+ encoder.configure(configFor(codec, width, height));
+ size = { width, height };
+ key = true;
+ }
+ const chunks = [];
+ sink = chunks;
+ const frame = new VideoFrame(image, {
+ timestamp: Math.round(performance.now() * 1000),
+ visibleRect: { x: 0, y: 0, width, height },
+ });
+ encoder.encode(frame, { keyFrame: key });
+ frame.close();
+ await encoder.flush();
+ sink = null;
+ if (chunks.length === 0) return null;
+ key = false;
+ const bytes = new Uint8Array(chunks.reduce((total, chunk) => total + chunk.byteLength, 0));
+ let offset = 0;
+ for (const chunk of chunks) {
+ chunk.copyTo(bytes.subarray(offset));
+ offset += chunk.byteLength;
+ }
+ return { key: chunks[0].type === "key", data: bytes.toBase64(), width, height };
+ } finally {
+ image.close();
+ }
+ },
+ };
+})()`;
+
export const recordingEncoderScript = (frameRate: BrowserRecordingFrameRate) => `(() => {
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
diff --git a/apps/server/src/preview/ServerBrowserStream.test.ts b/apps/server/src/preview/ServerBrowserStream.test.ts
index d3f4781829a85..c41db3afecc3f 100644
--- a/apps/server/src/preview/ServerBrowserStream.test.ts
+++ b/apps/server/src/preview/ServerBrowserStream.test.ts
@@ -78,6 +78,7 @@ it.effect.each([
const inputs: unknown[] = [];
const attachments: Parameters[0][] = [];
const acked = Promise.withResolvers();
+ const keyFrameRequested = Promise.withResolvers();
const frame = new Uint8Array([255, 216, 255, 217]);
const output = yield* Queue.make();
yield* Queue.offer(output, { _tag: "viewport", width: 1280, height: 800 });
@@ -89,6 +90,7 @@ it.effect.each([
const browser = ServerBrowser.ServerBrowser.of({
clearProfile: () => Effect.void,
reportProfiles: () => Effect.void,
+ listGpus: Effect.succeed({ gpus: [] }),
openDownload: () => Effect.succeedNone,
answerFileChooser: () => Effect.succeed(false),
attachViewer: (input) =>
@@ -97,6 +99,7 @@ it.effect.each([
return {
output,
input: (message) => Effect.sync(() => void inputs.push(message)),
+ requestKeyFrame: Effect.sync(() => keyFrameRequested.resolve()),
};
}),
});
@@ -111,7 +114,7 @@ it.effect.each([
);
const server = Context.get(services, HttpServer.HttpServer);
const origin = HttpServer.formatAddress(server.address).replace(/^http/, "ws");
- const resource = `/api/preview-stream/ws?threadId=thread&tabId=tab&wsTicket=one-use-ticket${interactive ? "" : "&interactive=false"}`;
+ const resource = `/api/preview-stream/ws?threadId=thread&tabId=tab&codecs=vp8,hevc&wsTicket=one-use-ticket${interactive ? "" : "&interactive=false"}`;
const received = Promise.withResolvers();
const socket = yield* Effect.acquireRelease(
Effect.sync(() => new WebSocket(`${origin}${resource}`)),
@@ -129,12 +132,15 @@ it.effect.each([
frames.push(new Uint8Array(event.data as ArrayBuffer));
for (const message of mutations) socket.send(JSON.stringify(message));
socket.send("malformed input");
+ // Read-only viewers decode video too, so key frame requests skip the control check.
+ socket.send(JSON.stringify({ type: "keyFrame" }));
socket.send(JSON.stringify({ type: "ack" }));
received.resolve();
});
yield* Effect.promise(() => received.promise);
// The socket ack follows every mutation, providing a barrier without sleeps.
yield* Effect.promise(() => acked.promise);
+ yield* Effect.promise(() => keyFrameRequested.promise);
expect(frames).toEqual([frame]);
expect(viewports).toEqual([{ type: "viewport", width: 1280, height: 800 }]);
expect(inputs).toEqual(canOperate ? [...mutations, null] : []);
@@ -146,84 +152,141 @@ it.effect.each([
maxHeight: 800,
quality: 70,
canOperate,
+ videoCodecs: ["vp8"],
},
]);
expect(auth.requests).toEqual([resource]);
}).pipe(Effect.scoped),
);
-it.effect("sends replies ahead of stale frames and only the newest frame after an ack", () =>
- Effect.gen(function* () {
- const output = yield* Queue.make();
- const released: number[] = [];
- const frame = (id: number): ServerBrowser.ServerBrowserViewerOutput => ({
- _tag: "frame",
- data: new Uint8Array([id]),
- ack: Effect.sync(() => void released.push(id)),
- });
- const browser = ServerBrowser.ServerBrowser.of({
- clearProfile: () => Effect.void,
- reportProfiles: () => Effect.void,
- openDownload: () => Effect.succeedNone,
- answerFileChooser: () => Effect.succeed(false),
- attachViewer: () => Effect.succeed({ output, input: () => Effect.void }),
- });
- const services = yield* Layer.build(
- HttpRouter.serve(
- routeLayer.pipe(
- Layer.provide(Layer.succeed(ServerBrowser.ServerBrowser, browser)),
- Layer.provide(platformLayer),
- ),
- { disableListenLog: true },
- ).pipe(
- Layer.provideMerge(NodeHttpServer.layerTest),
- Layer.provide(makeAuth([AuthOrchestrationReadScope]).layer),
+const openFrameStream = Effect.fnUntraced(function* (
+ output: Queue.Queue,
+) {
+ const browser = ServerBrowser.ServerBrowser.of({
+ clearProfile: () => Effect.void,
+ reportProfiles: () => Effect.void,
+ listGpus: Effect.succeed({ gpus: [] }),
+ openDownload: () => Effect.succeedNone,
+ answerFileChooser: () => Effect.succeed(false),
+ attachViewer: () =>
+ Effect.succeed({ output, input: () => Effect.void, requestKeyFrame: Effect.void }),
+ });
+ const services = yield* Layer.build(
+ HttpRouter.serve(
+ routeLayer.pipe(
+ Layer.provide(Layer.succeed(ServerBrowser.ServerBrowser, browser)),
+ Layer.provide(platformLayer),
),
+ { disableListenLog: true },
+ ).pipe(
+ Layer.provideMerge(NodeHttpServer.layerTest),
+ Layer.provide(makeAuth([AuthOrchestrationReadScope]).layer),
+ ),
+ );
+ const server = Context.get(services, HttpServer.HttpServer);
+ const origin = HttpServer.formatAddress(server.address).replace(/^http/, "ws");
+ const received: Array = [];
+ const waiters: Array<{ count: number; resolve: () => void }> = [];
+ const socket = yield* Effect.acquireRelease(
+ Effect.sync(
+ () =>
+ new WebSocket(
+ `${origin}/api/preview-stream/ws?threadId=thread&tabId=tab&wsTicket=one-use-ticket`,
+ ),
+ ),
+ (socket) => Effect.sync(() => socket.close()),
+ );
+ socket.binaryType = "arraybuffer";
+ socket.addEventListener("message", (event) => {
+ received.push(
+ typeof event.data === "string"
+ ? JSON.parse(event.data).type
+ : new Uint8Array(event.data as ArrayBuffer)[0]!,
);
- const server = Context.get(services, HttpServer.HttpServer);
- const origin = HttpServer.formatAddress(server.address).replace(/^http/, "ws");
- const received: Array = [];
- let next = Promise.withResolvers();
- const socket = yield* Effect.acquireRelease(
- Effect.sync(
- () =>
- new WebSocket(
- `${origin}/api/preview-stream/ws?threadId=thread&tabId=tab&wsTicket=one-use-ticket`,
- ),
- ),
- (socket) => Effect.sync(() => socket.close()),
+ for (const waiter of waiters.filter((waiter) => received.length >= waiter.count)) {
+ waiters.splice(waiters.indexOf(waiter), 1);
+ waiter.resolve();
+ }
+ });
+ const receivedCount = (count: number) =>
+ Effect.promise(
+ () =>
+ new Promise((resolve) =>
+ received.length >= count ? resolve() : waiters.push({ count, resolve }),
+ ),
);
- socket.binaryType = "arraybuffer";
- socket.addEventListener("message", (event) => {
- received.push(
- typeof event.data === "string"
- ? JSON.parse(event.data).type
- : new Uint8Array(event.data as ArrayBuffer)[0]!,
- );
- next.resolve();
- });
+ const ack = Effect.sync(() => socket.send(JSON.stringify({ type: "ack" })));
+ return { received, receivedCount, ack };
+});
+
+it.effect("sends replies ahead of a large frame and only the newest frame after its ack", () =>
+ Effect.gen(function* () {
+ const output = yield* Queue.make();
+ const released: number[] = [];
+ // Past the in-flight byte budget, so each frame travels alone.
+ const frame = (id: number): ServerBrowser.ServerBrowserViewerOutput => {
+ const data = new Uint8Array(128 * 1024);
+ data[0] = id;
+ return { _tag: "frame", data, ack: Effect.sync(() => void released.push(id)) };
+ };
+ const stream = yield* openFrameStream(output);
yield* Queue.offer(output, frame(1));
- yield* Effect.promise(() => next.promise);
- next = Promise.withResolvers();
+ yield* stream.receivedCount(1);
yield* Queue.offerAll(output, [
frame(2),
frame(3),
frame(4),
{ _tag: "probe", x: 0, y: 0, editable: false },
]);
- yield* Effect.promise(() => next.promise);
- expect(received).toEqual([1, "probe"]);
+ yield* stream.receivedCount(2);
+ expect(stream.received).toEqual([1, "probe"]);
expect(released).toEqual([2, 3]);
- next = Promise.withResolvers();
- socket.send(JSON.stringify({ type: "ack" }));
- yield* Effect.promise(() => next.promise);
- expect(received).toEqual([1, "probe", 4]);
+ yield* stream.ack;
+ yield* stream.receivedCount(3);
+ expect(stream.received).toEqual([1, "probe", 4]);
expect(released).toEqual([2, 3, 1]);
}).pipe(Effect.scoped),
);
+it.effect("keeps several small frames in flight and encodes waiting frames only when sent", () =>
+ Effect.gen(function* () {
+ const output = yield* Queue.make();
+ const released: number[] = [];
+ const encoded: number[] = [];
+ const frame = (id: number): ServerBrowser.ServerBrowserViewerOutput => ({
+ _tag: "frame",
+ data: Effect.sync(() => {
+ encoded.push(id);
+ return new Uint8Array([id]);
+ }),
+ ack: Effect.sync(() => void released.push(id)),
+ });
+ const stream = yield* openFrameStream(output);
+
+ // A distant viewer gets more than one frame per round trip.
+ yield* Queue.offerAll(output, [1, 2, 3, 4, 5, 6].map(frame));
+ yield* stream.receivedCount(6);
+ yield* Queue.offerAll(output, [
+ frame(7),
+ frame(8),
+ { _tag: "probe", x: 0, y: 0, editable: false },
+ ]);
+ yield* stream.receivedCount(7);
+ expect(stream.received).toEqual([1, 2, 3, 4, 5, 6, "probe"]);
+ // Superseded before it was sent, so it was never encoded.
+ expect(released).toEqual([7]);
+ expect(encoded).toEqual([1, 2, 3, 4, 5, 6]);
+
+ yield* stream.ack;
+ yield* stream.receivedCount(8);
+ expect(stream.received).toEqual([1, 2, 3, 4, 5, 6, "probe", 8]);
+ expect(released).toEqual([7, 1]);
+ expect(encoded).toEqual([1, 2, 3, 4, 5, 6, 8]);
+ }).pipe(Effect.scoped),
+);
+
it.effect.each([
{ scopes: [], error: undefined, status: 403 },
{ scopes: [AuthOrchestrationOperateScope], error: undefined, status: 403 },
@@ -235,6 +298,7 @@ it.effect.each([
const browser = ServerBrowser.ServerBrowser.of({
clearProfile: () => Effect.void,
reportProfiles: () => Effect.void,
+ listGpus: Effect.succeed({ gpus: [] }),
openDownload: () => Effect.succeedNone,
answerFileChooser: () => Effect.succeed(false),
attachViewer: () => {
@@ -276,6 +340,7 @@ it.effect("serves a tab's download only to an authorized session", () =>
const browser = ServerBrowser.ServerBrowser.of({
clearProfile: () => Effect.void,
reportProfiles: () => Effect.void,
+ listGpus: Effect.succeed({ gpus: [] }),
openDownload: (input) =>
Effect.sync(() => {
requests.push(input);
@@ -324,6 +389,7 @@ it.effect("passes uploaded files to the page's open picker and needs operate sco
const browser = ServerBrowser.ServerBrowser.of({
clearProfile: () => Effect.void,
reportProfiles: () => Effect.void,
+ listGpus: Effect.succeed({ gpus: [] }),
openDownload: () => Effect.succeedNone,
answerFileChooser: (input) =>
Effect.sync(() => {
@@ -393,6 +459,7 @@ it.effect.each([
const browser = ServerBrowser.ServerBrowser.of({
clearProfile: () => Effect.void,
reportProfiles: () => Effect.void,
+ listGpus: Effect.succeed({ gpus: [] }),
openDownload: () => Effect.succeedNone,
answerFileChooser: () => Effect.succeed(false),
attachViewer: () => Effect.fail(new ServerBrowser.ServerBrowserLaunchError({ cause: error })),
diff --git a/apps/server/src/preview/ServerBrowserStream.ts b/apps/server/src/preview/ServerBrowserStream.ts
index 8d8164cd911c4..38a2680cac506 100644
--- a/apps/server/src/preview/ServerBrowserStream.ts
+++ b/apps/server/src/preview/ServerBrowserStream.ts
@@ -3,6 +3,7 @@ import {
AuthOrchestrationReadScope,
AuthPreviewOperateScope,
PREVIEW_STREAM_HOST_SETUP_CLOSE_CODE,
+ PREVIEW_STREAM_VIDEO_CODECS,
PreviewStreamHostSetup,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
@@ -30,6 +31,10 @@ const TAB_GONE_CODE = 4404;
const DEFAULT_QUALITY = 70;
const MAX_SOCKET_BUFFER_BYTES = 8 * 1024 * 1024;
+// One frame per round trip caps a distant viewer's frame rate, so small frames share a window.
+// A frame this large still travels alone, keeping replies from queueing behind images.
+const MAX_FRAMES_IN_FLIGHT = 6;
+const MAX_BYTES_IN_FLIGHT = 128 * 1024;
const textDecoder = new TextDecoder();
const intParam = (params: URLSearchParams, name: string, fallback: number, max: number) => {
@@ -39,8 +44,15 @@ const intParam = (params: URLSearchParams, name: string, fallback: number, max:
type Frame = Extract;
-const isAck = (message: unknown) =>
- typeof message === "object" && message !== null && "type" in message && message.type === "ack";
+const messageType = (message: unknown) =>
+ typeof message === "object" && message !== null && "type" in message ? message.type : undefined;
+
+const videoCodecsParam = (params: URLSearchParams) => {
+ const requested = params.get("codecs")?.split(",") ?? [];
+ return requested.filter((codec): codec is (typeof PREVIEW_STREAM_VIDEO_CODECS)[number] =>
+ PREVIEW_STREAM_VIDEO_CODECS.some((supported) => supported === codec),
+ );
+};
const parseMessage = (chunk: Uint8Array | string): unknown => {
try {
@@ -88,6 +100,7 @@ const makeHandler = Effect.fnUntraced(function* (browser: ServerBrowser.ServerBr
maxWidth: intParam(params, "maxWidth", 1280, 7680),
maxHeight: intParam(params, "maxHeight", 800, 4320),
quality: intParam(params, "quality", DEFAULT_QUALITY, 100),
+ videoCodecs: videoCodecsParam(params),
})
.pipe(
Effect.map((viewer) => ({ _tag: "attached" as const, viewer })),
@@ -124,11 +137,16 @@ const makeHandler = Effect.fnUntraced(function* (browser: ServerBrowser.ServerBr
}
const viewer = attached.viewer;
// `write` returns once the frame is queued, so Chromium's ack for each
- // frame waits for the viewer's `ack` message instead. Only one frame
- // is on the wire and only the newest waits behind it, so replies never
+ // frame waits for the viewer's `ack` message instead. Frames on the wire
+ // are bounded and only the newest waits behind them, so replies never
// queue behind stale images on a slow link.
- let inFlight: Effect.Effect | null = null;
+ const inFlight: Array<{ readonly ack: Effect.Effect; bytes: number }> = [];
+ let bytesInFlight = 0;
let pending: Frame | null = null;
+ const hasRoom = () =>
+ inFlight.length === 0 ||
+ (inFlight.length < MAX_FRAMES_IN_FLIGHT && bytesInFlight < MAX_BYTES_IN_FLIGHT);
+ const outgoing = yield* Queue.unbounded<{ frame: Frame; slot: (typeof inFlight)[number] }>();
const disconnectSlowViewer = Effect.sync(() => transport.destroy()).pipe(
Effect.andThen(Effect.interrupt),
);
@@ -140,15 +158,40 @@ const makeHandler = Effect.fnUntraced(function* (browser: ServerBrowser.ServerBr
}
return writer.write(data);
});
- const sendFrame = (frame: Frame) => {
- inFlight = frame.ack;
- return write(frame.data);
- };
+ const sendFrame = (frame: Frame) =>
+ Effect.sync(() => {
+ const slot = { ack: frame.ack, bytes: 0 };
+ inFlight.push(slot);
+ Queue.offerUnsafe(outgoing, { frame, slot });
+ });
+ const sendPending = Effect.suspend(() => {
+ const next = pending;
+ if (next === null || !hasRoom()) return Effect.void;
+ pending = null;
+ return sendFrame(next);
+ });
+ // Video frames encode in order as they go out, so one fiber writes every frame.
+ const sendFrames = Queue.take(outgoing).pipe(
+ Effect.flatMap(({ frame, slot }) =>
+ Effect.gen(function* () {
+ const data = frame.data instanceof Uint8Array ? frame.data : yield* frame.data;
+ if (data !== null) {
+ slot.bytes = data.byteLength;
+ bytesInFlight += data.byteLength;
+ return yield* write(data);
+ }
+ // The encoder dropped it, so no ack will come.
+ inFlight.splice(inFlight.indexOf(slot), 1);
+ yield* Effect.forkScoped(slot.ack);
+ yield* sendPending;
+ }),
+ ),
+ );
const sendOutput = Queue.take(viewer.output).pipe(
Effect.flatMap((output) => {
switch (output._tag) {
case "frame": {
- if (inFlight === null) return sendFrame(output);
+ if (hasRoom()) return sendFrame(output);
const superseded = pending;
pending = output;
// Never sent, but Chromium still waits for its ack.
@@ -178,26 +221,27 @@ const makeHandler = Effect.fnUntraced(function* (browser: ServerBrowser.ServerBr
// Incoming messages share the session span; frame acknowledgements are frequent.
const receive = Effect.fnUntraced(function* (chunk: Uint8Array | string) {
const message = parseMessage(chunk);
+ const type = messageType(message);
+ if (type === "keyFrame") return yield* Effect.forkScoped(viewer.requestKeyFrame);
// Ownership serializes actions in the service. Keep reading so dialog
// replies and takeover can unblock an action already waiting on the page.
- if (!isAck(message))
+ if (type !== "ack")
return yield* canOperate
? viewer.input(message).pipe(Effect.forkScoped, Effect.asVoid)
: Effect.void;
- const ack = inFlight;
- const next = pending;
- inFlight = null;
- pending = null;
+ const slot = inFlight.shift();
+ if (slot) bytesInFlight -= slot.bytes;
// Forked: Chromium acks are paced and must not hold up input.
- return yield* Effect.andThen(
- ack ? Effect.forkScoped(ack) : Effect.void,
- next ? sendFrame(next) : Effect.void,
- );
+ if (slot) yield* Effect.forkScoped(slot.ack);
+ return yield* sendPending;
});
const receiveInput = reader.pull.pipe(
Effect.flatMap((chunks) => Effect.forEach(chunks, receive, { discard: true })),
);
- return yield* Effect.raceFirst(Effect.forever(sendOutput), Effect.forever(receiveInput));
+ return yield* Effect.raceFirst(
+ Effect.forever(sendOutput),
+ Effect.raceFirst(Effect.forever(receiveInput), Effect.forever(sendFrames)),
+ );
}),
).pipe(
Effect.catchTags({
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index 34eb11815b13f..56898f9ccfb33 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -3014,6 +3014,7 @@ export const layerWsRpc = (
[WS_METHODS.previewClose]: (input) => previewManager.close(input),
[WS_METHODS.previewList]: (input) => previewManager.list(input),
[WS_METHODS.previewClearProfile]: (input) => serverBrowser.clearProfile(input.profileId),
+ [WS_METHODS.previewListGpus]: () => serverBrowser.listGpus,
[WS_METHODS.previewReportProfiles]: (input) => serverBrowser.reportProfiles(input),
[WS_METHODS.previewReportStatus]: (input) => previewManager.reportStatus(input),
[WS_METHODS.subscribePreviewEvents]: (_input) => previewManager.events,
diff --git a/apps/web/src/browser/ServerBrowserSurface.tsx b/apps/web/src/browser/ServerBrowserSurface.tsx
index c6ad2f51c3f31..9f41d6497ae97 100644
--- a/apps/web/src/browser/ServerBrowserSurface.tsx
+++ b/apps/web/src/browser/ServerBrowserSurface.tsx
@@ -359,17 +359,21 @@ export function ServerBrowserSurface(props: {
const canvas = canvasRef.current;
if (!visible || accessDenied || hostSetup || !access || !cap || !canvas) return;
let refreshTimer: ReturnType | null = null;
- const painter = createPreviewFramePainter(canvas, () => {
- if (hasFrameRef.current) return;
- hasFrameRef.current = true;
- firstFrame();
- });
+ const painter = createPreviewFramePainter(
+ canvas,
+ () => {
+ if (hasFrameRef.current) return;
+ hasFrameRef.current = true;
+ firstFrame();
+ },
+ () => client.requestKeyFrame(),
+ );
const client = createPreviewStreamClient(
{ access, threadId, tabId, maxWidth: cap.width, maxHeight: cap.height },
{
- onFrame: (jpeg) => {
+ onFrame: (frame) => {
unauthorizedRef.current = 0;
- painter.paint(jpeg);
+ painter.paint(frame);
},
onProbe: (result) => {
if (controlRef.current?.controller !== "you") return;
diff --git a/apps/web/src/browser/serverPictureInPicture.ts b/apps/web/src/browser/serverPictureInPicture.ts
index fda9ec7fa7294..686eb46d191e9 100644
--- a/apps/web/src/browser/serverPictureInPicture.ts
+++ b/apps/web/src/browser/serverPictureInPicture.ts
@@ -89,8 +89,8 @@ export async function openServerPictureInPicture(input: {
"position:fixed;right:0;bottom:0;width:1px;height:1px;opacity:0;pointer-events:none";
document.body.append(video);
- const painter = createPreviewFramePainter(canvas);
let client: PreviewStreamClient | null = null;
+ const painter = createPreviewFramePainter(canvas, undefined, () => client?.requestKeyFrame());
let stopped = false;
let refusals = 0;
let retryTimer: ReturnType | null = null;
@@ -115,9 +115,9 @@ export async function openServerPictureInPicture(input: {
interactive: false,
},
{
- onFrame: (jpeg) => {
+ onFrame: (frame) => {
refusals = 0;
- painter.paint(jpeg);
+ painter.paint(frame);
},
onViewport: () => undefined,
onConnectedChange: () => undefined,
diff --git a/apps/web/src/components/settings/BrowserRenderingSettings.tsx b/apps/web/src/components/settings/BrowserRenderingSettings.tsx
new file mode 100644
index 0000000000000..6cbcaf9032fc8
--- /dev/null
+++ b/apps/web/src/components/settings/BrowserRenderingSettings.tsx
@@ -0,0 +1,149 @@
+import { useAtomValue } from "@effect/atom-react";
+import {
+ DEFAULT_SERVER_BROWSER_GPU,
+ DEFAULT_SERVER_BROWSER_RENDER_SCALE,
+ type ServerBrowserGpuList,
+ type ServerBrowserRenderScale,
+} from "@t3tools/contracts";
+import { AsyncResult, Atom } from "effect/reactivity";
+
+import { previewEnvironment } from "../../state/preview";
+import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
+import { SettingResetButton, SettingsRow } from "./settingsLayout";
+import { searchableSetting } from "./settingsSearch";
+import { useSettingsScope } from "./SettingsScopeContext";
+import {
+ useScopedSettings,
+ useScopedSettingsMixed,
+ useUpdateScopedSettings,
+} from "./useScopedSettings";
+
+const NO_GPUS_ATOM = Atom.make(AsyncResult.success({ gpus: [] }));
+const RENDER_SCALES: ReadonlyArray = [1, 1.5, 2, 3];
+const APPLIES = "Changing it reloads the open browser tabs on this environment.";
+
+const scaleLabel = (scale: ServerBrowserRenderScale) =>
+ `${scale}×${scale === DEFAULT_SERVER_BROWSER_RENDER_SCALE ? " (default)" : ""}`;
+
+function BrowserGpuSetting() {
+ const { scope, environment } = useSettingsScope();
+ const settings = useScopedSettings();
+ const updateSettings = useUpdateScopedSettings();
+ // GPUs belong to one host, so they are listed only when one environment is selected.
+ const environmentId = scope.environmentIds.length === 1 ? environment?.environmentId : undefined;
+ const discovered = useAtomValue(
+ environmentId ? previewEnvironment.gpus({ environmentId, input: {} }) : NO_GPUS_ATOM,
+ );
+ const gpus = AsyncResult.isSuccess(discovered) ? discovered.value.gpus : [];
+ const current = settings.serverBrowserGpu;
+ const mixed = useScopedSettingsMixed(["serverBrowserGpu"]);
+ const options = [
+ { value: DEFAULT_SERVER_BROWSER_GPU, label: "Software (default)" },
+ { value: "auto", label: "Automatic" },
+ ...gpus.map((gpu) => ({
+ value: gpu.id,
+ label: gpu.driver ? `${gpu.name} (${gpu.driver})` : gpu.name,
+ })),
+ ];
+ // A saved GPU stays selectable while its host is offline or the GPU is gone.
+ if (!options.some((option) => option.value === current)) {
+ options.push({ value: current, label: `${current} (not found)` });
+ }
+ const labelFor = (value: string | null) =>
+ options.find((option) => option.value === value)?.label ?? "Mixed";
+
+ return (
+ updateSettings({ serverBrowserGpu: DEFAULT_SERVER_BROWSER_GPU })}
+ />
+ ) : null
+ }
+ control={
+
+ }
+ />
+ );
+}
+
+function BrowserRenderScaleSetting() {
+ const settings = useScopedSettings();
+ const updateSettings = useUpdateScopedSettings();
+ const current = settings.serverBrowserRenderScale;
+ const mixed = useScopedSettingsMixed(["serverBrowserRenderScale"]);
+
+ return (
+
+ updateSettings({ serverBrowserRenderScale: DEFAULT_SERVER_BROWSER_RENDER_SCALE })
+ }
+ />
+ ) : null
+ }
+ control={
+
+ }
+ />
+ );
+}
+
+export function BrowserRenderingSettings() {
+ return (
+ <>
+
+
+ >
+ );
+}
diff --git a/apps/web/src/components/settings/IntegrationsSettings.tsx b/apps/web/src/components/settings/IntegrationsSettings.tsx
index 5239f57bfdc37..6c86d7470ad47 100644
--- a/apps/web/src/components/settings/IntegrationsSettings.tsx
+++ b/apps/web/src/components/settings/IntegrationsSettings.tsx
@@ -110,6 +110,7 @@ import {
SettingsRow,
SettingsSection,
} from "./settingsLayout";
+import { BrowserRenderingSettings } from "./BrowserRenderingSettings";
import { searchableSetting } from "./settingsSearch";
import { AdvancedSettings } from "./AdvancedSettings";
import { useSettingsScope } from "./SettingsScopeContext";
@@ -1555,6 +1556,9 @@ export function BrowserSettingsPanel() {
+
+
+
diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts
index 641a29aaede6a..13fe5ecc1be55 100644
--- a/apps/web/src/components/settings/settingsSearch.ts
+++ b/apps/web/src/components/settings/settingsSearch.ts
@@ -868,6 +868,22 @@ export const SETTINGS_SEARCH_ITEMS = [
scope: "project-defaults",
searchTerms: ["allow disable enable open drive preview tools sessions project override"],
},
+ {
+ id: "browser-render-gpu",
+ title: "Browser GPU",
+ to: "/settings/browser",
+ scope: "environment-defaults",
+ searchTerms: [
+ "graphics card hardware acceleration render node nvidia amd intel software swiftshader",
+ ],
+ },
+ {
+ id: "browser-render-scale",
+ title: "Browser render scale",
+ to: "/settings/browser",
+ scope: "environment-defaults",
+ searchTerms: ["device pixel ratio dpr resolution sharp hidpi retina 1x 2x"],
+ },
{
id: "device-sources",
title: "Device sources",
diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md
index eca8907e87e14..a6c0a34fe26ce 100644
--- a/docs/user/remote-access.md
+++ b/docs/user/remote-access.md
@@ -239,6 +239,12 @@ On a phone, tap the floating preview's corner dot to show its controls, then
**Pop into separate window** to keep watching in picture-in-picture over other
apps.
+The host draws tabs on its CPU at 2× by default. If scrolling or animation is
+choppy and the host has a GPU, pick it under **Settings → Browser → Browser GPU**
+for that environment; Linux hosts list each GPU, other hosts offer
+**Automatic**. **Browser render scale** trades sharpness for speed. Changing
+either reloads the environment's open tabs.
+
### Browser host setup
macOS, Windows, and Linux desktops run the browser as is. Some Linux hosts need
diff --git a/packages/client-runtime/src/preview/serverBrowserStream.ts b/packages/client-runtime/src/preview/serverBrowserStream.ts
index b71fff335f881..5ecfa5b2fc919 100644
--- a/packages/client-runtime/src/preview/serverBrowserStream.ts
+++ b/packages/client-runtime/src/preview/serverBrowserStream.ts
@@ -1,7 +1,9 @@
// @effect-diagnostics globalTimers:off globalFetch:off - This browser and WebView transport runs without an Effect runtime.
import { type DeviceHubAccess, withDeviceHubQuery } from "../device/hubAccess.ts";
import {
+ decodePreviewStreamFrame,
PREVIEW_STREAM_HOST_SETUP_CLOSE_CODE,
+ PREVIEW_STREAM_VIDEO_CODECS,
type PreviewStreamHostSetup,
type PreviewViewportSetting,
} from "@t3tools/contracts";
@@ -183,7 +185,8 @@ export interface PreviewStreamTarget {
}
export interface PreviewStreamEvents {
- readonly onFrame: (jpeg: ArrayBuffer) => void;
+ /** A JPEG or video frame; pass it to a `PreviewFramePainter`. */
+ readonly onFrame: (frame: ArrayBuffer) => void;
readonly onViewport: (viewport: PreviewStreamViewport) => void;
readonly onProbe?: (probe: PreviewStreamProbe) => void;
readonly onPointer?: (pointer: PreviewStreamPointer) => void;
@@ -201,10 +204,24 @@ export interface PreviewStreamEvents {
export interface PreviewStreamClient {
readonly send: (input: PreviewStreamInput) => boolean;
+ /** For a painter whose video decoder failed; the next video frame is then a key frame. */
+ readonly requestKeyFrame: () => void;
readonly stop: () => void;
}
+let decodableVideoCodecs: Promise> | null = null;
+const videoCodecs = () =>
+ (decodableVideoCodecs ??= Promise.all(
+ PREVIEW_STREAM_VIDEO_CODECS.map((codec) =>
+ VideoDecoder.isConfigSupported({ codec, optimizeForLatency: true }).then(
+ (support) => (support.supported ? [codec] : []),
+ () => [],
+ ),
+ ),
+ ).then((supported) => supported.flat()));
+
const ACK_MESSAGE = JSON.stringify({ type: "ack" });
+const KEY_FRAME_MESSAGE = JSON.stringify({ type: "keyFrame" });
export function createPreviewStreamClient(
target: PreviewStreamTarget,
events: PreviewStreamEvents,
@@ -216,7 +233,7 @@ export function createPreviewStreamClient(
maxHeight: String(Math.max(1, Math.round(target.maxHeight))),
});
if (target.interactive === false) query.set("interactive", "false");
- const url = withDeviceHubQuery(`${target.access.wsBase}/ws?${query.toString()}`, target.access);
+ let url = "";
let stopped = false;
let socket: WebSocket | null = null;
let retryTimer: ReturnType | null = null;
@@ -369,7 +386,14 @@ export function createPreviewStreamClient(
ws.addEventListener("error", () => ws.close());
};
- connect();
+ const open = (codecs: ReadonlyArray) => {
+ if (codecs.length > 0) query.set("codecs", codecs.join(","));
+ url = withDeviceHubQuery(`${target.access.wsBase}/ws?${query.toString()}`, target.access);
+ connect();
+ };
+ // WebCodecs is missing in insecure contexts and older WebViews, which keep JPEG frames.
+ if (typeof VideoDecoder === "undefined") open([]);
+ else void videoCodecs().then(open);
return {
send: (input) => {
@@ -379,6 +403,9 @@ export function createPreviewStreamClient(
socket.send(JSON.stringify(input));
return true;
},
+ requestKeyFrame: () => {
+ if (socket?.readyState === WebSocket.OPEN) socket.send(KEY_FRAME_MESSAGE);
+ },
stop: () => {
stopped = true;
if (retryTimer !== null) clearTimeout(retryTimer);
@@ -391,52 +418,99 @@ export function createPreviewStreamClient(
}
export interface PreviewFramePainter {
- readonly paint: (jpeg: ArrayBuffer) => void;
+ readonly paint: (frame: ArrayBuffer) => void;
readonly stop: () => void;
}
-/** One decode at a time, keeping only the latest waiting frame for slow viewers. */
+/**
+ * Paints JPEG and video frames, never letting an older frame cover a newer one. JPEGs decode
+ * one at a time and keep only the latest waiting; every video frame decodes, as each builds on
+ * the last. A failed decoder waits for the key frame `onKeyFrameNeeded` asks for.
+ */
export function createPreviewFramePainter(
canvas: HTMLCanvasElement,
onPainted?: () => void,
+ onKeyFrameNeeded?: () => void,
): PreviewFramePainter {
const context = canvas.getContext("2d");
let stopped = false;
+ let sequence = 0;
+ let painted = -1;
let decoding = false;
- let waiting: ArrayBuffer | null = null;
- const draw = (jpeg: ArrayBuffer) => {
+ let waiting: { readonly order: number; readonly jpeg: Uint8Array } | null = null;
+ let decoder: VideoDecoder | null = null;
+ const show = (order: number, image: CanvasImageSource, width: number, height: number) => {
+ if (stopped || !context || order < painted) return;
+ painted = order;
+ if (canvas.width !== width || canvas.height !== height) {
+ canvas.width = width;
+ canvas.height = height;
+ }
+ context.drawImage(image, 0, 0);
+ onPainted?.();
+ };
+ const drawJpeg = (order: number, jpeg: Uint8Array) => {
decoding = true;
- void createImageBitmap(new Blob([jpeg], { type: "image/jpeg" }))
+ void createImageBitmap(new Blob([jpeg as Uint8Array], { type: "image/jpeg" }))
.then((bitmap) => {
- if (stopped || !context) {
- bitmap.close();
- return;
- }
- if (canvas.width !== bitmap.width || canvas.height !== bitmap.height) {
- canvas.width = bitmap.width;
- canvas.height = bitmap.height;
- }
- context.drawImage(bitmap, 0, 0);
+ show(order, bitmap, bitmap.width, bitmap.height);
bitmap.close();
- onPainted?.();
})
.catch(() => undefined)
.finally(() => {
decoding = false;
const next = waiting;
waiting = null;
- if (next && !stopped) draw(next);
+ if (next && !stopped) drawJpeg(next.order, next.jpeg);
});
};
+ const openDecoder = () =>
+ new VideoDecoder({
+ output: (frame) => {
+ show(frame.timestamp, frame, frame.displayWidth, frame.displayHeight);
+ frame.close();
+ },
+ error: () => resetDecoder(),
+ });
+ const resetDecoder = () => {
+ if (decoder && decoder.state !== "closed") decoder.close();
+ decoder = null;
+ if (!stopped) onKeyFrameNeeded?.();
+ };
return {
- paint: (jpeg) => {
- if (stopped) return;
- if (decoding) waiting = jpeg;
- else draw(jpeg);
+ paint: (data) => {
+ const frame = decodePreviewStreamFrame(new Uint8Array(data));
+ if (stopped || !frame) return;
+ const order = sequence++;
+ if (frame.type === "jpeg") {
+ if (decoding) waiting = { order, jpeg: frame.data };
+ else drawJpeg(order, frame.data);
+ return;
+ }
+ try {
+ if (frame.type === "key") {
+ decoder ??= openDecoder();
+ decoder.configure({
+ codec: frame.codec,
+ codedWidth: frame.width,
+ codedHeight: frame.height,
+ optimizeForLatency: true,
+ });
+ }
+ // Deltas are useless until the key frame after a decoder failure.
+ if (!decoder) return;
+ decoder.decode(
+ new EncodedVideoChunk({ type: frame.type, timestamp: order, data: frame.data }),
+ );
+ } catch {
+ resetDecoder();
+ }
},
stop: () => {
stopped = true;
waiting = null;
+ if (decoder && decoder.state !== "closed") decoder.close();
+ decoder = null;
},
};
}
diff --git a/packages/client-runtime/src/state/preview.ts b/packages/client-runtime/src/state/preview.ts
index 6bef0cc6825ab..ec28f2a9d8162 100644
--- a/packages/client-runtime/src/state/preview.ts
+++ b/packages/client-runtime/src/state/preview.ts
@@ -63,6 +63,11 @@ export function createPreviewEnvironmentAtoms(
scheduler: lifecycleScheduler,
concurrency: lifecycleConcurrency,
}),
+ gpus: createEnvironmentRpcQueryAtomFamily(runtime, {
+ label: "environment-data:preview:gpus",
+ tag: WS_METHODS.previewListGpus,
+ staleTimeMs: 60_000,
+ }),
clearProfile: createEnvironmentRpcCommand(runtime, {
label: "environment-data:preview:clear-profile",
tag: WS_METHODS.previewClearProfile,
diff --git a/packages/contracts/src/preview.test.ts b/packages/contracts/src/preview.test.ts
index 6618646f1f4fb..d1e80b7cbd097 100644
--- a/packages/contracts/src/preview.test.ts
+++ b/packages/contracts/src/preview.test.ts
@@ -1,6 +1,7 @@
import { Schema } from "effect";
import { describe, expect, it } from "vite-plus/test";
+import { decodePreviewStreamFrame, encodePreviewStreamVideoFrame } from "./preview.ts";
import { PreviewAutomationHost, PreviewAutomationStatus } from "./previewAutomation.ts";
const decodeAutomationHost = Schema.decodeUnknownSync(PreviewAutomationHost);
@@ -42,3 +43,32 @@ describe("PreviewAutomationStatus", () => {
).toEqual({ width: 412, height: 915 });
});
});
+
+describe("preview stream frames", () => {
+ it("tells JPEG frames from video frames, which old servers never send", () => {
+ const data = new Uint8Array([9, 8, 7]);
+ const key = encodePreviewStreamVideoFrame({
+ type: "key",
+ codec: "avc1.42E034",
+ width: 1650,
+ height: 1500,
+ data,
+ });
+ expect(decodePreviewStreamFrame(key)).toEqual({
+ type: "key",
+ codec: "avc1.42E034",
+ width: 1650,
+ height: 1500,
+ data,
+ });
+ expect(
+ decodePreviewStreamFrame(encodePreviewStreamVideoFrame({ type: "delta", data })),
+ ).toEqual({
+ type: "delta",
+ data,
+ });
+ const jpeg = new Uint8Array([0xff, 0xd8, 0xff, 0xd9]);
+ expect(decodePreviewStreamFrame(jpeg)).toEqual({ type: "jpeg", data: jpeg });
+ expect(decodePreviewStreamFrame(new Uint8Array([7]))).toBeNull();
+ });
+});
diff --git a/packages/contracts/src/preview.ts b/packages/contracts/src/preview.ts
index cbf8ac60b2690..4071885e3bede 100644
--- a/packages/contracts/src/preview.ts
+++ b/packages/contracts/src/preview.ts
@@ -148,6 +148,61 @@ export const PreviewStreamHostSetup = Schema.Struct({
export type PreviewStreamHostSetup = typeof PreviewStreamHostSetup.Type;
export const PREVIEW_STREAM_HOST_SETUP_CLOSE_CODE = 4503;
+/** WebCodecs strings the stream can encode, preferred first; clients send the ones they decode. */
+export const PREVIEW_STREAM_VIDEO_CODECS = ["avc1.42E034", "vp8"] as const;
+
+// A JPEG frame starts with 0xFF, so these first bytes mark the binary message as video.
+const VIDEO_KEY_FRAME = 1;
+const VIDEO_DELTA_FRAME = 2;
+
+export type PreviewStreamFrame =
+ | { readonly type: "jpeg"; readonly data: Uint8Array }
+ | {
+ readonly type: "key";
+ readonly codec: string;
+ readonly width: number;
+ readonly height: number;
+ readonly data: Uint8Array;
+ }
+ | { readonly type: "delta"; readonly data: Uint8Array };
+
+export const encodePreviewStreamVideoFrame = (
+ frame: Exclude,
+): Uint8Array => {
+ if (frame.type === "delta") {
+ const bytes = new Uint8Array(1 + frame.data.byteLength);
+ bytes[0] = VIDEO_DELTA_FRAME;
+ bytes.set(frame.data, 1);
+ return bytes;
+ }
+ const codec = new TextEncoder().encode(frame.codec);
+ const header = 6 + codec.byteLength;
+ const bytes = new Uint8Array(header + frame.data.byteLength);
+ const view = new DataView(bytes.buffer);
+ bytes[0] = VIDEO_KEY_FRAME;
+ view.setUint16(1, frame.width);
+ view.setUint16(3, frame.height);
+ bytes[5] = codec.byteLength;
+ bytes.set(codec, 6);
+ bytes.set(frame.data, header);
+ return bytes;
+};
+
+export const decodePreviewStreamFrame = (bytes: Uint8Array): PreviewStreamFrame | null => {
+ if (bytes[0] === VIDEO_DELTA_FRAME) return { type: "delta", data: bytes.subarray(1) };
+ if (bytes[0] !== VIDEO_KEY_FRAME) return bytes[0] === 0xff ? { type: "jpeg", data: bytes } : null;
+ if (bytes.byteLength < 6) return null;
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+ const header = 6 + bytes[5]!;
+ return {
+ type: "key",
+ width: view.getUint16(1),
+ height: view.getUint16(3),
+ codec: new TextDecoder().decode(bytes.subarray(6, header)),
+ data: bytes.subarray(header),
+ };
+};
+
export const PreviewSessionSnapshot = Schema.Struct({
threadId: TrimmedNonEmptyString,
tabId: PreviewTabId,
@@ -230,6 +285,27 @@ export const PreviewClearProfileInput = Schema.Struct({
});
export type PreviewClearProfileInput = typeof PreviewClearProfileInput.Type;
+/** "software" rasterizes on the CPU, "auto" lets Chromium pick, anything else is a GPU's `id`. */
+export const ServerBrowserGpu = Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(128));
+export type ServerBrowserGpu = typeof ServerBrowserGpu.Type;
+export const DEFAULT_SERVER_BROWSER_GPU = "software";
+export const ServerBrowserRenderScale = Schema.Literals([1, 1.5, 2, 3]);
+export type ServerBrowserRenderScale = typeof ServerBrowserRenderScale.Type;
+export const DEFAULT_SERVER_BROWSER_RENDER_SCALE: ServerBrowserRenderScale = 2;
+
+export const ServerBrowserGpuDevice = Schema.Struct({
+ id: Schema.String,
+ name: Schema.String,
+ driver: Schema.NullOr(Schema.String),
+});
+export type ServerBrowserGpuDevice = typeof ServerBrowserGpuDevice.Type;
+
+export const ServerBrowserGpuList = Schema.Struct({
+ /** Only Linux can pin a GPU; elsewhere the choice is software or automatic. */
+ gpus: Schema.Array(ServerBrowserGpuDevice),
+});
+export type ServerBrowserGpuList = typeof ServerBrowserGpuList.Type;
+
export const PreviewListInput = Schema.Struct({
threadId: ThreadId,
});
diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts
index 658f6276e247d..f0ec310802571 100644
--- a/packages/contracts/src/rpc.ts
+++ b/packages/contracts/src/rpc.ts
@@ -270,6 +270,7 @@ import {
PreviewEvent,
PreviewListInput,
PreviewListResult,
+ ServerBrowserGpuList,
PreviewClearProfileError,
PreviewClearProfileInput,
PreviewReportProfilesInput,
@@ -468,6 +469,7 @@ export const WS_METHODS = {
previewClose: "preview.close",
previewList: "preview.list",
previewClearProfile: "preview.clearProfile",
+ previewListGpus: "preview.listGpus",
previewReportProfiles: "preview.reportProfiles",
previewReportStatus: "preview.reportStatus",
previewStopLocalServer: "preview.stopLocalServer",
@@ -1569,6 +1571,12 @@ const WsPreviewListRpc = Rpc.make(WS_METHODS.previewList, {
error: EnvironmentAuthorizationError,
});
+const WsPreviewListGpusRpc = Rpc.make(WS_METHODS.previewListGpus, {
+ payload: Schema.Struct({}),
+ success: ServerBrowserGpuList,
+ error: EnvironmentAuthorizationError,
+});
+
const WsPreviewClearProfileRpc = Rpc.make(WS_METHODS.previewClearProfile, {
payload: PreviewClearProfileInput,
error: Schema.Union([PreviewClearProfileError, EnvironmentAuthorizationError]),
@@ -2088,6 +2096,7 @@ export const WsRpcGroup = RpcGroup.make(
WsPreviewAdjustRpc,
WsPreviewCloseRpc,
WsPreviewListRpc,
+ WsPreviewListGpusRpc,
WsPreviewClearProfileRpc,
WsPreviewReportProfilesRpc,
WsPreviewReportStatusRpc,
diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts
index 4ec228f8cd8ba..63be7950e0324 100644
--- a/packages/contracts/src/settings.ts
+++ b/packages/contracts/src/settings.ts
@@ -32,6 +32,12 @@ import { ModelSelection } from "./modelSelection.ts";
import { ProjectScript, type ProjectMutation } from "./project.ts";
import { DEFAULT_RUNTIME_MODE, RuntimeMode } from "./providerPolicy.ts";
import { BrowserProfile, BrowserProfileId, DEFAULT_BROWSER_PROFILE_ID } from "./browserProfile.ts";
+import {
+ DEFAULT_SERVER_BROWSER_GPU,
+ DEFAULT_SERVER_BROWSER_RENDER_SCALE,
+ ServerBrowserGpu,
+ ServerBrowserRenderScale,
+} from "./preview.ts";
import {
BrowserRecordingFrameRate,
DEFAULT_BROWSER_RECORDING_FRAME_RATE,
@@ -1191,6 +1197,12 @@ export const ServerSettings = Schema.Struct({
),
enableAgentBrowserAccess: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
+ serverBrowserGpu: ServerBrowserGpu.pipe(
+ Schema.withDecodingDefault(Effect.succeed(DEFAULT_SERVER_BROWSER_GPU)),
+ ),
+ serverBrowserRenderScale: ServerBrowserRenderScale.pipe(
+ Schema.withDecodingDefault(Effect.succeed(DEFAULT_SERVER_BROWSER_RENDER_SCALE)),
+ ),
projectAgentBrowserAccessOverrides: Schema.Record(ProjectId, Schema.Boolean).pipe(
Schema.withDecodingDefault(Effect.succeed({})),
),
@@ -1556,6 +1568,8 @@ export const ServerSettingsPatch = Schema.Struct({
enableProviderUpdateChecks: Schema.optionalKey(Schema.Boolean),
continueThreadsAfterServerUpdate: Schema.optionalKey(Schema.Boolean),
enableAgentBrowserAccess: Schema.optionalKey(Schema.Boolean),
+ serverBrowserGpu: Schema.optionalKey(ServerBrowserGpu),
+ serverBrowserRenderScale: Schema.optionalKey(ServerBrowserRenderScale),
projectAgentBrowserAccessOverrides: Schema.optionalKey(
Schema.Record(ProjectId, Schema.NullOr(Schema.Boolean)),
),