A local-first multi-agent app development platform, built on PenguinHarness
feat(server,web): 服务器自己跑一个浏览器,画面实时传到网页里
lmlihengd80660b3948d
diff --git a/changelog/unreleased/2026-11-01-server-browser.md b/changelog/unreleased/2026-11-01-server-browser.mdnew file mode 100644index 00000000..b491c46f--- /dev/null+++ b/changelog/unreleased/2026-11-01-server-browser.md@@ -0,0 +1,47 @@+# A browser the server runs itself, for the machines with no desktop window++- **Date:** 2026-11-01+- **Type:** feature+- **Scope:** `server`, `web`, `ui-gallery`, `docs`++[中文版](2026-11-01-server-browser.zh.md)++The sidebar has a **Server Browser** page: the browser process runs on the machine serving the app, its picture is streamed into the page, and clicks, scrolls and keystrokes travel back.++The built-in browser cannot do this. Its pages are elements of the desktop app's window, so opening `penguin web` in a browser, running in Docker, or reaching a machine remotely leaves no browser at all — `penguin browser` answers `browser_unavailable` in those cases. This page is the other way round: all it needs is a Chromium or Chrome on the server. Give it a virtual display and it is an ordinary windowed browser rather than a headless one — headless Chromium is unrecognizable to many sites, and often will not play their video at all.++Admins only: starting it spawns a process on the server, and the browser's profile is shared by the whole installation.++## The picture is one MJPEG stream++`GET /api/server-browser/frames` answers `multipart/x-mixed-replace`, which is what an `<img>` plays natively. So the page needs no canvas, no frame decoder and no socket — the browser on that machine rasterizes, and the page shows the result. Frames are dropped rather than queued when a viewer falls behind: somebody watching wants the newest picture, not a backlog of old ones. With no viewer, the screencast is not started at all, so a page standing still costs nothing.++## The last frame does not stay behind++In a `multipart/x-mixed-replace` stream, the browser only takes up a part once the next one begins. While a page is moving that is invisible; when a page repaints once it is the whole problem — you click, the page changes, and the picture still shows what was there before the click, as if the click had done nothing. So a frame that is not followed by another within 150 milliseconds is written again, and the copy is what gets taken up: the picture is current straight away. A page in motion pays nothing for this — no frame is written twice. The same holds for the dropping rule: what is dropped is the older frame a newer one replaced, never the newest itself.++## The address and the title come from the browser's history++No pixels carry an address bar, so the page reads the status every 1.2 seconds. The title is not the one the browser reports for the target: a page that commits with a `<title>` still reports its host name there — `example.com/` comes back as `example.com`, a local address as `127.0.0.1:38809` — while the browser's own history entry is right. So the title is asked of the history, not of the document by running a script in it.++## The page is redrawn at the size of the box++The picture is not a fixed-size image scaled to fit: the page redraws the server's page at whatever size this box measures (clamped to 320×240 … 1920×1200). Narrow the window and the page inside narrows with it, instead of becoming a small unreadable copy. Pointer coordinates are converted through the area `object-fit: contain` actually draws into, so a click does not drift when there are margins.++## Whose browser it is++Opening the page starts it (the picture request is the request for it), and closing the page leaves it **running** — it is not an appendage of the page, and whoever opens the page next sees the same browser and its one page. To actually let it go, press the stop button at the end of the toolbar. Sign-ins live in the data root's `browser-profile`, so they survive a restart and an upgrade. When the App is hot-swapped or shut down, the process goes down with it, rather than leaving two browsers fighting over one profile.++## What it cannot do++With no Chromium or Chrome on the server, or with it switched off by `ADELIE_SERVER_BROWSER=off`, a status read answers `available: false` with the reason and the page says so — a fact about the deployment, never a failure — and no route starts a process. A browser installed elsewhere is named by `ADELIE_SERVER_BROWSER_BIN`.++The page has one page and no tabs: what it exists for is watching a page your own machine cannot reach, and a second tab is where a window manager starts. The desktop app keeps its own tabs.++## The bar is watching, not scrolling a feed++The picture, the clicks, the wheel and the keyboard all work. Whether a data-centre IP can sign into some platform, or make its video play, is that platform's risk control and login problem and has nothing to do with this page showing a page. A browser under its default user agent cannot open some sites at all (it lands on a captcha interstitial), and those sites ask for a sign-in in a real desktop browser too.++## Input methods are not wired up yet++What travels back is the keyboard: letters, digits, symbols, Enter, Tab and the arrow keys all reach the page. Chinese — anything an input method composes first and then hands over as a whole string — does not, because the composing happens on your side and there is nothing there to catch it yet. That is the next thing to add, not a setting.diff --git a/changelog/unreleased/2026-11-01-server-browser.zh.md b/changelog/unreleased/2026-11-01-server-browser.zh.mdnew file mode 100644index 00000000..668ec83c--- /dev/null+++ b/changelog/unreleased/2026-11-01-server-browser.zh.md@@ -0,0 +1,47 @@+# 服务器自己跑一个浏览器:没有桌面窗口的机器也能看网页++- **Date:** 2026-11-01+- **Type:** feature+- **Scope:** `server`, `web`, `ui-gallery`, `docs`++[English](2026-11-01-server-browser.md)++侧栏多了一个**服务器浏览器**页面:浏览器进程跑在服务端那台机器上,画面实时传到页面里,点击、滚动和打字都从页面传回去。++内置浏览器做不到这件事。它的页面是桌面应用窗口里的元素,所以用浏览器打开 `penguin web`、在 Docker 里、或者访问一台远程机器,都没有浏览器——`penguin browser` 在这些场合回答 `browser_unavailable`。这个页面正相反,它只要求服务器上有一个 Chromium 或 Chrome:给它一个虚拟显示器,它就是一台正常的窗口浏览器,而不是无头模式——无头 Chromium 认不出很多站点,也常常放不出视频。++只有管理员能用:启动会在服务器上拉起一个进程,而它用的浏览器配置是整机共用的。++## 画面用一条 MJPEG 流++`GET /api/server-browser/frames` 回的是 `multipart/x-mixed-replace`,也就是一个 `<img>` 天生就能播的东西。页面上因此没有 canvas、没有帧解码、没有 WebSocket——栅格化由那台机器上的浏览器自己做,页面只负责显示结果。落后时丢帧而不是排队:看画面的人要的是最新的一张,不是一堆积压的旧图。没有观众时,浏览器那边的录屏整个不启动,静止的页面因此也不耗什么。++## 最后一帧不会停在上一张++一条 `multipart/x-mixed-replace` 的流里,浏览器要等到下一段开始,才会把上一段取上来显示。页面一直动的时候这看不出来,页面只重画一次的时候就是致命的:点一下画面、页面变了,可画面里显示的还是点之前那张——看着就像点击没生效。所以一帧写出后 150 毫秒内没有下一帧时,它会被再写一遍;被取走的是这一份,画面因此立刻是最新的。一直在动的页面照原样,一帧也不多写。落后时丢帧的规则也一样:丢的是被替换掉的旧帧,不是最新那帧。++## 地址和标题来自浏览器的历史记录++画面的像素里没有地址栏,所以页面每 1.2 秒读一次状态。标题不能取浏览器给目标报的那一个:一个明明带着 `<title>` 提交的页面,在目标的报告里仍然写着主机名——`example.com/` 报成 `example.com`,本机地址报成 `127.0.0.1:38809`——而回看浏览历史里那一条是对的。所以标题问的是历史记录,不是在页面里跑脚本。++## 页面按窗口的框重绘++画面不是把一张固定尺寸的图缩小了放上来:页面按这块区域量到的大小去重绘服务器上的页面(收敛在 320×240 到 1920×1200 之间)。所以窗口拉窄,里面的网页也跟着变窄,而不是变成一个看不清的小图。输入坐标按 `object-fit: contain` 实际画出来的那块区域换算,上下或左右留白时点击也不会偏。++## 它是谁的浏览器++打开这个页面就会启动它(画面请求送达即为请求),关掉页面它**继续运行**——它不是页面的附属物,别人打开看到的是同一个浏览器和它那一个页面。要真放掉它,用工具栏最右边的停止按钮。登录状态留在数据根目录的 `browser-profile` 里,重启和升级都还在。应用被热替换或结束时,这个进程随它一起下去,不会留下两个浏览器抢同一份配置。++## 做不到和前一台机器一样的事++服务器上没有 Chromium 或 Chrome、或者被 `ADELIE_SERVER_BROWSER=off` 关掉时,状态读出来是 `available: false` 加一句原因,页面照原样显示,任何路由都不会去启动进程——这是配置事实,不是故障。浏览器装在别处时用 `ADELIE_SERVER_BROWSER_BIN` 点名。++这个页面只有一个页面、没有标签页:它存在的意义是看一个自己的机器够不到的页面,而第二个标签页正是「窗口管理器」的开始。桌面应用那套多标签留在那里。++## 门槛在能看,不在能刷++画面、点击、滚动、键盘都通。至于用一个数据中心 IP 的浏览器登录某个平台、或者让视频起播——那是那个平台的风控和登录问题,跟这个页面能不能显示无关。一个默认 UA 的浏览器打不开某些站点(会撞上验证码中间页),而这样的站点在真实桌面浏览器里也会要求登录。++## 输入法还接不上++传回去的是键盘事件:字母、数字、符号、回车、Tab 和方向键都能到那个页面;中文这类要输入法先组合、再整段交出来的字还传不过去——组合发生在你自己这一侧,那边还没有一个接住它的地方。这是下一步要补的,不是配置问题。diff --git a/packages/docs/content/configuration.en.md b/packages/docs/content/configuration.en.mdindex 0e23bd1a..8ec7d10f 100644--- a/packages/docs/content/configuration.en.md+++ b/packages/docs/content/configuration.en.md@@ -24,6 +24,8 @@ The CLI and the server load a `.env` file from the working directory on startup.| `ADELIE_LANG` | CLI language (`en` / `zh`), set with `penguin config lang` | `en` || `ADELIE_UPDATE_CHECK` | `off` disables the Web App's new-release check | Enabled || `ADELIE_PLUGIN_MARKET` | `off` lists only the plugins this build carries in the plugin market, never querying npm | Enabled |+| `ADELIE_SERVER_BROWSER` | `off` switches off the server's own browser | Enabled |+| `ADELIE_SERVER_BROWSER_BIN` | The Chromium / Chrome the server's browser runs | Unset: looked up on `PATH` || `PENGUIN_NO_LOGIN_SHELL_ENV` | Any non-empty value stops the desktop app from importing the login shell's environment on macOS/Linux GUI launches | Unset: the import runs || `ADELIE_SHELL` | The shell that runs agent commands (an executable name or path) | Unset: picked automatically, see [Tools & Approval](/tools#command-sessions) || `ADELIE_CLI_ENTRY` | The CLI entry script this installation offers the agents it runs (see [PATH launcher](#path-launcher)) | Set by `penguin server` / `penguin web` and by the desktop app |@@ -37,6 +39,8 @@ Notes:- `MODELSCOPE_BRIDGE_URL`: server configuration like `PENGUIN_GO_ORIGIN`, not an endpoint the browser can name. It must be an HTTPS address with no credentials, query string or fragment. Unlike `PENGUIN_GO_ORIGIN`, a path prefix **is** allowed, because the production bridge lives under `https://go.penguin.ooo/modelscope`. See [Connect an account](/models#connect-an-account).- `ADELIE_UPDATE_CHECK`: `off` turns off the automatic release check, nothing else. Model requests, an enabled remote-control connection, provider key authorization and the proxy test still reach the network.- `ADELIE_PLUGIN_MARKET`: the market's shelf has two sides — the plugins this build carries (read locally, no network) and the ones published to npm. For the second the server queries npm's search API once, caching the result for ten minutes (for two minutes after a failure, serving the previous listing). With `off` that side is never queried and the shelf is the local one alone, which is what an offline or closed network wants. See [Plugins](/skills).+- `ADELIE_SERVER_BROWSER`: with `off`, the server browser is left entirely alone — the page says it is switched off and no route starts a process. For a deployment that does not want a browser pulled up on the host. See [Server browser](/server-browser).+- `ADELIE_SERVER_BROWSER_BIN`: names a browser installed on the server under none of the usual names (`chromium`, `chromium-browser`, `google-chrome-stable`, `google-chrome`, `chrome`). See [Server browser](/server-browser).- `PENGUIN_NO_LOGIN_SHELL_ENV`: without it, the import fills only variables the launch left unset. See [Desktop quickstart](/quickstart-desktop).- `ADELIE_CLI_ENTRY`: when the server was started from a source checkout, it falls back to that checkout's `packages/cli/dist/penguin.js`.diff --git a/packages/docs/content/configuration.zh.md b/packages/docs/content/configuration.zh.mdindex a1e41136..893c127d 100644--- a/packages/docs/content/configuration.zh.md+++ b/packages/docs/content/configuration.zh.md@@ -24,6 +24,8 @@ CLI 和服务器启动时会从工作目录加载 `.env` 文件。| `ADELIE_LANG` | CLI 语言(`en` / `zh`),用 `penguin config lang` 设置 | `en` || `ADELIE_UPDATE_CHECK` | 设为 `off` 时关闭 Web App 的新版本检查 | 启用 || `ADELIE_PLUGIN_MARKET` | 设为 `off` 时插件市场只列出本次构建自带的插件,不查询 npm | 启用 |+| `ADELIE_SERVER_BROWSER` | 设为 `off` 时关闭服务器自己的浏览器 | 启用 |+| `ADELIE_SERVER_BROWSER_BIN` | 服务器浏览器使用的 Chromium / Chrome 可执行文件 | 未设置:在 `PATH` 里找 || `PENGUIN_NO_LOGIN_SHELL_ENV` | 设为任意非空值后,桌面应用在 macOS/Linux 上从图形界面启动时不再导入登录 shell 的环境变量 | 未设置:照常导入 || `ADELIE_SHELL` | 运行 Agent 命令的 shell(可执行文件名或路径) | 未设置:自动选择,见[工具与审批](/tools#命令会话) || `ADELIE_CLI_ENTRY` | 本安装提供给所运行 Agent 的 CLI 入口脚本(见 [PATH 启动脚本](#path-启动脚本)) | 由 `penguin server` / `penguin web` 和桌面应用设置 |@@ -37,6 +39,8 @@ CLI 和服务器启动时会从工作目录加载 `.env` 文件。- `MODELSCOPE_BRIDGE_URL`:与 `PENGUIN_GO_ORIGIN` 一样是服务端配置,不接受浏览器指定的端点。它必须是不带凭据、查询参数或 fragment 的 HTTPS 地址。不同之处是**它允许带路径前缀**,因为生产环境的中转层就挂在 `https://go.penguin.ooo/modelscope` 下。见[连接账户](/models#连接账户)。- `ADELIE_UPDATE_CHECK`:设为 `off` 只关闭自动的版本检查,不影响其他对外请求:模型请求、已启用的远程控制连接、Key 授权和代理测试照常联网。- `ADELIE_PLUGIN_MARKET`:插件市场的货架有两侧,一侧是本次构建自带的插件(本地读,不联网),另一侧是发布到 npm 的插件。服务器为此查一次 npm 的搜索接口,结果缓存十分钟(失败时缓存两分钟并沿用上一次的结果)。设为 `off` 后这一侧完全不查,货架只剩本地那一侧——断网或封闭环境里应当如此。见[插件](/skills)。+- `ADELIE_SERVER_BROWSER`:设成 `off` 时,服务器浏览器整条路都不动:页面显示它被关闭,任何路由都不会去启动一个进程。用于不打算让服务器拉浏览器起来的环境。+- `ADELIE_SERVER_BROWSER_BIN`:服务器上没装在这几个常见名字下(`chromium`、`chromium-browser`、`google-chrome-stable`、`google-chrome`、`chrome`)的浏览器,用它点名。见[服务器浏览器](/server-browser)。- `PENGUIN_NO_LOGIN_SHELL_ENV`:不设置时,导入只填补启动过程没有设置的变量。见[桌面应用快速开始](/quickstart-desktop)。- `ADELIE_CLI_ENTRY`:服务器从源码检出启动时,会回退到检出目录中的 `packages/cli/dist/penguin.js`。diff --git a/packages/docs/content/server-browser.en.md b/packages/docs/content/server-browser.en.mdnew file mode 100644index 00000000..245e4c1c--- /dev/null+++ b/packages/docs/content/server-browser.en.md@@ -0,0 +1,63 @@+---+title: Server browser+description: A browser the server itself runs, streamed into the Web App — for machines with no desktop window, such as a Linux box reached over ssh.+---++The **server browser** is a page in the Web App (the **Server Browser** row in the sidebar): the browser process runs on the machine serving the app, and you watch its picture here — and click, scroll and type on it from here too.++It exists for what the [built-in browser](/builtin-browser) cannot reach. The built-in browser's pages are elements of the desktop app's window, so only a desktop app has one; open `penguin web` in a browser, run in Docker, or reach a machine remotely, and there is none. The server browser is the other way round: all it asks for is a Chromium or Chrome on the server.++- What it is and when to reach for it: [When to use it](#when-to-use-it).+- Opening a page and clicking in it: [Using it](#using-it).+- No browser on the server, or none wanted: [Switching it off, or naming another browser](#switching-it-off-or-naming-another-browser).+- An agent driving a browser itself is a different thing: see the [built-in browser](/builtin-browser#drive-it-from-the-command-line).++## When to use it++It is the machine's single set of browsing pages, and they belong to the server itself: every Project and every conversation sees the same browser and the one page it has open. That is unlike the built-in browser, whose tabs are also shared machine-wide — but that browser lives inside the desktop app's window.++It is for the cases where the browser on *this* machine sees something different from yours:++- Opening something reachable only from inside a server's network.+- Seeing what a web page looks like on a machine with no display at all: the server gives the browser a virtual display, so it is an ordinary windowed browser rather than a headless one.+- Keeping a page open somewhere that does not deserve a place on your own screen.++**It is an admin's tool.** Starting it spawns a process on the server, and the browser's profile is shared by the whole installation, so this page and every route behind it are open to admins only.++## Using it++Opening **Server Browser** in the sidebar is enough: the browser is started when the page asks for its picture, so there is no separate first step. The toolbar is **Back**, **Forward**, **Reload**, the address bar and **Go**; at the far end is the button that **Starts** the browser when it is not running and **Stops** it when it is.++- The address bar follows a browser's rules: a bare domain like `example.com` opens over `https://`, and Enter opens what you typed. Anything that is not http or https is refused.+- The picture is the page. **Click it to use it**: clicks, double-clicks, right-clicks, drags and the wheel all reach the page, and so does the keyboard — Tab, Enter and the arrow keys included.+- **Typing with an input method does not get there yet.** What travels is the keyboard: letters, digits, symbols, Enter, Tab and the arrow keys all work, but the step where an input method composes first and hands over the whole string is not wired up, so Chinese and anything else that needs one cannot be typed into the page for now.+- The line above the picture shows the page's title, its address, and whether it is still loading; the right-hand end is the size the browser is drawing the page at.+- The page is redrawn at the size of the box on this page. Narrow the window and the page on the server narrows with it — what you see in this area is the viewport, so nothing has to be magnified.+- When the picture stops — the browser was stopped, or the server was restarted — a line and a **Reload** button take its place; the button reconnects.++The browser **keeps running** after you close this page: it is not an appendage of the page, and anyone who opens this page sees the same browser. To actually let it go, press **Stop the browser** at the end of the toolbar.++## Sign-ins stay on the server++The browser's profile lives in the server's data root (`<root>/browser-profile`), so the sites you signed into are still signed in after a restart or an upgrade — and the same signed-in browser is what another machine opening this page sees.++That directory is shared by the whole installation: everyone using this server browser uses the same sign-ins.++## Switching it off, or naming another browser++With no Chromium or Chrome on the server, this page says so instead of showing an empty box. To keep the server from pulling a browser up at all, set `ADELIE_SERVER_BROWSER=off`; for a browser installed somewhere else or under another name, `ADELIE_SERVER_BROWSER_BIN` names its executable. Both are in [Configuration](/configuration#environment-variables).++The browser creates its profile directory inside the data root the first time it starts, so the disk holding that root has to be writable.++## The server API++The routes behind the page are the `/api/server-browser` group, admin-only like the page:++- `GET /api/server-browser` — what is going on: whether this server can show a browser, whether one is running, and the current page's address, title and drawn size.+- `POST /api/server-browser/start`, `/stop` — start or stop the browser.+- `POST /api/server-browser/navigate` with `{ url }`; `/back`, `/forward`, and `/reload` (with an optional `{ hard }`).+- `POST /api/server-browser/resize` with `{ width, height }` (brought inside 320×240 … 1920×1200).+- `POST /api/server-browser/input` with `{ events: [...] }`: one batch of input events, applied in order.+- `GET /api/server-browser/frames` — the picture itself, a `multipart/x-mixed-replace` MJPEG stream an `<img>` plays as it arrives. Frames are dropped rather than queued when a viewer falls behind.++With no browser on the machine, or with it switched off, a status read answers `available: false` and the reason — it is never reported as a failure.diff --git a/packages/docs/content/server-browser.zh.md b/packages/docs/content/server-browser.zh.mdnew file mode 100644index 00000000..e7cf71c9--- /dev/null+++ b/packages/docs/content/server-browser.zh.md@@ -0,0 +1,63 @@+---+title: 服务器浏览器+description: 由服务器自己跑起来的浏览器,画面实时传到 Web App 里;没有桌面窗口的机器也能看网页,比如一台只有 ssh 的 Linux 服务器。+---++**服务器浏览器**是 Web App 里的一个页面(侧栏的**服务器浏览器**):浏览器进程跑在服务端那台机器上,你在这个页面里看它的画面,也在它上面点击、滚动和打字。++它是给[内置浏览器](/builtin-browser)够不着的场合用的。内置浏览器的页面是桌面应用窗口里的元素,所以只有在桌面应用里才有;用浏览器打开 `penguin web`、Docker、或者一台被远程访问的机器,都没有它。服务器浏览器正好相反:它只要求服务器上装了一个 Chromium 或 Chrome。++- 想看它是什么、什么时候用它,见[什么时候用它](#什么时候用它)。+- 想开一个页面、点里面的东西,见[使用](#使用)。+- 服务器上没装浏览器、或者不想让它跑,见[关闭或另指一个浏览器](#关闭或另指一个浏览器)。+- Agent 自己驱动浏览器是另一件事,见[内置浏览器](/builtin-browser#在命令行中驱动)。++## 什么时候用它++它是整机唯一的一组浏览页面,只属于服务器本身:每个 Project、每个对话看到的都是同一个浏览器和它那一个页面。这与内置浏览器不同,后者的标签页同样是整机共享的,但那个浏览器长在桌面应用的窗口里。++用途通常是「这台机器上的浏览器看到的,和我的机器不一样」:++- 在一台内网或限制访问的服务器上打开只有那里能访问的页面。+- 在没有图形界面的机器上,用它来看一个网页长什么样——服务器会给浏览器一个虚拟显示器,所以它是个正常的窗口浏览器,不是无头模式。+- 把它当成一个「别人帮我盯着这个页面」的窗口,比如一个需要一直开着、又不值得占用自己屏幕的看板。++**它是管理员的工具。** 启动它会在服务器上拉起一个进程,它用的浏览器配置也是整机共用的,所以这个页面和它背后的每一条路由都只对管理员开放。++## 使用++打开侧栏的**服务器浏览器**就会开始解冻:页面里的画面请求送达时,服务器就把浏览器拉起来(不需要你先按一次启动)。工具栏从左到右是**后退**、**前进**、**刷新**、地址栏和**打开**;最右边是在浏览器不运行时**启动**它、运行中**停止**它的按钮。++- 地址栏按浏览器的规则解读:只写域名(如 `example.com`)时以 `https://` 打开,输入框里回车即打开。不是 http 或 https 的地址会被拒绝。+- 画面就是页面本身。**点击画面即可操作它**:单击、双击、右键、拖动和滚轮都会传给那个页面,键盘输入也一样,按 Tab、回车、方向键都可用。+- **用输入法打字还传不过去。** 传到那个页面的是键盘:字母、数字、符号、回车、Tab 和方向键都可以,但输入法先在自己这一侧组合、再整段交出来的那一步还没接上,所以中文这类需要输入法的字现在打不进去。+- 画面上方一行显示当前页面的标题、地址和它是否还在加载,右侧是浏览器当前绘制页面的尺寸。+- 页面按这个页面的框大小重绘。把窗口拉窄或拉宽,服务器上的页面会跟着变宽变窄——就是你在这块区域里看到的那个尺寸,所以不用放大镜。+- 画面中断(比如浏览器被停掉、或服务器重启了服务)时,中间会出现一句话和一个**刷新**按钮,点它重新连上。++浏览器在你关掉这个页面后**继续运行**:它不是这个页面的附属物,别人打开这个页面看到的也是它。要真正放掉它,按工具栏最右边的**停止浏览器**。++## 登录状态留在服务器上++浏览器自己的配置文件放在服务器的数据根目录(`<数据根>/browser-profile`),因此你在里面登录过的站点,在服务器重启、甚至升级之后仍然登录着——换台机器打开这个页面,看到的还是同一个已登录的浏览器。++这个目录是整机共用的。谁用这个服务器浏览器,用的就是同一份登录状态。++## 关闭或另指一个浏览器++服务器上没有 Chromium 或 Chrome 时,这个页面会直接说明,而不是给一个空框。想让服务器别拉浏览器起来,设 `ADELIE_SERVER_BROWSER=off`;浏览器装在别处或用的是别的名字时,用 `ADELIE_SERVER_BROWSER_BIN` 点名它的可执行文件。两个变量见[配置](/configuration#环境变量)。++浏览器在这个数据根目录里第一次启动时会新建自己的配置目录;数据根所在的磁盘因此需要能写。++## 服务端接口++页面背后的路由组是 `/api/server-browser`,与页面一样仅管理员可用:++- `GET /api/server-browser` — 现在的状态:这台服务器能不能显示浏览器、浏览器是否在运行、当前页面的地址、标题和绘制尺寸。+- `POST /api/server-browser/start`、`/stop` — 启动或停止浏览器。+- `POST /api/server-browser/navigate`,请求体 `{ url }`;`/back`、`/forward`、`/reload`(可选 `{ hard }`)。+- `POST /api/server-browser/resize`,请求体 `{ width, height }`(会被收敛到 320×240 与 1920×1200 之间)。+- `POST /api/server-browser/input`,请求体 `{ events: [...] }`,一次一批输入事件,顺序执行。+- `GET /api/server-browser/frames` — 画面本身,一条 `multipart/x-mixed-replace` 的 MJPEG 流,交给一个 `<img>` 就能播放;落后时丢帧而不是排队。++服务器上没有浏览器、或它被关掉时,读状态会得到 `available: false` 和一句原因——它不会被报成故障。diff --git a/packages/docs/src/lib/nav.ts b/packages/docs/src/lib/nav.tsindex 0d791c40..753aaace 100644--- a/packages/docs/src/lib/nav.ts+++ b/packages/docs/src/lib/nav.ts@@ -49,6 +49,7 @@ export const DOCS_NAV: DocsSectionDef[] = ["chat","files","builtin-browser",+ "server-browser","schedules","remote-control","agents",diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex f6efd91c..e3ea0caa 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -6841,6 +6841,78 @@ export interface DesktopBrowserEventMessage {event: DesktopBrowserEvent;}+// ---------------------------------------------------------------------------+// Server browser: a real Chromium on the server itself, for the machines the desktop app is+// not running on (a headless Linux box reached over the network). It draws on a virtual+// display and hands the picture out as frames, so a person can watch what it loads. See+// server-browser/.+// ---------------------------------------------------------------------------++/** Where the server's browser is, as the page shows it. */+export interface ServerBrowserState {+ url: string;+ title: string;+ loading: boolean;+ /** The viewport the page is drawn at — what a frame's pixels are of. */+ width: number;+ height: number;+}++/** Whether this server can show a browser at all, and what it is doing. */+export interface ServerBrowserStatus {+ /** False when this machine has no browser to run, or the browser is switched off. */+ available: boolean;+ /** Why not, in the server's own words; absent when it is available. */+ reason?: string;+ /** The browser is up and its page is attached. */+ running: boolean;+ /** Where its page is and what it looks like; null while nothing runs. */+ state: ServerBrowserState | null;+}++/**+ * One input event from the viewer, named after what the browser itself needs rather than after+ * the DOM: the page's own coordinates (not the canvas's, which the client scales), and the keys+ * as CDP's Input domain takes them.+ */+export type ServerBrowserInput =+ | {+ type: "mouse";+ action: "move" | "down" | "up";+ x: number;+ y: number;+ button?: "left" | "middle" | "right";+ /** Which buttons are held, CDP's own bitmask (1 left, 2 right, 4 middle); 0 after a release. */+ buttons?: number;+ clickCount?: number;+ }+ | { type: "wheel"; x: number; y: number; deltaY: number; deltaX?: number }+ | {+ type: "key";+ action: "down" | "up";+ key: string;+ code?: string;+ keyCode?: number;+ text?: string;+ }+ /** A whole string at once (an IME result, a paste): typed without pretending to be keystrokes. */+ | { type: "text"; text: string };++/** POST /api/server-browser/input: a batch of input events, in order. */+export interface ServerBrowserInputRequest {+ events: ServerBrowserInput[];+}++/** POST /api/server-browser/navigate, /resize. */+export interface ServerBrowserNavigateRequest {+ url: string;+}++export interface ServerBrowserResizeRequest {+ width: number;+ height: number;+}+// ---------------------------------------------------------------------------// Feedback (GET|POST /api/feedback)// ---------------------------------------------------------------------------diff --git a/packages/server/src/http/routes/server-browser.ts b/packages/server/src/http/routes/server-browser.tsnew file mode 100644index 00000000..3c84850b--- /dev/null+++ b/packages/server/src/http/routes/server-browser.ts@@ -0,0 +1,348 @@+/**+ * The server browser's routes: an admin's, because it spawns a process on the server and the+ * profile it fills in is shared by every Project on it — the same call as the plugin directory.+ *+ * GET /api/server-browser — what the browser is doing, and whether it can run here+ * POST /api/server-browser/start — start (or restart) it+ * POST /api/server-browser/stop — stop it+ * POST /api/server-browser/navigate — go to an address (a bare host is https)+ * POST /api/server-browser/back|forward|reload+ * POST /api/server-browser/resize — draw the page at another size (a viewer's box)+ * POST /api/server-browser/input — a batch of input events+ * GET /api/server-browser/frames — the picture, as a live MJPEG stream+ *+ * The picture is `multipart/x-mixed-replace`, which is what an `<img>` renders natively: the+ * page needs no canvas, no frame decoder and no socket, and the browser's own image pipeline+ * does the rasterizing. Frames are dropped rather than buffered when the viewer falls behind —+ * a lagging viewer wants the newest picture, not a backlog of old ones.+ */+import { Hono, type Context } from "hono";+import type { ServerBrowserInput, ServerBrowserStatus } from "../../api/types.js";+import { HttpError } from "../errors.js";+import type { AppEnv } from "../../auth/middleware.js";+import { readJson, requireString } from "../validate.js";+import { Bind, Component, Use } from "@adelie/core/kernel";+import type { ServerBrowser } from "../../services/server-browser-service.js";+import { normalizeAddress } from "../../server-browser/session.js";++/** The MJPEG boundary. One constant: the client never sees it, the `<img>` parses it. */+const BOUNDARY = "adelie-browser-frame";+/** How long a wedged browser may keep a request open before the route gives up on it. */+const STATUS_TIMEOUT_MS = 45_000;+/**+ * How long a written frame waits for the next one before it is written again. Frames that come+ * closer together than this are a page in motion, and the viewer is following it anyway.+ */+const FRAME_COMMIT_MS = 150;++/**+ * The MJPEG stream's parts, as they are handed to the transport: the headers, the JPEG, and the+ * boundary line that CLOSES this part.+ *+ * The boundary goes out with the frame it closes, not in front of the next one. A multipart parser+ * (the browser's, for the `<img>` pointed here) cannot call a part finished until it sees the line+ * after it, so a boundary that only arrives with the following frame leaves the picture one frame+ * behind — and on a page that has just stopped changing, the frame that had arrived is the one+ * that never appears. A click that painted once then looks like it did nothing. The bytes are the+ * same as they would be either way; what changes is when each one is written.+ */+function frameParts(): (jpeg: Buffer) => Uint8Array {+ // The first part opens the stream with its own boundary; every later one continues after the+ // boundary this closes with, so nothing is repeated and nothing is left out.+ let opened = false;+ return (jpeg) => {+ const lead = opened ? "" : `--${BOUNDARY}\r\n`;+ opened = true;+ return Buffer.concat([+ Buffer.from(+ `${lead}Content-Type: image/jpeg\r\nContent-Length: ${jpeg.length}\r\n\r\n`,+ "utf8",+ ),+ jpeg,+ Buffer.from(`\r\n--${BOUNDARY}\r\n`, "utf8"),+ ]);+ };+}++/** One input event off the wire, checked: the browser is given only well-formed events. */+function readInputEvent(raw: unknown): ServerBrowserInput {+ if (typeof raw !== "object" || raw === null)+ throw new HttpError(400, "bad_request", "not an input event");+ const e = raw as Record<string, unknown>;+ const type = e["type"];+ if (type === "mouse") {+ const action = e["action"];+ if (action !== "move" && action !== "down" && action !== "up") {+ throw new HttpError(400, "bad_request", "bad mouse action");+ }+ const button = e["button"];+ if (button !== undefined && button !== "left" && button !== "middle" && button !== "right") {+ throw new HttpError(400, "bad_request", "bad mouse button");+ }+ return {+ type: "mouse",+ action,+ x: coordinate(e["x"]),+ y: coordinate(e["y"]),+ ...(button === undefined ? {} : { button }),+ ...(e["buttons"] === undefined ? {} : { buttons: bitmask(e["buttons"]) }),+ ...(e["clickCount"] === undefined ? {} : { clickCount: coordinate(e["clickCount"]) }),+ };+ }+ if (type === "wheel") {+ return {+ type: "wheel",+ x: coordinate(e["x"]),+ y: coordinate(e["y"]),+ deltaY: amount(e["deltaY"]),+ ...(e["deltaX"] === undefined ? {} : { deltaX: amount(e["deltaX"]) }),+ };+ }+ if (type === "text") {+ return { type: "text", text: requireString(e, "text", { label: "text", maxLen: 10_000 }) };+ }+ if (type === "key") {+ const action = e["action"];+ if (action !== "down" && action !== "up")+ throw new HttpError(400, "bad_request", "bad key action");+ return {+ type: "key",+ action,+ key: requireString(e, "key", { label: "key", maxLen: 64 }),+ ...(typeof e["code"] === "string" ? { code: e["code"] } : {}),+ ...(e["keyCode"] === undefined ? {} : { keyCode: coordinate(e["keyCode"]) }),+ ...(typeof e["text"] === "string" ? { text: e["text"] } : {}),+ };+ }+ throw new HttpError(400, "bad_request", "unknown input event");+}++/** A coordinate or count: a finite, non-negative, half-pixel-precise number. */+function coordinate(value: unknown): number {+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {+ throw new HttpError(400, "bad_request", "bad coordinate");+ }+ return Math.round(value * 100) / 100;+}++/** A wheel delta: finite, and allowed to be negative (that is scrolling up). */+function amount(value: unknown): number {+ if (typeof value !== "number" || !Number.isFinite(value)) {+ throw new HttpError(400, "bad_request", "bad wheel delta");+ }+ return value;+}++/** Which buttons are held: an integer bitmask (left 1, right 2, middle 4), so 0 to 7. */+function bitmask(value: unknown): number {+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value > 7) {+ throw new HttpError(400, "bad_request", "bad mouse buttons");+ }+ return value;+}++/**+ * An OPTIONAL JSON body: a request that sends none, or an empty one, reads as `{}` — a plain+ * reload is the common case here and sending no body is not a mistake. Text that IS there but+ * does not parse is still a 400, so a caller with a typo is told rather than silently ignored.+ */+async function readOptionalJson(c: Context<AppEnv>): Promise<Record<string, unknown>> {+ if ((await c.req.text()).trim() === "") return {};+ return readJson(c);+}++export function serverBrowserRoutes(browser: ServerBrowser): Hono<AppEnv> {+ const app = new Hono<AppEnv>();++ app.use("*", async (c, next) => {+ if (!c.var.user.isAdmin) {+ throw new HttpError(403, "admin_required", "Only an admin can use the server's browser.");+ }+ await next();+ });++ /** Every write answers with the same status the read does, so a client never guesses. */+ const answer = (+ c: Context<AppEnv>,+ work: () => Promise<ServerBrowserStatus>,+ ): Promise<Response> => work().then((status) => c.json(status));++ app.get("/", async (c) => {+ const status = await withTimeout(browser.status(), STATUS_TIMEOUT_MS);+ return c.json(status satisfies ServerBrowserStatus);+ });++ app.post("/start", (c) => answer(c, () => browser.start()));+ app.post("/stop", (c) => answer(c, () => browser.stop()));++ app.post("/navigate", async (c) => {+ const body = await readJson(c);+ const raw = requireString(body, "url", { label: "url", maxLen: 4_000 });+ const url = normalizeAddress(raw);+ if (url === null) {+ throw new HttpError(400, "invalid_url", "That is not a web address.");+ }+ return answer(c, () => browser.navigate(url));+ });++ app.post("/back", (c) => answer(c, () => browser.go("back")));+ app.post("/forward", (c) => answer(c, () => browser.go("forward")));+ app.post("/reload", async (c) => {+ // The body is optional here: a plain reload is the common case, and sending none is not an+ // error — an absent or empty body reads as `{}`, a malformed one still 400s.+ const body = await readOptionalJson(c);+ return answer(c, () => browser.reload(body["hard"] === true));+ });++ app.post("/resize", async (c) => {+ const body = await readJson(c);+ return answer(c, () => browser.resize(coordinate(body["width"]), coordinate(body["height"])));+ });++ app.post("/input", async (c) => {+ const body = await readJson(c);+ const raw = body["events"];+ if (!Array.isArray(raw) || raw.length === 0 || raw.length > 64) {+ throw new HttpError(400, "bad_request", "events must be one to 64 input events");+ }+ const events = raw.map(readInputEvent);+ return answer(c, () => browser.input(events));+ });++ app.get("/frames", (c) => {+ c.header("x-accel-buffering", "no");+ c.header("cache-control", "no-cache");+ let off: (() => void) | null = null;+ /** Stops writing, however this stream ends — the viewer leaving, or the browser going away. */+ let stop: () => void = () => {};+ /** This viewer's parts: one writer per stream, so the boundary of the first is its own. */+ const write = frameParts();+ const body = new ReadableStream<Uint8Array>({+ start(controller) {+ let open = true;+ /** The newest frame not yet written out; an older one waiting here is simply replaced. */+ let newest: Buffer | null = null;+ /** Back-pressure: the retry that keeps a frame until the viewer has room for it. */+ let retry: ReturnType<typeof setTimeout> | null = null;+ /** The follow-up part for whatever was written last (see the commit below). */+ let commit: ReturnType<typeof setTimeout> | null = null;+ /** The frame the viewer would otherwise be left holding. */+ let held: Buffer | null = null;++ const send = (jpeg: Buffer): void => {+ controller.enqueue(write(jpeg));+ held = jpeg;+ // A multipart part reaches the viewer's image only once the part AFTER it begins —+ // which is fine while frames keep coming, and wrong the moment they stop: the last+ // repaint of a page (a click, a page that finished loading) would never be shown, and+ // the viewer would sit on a picture of something that is no longer there. So a written+ // frame that is not followed by another within a moment is written again; the copy is+ // what the viewer takes up, and it is the same picture. A page in motion never pays+ // for this: its frames arrive well inside that moment.+ if (commit !== null) clearTimeout(commit);+ commit = setTimeout(() => {+ commit = null;+ if (!open || newest !== null || held === null) return;+ try {+ controller.enqueue(write(held));+ } catch {+ open = false;+ }+ }, FRAME_COMMIT_MS);+ };++ /**+ * Writes the newest frame out, once there is room for it. While the viewer is behind,+ * the frame waits here rather than going away: dropping the NEWEST frame is how a viewer+ * ends up showing something that is no longer on the page. What gets dropped is the older+ * frame this one replaced, which is what makes a lagging viewer catch up on the present.+ */+ const pump = (): void => {+ retry = null;+ if (!open || newest === null) return;+ if ((controller.desiredSize ?? 1) <= 0) {+ retry = setTimeout(pump, 20);+ return;+ }+ const jpeg = newest;+ newest = null;+ try {+ send(jpeg);+ } catch {+ open = false;+ }+ };+ stop = () => {+ open = false;+ for (const timer of [retry, commit]) if (timer !== null) clearTimeout(timer);+ retry = null;+ commit = null;+ };+ off = browser.view((out) => {+ if (!open) return;+ if (out.kind === "frame") {+ newest = out.jpeg;+ if (retry === null) pump();+ return;+ }+ if (out.kind === "closed") {+ open = false;+ try {+ controller.close();+ } catch {+ // Already closed by the peer going away.+ }+ }+ });+ },+ cancel() {+ off?.();+ off = null;+ stop();+ },+ });+ return new Response(body, {+ headers: { "content-type": `multipart/x-mixed-replace; boundary=${BOUNDARY}` },+ });+ });++ return app;+}++/** A status read that cannot hang a request forever, whatever the browser is doing. */+function withTimeout<T>(work: Promise<T>, ms: number): Promise<T> {+ return Promise.race([+ work,+ new Promise<T>((_resolve, reject) => {+ setTimeout(+ () => reject(new HttpError(504, "browser_timeout", "The browser did not answer.")),+ ms,+ );+ }),+ ]);+}++/**+ * The route group: the same prefix and auth level as every other user-authenticated surface,+ * with the admin check inside the group rather than in the middleware — this is a server-level+ * resource, and the 403 comes from the same place the rule is written.+ */+@Component({+ contributes: {+ "HttpModule.routes": [+ {+ id: "server-browser.routes",+ prefix: "/api/server-browser",+ auth: "user",+ order: 72,+ },+ ],+ },+})+export class ServerBrowserRoutes {+ @Use() private readonly browser!: ServerBrowser;+ @Bind("server-browser.routes") routes!: Hono<AppEnv>;+ setup() {+ this.routes = serverBrowserRoutes(this.browser);+ }+}diff --git a/packages/server/src/platform.ts b/packages/server/src/platform.tsindex 53b7e86e..8b40f0dc 100644--- a/packages/server/src/platform.ts+++ b/packages/server/src/platform.ts@@ -88,6 +88,8 @@ import { ErrorRecorder } from "./runtime/error-recorder.js";import { UsageRecorder } from "./runtime/usage-recorder.js";import { UsageService } from "./services/usage-service.js";import { StorageAdmin, StorageService } from "./services/storage-service.js";+import { ServerBrowser, ServerBrowserService } from "./services/server-browser-service.js";+import { ServerBrowserRoutes } from "./http/routes/server-browser.js";import { ProjectConfigService } from "./services/project-config-service.js";import { ModelOAuthService } from "./services/model-oauth-service.js";import { PlatformAuth, PlatformAuthProvider } from "./services/platform-auth-service.js";@@ -493,6 +495,18 @@ export class ApiModule {}})export class WorkflowsModule {}+/**+ * The browser the server renders itself, for the deployments that cannot have the desktop one:+ * a group of its own, because its two nodes are the whole of it — the browser (which spawns a+ * Chromium and owns the profile in the data root) and the routes over it. Nothing else in the+ * tree names it, so both stay in the group and only `ServerBrowser` leaves it.+ */+@Module({+ children: [ServerBrowserService, ServerBrowserRoutes],+ exports: [ServerBrowser],+})+export class ServerBrowserModule {}+/** The root: provides nothing and requires nothing; it exists so the groups have a scope to see each other in. */@Module({children: [@@ -515,6 +529,7 @@ export class WorkflowsModule {}MachinesModule,TerminalRelay,WorkflowsModule,+ ServerBrowserModule,BuiltinBrowserModule,AgentApiModule,Startup,diff --git a/packages/server/src/server-browser/cdp.ts b/packages/server/src/server-browser/cdp.tsnew file mode 100644index 00000000..cdc3a437--- /dev/null+++ b/packages/server/src/server-browser/cdp.ts@@ -0,0 +1,227 @@+/**+ * The smallest CDP client this needs: one WebSocket to a browser's DevTools endpoint, requests+ * matched by id, events handed to listeners. Flattened sessions (Target.attachToTarget) ride in+ * the same socket, which is why every call takes an optional session id.+ *+ * The transport is an interface rather than `ws` itself so the routing can be tested without a+ * browser — the terminal's own reason for splitting its stream from its socket. Nothing here+ * reaches the network.+ */+import { WebSocket } from "ws";++/** One socket, as this client uses it: text frames both ways, and a close to hear about. */+export interface CdpSocket {+ send(data: string): void;+ close(): void;+ /** Returns the unsubscribe. */+ onMessage(listener: (data: string) => void): () => void;+ onClose(listener: (err?: Error) => void): () => void;+}++/** One CDP event, as it arrives: the method, its params, and the session that sent it. */+export interface CdpEvent {+ method: string;+ params: Record<string, unknown>;+ sessionId?: string;+}++/** How long one CDP call may take. Bounded: a wedged browser must not hold a request open. */+export const CDP_CALL_TIMEOUT_MS = 30_000;++/** A CDP call that failed: the browser answered with an error, or it did not answer in time. */+export class CdpError extends Error {+ constructor(+ readonly kind: "refused" | "timeout" | "closed",+ message: string,+ ) {+ super(message);+ this.name = "CdpError";+ }+}++interface Pending {+ resolve(result: Record<string, unknown>): void;+ reject(err: CdpError): void;+ timer: NodeJS.Timeout;+}++/** Raises the `data` of a frame to a listener, tolerating anything that is not a CDP frame. */+function asFrame(raw: string): {+ id?: number;+ method?: string;+ params?: unknown;+ sessionId?: string;+ result?: unknown;+ error?: { message?: string };+} | null {+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch {+ return null;+ }+ return typeof parsed === "object" && parsed !== null ? (parsed as never) : null;+}++export class CdpConnection {+ private readonly pending = new Map<number, Pending>();+ private readonly listeners = new Set<(event: CdpEvent) => void>();+ private readonly closeListeners = new Set<(err?: Error) => void>();+ private nextId = 0;+ private closed: Error | null = null;++ constructor(+ private readonly socket: CdpSocket,+ private readonly callTimeoutMs: number = CDP_CALL_TIMEOUT_MS,+ ) {+ socket.onMessage((data) => this.receive(data));+ socket.onClose((err) => this.fail(err ?? new Error("the browser closed the connection")));+ }++ /** Sends one CDP call and resolves with its result. `sessionId` targets an attached tab. */+ call(+ method: string,+ params: Record<string, unknown> = {},+ sessionId?: string,+ ): Promise<Record<string, unknown>> {+ if (this.closed !== null) return Promise.reject(new CdpError("closed", this.closed.message));+ this.nextId += 1;+ const id = this.nextId;+ return new Promise<Record<string, unknown>>((resolve, reject) => {+ const timer = setTimeout(() => {+ this.pending.delete(id);+ reject(+ new CdpError(+ "timeout",+ `the browser did not answer ${method} within ${this.callTimeoutMs}ms`,+ ),+ );+ }, this.callTimeoutMs);+ this.pending.set(id, { resolve, reject, timer });+ try {+ this.socket.send(+ JSON.stringify({ id, method, params, ...(sessionId === undefined ? {} : { sessionId }) }),+ );+ } catch (err) {+ clearTimeout(timer);+ this.pending.delete(id);+ reject(new CdpError("closed", err instanceof Error ? err.message : String(err)));+ }+ });+ }++ /** Every CDP event. Returns the unsubscribe. */+ onEvent(listener: (event: CdpEvent) => void): () => void {+ this.listeners.add(listener);+ return () => this.listeners.delete(listener);+ }++ /** Called once when the socket goes away, for whatever reason. */+ onClose(listener: (err?: Error) => void): () => void {+ this.closeListeners.add(listener);+ return () => this.closeListeners.delete(listener);+ }++ close(): void {+ this.socket.close();+ this.fail(new Error("closed by this server"));+ }++ /** Whether the socket is still usable. */+ get alive(): boolean {+ return this.closed === null;+ }++ private receive(raw: string): void {+ const frame = asFrame(raw);+ if (frame === null) return;+ if (typeof frame.id === "number") {+ const pending = this.pending.get(frame.id);+ if (pending === undefined) return;+ this.pending.delete(frame.id);+ clearTimeout(pending.timer);+ if (frame.error !== undefined) {+ pending.reject(+ new CdpError("refused", frame.error.message ?? "the browser refused the call"),+ );+ } else {+ pending.resolve((frame.result ?? {}) as Record<string, unknown>);+ }+ return;+ }+ if (typeof frame.method !== "string") return;+ const event: CdpEvent = {+ method: frame.method,+ params:+ typeof frame.params === "object" && frame.params !== null+ ? (frame.params as Record<string, unknown>)+ : {},+ ...(typeof frame.sessionId === "string" ? { sessionId: frame.sessionId } : {}),+ };+ for (const listener of this.listeners) {+ try {+ listener(event);+ } catch {+ // A listener's failure must not take the socket's reader down with it: this runs inside+ // the ws message handler, where a throw is an uncaught exception.+ }+ }+ }++ private fail(err: Error): void {+ if (this.closed !== null) return;+ this.closed = err;+ for (const [id, pending] of this.pending) {+ clearTimeout(pending.timer);+ pending.reject(new CdpError("closed", err.message));+ this.pending.delete(id);+ }+ for (const listener of this.closeListeners) {+ try {+ listener(err);+ } catch {+ // Same as above: a close listener that throws is not worth the process.+ }+ }+ this.closeListeners.clear();+ this.listeners.clear();+ }+}++/** Opens a CDP connection to a `ws://…/devtools/browser/<id>` endpoint. */+export function connectCdp(+ endpoint: string,+ timeoutMs = CDP_CALL_TIMEOUT_MS,+): Promise<CdpConnection> {+ return new Promise((resolve, reject) => {+ const ws = new WebSocket(endpoint, {+ // Screencast frames and screenshots are the largest things crossing this socket.+ maxPayload: 256 * 1024 * 1024,+ handshakeTimeout: 15_000,+ });+ const connection = new CdpConnection(+ {+ send: (data) => ws.send(data),+ close: () => ws.close(),+ onMessage: (listener) => {+ const handler = (data: unknown): void => listener(String(data));+ ws.on("message", handler);+ return () => ws.off("message", handler);+ },+ onClose: (listener) => {+ const onClose = (): void => listener();+ const onError = (err: Error): void => listener(err);+ ws.once("close", onClose);+ ws.once("error", onError);+ return () => {+ ws.off("close", onClose);+ ws.off("error", onError);+ };+ },+ },+ timeoutMs,+ );+ ws.once("open", () => resolve(connection));+ ws.once("error", (err: Error) => reject(err));+ });+}diff --git a/packages/server/src/server-browser/process.ts b/packages/server/src/server-browser/process.tsnew file mode 100644index 00000000..a0619016--- /dev/null+++ b/packages/server/src/server-browser/process.ts@@ -0,0 +1,279 @@+/**+ * The server's own browser process: a real Chromium (or Chrome) on a virtual display, driven+ * over CDP. This is the piece the desktop app replaces with Electron guests — a `<webview>`+ * lives in a window, and a server has none, so the picture is produced here instead and handed+ * out as frames (see session.ts).+ *+ * Why a display at all: a windowed Chromium under Xvfb is a browser in the ordinary sense.+ * `--headless` is cheaper but the sites this exists for see it, and headless Chromium on a+ * Debian box also carries no proprietary codecs or a real GPU path, so video that plays in the+ * picture a person is watching does not play at all. Xvfb is X11-only and optional: where a+ * DISPLAY is already set (a desktop machine running the server, a container with its own X) it+ * is used as it is.+ *+ * The profile is a directory the caller owns and this class only fills in: it carries the+ * sign-ins, so a browser restarted after an upgrade is still signed in where the person left+ * it. Chromium's own singleton files are cleared first — a process killed hard leaves them+ * behind and the next start would silently hand its URL to a browser that is not running.+ */+import { spawn } from "node:child_process";+import type { ChildProcess } from "node:child_process";+import { access, constants, mkdir, rm } from "node:fs/promises";+import { existsSync } from "node:fs";+import path from "node:path";++/** How long the DevTools endpoint may take to appear, and how long a stop waits before killing. */+const ENDPOINT_TIMEOUT_MS = 30_000;+const STOP_GRACE_MS = 4_000;+/** How long Xvfb may take to be ready to accept clients. */+const DISPLAY_SETTLE_MS = 1_200;++/**+ * The browsers this will run, in the order they are preferred: whatever the distribution or the+ * person installed, Chromium first because that is what a server image tends to carry. Env+ * override wins over all of them (ADELIE_SERVER_BROWSER_BIN) for a machine whose browser is+ * somewhere else, or is a different build entirely.+ */+const LINUX_CANDIDATES = [+ "chromium",+ "chromium-browser",+ "google-chrome-stable",+ "google-chrome",+ "chrome",+];+const MAC_CANDIDATES = [+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",+ "/Applications/Chromium.app/Contents/MacOS/Chromium",+].filter((p) => existsSync(p));++/** The binary to run, or null when this machine has none this knows about. */+export function findBrowserBinary(+ env: Record<string, string | undefined> = process.env,+): string | null {+ const named = env["ADELIE_SERVER_BROWSER_BIN"];+ if (named !== undefined && named.trim() !== "") return named.trim();+ const search = env["PATH"] ?? process.env["PATH"] ?? "";+ for (const candidate of process.platform === "darwin" ? MAC_CANDIDATES : LINUX_CANDIDATES) {+ const found = which(candidate, search);+ if (found !== null) return found;+ }+ return null;+}++/** PATH lookup, without shelling out: a candidate that is a path is used as it is. */+function which(name: string, search: string): string | null {+ if (name.includes("/")) return existsSync(name) ? name : null;+ for (const dir of search.split(path.delimiter)) {+ if (dir === "") continue;+ const full = path.join(dir, name);+ if (existsSync(full)) return full;+ }+ return null;+}++/** An X server for the browser to draw on, started by us so it can be stopped by us. */+interface Display {+ value: string;+ stop(): void;+}++/**+ * The display to use: the one already in the environment, or a fresh Xvfb. Null when neither+ * exists, which is the one case where the server cannot render a browser at all — a headless+ * container image with no Xvfb installed.+ *+ * The number picked is the first free one from 99 up: a fixed 99 would collide with a second+ * Adelie (or anything else) already holding it, and the socket is what decides.+ */+async function ensureDisplay(+ width: number,+ height: number,+ log: (line: string) => void,+): Promise<Display | null> {+ const existing = process.env["DISPLAY"];+ if (existing !== undefined && existing.trim() !== "") {+ return { value: existing, stop: () => {} };+ }+ if (process.platform !== "linux") return null;+ const xvfb = which("Xvfb", process.env["PATH"] ?? "");+ if (xvfb === null) return null;+ for (let n = 99; n < 130; n += 1) {+ if (existsSync(`/tmp/.X11-unix/X${n}`)) continue;+ const proc = spawn(+ xvfb,+ [`:${n}`, "-screen", "0", `${width}x${height}x24`, "-nolisten", "tcp"],+ {+ stdio: "ignore",+ detached: false,+ },+ );+ let died = false;+ proc.once("exit", () => {+ died = true;+ });+ await new Promise((r) => setTimeout(r, DISPLAY_SETTLE_MS));+ if (died) continue;+ log(`[browser] Xvfb :${n} (${width}x${height})`);+ return {+ value: `:${n}`,+ stop: () => {+ try {+ proc.kill("SIGTERM");+ } catch {+ // Already gone: nothing to stop.+ }+ },+ };+ }+ return null;+}++export interface BrowserProcessOptions {+ /** The profile directory, created when missing. */+ profileDir: string;+ width: number;+ height: number;+ /** The binary; discovered when omitted. */+ binary?: string;+ log?: (line: string) => void;+}++/**+ * A running browser, from the process side: where it draws (Xvfb when this machine has no+ * display of its own), where its DevTools endpoint is, and how to put it down again.+ */+export class BrowserProcess {+ private constructor(+ readonly binary: string,+ readonly endpoint: string,+ private readonly child: ChildProcess,+ private readonly display: Display,+ readonly profileDir: string,+ private readonly log: (line: string) => void,+ ) {}++ /** Starts one browser: display, profile, process, and waits for the DevTools endpoint. */+ static async start(options: BrowserProcessOptions): Promise<BrowserProcess> {+ const log = options.log ?? (() => {});+ const binary = options.binary ?? findBrowserBinary();+ if (binary === null) throw new Error("no Chromium or Chrome on this machine");++ const display = await ensureDisplay(options.width, options.height, log);+ if (display === null) {+ throw new Error("no display and no Xvfb: this machine cannot render a browser");+ }++ await mkdir(options.profileDir, { recursive: true });+ await clearSingletonFiles(options.profileDir);++ const child = spawn(+ binary,+ [+ // 0 asks the OS for a free port; the endpoint it prints is what we connect to, so two+ // servers on one machine can never fight over 9222.+ "--remote-debugging-port=0",+ `--user-data-dir=${options.profileDir}`,+ "--no-first-run",+ "--no-default-browser-check",+ "--disable-dev-shm-usage",+ // Chromium refuses to run as root without this, and a server commonly is root. It+ // removes Chromium's own process sandbox; the browser here only ever visits pages the+ // person asked for, in a profile of its own.+ "--no-sandbox",+ `--window-size=${options.width},${options.height}`,+ "--window-position=0,0",+ "about:blank",+ ],+ {+ env: { ...process.env, DISPLAY: display.value },+ stdio: ["ignore", "ignore", "pipe"],+ },+ );++ try {+ const endpoint = await endpointOf(child);+ log(`[browser] ${binary} on ${display.value}`);+ return new BrowserProcess(binary, endpoint, child, display, options.profileDir, log);+ } catch (err) {+ child.kill("SIGKILL");+ display.stop();+ throw err;+ }+ }++ /** Whether this process is still up. */+ get running(): boolean {+ return this.child.exitCode === null && !this.child.killed;+ }++ /** Takes the browser down, then the display. Never throws: a stop that failed is a stop. */+ async stop(): Promise<void> {+ await endProcess(this.child);+ this.display.stop();+ }+}++/** Chromium prints `DevTools listening on ws://127.0.0.1:<port>/devtools/browser/<id>` on stderr. */+function endpointOf(child: ChildProcess): Promise<string> {+ return new Promise((resolve, reject) => {+ let seen = "";+ const timer = setTimeout(() => {+ reject(new Error(`the browser printed no DevTools endpoint within ${ENDPOINT_TIMEOUT_MS}ms`));+ }, ENDPOINT_TIMEOUT_MS);+ const finish = (err: Error | null, endpoint?: string): void => {+ clearTimeout(timer);+ child.stderr?.off("data", onData);+ child.off("exit", onExit);+ if (err !== null) reject(err);+ else resolve(endpoint as string);+ };+ const onData = (chunk: Buffer): void => {+ seen += chunk.toString();+ const match = /ws:\/\/[^\s]+/.exec(seen);+ if (match !== null) finish(null, match[0]);+ };+ const onExit = (code: number | null): void => {+ finish(new Error(`the browser exited with code ${code ?? "null"} before answering`));+ };+ child.stderr?.on("data", onData);+ child.once("exit", onExit);+ });+}++/** SIGTERM, wait, SIGKILL: a browser that ignores the first does not get to keep the profile. */+async function endProcess(child: ChildProcess): Promise<void> {+ if (child.exitCode !== null || child.signalCode !== null) return;+ const gone = new Promise<void>((resolve) => {+ child.once("exit", () => resolve());+ setTimeout(resolve, STOP_GRACE_MS);+ });+ try {+ child.kill("SIGTERM");+ } catch {+ return;+ }+ await gone;+ try {+ child.kill("SIGKILL");+ } catch {+ // Already gone.+ }+}++/**+ * Chromium's profile singletons, removed before every start: they are a lock and a socket, and+ * one left behind by a process that was killed makes the next browser hand its arguments to a+ * browser that no longer exists and exit. Only these three files: everything else in the+ * directory is the person's profile.+ */+async function clearSingletonFiles(profileDir: string): Promise<void> {+ for (const name of ["SingletonLock", "SingletonSocket", "SingletonCookie"]) {+ const file = path.join(profileDir, name);+ try {+ await access(file, constants.F_OK);+ } catch {+ continue;+ }+ await rm(file, { force: true, recursive: true });+ }+}diff --git a/packages/server/src/server-browser/session.ts b/packages/server/src/server-browser/session.tsnew file mode 100644index 00000000..65394a68--- /dev/null+++ b/packages/server/src/server-browser/session.ts@@ -0,0 +1,405 @@+/**+ * One page, driven over CDP: where it is, how big it is drawn, what it looks like right now, and+ * the four things a viewer can do to it (navigate, go back/forward, reload, and input).+ *+ * One page and not a tab strip: what this exists for is watching a page the person cannot reach+ * from their own machine, and a second tab is the first thing that turns into a window manager.+ * The several tabs the desktop app's built-in browser has stay there.+ *+ * The picture is `Page.startScreencast`: the browser sends a JPEG whenever the page changes, so a+ * page standing still costs nothing and a playing video costs what it is worth watching. Frames+ * go out only while somebody is subscribed — a session with no viewer runs no screencast at all.+ *+ * Everything the viewer needs to know besides the pixels is the state: address, title, whether it+ * is still loading. That comes from the browser's own events (target info changes, load events),+ * never from polling or from injecting scripts into the page.+ */+import type { ServerBrowserInput, ServerBrowserState } from "../api/types.js";+import { CdpConnection, connectCdp } from "./cdp.js";+import type { CdpEvent } from "./cdp.js";+import type { BrowserProcess } from "./process.js";++/** The viewport a viewer asks for is clamped to this, so one page cannot eat a server. */+export const MIN_VIEWPORT = { width: 320, height: 240 };+export const MAX_VIEWPORT = { width: 1920, height: 1200 };+/** JPEG quality and per-frame cap for the screencast: a picture to watch, not a screenshot. */+const FRAME_QUALITY = 55;++export type ServerBrowserOutput =+ | { kind: "frame"; jpeg: Buffer }+ | { kind: "state"; state: ServerBrowserState }+ /**+ * The session is over: the browser went away, or somebody stopped it. The viewer's stream ends+ * with this rather than going quiet, so a page that was watching reconnects and learns where+ * the browser went instead of holding its last frame forever.+ */+ | { kind: "closed"; reason: string };++export interface ServerBrowserSessionDeps {+ width: number;+ height: number;+ log?: (line: string) => void;+}++/** The address to actually load: a bare host is https, and anything else must be a web address. */+export function normalizeAddress(input: string): string | null {+ const trimmed = input.trim();+ if (trimmed === "") return null;+ // A scheme is one only when `//` follows it: `example.com:8080` is a host and a port, and+ // reading that colon as a scheme is how a bare address carrying a port gets silently lost.+ const addressed = /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`;+ try {+ const url = new URL(addressed);+ return url.protocol === "http:" || url.protocol === "https:" ? url.toString() : null;+ } catch {+ return null;+ }+}++/** Clamps a requested viewport into what this will render. */+export function clampViewport(width: number, height: number): { width: number; height: number } {+ const clamp = (value: number, min: number, max: number): number =>+ Math.max(min, Math.min(max, Math.round(value)));+ return {+ width: clamp(width, MIN_VIEWPORT.width, MAX_VIEWPORT.width),+ height: clamp(height, MIN_VIEWPORT.height, MAX_VIEWPORT.height),+ };+}++export class ServerBrowserSession {+ private listeners = new Set<(out: ServerBrowserOutput) => void>();+ private targetId = "";+ private sessionId = "";+ private unsubscribes: Array<() => void> = [];+ private table: ServerBrowserState;+ private closed = false;+ private streaming = false;+ private crashReason: string | null = null;++ private constructor(+ private readonly cdp: CdpConnection,+ private readonly log: (line: string) => void,+ initial: ServerBrowserState,+ ) {+ this.table = initial;+ }++ /** Attaches to the browser's page target and starts following its state. */+ static async attach(+ cdp: CdpConnection,+ deps: ServerBrowserSessionDeps,+ ): Promise<ServerBrowserSession> {+ const log = deps.log ?? (() => {});+ const { targetInfos } = (await cdp.call("Target.getTargets")) as {+ targetInfos?: Array<{ targetId?: string; type?: string; url?: string; title?: string }>;+ };+ const page = (targetInfos ?? []).find(+ (t) => t.type === "page" && typeof t.targetId === "string",+ );+ if (page?.targetId === undefined) throw new Error("the browser has no page to show");++ const { sessionId } = (await cdp.call("Target.attachToTarget", {+ targetId: page.targetId,+ flatten: true,+ })) as { sessionId?: string };+ if (typeof sessionId !== "string") throw new Error("the browser refused to attach to its page");++ const viewport = clampViewport(deps.width, deps.height);+ const session = new ServerBrowserSession(cdp, log, {+ url: page.url ?? "",+ title: page.title ?? "",+ loading: false,+ width: viewport.width,+ height: viewport.height,+ });+ session.targetId = page.targetId;+ session.sessionId = sessionId;++ await cdp.call("Page.enable", {}, sessionId);+ await cdp.call("Target.setDiscoverTargets", { discover: true });+ await session.applyViewport(viewport.width, viewport.height);++ session.unsubscribes.push(cdp.onEvent((event) => session.receive(event)));+ cdp.onClose((err) => session.close(err ?? new Error("the browser went away")));+ return session;+ }++ state(): ServerBrowserState {+ return { ...this.table };+ }++ /** Loads an address; `url` is normalized first and a non-web one is refused by the caller. */+ async navigate(url: string): Promise<void> {+ this.table = { ...this.table, url, loading: true };+ this.publishState();+ await this.cdp.call("Page.navigate", { url }, this.sessionId);+ }++ /** Whether there is anywhere to go back to, as far as the page's own history knows. */+ async go(direction: "back" | "forward"): Promise<void> {+ const history = (await this.cdp.call("Page.getNavigationHistory", {}, this.sessionId)) as {+ currentIndex?: number;+ entries?: Array<{ id?: number }>;+ };+ const index = history.currentIndex ?? 0;+ const entry = (history.entries ?? [])[direction === "back" ? index - 1 : index + 1];+ if (entry?.id === undefined) return;+ await this.cdp.call("Page.navigateToHistoryEntry", { entryId: entry.id }, this.sessionId);+ }++ async reload(hard: boolean): Promise<void> {+ this.table = { ...this.table, loading: true };+ this.publishState();+ await this.cdp.call("Page.reload", { ignoreCache: hard }, this.sessionId);+ }++ /** Draws the page at another size, which is what a viewer's box just became. */+ async resize(width: number, height: number): Promise<void> {+ const viewport = clampViewport(width, height);+ if (viewport.width === this.table.width && viewport.height === this.table.height) return;+ await this.applyViewport(viewport.width, viewport.height);+ }++ /** One input event, from the viewer's pointer or keyboard. */+ async input(event: ServerBrowserInput): Promise<void> {+ if (this.crashReason !== null) throw new Error(`the page crashed (${this.crashReason})`);+ if (event.type === "mouse") {+ await this.cdp.call(+ "Input.dispatchMouseEvent",+ {+ type:+ event.action === "move"+ ? "mouseMoved"+ : event.action === "down"+ ? "mousePressed"+ : "mouseReleased",+ x: event.x,+ y: event.y,+ button: event.button ?? "left",+ buttons: event.buttons ?? (event.action === "down" ? 1 : 0),+ clickCount: event.action === "move" ? 0 : (event.clickCount ?? 1),+ },+ this.sessionId,+ );+ return;+ }+ if (event.type === "wheel") {+ await this.cdp.call(+ "Input.dispatchMouseEvent",+ {+ type: "mouseWheel",+ x: event.x,+ y: event.y,+ button: "none",+ deltaX: event.deltaX ?? 0,+ deltaY: event.deltaY,+ },+ this.sessionId,+ );+ return;+ }+ if (event.type === "text") {+ await this.cdp.call("Input.insertText", { text: event.text }, this.sessionId);+ return;+ }+ await this.cdp.call(+ "Input.dispatchKeyEvent",+ {+ type: event.action === "down" ? "keyDown" : "keyUp",+ key: event.key,+ ...(event.code === undefined ? {} : { code: event.code }),+ ...(event.keyCode === undefined ? {} : { windowsVirtualKeyCode: event.keyCode }),+ ...(event.action === "down" && event.text !== undefined ? { text: event.text } : {}),+ },+ this.sessionId,+ );+ }++ /** Frames and state changes, for as long as the returned unsubscribe is not called. */+ subscribe(listener: (out: ServerBrowserOutput) => void): () => void {+ this.listeners.add(listener);+ listener({ kind: "state", state: this.state() });+ void this.startStreaming();+ return () => {+ this.listeners.delete(listener);+ if (this.listeners.size === 0) void this.stopStreaming();+ };+ }++ /** Whether this session is still usable (the browser it drives is reachable). */+ get alive(): boolean {+ return !this.closed && this.cdp.alive;+ }++ async close(reason?: Error): Promise<void> {+ if (this.closed) return;+ this.closed = true;+ if (reason !== undefined) this.log(`[browser] session closed: ${reason.message}`);+ this.emit({ kind: "closed", reason: reason?.message ?? "closed" });+ for (const off of this.unsubscribes) off();+ this.unsubscribes = [];+ this.listeners.clear();+ this.cdp.close();+ }++ private async applyViewport(width: number, height: number): Promise<void> {+ await this.cdp.call(+ "Emulation.setDeviceMetricsOverride",+ { width, height, deviceScaleFactor: 1, mobile: false },+ this.sessionId,+ );+ this.table = { ...this.table, width, height };+ this.publishState();+ }++ private async startStreaming(): Promise<void> {+ if (this.streaming || this.closed) return;+ this.streaming = true;+ try {+ await this.cdp.call(+ "Page.startScreencast",+ {+ format: "jpeg",+ quality: FRAME_QUALITY,+ maxWidth: this.table.width,+ maxHeight: this.table.height,+ everyNthFrame: 1,+ },+ this.sessionId,+ );+ } catch (err) {+ this.streaming = false;+ this.log(`[browser] screencast refused: ${err instanceof Error ? err.message : String(err)}`);+ }+ }++ private async stopStreaming(): Promise<void> {+ if (!this.streaming) return;+ this.streaming = false;+ try {+ await this.cdp.call("Page.stopScreencast", {}, this.sessionId);+ } catch {+ // The browser is busy or gone; the next subscriber starts it again.+ }+ }++ private receive(event: CdpEvent): void {+ if (this.closed) return;+ switch (event.method) {+ case "Page.screencastFrame": {+ const frameSession = event.params["sessionId"];+ void this.cdp+ .call("Page.screencastFrameAck", { sessionId: frameSession }, this.sessionId)+ .catch(() => {});+ const data = event.params["data"];+ if (typeof data === "string") {+ this.emit({ kind: "frame", jpeg: Buffer.from(data, "base64") });+ }+ return;+ }+ case "Target.targetInfoChanged": {+ const info = event.params["targetInfo"] as { targetId?: string; url?: string } | undefined;+ if (info?.targetId !== this.targetId || typeof info.url !== "string") return;+ // The address only: the target's own title lags the document's (it keeps the host name a+ // page commits under), so the title comes from the history entry instead — see+ // refreshTitle().+ if (info.url === this.table.url) return;+ this.table = { ...this.table, url: info.url };+ this.publishState();+ return;+ }+ case "Page.frameNavigated": {+ const frame = event.params["frame"] as+ { id?: string; url?: string; parentId?: string } | undefined;+ if (frame === undefined || frame.parentId !== undefined || typeof frame.url !== "string")+ return;+ // The main frame's id is what the two loading events below are filtered by: a page full+ // of iframes would otherwise keep resetting the state line as they come and go.+ if (typeof frame.id === "string") this.frameId = frame.id;+ this.crashReason = null;+ this.table = { ...this.table, url: frame.url, loading: true };+ this.publishState();+ void this.refreshTitle();+ return;+ }+ case "Page.frameStoppedLoading": {+ if (event.params["frameId"] !== this.frameId) return;+ this.setLoading(false);+ void this.refreshTitle();+ return;+ }+ case "Page.frameStartedLoading": {+ if (event.params["frameId"] !== this.frameId) return;+ this.setLoading(true);+ return;+ }+ case "Page.loadEventFired": {+ this.setLoading(false);+ void this.refreshTitle();+ return;+ }+ case "Inspector.targetCrashed": {+ this.crashReason = "crashed";+ this.table = { ...this.table, loading: false };+ this.publishState();+ return;+ }+ default:+ return;+ }+ }++ /** The main frame's id, as the browser reports it; "" until the first navigation. */+ private frameId = "";++ /**+ * The page's own title, read from the history entry it is on. The target's own title is not+ * it: a page that commits with a `<title>` still reports its host name there until something+ * else moves it, and the history entry is what the browser's own window title comes from. No+ * script is run in the page for this — the title is asked of the browser, not of the document.+ */+ private async refreshTitle(): Promise<void> {+ try {+ const history = (await this.cdp.call("Page.getNavigationHistory", {}, this.sessionId)) as {+ currentIndex?: number;+ entries?: Array<{ title?: string }>;+ };+ const title = (history.entries ?? [])[history.currentIndex ?? -1]?.title ?? "";+ if (title === this.table.title) return;+ this.table = { ...this.table, title };+ this.publishState();+ } catch {+ // The page is mid-navigation or the browser is gone; the title it already shows stands.+ }+ }++ /** Loading only means something the first time it changes: a state line per event would flood. */+ private setLoading(loading: boolean): void {+ if (this.table.loading === loading) return;+ this.table = { ...this.table, loading };+ this.publishState();+ }++ private publishState(): void {+ this.emit({ kind: "state", state: this.state() });+ }++ private emit(out: ServerBrowserOutput): void {+ for (const listener of this.listeners) {+ try {+ listener(out);+ } catch {+ // A viewer that threw while being written to is dropped by its own transport, not here.+ }+ }+ }+}++/** Starts the browser and attaches a session to it. */+export async function openSession(+ process: BrowserProcess,+ deps: ServerBrowserSessionDeps,+): Promise<ServerBrowserSession> {+ const cdp = await connectCdp(process.endpoint);+ return ServerBrowserSession.attach(cdp, deps);+}diff --git a/packages/server/src/services/server-browser-service.ts b/packages/server/src/services/server-browser-service.tsnew file mode 100644index 00000000..f27e65d3--- /dev/null+++ b/packages/server/src/services/server-browser-service.ts@@ -0,0 +1,227 @@+/**+ * The server's own browser, as the rest of the server reaches it: one Chromium on a virtual+ * display, one page, and a frame stream a viewer can subscribe to.+ *+ * Where this sits: the built-in browser (builtin-browser/) belongs to the desktop app, because+ * its pages ARE `<webview>` elements of the app's window — a server started any other way has no+ * window and therefore no browser at all (`not_desktop`). This is the other half of that: a+ * browser the server itself renders, for exactly the deployments that cannot have the desktop+ * one — a Linux box reached over the network.+ *+ * Lifetime: nothing is spawned until somebody asks (a Start, or a viewer opening the page), the+ * profile lives in the data root so sign-ins survive a restart, and one browser serves every+ * viewer. A browser this process started is this process's to stop.+ *+ * Unavailable rather than broken where it cannot work: no Chromium on the machine, or+ * ADELIE_SERVER_BROWSER=off, means `available: false` with the reason, and no route ever starts+ * a process then.+ */+import path from "node:path";+import { Component, Interface, Use } from "@adelie/core/kernel";+import type { ClassCtx } from "@adelie/core/kernel";+import type { ServerBrowserInput, ServerBrowserStatus } from "../api/types.js";+import type { Config } from "../hmr/capabilities.js";+import { HttpError } from "../http/errors.js";+import { BrowserProcess, findBrowserBinary } from "../server-browser/process.js";+import { openSession } from "../server-browser/session.js";+import type { ServerBrowserOutput, ServerBrowserSession } from "../server-browser/session.js";++/** The page size a viewer gets before it asks for its own. */+const DEFAULT_VIEWPORT = { width: 1280, height: 800 };+/** The profile directory inside the data root: the person's sign-ins, kept across restarts. */+const PROFILE_DIRNAME = "browser-profile";++const messageOf = (err: unknown): string => (err instanceof Error ? err.message : String(err));++/** One viewer's subscription, from the moment it arrives to the session it ends up on. */+interface Viewer {+ readonly listener: (out: ServerBrowserOutput) => void;+ /** Set once the session is up; null while the browser is still starting. */+ off: (() => void) | null;+}++/** The mechanism the routes and the frame transport both use. */+@Interface()+export abstract class ServerBrowser {+ abstract status(): Promise<ServerBrowserStatus>;+ /** Starts (or restarts) the browser; a no-op when it is already up. */+ abstract start(): Promise<ServerBrowserStatus>;+ /** Stops it, taking the page and the display down with it. */+ abstract stop(): Promise<ServerBrowserStatus>;+ abstract navigate(url: string): Promise<ServerBrowserStatus>;+ abstract go(direction: "back" | "forward"): Promise<ServerBrowserStatus>;+ abstract reload(hard: boolean): Promise<ServerBrowserStatus>;+ abstract resize(width: number, height: number): Promise<ServerBrowserStatus>;+ abstract input(events: readonly ServerBrowserInput[]): Promise<ServerBrowserStatus>;+ /**+ * Everything a viewer needs to see and follow the page: frames, every state change, and one+ * `closed` when the browser goes away. Starts the browser when it is not up. The returned+ * unsubscribe takes this viewer off, and the screencast stops once the last one is gone.+ */+ abstract view(listener: (out: ServerBrowserOutput) => void): () => void;+}++@Component()+export class ServerBrowserService implements ServerBrowser {+ @Use() private readonly config!: Config;+ /** Environment to read ADELIE_SERVER_BROWSER from; a test wires its own. */+ private env: Record<string, string | undefined> = process.env;+ private process: BrowserProcess | null = null;+ private session: ServerBrowserSession | null = null;+ private starting: Promise<ServerBrowserSession> | null = null;+ private readonly viewers = new Set<Viewer>();++ /**+ * The browser is this process's child, so it goes down with the App: a hot swap hands the+ * profile to the next generation's browser instead of leaving two of them on one display, and a+ * stopped server leaves no Chromium behind.+ */+ setup({ effect }: ClassCtx): void {+ effect(() => {+ void this.shutdown("the server is going down");+ });+ }++ async status(): Promise<ServerBrowserStatus> {+ const why = this.unavailableReason();+ if (why !== null) return { available: false, reason: why, running: false, state: null };+ if (!this.running()) return { available: true, running: false, state: null };+ return { available: true, running: true, state: this.session?.state() ?? null };+ }++ async start(): Promise<ServerBrowserStatus> {+ await this.ensure();+ return this.status();+ }++ async stop(): Promise<ServerBrowserStatus> {+ await this.shutdown("stopped");+ return this.status();+ }++ async navigate(url: string): Promise<ServerBrowserStatus> {+ const session = await this.ensure();+ await session.navigate(url);+ return this.status();+ }++ async go(direction: "back" | "forward"): Promise<ServerBrowserStatus> {+ const session = await this.ensure();+ await session.go(direction);+ return this.status();+ }++ async reload(hard: boolean): Promise<ServerBrowserStatus> {+ const session = await this.ensure();+ await session.reload(hard);+ return this.status();+ }++ async resize(width: number, height: number): Promise<ServerBrowserStatus> {+ const session = await this.ensure();+ await session.resize(width, height);+ return this.status();+ }++ async input(events: readonly ServerBrowserInput[]): Promise<ServerBrowserStatus> {+ const session = await this.ensure();+ for (const event of events) await session.input(event);+ return this.status();+ }++ view(listener: (out: ServerBrowserOutput) => void): () => void {+ const viewer: Viewer = { listener, off: null };+ this.viewers.add(viewer);+ // Opening the page is the same act as pressing Start, so the browser is started behind the+ // viewer's back rather than asking for a second press.+ void this.ensure()+ .then((session) => {+ if (!this.viewers.has(viewer)) return;+ viewer.off = session.subscribe(listener);+ })+ .catch((err: unknown) => {+ this.viewers.delete(viewer);+ listener({ kind: "closed", reason: messageOf(err) });+ });+ return () => {+ this.viewers.delete(viewer);+ viewer.off?.();+ viewer.off = null;+ };+ }++ /** Whether a browser is up and its page still reachable. */+ private running(): boolean {+ return this.session !== null && this.session.alive && (this.process?.running ?? false);+ }++ private unavailableReason(): string | null {+ if (this.env["ADELIE_SERVER_BROWSER"] === "off") {+ return "switched off by ADELIE_SERVER_BROWSER=off";+ }+ if (findBrowserBinary(this.env) === null) {+ return "no Chromium or Chrome on this machine (name one with ADELIE_SERVER_BROWSER_BIN)";+ }+ return null;+ }++ /** The live session, starting the browser when it is not up. One start at a time. */+ private ensure(): Promise<ServerBrowserSession> {+ const reason = this.unavailableReason();+ // A 503 with the reason rather than a bare failure: "this machine has no Chromium" is a fact+ // about the deployment, and the panel shows it as one (see the routes and the web page).+ if (reason !== null) {+ return Promise.reject(new HttpError(503, "browser_unavailable", reason));+ }+ if (this.running()) return Promise.resolve(this.session as ServerBrowserSession);+ this.starting ??= this.boot().finally(() => {+ this.starting = null;+ });+ return this.starting;+ }++ private async boot(): Promise<ServerBrowserSession> {+ await this.shutdown("restarting");+ const binary = findBrowserBinary(this.env) ?? undefined;+ const process0 = await BrowserProcess.start({+ profileDir: path.join(this.config.root, PROFILE_DIRNAME),+ width: DEFAULT_VIEWPORT.width,+ height: DEFAULT_VIEWPORT.height,+ ...(binary === undefined ? {} : { binary }),+ log: (line) => this.log(line),+ });+ let session: ServerBrowserSession;+ try {+ session = await openSession(process0, {+ width: DEFAULT_VIEWPORT.width,+ height: DEFAULT_VIEWPORT.height,+ log: (line) => this.log(line),+ });+ } catch (err) {+ await process0.stop();+ throw err;+ }+ this.process = process0;+ this.session = session;+ // Whoever was already watching gets moved onto the new page — a restart must not leave the+ // panel showing the last frame of a browser that no longer exists.+ for (const viewer of this.viewers) viewer.off = session.subscribe(viewer.listener);+ return session;+ }++ private async shutdown(reason: string): Promise<void> {+ const session = this.session;+ const process0 = this.process;+ this.session = null;+ this.process = null;+ // The viewers are told through the session's own subscribers, so a browser that died on its+ // own closes the streams too, not only a requested stop.+ if (session !== null) await session.close(new Error(reason));+ if (process0 !== null) await process0.stop();+ for (const viewer of this.viewers) viewer.off = null;+ }++ private log(line: string): void {+ console.warn(line);+ }+}diff --git a/packages/server/test/server-browser-cdp.test.ts b/packages/server/test/server-browser-cdp.test.tsnew file mode 100644index 00000000..f530d555--- /dev/null+++ b/packages/server/test/server-browser-cdp.test.ts@@ -0,0 +1,178 @@+/**+ * The CDP client on its own: calls matched by id, events fanned out, and the four ways a call+ * can end. The transport is a fake socket, so nothing here starts a browser — the real one is+ * exercised by the end-to-end pass in server-browser.test.ts.+ */+import { describe, expect, it, vi } from "vitest";+import { CdpConnection, CdpError } from "../src/server-browser/cdp.js";+import type { CdpEvent, CdpSocket } from "../src/server-browser/cdp.js";++interface FakeSocket extends CdpSocket {+ /** Every frame this client sent, parsed. */+ readonly sent: Array<Record<string, unknown>>;+ /** Hands `frame` to the client as if the browser had sent it. */+ deliver(frame: unknown): void;+ /** The browser's socket dropping, with or without an error. */+ drop(err?: Error): void;+ readonly closed: boolean;+}++function fakeSocket(): FakeSocket {+ const sent: Array<Record<string, unknown>> = [];+ const messageListeners = new Set<(data: string) => void>();+ const closeListeners = new Set<(err?: Error) => void>();+ let closed = false;+ return {+ sent,+ get closed() {+ return closed;+ },+ send(data: string) {+ sent.push(JSON.parse(data) as Record<string, unknown>);+ },+ close() {+ if (closed) return;+ closed = true;+ for (const listener of closeListeners) listener();+ },+ onMessage(listener) {+ messageListeners.add(listener);+ return () => messageListeners.delete(listener);+ },+ onClose(listener) {+ closeListeners.add(listener);+ return () => closeListeners.delete(listener);+ },+ deliver(frame) {+ const text = typeof frame === "string" ? frame : JSON.stringify(frame);+ for (const listener of messageListeners) listener(text);+ },+ drop(err) {+ if (closed) return;+ closed = true;+ for (const listener of closeListeners) listener(err);+ },+ };+}++/** The call a connection has just sent, as the browser would answer it. */+const answer = (socket: FakeSocket, index: number, result: unknown): void => {+ socket.deliver({ id: socket.sent[index]!["id"], result });+};++describe("the CDP connection", () => {+ it("matches an answer to the call that asked for it, in order", async () => {+ const socket = fakeSocket();+ const cdp = new CdpConnection(socket);+ const first = cdp.call("Page.navigate", { url: "https://example.test" });+ const second = cdp.call("Page.enable");+ expect(socket.sent[0]).toMatchObject({+ method: "Page.navigate",+ params: { url: "https://example.test" },+ });+ // Answered out of order: the id, not the arrival sequence, is what pairs them.+ answer(socket, 1, { enabled: true });+ answer(socket, 0, { frameId: "F1" });+ expect(await second).toEqual({ enabled: true });+ expect(await first).toEqual({ frameId: "F1" });+ });++ it("targets an attached page's session on every call made through it", async () => {+ const socket = fakeSocket();+ const cdp = new CdpConnection(socket);+ const call = cdp.call("Runtime.evaluate", { expression: "1" }, "TAB-1");+ expect(socket.sent[0]).toMatchObject({ sessionId: "TAB-1" });+ answer(socket, 0, { result: { value: 1 } });+ await expect(call).resolves.toEqual({ result: { value: 1 } });+ });++ it("rejects with the browser's own refusal, and keeps the connection usable", async () => {+ const socket = fakeSocket();+ const cdp = new CdpConnection(socket);+ const refused = cdp.call("Page.navigate", { url: "not-a-url" });+ socket.deliver({+ id: socket.sent[0]!["id"],+ error: { message: "Cannot navigate to invalid URL" },+ });+ await expect(refused).rejects.toThrowError("Cannot navigate to invalid URL");+ await expect(refused).rejects.toBeInstanceOf(CdpError);+ expect(cdp.alive).toBe(true);+ const next = cdp.call("Page.enable");+ answer(socket, 1, {});+ await expect(next).resolves.toEqual({});+ });++ it("gives up on a call the browser never answers", async () => {+ vi.useFakeTimers();+ try {+ const socket = fakeSocket();+ const cdp = new CdpConnection(socket, 500);+ const call = cdp.call("Browser.crash");+ const failure = call.catch((err: unknown) => err);+ await vi.advanceTimersByTimeAsync(500);+ const err = await failure;+ expect(err).toBeInstanceOf(CdpError);+ expect((err as CdpError).kind).toBe("timeout");+ } finally {+ vi.useRealTimers();+ }+ });++ it("fails everything in flight when the socket goes away, once", async () => {+ const socket = fakeSocket();+ const cdp = new CdpConnection(socket);+ const closes: Array<Error | undefined> = [];+ cdp.onClose((err) => closes.push(err));+ const inflight = cdp.call("Page.enable");+ socket.drop(new Error("ECONNRESET"));+ await expect(inflight).rejects.toThrowError("ECONNRESET");+ expect(closes).toHaveLength(1);+ expect(cdp.alive).toBe(false);+ // A later call is refused rather than queued behind a socket that is gone.+ await expect(cdp.call("Page.enable")).rejects.toMatchObject({ kind: "closed" });+ });++ it("hands every event to every listener, and a listener that throws does not stop the next", () => {+ const socket = fakeSocket();+ const cdp = new CdpConnection(socket);+ const seen: CdpEvent[] = [];+ cdp.onEvent((event) => {+ throw new Error("this viewer is broken");+ });+ cdp.onEvent((event) => seen.push(event));+ socket.deliver({ method: "Page.loadEventFired", params: {}, sessionId: "TAB-1" });+ expect(seen).toEqual([{ method: "Page.loadEventFired", params: {}, sessionId: "TAB-1" }]);+ });++ it("ignores anything that is not a CDP frame", () => {+ const socket = fakeSocket();+ const cdp = new CdpConnection(socket);+ const seen: CdpEvent[] = [];+ cdp.onEvent((event) => seen.push(event));+ socket.deliver("this is not JSON");+ socket.deliver("42");+ socket.deliver({ nope: true });+ expect(seen).toEqual([]);+ expect(cdp.alive).toBe(true);+ });++ it("turns a socket that refuses to send into a closed failure", async () => {+ const socket = fakeSocket();+ const cdp = new CdpConnection(socket);+ socket.send = () => {+ throw new Error("WebSocket is not open");+ };+ await expect(cdp.call("Page.enable")).rejects.toMatchObject({ kind: "closed" });+ });++ it("closing it closes the socket and tells the close listeners", () => {+ const socket = fakeSocket();+ const cdp = new CdpConnection(socket);+ const closes: Array<Error | undefined> = [];+ cdp.onClose((err) => closes.push(err));+ cdp.close();+ expect(socket.closed).toBe(true);+ expect(closes).toHaveLength(1);+ expect(cdp.alive).toBe(false);+ });+});diff --git a/packages/server/test/server-browser.test.ts b/packages/server/test/server-browser.test.tsnew file mode 100644index 00000000..2a4f5f70--- /dev/null+++ b/packages/server/test/server-browser.test.ts@@ -0,0 +1,455 @@+/**+ * The server's browser: the address and viewport rules on their own, the routes over a fake+ * browser, and the two facts about the real thing that only an app boot can show — that the+ * platform actually wires it up, and that a server told not to run one says so instead of+ * failing.+ *+ * No Chromium is started here. What the routes do to a live browser is covered by the end-to-end+ * pass in this file's last suite, which is skipped when the machine has none.+ */+import { createServer } from "node:http";+import type { AddressInfo } from "node:net";+import type { Server } from "node:http";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { Hono } from "hono";+import type { ServerBrowserInput, ServerBrowserStatus } from "../src/api/types.js";+import type { AppEnv } from "../src/auth/middleware.js";+import { handleError, normalizeError } from "../src/http/errors.js";+import { serverBrowserRoutes } from "../src/http/routes/server-browser.js";+import { ServerBrowser } from "../src/services/server-browser-service.js";+import type { ServerBrowserOutput } from "../src/server-browser/session.js";+import {+ clampViewport,+ normalizeAddress,+ MAX_VIEWPORT,+ MIN_VIEWPORT,+} from "../src/server-browser/session.js";+import { findBrowserBinary } from "../src/server-browser/process.js";+import { apiClient, createTestApp, loginAdmin } from "./helpers.js";+import type { TestApp } from "./helpers.js";++const IDLE: ServerBrowserStatus = { available: true, running: false, state: null };++/** A browser the routes can talk to without one existing: it records and answers. */+class FakeBrowser implements ServerBrowser {+ readonly calls: string[] = [];+ readonly inputs: ServerBrowserInput[][] = [];+ readonly navigations: string[] = [];+ readonly reloads: boolean[] = [];+ statusValue: ServerBrowserStatus = IDLE;+ private readonly viewers = new Set<(out: ServerBrowserOutput) => void>();++ status(): Promise<ServerBrowserStatus> {+ this.calls.push("status");+ return Promise.resolve(this.statusValue);+ }+ start(): Promise<ServerBrowserStatus> {+ this.calls.push("start");+ return Promise.resolve(this.statusValue);+ }+ stop(): Promise<ServerBrowserStatus> {+ this.calls.push("stop");+ return Promise.resolve(this.statusValue);+ }+ navigate(url: string): Promise<ServerBrowserStatus> {+ this.calls.push("navigate");+ this.navigations.push(url);+ return Promise.resolve(this.statusValue);+ }+ go(direction: "back" | "forward"): Promise<ServerBrowserStatus> {+ this.calls.push(`go:${direction}`);+ return Promise.resolve(this.statusValue);+ }+ reload(hard: boolean): Promise<ServerBrowserStatus> {+ this.calls.push("reload");+ this.reloads.push(hard);+ return Promise.resolve(this.statusValue);+ }+ resize(width: number, height: number): Promise<ServerBrowserStatus> {+ this.calls.push(`resize:${width}x${height}`);+ return Promise.resolve(this.statusValue);+ }+ input(events: readonly ServerBrowserInput[]): Promise<ServerBrowserStatus> {+ this.calls.push("input");+ this.inputs.push([...events]);+ return Promise.resolve(this.statusValue);+ }+ view(listener: (out: ServerBrowserOutput) => void): () => void {+ this.viewers.add(listener);+ return () => this.viewers.delete(listener);+ }+ /** Pushes one output to everyone watching, as a live session would. */+ emit(out: ServerBrowserOutput): void {+ for (const viewer of this.viewers) viewer(out);+ }+ get watchers(): number {+ return this.viewers.size;+ }+}++const ADMIN = { isAdmin: true } as never;++/** The route group alone, behind a middleware that injects the caller. */+function routeApp(browser: ServerBrowser, user: unknown = ADMIN) {+ const app = new Hono<AppEnv>();+ app.onError((err, c) => handleError(normalizeError(err), c));+ app.use("*", async (c, next) => {+ c.set("user", user as never);+ await next();+ });+ app.route("/api/server-browser", serverBrowserRoutes(browser));+ return app;+}++const errorOf = (body: unknown): { code: string; message: string } =>+ (body as { error: { code: string; message: string } }).error;++describe("normalizeAddress", () => {+ it("takes a bare host as https and keeps an explicit scheme", () => {+ expect(normalizeAddress("example.com")).toBe("https://example.com/");+ expect(normalizeAddress("example.com:8080/a?b=c")).toBe("https://example.com:8080/a?b=c");+ expect(normalizeAddress(" http://example.com/x ")).toBe("http://example.com/x");+ });++ it("refuses what is not a web address, and an empty one", () => {+ expect(normalizeAddress("")).toBeNull();+ expect(normalizeAddress(" ")).toBeNull();+ expect(normalizeAddress("file:///etc/passwd")).toBeNull();+ expect(normalizeAddress("javascript:alert(1)")).toBeNull();+ expect(normalizeAddress("about:blank")).toBeNull();+ // A colon in the host is read as a scheme, so this is not silently rescued into https.+ expect(normalizeAddress("http://")).toBeNull();+ });+});++describe("clampViewport", () => {+ it("holds a request between the smallest and largest page this will draw", () => {+ expect(clampViewport(1280, 800)).toEqual({ width: 1280, height: 800 });+ expect(clampViewport(1, 1)).toEqual(MIN_VIEWPORT);+ expect(clampViewport(99_999, 99_999)).toEqual(MAX_VIEWPORT);+ expect(clampViewport(640.6, 480.4)).toEqual({ width: 641, height: 480 });+ });+});++describe("findBrowserBinary", () => {+ it("prefers the environment's own binary", () => {+ expect(findBrowserBinary({ ADELIE_SERVER_BROWSER_BIN: "/opt/odd/chrome" })).toBe(+ "/opt/odd/chrome",+ );+ // A blank name is not a choice, it is an unset one.+ expect(findBrowserBinary({ ADELIE_SERVER_BROWSER_BIN: " ", PATH: "" })).toBeNull();+ });++ it("finds nothing on a machine whose PATH has no browser", () => {+ expect(findBrowserBinary({ PATH: "/nonexistent-and-empty" })).toBeNull();+ });+});++describe("the server browser's routes", () => {+ let browser: FakeBrowser;+ let app: Hono<AppEnv>;++ beforeEach(() => {+ browser = new FakeBrowser();+ app = routeApp(browser);+ });++ const post = async (apiPath: string, body?: unknown): Promise<Response> =>+ app.request(apiPath, {+ method: "POST",+ headers: body === undefined ? {} : { "content-type": "application/json" },+ ...(body === undefined+ ? {}+ : { body: typeof body === "string" ? body : JSON.stringify(body) }),+ });++ it("is an admin's tool: anyone else is refused before anything is started", async () => {+ const res = await routeApp(browser, { isAdmin: false } as never).request("/api/server-browser");+ expect(res.status).toBe(403);+ expect(errorOf(await res.json()).code).toBe("admin_required");+ expect(browser.calls).toEqual([]);+ });++ it("answers a read with what the browser is doing", async () => {+ browser.statusValue = {+ available: true,+ running: true,+ state: {+ url: "https://example.com/",+ title: "Example",+ loading: false,+ width: 1280,+ height: 800,+ },+ };+ const res = await app.request("/api/server-browser");+ expect(res.status).toBe(200);+ await expect(res.json()).resolves.toEqual(browser.statusValue);+ });++ it("normalizes a navigation and refuses a non-web address", async () => {+ await post("/api/server-browser/navigate", { url: "example.com/x" });+ expect(browser.navigations).toEqual(["https://example.com/x"]);+ const bad = await post("/api/server-browser/navigate", { url: "file:///etc/passwd" });+ expect(bad.status).toBe(400);+ expect(errorOf(await bad.json()).code).toBe("invalid_url");+ expect((await post("/api/server-browser/navigate", {})).status).toBe(400);+ expect(browser.navigations).toHaveLength(1);+ });++ it("reloads without a body, and still refuses a malformed one", async () => {+ await expect(post("/api/server-browser/reload")).resolves.toMatchObject({ status: 200 });+ await post("/api/server-browser/reload", {});+ await post("/api/server-browser/reload", { hard: true });+ expect(browser.reloads).toEqual([false, false, true]);+ const malformed = await post("/api/server-browser/reload", "{not json");+ expect(malformed.status).toBe(400);+ expect(browser.reloads).toHaveLength(3);+ });++ it("takes a batch of input events, and refuses one that is not one", async () => {+ const events: ServerBrowserInput[] = [+ { type: "mouse", action: "down", x: 10, y: 20, button: "left" },+ { type: "wheel", x: 10, y: 20, deltaY: -120 },+ { type: "text", text: "你好" },+ { type: "key", action: "down", key: "Enter", keyCode: 13, text: "\r" },+ ];+ const ok = await post("/api/server-browser/input", { events });+ expect(ok.status).toBe(200);+ expect(browser.inputs).toEqual([events]);++ for (const bad of [+ { events: [] },+ { events: "nope" },+ { events: [{ type: "mouse", action: "wiggle", x: 1, y: 2 }] },+ { events: [{ type: "mouse", action: "move", x: -1, y: 0 }] },+ { events: [{ type: "wheel", x: 0, y: 0, deltaY: "lots" }] },+ { events: [{ type: "text" }] },+ { events: [{ type: "telepathy" }] },+ { events: [{ type: "key", action: "down" }] },+ ]) {+ const res = await post("/api/server-browser/input", bad);+ expect(res.status, JSON.stringify(bad)).toBe(400);+ }+ expect(browser.inputs).toHaveLength(1);+ });++ it("resizes to what the viewer's box measured", async () => {+ await post("/api/server-browser/resize", { width: 1024, height: 768 });+ expect(browser.calls).toContain("resize:1024x768");+ expect((await post("/api/server-browser/resize", { width: "wide", height: 768 })).status).toBe(+ 400,+ );+ });++ it("streams frames as MJPEG, dropping the stream when the browser goes away", async () => {+ const res = await app.request("/api/server-browser/frames");+ expect(res.headers.get("content-type")).toBe(+ "multipart/x-mixed-replace; boundary=adelie-browser-frame",+ );+ expect(browser.watchers).toBe(1);++ const reader = res.body!.getReader();+ browser.emit({ kind: "frame", jpeg: Buffer.from([1, 2, 3, 4]) });+ const first = await reader.read();+ const text = Buffer.from(first.value!).toString("latin1");+ expect(text).toContain("--adelie-browser-frame");+ expect(text).toContain("Content-Type: image/jpeg");+ expect(text).toContain("Content-Length: 4");++ browser.emit({ kind: "closed", reason: "stopped" });+ await expect(reader.read()).resolves.toMatchObject({ done: true });+ });++ it("forgets a viewer whose request is cancelled", async () => {+ const res = await app.request("/api/server-browser/frames");+ expect(browser.watchers).toBe(1);+ await res.body!.cancel();+ expect(browser.watchers).toBe(0);+ });++ it("writes a frame again when nothing follows it, so the viewer is not left one behind", async () => {+ const res = await app.request("/api/server-browser/frames");+ const reader = res.body!.getReader();+ browser.emit({ kind: "frame", jpeg: Buffer.from([7, 7, 7]) });++ const first = Buffer.from((await reader.read()).value!).toString("latin1");+ expect(first).toContain("Content-Length: 3");+ // The viewer's image only takes up a part once the next one begins, so a frame that was the+ // last of its burst has to be sent twice or it is never shown at all.+ const again = Buffer.from((await reader.read()).value!).toString("latin1");+ expect(again).toContain("Content-Length: 3");+ expect(again.endsWith("--adelie-browser-frame\r\n")).toBe(true);+ });++ it("holds the newest frame for a viewer that is behind instead of losing it", async () => {+ const res = await app.request("/api/server-browser/frames");+ const reader = res.body!.getReader();+ // Three frames nobody has read yet: the viewer is behind by more than the one it can hold.+ browser.emit({ kind: "frame", jpeg: Buffer.from([1]) });+ browser.emit({ kind: "frame", jpeg: Buffer.from([2, 2]) });+ browser.emit({ kind: "frame", jpeg: Buffer.from([3, 3, 3]) });++ const first = Buffer.from((await reader.read()).value!).toString("latin1");+ expect(first).toContain("Content-Length: 1");+ // The middle frame is the one a lagging viewer loses; the newest is the one it must not:+ // a picture left one repaint behind is how a click looks like nothing happened.+ await new Promise((resolve) => setTimeout(resolve, 60));+ const second = Buffer.from((await reader.read()).value!).toString("latin1");+ expect(second).toContain("Content-Length: 3");+ });+});++describe("the server browser in a real app", () => {+ let app: TestApp;++ afterEach(async () => {+ await app.cleanup();+ });++ it("is wired into the platform, and says why it is off when it is", async () => {+ const previous = process.env["ADELIE_SERVER_BROWSER"];+ process.env["ADELIE_SERVER_BROWSER"] = "off";+ try {+ app = await createTestApp();+ const api = apiClient(app.app, (await loginAdmin(app.app)).cookie);+ const res = await api.get("/api/server-browser");+ expect(res.status).toBe(200);+ await expect(res.json()).resolves.toEqual({+ available: false,+ reason: "switched off by ADELIE_SERVER_BROWSER=off",+ running: false,+ state: null,+ });+ // Nothing may be started while it is unavailable — a hand-made POST says why, and starts+ // nothing.+ const started = await api.post("/api/server-browser/start");+ expect(started.status).toBe(503);+ expect(errorOf(await started.json())).toEqual({+ code: "browser_unavailable",+ message: "switched off by ADELIE_SERVER_BROWSER=off",+ });+ } finally {+ if (previous === undefined) delete process.env["ADELIE_SERVER_BROWSER"];+ else process.env["ADELIE_SERVER_BROWSER"] = previous;+ }+ });+});++/**+ * The real thing, end to end: a browser this process starts on a virtual display, a page served+ * from a socket in this test, the picture a viewer reads off the MJPEG stream, and a click that+ * reaches the page. Skipped where the machine has no browser to run — what is under test here is+ * the wiring, not the machine.+ */+const binary = findBrowserBinary();+const maybe = binary === null ? describe.skip : describe;++maybe("a browser the server really renders", () => {+ let app: TestApp | null = null;+ let server: Server | null = null;+ let origin = "";+ let clicked = "";++ beforeEach(async () => {+ clicked = "";+ // A page of our own over a socket in this process: the test never needs the network, and the+ // address it navigates to is an ordinary http one, which is all the route accepts.+ server = createServer((req, res) => {+ if (req.url === "/clicked") {+ clicked = "yes";+ res.writeHead(204).end();+ return;+ }+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" }).end(+ [+ "<title>hello from the server browser</title>",+ '<h1 id="hello">你好</h1>',+ // Pinned to the corner at a size of its own, so the click below lands on it whatever the+ // text metrics on this machine turn out to be.+ '<a id="hit" href="/clicked" style="position:fixed;left:0;top:0;width:300px;height:120px">press me</a>',+ ].join(""),+ );+ });+ await new Promise<void>((resolve) => server!.listen(0, "127.0.0.1", resolve));+ const address = server.address() as AddressInfo;+ origin = `http://127.0.0.1:${address.port}`;+ app = await createTestApp();+ });++ afterEach(async () => {+ // Stopped through the route, not left to the App's teardown: the profile directory is about to+ // be removed and Chromium holding files in it is how cleanup starts failing.+ if (app !== null) {+ const api = apiClient(app.app, (await loginAdmin(app.app)).cookie);+ await Promise.resolve(api.post("/api/server-browser/stop")).catch(() => {});+ await app.cleanup();+ }+ if (server !== null) {+ await new Promise<void>((resolve) => server!.close(() => resolve()));+ }+ app = null;+ server = null;+ });++ it("starts, loads an address, and hands a viewer its picture", async () => {+ const api = apiClient(app!.app, (await loginAdmin(app!.app)).cookie);+ const started = await api.post("/api/server-browser/start");+ expect(started.status).toBe(200);+ await expect(started.json()).resolves.toMatchObject({ available: true, running: true });++ // Subscribe before navigating: a viewer is what the screencast is started for.+ const frames = await api.get("/api/server-browser/frames");+ expect(frames.headers.get("content-type")).toContain("multipart/x-mixed-replace");++ await api.post("/api/server-browser/navigate", { url: origin });+ await waitFor(+ async () => (await statusOf(api)).state?.title === "hello from the server browser",+ );++ const jpeg = await firstFrame(frames, 30_000);+ // A real JPEG: the browser rendered the page, and this is its pixels.+ expect(jpeg.subarray(0, 2)).toEqual(Buffer.from([0xff, 0xd8]));++ // A click at the link, in the page's own coordinates. The picture is 1280x800 by default, and+ // the link sits at the top left of it.+ await api.post("/api/server-browser/input", {+ events: [+ { type: "mouse", action: "down", x: 30, y: 45, button: "left" },+ { type: "mouse", action: "up", x: 30, y: 45, button: "left" },+ ],+ });+ await waitFor(async () => clicked === "yes");+ }, 120_000);+});++/** The browser's own view of itself, as the route reports it. */+async function statusOf(api: ReturnType<typeof apiClient>): Promise<ServerBrowserStatus> {+ return (await (await api.get("/api/server-browser")).json()) as ServerBrowserStatus;+}++/** Polls until `done`, or fails: everything here is another process's timing, not an assertion. */+async function waitFor(done: () => Promise<boolean>, timeoutMs = 30_000): Promise<void> {+ const deadline = Date.now() + timeoutMs;+ while (Date.now() < deadline) {+ if (await done()) return;+ await new Promise((r) => setTimeout(r, 250));+ }+ throw new Error(`nothing happened within ${timeoutMs}ms`);+}++/** The first whole JPEG in the MJPEG stream — one part's header, then its bytes. */+async function firstFrame(res: Response, timeoutMs: number): Promise<Buffer> {+ const reader = res.body!.getReader();+ const timer = setTimeout(() => void reader.cancel(), timeoutMs);+ try {+ for (;;) {+ const { value, done } = await reader.read();+ if (done) throw new Error("the frame stream ended before a picture arrived");+ const found = Buffer.from(value!).indexOf(Buffer.from([0xff, 0xd8]));+ if (found !== -1) return Buffer.from(value!).subarray(found);+ }+ } finally {+ clearTimeout(timer);+ }+}diff --git a/packages/ui-gallery/src/app/mock/routes.ts b/packages/ui-gallery/src/app/mock/routes.tsindex 7ad9b718..21ac75c5 100644--- a/packages/ui-gallery/src/app/mock/routes.ts+++ b/packages/ui-gallery/src/app/mock/routes.ts@@ -109,6 +109,8 @@ import type {SessionsBatchResponse,SessionsResponse,SessionTracesResponse,+ ServerBrowserState,+ ServerBrowserStatus,SshHostResponse,StorageApplyResponse,StoragePlanEntryView,@@ -2724,6 +2726,78 @@ router.delete("/api/builtin-browser/history", () => empty()).post("/api/builtin-browser/clear-data", browserUnavailable);+// ---------------------------------------------------------------------------------------------+// The server browser: a browser the SERVER runs. The demo has no such process, so it answers as+// a server that does have one — the address bar, the toolbar and the input path are what the+// gallery is for. The picture is the one thing a browser-less demo cannot produce, so the frame+// stream answers with the header of a single blank frame and nothing after it.+// ---------------------------------------------------------------------------------------------++/** The demo's browser: a page standing still, which the toolbar and the address bar then move. */+let serverBrowserPage: ServerBrowserState = {+ url: "https://example.com/",+ title: "Example Domain",+ loading: false,+ width: 1280,+ height: 800,+};++const serverBrowserStatus = (): ServerBrowserStatus => ({+ available: true,+ running: true,+ state: { ...serverBrowserPage },+});++const serverBrowserInput = (body: unknown): ServerBrowserStatus => {+ // The picture does not move in the demo, so only the state a caller can see changes: a wheel+ // says the page is loading for a beat, which is what the strip above the picture shows.+ const given = record(body).events;+ if (Array.isArray(given) && given.some((event) => record(event).type === "wheel")) {+ serverBrowserPage = { ...serverBrowserPage, loading: true };+ }+ return serverBrowserStatus();+};++router+ .get("/api/server-browser", serverBrowserStatus)+ .post("/api/server-browser/start", serverBrowserStatus)+ .post("/api/server-browser/stop", (): ServerBrowserStatus => ({+ available: true,+ running: false,+ state: null,+ }))+ .post("/api/server-browser/navigate", ({ body }): ServerBrowserStatus => {+ const url = String(record(body).url ?? "");+ serverBrowserPage = {+ ...serverBrowserPage,+ url,+ title: url.replace(/^https?:\/\//, "").replace(/\/$/, ""),+ loading: false,+ };+ return serverBrowserStatus();+ })+ .post("/api/server-browser/back", serverBrowserStatus)+ .post("/api/server-browser/forward", serverBrowserStatus)+ .post("/api/server-browser/reload", (): ServerBrowserStatus => {+ serverBrowserPage = { ...serverBrowserPage, loading: false };+ return serverBrowserStatus();+ })+ .post("/api/server-browser/resize", ({ body }): ServerBrowserStatus => {+ const { width, height } = record(body);+ serverBrowserPage = {+ ...serverBrowserPage,+ width: typeof width === "number" ? Math.round(width) : serverBrowserPage.width,+ height: typeof height === "number" ? Math.round(height) : serverBrowserPage.height,+ };+ return serverBrowserStatus();+ })+ .post("/api/server-browser/input", ({ body }) => serverBrowserInput(body))+ .get("/api/server-browser/frames", () =>+ raw("--adelie-browser-frame\r\nContent-Type: image/jpeg\r\nContent-Length: 0\r\n\r\n", {+ "content-type": "multipart/x-mixed-replace; boundary=adelie-browser-frame",+ }),+ );+// ---------------------------------------------------------------------------------------------// Company mode: off in the demo, so every organization route answers as the server does then// ---------------------------------------------------------------------------------------------diff --git a/packages/ui-gallery/src/app/surfaces.ts b/packages/ui-gallery/src/app/surfaces.tsindex 1db76ed2..3f06f7fb 100644--- a/packages/ui-gallery/src/app/surfaces.ts+++ b/packages/ui-gallery/src/app/surfaces.ts@@ -33,6 +33,7 @@ export const SURFACE_IDS = ["plugin-detail","models","machines",+ "browser","usage","benchmark","benchmark-detail",@@ -70,6 +71,7 @@ export const SURFACES: readonly Surface[] = [{ id: "plugin-detail", group: "resources", route: "/plugins/registry/claude-code-expert" },{ id: "models", group: "resources", route: "/models" },{ id: "machines", group: "resources", route: "/machines" },+ { id: "browser", group: "resources", route: "/browser" },{ id: "usage", group: "measure", route: "/usage" },{ id: "benchmark", group: "measure", route: "/benchmark" },{ id: "benchmark-detail", group: "measure", route: "/benchmark/docs-qa-v1" },diff --git a/packages/ui-gallery/src/strings-en.ts b/packages/ui-gallery/src/strings-en.tsindex 58695076..3fc7dce7 100644--- a/packages/ui-gallery/src/strings-en.ts+++ b/packages/ui-gallery/src/strings-en.ts@@ -121,6 +121,12 @@ export const en: GalleryStrings = {"This machine and remote ones: install state, connections, probe results, and adding an ssh host.",how: "Sidebar › Machines (admins only).",},+ browser: {+ title: "Server Browser",+ description:+ "A browser running on the server, streamed into this page: address bar, back/forward, reload, and the page it loaded is clickable.",+ how: "Sidebar › Server Browser (admins only).",+ },usage: {title: "Cost center",description:diff --git a/packages/ui-gallery/src/strings.ts b/packages/ui-gallery/src/strings.tsindex 9c342075..bdc390eb 100644--- a/packages/ui-gallery/src/strings.ts+++ b/packages/ui-gallery/src/strings.ts@@ -131,6 +131,12 @@ export const zh = {description: "本机与远程机器:安装状态、连接、探测结果,以及添加 ssh 主机。",how: "侧栏 › 机器(仅管理员)。",},+ browser: {+ title: "服务器浏览器",+ description:+ "浏览器跑在服务器上,画面实时传到这个页面:地址栏、前进后退、刷新,点画面就能操作它打开的那个网页。",+ how: "侧栏 › 服务器浏览器(仅管理员)。",+ },usage: {title: "成本中心",description:diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex 738cdc71..6eab8ae9 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -201,6 +201,11 @@ import type {SessionsBatchRequest,SessionsBatchResponse,SessionTracesResponse,+ ServerBrowserInput,+ ServerBrowserInputRequest,+ ServerBrowserNavigateRequest,+ ServerBrowserResizeRequest,+ ServerBrowserStatus,SkillArchiveInstallRequest,SteerRequest,StorageApplyRequest,@@ -2791,6 +2796,55 @@ export const clearBuiltinBrowserData = (storages: BuiltinBrowserStorage[]) =>server: null,});+// ---- The server browser (a browser the SERVER runs; every route is admin-only) ----+/**+ * Always this server's: the browser is a process on the machine serving this window, which is+ * the point — a desktop app's own browser lives in its window (see the built-in browser above).+ */+const serverBrowserPath = (rest: string) => `/api/server-browser${rest}`;++/** Where the live picture is: an MJPEG stream, which an `<img>` renders as it arrives. */+export const SERVER_BROWSER_FRAMES_URL = serverBrowserPath("/frames");++/** Whether this server can show a browser at all, and what it is doing. */+export const getServerBrowserStatus = () =>+ apiFetch<ServerBrowserStatus>(serverBrowserPath(""), { server: null });+export const startServerBrowser = () =>+ apiFetch<ServerBrowserStatus>(serverBrowserPath("/start"), { method: "POST", server: null });+export const stopServerBrowser = () =>+ apiFetch<ServerBrowserStatus>(serverBrowserPath("/stop"), { method: "POST", server: null });+/** A bare host is given its scheme by the server; anything that is not a web address is a 400. */+export const navigateServerBrowser = (url: string) =>+ apiFetch<ServerBrowserStatus>(serverBrowserPath("/navigate"), {+ method: "POST",+ body: { url } satisfies ServerBrowserNavigateRequest,+ server: null,+ });+export const serverBrowserBack = () =>+ apiFetch<ServerBrowserStatus>(serverBrowserPath("/back"), { method: "POST", server: null });+export const serverBrowserForward = () =>+ apiFetch<ServerBrowserStatus>(serverBrowserPath("/forward"), { method: "POST", server: null });+export const reloadServerBrowser = (hard: boolean) =>+ apiFetch<ServerBrowserStatus>(serverBrowserPath("/reload"), {+ method: "POST",+ body: { hard },+ server: null,+ });+/** Draws the page at another size — what the viewer's frame box just became. */+export const resizeServerBrowser = (width: number, height: number) =>+ apiFetch<ServerBrowserStatus>(serverBrowserPath("/resize"), {+ method: "POST",+ body: { width, height } satisfies ServerBrowserResizeRequest,+ server: null,+ });+/** One batch of input events, in page coordinates and in order. */+export const sendServerBrowserInput = (events: ServerBrowserInput[]) =>+ apiFetch<ServerBrowserStatus>(serverBrowserPath("/input"), {+ method: "POST",+ body: { events } satisfies ServerBrowserInputRequest,+ server: null,+ });+// ---- Themes this installation imported (a data root's own `themes/` directory) ----/*** What this installation put in its data root's `themes/`, plus the files that would not read anddiff --git a/packages/web/src/features/server-browser/frame-geometry.ts b/packages/web/src/features/server-browser/frame-geometry.tsnew file mode 100644index 00000000..5dc5c158--- /dev/null+++ b/packages/web/src/features/server-browser/frame-geometry.ts@@ -0,0 +1,49 @@+/**+ * Where a pointer is, in the page's own coordinates (pure decisions, unit tested).+ *+ * The picture is drawn scaled to fit the box (`object-fit: contain`), so the element's rectangle+ * and the page's are two different things whenever the aspect ratios differ: the drawn part is+ * centred inside the box and there are margins. Every click has to be converted through that, or+ * a click lands somewhere else the moment the box is not exactly the page's shape.+ *+ * The numbers here are the page's: the browser on the server is drawing at `naturalWidth ×+ * naturalHeight` (the viewport it was told), and CDP takes input in those coordinates.+ */++/** The rectangle the picture is drawn into, as the DOM reports it. */+export interface Box {+ left: number;+ top: number;+ width: number;+ height: number;+}++export interface Point {+ x: number;+ y: number;+}++/**+ * The page coordinate `clientX/clientY` points at, or null when there is nothing to convert —+ * no picture has arrived yet, or the box has no size. The result is clamped to the page: a+ * pointer in the letterbox margin belongs to the nearest edge, not to a coordinate off the page.+ */+export function pointerToPagePoint(+ natural: { width: number; height: number },+ box: Box,+ clientX: number,+ clientY: number,+): Point | null {+ if (natural.width < 1 || natural.height < 1) return null;+ if (box.width < 1 || box.height < 1) return null;+ // `contain`: the whole page is visible, scaled by whichever dimension runs out first.+ const scale = Math.min(box.width / natural.width, box.height / natural.height);+ if (scale <= 0) return null;+ const left = box.left + (box.width - natural.width * scale) / 2;+ const top = box.top + (box.height - natural.height * scale) / 2;+ const round = (value: number): number => Math.round(value * 100) / 100;+ return {+ x: Math.min(Math.max(round((clientX - left) / scale), 0), natural.width - 1),+ y: Math.min(Math.max(round((clientY - top) / scale), 0), natural.height - 1),+ };+}diff --git a/packages/web/src/features/server-browser/server-browser-page.tsx b/packages/web/src/features/server-browser/server-browser-page.tsxnew file mode 100644index 00000000..ae19041c--- /dev/null+++ b/packages/web/src/features/server-browser/server-browser-page.tsx@@ -0,0 +1,453 @@+/**+ * The server browser: a browser running on the machine that serves this window, its picture+ * streamed into this page.+ *+ * Why it exists: the built-in browser is the desktop app's — its pages ARE `<webview>` elements of+ * that window, so a server reached from anywhere else has no browser at all. This page is for+ * exactly those deployments: a Linux box with no display, driven over the network.+ *+ * How the picture arrives: an `<img>` pointed at the server's MJPEG stream. `multipart/x-mixed-+ * replace` is what an image element renders natively, so there is no canvas, no decoder and no+ * socket here — the browser on the server rasterizes, and this page shows the result. Frames are+ * dropped rather than queued server-side when this page falls behind.+ *+ * What the page adds on top: the address and the title, which the picture cannot carry. Those are+ * read from the status route on a slow poll rather than pushed with the pixels — the stream is one+ * long response, and something has to come beside it.+ *+ * Input goes the other way, one batch per request: a click is a press and a release, a drag or a+ * scroll is coalesced over a few tens of milliseconds so a pointer moving at 60Hz is not 60+ * requests. Coordinates are the PAGE's, converted here from where the pointer is in the picture —+ * the picture is scaled to the box, and the box is the page's own size (the page is redrawn at+ * whatever the box measures, so a window here is a viewport there).+ */+import { useCallback, useEffect, useRef, useState } from "react";+import type {+ ServerBrowserInput,+ ServerBrowserState,+ ServerBrowserStatus,+} from "@adelie/server/api";+import {+ Button,+ GlyphIcon,+ ICONS,+ ICON_SIZE,+ Input,+ PageFrame,+ PageHeader,+ Skeleton,+} from "@adelie/ui";+import * as api from "../../api/endpoints";+import { S } from "../../lib/strings";+import { apiErrorText } from "../../lib/api-error";+import { useDocumentTitle } from "../../lib/use-document-title";+import { pointerToPagePoint } from "./frame-geometry";++/** How often the page re-reads what the browser is doing (the picture comes over its own stream). */+const POLL_MS = 1200;+/** A burst of input — a drag, a fast scroll — goes out as one request this often. */+const INPUT_FLUSH_MS = 40;+/** How long the box has to hold still before the page is redrawn at its size. */+const RESIZE_DEBOUNCE_MS = 350;+/** The page's own default, matching the server's: what the box is drawn at before it measures. */+const FALLBACK_VIEWPORT = { width: 1280, height: 800 };++/** The state the page shows while the browser has not answered yet. */+const INITIAL_STATE: ServerBrowserState = {+ url: "",+ title: "",+ loading: false,+ ...FALLBACK_VIEWPORT,+};++export function ServerBrowserPage() {+ useDocumentTitle(S.serverBrowser.pageTitle);+ const [status, setStatus] = useState<ServerBrowserStatus | null>(null);+ const [failure, setFailure] = useState<string | null>(null);+ /**+ * How far the picture has got: `none` before a single frame has arrived, `live` while they are+ * coming, `ended` when a stream that had been running stopped. The difference matters — the+ * first and last look nothing alike to somebody who is watching.+ */+ const [stream, setStream] = useState<"none" | "live" | "ended">("none");+ /** Bumped to point the `<img>` at the stream again: the one way to reconnect a broken one. */+ const [streamGeneration, setStreamGeneration] = useState(0);+ const [draft, setDraft] = useState<string | null>(null);+ const [busy, setBusy] = useState(false);++ const outbox = useRef<ServerBrowserInput[]>([]);+ const flushing = useRef(false);++ const state = status?.state ?? INITIAL_STATE;+ const available = status?.available ?? null;++ /** Reads the status once; a failure to read it is shown, not thrown. */+ const read = useCallback(async () => {+ try {+ setStatus(await api.getServerBrowserStatus());+ setFailure(null);+ } catch (err) {+ setFailure(apiErrorText(err));+ }+ }, []);++ useEffect(() => {+ void read();+ const id = setInterval(() => {+ if (document.visibilityState === "visible") void read();+ }, POLL_MS);+ return () => clearInterval(id);+ }, [read]);++ /** One write to the browser, with the busy flag and the failure shown where it lands. */+ const act = useCallback(async (work: () => Promise<ServerBrowserStatus>) => {+ setBusy(true);+ try {+ setStatus(await work());+ setFailure(null);+ } catch (err) {+ // A refusal here is about the browser, which is exactly where the page already shows+ // trouble; a toast would say the same thing twice.+ setFailure(apiErrorText(err));+ } finally {+ setBusy(false);+ }+ }, []);++ /**+ * Input, coalesced: everything queued inside one window goes out together, in order. The queue+ * is the reason a drag does not become one request per pointer event.+ */+ const send = useCallback((event: ServerBrowserInput) => {+ outbox.current.push(event);+ if (flushing.current) return;+ flushing.current = true;+ setTimeout(() => {+ const batch = outbox.current;+ outbox.current = [];+ flushing.current = false;+ if (batch.length === 0) return;+ void api.sendServerBrowserInput(batch).then(setStatus, () => {+ // Input that did not land means the browser is gone; the poll says so within a second, and+ // the next frame never comes. Nothing to add here.+ });+ }, INPUT_FLUSH_MS);+ }, []);++ const unreadable = failure !== null && status === null;+ const go = (url: string): void => {+ setDraft(null);+ void act(() => api.navigateServerBrowser(url));+ };++ return (+ <PageFrame width="full" contentClassName="flex flex-col gap-3">+ <PageHeader title={S.serverBrowser.pageTitle} description={S.serverBrowser.intro} />+ <Toolbar+ address={draft ?? state.url}+ busy={busy}+ disabled={available !== true}+ loading={state.loading}+ onAddress={(value) => setDraft(value)}+ onGo={go}+ onBack={() => void act(api.serverBrowserBack)}+ onForward={() => void act(api.serverBrowserForward)}+ onReload={() => void act(() => api.reloadServerBrowser(false))}+ onStart={() =>+ void act(status?.running === true ? api.stopServerBrowser : api.startServerBrowser)+ }+ running={status?.running === true}+ />+ {available === false && <Unavailable reason={status?.reason ?? null} />}+ {failure !== null && status !== null && <Notice text={failure} />}+ {available === true && (+ <>+ <div className="flex min-h-0 items-center gap-2 text-xs text-gray-500 dark:text-gray-400">+ <span className="truncate">{state.title === "" ? state.url : state.title}</span>+ <span className="shrink-0">{state.loading ? S.serverBrowser.loading : ""}</span>+ <span className="ml-auto shrink-0">+ {state.width}×{state.height}+ </span>+ </div>+ <Frame+ streamKey={streamGeneration}+ stream={stream}+ address={state.url}+ onStream={(next) =>+ setStream((was) => (next === "ended" && was !== "live" ? "none" : next))+ }+ onReconnect={() => {+ setStream("none");+ setStreamGeneration((n) => n + 1);+ }}+ send={send}+ onStatus={setStatus}+ />+ <p className="text-xs text-gray-500 dark:text-gray-400">{S.serverBrowser.hint}</p>+ </>+ )}+ {available === null && <Skeleton className="h-64 w-full" />}+ </PageFrame>+ );+}++/** The address bar and the five things a browser's toolbar does. */+function Toolbar({+ address,+ busy,+ disabled,+ loading,+ running,+ onAddress,+ onGo,+ onBack,+ onForward,+ onReload,+ onStart,+}: {+ address: string;+ busy: boolean;+ disabled: boolean;+ loading: boolean;+ running: boolean;+ onAddress: (value: string) => void;+ onGo: (url: string) => void;+ onBack: () => void;+ onForward: () => void;+ onReload: () => void;+ onStart: () => void;+}) {+ const icon = (d: string, label: string, onClick: () => void) => (+ <Button size="sm" variant="ghost" aria-label={label} title={label} onClick={onClick}>+ <GlyphIcon d={d} size={ICON_SIZE.rowLead} />+ </Button>+ );+ return (+ <div className="flex flex-wrap items-center gap-1">+ {icon(ICONS.arrowLeft, S.serverBrowser.back, onBack)}+ {icon(ICONS.arrowRightCentered, S.serverBrowser.forward, onForward)}+ {icon(loading ? ICONS.xCircle : ICONS.refresh, S.serverBrowser.reload, onReload)}+ <form+ className="min-w-64 flex-1"+ onSubmit={(event) => {+ event.preventDefault();+ if (address.trim() !== "") onGo(address.trim());+ }}+ >+ <Input+ aria-label={S.serverBrowser.address}+ placeholder={S.serverBrowser.addressPlaceholder}+ value={address}+ disabled={disabled}+ onChange={(event) => onAddress(event.target.value)}+ />+ </form>+ <Button+ size="sm"+ variant="secondary"+ onClick={() => onGo(address.trim())}+ disabled={disabled}+ >+ {S.serverBrowser.go}+ </Button>+ <Button size="sm" variant="ghost" onClick={onStart} disabled={busy}>+ {running ? S.serverBrowser.stop : busy ? S.serverBrowser.starting : S.serverBrowser.start}+ </Button>+ </div>+ );+}++/** Wheels, clicks and keys, over the picture: everything the page is asked to do. */+function Frame({+ streamKey,+ stream,+ address,+ send,+ onStream,+ onReconnect,+ onStatus,+}: {+ streamKey: number;+ stream: "none" | "live" | "ended";+ address: string;+ send: (event: ServerBrowserInput) => void;+ onStream: (next: "live" | "ended") => void;+ onReconnect: () => void;+ onStatus: (status: ServerBrowserStatus) => void;+}) {+ const image = useRef<HTMLImageElement | null>(null);+ const surface = useRef<HTMLDivElement | null>(null);+ /** The size the page is currently drawn at, so a resize of the same size is not sent twice. */+ const drawnAt = useRef("");++ /**+ * Where a pointer is, in the page's own coordinates: the picture is drawn scaled to fit the+ * box, so the element's rectangle is measured rather than assumed (see frame-geometry.ts).+ */+ const point = useCallback((clientX: number, clientY: number) => {+ const img = image.current;+ if (img === null) return null;+ return pointerToPagePoint(+ { width: img.naturalWidth, height: img.naturalHeight },+ img.getBoundingClientRect(),+ clientX,+ clientY,+ );+ }, []);++ /**+ * The page is redrawn at the size of this box, so what is on screen is what the browser+ * rendered rather than a shrunken copy of it. Debounced: a window being dragged is one redraw+ * at the end of it. The observer lives here rather than on the page because the box only exists+ * once the picture does — an effect on the page would run before that and watch nothing.+ */+ useEffect(() => {+ const box = surface.current;+ if (box === null) return;+ const observer = new ResizeObserver(() => {+ const rect = box.getBoundingClientRect();+ const width = Math.round(rect.width);+ const height = Math.round(rect.height);+ if (width < 1 || height < 1) return;+ const key = `${width}x${height}`;+ if (key === drawnAt.current) return;+ drawnAt.current = key;+ setTimeout(() => {+ if (drawnAt.current !== key) return;+ void api.resizeServerBrowser(width, height).then(onStatus, () => {});+ }, RESIZE_DEBOUNCE_MS);+ });+ observer.observe(box);+ return () => observer.disconnect();+ }, [onStatus]);++ /**+ * The wheel is the one input React cannot take: it attaches `wheel` passively, so a handler+ * there cannot stop the page underneath from scrolling as well. A native listener can.+ */+ useEffect(() => {+ const box = surface.current;+ if (box === null) return;+ const onWheel = (event: WheelEvent): void => {+ event.preventDefault();+ const at = point(event.clientX, event.clientY);+ if (at === null) return;+ send({ type: "wheel", ...at, deltaY: event.deltaY, deltaX: event.deltaX });+ };+ box.addEventListener("wheel", onWheel, { passive: false });+ return () => box.removeEventListener("wheel", onWheel);+ }, [point, send]);+ const mouse =+ (action: "move" | "down" | "up") =>+ (event: React.MouseEvent<HTMLDivElement>): void => {+ const at = point(event.clientX, event.clientY);+ if (at === null) return;+ send({+ type: "mouse",+ action,+ ...at,+ button: event.button === 2 ? "right" : event.button === 1 ? "middle" : "left",+ buttons: event.buttons,+ ...(action === "move" ? {} : { clickCount: event.detail }),+ });+ };+ const key =+ (action: "down" | "up") =>+ (event: React.KeyboardEvent<HTMLDivElement>): void => {+ event.preventDefault();+ // Printable keys carry their text so the page receives a real character; everything else is+ // a named key the page's own handlers see.+ const text =+ action === "down" && event.key.length === 1 && !event.ctrlKey && !event.metaKey+ ? event.key+ : undefined;+ send({+ type: "key",+ action,+ key: event.key,+ code: event.code === "" ? undefined : event.code,+ keyCode: event.keyCode === 0 ? undefined : event.keyCode,+ ...(text === undefined ? {} : { text }),+ });+ };++ return (+ <div className="overflow-hidden rounded-lg border border-[--line] bg-[--surface-sunken]">+ <div+ ref={surface}+ className="relative aspect-[16/10] w-full outline-none"+ tabIndex={0}+ aria-label={S.serverBrowser.pageTitle}+ onMouseDown={mouse("down")}+ onMouseUp={mouse("up")}+ onMouseMove={mouse("move")}+ onContextMenu={(event) => event.preventDefault()}+ onKeyDown={key("down")}+ onKeyUp={key("up")}+ >+ {stream === "ended" ? (+ <div className="flex h-full flex-col items-center justify-center gap-3 p-6 text-center">+ <p className="text-sm text-gray-500 dark:text-gray-400">+ {S.serverBrowser.streamEnded}+ </p>+ <Button size="sm" variant="secondary" onClick={onReconnect}>+ {S.serverBrowser.reload}+ </Button>+ </div>+ ) : (+ <>+ <img+ ref={image}+ // Pointed at the stream, so the browser is started and the picture begins arriving+ // as soon as this page is open.+ src={`${api.SERVER_BROWSER_FRAMES_URL}?v=${streamKey}`}+ alt={address === "" ? S.serverBrowser.empty : address}+ className="h-full w-full object-contain"+ draggable={false}+ onLoad={() => onStream("live")}+ onError={() => onStream("ended")}+ />+ {/* Before the first frame: what the picture would be of. A stream that has not+ produced anything yet is not a stream that broke, and the two are said apart. */}+ {stream === "none" && (+ <div className="absolute inset-0 flex flex-col items-center justify-center gap-1 p-6 text-center">+ <p className="text-sm font-medium">{S.serverBrowser.idleTitle}</p>+ <p className="text-xs text-gray-500 dark:text-gray-400">+ {S.serverBrowser.idleBody}+ </p>+ </div>+ )}+ </>+ )}+ </div>+ </div>+ );+}++/** A line of trouble, in the place the picture would be. */+function Notice({ text }: { text: string }) {+ return (+ <div className="rounded-lg border border-[--line] bg-[--surface-sunken] px-3 py-2 text-sm">+ {text}+ </div>+ );+}++/** The browser cannot run on this machine: the reason, and what names one that can. */+function Unavailable({ reason }: { reason: string | null }) {+ // The server's own sentence names the switch, which is what tells the two cases apart; it is+ // shown beside the localized line rather than instead of it.+ const off = reason !== null && reason.includes("ADELIE_SERVER_BROWSER=off");+ return (+ <div className="rounded-lg border border-[--line] bg-[--surface-sunken] p-6">+ <h2 className="text-sm font-medium">{S.serverBrowser.unavailableTitle}</h2>+ <p className="mt-2 text-sm text-gray-500 dark:text-gray-400">+ {off ? S.serverBrowser.unavailableOff : S.serverBrowser.unavailableNoBrowser}+ </p>+ <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">+ {S.serverBrowser.unavailableBody}+ {reason === null || off ? "" : `(${reason})`}+ </p>+ </div>+ );+}diff --git a/packages/web/src/lib/nav-group-collapse.ts b/packages/web/src/lib/nav-group-collapse.tsindex 8b2ad2be..a3e83ee9 100644--- a/packages/web/src/lib/nav-group-collapse.ts+++ b/packages/web/src/lib/nav-group-collapse.ts@@ -25,7 +25,8 @@*/import { NAV_PAGE_KEYS, PAGES } from "./pages";-export type NavGroupKey = "agents" | "plugins" | "models" | "machines" | "usage" | "benchmark";+export type NavGroupKey =+ "agents" | "plugins" | "models" | "machines" | "usage" | "benchmark" | "browser";/*** The manifest, derived from the app's own module.json (lib/pages.ts): every page whose* `nav` is "main", in manifest order. The literal key type above is the set the stringsdiff --git a/packages/web/src/lib/nav-icons.ts b/packages/web/src/lib/nav-icons.tsindex 57afa624..8d75b2a7 100644--- a/packages/web/src/lib/nav-icons.ts+++ b/packages/web/src/lib/nav-icons.ts@@ -22,6 +22,8 @@ export const NAV_ICONS = {benchmark: ICONS.trophy,/** Terminal (a `>_` prompt in a window frame). */terminal: ICONS.terminalWindow,+ /** The server browser (a globe: a page fetched from somewhere the window is not). */+ browser: ICONS.globe,/** Company mode's overview. */orgOverview: ICONS.dashboard,/** The org chart. */diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 8221880f..b9fdb234 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -21,6 +21,7 @@ export const en: Strings = {usage: "Cost Center",traces: "Trajectories",benchmark: "Evaluation Center",+ browser: "Server Browser",// Collapsed-rail tooltips (product-specified wording; new chat reuses chat.newSessionMenu, the other pages reuse the page names above).lastConversation: "Last conversation",// The rail avatar's tooltip says what the control does; who is signed in stays in its accessible name.@@ -360,6 +361,44 @@ export const en: Strings = {},},+ /**+ * The server browser page: a browser the server itself runs, for the deployments that cannot+ * have the desktop window's one (a Linux box reached over the network).+ */+ serverBrowser: {+ pageTitle: "Server Browser",+ intro: "The browser runs on this server and its picture is streamed here. Admins only.",+ /** The address bar. */+ address: "Address",+ addressPlaceholder: "Type an address and press Enter, e.g. example.com",+ go: "Go",+ back: "Back",+ forward: "Forward",+ reload: "Reload",+ stop: "Stop the browser",+ start: "Start the browser",+ starting: "Starting the browser…",+ /** While the page in the browser is loading. */+ loading: "Loading…",+ /** The frame area before anything has been loaded. */+ empty: "Type an address above to start browsing.",+ /** The frame area while the browser has no page yet. */+ idleTitle: "The browser is not running",+ idleBody: "Opening this page starts it; the button above starts it by hand.",+ unavailableTitle: "This server cannot show a browser",+ /** The browser is switched off for this server by its own configuration. */+ unavailableOff: "Switched off by the administrator (ADELIE_SERVER_BROWSER=off).",+ /** Nothing on this machine can draw a page. */+ unavailableNoBrowser: "There is no Chromium or Chrome on this server.",+ unavailableBody: "ADELIE_SERVER_BROWSER_BIN names one that lives somewhere else.",+ /** Something went wrong between this page and the browser on the server. */+ failed: (reason: string): string => `Could not reach the browser on the server: ${reason}`,+ /** The picture is not being received any more; the browser on the server may have stopped. */+ streamEnded: "The picture stopped; the browser on the server may have shut down.",+ /** The frame area's keyboard hint: what a visitor can do with the page. */+ hint: "Click the picture to use the page, or just type.",+ },+tracePanel: {empty: "No traces yet",emptyHint: "This session has not produced a Trace file yet",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 96da8f13..9a1230f3 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -28,6 +28,7 @@ export const zh = {usage: "成本中心",traces: "轨迹观测",benchmark: "评估中心",+ browser: "服务器浏览器",// Collapsed-rail tooltips (product-specified wording; new chat reuses chat.newSessionMenu, the other pages reuse the page names above).lastConversation: "最近一次对话",// The rail avatar's tooltip says what the control does; who is signed in stays in its accessible name.@@ -428,6 +429,44 @@ export const zh = {},},+ /**+ * The server browser page: a browser the server itself runs, for the deployments that cannot+ * have the desktop window's one (a Linux box reached over the network).+ */+ serverBrowser: {+ pageTitle: "服务器浏览器",+ intro: "浏览器在这个服务器上运行,画面实时传到这里。只有服务器管理员可以使用。",+ /** The address bar. */+ address: "地址栏",+ addressPlaceholder: "输入网址后回车,例如 example.com",+ go: "打开",+ back: "后退",+ forward: "前进",+ reload: "刷新",+ stop: "停止浏览器",+ start: "启动浏览器",+ starting: "正在启动浏览器…",+ /** While the page in the browser is loading. */+ loading: "加载中…",+ /** The frame area before anything has been loaded. */+ empty: "在上方输入一个网址开始浏览。",+ /** The frame area while the browser has no page yet. */+ idleTitle: "浏览器还没有启动",+ idleBody: "打开这个页面时会自动启动它;也可以按上面的按钮自行启动。",+ unavailableTitle: "这台服务器不能显示浏览器",+ /** The browser is switched off for this server by its own configuration. */+ unavailableOff: "已被管理员关闭(ADELIE_SERVER_BROWSER=off)。",+ /** Nothing on this machine can draw a page. */+ unavailableNoBrowser: "这台服务器上没有找到 Chromium 或 Chrome。",+ unavailableBody: "可以用 ADELIE_SERVER_BROWSER_BIN 指定一个浏览器程序的位置。",+ /** Something went wrong between this page and the browser on the server. */+ failed: (reason: string): string => `无法连接服务器上的浏览器:${reason}`,+ /** The picture is not being received any more; the browser on the server may have stopped. */+ streamEnded: "画面已中断,浏览器可能已经停止。",+ /** The frame area's keyboard hint: what a visitor can do with the page. */+ hint: "点击画面可与页面交互,也可以直接输入。",+ },+/** The Trace dock panel (the current conversation's Trace files). */tracePanel: {empty: "暂无轨迹",diff --git a/packages/web/src/module.json b/packages/web/src/module.jsonindex 0dee3dc3..14d6377e 100644--- a/packages/web/src/module.json+++ b/packages/web/src/module.json@@ -125,6 +125,17 @@"renderer": {"builtin": "SchedulesPage"}+ },+ {+ "id": "web.server-browser",+ "key": "browser",+ "path": "/browser",+ "nav": "main",+ "admin": true,+ "released": true,+ "renderer": {+ "builtin": "ServerBrowserPage"+ }}]}diff --git a/packages/web/src/router.tsx b/packages/web/src/router.tsxindex c03a2637..f4a28343 100644--- a/packages/web/src/router.tsx+++ b/packages/web/src/router.tsx@@ -35,6 +35,7 @@ import { FinancePage } from "./features/company/finance-page";import { ChannelView } from "./features/company/channel-view";import { HandbookPage } from "./features/company/handbook-page";import { MachinesPage } from "./features/machines/machines-page";+import { ServerBrowserPage } from "./features/server-browser/server-browser-page";import { WorkflowAppPage } from "./features/workflows/workflow-app-page";import { PetPage } from "./features/pet/pet-page";import { PAGES } from "./lib/pages";@@ -56,6 +57,7 @@ const BUILTIN_PAGES: Record<string, React.ComponentType> = {BenchmarkPage,BenchmarkDetailPage,SchedulesPage,+ ServerBrowserPage,};function renderPage(page: PageEntry): React.ReactNode {diff --git a/packages/web/test/nav-group-collapse.test.ts b/packages/web/test/nav-group-collapse.test.tsindex 13a44559..e5997e92 100644--- a/packages/web/test/nav-group-collapse.test.ts+++ b/packages/web/test/nav-group-collapse.test.ts@@ -38,6 +38,7 @@ import {withNavPinned,} from "../src/lib/nav-group-collapse";import type { NavCollapseStorage, NavPinOverrides } from "../src/lib/nav-group-collapse";+import { PAGES } from "../src/lib/pages";import { zh } from "../src/lib/strings";import { en } from "../src/lib/strings-en";import { blockedStorage, memoryStorage } from "./helpers/storage";@@ -61,18 +62,24 @@ describe("navEntryKeysFor", () => {expect(en.nav.newChat).toBe(en.chat.newSessionMenu);});- it("the Machines page heading is its nav label", () => {+ it("a page's heading is its nav label", () => {expect(zh.machines.pageTitle).toBe(zh.nav.machines);expect(en.machines.pageTitle).toBe(en.nav.machines);+ expect(zh.serverBrowser.pageTitle).toBe(zh.nav.browser);+ expect(en.serverBrowser.pageTitle).toBe(en.nav.browser);});});describe("navKeysFor", () => {- it("a member sees the admin's entries minus Machines, which the server refuses them", () => {- // /api/machines is admin-gated server-side (it spawns ssh with the server account's- // keys), so offering a member the row would only ever produce a 403.- expect(navKeysFor(true)).toContain("machines");- expect(navKeysFor(false)).toEqual(navKeysFor(true).filter((key) => key !== "machines"));+ it("a member sees the admin's entries minus the pages the server refuses them", () => {+ // Both /api/machines (ssh with the server account's keys) and /api/server-browser (a browser+ // process on the server) are admin-gated, so offering a member the row would only ever+ // produce a 403. Which pages those are is read off the manifest rather than listed here, so+ // a page added later is covered without this test being the thing that catches it.+ const adminOnly = PAGES.filter((p) => p.nav === "main" && p.admin).map((p) => p.key);+ expect(adminOnly).toContain("machines");+ expect(adminOnly).toContain("browser");+ expect(navKeysFor(false)).toEqual(navKeysFor(true).filter((key) => !adminOnly.includes(key)));});});@@ -80,7 +87,7 @@ describe("pinned vs. collapsible", () => {it("defaults: New chat, Agents, Models and Plugins pinned; the rest collapsible", () => {expect(splitNavEntries(navEntryKeysFor(true), {})).toEqual({pinned: ["newChat", "agents", "models", "plugins"],- collapsible: ["machines", "usage", "benchmark"],+ collapsible: ["machines", "usage", "benchmark", "browser"],});});@@ -101,7 +108,7 @@ describe("pinned vs. collapsible", () => {// Models lands ahead of Machines (its manifest place), not at the end it was moved to.expect(splitNavEntries(navEntryKeysFor(true), unpinned)).toEqual({pinned: ["newChat", "agents", "plugins"],- collapsible: ["models", "machines", "usage", "benchmark"],+ collapsible: ["models", "machines", "usage", "benchmark", "browser"],});});@@ -111,7 +118,7 @@ describe("pinned vs. collapsible", () => {expect(first).toEqual(second);expect(splitNavEntries(navEntryKeysFor(true), first)).toEqual({pinned: ["newChat", "agents", "models", "plugins", "usage", "benchmark"],- collapsible: ["machines"],+ collapsible: ["machines", "browser"],});});@@ -145,7 +152,7 @@ describe("pinned vs. collapsible", () => {it("everything pinned leaves the collapsible area empty, so folding hides nothing", () => {let overrides: NavPinOverrides = {};for (const key of navEntryKeysFor(true)) overrides = withNavPinned(overrides, key, true);- expect(overrides).toEqual({ machines: true, usage: true, benchmark: true });+ expect(overrides).toEqual({ machines: true, usage: true, benchmark: true, browser: true });const { collapsible } = splitNavEntries(navEntryKeysFor(true), overrides);expect(collapsible).toEqual([]);expect(visibleNavKeys(true, true, overrides)).toEqual(navEntryKeysFor(true));@@ -177,6 +184,7 @@ describe("visibleNavKeys", () => {"machines","usage","benchmark",+ "browser",]);expect(visibleNavKeys(true, true, overrides)).toEqual(["newChat", "agents", "plugins"]);});@@ -252,7 +260,7 @@ describe("persisted pin choices (one global localStorage key)", () => {expect(restored).toEqual(moved);expect(splitNavEntries(navEntryKeysFor(true), restored)).toEqual({pinned: ["newChat", "agents", "plugins", "usage"],- collapsible: ["models", "machines", "benchmark"],+ collapsible: ["models", "machines", "benchmark", "browser"],});});diff --git a/packages/web/test/server-browser-frame.test.ts b/packages/web/test/server-browser-frame.test.tsnew file mode 100644index 00000000..2f199304--- /dev/null+++ b/packages/web/test/server-browser-frame.test.ts@@ -0,0 +1,54 @@+/**+ * The picture's coordinates: how a pointer in the frame becomes a coordinate the page on the+ * server understands. The cases that matter are the ones where the box and the page are not the+ * same shape — a click there must still land on what the person aimed at.+ */+import { describe, expect, it } from "vitest";+import { pointerToPagePoint } from "../src/features/server-browser/frame-geometry";++const PAGE = { width: 1280, height: 800 };++describe("pointerToPagePoint", () => {+ it("is the identity when the page is drawn at its own size", () => {+ const box = { left: 100, top: 50, width: 1280, height: 800 };+ expect(pointerToPagePoint(PAGE, box, 100, 50)).toEqual({ x: 0, y: 0 });+ expect(pointerToPagePoint(PAGE, box, 420, 210)).toEqual({ x: 320, y: 160 });+ expect(pointerToPagePoint(PAGE, box, 1379, 849)).toEqual({ x: 1279, y: 799 });+ });++ it("scales down, so a shrunken picture still points at the same place", () => {+ // Half size: the same page point is half as far from the box's corner.+ const box = { left: 0, top: 0, width: 640, height: 400 };+ expect(pointerToPagePoint(PAGE, box, 320, 200)).toEqual({ x: 640, y: 400 });+ });++ it("accounts for the letterbox when the box is taller than the page", () => {+ // 1280x800 into a 1280x1000 box: drawn 1280x800, centred, so 100px of margin top and bottom.+ const box = { left: 0, top: 0, width: 1280, height: 1000 };+ expect(pointerToPagePoint(PAGE, box, 0, 100)).toEqual({ x: 0, y: 0 });+ expect(pointerToPagePoint(PAGE, box, 640, 100)).toEqual({ x: 640, y: 0 });+ // Inside the top margin: the nearest edge, never a coordinate off the page.+ expect(pointerToPagePoint(PAGE, box, 640, 20)).toEqual({ x: 640, y: 0 });+ expect(pointerToPagePoint(PAGE, box, 640, 980)).toEqual({ x: 640, y: 799 });+ });++ it("accounts for the letterbox when the box is wider than the page", () => {+ // 1280x800 into a 1600x800 box: drawn 1280x800, centred, so 160px of margin each side.+ const box = { left: 0, top: 0, width: 1600, height: 800 };+ expect(pointerToPagePoint(PAGE, box, 160, 0)).toEqual({ x: 0, y: 0 });+ expect(pointerToPagePoint(PAGE, box, 1600, 800)).toEqual({ x: 1279, y: 799 });+ });++ it("has nothing to say before a picture has arrived or before the box has a size", () => {+ const box = { left: 0, top: 0, width: 640, height: 400 };+ expect(pointerToPagePoint({ width: 0, height: 0 }, box, 10, 10)).toBeNull();+ expect(pointerToPagePoint(PAGE, { left: 0, top: 0, width: 0, height: 0 }, 10, 10)).toBeNull();+ });++ it("keeps two decimal places, which is finer than a pixel of the page", () => {+ // 1280x800 fits a 600x400 box at 0.46875 — its width exactly, so 12.5px of margin above and+ // below — and neither the offset nor the division lands on a whole page pixel.+ const box = { left: 0, top: 0, width: 600, height: 400 };+ expect(pointerToPagePoint(PAGE, box, 100, 100)).toEqual({ x: 213.33, y: 186.67 });+ });+});diff --git a/packages/web/test/shortcut-guard.test.ts b/packages/web/test/shortcut-guard.test.tsindex 4e16ecd9..6b17b1d8 100644--- a/packages/web/test/shortcut-guard.test.ts+++ b/packages/web/test/shortcut-guard.test.ts@@ -19,14 +19,17 @@ const ALLOWED_DIR = "lib/shortcuts";* Files that read the modifiers for something other than a chord of their own, and are* therefore excused: the Workspace picker's fixed file-browser keys (Finder's ⌘↑ / ⌘[ / ⌘],* Explorer's Alt+←) and its type-to-select, the model picker's Alt+digit group jump and its- * type-to-focus (both "is this a bare key" tests), and the workflow frame's key forwarding,- * which copies an event to re-raise it on the app's window. None is an app command a user- * would rebind. A new entry here needs a reason of the same kind.+ * type-to-focus (both "is this a bare key" tests), the workflow frame's key forwarding,+ * which copies an event to re-raise it on the app's window, and the server browser's frame,+ * which forwards a keystroke to a browser on another machine and answers the same question+ * every browser does — whether this keystroke is a character or a chord handled up there.+ * None is an app command a user would rebind. A new entry here needs a reason of the same kind.*/const EXCUSED_FILES = new Set(["features/chat/workspace-finder-model.ts","features/chat/model-picker-logic.ts","features/chat/model-picker-modal.tsx",+ "features/server-browser/server-browser-page.tsx","lib/workflow-theme.ts",]);