Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 9 additions & 5 deletions apps/mobile/src/features/browser/preview-stream.browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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 }),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => ({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -378,6 +379,17 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
onValueChange={(value) => write({ enableAgentBrowserAccess: value })}
/>
</SettingsSection>
{projectSelected ? null : (
<BrowserRenderingSections
environmentId={
targets.length === 1 ? (reference?.environment.environmentId ?? null) : null
}
gpu={uniform("serverBrowserGpu")}
scale={uniform("serverBrowserRenderScale")}
disabled={disabled}
write={write}
/>
)}
<AutoSettleSettingsRows write={write} pending={pendingWrites > 0} />
</>
) : null}
Expand Down
Original file line number Diff line number Diff line change
@@ -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<ServerBrowserGpuList>({ gpus: [] }));
const RENDER_SCALES: ReadonlyArray<ServerBrowserRenderScale> = [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 (
<>
<SettingsSection title="Browser GPU">
{gpuChoices.map((choice, index) => (
<ListChoiceRow
key={choice.id}
label={choice.label}
description={choice.description}
selected={props.gpu === choice.id}
separated={index > 0}
disabled={props.disabled}
onPress={() => props.write({ serverBrowserGpu: choice.id })}
/>
))}
</SettingsSection>
<SettingsSection title="Browser render scale">
{RENDER_SCALES.map((scale, index) => (
<ListChoiceRow
key={scale}
label={`${scale}×`}
{...(scale === DEFAULT_SERVER_BROWSER_RENDER_SCALE
? { description: `The default. ${APPLIES}` }
: {})}
selected={props.scale === scale}
separated={index > 0}
disabled={props.disabled}
onPress={() => props.write({ serverBrowserRenderScale: scale })}
/>
))}
</SettingsSection>
</>
);
}
1 change: 1 addition & 0 deletions apps/server/src/auth/RpcAuthorization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/observability/RpcInstrumentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
134 changes: 133 additions & 1 deletion apps/server/src/preview/ServerBrowser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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";
Expand Down Expand Up @@ -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();
}
Expand Down Expand Up @@ -87,7 +93,7 @@ function makeSession(frame?: ReturnType<typeof makeFrame>) {
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<Record<string, unknown>> => {
if (method === "Page.getNavigationHistory") return { currentIndex: 0, entries: [{}] };
Expand Down Expand Up @@ -259,6 +265,8 @@ function makeEncoderPage() {
}

const contexts: ReturnType<typeof makeContext>[] = [];
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<void> | null = null;
Expand Down Expand Up @@ -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<ServerSettings>((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),
Expand Down Expand Up @@ -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<string> = [];
const started = Promise.withResolvers<void>();
const handled = Promise.withResolvers<void>();
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 },
Expand Down
Loading
Loading